net.go 34 KB

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