github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/p2p/discv5/net.go (about) 1 // Copyright 2016 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 discv5 18 19 import ( 20 "bytes" 21 "crypto/ecdsa" 22 "errors" 23 "fmt" 24 "net" 25 "time" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/common/mclock" 29 "github.com/ethereum/go-ethereum/crypto" 30 "github.com/ethereum/go-ethereum/crypto/sha3" 31 "github.com/ethereum/go-ethereum/log" 32 "github.com/ethereum/go-ethereum/p2p/nat" 33 "github.com/ethereum/go-ethereum/p2p/netutil" 34 "github.com/ethereum/go-ethereum/rlp" 35 ) 36 37 var ( 38 errInvalidEvent = errors.New("invalid in current state") 39 errNoQuery = errors.New("no pending query") 40 errWrongAddress = errors.New("unknown sender address") 41 ) 42 43 const ( 44 autoRefreshInterval = 1 * time.Hour 45 bucketRefreshInterval = 1 * time.Minute 46 seedCount = 30 47 seedMaxAge = 5 * 24 * time.Hour 48 lowPort = 1024 49 ) 50 51 const testTopic = "foo" 52 53 const ( 54 printDebugLogs = false 55 printTestImgLogs = false 56 ) 57 58 func debugLog(s string) { 59 if printDebugLogs { 60 fmt.Println(s) 61 } 62 } 63 64 // Network manages the table and all protocol interaction. 65 type Network struct { 66 db *nodeDB // database of known nodes 67 conn transport 68 netrestrict *netutil.Netlist 69 70 closed chan struct{} // closed when loop is done 71 closeReq chan struct{} // 'request to close' 72 refreshReq chan []*Node // lookups ask for refresh on this channel 73 refreshResp chan (<-chan struct{}) // ...and get the channel to block on from this one 74 read chan ingressPacket // ingress packets arrive here 75 timeout chan timeoutEvent 76 queryReq chan *findnodeQuery // lookups submit findnode queries on this channel 77 tableOpReq chan func() 78 tableOpResp chan struct{} 79 topicRegisterReq chan topicRegisterReq 80 topicSearchReq chan topicSearchReq 81 82 // State of the main loop. 83 tab *Table 84 topictab *topicTable 85 ticketStore *ticketStore 86 nursery []*Node 87 nodes map[NodeID]*Node // tracks active nodes with state != known 88 timeoutTimers map[timeoutEvent]*time.Timer 89 90 // Revalidation queues. 91 // Nodes put on these queues will be pinged eventually. 92 slowRevalidateQueue []*Node 93 fastRevalidateQueue []*Node 94 95 // Buffers for state transition. 96 sendBuf []*ingressPacket 97 } 98 99 // transport is implemented by the UDP transport. 100 // it is an interface so we can test without opening lots of UDP 101 // sockets and without generating a private key. 102 type transport interface { 103 sendPing(remote *Node, remoteAddr *net.UDPAddr, topics []Topic) (hash []byte) 104 sendNeighbours(remote *Node, nodes []*Node) 105 sendFindnodeHash(remote *Node, target common.Hash) 106 sendTopicRegister(remote *Node, topics []Topic, topicIdx int, pong []byte) 107 sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) 108 109 send(remote *Node, ptype nodeEvent, p interface{}) (hash []byte) 110 111 localAddr() *net.UDPAddr 112 Close() 113 } 114 115 type findnodeQuery struct { 116 remote *Node 117 target common.Hash 118 reply chan<- []*Node 119 nresults int // counter for received nodes 120 } 121 122 type topicRegisterReq struct { 123 add bool 124 topic Topic 125 } 126 127 type topicSearchReq struct { 128 topic Topic 129 found chan<- *Node 130 lookup chan<- bool 131 delay time.Duration 132 } 133 134 type topicSearchResult struct { 135 target lookupInfo 136 nodes []*Node 137 } 138 139 type timeoutEvent struct { 140 ev nodeEvent 141 node *Node 142 } 143 144 func newNetwork(conn transport, ourPubkey ecdsa.PublicKey, natm nat.Interface, dbPath string, netrestrict *netutil.Netlist) (*Network, error) { 145 ourID := PubkeyID(&ourPubkey) 146 147 var db *nodeDB 148 if dbPath != "<no database>" { 149 var err error 150 if db, err = newNodeDB(dbPath, Version, ourID); err != nil { 151 return nil, err 152 } 153 } 154 155 tab := newTable(ourID, conn.localAddr()) 156 net := &Network{ 157 db: db, 158 conn: conn, 159 netrestrict: netrestrict, 160 tab: tab, 161 topictab: newTopicTable(db, tab.self), 162 ticketStore: newTicketStore(), 163 refreshReq: make(chan []*Node), 164 refreshResp: make(chan (<-chan struct{})), 165 closed: make(chan struct{}), 166 closeReq: make(chan struct{}), 167 read: make(chan ingressPacket, 100), 168 timeout: make(chan timeoutEvent), 169 timeoutTimers: make(map[timeoutEvent]*time.Timer), 170 tableOpReq: make(chan func()), 171 tableOpResp: make(chan struct{}), 172 queryReq: make(chan *findnodeQuery), 173 topicRegisterReq: make(chan topicRegisterReq), 174 topicSearchReq: make(chan topicSearchReq), 175 nodes: make(map[NodeID]*Node), 176 } 177 go net.loop() 178 return net, nil 179 } 180 181 // Close terminates the network listener and flushes the node database. 182 func (net *Network) Close() { 183 net.conn.Close() 184 select { 185 case <-net.closed: 186 case net.closeReq <- struct{}{}: 187 <-net.closed 188 } 189 } 190 191 // Self returns the local node. 192 // The returned node should not be modified by the caller. 193 func (net *Network) Self() *Node { 194 return net.tab.self 195 } 196 197 // ReadRandomNodes fills the given slice with random nodes from the 198 // table. It will not write the same node more than once. The nodes in 199 // the slice are copies and can be modified by the caller. 200 func (net *Network) ReadRandomNodes(buf []*Node) (n int) { 201 net.reqTableOp(func() { n = net.tab.readRandomNodes(buf) }) 202 return n 203 } 204 205 // SetFallbackNodes sets the initial points of contact. These nodes 206 // are used to connect to the network if the table is empty and there 207 // are no known nodes in the database. 208 func (net *Network) SetFallbackNodes(nodes []*Node) error { 209 nursery := make([]*Node, 0, len(nodes)) 210 for _, n := range nodes { 211 if err := n.validateComplete(); err != nil { 212 return fmt.Errorf("bad bootstrap/fallback node %q (%v)", n, err) 213 } 214 // Recompute cpy.sha because the node might not have been 215 // created by NewNode or ParseNode. 216 cpy := *n 217 cpy.sha = crypto.Keccak256Hash(n.ID[:]) 218 nursery = append(nursery, &cpy) 219 } 220 net.reqRefresh(nursery) 221 return nil 222 } 223 224 // Resolve searches for a specific node with the given ID. 225 // It returns nil if the node could not be found. 226 func (net *Network) Resolve(targetID NodeID) *Node { 227 result := net.lookup(crypto.Keccak256Hash(targetID[:]), true) 228 for _, n := range result { 229 if n.ID == targetID { 230 return n 231 } 232 } 233 return nil 234 } 235 236 // Lookup performs a network search for nodes close 237 // to the given target. It approaches the target by querying 238 // nodes that are closer to it on each iteration. 239 // The given target does not need to be an actual node 240 // identifier. 241 // 242 // The local node may be included in the result. 243 func (net *Network) Lookup(targetID NodeID) []*Node { 244 return net.lookup(crypto.Keccak256Hash(targetID[:]), false) 245 } 246 247 func (net *Network) lookup(target common.Hash, stopOnMatch bool) []*Node { 248 var ( 249 asked = make(map[NodeID]bool) 250 seen = make(map[NodeID]bool) 251 reply = make(chan []*Node, alpha) 252 result = nodesByDistance{target: target} 253 pendingQueries = 0 254 ) 255 // Get initial answers from the local node. 256 result.push(net.tab.self, bucketSize) 257 for { 258 // Ask the α closest nodes that we haven't asked yet. 259 for i := 0; i < len(result.entries) && pendingQueries < alpha; i++ { 260 n := result.entries[i] 261 if !asked[n.ID] { 262 asked[n.ID] = true 263 pendingQueries++ 264 net.reqQueryFindnode(n, target, reply) 265 } 266 } 267 if pendingQueries == 0 { 268 // We have asked all closest nodes, stop the search. 269 break 270 } 271 // Wait for the next reply. 272 select { 273 case nodes := <-reply: 274 for _, n := range nodes { 275 if n != nil && !seen[n.ID] { 276 seen[n.ID] = true 277 result.push(n, bucketSize) 278 if stopOnMatch && n.sha == target { 279 return result.entries 280 } 281 } 282 } 283 pendingQueries-- 284 case <-time.After(respTimeout): 285 // forget all pending requests, start new ones 286 pendingQueries = 0 287 reply = make(chan []*Node, alpha) 288 } 289 } 290 return result.entries 291 } 292 293 func (net *Network) RegisterTopic(topic Topic, stop <-chan struct{}) { 294 select { 295 case net.topicRegisterReq <- topicRegisterReq{true, topic}: 296 case <-net.closed: 297 return 298 } 299 select { 300 case <-net.closed: 301 case <-stop: 302 select { 303 case net.topicRegisterReq <- topicRegisterReq{false, topic}: 304 case <-net.closed: 305 } 306 } 307 } 308 309 func (net *Network) SearchTopic(topic Topic, setPeriod <-chan time.Duration, found chan<- *Node, lookup chan<- bool) { 310 for { 311 select { 312 case <-net.closed: 313 return 314 case delay, ok := <-setPeriod: 315 select { 316 case net.topicSearchReq <- topicSearchReq{topic: topic, found: found, lookup: lookup, delay: delay}: 317 case <-net.closed: 318 return 319 } 320 if !ok { 321 return 322 } 323 } 324 } 325 } 326 327 func (net *Network) reqRefresh(nursery []*Node) <-chan struct{} { 328 select { 329 case net.refreshReq <- nursery: 330 return <-net.refreshResp 331 case <-net.closed: 332 return net.closed 333 } 334 } 335 336 func (net *Network) reqQueryFindnode(n *Node, target common.Hash, reply chan []*Node) bool { 337 q := &findnodeQuery{remote: n, target: target, reply: reply} 338 select { 339 case net.queryReq <- q: 340 return true 341 case <-net.closed: 342 return false 343 } 344 } 345 346 func (net *Network) reqReadPacket(pkt ingressPacket) { 347 select { 348 case net.read <- pkt: 349 case <-net.closed: 350 } 351 } 352 353 func (net *Network) reqTableOp(f func()) (called bool) { 354 select { 355 case net.tableOpReq <- f: 356 <-net.tableOpResp 357 return true 358 case <-net.closed: 359 return false 360 } 361 } 362 363 // TODO: external address handling. 364 365 type topicSearchInfo struct { 366 lookupChn chan<- bool 367 period time.Duration 368 } 369 370 const maxSearchCount = 5 371 372 func (net *Network) loop() { 373 var ( 374 refreshTimer = time.NewTicker(autoRefreshInterval) 375 bucketRefreshTimer = time.NewTimer(bucketRefreshInterval) 376 refreshDone chan struct{} // closed when the 'refresh' lookup has ended 377 ) 378 379 // Tracking the next ticket to register. 380 var ( 381 nextTicket *ticketRef 382 nextRegisterTimer *time.Timer 383 nextRegisterTime <-chan time.Time 384 ) 385 defer func() { 386 if nextRegisterTimer != nil { 387 nextRegisterTimer.Stop() 388 } 389 }() 390 resetNextTicket := func() { 391 t, timeout := net.ticketStore.nextFilteredTicket() 392 if t != nextTicket { 393 nextTicket = t 394 if nextRegisterTimer != nil { 395 nextRegisterTimer.Stop() 396 nextRegisterTime = nil 397 } 398 if t != nil { 399 nextRegisterTimer = time.NewTimer(timeout) 400 nextRegisterTime = nextRegisterTimer.C 401 } 402 } 403 } 404 405 // Tracking registration and search lookups. 406 var ( 407 topicRegisterLookupTarget lookupInfo 408 topicRegisterLookupDone chan []*Node 409 topicRegisterLookupTick = time.NewTimer(0) 410 searchReqWhenRefreshDone []topicSearchReq 411 searchInfo = make(map[Topic]topicSearchInfo) 412 activeSearchCount int 413 ) 414 topicSearchLookupDone := make(chan topicSearchResult, 100) 415 topicSearch := make(chan Topic, 100) 416 <-topicRegisterLookupTick.C 417 418 statsDump := time.NewTicker(10 * time.Second) 419 420 loop: 421 for { 422 resetNextTicket() 423 424 select { 425 case <-net.closeReq: 426 debugLog("<-net.closeReq") 427 break loop 428 429 // Ingress packet handling. 430 case pkt := <-net.read: 431 //fmt.Println("read", pkt.ev) 432 debugLog("<-net.read") 433 n := net.internNode(&pkt) 434 prestate := n.state 435 status := "ok" 436 if err := net.handle(n, pkt.ev, &pkt); err != nil { 437 status = err.Error() 438 } 439 log.Trace("", "msg", log.Lazy{Fn: func() string { 440 return fmt.Sprintf("<<< (%d) %v from %x@%v: %v -> %v (%v)", 441 net.tab.count, pkt.ev, pkt.remoteID[:8], pkt.remoteAddr, prestate, n.state, status) 442 }}) 443 // TODO: persist state if n.state goes >= known, delete if it goes <= known 444 445 // State transition timeouts. 446 case timeout := <-net.timeout: 447 debugLog("<-net.timeout") 448 if net.timeoutTimers[timeout] == nil { 449 // Stale timer (was aborted). 450 continue 451 } 452 delete(net.timeoutTimers, timeout) 453 prestate := timeout.node.state 454 status := "ok" 455 if err := net.handle(timeout.node, timeout.ev, nil); err != nil { 456 status = err.Error() 457 } 458 log.Trace("", "msg", log.Lazy{Fn: func() string { 459 return fmt.Sprintf("--- (%d) %v for %x@%v: %v -> %v (%v)", 460 net.tab.count, timeout.ev, timeout.node.ID[:8], timeout.node.addr(), prestate, timeout.node.state, status) 461 }}) 462 463 // Querying. 464 case q := <-net.queryReq: 465 debugLog("<-net.queryReq") 466 if !q.start(net) { 467 q.remote.deferQuery(q) 468 } 469 470 // Interacting with the table. 471 case f := <-net.tableOpReq: 472 debugLog("<-net.tableOpReq") 473 f() 474 net.tableOpResp <- struct{}{} 475 476 // Topic registration stuff. 477 case req := <-net.topicRegisterReq: 478 debugLog("<-net.topicRegisterReq") 479 if !req.add { 480 net.ticketStore.removeRegisterTopic(req.topic) 481 continue 482 } 483 net.ticketStore.addTopic(req.topic, true) 484 // If we're currently waiting idle (nothing to look up), give the ticket store a 485 // chance to start it sooner. This should speed up convergence of the radius 486 // determination for new topics. 487 // if topicRegisterLookupDone == nil { 488 if topicRegisterLookupTarget.target == (common.Hash{}) { 489 debugLog("topicRegisterLookupTarget == null") 490 if topicRegisterLookupTick.Stop() { 491 <-topicRegisterLookupTick.C 492 } 493 target, delay := net.ticketStore.nextRegisterLookup() 494 topicRegisterLookupTarget = target 495 topicRegisterLookupTick.Reset(delay) 496 } 497 498 case nodes := <-topicRegisterLookupDone: 499 debugLog("<-topicRegisterLookupDone") 500 net.ticketStore.registerLookupDone(topicRegisterLookupTarget, nodes, func(n *Node) []byte { 501 net.ping(n, n.addr()) 502 return n.pingEcho 503 }) 504 target, delay := net.ticketStore.nextRegisterLookup() 505 topicRegisterLookupTarget = target 506 topicRegisterLookupTick.Reset(delay) 507 topicRegisterLookupDone = nil 508 509 case <-topicRegisterLookupTick.C: 510 debugLog("<-topicRegisterLookupTick") 511 if (topicRegisterLookupTarget.target == common.Hash{}) { 512 target, delay := net.ticketStore.nextRegisterLookup() 513 topicRegisterLookupTarget = target 514 topicRegisterLookupTick.Reset(delay) 515 topicRegisterLookupDone = nil 516 } else { 517 topicRegisterLookupDone = make(chan []*Node) 518 target := topicRegisterLookupTarget.target 519 go func() { topicRegisterLookupDone <- net.lookup(target, false) }() 520 } 521 522 case <-nextRegisterTime: 523 debugLog("<-nextRegisterTime") 524 net.ticketStore.ticketRegistered(*nextTicket) 525 //fmt.Println("sendTopicRegister", nextTicket.t.node.addr().String(), nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) 526 net.conn.sendTopicRegister(nextTicket.t.node, nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) 527 528 case req := <-net.topicSearchReq: 529 if refreshDone == nil { 530 debugLog("<-net.topicSearchReq") 531 info, ok := searchInfo[req.topic] 532 if ok { 533 if req.delay == time.Duration(0) { 534 delete(searchInfo, req.topic) 535 net.ticketStore.removeSearchTopic(req.topic) 536 } else { 537 info.period = req.delay 538 searchInfo[req.topic] = info 539 } 540 continue 541 } 542 if req.delay != time.Duration(0) { 543 var info topicSearchInfo 544 info.period = req.delay 545 info.lookupChn = req.lookup 546 searchInfo[req.topic] = info 547 net.ticketStore.addSearchTopic(req.topic, req.found) 548 topicSearch <- req.topic 549 } 550 } else { 551 searchReqWhenRefreshDone = append(searchReqWhenRefreshDone, req) 552 } 553 554 case topic := <-topicSearch: 555 if activeSearchCount < maxSearchCount { 556 activeSearchCount++ 557 target := net.ticketStore.nextSearchLookup(topic) 558 go func() { 559 nodes := net.lookup(target.target, false) 560 topicSearchLookupDone <- topicSearchResult{target: target, nodes: nodes} 561 }() 562 } 563 period := searchInfo[topic].period 564 if period != time.Duration(0) { 565 go func() { 566 time.Sleep(period) 567 topicSearch <- topic 568 }() 569 } 570 571 case res := <-topicSearchLookupDone: 572 activeSearchCount-- 573 if lookupChn := searchInfo[res.target.topic].lookupChn; lookupChn != nil { 574 lookupChn <- net.ticketStore.radius[res.target.topic].converged 575 } 576 net.ticketStore.searchLookupDone(res.target, res.nodes, func(n *Node) []byte { 577 net.ping(n, n.addr()) 578 return n.pingEcho 579 }, func(n *Node, topic Topic) []byte { 580 if n.state == known { 581 return net.conn.send(n, topicQueryPacket, topicQuery{Topic: topic}) // TODO: set expiration 582 } else { 583 if n.state == unknown { 584 net.ping(n, n.addr()) 585 } 586 return nil 587 } 588 }) 589 590 case <-statsDump.C: 591 debugLog("<-statsDump.C") 592 /*r, ok := net.ticketStore.radius[testTopic] 593 if !ok { 594 fmt.Printf("(%x) no radius @ %v\n", net.tab.self.ID[:8], time.Now()) 595 } else { 596 topics := len(net.ticketStore.tickets) 597 tickets := len(net.ticketStore.nodes) 598 rad := r.radius / (maxRadius/10000+1) 599 fmt.Printf("(%x) topics:%d radius:%d tickets:%d @ %v\n", net.tab.self.ID[:8], topics, rad, tickets, time.Now()) 600 }*/ 601 602 tm := mclock.Now() 603 for topic, r := range net.ticketStore.radius { 604 if printTestImgLogs { 605 rad := r.radius / (maxRadius/1000000 + 1) 606 minrad := r.minRadius / (maxRadius/1000000 + 1) 607 fmt.Printf("*R %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], rad) 608 fmt.Printf("*MR %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], minrad) 609 } 610 } 611 for topic, t := range net.topictab.topics { 612 wp := t.wcl.nextWaitPeriod(tm) 613 if printTestImgLogs { 614 fmt.Printf("*W %d %v %016x %d\n", tm/1000000, topic, net.tab.self.sha[:8], wp/1000000) 615 } 616 } 617 618 // Periodic / lookup-initiated bucket refresh. 619 case <-refreshTimer.C: 620 debugLog("<-refreshTimer.C") 621 // TODO: ideally we would start the refresh timer after 622 // fallback nodes have been set for the first time. 623 if refreshDone == nil { 624 refreshDone = make(chan struct{}) 625 net.refresh(refreshDone) 626 } 627 case <-bucketRefreshTimer.C: 628 target := net.tab.chooseBucketRefreshTarget() 629 go func() { 630 net.lookup(target, false) 631 bucketRefreshTimer.Reset(bucketRefreshInterval) 632 }() 633 case newNursery := <-net.refreshReq: 634 debugLog("<-net.refreshReq") 635 if newNursery != nil { 636 net.nursery = newNursery 637 } 638 if refreshDone == nil { 639 refreshDone = make(chan struct{}) 640 net.refresh(refreshDone) 641 } 642 net.refreshResp <- refreshDone 643 case <-refreshDone: 644 debugLog("<-net.refreshDone") 645 refreshDone = nil 646 list := searchReqWhenRefreshDone 647 searchReqWhenRefreshDone = nil 648 go func() { 649 for _, req := range list { 650 net.topicSearchReq <- req 651 } 652 }() 653 } 654 } 655 debugLog("loop stopped") 656 657 log.Debug(fmt.Sprintf("shutting down")) 658 if net.conn != nil { 659 net.conn.Close() 660 } 661 if refreshDone != nil { 662 // TODO: wait for pending refresh. 663 //<-refreshResults 664 } 665 // Cancel all pending timeouts. 666 for _, timer := range net.timeoutTimers { 667 timer.Stop() 668 } 669 if net.db != nil { 670 net.db.close() 671 } 672 close(net.closed) 673 } 674 675 // Everything below runs on the Network.loop goroutine 676 // and can modify Node, Table and Network at any time without locking. 677 678 func (net *Network) refresh(done chan<- struct{}) { 679 var seeds []*Node 680 if net.db != nil { 681 seeds = net.db.querySeeds(seedCount, seedMaxAge) 682 } 683 if len(seeds) == 0 { 684 seeds = net.nursery 685 } 686 if len(seeds) == 0 { 687 log.Trace("no seed nodes found") 688 close(done) 689 return 690 } 691 for _, n := range seeds { 692 log.Debug("", "msg", log.Lazy{Fn: func() string { 693 var age string 694 if net.db != nil { 695 age = time.Since(net.db.lastPong(n.ID)).String() 696 } else { 697 age = "unknown" 698 } 699 return fmt.Sprintf("seed node (age %s): %v", age, n) 700 }}) 701 n = net.internNodeFromDB(n) 702 if n.state == unknown { 703 net.transition(n, verifyinit) 704 } 705 // Force-add the seed node so Lookup does something. 706 // It will be deleted again if verification fails. 707 net.tab.add(n) 708 } 709 // Start self lookup to fill up the buckets. 710 go func() { 711 net.Lookup(net.tab.self.ID) 712 close(done) 713 }() 714 } 715 716 // Node Interning. 717 718 func (net *Network) internNode(pkt *ingressPacket) *Node { 719 if n := net.nodes[pkt.remoteID]; n != nil { 720 n.IP = pkt.remoteAddr.IP 721 n.UDP = uint16(pkt.remoteAddr.Port) 722 n.TCP = uint16(pkt.remoteAddr.Port) 723 return n 724 } 725 n := NewNode(pkt.remoteID, pkt.remoteAddr.IP, uint16(pkt.remoteAddr.Port), uint16(pkt.remoteAddr.Port)) 726 n.state = unknown 727 net.nodes[pkt.remoteID] = n 728 return n 729 } 730 731 func (net *Network) internNodeFromDB(dbn *Node) *Node { 732 if n := net.nodes[dbn.ID]; n != nil { 733 return n 734 } 735 n := NewNode(dbn.ID, dbn.IP, dbn.UDP, dbn.TCP) 736 n.state = unknown 737 net.nodes[n.ID] = n 738 return n 739 } 740 741 func (net *Network) internNodeFromNeighbours(sender *net.UDPAddr, rn rpcNode) (n *Node, err error) { 742 if rn.ID == net.tab.self.ID { 743 return nil, errors.New("is self") 744 } 745 if rn.UDP <= lowPort { 746 return nil, errors.New("low port") 747 } 748 n = net.nodes[rn.ID] 749 if n == nil { 750 // We haven't seen this node before. 751 n, err = nodeFromRPC(sender, rn) 752 if net.netrestrict != nil && !net.netrestrict.Contains(n.IP) { 753 return n, errors.New("not contained in netrestrict whitelist") 754 } 755 if err == nil { 756 n.state = unknown 757 net.nodes[n.ID] = n 758 } 759 return n, err 760 } 761 if !n.IP.Equal(rn.IP) || n.UDP != rn.UDP || n.TCP != rn.TCP { 762 err = fmt.Errorf("metadata mismatch: got %v, want %v", rn, n) 763 } 764 return n, err 765 } 766 767 // nodeNetGuts is embedded in Node and contains fields. 768 type nodeNetGuts struct { 769 // This is a cached copy of sha3(ID) which is used for node 770 // distance calculations. This is part of Node in order to make it 771 // possible to write tests that need a node at a certain distance. 772 // In those tests, the content of sha will not actually correspond 773 // with ID. 774 sha common.Hash 775 776 // State machine fields. Access to these fields 777 // is restricted to the Network.loop goroutine. 778 state *nodeState 779 pingEcho []byte // hash of last ping sent by us 780 pingTopics []Topic // topic set sent by us in last ping 781 deferredQueries []*findnodeQuery // queries that can't be sent yet 782 pendingNeighbours *findnodeQuery // current query, waiting for reply 783 queryTimeouts int 784 } 785 786 func (n *nodeNetGuts) deferQuery(q *findnodeQuery) { 787 n.deferredQueries = append(n.deferredQueries, q) 788 } 789 790 func (n *nodeNetGuts) startNextQuery(net *Network) { 791 if len(n.deferredQueries) == 0 { 792 return 793 } 794 nextq := n.deferredQueries[0] 795 if nextq.start(net) { 796 n.deferredQueries = append(n.deferredQueries[:0], n.deferredQueries[1:]...) 797 } 798 } 799 800 func (q *findnodeQuery) start(net *Network) bool { 801 // Satisfy queries against the local node directly. 802 if q.remote == net.tab.self { 803 closest := net.tab.closest(crypto.Keccak256Hash(q.target[:]), bucketSize) 804 q.reply <- closest.entries 805 return true 806 } 807 if q.remote.state.canQuery && q.remote.pendingNeighbours == nil { 808 net.conn.sendFindnodeHash(q.remote, q.target) 809 net.timedEvent(respTimeout, q.remote, neighboursTimeout) 810 q.remote.pendingNeighbours = q 811 return true 812 } 813 // If the node is not known yet, it won't accept queries. 814 // Initiate the transition to known. 815 // The request will be sent later when the node reaches known state. 816 if q.remote.state == unknown { 817 net.transition(q.remote, verifyinit) 818 } 819 return false 820 } 821 822 // Node Events (the input to the state machine). 823 824 type nodeEvent uint 825 826 //go:generate stringer -type=nodeEvent 827 828 const ( 829 invalidEvent nodeEvent = iota // zero is reserved 830 831 // Packet type events. 832 // These correspond to packet types in the UDP protocol. 833 pingPacket 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 debugLog(fmt.Sprintf("ping(node = %x)", n.ID[:8])) 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 debugLog(fmt.Sprintf("handlePing(node = %x)", n.ID[:8])) 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 debugLog(fmt.Sprintf("handleKnownPong(node = %x)", n.ID[:8])) 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 debugLog(fmt.Sprintf(" error: %v", err)) 1143 } 1144 1145 n.pingEcho = nil 1146 n.pingTopics = nil 1147 return err 1148 } 1149 1150 func (net *Network) handleQueryEvent(n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) { 1151 switch ev { 1152 case findnodePacket: 1153 target := crypto.Keccak256Hash(pkt.data.(*findnode).Target[:]) 1154 results := net.tab.closest(target, bucketSize).entries 1155 net.conn.sendNeighbours(n, results) 1156 return n.state, nil 1157 case neighborsPacket: 1158 err := net.handleNeighboursPacket(n, pkt) 1159 return n.state, err 1160 case neighboursTimeout: 1161 if n.pendingNeighbours != nil { 1162 n.pendingNeighbours.reply <- nil 1163 n.pendingNeighbours = nil 1164 } 1165 n.queryTimeouts++ 1166 if n.queryTimeouts > maxFindnodeFailures && n.state == known { 1167 return contested, errors.New("too many timeouts") 1168 } 1169 return n.state, nil 1170 1171 // v5 1172 1173 case findnodeHashPacket: 1174 results := net.tab.closest(pkt.data.(*findnodeHash).Target, bucketSize).entries 1175 net.conn.sendNeighbours(n, results) 1176 return n.state, nil 1177 case topicRegisterPacket: 1178 //fmt.Println("got topicRegisterPacket") 1179 regdata := pkt.data.(*topicRegister) 1180 pong, err := net.checkTopicRegister(regdata) 1181 if err != nil { 1182 //fmt.Println(err) 1183 return n.state, fmt.Errorf("bad waiting ticket: %v", err) 1184 } 1185 net.topictab.useTicket(n, pong.TicketSerial, regdata.Topics, int(regdata.Idx), pong.Expiration, pong.WaitPeriods) 1186 return n.state, nil 1187 case topicQueryPacket: 1188 // TODO: handle expiration 1189 topic := pkt.data.(*topicQuery).Topic 1190 results := net.topictab.getEntries(topic) 1191 if _, ok := net.ticketStore.tickets[topic]; ok { 1192 results = append(results, net.tab.self) // we're not registering in our own table but if we're advertising, return ourselves too 1193 } 1194 if len(results) > 10 { 1195 results = results[:10] 1196 } 1197 var hash common.Hash 1198 copy(hash[:], pkt.hash) 1199 net.conn.sendTopicNodes(n, hash, results) 1200 return n.state, nil 1201 case topicNodesPacket: 1202 p := pkt.data.(*topicNodes) 1203 if net.ticketStore.gotTopicNodes(n, p.Echo, p.Nodes) { 1204 n.queryTimeouts++ 1205 if n.queryTimeouts > maxFindnodeFailures && n.state == known { 1206 return contested, errors.New("too many timeouts") 1207 } 1208 } 1209 return n.state, nil 1210 1211 default: 1212 return n.state, errInvalidEvent 1213 } 1214 } 1215 1216 func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) { 1217 var pongpkt ingressPacket 1218 if err := decodePacket(data.Pong, &pongpkt); err != nil { 1219 return nil, err 1220 } 1221 if pongpkt.ev != pongPacket { 1222 return nil, errors.New("is not pong packet") 1223 } 1224 if pongpkt.remoteID != net.tab.self.ID { 1225 return nil, errors.New("not signed by us") 1226 } 1227 // check that we previously authorised all topics 1228 // that the other side is trying to register. 1229 if rlpHash(data.Topics) != pongpkt.data.(*pong).TopicHash { 1230 return nil, errors.New("topic hash mismatch") 1231 } 1232 if data.Idx < 0 || int(data.Idx) >= len(data.Topics) { 1233 return nil, errors.New("topic index out of range") 1234 } 1235 return pongpkt.data.(*pong), nil 1236 } 1237 1238 func rlpHash(x interface{}) (h common.Hash) { 1239 hw := sha3.NewKeccak256() 1240 rlp.Encode(hw, x) 1241 hw.Sum(h[:0]) 1242 return h 1243 } 1244 1245 func (net *Network) handleNeighboursPacket(n *Node, pkt *ingressPacket) error { 1246 if n.pendingNeighbours == nil { 1247 return errNoQuery 1248 } 1249 net.abortTimedEvent(n, neighboursTimeout) 1250 1251 req := pkt.data.(*neighbors) 1252 nodes := make([]*Node, len(req.Nodes)) 1253 for i, rn := range req.Nodes { 1254 nn, err := net.internNodeFromNeighbours(pkt.remoteAddr, rn) 1255 if err != nil { 1256 log.Debug(fmt.Sprintf("invalid neighbour (%v) from %x@%v: %v", rn.IP, n.ID[:8], pkt.remoteAddr, err)) 1257 continue 1258 } 1259 nodes[i] = nn 1260 // Start validation of query results immediately. 1261 // This fills the table quickly. 1262 // TODO: generates way too many packets, maybe do it via queue. 1263 if nn.state == unknown { 1264 net.transition(nn, verifyinit) 1265 } 1266 } 1267 // TODO: don't ignore second packet 1268 n.pendingNeighbours.reply <- nodes 1269 n.pendingNeighbours = nil 1270 // Now that this query is done, start the next one. 1271 n.startNextQuery(net) 1272 return nil 1273 }