peerstore.go 6.03 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
4
5
package peer

import (
	"errors"
	"sync"
6
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	ic "github.com/jbenet/go-ipfs/p2p/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
10
11
12
13
14

	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dssync "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
)

15
16
17
18
19
const (
	// AddressTTL is the expiration time of addresses.
	AddressTTL = time.Hour
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Peerstore provides a threadsafe store of Peer related
// information.
type Peerstore interface {
	KeyBook
	AddressBook
	Metrics

	// Peers returns a list of all peer.IDs in this Peerstore
	Peers() []ID

	// PeerInfo returns a peer.PeerInfo struct for given peer.ID.
	// This is a small slice of the information Peerstore has on
	// that peer, useful to other services.
	PeerInfo(ID) PeerInfo

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
36
37
	// AddPeerInfo absorbs the information listed in given PeerInfo.
	AddPeerInfo(PeerInfo)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
39
40
41
42
43
44
45
46
	// Get/Put is a simple registry for other peer-related key/value pairs.
	// if we find something we use often, it should become its own set of
	// methods. this is a last resort.
	Get(id ID, key string) (interface{}, error)
	Put(id ID, key string, val interface{}) error
}

// AddressBook tracks the addresses of Peers
type AddressBook interface {
47
48
49
50
	Addresses(ID) []ma.Multiaddr     // returns addresses for ID
	AddAddress(ID, ma.Multiaddr)     // Adds given addr for ID
	AddAddresses(ID, []ma.Multiaddr) // Adds given addrs for ID
	SetAddresses(ID, []ma.Multiaddr) // Sets given addrs for ID (clears previously stored)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
52
}

53
54
55
56
57
58
59
60
61
62
type expiringAddr struct {
	Addr ma.Multiaddr
	TTL  time.Time
}

func (e *expiringAddr) Expired() bool {
	return time.Now().After(e.TTL)
}

type addressMap map[string]expiringAddr
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
64

type addressbook struct {
65
66
	sync.RWMutex // guards all fields

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
	addrs map[ID]addressMap
68
	ttl   time.Duration // initial ttl
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
70
71
}

func newAddressbook() *addressbook {
72
73
74
75
	return &addressbook{
		addrs: map[ID]addressMap{},
		ttl:   AddressTTL,
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
77
78
79
80
81
82
83
84
85
86
87
88
}

func (ab *addressbook) Peers() []ID {
	ab.RLock()
	ps := make([]ID, 0, len(ab.addrs))
	for p := range ab.addrs {
		ps = append(ps, p)
	}
	ab.RUnlock()
	return ps
}

func (ab *addressbook) Addresses(p ID) []ma.Multiaddr {
89
90
	ab.Lock()
	defer ab.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
92
93
94
95
96

	maddrs, found := ab.addrs[p]
	if !found {
		return nil
	}

97
98
99
100
101
102
103
104
105
106
107
108
109
	good := make([]ma.Multiaddr, 0, len(maddrs))
	var expired []string
	for s, m := range maddrs {
		if m.Expired() {
			expired = append(expired, s)
		} else {
			good = append(good, m.Addr)
		}
	}

	// clean up the expired ones.
	for _, s := range expired {
		delete(ab.addrs[p], s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110
	}
111
	return good
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
113
114
}

func (ab *addressbook) AddAddress(p ID, m ma.Multiaddr) {
115
116
117
118
	ab.AddAddresses(p, []ma.Multiaddr{m})
}

func (ab *addressbook) AddAddresses(p ID, ms []ma.Multiaddr) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
120
121
	ab.Lock()
	defer ab.Unlock()

122
	amap, found := ab.addrs[p]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
	if !found {
124
125
126
		amap = addressMap{}
		ab.addrs[p] = amap
	}
127
128

	ttl := time.Now().Add(ab.ttl)
129
	for _, m := range ms {
130
131
132
133
134
		// re-set all of them for new ttl.
		amap[m.String()] = expiringAddr{
			Addr: m,
			TTL:  ttl,
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135
136
137
	}
}

138
func (ab *addressbook) SetAddresses(p ID, ms []ma.Multiaddr) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
140
141
	ab.Lock()
	defer ab.Unlock()

142
	amap := addressMap{}
143
	ttl := time.Now().Add(ab.ttl)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
	for _, m := range ms {
145
		amap[m.String()] = expiringAddr{Addr: m, TTL: ttl}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
	}
147
	ab.addrs[p] = amap // clear what was there before
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
}

// KeyBook tracks the Public keys of Peers.
type KeyBook interface {
	PubKey(ID) ic.PubKey
	AddPubKey(ID, ic.PubKey) error

	PrivKey(ID) ic.PrivKey
	AddPrivKey(ID, ic.PrivKey) error
}

type keybook struct {
	pks map[ID]ic.PubKey
	sks map[ID]ic.PrivKey

	sync.RWMutex // same lock. wont happen a ton.
}

func newKeybook() *keybook {
	return &keybook{
		pks: map[ID]ic.PubKey{},
		sks: map[ID]ic.PrivKey{},
	}
}

func (kb *keybook) Peers() []ID {
	kb.RLock()
	ps := make([]ID, 0, len(kb.pks)+len(kb.sks))
	for p := range kb.pks {
		ps = append(ps, p)
	}
	for p := range kb.sks {
		if _, found := kb.pks[p]; !found {
			ps = append(ps, p)
		}
	}
	kb.RUnlock()
	return ps
}

func (kb *keybook) PubKey(p ID) ic.PubKey {
	kb.RLock()
	pk := kb.pks[p]
	kb.RUnlock()
	return pk
}

func (kb *keybook) AddPubKey(p ID, pk ic.PubKey) error {

	// check it's correct first
	if !p.MatchesPublicKey(pk) {
		return errors.New("ID does not match PublicKey")
	}

	kb.Lock()
	kb.pks[p] = pk
	kb.Unlock()
	return nil
}

func (kb *keybook) PrivKey(p ID) ic.PrivKey {
	kb.RLock()
	sk := kb.sks[p]
	kb.RUnlock()
	return sk
}

func (kb *keybook) AddPrivKey(p ID, sk ic.PrivKey) error {

	if sk == nil {
		return errors.New("sk is nil (PrivKey)")
	}

	// check it's correct first
	if !p.MatchesPrivateKey(sk) {
		return errors.New("ID does not match PrivateKey")
	}

	kb.Lock()
	kb.sks[p] = sk
	kb.Unlock()
	return nil
}

type peerstore struct {
	keybook
	addressbook
	metrics

	// store other data, like versions
	ds ds.ThreadSafeDatastore
}

// NewPeerstore creates a threadsafe collection of peers.
func NewPeerstore() Peerstore {
	return &peerstore{
		keybook:     *newKeybook(),
		addressbook: *newAddressbook(),
		metrics:     *(NewMetrics()).(*metrics),
		ds:          dssync.MutexWrap(ds.NewMapDatastore()),
	}
}

func (ps *peerstore) Put(p ID, key string, val interface{}) error {
	dsk := ds.NewKey(string(p) + "/" + key)
	return ps.ds.Put(dsk, val)
}

func (ps *peerstore) Get(p ID, key string) (interface{}, error) {
	dsk := ds.NewKey(string(p) + "/" + key)
	return ps.ds.Get(dsk)
}

func (ps *peerstore) Peers() []ID {
	set := map[ID]struct{}{}
	for _, p := range ps.keybook.Peers() {
		set[p] = struct{}{}
	}
	for _, p := range ps.addressbook.Peers() {
		set[p] = struct{}{}
	}

	pps := make([]ID, 0, len(set))
	for p := range set {
		pps = append(pps, p)
	}
	return pps
}

func (ps *peerstore) PeerInfo(p ID) PeerInfo {
	return PeerInfo{
		ID:    p,
		Addrs: ps.addressbook.Addresses(p),
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284
285
286
287
func (ps *peerstore) AddPeerInfo(pi PeerInfo) {
	ps.AddAddresses(pi.ID, pi.Addrs)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
func PeerInfos(ps Peerstore, peers []ID) []PeerInfo {
	pi := make([]PeerInfo, len(peers))
	for i, p := range peers {
		pi[i] = ps.PeerInfo(p)
	}
	return pi
}

func PeerInfoIDs(pis []PeerInfo) []ID {
	ps := make([]ID, len(pis))
	for i, pi := range pis {
		ps[i] = pi.ID
	}
	return ps
}