peer.go 8.08 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
type Peer interface {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
59 60 61 62

	// TODO reduce the peer interface to be read-only. Force mutations to occur
	// on the peer store eg. peerstore.SetLatency(peerId, value).

63 64
	// ID returns the peer's ID
	ID() ID
Jeromy's avatar
Jeromy committed
65

66 67 68 69 70 71 72
	// 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.
73 74
	// returns whether this was a newly added address.
	AddAddress(a ma.Multiaddr) bool
75 76 77 78

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79 80 81 82
	// Services returns the peer's services
	// Services() []mux.ProtocolID
	// SetServices([]mux.ProtocolID)

83 84 85 86 87 88 89 90 91 92 93 94 95
	// 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
96 97 98

	// Update with the data of another peer instance
	Update(Peer) error
99 100 101 102 103
}

type peer struct {
	id        ID
	addresses []ma.Multiaddr
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
	// services  []mux.ProtocolID
105 106 107

	privKey ic.PrivKey
	pubKey  ic.PubKey
108

Brian Tiger Chow's avatar
Brian Tiger Chow committed
109 110
	// TODO move latency away from peer into the package that uses it. Instead,
	// within that package, map from ID to latency value.
111 112 113
	latency time.Duration

	sync.RWMutex
114 115
}

116
// String prints out the peer.
117 118
func (p *peer) String() string {
	return "[Peer " + p.id.String()[:12] + "]"
119 120
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
// Key returns the ID as a Key (string) for maps.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
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
144
	p.RLock()
145
	copy(cp, p.addresses)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
	defer p.RUnlock()
147
	return cp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
150
// AddAddress adds the given Multiaddr address to Peer's addresses.
151 152
// Returns whether this address was a newly added address
func (p *peer) AddAddress(a ma.Multiaddr) bool {
153 154 155
	p.Lock()
	defer p.Unlock()

156
	for _, addr := range p.addresses {
157
		if addr.Equal(a) {
158
			return false
159 160
		}
	}
161
	p.addresses = append(p.addresses, a)
162
	return true
163 164
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
165
// NetAddress returns the first Multiaddr found for a given network.
166
func (p *peer) NetAddress(n string) ma.Multiaddr {
167 168 169
	p.RLock()
	defer p.RUnlock()

170
	for _, a := range p.addresses {
171
		for _, p := range a.Protocols() {
172 173 174 175 176 177 178
			if p.Name == n {
				return a
			}
		}
	}
	return nil
}
Jeromy's avatar
Jeromy committed
179

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
180 181 182 183 184 185 186 187 188 189 190 191
// 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
192
// GetLatency retrieves the current latency measurement.
193
func (p *peer) GetLatency() (out time.Duration) {
194
	p.RLock()
195
	out = p.latency
196
	p.RUnlock()
197
	return
Jeromy's avatar
Jeromy committed
198 199
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
// SetLatency sets the latency measurement.
201 202
// TODO: Instead of just keeping a single number,
//		 keep a running average over the last hour or so
203
// Yep, should be EWMA or something. (-jbenet)
204
func (p *peer) SetLatency(laten time.Duration) {
205
	p.Lock()
206 207 208 209 210
	if p.latency == 0 {
		p.latency = laten
	} else {
		p.latency = ((p.latency * 9) + laten) / 10
	}
211
	p.Unlock()
Jeromy's avatar
Jeromy committed
212
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215

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

222 223 224 225 226 227
	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
228 229 230 231 232
	// 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
233 234 235
	p.Lock()
	defer p.Unlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
	// if we didn't have the priavte key, assign it
237 238
	if p.privKey == nil {
		p.privKey = sk
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239 240 241 242
		return nil
	}

	// if we already had the keys, check they're equal.
243
	if p.privKey.Equals(sk) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244 245 246 247 248 249
		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.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
	log.Errorf("%s had PrivKey: %v -- got %v", p, p.privKey, sk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251 252 253 254
	panic("invariant violated: unexpected key mismatch")
}

// VerifyAndSetPubKey sets public key, given it matches the peer.ID
255
func (p *peer) VerifyAndSetPubKey(pk ic.PubKey) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256 257 258 259 260
	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
261 262 263
	p.Lock()
	defer p.Unlock()

264
	if !p.id.Equal(pkid) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266 267 268
		return fmt.Errorf("Public key does not match peer.ID.")
	}

	// if we didn't have the keys, assign them.
269 270
	if p.pubKey == nil {
		p.pubKey = pk
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
271 272 273 274
		return nil
	}

	// if we already had the pubkey, check they're equal.
275
	if p.pubKey.Equals(pk) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276 277 278 279 280 281
		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.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
	log.Errorf("%s had PubKey: %v -- got %v", p, p.pubKey, pk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283 284
	panic("invariant violated: unexpected key mismatch")
}
285

Jeromy's avatar
Jeromy committed
286
// Updates this peer with information from another peer instance
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287 288 289 290 291 292 293 294 295
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)
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
296 297
	p.SetLatency(other.GetLatency())

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311
	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
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
// 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))
}