-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_table.go
250 lines (206 loc) · 5.7 KB
/
peer_table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
package peer
import (
"math/rand"
"sync"
"strings"
"path"
"path/filepath"
pr "github.com/libp2p/go-libp2p-core/peer"
"github.com/ltdai010/theta/common"
mm "github.com/ltdai010/theta/common/math"
"github.com/spf13/viper"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/opt"
)
const (
// % of total peers known returned by GetSelection.
getSelectionPercent = 23
// min peers that must be returned by GetSelection. Useful for bootstrapping.
minGetSelection = 32
// max peers returned by GetSelection
maxGetSelection = 250
dbKey = "peers"
)
//
// PeerTable is a lookup table for peers
//
type PeerTable struct {
mutex *sync.Mutex
peerMap map[pr.ID]*Peer // map: peerID |-> *Peer
peers []*Peer // For iteration with deterministic order
db *leveldb.DB // peerTable persistence for restart
}
// CreatePeerTable creates an instance of the PeerTable
func CreatePeerTable() PeerTable {
cfgPath := filepath.Dir(viper.ConfigFileUsed())
dbPath := path.Join(cfgPath, "db", "peer_table")
db, err := leveldb.OpenFile(dbPath, &opt.Options{
OpenFilesCacheCapacity: 0,
BlockCacheCapacity: 256 / 2 * opt.MiB,
WriteBuffer: 256 / 4 * opt.MiB, // Two of these are used internally
Filter: filter.NewBloomFilter(10),
})
if _, corrupted := err.(*errors.ErrCorrupted); corrupted {
db, err = leveldb.RecoverFile(dbPath, nil)
}
// (Re)check for errors and abort if opening of the db failed
if err != nil {
logger.Errorf("Failed to create db for peer table, %v", err)
}
return PeerTable{
mutex: &sync.Mutex{},
peerMap: make(map[pr.ID]*Peer),
db: db,
}
}
// AddPeer adds the given peer to the PeerTable
func (pt *PeerTable) AddPeer(peer *Peer) bool {
pt.mutex.Lock()
defer pt.mutex.Unlock()
_, exists := pt.peerMap[peer.ID()]
if exists {
// Update existing entry with same ID.
for i, p := range pt.peers {
if p.ID() == peer.ID() {
p.Stop()
logger.Warnf("Stopping duplicated peer: %v", p.ID())
pt.peers[i] = peer
break
}
}
} else {
pt.peers = append(pt.peers, peer)
}
pt.peerMap[peer.ID()] = peer
pt.persistPeers()
return true
}
// DeletePeer deletes the given peer from the PeerTable
func (pt *PeerTable) DeletePeer(peerID pr.ID) {
pt.mutex.Lock()
defer pt.mutex.Unlock()
if _, ok := pt.peerMap[peerID]; !ok {
return
}
delete(pt.peerMap, peerID)
for idx, peer := range pt.peers {
if peer.ID() == peerID {
pt.peers = append(pt.peers[:idx], pt.peers[idx+1:]...)
}
}
pt.persistPeers()
}
// GetPeer returns the peer for the given peerID (if exists)
func (pt *PeerTable) GetPeer(peerID pr.ID) *Peer {
pt.mutex.Lock()
defer pt.mutex.Unlock()
peer, exists := pt.peerMap[peerID]
if !exists {
return nil
}
return peer
}
// PeerExists indicates whether the PeerTable has a peer for the given peerID
func (pt *PeerTable) PeerExists(peerID pr.ID) bool {
pt.mutex.Lock()
defer pt.mutex.Unlock()
_, exists := pt.peerMap[peerID]
return exists
}
// GetAllPeers returns all the peers
func (pt *PeerTable) GetAllPeers() *([]*Peer) {
pt.mutex.Lock()
defer pt.mutex.Unlock()
ret := make([]*Peer, len(pt.peers))
for i, p := range pt.peers {
ret[i] = p
}
return &ret
}
// GetAllPeers returns all the peers
func (pt *PeerTable) GetAllPeerIDs() *[]pr.ID {
pt.mutex.Lock()
defer pt.mutex.Unlock()
ret := make([]pr.ID, len(pt.peers))
for i, p := range pt.peers {
ret[i] = p.ID()
}
return &ret
}
func (pt *PeerTable) RetrievePreviousPeers() (res []*pr.AddrInfo, err error) {
dat, err := pt.db.Get([]byte(dbKey), nil)
if err != nil {
logger.Warnf("Failed to retrieve previously persisted peers")
return
}
arr := strings.Split(string(dat), "|")
for _, json := range arr {
var addrInfo pr.AddrInfo
err = addrInfo.UnmarshalJSON([]byte(json))
if err != nil {
logger.Warnf("Failed to unmarshal peer addr info, %v", json)
break
}
res = append(res, &addrInfo)
}
return
}
func (pt *PeerTable) persistPeers() {
maxPeerPersistence := viper.GetInt(common.CfgMaxNumPersistentPeers)
numPeers := len(pt.peers)
numInDB := numPeers
if numPeers > maxPeerPersistence {
numInDB = maxPeerPersistence
}
peerAddrInfos := make([]string, numInDB)
dbPeers := pt.peers[numPeers - numInDB:]
for i, p := range dbPeers {
json, err := p.addrInfo.MarshalJSON()
if err == nil {
peerAddrInfos[i] = string(json)
}
}
go pt.writeToDB(dbKey, strings.Join(peerAddrInfos, "|"))
}
func (pt *PeerTable) writeToDB(key, value string) {
pt.db.Put([]byte(key), []byte(value), nil)
}
// GetSelection randomly selects some peers. Suitable for peer-exchange protocols.
func (pt *PeerTable) GetSelection() (peerIDAddrs []pr.ID) {
pt.mutex.Lock()
defer pt.mutex.Unlock()
if len(pt.peers) == 0 {
return nil
}
peers := make([]*Peer, len(pt.peers))
copy(peers, pt.peers)
numPeers := mm.MaxInt(
mm.MinInt(minGetSelection, len(peers)),
len(peers)*getSelectionPercent/100)
numPeers = mm.MinInt(maxGetSelection, numPeers)
// Fisher-Yates shuffle the array. We only need to do the first
// `numPeers' since we are throwing the rest.
for i := 0; i < numPeers; i++ {
// pick a number between current index and the end
j := rand.Intn(len(peers)-i) + i
peers[i], peers[j] = peers[j], peers[i]
}
// slice off the limit we are willing to share.
peers = peers[:numPeers]
for _, peer := range peers {
// peerIDAddr := PeerIDAddress{
// ID: peer.ID(),
// Addr: peer.netAddress,
// }
peerIDAddrs = append(peerIDAddrs, peer.ID())
}
return
}
// GetTotalNumPeers returns the total number of peers in the PeerTable
func (pt *PeerTable) GetTotalNumPeers() uint {
pt.mutex.Lock()
defer pt.mutex.Unlock()
return uint(len(pt.peers))
}