-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeer.go
More file actions
362 lines (331 loc) · 10.1 KB
/
Copy pathpeer.go
File metadata and controls
362 lines (331 loc) · 10.1 KB
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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"io/ioutil"
"net/http"
"sort"
)
type PeerId uuid.UUID
type Peer struct {
Id PeerId
Address string
}
func (p Peer) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"id": uuid.UUID(p.Id).String(),
"address": p.Address,
})
}
func (p *Peer) UnmarshalJSON(byt []byte) error {
var temp struct {
Id string `json:"id"`
Address string `json:"address"`
}
err := json.Unmarshal(byt, &temp)
if err != nil {
return err
}
rawPeerId, err := uuid.Parse(temp.Id)
if err != nil {
return err
}
p.Id = PeerId(rawPeerId)
p.Address = temp.Address
return nil
}
func (p *Peer) Header() string {
return fmt.Sprintf("%s %s", uuid.UUID(p.Id).String(), p.Address)
}
func (p *Peer) Equal(to Peer) bool {
return p.Id == to.Id && p.Address == to.Address
}
type PeerRanking uint
const NODE_DEFAULT_PEER_RANKING = PeerRanking(10)
const NODE_PEER_OFFLINE_DECREMENT = PeerRanking(1)
const NODE_PEER_INVALID_REQUEST_DECREMENT = PeerRanking(1)
const NODE_PEER_NEW_VALID_PEER_INCREMENT = PeerRanking(2)
const NODE_MINIMUM_PEER_COUNT = 3
const NODE_IDEAL_PEER_COUNT = 10
type PeerSet struct {
Me Peer
peers map[PeerId]Peer
rankings map[PeerId]PeerRanking
untrusted []PeerId
}
func NewPeerSet(address string) *PeerSet {
me := Peer{
Id: PeerId(uuid.New()),
Address: address,
}
return &PeerSet{
Me: me,
peers: map[PeerId]Peer{me.Id: me},
rankings: map[PeerId]PeerRanking{
me.Id: NODE_DEFAULT_PEER_RANKING,
},
untrusted: []PeerId{},
}
}
func (ps *PeerSet) Has(id PeerId) bool {
if _, ok := ps.peers[id]; ok {
return true
} else {
return false
}
}
func (ps *PeerSet) Untrusted(id PeerId) bool {
for _, pId := range ps.untrusted {
if pId == id {
return true
}
}
return false
}
func (ps *PeerSet) MarkUntrusted(id PeerId) {
ps.untrusted = append(ps.untrusted, id)
}
func (ps *PeerSet) Count() int {
return len(ps.rankings)
}
func (ps *PeerSet) Insert(peer Peer) bool {
// Add peers into the peerset, if they aren't already in the peerset, or already been marked as
// untrusted
if ps.Has(peer.Id) {
return false
}
if ps.Untrusted(peer.Id) {
return false
}
if peer.Id == ps.Me.Id {
return false
}
ps.peers[peer.Id] = peer
ps.rankings[peer.Id] = NODE_DEFAULT_PEER_RANKING
fmt.Printf("New peer %s (address %s) found!\n", uuid.UUID(peer.Id).String(), peer.Address)
return true
}
func (ps *PeerSet) InsertByAddress(peerAddress string) error {
resp, err := http.Get(fmt.Sprintf("%s/v1/me", peerAddress))
if err != nil {
return errors.New(fmt.Sprintf("Failed to get info from peer with address %s! %s\n", peerAddress, err))
}
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("Failed to get info from peer with address %s, failed with %d!\n", peerAddress, resp.StatusCode))
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
return errors.New(fmt.Sprintf("Failed to parse body when getting info from peer with address %s! %s\n", peerAddress, err2))
}
var response Peer
err = json.Unmarshal(body, &response)
if err != nil {
return errors.New(fmt.Sprintf("Failed to parse json body when getting info from peer with address %s! %s\n", peerAddress, err))
}
ps.Insert(response)
return nil
}
func (ps *PeerSet) Increment(id PeerId, change PeerRanking) {
ps.rankings[id] += change
ps.Rank()
}
func (ps *PeerSet) Decrement(id PeerId, change PeerRanking) {
if ps.rankings[id] > 0 {
ps.rankings[id] -= change
}
ps.Rank()
}
func (ps *PeerSet) Remove(id PeerId) {
delete(ps.peers, id)
delete(ps.rankings, id)
// But keep it in untrusted! That seems like a good idea
}
func (ps *PeerSet) Rank() {
// Recompute which peers are trustworthy and untrustworthy
for k, v := range ps.rankings {
if v == 0 {
ps.untrusted = append(ps.untrusted, k)
delete(ps.rankings, k)
}
}
}
func (ps *PeerSet) Refresh() error {
client := &http.Client{}
if len(ps.rankings) == 1 {
return errors.New("This node has no other peers to query for more peers!")
}
fmt.Println("Checking to make sure all peers are healthy...")
for _, peer := range ps.ListOthers() {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/v1/me", peer.Address), nil)
if err != nil {
fmt.Printf("Failed to assemble request for peer %s! %s\n", uuid.UUID(peer.Id).String(), err)
// Don't decrement the ranking in this case, this is probably not the peer's fault
continue
}
req.Header.Add("X-Peer-Info", ps.Me.Header())
resp, err1 := client.Do(req)
if err1 != nil {
fmt.Printf("Failed to check peer %s health! %s\n", uuid.UUID(peer.Id).String(), err1)
ps.Decrement(peer.Id, NODE_PEER_OFFLINE_DECREMENT)
continue
}
if resp.StatusCode != 200 {
fmt.Printf("Failed to check peer %s health, failed with %d!\n", uuid.UUID(peer.Id).String(), resp.StatusCode)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
fmt.Printf("Failed to parse body when checking peer %s health! %s\n", uuid.UUID(peer.Id).String(), err2)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
var response Peer
err = json.Unmarshal(body, &response)
if err != nil {
fmt.Printf("Failed to parse json body when checking peer %s health! %s\n", uuid.UUID(peer.Id).String(), err)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
// Make sure we aren't talking to ourselves!
if peer.Id == ps.Me.Id {
ps.Remove(peer.Id)
}
if peer.Id != response.Id {
fmt.Printf("Peer %s now has a different id, removing...\n", uuid.UUID(peer.Id).String())
ps.Remove(peer.Id)
ps.MarkUntrusted(peer.Id)
}
}
fmt.Println("Checking to make sure all peers are healthy...done")
fmt.Printf("Number of healthy peers: %d\n", ps.Count())
if len(ps.rankings) > NODE_MINIMUM_PEER_COUNT {
return nil
}
// Talk to peers to try to get more peers if we don't have enough
fmt.Printf("Trying to aquire more peers to get to %d\n", NODE_IDEAL_PEER_COUNT)
for _, peer := range ps.ListOthers() {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/v1/peers", peer.Address), nil)
if err != nil {
fmt.Printf("Failed to assemble request for peer %s! %s\n", uuid.UUID(peer.Id).String(), err)
// Don't decrement the ranking in this case, this is probably not the peer's fault
continue
}
req.Header.Add("X-Peer-Info", ps.Me.Header())
resp, err1 := client.Do(req)
if err1 != nil {
fmt.Printf("Failed to get peers from peer %s! %s\n", uuid.UUID(peer.Id).String(), err1)
ps.Decrement(peer.Id, NODE_PEER_OFFLINE_DECREMENT)
continue
}
if resp.StatusCode != 200 {
fmt.Printf("Failed to get peers from peer %s, failed with %d!\n", uuid.UUID(peer.Id).String(), resp.StatusCode)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
fmt.Printf("Failed to parse body when getting peers from peer %s! %s\n", uuid.UUID(peer.Id).String(), err2)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
var peerResponse struct {
Peers []Peer `json:"peers"`
}
err = json.Unmarshal(body, &peerResponse)
if err != nil {
fmt.Printf("Failed to parse json body when getting peers from peer %s! %s\n", uuid.UUID(peer.Id).String(), err)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
// For each new peer, try to merge it into the existing peer list
for _, newPeer := range peerResponse.Peers {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/v1/me", peer.Address), nil)
if err != nil {
fmt.Printf("Failed to assemble request for peer %s! %s\n", uuid.UUID(peer.Id).String(), err)
continue
}
req.Header.Add("X-Peer-Info", ps.Me.Header())
resp, err1 := client.Do(req)
if err1 != nil {
fmt.Printf("Failed to check peer %s id! %s\n", uuid.UUID(peer.Id).String(), err1)
continue
}
if resp.StatusCode != 200 {
fmt.Printf("Failed to check peer %s id, failed with %d!\n", uuid.UUID(peer.Id).String(), resp.StatusCode)
continue
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
fmt.Printf("Failed to parse body when checking peer %s id! %s\n", uuid.UUID(peer.Id).String(), err2)
ps.Decrement(peer.Id, NODE_PEER_INVALID_REQUEST_DECREMENT)
continue
}
var response Peer
err = json.Unmarshal(body, &response)
if err != nil {
fmt.Printf("Failed to parse json body when checking peer %s id! %s\n", uuid.UUID(peer.Id).String(), err)
continue
}
if uuid.UUID(peer.Id).String() != uuid.UUID(response.Id).String() {
fmt.Printf("Upon verification, peer %s actually has id %s, rejecting...\n", uuid.UUID(peer.Id).String(), uuid.UUID(response.Id).String())
continue
}
if ok := ps.Insert(newPeer); !ok {
continue
}
ps.Increment(peer.Id, NODE_PEER_NEW_VALID_PEER_INCREMENT)
fmt.Printf("Successfully added peer %s (from %s)\n", uuid.UUID(newPeer.Id).String(), uuid.UUID(peer.Id).String())
// Once we have enough peers, then we're done!
if ps.Count() >= NODE_IDEAL_PEER_COUNT {
fmt.Println("Reached ideal peer count!")
ps.Rank()
return nil
}
}
}
fmt.Printf("Number of peers: %d\n", ps.Count())
ps.Rank()
return nil
}
// ref: https://medium.com/@kdnotes/how-to-sort-golang-maps-by-value-and-key-eedc1199d944
type Pair struct {
Key Peer
Value PeerRanking
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (ps *PeerSet) List() []Peer {
// Return all peers, sorted in rank order
p := make(PairList, len(ps.rankings))
i := 0
for _, peer := range ps.peers {
if rank, ok := ps.rankings[peer.Id]; ok {
p[i] = Pair{peer, rank}
i++
}
}
sort.Sort(p)
var peerList []Peer = []Peer{}
for _, item := range p {
peerList = append(peerList, item.Key)
}
return peerList
}
func (ps *PeerSet) ListOthers() []Peer {
var peerList []Peer
for _, peer := range ps.List() {
if peer != ps.Me {
peerList = append(peerList, peer)
}
}
return peerList
}