net.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. seedCount = 30
  41. seedMaxAge = 5 * 24 * time.Hour
  42. )
  43. const testTopic = "foo"
  44. const (
  45. printDebugLogs = false
  46. printTestImgLogs = false
  47. )
  48. func debugLog(s string) {
  49. if printDebugLogs {
  50. fmt.Println(s)
  51. }
  52. }
  53. // BootNodes are the enode URLs of the P2P bootstrap nodes for the experimental RLPx v5 "Topic Discovery" network
  54. // warning: local bootnodes for testing!!!
  55. var BootNodes = []*Node{
  56. //MustParseNode("enode://6f974ede10d07334e7e651c1501cb540d087dd3a6dea81432620895c913f281790b49459d72cb8011bfbbfbd24fad956356189c31b7181a96cd44ccfb68bfc71@127.0.0.1:30301"),
  57. MustParseNode("enode://0cc5f5ffb5d9098c8b8c62325f3797f56509bff942704687b6530992ac706e2cb946b90a34f1f19548cd3c7baccbcaea354531e5983c7d1bc0dee16ce4b6440b@40.118.3.223:30305"),
  58. }
  59. // Network manages the table and all protocol interaction.
  60. type Network struct {
  61. db *nodeDB // database of known nodes
  62. conn transport
  63. closed chan struct{} // closed when loop is done
  64. closeReq chan struct{} // 'request to close'
  65. refreshReq chan []*Node // lookups ask for refresh on this channel
  66. refreshResp chan (<-chan struct{}) // ...and get the channel to block on from this one
  67. read chan ingressPacket // ingress packets arrive here
  68. timeout chan timeoutEvent
  69. queryReq chan *findnodeQuery // lookups submit findnode queries on this channel
  70. tableOpReq chan func()
  71. tableOpResp chan struct{}
  72. topicRegisterReq chan topicRegisterReq
  73. topicSearchReq chan topicSearchReq
  74. bucketFillChn chan chan struct{}
  75. // State of the main loop.
  76. tab *Table
  77. topictab *topicTable
  78. ticketStore *ticketStore
  79. nursery []*Node
  80. nodes map[NodeID]*Node // tracks active nodes with state != known
  81. timeoutTimers map[timeoutEvent]*time.Timer
  82. // Revalidation queues.
  83. // Nodes put on these queues will be pinged eventually.
  84. slowRevalidateQueue []*Node
  85. fastRevalidateQueue []*Node
  86. // Buffers for state transition.
  87. sendBuf []*ingressPacket
  88. }
  89. // transport is implemented by the UDP transport.
  90. // it is an interface so we can test without opening lots of UDP
  91. // sockets and without generating a private key.
  92. type transport interface {
  93. sendPing(remote *Node, remoteAddr *net.UDPAddr, topics []Topic) (hash []byte)
  94. sendNeighbours(remote *Node, nodes []*Node)
  95. sendFindnodeHash(remote *Node, target common.Hash)
  96. sendTopicRegister(remote *Node, topics []Topic, topicIdx int, pong []byte)
  97. sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node)
  98. send(remote *Node, ptype nodeEvent, p interface{}) (hash []byte)
  99. localAddr() *net.UDPAddr
  100. Close()
  101. }
  102. type findnodeQuery struct {
  103. remote *Node
  104. target common.Hash
  105. reply chan<- []*Node
  106. nresults int // counter for received nodes
  107. }
  108. type topicRegisterReq struct {
  109. add bool
  110. topic Topic
  111. }
  112. type topicSearchReq struct {
  113. topic Topic
  114. found chan<- string
  115. }
  116. type timeoutEvent struct {
  117. ev nodeEvent
  118. node *Node
  119. }
  120. func newNetwork(conn transport, ourPubkey ecdsa.PublicKey, natm nat.Interface, dbPath string) (*Network, error) {
  121. ourID := PubkeyID(&ourPubkey)
  122. var db *nodeDB
  123. if dbPath != "<no database>" {
  124. var err error
  125. if db, err = newNodeDB(dbPath, Version, ourID); err != nil {
  126. return nil, err
  127. }
  128. }
  129. tab := newTable(ourID, conn.localAddr())
  130. net := &Network{
  131. db: db,
  132. conn: conn,
  133. tab: tab,
  134. topictab: newTopicTable(db, tab.self),
  135. ticketStore: newTicketStore(),
  136. refreshReq: make(chan []*Node),
  137. refreshResp: make(chan (<-chan struct{})),
  138. closed: make(chan struct{}),
  139. closeReq: make(chan struct{}),
  140. read: make(chan ingressPacket, 100),
  141. timeout: make(chan timeoutEvent),
  142. timeoutTimers: make(map[timeoutEvent]*time.Timer),
  143. tableOpReq: make(chan func()),
  144. tableOpResp: make(chan struct{}),
  145. queryReq: make(chan *findnodeQuery),
  146. topicRegisterReq: make(chan topicRegisterReq),
  147. topicSearchReq: make(chan topicSearchReq),
  148. bucketFillChn: make(chan chan struct{}, 1),
  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. refreshDone chan struct{} // closed when the 'refresh' lookup has ended
  319. )
  320. // Tracking the next ticket to register.
  321. var (
  322. nextTicket *ticketRef
  323. nextRegisterTimer *time.Timer
  324. nextRegisterTime <-chan time.Time
  325. )
  326. defer func() {
  327. if nextRegisterTimer != nil {
  328. nextRegisterTimer.Stop()
  329. }
  330. }()
  331. resetNextTicket := func() {
  332. t, timeout := net.ticketStore.nextFilteredTicket()
  333. if t != nextTicket {
  334. nextTicket = t
  335. if nextRegisterTimer != nil {
  336. nextRegisterTimer.Stop()
  337. nextRegisterTime = nil
  338. }
  339. if t != nil {
  340. nextRegisterTimer = time.NewTimer(timeout)
  341. nextRegisterTime = nextRegisterTimer.C
  342. }
  343. }
  344. }
  345. // Tracking registration and search lookups.
  346. var (
  347. topicRegisterLookupTarget lookupInfo
  348. topicRegisterLookupDone chan []*Node
  349. topicRegisterLookupTick = time.NewTimer(0)
  350. topicSearchLookupTarget lookupInfo
  351. )
  352. topicSearchLookupDone := make(chan []*Node, 1)
  353. <-topicRegisterLookupTick.C
  354. statsDump := time.NewTicker(10 * time.Second)
  355. loop:
  356. for {
  357. resetNextTicket()
  358. select {
  359. case <-net.closeReq:
  360. debugLog("<-net.closeReq")
  361. break loop
  362. // Ingress packet handling.
  363. case pkt := <-net.read:
  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. debugLog("<-net.topicSearchReq")
  454. if req.found == nil {
  455. net.ticketStore.removeSearchTopic(req.topic)
  456. continue
  457. }
  458. net.ticketStore.addSearchTopic(req.topic, req.found)
  459. if (topicSearchLookupTarget.target == common.Hash{}) {
  460. topicSearchLookupDone <- nil
  461. }
  462. case nodes := <-topicSearchLookupDone:
  463. debugLog("<-topicSearchLookupDone")
  464. net.ticketStore.searchLookupDone(topicSearchLookupTarget, nodes, func(n *Node) []byte {
  465. net.ping(n, n.addr())
  466. return n.pingEcho
  467. }, func(n *Node, topic Topic) []byte {
  468. return net.conn.send(n, topicQueryPacket, topicQuery{Topic: topic}) // TODO: set expiration
  469. })
  470. topicSearchLookupTarget = net.ticketStore.nextSearchLookup()
  471. target := topicSearchLookupTarget.target
  472. if (target != common.Hash{}) {
  473. go func() { topicSearchLookupDone <- net.lookup(target, false) }()
  474. }
  475. case <-statsDump.C:
  476. debugLog("<-statsDump.C")
  477. /*r, ok := net.ticketStore.radius[testTopic]
  478. if !ok {
  479. fmt.Printf("(%x) no radius @ %v\n", net.tab.self.ID[:8], time.Now())
  480. } else {
  481. topics := len(net.ticketStore.tickets)
  482. tickets := len(net.ticketStore.nodes)
  483. rad := r.radius / (maxRadius/10000+1)
  484. fmt.Printf("(%x) topics:%d radius:%d tickets:%d @ %v\n", net.tab.self.ID[:8], topics, rad, tickets, time.Now())
  485. }*/
  486. tm := mclock.Now()
  487. for topic, r := range net.ticketStore.radius {
  488. if printTestImgLogs {
  489. rad := r.radius / (maxRadius/1000000 + 1)
  490. minrad := r.minRadius / (maxRadius/1000000 + 1)
  491. fmt.Printf("*R %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], rad)
  492. fmt.Printf("*MR %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], minrad)
  493. }
  494. }
  495. for topic, t := range net.topictab.topics {
  496. wp := t.wcl.nextWaitPeriod(tm)
  497. if printTestImgLogs {
  498. fmt.Printf("*W %d %v %016x %d\n", tm/1000000, topic, net.tab.self.sha[:8], wp/1000000)
  499. }
  500. }
  501. // Periodic / lookup-initiated bucket refresh.
  502. case <-refreshTimer.C:
  503. debugLog("<-refreshTimer.C")
  504. // TODO: ideally we would start the refresh timer after
  505. // fallback nodes have been set for the first time.
  506. if refreshDone == nil {
  507. refreshDone = make(chan struct{})
  508. net.refresh(refreshDone)
  509. }
  510. case doneChn := <-net.bucketFillChn:
  511. debugLog("bucketFill")
  512. net.bucketFill(doneChn)
  513. case newNursery := <-net.refreshReq:
  514. debugLog("<-net.refreshReq")
  515. if newNursery != nil {
  516. net.nursery = newNursery
  517. }
  518. if refreshDone == nil {
  519. refreshDone = make(chan struct{})
  520. net.refresh(refreshDone)
  521. }
  522. net.refreshResp <- refreshDone
  523. case <-refreshDone:
  524. debugLog("<-net.refreshDone")
  525. refreshDone = nil
  526. }
  527. }
  528. debugLog("loop stopped")
  529. glog.V(logger.Debug).Infof("shutting down")
  530. if net.conn != nil {
  531. net.conn.Close()
  532. }
  533. if refreshDone != nil {
  534. // TODO: wait for pending refresh.
  535. //<-refreshResults
  536. }
  537. // Cancel all pending timeouts.
  538. for _, timer := range net.timeoutTimers {
  539. timer.Stop()
  540. }
  541. if net.db != nil {
  542. net.db.close()
  543. }
  544. close(net.closed)
  545. }
  546. // Everything below runs on the Network.loop goroutine
  547. // and can modify Node, Table and Network at any time without locking.
  548. func (net *Network) refresh(done chan<- struct{}) {
  549. var seeds []*Node
  550. if net.db != nil {
  551. seeds = net.db.querySeeds(seedCount, seedMaxAge)
  552. }
  553. if len(seeds) == 0 {
  554. seeds = net.nursery
  555. }
  556. if len(seeds) == 0 {
  557. glog.V(logger.Detail).Info("no seed nodes found")
  558. close(done)
  559. return
  560. }
  561. for _, n := range seeds {
  562. if glog.V(logger.Debug) {
  563. var age string
  564. if net.db != nil {
  565. age = time.Since(net.db.lastPong(n.ID)).String()
  566. } else {
  567. age = "unknown"
  568. }
  569. glog.Infof("seed node (age %s): %v", age, n)
  570. }
  571. n = net.internNodeFromDB(n)
  572. if n.state == unknown {
  573. net.transition(n, verifyinit)
  574. }
  575. // Force-add the seed node so Lookup does something.
  576. // It will be deleted again if verification fails.
  577. net.tab.add(n)
  578. }
  579. // Start self lookup to fill up the buckets.
  580. go func() {
  581. net.Lookup(net.tab.self.ID)
  582. close(done)
  583. }()
  584. }
  585. func (net *Network) bucketFill(done chan<- struct{}) {
  586. target := net.tab.chooseBucketFillTarget()
  587. go func() {
  588. net.lookup(target, false)
  589. close(done)
  590. }()
  591. }
  592. func (net *Network) BucketFill() {
  593. done := make(chan struct{})
  594. select {
  595. case net.bucketFillChn <- done:
  596. <-done
  597. case <-net.closed:
  598. close(done)
  599. }
  600. }
  601. // Node Interning.
  602. func (net *Network) internNode(pkt *ingressPacket) *Node {
  603. if n := net.nodes[pkt.remoteID]; n != nil {
  604. return n
  605. }
  606. n := NewNode(pkt.remoteID, pkt.remoteAddr.IP, uint16(pkt.remoteAddr.Port), uint16(pkt.remoteAddr.Port))
  607. n.state = unknown
  608. net.nodes[pkt.remoteID] = n
  609. return n
  610. }
  611. func (net *Network) internNodeFromDB(dbn *Node) *Node {
  612. if n := net.nodes[dbn.ID]; n != nil {
  613. return n
  614. }
  615. n := NewNode(dbn.ID, dbn.IP, dbn.UDP, dbn.TCP)
  616. n.state = unknown
  617. net.nodes[n.ID] = n
  618. return n
  619. }
  620. func (net *Network) internNodeFromNeighbours(rn rpcNode) (n *Node, err error) {
  621. if rn.ID == net.tab.self.ID {
  622. return nil, errors.New("is self")
  623. }
  624. n = net.nodes[rn.ID]
  625. if n == nil {
  626. // We haven't seen this node before.
  627. n, err = nodeFromRPC(rn)
  628. n.state = unknown
  629. if err == nil {
  630. net.nodes[n.ID] = n
  631. }
  632. return n, err
  633. }
  634. if !bytes.Equal(n.IP, rn.IP) || n.UDP != rn.UDP || n.TCP != rn.TCP {
  635. err = fmt.Errorf("metadata mismatch: got %v, want %v", rn, n)
  636. }
  637. return n, err
  638. }
  639. // nodeNetGuts is embedded in Node and contains fields.
  640. type nodeNetGuts struct {
  641. // This is a cached copy of sha3(ID) which is used for node
  642. // distance calculations. This is part of Node in order to make it
  643. // possible to write tests that need a node at a certain distance.
  644. // In those tests, the content of sha will not actually correspond
  645. // with ID.
  646. sha common.Hash
  647. // State machine fields. Access to these fields
  648. // is restricted to the Network.loop goroutine.
  649. state *nodeState
  650. pingEcho []byte // hash of last ping sent by us
  651. pingTopics []Topic // topic set sent by us in last ping
  652. deferredQueries []*findnodeQuery // queries that can't be sent yet
  653. pendingNeighbours *findnodeQuery // current query, waiting for reply
  654. queryTimeouts int
  655. }
  656. func (n *nodeNetGuts) deferQuery(q *findnodeQuery) {
  657. n.deferredQueries = append(n.deferredQueries, q)
  658. }
  659. func (n *nodeNetGuts) startNextQuery(net *Network) {
  660. if len(n.deferredQueries) == 0 {
  661. return
  662. }
  663. nextq := n.deferredQueries[0]
  664. if nextq.start(net) {
  665. n.deferredQueries = append(n.deferredQueries[:0], n.deferredQueries[1:]...)
  666. }
  667. }
  668. func (q *findnodeQuery) start(net *Network) bool {
  669. // Satisfy queries against the local node directly.
  670. if q.remote == net.tab.self {
  671. closest := net.tab.closest(crypto.Keccak256Hash(q.target[:]), bucketSize)
  672. q.reply <- closest.entries
  673. return true
  674. }
  675. if q.remote.state.canQuery && q.remote.pendingNeighbours == nil {
  676. net.conn.sendFindnodeHash(q.remote, q.target)
  677. net.timedEvent(respTimeout, q.remote, neighboursTimeout)
  678. q.remote.pendingNeighbours = q
  679. return true
  680. }
  681. // If the node is not known yet, it won't accept queries.
  682. // Initiate the transition to known.
  683. // The request will be sent later when the node reaches known state.
  684. if q.remote.state == unknown {
  685. net.transition(q.remote, verifyinit)
  686. }
  687. return false
  688. }
  689. // Node Events (the input to the state machine).
  690. type nodeEvent uint
  691. //go:generate stringer -type=nodeEvent
  692. const (
  693. invalidEvent nodeEvent = iota // zero is reserved
  694. // Packet type events.
  695. // These correspond to packet types in the UDP protocol.
  696. pingPacket
  697. pongPacket
  698. findnodePacket
  699. neighborsPacket
  700. findnodeHashPacket
  701. topicRegisterPacket
  702. topicQueryPacket
  703. topicNodesPacket
  704. // Non-packet events.
  705. // Event values in this category are allocated outside
  706. // the packet type range (packet types are encoded as a single byte).
  707. pongTimeout nodeEvent = iota + 256
  708. pingTimeout
  709. neighboursTimeout
  710. )
  711. // Node State Machine.
  712. type nodeState struct {
  713. name string
  714. handle func(*Network, *Node, nodeEvent, *ingressPacket) (next *nodeState, err error)
  715. enter func(*Network, *Node)
  716. canQuery bool
  717. }
  718. func (s *nodeState) String() string {
  719. return s.name
  720. }
  721. var (
  722. unknown *nodeState
  723. verifyinit *nodeState
  724. verifywait *nodeState
  725. remoteverifywait *nodeState
  726. known *nodeState
  727. contested *nodeState
  728. unresponsive *nodeState
  729. )
  730. func init() {
  731. unknown = &nodeState{
  732. name: "unknown",
  733. enter: func(net *Network, n *Node) {
  734. net.tab.delete(n)
  735. n.pingEcho = nil
  736. // Abort active queries.
  737. for _, q := range n.deferredQueries {
  738. q.reply <- nil
  739. }
  740. n.deferredQueries = nil
  741. if n.pendingNeighbours != nil {
  742. n.pendingNeighbours.reply <- nil
  743. n.pendingNeighbours = nil
  744. }
  745. n.queryTimeouts = 0
  746. },
  747. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  748. switch ev {
  749. case pingPacket:
  750. net.handlePing(n, pkt)
  751. net.ping(n, pkt.remoteAddr)
  752. return verifywait, nil
  753. default:
  754. return unknown, errInvalidEvent
  755. }
  756. },
  757. }
  758. verifyinit = &nodeState{
  759. name: "verifyinit",
  760. enter: func(net *Network, n *Node) {
  761. net.ping(n, n.addr())
  762. },
  763. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  764. switch ev {
  765. case pingPacket:
  766. net.handlePing(n, pkt)
  767. return verifywait, nil
  768. case pongPacket:
  769. err := net.handleKnownPong(n, pkt)
  770. return remoteverifywait, err
  771. case pongTimeout:
  772. return unknown, nil
  773. default:
  774. return verifyinit, errInvalidEvent
  775. }
  776. },
  777. }
  778. verifywait = &nodeState{
  779. name: "verifywait",
  780. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  781. switch ev {
  782. case pingPacket:
  783. net.handlePing(n, pkt)
  784. return verifywait, nil
  785. case pongPacket:
  786. err := net.handleKnownPong(n, pkt)
  787. return known, err
  788. case pongTimeout:
  789. return unknown, nil
  790. default:
  791. return verifywait, errInvalidEvent
  792. }
  793. },
  794. }
  795. remoteverifywait = &nodeState{
  796. name: "remoteverifywait",
  797. enter: func(net *Network, n *Node) {
  798. net.timedEvent(respTimeout, n, pingTimeout)
  799. },
  800. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  801. switch ev {
  802. case pingPacket:
  803. net.handlePing(n, pkt)
  804. return remoteverifywait, nil
  805. case pingTimeout:
  806. return known, nil
  807. default:
  808. return remoteverifywait, errInvalidEvent
  809. }
  810. },
  811. }
  812. known = &nodeState{
  813. name: "known",
  814. canQuery: true,
  815. enter: func(net *Network, n *Node) {
  816. n.queryTimeouts = 0
  817. n.startNextQuery(net)
  818. // Insert into the table and start revalidation of the last node
  819. // in the bucket if it is full.
  820. last := net.tab.add(n)
  821. if last != nil && last.state == known {
  822. // TODO: do this asynchronously
  823. net.transition(last, contested)
  824. }
  825. },
  826. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  827. switch ev {
  828. case pingPacket:
  829. net.handlePing(n, pkt)
  830. return known, nil
  831. case pongPacket:
  832. err := net.handleKnownPong(n, pkt)
  833. return known, err
  834. default:
  835. return net.handleQueryEvent(n, ev, pkt)
  836. }
  837. },
  838. }
  839. contested = &nodeState{
  840. name: "contested",
  841. canQuery: true,
  842. enter: func(net *Network, n *Node) {
  843. net.ping(n, n.addr())
  844. },
  845. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  846. switch ev {
  847. case pongPacket:
  848. // Node is still alive.
  849. err := net.handleKnownPong(n, pkt)
  850. return known, err
  851. case pongTimeout:
  852. net.tab.deleteReplace(n)
  853. return unresponsive, nil
  854. case pingPacket:
  855. net.handlePing(n, pkt)
  856. return contested, nil
  857. default:
  858. return net.handleQueryEvent(n, ev, pkt)
  859. }
  860. },
  861. }
  862. unresponsive = &nodeState{
  863. name: "unresponsive",
  864. canQuery: true,
  865. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  866. switch ev {
  867. case pingPacket:
  868. net.handlePing(n, pkt)
  869. return known, nil
  870. case pongPacket:
  871. err := net.handleKnownPong(n, pkt)
  872. return known, err
  873. default:
  874. return net.handleQueryEvent(n, ev, pkt)
  875. }
  876. },
  877. }
  878. }
  879. // handle processes packets sent by n and events related to n.
  880. func (net *Network) handle(n *Node, ev nodeEvent, pkt *ingressPacket) error {
  881. if pkt != nil {
  882. if err := net.checkPacket(n, ev, pkt); err != nil {
  883. return err
  884. }
  885. // Start the background expiration goroutine after the first
  886. // successful communication. Subsequent calls have no effect if it
  887. // is already running. We do this here instead of somewhere else
  888. // so that the search for seed nodes also considers older nodes
  889. // that would otherwise be removed by the expirer.
  890. if net.db != nil {
  891. net.db.ensureExpirer()
  892. }
  893. }
  894. if n.state == nil {
  895. n.state = unknown //???
  896. }
  897. next, err := n.state.handle(net, n, ev, pkt)
  898. net.transition(n, next)
  899. return err
  900. }
  901. func (net *Network) checkPacket(n *Node, ev nodeEvent, pkt *ingressPacket) error {
  902. // Replay prevention checks.
  903. switch ev {
  904. case pingPacket, findnodeHashPacket, neighborsPacket:
  905. // TODO: check date is > last date seen
  906. // TODO: check ping version
  907. case pongPacket:
  908. if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) {
  909. // fmt.Println("pong reply token mismatch")
  910. return fmt.Errorf("pong reply token mismatch")
  911. }
  912. n.pingEcho = nil
  913. }
  914. // Address validation.
  915. // TODO: Ideally we would do the following:
  916. // - reject all packets with wrong address except ping.
  917. // - for ping with new address, transition to verifywait but keep the
  918. // previous node (with old address) around. if the new one reaches known,
  919. // swap it out.
  920. return nil
  921. }
  922. func (net *Network) transition(n *Node, next *nodeState) {
  923. if n.state != next {
  924. n.state = next
  925. if next.enter != nil {
  926. next.enter(net, n)
  927. }
  928. }
  929. // TODO: persist/unpersist node
  930. }
  931. func (net *Network) timedEvent(d time.Duration, n *Node, ev nodeEvent) {
  932. timeout := timeoutEvent{ev, n}
  933. net.timeoutTimers[timeout] = time.AfterFunc(d, func() {
  934. select {
  935. case net.timeout <- timeout:
  936. case <-net.closed:
  937. }
  938. })
  939. }
  940. func (net *Network) abortTimedEvent(n *Node, ev nodeEvent) {
  941. timer := net.timeoutTimers[timeoutEvent{ev, n}]
  942. if timer != nil {
  943. timer.Stop()
  944. delete(net.timeoutTimers, timeoutEvent{ev, n})
  945. }
  946. }
  947. func (net *Network) ping(n *Node, addr *net.UDPAddr) {
  948. debugLog(fmt.Sprintf("ping(node = %x)", n.ID[:8]))
  949. n.pingTopics = net.ticketStore.regTopicSet()
  950. n.pingEcho = net.conn.sendPing(n, addr, n.pingTopics)
  951. net.timedEvent(respTimeout, n, pongTimeout)
  952. }
  953. func (net *Network) handlePing(n *Node, pkt *ingressPacket) {
  954. debugLog(fmt.Sprintf("handlePing(node = %x)", n.ID[:8]))
  955. ping := pkt.data.(*ping)
  956. n.TCP = ping.From.TCP
  957. t := net.topictab.getTicket(n, ping.Topics)
  958. pong := &pong{
  959. To: makeEndpoint(n.addr(), n.TCP), // TODO: maybe use known TCP port from DB
  960. ReplyTok: pkt.hash,
  961. Expiration: uint64(time.Now().Add(expiration).Unix()),
  962. }
  963. ticketToPong(t, pong)
  964. net.conn.send(n, pongPacket, pong)
  965. }
  966. func (net *Network) handleKnownPong(n *Node, pkt *ingressPacket) error {
  967. debugLog(fmt.Sprintf("handleKnownPong(node = %x)", n.ID[:8]))
  968. net.abortTimedEvent(n, pongTimeout)
  969. now := mclock.Now()
  970. ticket, err := pongToTicket(now, n.pingTopics, n, pkt)
  971. if err == nil {
  972. // fmt.Printf("(%x) ticket: %+v\n", net.tab.self.ID[:8], pkt.data)
  973. net.ticketStore.addTicket(now, pkt.data.(*pong).ReplyTok, ticket)
  974. } else {
  975. debugLog(fmt.Sprintf(" error: %v", err))
  976. }
  977. n.pingEcho = nil
  978. n.pingTopics = nil
  979. return err
  980. }
  981. func (net *Network) handleQueryEvent(n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  982. switch ev {
  983. case findnodePacket:
  984. target := crypto.Keccak256Hash(pkt.data.(*findnode).Target[:])
  985. results := net.tab.closest(target, bucketSize).entries
  986. net.conn.sendNeighbours(n, results)
  987. return n.state, nil
  988. case neighborsPacket:
  989. err := net.handleNeighboursPacket(n, pkt.data.(*neighbors))
  990. return n.state, err
  991. case neighboursTimeout:
  992. if n.pendingNeighbours != nil {
  993. n.pendingNeighbours.reply <- nil
  994. n.pendingNeighbours = nil
  995. }
  996. n.queryTimeouts++
  997. if n.queryTimeouts > maxFindnodeFailures && n.state == known {
  998. return contested, errors.New("too many timeouts")
  999. }
  1000. return n.state, nil
  1001. // v5
  1002. case findnodeHashPacket:
  1003. results := net.tab.closest(pkt.data.(*findnodeHash).Target, bucketSize).entries
  1004. net.conn.sendNeighbours(n, results)
  1005. return n.state, nil
  1006. case topicRegisterPacket:
  1007. //fmt.Println("got topicRegisterPacket")
  1008. regdata := pkt.data.(*topicRegister)
  1009. pong, err := net.checkTopicRegister(regdata)
  1010. if err != nil {
  1011. //fmt.Println(err)
  1012. return n.state, fmt.Errorf("bad waiting ticket: %v", err)
  1013. }
  1014. net.topictab.useTicket(n, pong.TicketSerial, regdata.Topics, int(regdata.Idx), pong.Expiration, pong.WaitPeriods)
  1015. return n.state, nil
  1016. case topicQueryPacket:
  1017. // TODO: handle expiration
  1018. topic := pkt.data.(*topicQuery).Topic
  1019. results := net.topictab.getEntries(topic)
  1020. if _, ok := net.ticketStore.tickets[topic]; ok {
  1021. results = append(results, net.tab.self) // we're not registering in our own table but if we're advertising, return ourselves too
  1022. }
  1023. if len(results) > 10 {
  1024. results = results[:10]
  1025. }
  1026. var hash common.Hash
  1027. copy(hash[:], pkt.hash)
  1028. net.conn.sendTopicNodes(n, hash, results)
  1029. return n.state, nil
  1030. case topicNodesPacket:
  1031. p := pkt.data.(*topicNodes)
  1032. if net.ticketStore.gotTopicNodes(n, p.Echo, p.Nodes) {
  1033. n.queryTimeouts++
  1034. if n.queryTimeouts > maxFindnodeFailures && n.state == known {
  1035. return contested, errors.New("too many timeouts")
  1036. }
  1037. }
  1038. return n.state, nil
  1039. default:
  1040. return n.state, errInvalidEvent
  1041. }
  1042. }
  1043. func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {
  1044. var pongpkt ingressPacket
  1045. if err := decodePacket(data.Pong, &pongpkt); err != nil {
  1046. return nil, err
  1047. }
  1048. if pongpkt.ev != pongPacket {
  1049. return nil, errors.New("is not pong packet")
  1050. }
  1051. if pongpkt.remoteID != net.tab.self.ID {
  1052. return nil, errors.New("not signed by us")
  1053. }
  1054. // check that we previously authorised all topics
  1055. // that the other side is trying to register.
  1056. if rlpHash(data.Topics) != pongpkt.data.(*pong).TopicHash {
  1057. return nil, errors.New("topic hash mismatch")
  1058. }
  1059. if data.Idx < 0 || int(data.Idx) >= len(data.Topics) {
  1060. return nil, errors.New("topic index out of range")
  1061. }
  1062. return pongpkt.data.(*pong), nil
  1063. }
  1064. func rlpHash(x interface{}) (h common.Hash) {
  1065. hw := sha3.NewKeccak256()
  1066. rlp.Encode(hw, x)
  1067. hw.Sum(h[:0])
  1068. return h
  1069. }
  1070. func (net *Network) handleNeighboursPacket(n *Node, req *neighbors) error {
  1071. if n.pendingNeighbours == nil {
  1072. return errNoQuery
  1073. }
  1074. net.abortTimedEvent(n, neighboursTimeout)
  1075. nodes := make([]*Node, len(req.Nodes))
  1076. for i, rn := range req.Nodes {
  1077. nn, err := net.internNodeFromNeighbours(rn)
  1078. if err != nil {
  1079. glog.V(logger.Debug).Infof("invalid neighbour from %x: %v", n.ID[:8], err)
  1080. continue
  1081. }
  1082. nodes[i] = nn
  1083. // Start validation of query results immediately.
  1084. // This fills the table quickly.
  1085. // TODO: generates way too many packets, maybe do it via queue.
  1086. if nn.state == unknown {
  1087. net.transition(nn, verifyinit)
  1088. }
  1089. }
  1090. // TODO: don't ignore second packet
  1091. n.pendingNeighbours.reply <- nodes
  1092. n.pendingNeighbours = nil
  1093. // Now that this query is done, start the next one.
  1094. n.startNextQuery(net)
  1095. return nil
  1096. }