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

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	u "github.com/jbenet/go-ipfs/util"
5 6
	ma "github.com/jbenet/go-multiaddr"
	mh "github.com/jbenet/go-multihash"
7 8

	"bytes"
9 10
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
// ID is a byte slice representing the identity of a peer.
type ID mh.Multihash
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13

14 15 16 17 18
// Utililty function for comparing two peer ID's
func (id *ID) Equal(other *ID) bool {
	return bytes.Equal(*id, *other)
}

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

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
22
// Peer represents the identity information of an IPFS Node, including
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23
// ID, and relevant Addresses.
24
type Peer struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25
	ID        ID
26 27 28
	Addresses []*ma.Multiaddr
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
// Key returns the ID as a Key (string) for maps.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
func (p *Peer) Key() u.Key {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
	return u.Key(p.ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32 33
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
34
// AddAddress adds the given Multiaddr address to Peer's addresses.
35 36 37 38
func (p *Peer) AddAddress(a *ma.Multiaddr) {
	p.Addresses = append(p.Addresses, a)
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
39
// NetAddress returns the first Multiaddr found for a given network.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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
}