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

import (
4
	"encoding/hex"
5
	"time"
6

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

	"bytes"
12 13
)

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

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

22 23 24 25
func (id ID) Pretty() string {
	return hex.EncodeToString(id)
}

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

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

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

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

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
47
// NetAddress returns the first Multiaddr found for a given network.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
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
}