net.go 35 KB

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