peer.go 7.58 KB
Newer Older
1 2 3
package peer

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"bytes"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
Jeromy's avatar
Jeromy committed
7
	"sync"
Jeromy's avatar
Jeromy committed
8
	"time"
9

10 11 12
	b58 "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-base58"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13

14
	ic "github.com/jbenet/go-ipfs/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	u "github.com/jbenet/go-ipfs/util"
16 17
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
var log = u.Logger("peer")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21
// ID is a byte slice representing the identity of a peer.
type ID mh.Multihash
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22

23 24 25 26 27
// String is utililty function for printing out peer ID strings.
func (id ID) String() string {
	return id.Pretty()
}

Siraj Ravel's avatar
Siraj Ravel committed
28
// Equal is utililty function for comparing two peer ID's
29 30
func (id ID) Equal(other ID) bool {
	return bytes.Equal(id, other)
31 32
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
// Pretty returns a b58-encoded string of the ID
34
func (id ID) Pretty() string {
35
	return b58.Encode(id)
36 37
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40 41 42
// DecodePrettyID returns a b58-encoded string of the ID
func DecodePrettyID(s string) ID {
	return b58.Decode(s)
}

43 44 45 46 47 48 49 50 51 52
// IDFromPubKey retrieves a Public Key from the peer given by pk
func IDFromPubKey(pk ic.PubKey) (ID, error) {
	b, err := pk.Bytes()
	if err != nil {
		return nil, err
	}
	hash := u.Hash(b)
	return ID(hash), nil
}

53 54
// Map maps Key (string) : *peer (slices are not comparable).
type Map map[u.Key]Peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
56
// Peer represents the identity information of an IPFS Node, including
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
// ID, and relevant Addresses.
58 59 60
type Peer interface {
	// ID returns the peer's ID
	ID() ID
Jeromy's avatar
Jeromy committed
61

62 63 64 65 66 67 68 69 70 71 72 73
	// Key returns the ID as a Key (string) for maps.
	Key() u.Key

	// Addresses returns the peer's multiaddrs
	Addresses() []ma.Multiaddr

	// AddAddress adds the given Multiaddr address to Peer's addresses.
	AddAddress(a ma.Multiaddr)

	// NetAddress returns the first Multiaddr found for a given network.
	NetAddress(n string) ma.Multiaddr

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74 75 76 77
	// Services returns the peer's services
	// Services() []mux.ProtocolID
	// SetServices([]mux.ProtocolID)

78 79 80 81 82 83 84 85 86 87 88 89 90
	// Priv/PubKey returns the peer's Private Key
	PrivKey() ic.PrivKey
	PubKey() ic.PubKey

	// LoadAndVerifyKeyPair unmarshalls, loads a private/public key pair.
	// Error if (a) unmarshalling fails, or (b) pubkey does not match id.
	LoadAndVerifyKeyPair(marshalled []byte) error
	VerifyAndSetPrivKey(sk ic.PrivKey) error
	VerifyAndSetPubKey(pk ic.PubKey) error

	// Get/SetLatency manipulate the current latency measurement.
	GetLatency() (out time.Duration)
	SetLatency(laten time.Duration)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91 92 93

	// Update with the data of another peer instance
	Update(Peer) error
94 95 96 97 98
}

type peer struct {
	id        ID
	addresses []ma.Multiaddr
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99
	// services  []mux.ProtocolID
100 101 102

	privKey ic.PrivKey
	pubKey  ic.PubKey
103

104 105 106
	latency time.Duration

	sync.RWMutex
107 108
}

109
// String prints out the peer.
110 111
func (p *peer) String() string {
	return "[Peer " + p.id.String()[:12] + "]"
112 113
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
// Key returns the ID as a Key (string) for maps.
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
func (p *peer) Key() u.Key {
	return u.Key(p.id)
}

// ID returns the peer's ID
func (p *peer) ID() ID {
	return p.id
}

// PrivKey returns the peer's Private Key
func (p *peer) PrivKey() ic.PrivKey {
	return p.privKey
}

// PubKey returns the peer's Private Key
func (p *peer) PubKey() ic.PubKey {
	return p.pubKey
}

// Addresses returns the peer's multiaddrs
func (p *peer) Addresses() []ma.Multiaddr {
	cp := make([]ma.Multiaddr, len(p.addresses))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	p.RLock()
138
	copy(cp, p.addresses)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
	defer p.RUnlock()
140
	return cp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
143
// AddAddress adds the given Multiaddr address to Peer's addresses.
144
func (p *peer) AddAddress(a ma.Multiaddr) {
145 146 147
	p.Lock()
	defer p.Unlock()

148
	for _, addr := range p.addresses {
149 150 151 152
		if addr.Equal(a) {
			return
		}
	}
153
	p.addresses = append(p.addresses, a)
154 155
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
156
// NetAddress returns the first Multiaddr found for a given network.
157
func (p *peer) NetAddress(n string) ma.Multiaddr {
158 159 160
	p.RLock()
	defer p.RUnlock()

161
	for _, a := range p.addresses {
162
		for _, p := range a.Protocols() {
163 164 165 166 167 168 169
			if p.Name == n {
				return a
			}
		}
	}
	return nil
}
Jeromy's avatar
Jeromy committed
170

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171 172 173 174 175 176 177 178 179 180 181 182
// func (p *peer) Services() []mux.ProtocolID {
// 	p.RLock()
// 	defer p.RUnlock()
// 	return p.services
// }
//
// func (p *peer) SetServices(s []mux.ProtocolID) {
// 	p.Lock()
// 	defer p.Unlock()
// 	p.services = s
// }

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
// GetLatency retrieves the current latency measurement.
184
func (p *peer) GetLatency() (out time.Duration) {
185
	p.RLock()
186
	out = p.latency
187
	p.RUnlock()
188
	return
Jeromy's avatar
Jeromy committed
189 190
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
// SetLatency sets the latency measurement.
192 193
// TODO: Instead of just keeping a single number,
//		 keep a running average over the last hour or so
194
// Yep, should be EWMA or something. (-jbenet)
195
func (p *peer) SetLatency(laten time.Duration) {
196
	p.Lock()
197 198 199 200 201
	if p.latency == 0 {
		p.latency = laten
	} else {
		p.latency = ((p.latency * 9) + laten) / 10
	}
202
	p.Unlock()
Jeromy's avatar
Jeromy committed
203
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205 206

// LoadAndVerifyKeyPair unmarshalls, loads a private/public key pair.
// Error if (a) unmarshalling fails, or (b) pubkey does not match id.
207
func (p *peer) LoadAndVerifyKeyPair(marshalled []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209 210 211 212
	sk, err := ic.UnmarshalPrivateKey(marshalled)
	if err != nil {
		return fmt.Errorf("Failed to unmarshal private key: %v", err)
	}

213 214 215 216 217 218
	return p.VerifyAndSetPrivKey(sk)
}

// VerifyAndSetPrivKey sets private key, given its pubkey matches the peer.ID
func (p *peer) VerifyAndSetPrivKey(sk ic.PrivKey) error {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220 221 222 223
	// construct and assign pubkey. ensure it matches this peer
	if err := p.VerifyAndSetPubKey(sk.GetPublic()); err != nil {
		return err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226
	p.Lock()
	defer p.Unlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
	// if we didn't have the priavte key, assign it
228 229
	if p.privKey == nil {
		p.privKey = sk
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230 231 232 233
		return nil
	}

	// if we already had the keys, check they're equal.
234
	if p.privKey.Equals(sk) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235 236 237 238 239 240
		return nil // as expected. keep the old objects.
	}

	// keys not equal. invariant violated. this warrants a panic.
	// these keys should be _the same_ because peer.ID = H(pk)
	// this mismatch should never happen.
241
	log.Error("%s had PrivKey: %v -- got %v", p, p.privKey, sk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242 243 244 245
	panic("invariant violated: unexpected key mismatch")
}

// VerifyAndSetPubKey sets public key, given it matches the peer.ID
246
func (p *peer) VerifyAndSetPubKey(pk ic.PubKey) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249 250 251
	pkid, err := IDFromPubKey(pk)
	if err != nil {
		return fmt.Errorf("Failed to hash public key: %v", err)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253 254
	p.Lock()
	defer p.Unlock()

255
	if !p.id.Equal(pkid) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256 257 258 259
		return fmt.Errorf("Public key does not match peer.ID.")
	}

	// if we didn't have the keys, assign them.
260 261
	if p.pubKey == nil {
		p.pubKey = pk
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263 264 265
		return nil
	}

	// if we already had the pubkey, check they're equal.
266
	if p.pubKey.Equals(pk) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267 268 269 270 271 272
		return nil // as expected. keep the old objects.
	}

	// keys not equal. invariant violated. this warrants a panic.
	// these keys should be _the same_ because peer.ID = H(pk)
	// this mismatch should never happen.
273
	log.Error("%s had PubKey: %v -- got %v", p, p.pubKey, pk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274 275
	panic("invariant violated: unexpected key mismatch")
}
276

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
func (p *peer) Update(other Peer) error {
	if !p.ID().Equal(other.ID()) {
		return errors.New("peer ids do not match")
	}

	for _, a := range other.Addresses() {
		p.AddAddress(a)
	}

	sk := other.PrivKey()
	pk := other.PubKey()
	p.Lock()
	if p.privKey == nil {
		p.privKey = sk
	}

	if p.pubKey == nil {
		p.pubKey = pk
	}
	defer p.Unlock()
	return nil
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
// WithKeyPair returns a Peer object with given keys.
func WithKeyPair(sk ic.PrivKey, pk ic.PubKey) (Peer, error) {
	if sk == nil && pk == nil {
		return nil, fmt.Errorf("PeerWithKeyPair nil keys")
	}

	pk2 := sk.GetPublic()
	if pk == nil {
		pk = pk2
	} else if !pk.Equals(pk2) {
		return nil, fmt.Errorf("key mismatch. pubkey is not privkey's pubkey")
	}

	pkid, err := IDFromPubKey(pk)
	if err != nil {
		return nil, fmt.Errorf("Failed to hash public key: %v", err)
	}

	return &peer{id: pkid, pubKey: pk, privKey: sk}, nil
}

// WithID constructs a peer with given ID.
func WithID(id ID) Peer {
	return &peer{id: id}
}

// WithIDString constructs a peer with given ID (string).
func WithIDString(id string) Peer {
	return WithID(ID(id))
}