net.go 35 KB

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