/
table.go
229 lines (175 loc) · 5.34 KB
/
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
package kademlia
import (
"container/list"
"fmt"
"github.com/perlin-network/noise"
"sync"
)
// Table represents a Kademlia routing table.
type Table struct {
sync.RWMutex
entries [noise.SizePublicKey * 8]*list.List
self noise.ID
size int
}
// NewTable instantiates a new routing table whose XOR distance metric is defined with respect to some
// given ID.
func NewTable(self noise.ID) *Table {
table := &Table{self: self}
for i := 0; i < len(table.entries); i++ {
table.entries[i] = list.New()
}
if _, err := table.Update(self); err != nil {
panic(err)
}
return table
}
// Self returns the ID which this routing table's XOR distance metric is defined with respect to.
func (t *Table) Self() noise.ID {
return t.self
}
// Last returns the last id of the bucket where target resides within.
func (t *Table) Last(target noise.PublicKey) noise.ID {
t.RLock()
defer t.RUnlock()
return t.entries[t.getBucketIndex(target)].Back().Value.(noise.ID)
}
// Bucket returns all entries of a bucket where target reside within.
func (t *Table) Bucket(target noise.PublicKey) []noise.ID {
t.RLock()
defer t.RUnlock()
bucket := t.entries[t.getBucketIndex(target)]
entries := make([]noise.ID, 0, bucket.Len())
for e := bucket.Front(); e != nil; e = e.Next() {
entries = append(entries, e.Value.(noise.ID))
}
return entries
}
// Update attempts to insert the target node/peer ID into this routing table. If the bucket it was expected
// to be inserted within is full, ErrBucketFull is returned. If the ID already exists in its respective routing
// table bucket, it is moved to the head of the bucket and false is returned. If the ID has yet to exist, it is
// appended to the head of its intended bucket and true is returned.
func (t *Table) Update(target noise.ID) (bool, error) {
if target.ID == noise.ZeroPublicKey {
return false, nil
}
t.Lock()
defer t.Unlock()
bucket := t.entries[t.getBucketIndex(target.ID)]
for e := bucket.Front(); e != nil; e = e.Next() {
if e.Value.(noise.ID).ID == target.ID { // Found the target ID already inside the routing table.
bucket.MoveToFront(e)
return false, nil
}
}
if bucket.Len() < BucketSize { // The bucket is not yet under full capacity.
bucket.PushFront(target)
t.size++
return true, nil
}
// The bucket is at full capacity. Return ErrBucketFull.
return false, fmt.Errorf("cannot insert id %x into routing table: %w", target.ID, ErrBucketFull)
}
// Recorded returns true if target is already recorded in this routing table.
func (t *Table) Recorded(target noise.PublicKey) bool {
t.RLock()
defer t.RUnlock()
bucket := t.entries[t.getBucketIndex(target)]
for e := bucket.Front(); e != nil; e = e.Next() {
if e.Value.(noise.ID).ID == target {
return true
}
}
return false
}
// Delete removes target from this routing table. It returns the id of the delted target and true if found, or
// a zero-value ID and false otherwise.
func (t *Table) Delete(target noise.PublicKey) (noise.ID, bool) {
t.Lock()
defer t.Unlock()
bucket := t.entries[t.getBucketIndex(target)]
for e := bucket.Front(); e != nil; e = e.Next() {
id := e.Value.(noise.ID)
if id.ID == target {
bucket.Remove(e)
t.size--
return id, true
}
}
return noise.ID{}, false
}
// DeleteByAddress removes the first occurrence of an id with target as its address from this routing table. It
// returns the id of the deleted target and true if found, or a zero-value ID and false otherwise.
func (t *Table) DeleteByAddress(target string) (noise.ID, bool) {
t.Lock()
defer t.Unlock()
for _, bucket := range t.entries {
for e := bucket.Front(); e != nil; e = e.Next() {
id := e.Value.(noise.ID)
if id.Address == target {
bucket.Remove(e)
t.size--
return id, true
}
}
}
return noise.ID{}, false
}
// Peers returns BucketSize closest peer IDs to the ID which this routing table's distance metric is defined against.
func (t *Table) Peers() []noise.ID {
return t.FindClosest(t.self.ID, BucketSize)
}
// FindClosest returns the k closest peer IDs to target, and sorts them based on how close they are.
func (t *Table) FindClosest(target noise.PublicKey, k int) []noise.ID {
var closest []noise.ID
f := func(bucket *list.List) {
for e := bucket.Front(); e != nil; e = e.Next() {
id := e.Value.(noise.ID)
if id.ID != target {
closest = append(closest, id)
}
}
}
t.RLock()
defer t.RUnlock()
idx := t.getBucketIndex(target)
f(t.entries[idx])
for i := 1; len(closest) < k && (idx-i >= 0 || idx+i < len(t.entries)); i++ {
if idx-i >= 0 {
f(t.entries[idx-i])
}
if idx+i < len(t.entries) {
f(t.entries[idx+i])
}
}
closest = SortByDistance(target, closest)
if len(closest) > k {
closest = closest[:k]
}
return closest
}
// Entries returns all stored ids in this routing table.
func (t *Table) Entries() []noise.ID {
t.RLock()
defer t.RUnlock()
entries := make([]noise.ID, 0, t.size)
for _, bucket := range t.entries {
for e := bucket.Front(); e != nil; e = e.Next() {
entries = append(entries, e.Value.(noise.ID))
}
}
return entries
}
// NumEntries returns the total amount of ids stored in this routing table.
func (t *Table) NumEntries() int {
t.RLock()
defer t.RUnlock()
return t.size
}
func (t *Table) getBucketIndex(target noise.PublicKey) int {
l := PrefixLen(XOR(target[:], t.self.ID[:]))
if l == noise.SizePublicKey*8 {
return l - 1
}
return l
}