github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/p2p/discv5/net.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package discv5 19 20 import ( 21 "bytes" 22 "crypto/ecdsa" 23 "errors" 24 "fmt" 25 "net" 26 "time" 27 28 "github.com/AigarNetwork/aigar/common" 29 "github.com/AigarNetwork/aigar/common/mclock" 30 "github.com/AigarNetwork/aigar/crypto" 31 "github.com/AigarNetwork/aigar/log" 32 "github.com/AigarNetwork/aigar/p2p/netutil" 33 "github.com/AigarNetwork/aigar/rlp" 34 "golang.org/x/crypto/sha3" 35 ) 36 37 var ( 38 errInvalidEvent = errors.New("invalid in current state") 39 errNoQuery = errors.New("no pending query") 40 ) 41 42 const ( 43 autoRefreshInterval = 1 * time.Hour 44 bucketRefreshInterval = 1 * time.Minute 45 seedCount = 30 46 seedMaxAge = 5 * 24 * time.Hour 47 lowPort = 1024 48 ) 49 50 const testTopic = "foo" 51 52 const ( 53 printTestImgLogs = false 54 ) 55 56 // Network manages the table and all protocol interaction. 57 type Network struct { 58 db *nodeDB // database of known nodes 59 conn transport 60 netrestrict *netutil.Netlist 61 62 closed chan struct{} // closed when loop is done 63 closeReq chan struct{} // 'request to close' 64 refreshReq chan []*Node // lookups ask for refresh on this channel 65 refreshResp chan (<-chan struct{}) // ...and get the channel to block on from this one 66 read chan ingressPacket // ingress packets arrive here 67 timeout chan timeoutEvent 68 queryReq chan *findnodeQuery // lookups submit findnode queries on this channel 69 tableOpReq chan func() 70 tableOpResp chan struct{} 71 topicRegisterReq chan topicRegisterReq 72 topicSearchReq chan topicSearchReq 73 74 // State of the main loop. 75 tab *Table 76 topictab *topicTable 77 ticketStore *ticketStore 78 nursery []*Node 79 nodes map[NodeID]*Node // tracks active nodes with state != known 80 timeoutTimers map[timeoutEvent]*time.Timer 81 82 // Revalidation queues. 83 // Nodes put on these queues will be pinged eventually. 84 slowRevalidateQueue []*Node 85 fastRevalidateQueue []*Node 86 87 // Buffers for state transition. 88 sendBuf []*ingressPacket 89 } 90 91 // transport is implemented by the UDP transport. 92 // it is an interface so we can test without opening lots of UDP 93 // sockets and without generating a private key. 94 type transport interface { 95 sendPing(remote *Node, remoteAddr *net.UDPAddr, topics []Topic) (hash []byte) 96 sendNeighbours(remote *Node, nodes []*Node) 97 sendFindnodeHash(remote *Node, target common.Hash) 98 sendTopicRegister(remote *Node, topics []Topic, topicIdx int, pong []byte) 99 sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) 100 101 send(remote *Node, ptype nodeEvent, p interface{}) (hash []byte) 102 103 localAddr() *net.UDPAddr 104 Close() 105 } 106 107 type findnodeQuery struct { 108 remote *Node 109 target common.Hash 110 reply chan<- []*Node 111 nresults int // counter for received nodes 112 } 113 114 type topicRegisterReq struct { 115 add bool 116 topic Topic 117 } 118 119 type topicSearchReq struct { 120 topic Topic 121 found chan<- *Node 122 lookup chan<- bool 123 delay time.Duration 124 } 125 126 type topicSearchResult struct { 127 target lookupInfo 128 nodes []*Node 129 } 130 131 type timeoutEvent struct { 132 ev nodeEvent 133 node *Node 134 } 135 136 func newNetwork(conn transport, ourPubkey ecdsa.PublicKey, dbPath string, netrestrict *netutil.Netlist) (*Network, error) { 137 ourID := PubkeyID(&ourPubkey) 138 139 var db *nodeDB 140 if dbPath != "<no database>" { 141 var err error 142 if db, err = newNodeDB(dbPath, Version, ourID); err != nil { 143 return nil, err 144 } 145 } 146 147 tab := newTable(ourID, conn.localAddr()) 148 net := &Network{ 149 db: db, 150 conn: conn, 151 netrestrict: netrestrict, 152 tab: tab, 153 topictab: newTopicTable(db, tab.self), 154 ticketStore: newTicketStore(), 155 refreshReq: make(chan []*Node), 156 refreshResp: make(chan (<-chan struct{})), 157 closed: make(chan struct{}), 158 closeReq: make(chan struct{}), 159 read: make(chan ingressPacket, 100), 160 timeout: make(chan timeoutEvent), 161 timeoutTimers: make(map[timeoutEvent]*time.Timer), 162 tableOpReq: make(chan func()), 163 tableOpResp: make(chan struct{}), 164 queryReq: make(chan *findnodeQuery), 165 topicRegisterReq: make(chan topicRegisterReq), 166 topicSearchReq: make(chan topicSearchReq), 167 nodes: make(map[NodeID]*Node), 168 } 169 go net.loop() 170 return net, nil 171 } 172 173 // Close terminates the network listener and flushes the node database. 174 func (net *Network) Close() { 175 net.conn.Close() 176 select { 177 case <-net.closed: 178 case net.closeReq <- struct{}{}: 179 <-net.closed 180 } 181 } 182 183 // Self returns the local node. 184 // The returned node should not be modified by the caller. 185 func (net *Network) Self() *Node { 186 return net.tab.self 187 } 188 189 // ReadRandomNodes fills the given slice with random nodes from the 190 // table. It will not write the same node more than once. The nodes in 191 // the slice are copies and can be modified by the caller. 192 func (net *Network) ReadRandomNodes(buf []*Node) (n int) { 193 net.reqTableOp(func() { n = net.tab.readRandomNodes(buf) }) 194 return n 195 } 196 197 // SetFallbackNodes sets the initial points of contact. These nodes 198 // are used to connect to the network if the table is empty and there 199 // are no known nodes in the database. 200 func (net *Network) SetFallbackNodes(nodes []*Node) error { 201 nursery := make([]*Node, 0, len(nodes)) 202 for _, n := range nodes { 203 if err := n.validateComplete(); err != nil { 204 return fmt.Errorf("bad bootstrap/fallback node %q (%v)", n, err) 205 } 206 // Recompute cpy.sha because the node might not have been 207 // created by NewNode or ParseNode. 208 cpy := *n 209 cpy.sha = crypto.Keccak256Hash(n.ID[:]) 210 nursery = append(nursery, &cpy) 211 } 212 net.reqRefresh(nursery) 213 return nil 214 } 215 216 // Resolve searches for a specific node with the given ID. 217 // It returns nil if the node could not be found. 218 func (net *Network) Resolve(targetID NodeID) *Node { 219 result := net.lookup(crypto.Keccak256Hash(targetID[:]), true) 220 for _, n := range result { 221 if n.ID == targetID { 222 return n 223 } 224 } 225 return nil 226 } 227 228 // Lookup performs a network search for nodes close 229 // to the given target. It approaches the target by querying 230 // nodes that are closer to it on each iteration. 231 // The given target does not need to be an actual node 232 // identifier. 233 // 234 // The local node may be included in the result. 235 func (net *Network) Lookup(targetID NodeID) []*Node { 236 return net.lookup(crypto.Keccak256Hash(targetID[:]), false) 237 } 238 239 func (net *Network) lookup(target common.Hash, stopOnMatch bool) []*Node { 240 var ( 241 asked = make(map[NodeID]bool) 242 seen = make(map[NodeID]bool) 243 reply = make(chan []*Node, alpha) 244 result = nodesByDistance{target: target} 245 pendingQueries = 0 246 ) 247 // Get initial answers from the local node. 248 result.push(net.tab.self, bucketSize) 249 for { 250 // Ask the α closest nodes that we haven't asked yet. 251 for i := 0; i < len(result.entries) && pendingQueries < alpha; i++ { 252 n := result.entries[i] 253 if !asked[n.ID] { 254 asked[n.ID] = true 255 pendingQueries++ 256 net.reqQueryFindnode(n, target, reply) 257 } 258 } 259 if pendingQueries == 0 { 260 // We have asked all closest nodes, stop the search. 261 break 262 } 263 // Wait for the next reply. 264 select { 265 case nodes := <-reply: 266 for _, n := range nodes { 267 if n != nil && !seen[n.ID] { 268 seen[n.ID] = true 269 result.push(n, bucketSize) 270 if stopOnMatch && n.sha == target { 271 return result.entries 272 } 273 } 274 } 275 pendingQueries-- 276 case <-time.After(respTimeout): 277 // forget all pending requests, start new ones 278 pendingQueries = 0 279 reply = make(chan []*Node, alpha) 280 } 281 } 282 return result.entries 283 } 284 285 func (net *Network) RegisterTopic(topic Topic, stop <-chan struct{}) { 286 select { 287 case net.topicRegisterReq <- topicRegisterReq{true, topic}: 288 case <-net.closed: 289 return 290 } 291 select { 292 case <-net.closed: 293 case <-stop: 294 select { 295 case net.topicRegisterReq <- topicRegisterReq{false, topic}: 296 case <-net.closed: 297 } 298 } 299 } 300 301 func (net *Network) SearchTopic(topic Topic, setPeriod <-chan time.Duration, found chan<- *Node, lookup chan<- bool) { 302 for { 303 select { 304 case <-net.closed: 305 return 306 case delay, ok := <-setPeriod: 307 select { 308 case net.topicSearchReq <- topicSearchReq{topic: topic, found: found, lookup: lookup, delay: delay}: 309 case <-net.closed: 310 return 311 } 312 if !ok { 313 return 314 } 315 } 316 } 317 } 318 319 func (net *Network) reqRefresh(nursery []*Node) <-chan struct{} { 320 select { 321 case net.refreshReq <- nursery: 322 return <-net.refreshResp 323 case <-net.closed: 324 return net.closed 325 } 326 } 327 328 func (net *Network) reqQueryFindnode(n *Node, target common.Hash, reply chan []*Node) bool { 329 q := &findnodeQuery{remote: n, target: target, reply: reply} 330 select { 331 case net.queryReq <- q: 332 return true 333 case <-net.closed: 334 return false 335 } 336 } 337 338 func (net *Network) reqReadPacket(pkt ingressPacket) { 339 select { 340 case net.read <- pkt: 341 case <-net.closed: 342 } 343 } 344 345 func (net *Network) reqTableOp(f func()) (called bool) { 346 select { 347 case net.tableOpReq <- f: 348 <-net.tableOpResp 349 return true 350 case <-net.closed: 351 return false 352 } 353 } 354 355 // TODO: external address handling. 356 357 type topicSearchInfo struct { 358 lookupChn chan<- bool 359 period time.Duration 360 } 361 362 const maxSearchCount = 5 363 364 func (net *Network) loop() { 365 var ( 366 refreshTimer = time.NewTicker(autoRefreshInterval) 367 bucketRefreshTimer = time.NewTimer(bucketRefreshInterval) 368 refreshDone chan struct{} // closed when the 'refresh' lookup has ended 369 ) 370 371 // Tracking the next ticket to register. 372 var ( 373 nextTicket *ticketRef 374 nextRegisterTimer *time.Timer 375 nextRegisterTime <-chan time.Time 376 ) 377 defer func() { 378 if nextRegisterTimer != nil { 379 nextRegisterTimer.Stop() 380 } 381 }() 382 resetNextTicket := func() { 383 ticket, timeout := net.ticketStore.nextFilteredTicket() 384 if nextTicket != ticket { 385 nextTicket = ticket 386 if nextRegisterTimer != nil { 387 nextRegisterTimer.Stop() 388 nextRegisterTime = nil 389 } 390 if ticket != nil { 391 nextRegisterTimer = time.NewTimer(timeout) 392 nextRegisterTime = nextRegisterTimer.C 393 } 394 } 395 } 396 397 // Tracking registration and search lookups. 398 var ( 399 topicRegisterLookupTarget lookupInfo 400 topicRegisterLookupDone chan []*Node 401 topicRegisterLookupTick = time.NewTimer(0) 402 searchReqWhenRefreshDone []topicSearchReq 403 searchInfo = make(map[Topic]topicSearchInfo) 404 activeSearchCount int 405 ) 406 topicSearchLookupDone := make(chan topicSearchResult, 100) 407 topicSearch := make(chan Topic, 100) 408 <-topicRegisterLookupTick.C 409 410 statsDump := time.NewTicker(10 * time.Second) 411 412 loop: 413 for { 414 resetNextTicket() 415 416 select { 417 case <-net.closeReq: 418 log.Trace("<-net.closeReq") 419 break loop 420 421 // Ingress packet handling. 422 case pkt := <-net.read: 423 //fmt.Println("read", pkt.ev) 424 log.Trace("<-net.read") 425 n := net.internNode(&pkt) 426 prestate := n.state 427 status := "ok" 428 if err := net.handle(n, pkt.ev, &pkt); err != nil { 429 status = err.Error() 430 } 431 log.Trace("", "msg", log.Lazy{Fn: func() string { 432 return fmt.Sprintf("<<< (%d) %v from %x@%v: %v -> %v (%v)", 433 net.tab.count, pkt.ev, pkt.remoteID[:8], pkt.remoteAddr, prestate, n.state, status) 434 }}) 435 // TODO: persist state if n.state goes >= known, delete if it goes <= known 436 437 // State transition timeouts. 438 case timeout := <-net.timeout: 439 log.Trace("<-net.timeout") 440 if net.timeoutTimers[timeout] == nil { 441 // Stale timer (was aborted). 442 continue 443 } 444 delete(net.timeoutTimers, timeout) 445 prestate := timeout.node.state 446 status := "ok" 447 if err := net.handle(timeout.node, timeout.ev, nil); err != nil { 448 status = err.Error() 449 } 450 log.Trace("", "msg", log.Lazy{Fn: func() string { 451 return fmt.Sprintf("--- (%d) %v for %x@%v: %v -> %v (%v)", 452 net.tab.count, timeout.ev, timeout.node.ID[:8], timeout.node.addr(), prestate, timeout.node.state, status) 453 }}) 454 455 // Querying. 456 case q := <-net.queryReq: 457 log.Trace("<-net.queryReq") 458 if !q.start(net) { 459 q.remote.deferQuery(q) 460 } 461 462 // Interacting with the table. 463 case f := <-net.tableOpReq: 464 log.Trace("<-net.tableOpReq") 465 f() 466 net.tableOpResp <- struct{}{} 467 468 // Topic registration stuff. 469 case req := <-net.topicRegisterReq: 470 log.Trace("<-net.topicRegisterReq") 471 if !req.add { 472 net.ticketStore.removeRegisterTopic(req.topic) 473 continue 474 } 475 net.ticketStore.addTopic(req.topic, true) 476 // If we're currently waiting idle (nothing to look up), give the ticket store a 477 // chance to start it sooner. This should speed up convergence of the radius 478 // determination for new topics. 479 // if topicRegisterLookupDone == nil { 480 if topicRegisterLookupTarget.target == (common.Hash{}) { 481 log.Trace("topicRegisterLookupTarget == null") 482 if topicRegisterLookupTick.Stop() { 483 <-topicRegisterLookupTick.C 484 } 485 target, delay := net.ticketStore.nextRegisterLookup() 486 topicRegisterLookupTarget = target 487 topicRegisterLookupTick.Reset(delay) 488 } 489 490 case nodes := <-topicRegisterLookupDone: 491 log.Trace("<-topicRegisterLookupDone") 492 net.ticketStore.registerLookupDone(topicRegisterLookupTarget, nodes, func(n *Node) []byte { 493 net.ping(n, n.addr()) 494 return n.pingEcho 495 }) 496 target, delay := net.ticketStore.nextRegisterLookup() 497 topicRegisterLookupTarget = target 498 topicRegisterLookupTick.Reset(delay) 499 topicRegisterLookupDone = nil 500 501 case <-topicRegisterLookupTick.C: 502 log.Trace("<-topicRegisterLookupTick") 503 if (topicRegisterLookupTarget.target == common.Hash{}) { 504 target, delay := net.ticketStore.nextRegisterLookup() 505 topicRegisterLookupTarget = target 506 topicRegisterLookupTick.Reset(delay) 507 topicRegisterLookupDone = nil 508 } else { 509 topicRegisterLookupDone = make(chan []*Node) 510 target := topicRegisterLookupTarget.target 511 go func() { topicRegisterLookupDone <- net.lookup(target, false) }() 512 } 513 514 case <-nextRegisterTime: 515 log.Trace("<-nextRegisterTime") 516 net.ticketStore.ticketRegistered(*nextTicket) 517 //fmt.Println("sendTopicRegister", nextTicket.t.node.addr().String(), nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) 518 net.conn.sendTopicRegister(nextTicket.t.node, nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) 519 520 case req := <-net.topicSearchReq: 521 if refreshDone == nil { 522 log.Trace("<-net.topicSearchReq") 523 info, ok := searchInfo[req.topic] 524 if ok { 525 if req.delay == time.Duration(0) { 526 delete(searchInfo, req.topic) 527 net.ticketStore.removeSearchTopic(req.topic) 528 } else { 529 info.period = req.delay 530 searchInfo[req.topic] = info 531 } 532 continue 533 } 534 if req.delay != time.Duration(0) { 535 var info topicSearchInfo 536 info.period = req.delay 537 info.lookupChn = req.lookup 538 searchInfo[req.topic] = info 539 net.ticketStore.addSearchTopic(req.topic, req.found) 540 topicSearch <- req.topic 541 } 542 } else { 543 searchReqWhenRefreshDone = append(searchReqWhenRefreshDone, req) 544 } 545 546 case topic := <-topicSearch: 547 if activeSearchCount < maxSearchCount { 548 activeSearchCount++ 549 target := net.ticketStore.nextSearchLookup(topic) 550 go func() { 551 nodes := net.lookup(target.target, false) 552 topicSearchLookupDone <- topicSearchResult{target: target, nodes: nodes} 553 }() 554 } 555 period := searchInfo[topic].period 556 if period != time.Duration(0) { 557 go func() { 558 time.Sleep(period) 559 topicSearch <- topic 560 }() 561 } 562 563 case res := <-topicSearchLookupDone: 564 activeSearchCount-- 565 if lookupChn := searchInfo[res.target.topic].lookupChn; lookupChn != nil { 566 lookupChn <- net.ticketStore.radius[res.target.topic].converged 567 } 568 net.ticketStore.searchLookupDone(res.target, res.nodes, func(n *Node, topic Topic) []byte { 569 if n.state != nil && n.state.canQuery { 570 return net.conn.send(n, topicQueryPacket, topicQuery{Topic: topic}) // TODO: set expiration 571 } 572 if n.state == unknown { 573 net.ping(n, n.addr()) 574 } 575 return nil 576 }) 577 578 case <-statsDump.C: 579 log.Trace("<-statsDump.C") 580 /*r, ok := net.ticketStore.radius[testTopic] 581 if !ok { 582 fmt.Printf("(%x) no radius @ %v\n", net.tab.self.ID[:8], time.Now()) 583 } else { 584 topics := len(net.ticketStore.tickets) 585 tickets := len(net.ticketStore.nodes) 586 rad := r.radius / (maxRadius/10000+1) 587 fmt.Printf("(%x) topics:%d radius:%d tickets:%d @ %v\n", net.tab.self.ID[:8], topics, rad, tickets, time.Now()) 588 }*/ 589 590 tm := mclock.Now() 591 for topic, r := range net.ticketStore.radius { 592 if printTestImgLogs { 593 rad := r.radius / (maxRadius/1000000 + 1) 594 minrad := r.minRadius / (maxRadius/1000000 + 1) 595 fmt.Printf("*R %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], rad) 596 fmt.Printf("*MR %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], minrad) 597 } 598 } 599 for topic, t := range net.topictab.topics { 600 wp := t.wcl.nextWaitPeriod(tm) 601 if printTestImgLogs { 602 fmt.Printf("*W %d %v %016x %d\n", tm/1000000, topic, net.tab.self.sha[:8], wp/1000000) 603 } 604 } 605 606 // Periodic / lookup-initiated bucket refresh. 607 case <-refreshTimer.C: 608 log.Trace("<-refreshTimer.C") 609 // TODO: ideally we would start the refresh timer after 610 // fallback nodes have been set for the first time. 611 if refreshDone == nil { 612 refreshDone = make(chan struct{}) 613 net.refresh(refreshDone) 614 } 615 case <-bucketRefreshTimer.C: 616 target := net.tab.chooseBucketRefreshTarget() 617 go func() { 618 net.lookup(target, false) 619 bucketRefreshTimer.Reset(bucketRefreshInterval) 620 }() 621 case newNursery := <-net.refreshReq: 622 log.Trace("<-net.refreshReq") 623 if newNursery != nil { 624 net.nursery = newNursery 625 } 626 if refreshDone == nil { 627 refreshDone = make(chan struct{}) 628 net.refresh(refreshDone) 629 } 630 net.refreshResp <- refreshDone 631 case <-refreshDone: 632 log.Trace("<-net.refreshDone", "table size", net.tab.count) 633 if net.tab.count != 0 { 634 refreshDone = nil 635 list := searchReqWhenRefreshDone 636 searchReqWhenRefreshDone = nil 637 go func() { 638 for _, req := range list { 639 net.topicSearchReq <- req 640 } 641 }() 642 } else { 643 refreshDone = make(chan struct{}) 644 net.refresh(refreshDone) 645 } 646 } 647 } 648 log.Trace("loop stopped") 649 650 log.Debug(fmt.Sprintf("shutting down")) 651 if net.conn != nil { 652 net.conn.Close() 653 } 654 if refreshDone != nil { 655 // TODO: wait for pending refresh. 656 //<-refreshResults 657 } 658 // Cancel all pending timeouts. 659 for _, timer := range net.timeoutTimers { 660 timer.Stop() 661 } 662 if net.db != nil { 663 net.db.close() 664 } 665 close(net.closed) 666 } 667 668 // Everything below runs on the Network.loop goroutine 669 // and can modify Node, Table and Network at any time without locking. 670 671 func (net *Network) refresh(done chan<- struct{}) { 672 var seeds []*Node 673 if net.db != nil { 674 seeds = net.db.querySeeds(seedCount, seedMaxAge) 675 } 676 if len(seeds) == 0 { 677 seeds = net.nursery 678 } 679 if len(seeds) == 0 { 680 log.Trace("no seed nodes found") 681 time.AfterFunc(time.Second*10, func() { close(done) }) 682 return 683 } 684 for _, n := range seeds { 685 log.Debug("", "msg", log.Lazy{Fn: func() string { 686 var age string 687 if net.db != nil { 688 age = time.Since(net.db.lastPong(n.ID)).String() 689 } else { 690 age = "unknown" 691 } 692 return fmt.Sprintf("seed node (age %s): %v", age, n) 693 }}) 694 n = net.internNodeFromDB(n) 695 if n.state == unknown { 696 net.transition(n, verifyinit) 697 } 698 // Force-add the seed node so Lookup does something. 699 // It will be deleted again if verification fails. 700 net.tab.add(n) 701 } 702 // Start self lookup to fill up the buckets. 703 go func() { 704 net.Lookup(net.tab.self.ID) 705 close(done) 706 }() 707 } 708 709 // Node Interning. 710 711 func (net *Network) internNode(pkt *ingressPacket) *Node { 712 if n := net.nodes[pkt.remoteID]; n != nil { 713 n.IP = pkt.remoteAddr.IP 714 n.UDP = uint16(pkt.remoteAddr.Port) 715 n.TCP = uint16(pkt.remoteAddr.Port) 716 return n 717 } 718 n := NewNode(pkt.remoteID, pkt.remoteAddr.IP, uint16(pkt.remoteAddr.Port), uint16(pkt.remoteAddr.Port)) 719 n.state = unknown 720 net.nodes[pkt.remoteID] = n 721 return n 722 } 723 724 func (net *Network) internNodeFromDB(dbn *Node) *Node { 725 if n := net.nodes[dbn.ID]; n != nil { 726 return n 727 } 728 n := NewNode(dbn.ID, dbn.IP, dbn.UDP, dbn.TCP) 729 n.state = unknown 730 net.nodes[n.ID] = n 731 return n 732 } 733 734 func (net *Network) internNodeFromNeighbours(sender *net.UDPAddr, rn rpcNode) (n *Node, err error) { 735 if rn.ID == net.tab.self.ID { 736 return nil, errors.New("is self") 737 } 738 if rn.UDP <= lowPort { 739 return nil, errors.New("low port") 740 } 741 n = net.nodes[rn.ID] 742 if n == nil { 743 // We haven't seen this node before. 744 n, err = nodeFromRPC(sender, rn) 745 if net.netrestrict != nil && !net.netrestrict.Contains(n.IP) { 746 return n, errors.New("not contained in netrestrict whitelist") 747 } 748 if err == nil { 749 n.state = unknown 750 net.nodes[n.ID] = n 751 } 752 return n, err 753 } 754 if !n.IP.Equal(rn.IP) || n.UDP != rn.UDP || n.TCP != rn.TCP { 755 if n.state == known { 756 // reject address change if node is known by us 757 err = fmt.Errorf("metadata mismatch: got %v, want %v", rn, n) 758 } else { 759 // accept otherwise; this will be handled nicer with signed ENRs 760 n.IP = rn.IP 761 n.UDP = rn.UDP 762 n.TCP = rn.TCP 763 } 764 } 765 return n, err 766 } 767 768 // nodeNetGuts is embedded in Node and contains fields. 769 type nodeNetGuts struct { 770 // This is a cached copy of sha3(ID) which is used for node 771 // distance calculations. This is part of Node in order to make it 772 // possible to write tests that need a node at a certain distance. 773 // In those tests, the content of sha will not actually correspond 774 // with ID. 775 sha common.Hash 776 777 // State machine fields. Access to these fields 778 // is restricted to the Network.loop goroutine. 779 state *nodeState 780 pingEcho []byte // hash of last ping sent by us 781 pingTopics []Topic // topic set sent by us in last ping 782 deferredQueries []*findnodeQuery // queries that can't be sent yet 783 pendingNeighbours *findnodeQuery // current query, waiting for reply 784 queryTimeouts int 785 } 786 787 func (n *nodeNetGuts) deferQuery(q *findnodeQuery) { 788 n.deferredQueries = append(n.deferredQueries, q) 789 } 790 791 func (n *nodeNetGuts) startNextQuery(net *Network) { 792 if len(n.deferredQueries) == 0 { 793 return 794 } 795 nextq := n.deferredQueries[0] 796 if nextq.start(net) { 797 n.deferredQueries = append(n.deferredQueries[:0], n.deferredQueries[1:]...) 798 } 799 } 800 801 func (q *findnodeQuery) start(net *Network) bool { 802 // Satisfy queries against the local node directly. 803 if q.remote == net.tab.self { 804 closest := net.tab.closest(q.target, bucketSize) 805 q.reply <- closest.entries 806 return true 807 } 808 if q.remote.state.canQuery && q.remote.pendingNeighbours == nil { 809 net.conn.sendFindnodeHash(q.remote, q.target) 810 net.timedEvent(respTimeout, q.remote, neighboursTimeout) 811 q.remote.pendingNeighbours = q 812 return true 813 } 814 // If the node is not known yet, it won't accept queries. 815 // Initiate the transition to known. 816 // The request will be sent later when the node reaches known state. 817 if q.remote.state == unknown { 818 net.transition(q.remote, verifyinit) 819 } 820 return false 821 } 822 823 // Node Events (the input to the state machine). 824 825 type nodeEvent uint 826 827 //go:generate stringer -type=nodeEvent 828 829 const ( 830 831 // Packet type events. 832 // These correspond to packet types in the UDP protocol. 833 pingPacket = iota + 1 834 pongPacket 835 findnodePacket 836 neighborsPacket 837 findnodeHashPacket 838 topicRegisterPacket 839 topicQueryPacket 840 topicNodesPacket 841 842 // Non-packet events. 843 // Event values in this category are allocated outside 844 // the packet type range (packet types are encoded as a single byte). 845 pongTimeout nodeEvent = iota + 256 846 pingTimeout 847 neighboursTimeout 848 ) 849 850 // Node State Machine. 851 852 type nodeState struct { 853 name string 854 handle func(*Network, *Node, nodeEvent, *ingressPacket) (next *nodeState, err error) 855 enter func(*Network, *Node) 856 canQuery bool 857 } 858 859 func (s *nodeState) String() string { 860 return s.name 861 } 862 863 var ( 864 unknown *nodeState 865 verifyinit *nodeState 866 verifywait *nodeState 867 remoteverifywait *nodeState 868 known *nodeState 869 contested *nodeState 870 unresponsive *nodeState 871 ) 872 873 func init() { 874 unknown = &nodeState{ 875 name: "unknown", 876 enter: func(net *Network, n *Node) { 877 net.tab.delete(n) 878 n.pingEcho = nil 879 // Abort active queries. 880 for _, q := range n.deferredQueries { 881 q.reply <- nil 882 } 883 n.deferredQueries = nil 884 if n.pendingNeighbours != nil { 885 n.pendingNeighbours.reply <- nil 886 n.pendingNeighbours = nil 887 } 888 n.queryTimeouts = 0 889 }, 890 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 891 switch ev { 892 case pingPacket: 893 net.handlePing(n, pkt) 894 net.ping(n, pkt.remoteAddr) 895 return verifywait, nil 896 default: 897 return unknown, errInvalidEvent 898 } 899 }, 900 } 901 902 verifyinit = &nodeState{ 903 name: "verifyinit", 904 enter: func(net *Network, n *Node) { 905 net.ping(n, n.addr()) 906 }, 907 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 908 switch ev { 909 case pingPacket: 910 net.handlePing(n, pkt) 911 return verifywait, nil 912 case pongPacket: 913 err := net.handleKnownPong(n, pkt) 914 return remoteverifywait, err 915 case pongTimeout: 916 return unknown, nil 917 default: 918 return verifyinit, errInvalidEvent 919 } 920 }, 921 } 922 923 verifywait = &nodeState{ 924 name: "verifywait", 925 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 926 switch ev { 927 case pingPacket: 928 net.handlePing(n, pkt) 929 return verifywait, nil 930 case pongPacket: 931 err := net.handleKnownPong(n, pkt) 932 return known, err 933 case pongTimeout: 934 return unknown, nil 935 default: 936 return verifywait, errInvalidEvent 937 } 938 }, 939 } 940 941 remoteverifywait = &nodeState{ 942 name: "remoteverifywait", 943 enter: func(net *Network, n *Node) { 944 net.timedEvent(respTimeout, n, pingTimeout) 945 }, 946 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 947 switch ev { 948 case pingPacket: 949 net.handlePing(n, pkt) 950 return remoteverifywait, nil 951 case pingTimeout: 952 return known, nil 953 default: 954 return remoteverifywait, errInvalidEvent 955 } 956 }, 957 } 958 959 known = &nodeState{ 960 name: "known", 961 canQuery: true, 962 enter: func(net *Network, n *Node) { 963 n.queryTimeouts = 0 964 n.startNextQuery(net) 965 // Insert into the table and start revalidation of the last node 966 // in the bucket if it is full. 967 last := net.tab.add(n) 968 if last != nil && last.state == known { 969 // TODO: do this asynchronously 970 net.transition(last, contested) 971 } 972 }, 973 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 974 switch ev { 975 case pingPacket: 976 net.handlePing(n, pkt) 977 return known, nil 978 case pongPacket: 979 err := net.handleKnownPong(n, pkt) 980 return known, err 981 default: 982 return net.handleQueryEvent(n, ev, pkt) 983 } 984 }, 985 } 986 987 contested = &nodeState{ 988 name: "contested", 989 canQuery: true, 990 enter: func(net *Network, n *Node) { 991 net.ping(n, n.addr()) 992 }, 993 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 994 switch ev { 995 case pongPacket: 996 // Node is still alive. 997 err := net.handleKnownPong(n, pkt) 998 return known, err 999 case pongTimeout: 1000 net.tab.deleteReplace(n) 1001 return unresponsive, nil 1002 case pingPacket: 1003 net.handlePing(n, pkt) 1004 return contested, nil 1005 default: 1006 return net.handleQueryEvent(n, ev, pkt) 1007 } 1008 }, 1009 } 1010 1011 unresponsive = &nodeState{ 1012 name: "unresponsive", 1013 canQuery: true, 1014 handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 1015 switch ev { 1016 case pingPacket: 1017 net.handlePing(n, pkt) 1018 return known, nil 1019 case pongPacket: 1020 err := net.handleKnownPong(n, pkt) 1021 return known, err 1022 default: 1023 return net.handleQueryEvent(n, ev, pkt) 1024 } 1025 }, 1026 } 1027 } 1028 1029 // handle processes packets sent by n and events related to n. 1030 func (net *Network) handle(n *Node, ev nodeEvent, pkt *ingressPacket) error { 1031 //fmt.Println("handle", n.addr().String(), n.state, ev) 1032 if pkt != nil { 1033 if err := net.checkPacket(n, ev, pkt); err != nil { 1034 //fmt.Println("check err:", err) 1035 return err 1036 } 1037 // Start the background expiration goroutine after the first 1038 // successful communication. Subsequent calls have no effect if it 1039 // is already running. We do this here instead of somewhere else 1040 // so that the search for seed nodes also considers older nodes 1041 // that would otherwise be removed by the expirer. 1042 if net.db != nil { 1043 net.db.ensureExpirer() 1044 } 1045 } 1046 if n.state == nil { 1047 n.state = unknown //??? 1048 } 1049 next, err := n.state.handle(net, n, ev, pkt) 1050 net.transition(n, next) 1051 //fmt.Println("new state:", n.state) 1052 return err 1053 } 1054 1055 func (net *Network) checkPacket(n *Node, ev nodeEvent, pkt *ingressPacket) error { 1056 // Replay prevention checks. 1057 switch ev { 1058 case pingPacket, findnodeHashPacket, neighborsPacket: 1059 // TODO: check date is > last date seen 1060 // TODO: check ping version 1061 case pongPacket: 1062 if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) { 1063 // fmt.Println("pong reply token mismatch") 1064 return fmt.Errorf("pong reply token mismatch") 1065 } 1066 n.pingEcho = nil 1067 } 1068 // Address validation. 1069 // TODO: Ideally we would do the following: 1070 // - reject all packets with wrong address except ping. 1071 // - for ping with new address, transition to verifywait but keep the 1072 // previous node (with old address) around. if the new one reaches known, 1073 // swap it out. 1074 return nil 1075 } 1076 1077 func (net *Network) transition(n *Node, next *nodeState) { 1078 if n.state != next { 1079 n.state = next 1080 if next.enter != nil { 1081 next.enter(net, n) 1082 } 1083 } 1084 1085 // TODO: persist/unpersist node 1086 } 1087 1088 func (net *Network) timedEvent(d time.Duration, n *Node, ev nodeEvent) { 1089 timeout := timeoutEvent{ev, n} 1090 net.timeoutTimers[timeout] = time.AfterFunc(d, func() { 1091 select { 1092 case net.timeout <- timeout: 1093 case <-net.closed: 1094 } 1095 }) 1096 } 1097 1098 func (net *Network) abortTimedEvent(n *Node, ev nodeEvent) { 1099 timer := net.timeoutTimers[timeoutEvent{ev, n}] 1100 if timer != nil { 1101 timer.Stop() 1102 delete(net.timeoutTimers, timeoutEvent{ev, n}) 1103 } 1104 } 1105 1106 func (net *Network) ping(n *Node, addr *net.UDPAddr) { 1107 //fmt.Println("ping", n.addr().String(), n.ID.String(), n.sha.Hex()) 1108 if n.pingEcho != nil || n.ID == net.tab.self.ID { 1109 //fmt.Println(" not sent") 1110 return 1111 } 1112 log.Trace("Pinging remote node", "node", n.ID) 1113 n.pingTopics = net.ticketStore.regTopicSet() 1114 n.pingEcho = net.conn.sendPing(n, addr, n.pingTopics) 1115 net.timedEvent(respTimeout, n, pongTimeout) 1116 } 1117 1118 func (net *Network) handlePing(n *Node, pkt *ingressPacket) { 1119 log.Trace("Handling remote ping", "node", n.ID) 1120 ping := pkt.data.(*ping) 1121 n.TCP = ping.From.TCP 1122 t := net.topictab.getTicket(n, ping.Topics) 1123 1124 pong := &pong{ 1125 To: makeEndpoint(n.addr(), n.TCP), // TODO: maybe use known TCP port from DB 1126 ReplyTok: pkt.hash, 1127 Expiration: uint64(time.Now().Add(expiration).Unix()), 1128 } 1129 ticketToPong(t, pong) 1130 net.conn.send(n, pongPacket, pong) 1131 } 1132 1133 func (net *Network) handleKnownPong(n *Node, pkt *ingressPacket) error { 1134 log.Trace("Handling known pong", "node", n.ID) 1135 net.abortTimedEvent(n, pongTimeout) 1136 now := mclock.Now() 1137 ticket, err := pongToTicket(now, n.pingTopics, n, pkt) 1138 if err == nil { 1139 // fmt.Printf("(%x) ticket: %+v\n", net.tab.self.ID[:8], pkt.data) 1140 net.ticketStore.addTicket(now, pkt.data.(*pong).ReplyTok, ticket) 1141 } else { 1142 log.Trace("Failed to convert pong to ticket", "err", err) 1143 } 1144 n.pingEcho = nil 1145 n.pingTopics = nil 1146 return err 1147 } 1148 1149 func (net *Network) handleQueryEvent(n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 1150 switch ev { 1151 case findnodePacket: 1152 target := crypto.Keccak256Hash(pkt.data.(*findnode).Target[:]) 1153 results := net.tab.closest(target, bucketSize).entries 1154 net.conn.sendNeighbours(n, results) 1155 return n.state, nil 1156 case neighborsPacket: 1157 err := net.handleNeighboursPacket(n, pkt) 1158 return n.state, err 1159 case neighboursTimeout: 1160 if n.pendingNeighbours != nil { 1161 n.pendingNeighbours.reply <- nil 1162 n.pendingNeighbours = nil 1163 } 1164 n.queryTimeouts++ 1165 if n.queryTimeouts > maxFindnodeFailures && n.state == known { 1166 return contested, errors.New("too many timeouts") 1167 } 1168 return n.state, nil 1169 1170 // v5 1171 1172 case findnodeHashPacket: 1173 results := net.tab.closest(pkt.data.(*findnodeHash).Target, bucketSize).entries 1174 net.conn.sendNeighbours(n, results) 1175 return n.state, nil 1176 case topicRegisterPacket: 1177 //fmt.Println("got topicRegisterPacket") 1178 regdata := pkt.data.(*topicRegister) 1179 pong, err := net.checkTopicRegister(regdata) 1180 if err != nil { 1181 //fmt.Println(err) 1182 return n.state, fmt.Errorf("bad waiting ticket: %v", err) 1183 } 1184 net.topictab.useTicket(n, pong.TicketSerial, regdata.Topics, int(regdata.Idx), pong.Expiration, pong.WaitPeriods) 1185 return n.state, nil 1186 case topicQueryPacket: 1187 // TODO: handle expiration 1188 topic := pkt.data.(*topicQuery).Topic 1189 results := net.topictab.getEntries(topic) 1190 if _, ok := net.ticketStore.tickets[topic]; ok { 1191 results = append(results, net.tab.self) // we're not registering in our own table but if we're advertising, return ourselves too 1192 } 1193 if len(results) > 10 { 1194 results = results[:10] 1195 } 1196 var hash common.Hash 1197 copy(hash[:], pkt.hash) 1198 net.conn.sendTopicNodes(n, hash, results) 1199 return n.state, nil 1200 case topicNodesPacket: 1201 p := pkt.data.(*topicNodes) 1202 if net.ticketStore.gotTopicNodes(n, p.Echo, p.Nodes) { 1203 n.queryTimeouts++ 1204 if n.queryTimeouts > maxFindnodeFailures && n.state == known { 1205 return contested, errors.New("too many timeouts") 1206 } 1207 } 1208 return n.state, nil 1209 1210 default: 1211 return n.state, errInvalidEvent 1212 } 1213 } 1214 1215 func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) { 1216 var pongpkt ingressPacket 1217 if err := decodePacket(data.Pong, &pongpkt); err != nil { 1218 return nil, err 1219 } 1220 if pongpkt.ev != pongPacket { 1221 return nil, errors.New("is not pong packet") 1222 } 1223 if pongpkt.remoteID != net.tab.self.ID { 1224 return nil, errors.New("not signed by us") 1225 } 1226 // check that we previously authorised all topics 1227 // that the other side is trying to register. 1228 if rlpHash(data.Topics) != pongpkt.data.(*pong).TopicHash { 1229 return nil, errors.New("topic hash mismatch") 1230 } 1231 if data.Idx >= uint(len(data.Topics)) { 1232 return nil, errors.New("topic index out of range") 1233 } 1234 return pongpkt.data.(*pong), nil 1235 } 1236 1237 func rlpHash(x interface{}) (h common.Hash) { 1238 hw := sha3.NewLegacyKeccak256() 1239 rlp.Encode(hw, x) 1240 hw.Sum(h[:0]) 1241 return h 1242 } 1243 1244 func (net *Network) handleNeighboursPacket(n *Node, pkt *ingressPacket) error { 1245 if n.pendingNeighbours == nil { 1246 return errNoQuery 1247 } 1248 net.abortTimedEvent(n, neighboursTimeout) 1249 1250 req := pkt.data.(*neighbors) 1251 nodes := make([]*Node, len(req.Nodes)) 1252 for i, rn := range req.Nodes { 1253 nn, err := net.internNodeFromNeighbours(pkt.remoteAddr, rn) 1254 if err != nil { 1255 log.Debug(fmt.Sprintf("invalid neighbour (%v) from %x@%v: %v", rn.IP, n.ID[:8], pkt.remoteAddr, err)) 1256 continue 1257 } 1258 nodes[i] = nn 1259 // Start validation of query results immediately. 1260 // This fills the table quickly. 1261 // TODO: generates way too many packets, maybe do it via queue. 1262 if nn.state == unknown { 1263 net.transition(nn, verifyinit) 1264 } 1265 } 1266 // TODO: don't ignore second packet 1267 n.pendingNeighbours.reply <- nodes 1268 n.pendingNeighbours = nil 1269 // Now that this query is done, start the next one. 1270 n.startNextQuery(net) 1271 return nil 1272 }