net.go 34 KB

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