table.go 19 KB

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