github.com/amazechain/amc@v0.1.3/internal/p2p/discover/table.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package discover implements the Node Discovery Protocol. 18 // 19 // The Node Discovery protocol provides a way to find RLPx nodes that 20 // can be connected to. It uses a Kademlia-like protocol to maintain a 21 // distributed database of the IDs and endpoints of all listening 22 // nodes. 23 package discover 24 25 import ( 26 crand "crypto/rand" 27 "encoding/binary" 28 "fmt" 29 "github.com/amazechain/amc/common/types" 30 "github.com/amazechain/amc/internal/p2p/netutil" 31 "github.com/amazechain/amc/log" 32 mrand "math/rand" 33 "net" 34 "sort" 35 "sync" 36 "time" 37 38 "github.com/amazechain/amc/internal/p2p/enode" 39 ) 40 41 const ( 42 alpha = 3 // Kademlia concurrency factor 43 bucketSize = 16 // Kademlia bucket size 44 maxReplacements = 10 // Size of per-bucket replacement list 45 46 // We keep buckets for the upper 1/15 of distances because 47 // it's very unlikely we'll ever encounter a node that's closer. 48 hashBits = len(types.Hash{}) * 8 49 nBuckets = hashBits / 15 // Number of buckets 50 bucketMinDistance = hashBits - nBuckets // Log distance of closest bucket 51 52 // IP address limits. 53 bucketIPLimit, bucketSubnet = 2, 24 // at most 2 addresses from the same /24 54 tableIPLimit, tableSubnet = 10, 24 55 56 // refreshInterval 5分钟一刷新。 57 refreshInterval = 5 * time.Minute 58 revalidateInterval = 10 * time.Second 59 copyNodesInterval = 30 * time.Second 60 seedMinTableTime = 5 * time.Minute 61 seedCount = 30 62 seedMaxAge = 5 * 24 * time.Hour 63 ) 64 65 // Table is the 'node table', a Kademlia-like index of neighbor nodes. The table keeps 66 // itself up-to-date by verifying the liveness of neighbors and requesting their node 67 // records when announcements of a new record version are received. 68 type Table struct { 69 mutex sync.Mutex // protects buckets, bucket content, nursery, rand 70 buckets [nBuckets]*bucket // index of known nodes by distance 71 nursery []*node // bootstrap nodes 72 rand *mrand.Rand // source of randomness, periodically reseeded 73 ips netutil.DistinctNetSet 74 75 log log.Logger 76 db *enode.DB // database of known nodes 77 net transport 78 refreshReq chan chan struct{} 79 initDone chan struct{} 80 closeReq chan struct{} 81 closed chan struct{} 82 83 nodeAddedHook func(*node) // for testing 84 } 85 86 // transport is implemented by the UDP transports. 87 type transport interface { 88 Self() *enode.Node 89 RequestENR(*enode.Node) (*enode.Node, error) 90 lookupRandom() []*enode.Node 91 lookupSelf() []*enode.Node 92 ping(*enode.Node) (seq uint64, err error) 93 } 94 95 // bucket contains nodes, ordered by their last activity. the entry 96 // that was most recently active is the first element in entries. 97 type bucket struct { 98 entries []*node // live entries, sorted by time of last contact 99 replacements []*node // recently seen nodes to be used if revalidation fails 100 ips netutil.DistinctNetSet 101 } 102 103 func newTable(t transport, db *enode.DB, bootnodes []*enode.Node, log log.Logger) (*Table, error) { 104 tab := &Table{ 105 net: t, 106 db: db, 107 refreshReq: make(chan chan struct{}), 108 initDone: make(chan struct{}), 109 closeReq: make(chan struct{}), 110 closed: make(chan struct{}), 111 rand: mrand.New(mrand.NewSource(0)), 112 ips: netutil.DistinctNetSet{Subnet: tableSubnet, Limit: tableIPLimit}, 113 log: log, 114 } 115 if err := tab.setFallbackNodes(bootnodes); err != nil { 116 return nil, err 117 } 118 for i := range tab.buckets { 119 tab.buckets[i] = &bucket{ 120 ips: netutil.DistinctNetSet{Subnet: bucketSubnet, Limit: bucketIPLimit}, 121 } 122 } 123 tab.seedRand() 124 tab.loadSeedNodes() 125 126 return tab, nil 127 } 128 129 func (tab *Table) self() *enode.Node { 130 return tab.net.Self() 131 } 132 133 func (tab *Table) seedRand() { 134 var b [8]byte 135 crand.Read(b[:]) 136 137 tab.mutex.Lock() 138 tab.rand.Seed(int64(binary.BigEndian.Uint64(b[:]))) 139 tab.mutex.Unlock() 140 } 141 142 // ReadRandomNodes fills the given slice with random nodes from the table. The results 143 // are guaranteed to be unique for a single invocation, no node will appear twice. 144 func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) { 145 if !tab.isInitDone() { 146 return 0 147 } 148 tab.mutex.Lock() 149 defer tab.mutex.Unlock() 150 151 var nodes []*enode.Node 152 for _, b := range &tab.buckets { 153 for _, n := range b.entries { 154 nodes = append(nodes, unwrapNode(n)) 155 } 156 } 157 // Shuffle. 158 for i := 0; i < len(nodes); i++ { 159 j := tab.rand.Intn(len(nodes)) 160 nodes[i], nodes[j] = nodes[j], nodes[i] 161 } 162 return copy(buf, nodes) 163 } 164 165 // getNode returns the node with the given ID or nil if it isn't in the table. 166 func (tab *Table) getNode(id enode.ID) *enode.Node { 167 tab.mutex.Lock() 168 defer tab.mutex.Unlock() 169 170 b := tab.bucket(id) 171 for _, e := range b.entries { 172 if e.ID() == id { 173 return unwrapNode(e) 174 } 175 } 176 return nil 177 } 178 179 // close terminates the network listener and flushes the node database. 180 func (tab *Table) close() { 181 close(tab.closeReq) 182 <-tab.closed 183 } 184 185 // setFallbackNodes sets the initial points of contact. These nodes 186 // are used to connect to the network if the table is empty and there 187 // are no known nodes in the database. 188 func (tab *Table) setFallbackNodes(nodes []*enode.Node) error { 189 for _, n := range nodes { 190 if err := n.ValidateComplete(); err != nil { 191 return fmt.Errorf("bad bootstrap node %q: %v", n, err) 192 } 193 } 194 tab.nursery = wrapNodes(nodes) 195 return nil 196 } 197 198 // isInitDone returns whether the table's initial seeding procedure has completed. 199 func (tab *Table) isInitDone() bool { 200 select { 201 case <-tab.initDone: 202 return true 203 default: 204 return false 205 } 206 } 207 208 func (tab *Table) refresh() <-chan struct{} { 209 done := make(chan struct{}) 210 select { 211 case tab.refreshReq <- done: 212 case <-tab.closeReq: 213 close(done) 214 } 215 return done 216 } 217 218 // loop schedules runs of doRefresh, doRevalidate and copyLiveNodes. 219 func (tab *Table) loop() { 220 var ( 221 revalidate = time.NewTimer(tab.nextRevalidateTime()) 222 refresh = time.NewTicker(refreshInterval) 223 copyNodes = time.NewTicker(copyNodesInterval) 224 refreshDone = make(chan struct{}) // where doRefresh reports completion 225 revalidateDone chan struct{} // where doRevalidate reports completion 226 waiting = []chan struct{}{tab.initDone} // holds waiting callers while doRefresh runs 227 ) 228 defer refresh.Stop() 229 defer revalidate.Stop() 230 defer copyNodes.Stop() 231 232 // Start initial refresh. 233 go tab.doRefresh(refreshDone) 234 235 loop: 236 for { 237 select { 238 case <-refresh.C: 239 tab.seedRand() 240 if refreshDone == nil { 241 refreshDone = make(chan struct{}) 242 go tab.doRefresh(refreshDone) 243 } 244 case req := <-tab.refreshReq: 245 waiting = append(waiting, req) 246 if refreshDone == nil { 247 refreshDone = make(chan struct{}) 248 go tab.doRefresh(refreshDone) 249 } 250 case <-refreshDone: 251 for _, ch := range waiting { 252 close(ch) 253 } 254 waiting, refreshDone = nil, nil 255 case <-revalidate.C: 256 revalidateDone = make(chan struct{}) 257 go tab.doRevalidate(revalidateDone) 258 case <-revalidateDone: 259 revalidate.Reset(tab.nextRevalidateTime()) 260 revalidateDone = nil 261 case <-copyNodes.C: 262 go tab.copyLiveNodes() 263 case <-tab.closeReq: 264 break loop 265 } 266 } 267 268 if refreshDone != nil { 269 <-refreshDone 270 } 271 for _, ch := range waiting { 272 close(ch) 273 } 274 if revalidateDone != nil { 275 <-revalidateDone 276 } 277 close(tab.closed) 278 } 279 280 // doRefresh performs a lookup for a random target to keep buckets full. seed nodes are 281 // inserted if the table is empty (initial bootstrap or discarded faulty peers). 282 func (tab *Table) doRefresh(done chan struct{}) { 283 defer close(done) 284 285 // Load nodes from the database and insert 286 // them. This should yield a few previously seen nodes that are 287 // (hopefully) still alive. 288 tab.loadSeedNodes() 289 290 // Run self lookup to discover new neighbor nodes. 291 tab.net.lookupSelf() 292 293 // The Kademlia paper specifies that the bucket refresh should 294 // perform a lookup in the least recently used bucket. We cannot 295 // adhere to this because the findnode target is a 512bit value 296 // (not hash-sized) and it is not easily possible to generate a 297 // sha3 preimage that falls into a chosen bucket. 298 // We perform a few lookups with a random target instead. 299 for i := 0; i < 3; i++ { 300 tab.net.lookupRandom() 301 } 302 } 303 304 func (tab *Table) loadSeedNodes() { 305 seeds := wrapNodes(tab.db.QuerySeeds(seedCount, seedMaxAge)) 306 seeds = append(seeds, tab.nursery...) 307 for i := range seeds { 308 seed := seeds[i] 309 tab.addSeenNode(seed) 310 } 311 } 312 313 // doRevalidate checks that the last node in a random bucket is still live and replaces or 314 // deletes the node if it isn't. 315 func (tab *Table) doRevalidate(done chan<- struct{}) { 316 defer func() { done <- struct{}{} }() 317 318 last, bi := tab.nodeToRevalidate() 319 if last == nil { 320 // No non-empty bucket found. 321 return 322 } 323 324 // Ping the selected node and wait for a pong. 325 remoteSeq, err := tab.net.ping(unwrapNode(last)) 326 327 // Also fetch record if the node replied and returned a higher sequence number. 328 if last.Seq() < remoteSeq { 329 n, err := tab.net.RequestENR(unwrapNode(last)) 330 if err != nil { 331 tab.log.Debug("ENR request failed", "id", last.ID(), "addr", last.addr(), "err", err) 332 } else { 333 last = &node{Node: *n, addedAt: last.addedAt, livenessChecks: last.livenessChecks} 334 } 335 } 336 337 tab.mutex.Lock() 338 defer tab.mutex.Unlock() 339 b := tab.buckets[bi] 340 if err == nil { 341 // The node responded, move it to the front. 342 last.livenessChecks++ 343 tab.log.Trace("Revalidated node", "b", bi, "id", last.ID(), "checks", last.livenessChecks) 344 tab.bumpInBucket(b, last) 345 return 346 } 347 // No reply received, pick a replacement or delete the node if there aren't 348 // any replacements. 349 if r := tab.replace(b, last); r != nil { 350 tab.log.Debug("Replaced dead node", "b", bi, "id", last.ID(), "ip", last.IP(), "checks", last.livenessChecks, "r", r.ID(), "rip", r.IP()) 351 } else { 352 tab.log.Debug("Removed dead node", "b", bi, "id", last.ID(), "ip", last.IP(), "checks", last.livenessChecks) 353 } 354 } 355 356 // nodeToRevalidate returns the last node in a random, non-empty bucket. 357 func (tab *Table) nodeToRevalidate() (n *node, bi int) { 358 tab.mutex.Lock() 359 defer tab.mutex.Unlock() 360 361 for _, bi = range tab.rand.Perm(len(tab.buckets)) { 362 b := tab.buckets[bi] 363 if len(b.entries) > 0 { 364 last := b.entries[len(b.entries)-1] 365 return last, bi 366 } 367 } 368 return nil, 0 369 } 370 371 func (tab *Table) nextRevalidateTime() time.Duration { 372 tab.mutex.Lock() 373 defer tab.mutex.Unlock() 374 375 return time.Duration(tab.rand.Int63n(int64(revalidateInterval))) 376 } 377 378 // copyLiveNodes adds nodes from the table to the database if they have been in the table 379 // longer than seedMinTableTime. 380 func (tab *Table) copyLiveNodes() { 381 tab.mutex.Lock() 382 defer tab.mutex.Unlock() 383 384 now := time.Now() 385 for _, b := range &tab.buckets { 386 for _, n := range b.entries { 387 if n.livenessChecks > 0 && now.Sub(n.addedAt) >= seedMinTableTime { 388 tab.db.UpdateNode(unwrapNode(n)) 389 } 390 } 391 } 392 } 393 394 // findnodeByID returns the n nodes in the table that are closest to the given id. 395 // This is used by the FINDNODE/v4 handler. 396 // 397 // The preferLive parameter says whether the caller wants liveness-checked results. If 398 // preferLive is true and the table contains any verified nodes, the result will not 399 // contain unverified nodes. However, if there are no verified nodes at all, the result 400 // will contain unverified nodes. 401 func (tab *Table) findnodeByID(target enode.ID, nresults int, preferLive bool) *nodesByDistance { 402 tab.mutex.Lock() 403 defer tab.mutex.Unlock() 404 405 // Scan all buckets. There might be a better way to do this, but there aren't that many 406 // buckets, so this solution should be fine. The worst-case complexity of this loop 407 // is O(tab.len() * nresults). 408 nodes := &nodesByDistance{target: target} 409 liveNodes := &nodesByDistance{target: target} 410 for _, b := range &tab.buckets { 411 for _, n := range b.entries { 412 nodes.push(n, nresults) 413 if preferLive && n.livenessChecks > 0 { 414 liveNodes.push(n, nresults) 415 } 416 } 417 } 418 419 if preferLive && len(liveNodes.entries) > 0 { 420 return liveNodes 421 } 422 return nodes 423 } 424 425 // len returns the number of nodes in the table. 426 func (tab *Table) len() (n int) { 427 tab.mutex.Lock() 428 defer tab.mutex.Unlock() 429 430 for _, b := range &tab.buckets { 431 n += len(b.entries) 432 } 433 return n 434 } 435 436 // bucketLen returns the number of nodes in the bucket for the given ID. 437 func (tab *Table) bucketLen(id enode.ID) int { 438 tab.mutex.Lock() 439 defer tab.mutex.Unlock() 440 441 return len(tab.bucket(id).entries) 442 } 443 444 // bucket returns the bucket for the given node ID hash. 445 func (tab *Table) bucket(id enode.ID) *bucket { 446 d := enode.LogDist(tab.self().ID(), id) 447 return tab.bucketAtDistance(d) 448 } 449 450 func (tab *Table) bucketAtDistance(d int) *bucket { 451 if d <= bucketMinDistance { 452 return tab.buckets[0] 453 } 454 return tab.buckets[d-bucketMinDistance-1] 455 } 456 457 // addSeenNode adds a node which may or may not be live to the end of a bucket. If the 458 // bucket has space available, adding the node succeeds immediately. Otherwise, the node is 459 // added to the replacements list. 460 // 461 // The caller must not hold tab.mutex. 462 func (tab *Table) addSeenNode(n *node) { 463 if n.ID() == tab.self().ID() { 464 return 465 } 466 467 tab.mutex.Lock() 468 defer tab.mutex.Unlock() 469 b := tab.bucket(n.ID()) 470 if contains(b.entries, n.ID()) { 471 // Already in bucket, don't add. 472 return 473 } 474 if len(b.entries) >= bucketSize { 475 // Bucket full, maybe add as replacement. 476 tab.addReplacement(b, n) 477 return 478 } 479 if !tab.addIP(b, n.IP()) { 480 // Can't add: IP limit reached. 481 return 482 } 483 // Add to end of bucket: 484 b.entries = append(b.entries, n) 485 b.replacements = deleteNode(b.replacements, n) 486 n.addedAt = time.Now() 487 if tab.nodeAddedHook != nil { 488 tab.nodeAddedHook(n) 489 } 490 } 491 492 // addVerifiedNode adds a node whose existence has been verified recently to the front of a 493 // bucket. If the node is already in the bucket, it is moved to the front. If the bucket 494 // has no space, the node is added to the replacements list. 495 // 496 // There is an additional safety measure: if the table is still initializing the node 497 // is not added. This prevents an attack where the table could be filled by just sending 498 // ping repeatedly. 499 // 500 // The caller must not hold tab.mutex. 501 func (tab *Table) addVerifiedNode(n *node) { 502 if !tab.isInitDone() { 503 return 504 } 505 if n.ID() == tab.self().ID() { 506 return 507 } 508 509 tab.mutex.Lock() 510 defer tab.mutex.Unlock() 511 b := tab.bucket(n.ID()) 512 if tab.bumpInBucket(b, n) { 513 // Already in bucket, moved to front. 514 return 515 } 516 if len(b.entries) >= bucketSize { 517 // Bucket full, maybe add as replacement. 518 tab.addReplacement(b, n) 519 return 520 } 521 if !tab.addIP(b, n.IP()) { 522 // Can't add: IP limit reached. 523 return 524 } 525 // Add to front of bucket. 526 b.entries, _ = pushNode(b.entries, n, bucketSize) 527 b.replacements = deleteNode(b.replacements, n) 528 n.addedAt = time.Now() 529 if tab.nodeAddedHook != nil { 530 tab.nodeAddedHook(n) 531 } 532 } 533 534 // delete removes an entry from the node table. It is used to evacuate dead nodes. 535 func (tab *Table) delete(node *node) { 536 tab.mutex.Lock() 537 defer tab.mutex.Unlock() 538 539 tab.deleteInBucket(tab.bucket(node.ID()), node) 540 } 541 542 func (tab *Table) addIP(b *bucket, ip net.IP) bool { 543 if len(ip) == 0 { 544 return false // Nodes without IP cannot be added. 545 } 546 if netutil.IsLAN(ip) { 547 return true 548 } 549 if !tab.ips.Add(ip) { 550 tab.log.Debug("IP exceeds table limit", "ip", ip) 551 return false 552 } 553 if !b.ips.Add(ip) { 554 tab.log.Debug("IP exceeds bucket limit", "ip", ip) 555 tab.ips.Remove(ip) 556 return false 557 } 558 return true 559 } 560 561 func (tab *Table) removeIP(b *bucket, ip net.IP) { 562 if netutil.IsLAN(ip) { 563 return 564 } 565 tab.ips.Remove(ip) 566 b.ips.Remove(ip) 567 } 568 569 func (tab *Table) addReplacement(b *bucket, n *node) { 570 for _, e := range b.replacements { 571 if e.ID() == n.ID() { 572 return // already in list 573 } 574 } 575 if !tab.addIP(b, n.IP()) { 576 return 577 } 578 var removed *node 579 b.replacements, removed = pushNode(b.replacements, n, maxReplacements) 580 if removed != nil { 581 tab.removeIP(b, removed.IP()) 582 } 583 } 584 585 // replace removes n from the replacement list and replaces 'last' with it if it is the 586 // last entry in the bucket. If 'last' isn't the last entry, it has either been replaced 587 // with someone else or became active. 588 func (tab *Table) replace(b *bucket, last *node) *node { 589 if len(b.entries) == 0 || b.entries[len(b.entries)-1].ID() != last.ID() { 590 // Entry has moved, don't replace it. 591 return nil 592 } 593 // Still the last entry. 594 if len(b.replacements) == 0 { 595 tab.deleteInBucket(b, last) 596 return nil 597 } 598 r := b.replacements[tab.rand.Intn(len(b.replacements))] 599 b.replacements = deleteNode(b.replacements, r) 600 b.entries[len(b.entries)-1] = r 601 tab.removeIP(b, last.IP()) 602 return r 603 } 604 605 // bumpInBucket moves the given node to the front of the bucket entry list 606 // if it is contained in that list. 607 func (tab *Table) bumpInBucket(b *bucket, n *node) bool { 608 for i := range b.entries { 609 if b.entries[i].ID() == n.ID() { 610 if !n.IP().Equal(b.entries[i].IP()) { 611 // Endpoint has changed, ensure that the new IP fits into table limits. 612 tab.removeIP(b, b.entries[i].IP()) 613 if !tab.addIP(b, n.IP()) { 614 // It doesn't, put the previous one back. 615 tab.addIP(b, b.entries[i].IP()) 616 return false 617 } 618 } 619 // Move it to the front. 620 copy(b.entries[1:], b.entries[:i]) 621 b.entries[0] = n 622 return true 623 } 624 } 625 return false 626 } 627 628 func (tab *Table) deleteInBucket(b *bucket, n *node) { 629 b.entries = deleteNode(b.entries, n) 630 tab.removeIP(b, n.IP()) 631 } 632 633 func contains(ns []*node, id enode.ID) bool { 634 for _, n := range ns { 635 if n.ID() == id { 636 return true 637 } 638 } 639 return false 640 } 641 642 // pushNode adds n to the front of list, keeping at most max items. 643 func pushNode(list []*node, n *node, max int) ([]*node, *node) { 644 if len(list) < max { 645 list = append(list, nil) 646 } 647 removed := list[len(list)-1] 648 copy(list[1:], list) 649 list[0] = n 650 return list, removed 651 } 652 653 // deleteNode removes n from list. 654 func deleteNode(list []*node, n *node) []*node { 655 for i := range list { 656 if list[i].ID() == n.ID() { 657 return append(list[:i], list[i+1:]...) 658 } 659 } 660 return list 661 } 662 663 // nodesByDistance is a list of nodes, ordered by distance to target. 664 type nodesByDistance struct { 665 entries []*node 666 target enode.ID 667 } 668 669 // push adds the given node to the list, keeping the total size below maxElems. 670 func (h *nodesByDistance) push(n *node, maxElems int) { 671 ix := sort.Search(len(h.entries), func(i int) bool { 672 return enode.DistCmp(h.target, h.entries[i].ID(), n.ID()) > 0 673 }) 674 675 end := len(h.entries) 676 if len(h.entries) < maxElems { 677 h.entries = append(h.entries, n) 678 } 679 if ix < end { 680 // Slide existing entries down to make room. 681 // This will overwrite the entry we just appended. 682 copy(h.entries[ix+1:], h.entries[ix:]) 683 h.entries[ix] = n 684 } 685 }