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

import (
Jeromy's avatar
Jeromy committed
4
	"sync"
Jeromy's avatar
Jeromy committed
5
	"time"
6

Jeromy's avatar
Jeromy committed
7
	b58 "github.com/jbenet/go-base58"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	u "github.com/jbenet/go-ipfs/util"
9 10
	ma "github.com/jbenet/go-multiaddr"
	mh "github.com/jbenet/go-multihash"
11 12

	"bytes"
13 14
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16
// ID is a byte slice representing the identity of a peer.
type ID mh.Multihash
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17

18
// Utililty function for comparing two peer ID's
19 20
func (id ID) Equal(other ID) bool {
	return bytes.Equal(id, other)
21 22
}

23
func (id ID) Pretty() string {
24
	return b58.Encode(id)
25 26
}

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

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
30
// Peer represents the identity information of an IPFS Node, including
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
// ID, and relevant Addresses.
32
type Peer struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
	ID        ID
34
	Addresses []*ma.Multiaddr
Jeromy's avatar
Jeromy committed
35

Jeromy's avatar
Jeromy committed
36
	latency   time.Duration
37
	latenLock sync.RWMutex
38 39
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
// Key returns the ID as a Key (string) for maps.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
func (p *Peer) Key() u.Key {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	return u.Key(p.ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
45
// AddAddress adds the given Multiaddr address to Peer's addresses.
46 47 48 49
func (p *Peer) AddAddress(a *ma.Multiaddr) {
	p.Addresses = append(p.Addresses, a)
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
50
// NetAddress returns the first Multiaddr found for a given network.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
func (p *Peer) NetAddress(n string) *ma.Multiaddr {
	for _, a := range p.Addresses {
		ps, err := a.Protocols()
		if err != nil {
			continue // invalid addr
		}

		for _, p := range ps {
			if p.Name == n {
				return a
			}
		}
	}
	return nil
}
Jeromy's avatar
Jeromy committed
66

67 68 69 70 71
func (p *Peer) GetLatency() (out time.Duration) {
	p.latenLock.RLock()
	out = p.latency
	p.latenLock.RUnlock()
	return
Jeromy's avatar
Jeromy committed
72 73
}

74 75
// TODO: Instead of just keeping a single number,
//		 keep a running average over the last hour or so
76 77 78 79
func (p *Peer) SetLatency(laten time.Duration) {
	p.latenLock.Lock()
	p.latency = laten
	p.latenLock.Unlock()
Jeromy's avatar
Jeromy committed
80
}