v4_udp.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. // Copyright 2019 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 discover
  17. import (
  18. "bytes"
  19. "container/list"
  20. "crypto/ecdsa"
  21. crand "crypto/rand"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net"
  26. "sync"
  27. "time"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/p2p/enode"
  31. "github.com/ethereum/go-ethereum/p2p/enr"
  32. "github.com/ethereum/go-ethereum/p2p/netutil"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. // Errors
  36. var (
  37. errPacketTooSmall = errors.New("too small")
  38. errBadHash = errors.New("bad hash")
  39. errExpired = errors.New("expired")
  40. errUnsolicitedReply = errors.New("unsolicited reply")
  41. errUnknownNode = errors.New("unknown node")
  42. errTimeout = errors.New("RPC timeout")
  43. errClockWarp = errors.New("reply deadline too far in the future")
  44. errClosed = errors.New("socket closed")
  45. )
  46. const (
  47. respTimeout = 500 * time.Millisecond
  48. expiration = 20 * time.Second
  49. bondExpiration = 24 * time.Hour
  50. maxFindnodeFailures = 5 // nodes exceeding this limit are dropped
  51. ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
  52. ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
  53. driftThreshold = 10 * time.Second // Allowed clock drift before warning user
  54. // Discovery packets are defined to be no larger than 1280 bytes.
  55. // Packets larger than this size will be cut at the end and treated
  56. // as invalid because their hash won't match.
  57. maxPacketSize = 1280
  58. )
  59. // RPC packet types
  60. const (
  61. p_pingV4 = iota + 1 // zero is 'reserved'
  62. p_pongV4
  63. p_findnodeV4
  64. p_neighborsV4
  65. p_enrRequestV4
  66. p_enrResponseV4
  67. )
  68. // RPC request structures
  69. type (
  70. pingV4 struct {
  71. senderKey *ecdsa.PublicKey // filled in by preverify
  72. Version uint
  73. From, To rpcEndpoint
  74. Expiration uint64
  75. // Ignore additional fields (for forward compatibility).
  76. Rest []rlp.RawValue `rlp:"tail"`
  77. }
  78. // pongV4 is the reply to pingV4.
  79. pongV4 struct {
  80. // This field should mirror the UDP envelope address
  81. // of the ping packet, which provides a way to discover the
  82. // the external address (after NAT).
  83. To rpcEndpoint
  84. ReplyTok []byte // This contains the hash of the ping packet.
  85. Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
  86. // Ignore additional fields (for forward compatibility).
  87. Rest []rlp.RawValue `rlp:"tail"`
  88. }
  89. // findnodeV4 is a query for nodes close to the given target.
  90. findnodeV4 struct {
  91. Target encPubkey
  92. Expiration uint64
  93. // Ignore additional fields (for forward compatibility).
  94. Rest []rlp.RawValue `rlp:"tail"`
  95. }
  96. // neighborsV4 is the reply to findnodeV4.
  97. neighborsV4 struct {
  98. Nodes []rpcNode
  99. Expiration uint64
  100. // Ignore additional fields (for forward compatibility).
  101. Rest []rlp.RawValue `rlp:"tail"`
  102. }
  103. // enrRequestV4 queries for the remote node's record.
  104. enrRequestV4 struct {
  105. Expiration uint64
  106. // Ignore additional fields (for forward compatibility).
  107. Rest []rlp.RawValue `rlp:"tail"`
  108. }
  109. // enrResponseV4 is the reply to enrRequestV4.
  110. enrResponseV4 struct {
  111. ReplyTok []byte // Hash of the enrRequest packet.
  112. Record enr.Record
  113. // Ignore additional fields (for forward compatibility).
  114. Rest []rlp.RawValue `rlp:"tail"`
  115. }
  116. rpcNode struct {
  117. IP net.IP // len 4 for IPv4 or 16 for IPv6
  118. UDP uint16 // for discovery protocol
  119. TCP uint16 // for RLPx protocol
  120. ID encPubkey
  121. }
  122. rpcEndpoint struct {
  123. IP net.IP // len 4 for IPv4 or 16 for IPv6
  124. UDP uint16 // for discovery protocol
  125. TCP uint16 // for RLPx protocol
  126. }
  127. )
  128. // packetV4 is implemented by all v4 protocol messages.
  129. type packetV4 interface {
  130. // preverify checks whether the packet is valid and should be handled at all.
  131. preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error
  132. // handle handles the packet.
  133. handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte)
  134. // packet name and type for logging purposes.
  135. name() string
  136. kind() byte
  137. }
  138. func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
  139. ip := net.IP{}
  140. if ip4 := addr.IP.To4(); ip4 != nil {
  141. ip = ip4
  142. } else if ip6 := addr.IP.To16(); ip6 != nil {
  143. ip = ip6
  144. }
  145. return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
  146. }
  147. func (t *UDPv4) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*node, error) {
  148. if rn.UDP <= 1024 {
  149. return nil, errors.New("low port")
  150. }
  151. if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
  152. return nil, err
  153. }
  154. if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
  155. return nil, errors.New("not contained in netrestrict whitelist")
  156. }
  157. key, err := decodePubkey(rn.ID)
  158. if err != nil {
  159. return nil, err
  160. }
  161. n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
  162. err = n.ValidateComplete()
  163. return n, err
  164. }
  165. func nodeToRPC(n *node) rpcNode {
  166. var key ecdsa.PublicKey
  167. var ekey encPubkey
  168. if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
  169. ekey = encodePubkey(&key)
  170. }
  171. return rpcNode{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
  172. }
  173. // UDPv4 implements the v4 wire protocol.
  174. type UDPv4 struct {
  175. conn UDPConn
  176. log log.Logger
  177. netrestrict *netutil.Netlist
  178. priv *ecdsa.PrivateKey
  179. localNode *enode.LocalNode
  180. db *enode.DB
  181. tab *Table
  182. closeOnce sync.Once
  183. wg sync.WaitGroup
  184. addReplyMatcher chan *replyMatcher
  185. gotreply chan reply
  186. closing chan struct{}
  187. }
  188. // replyMatcher represents a pending reply.
  189. //
  190. // Some implementations of the protocol wish to send more than one
  191. // reply packet to findnode. In general, any neighbors packet cannot
  192. // be matched up with a specific findnode packet.
  193. //
  194. // Our implementation handles this by storing a callback function for
  195. // each pending reply. Incoming packets from a node are dispatched
  196. // to all callback functions for that node.
  197. type replyMatcher struct {
  198. // these fields must match in the reply.
  199. from enode.ID
  200. ip net.IP
  201. ptype byte
  202. // time when the request must complete
  203. deadline time.Time
  204. // callback is called when a matching reply arrives. If it returns matched == true, the
  205. // reply was acceptable. The second return value indicates whether the callback should
  206. // be removed from the pending reply queue. If it returns false, the reply is considered
  207. // incomplete and the callback will be invoked again for the next matching reply.
  208. callback replyMatchFunc
  209. // errc receives nil when the callback indicates completion or an
  210. // error if no further reply is received within the timeout.
  211. errc chan error
  212. // reply contains the most recent reply. This field is safe for reading after errc has
  213. // received a value.
  214. reply packetV4
  215. }
  216. type replyMatchFunc func(interface{}) (matched bool, requestDone bool)
  217. // reply is a reply packet from a certain node.
  218. type reply struct {
  219. from enode.ID
  220. ip net.IP
  221. data packetV4
  222. // loop indicates whether there was
  223. // a matching request by sending on this channel.
  224. matched chan<- bool
  225. }
  226. func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
  227. t := &UDPv4{
  228. conn: c,
  229. priv: cfg.PrivateKey,
  230. netrestrict: cfg.NetRestrict,
  231. localNode: ln,
  232. db: ln.Database(),
  233. closing: make(chan struct{}),
  234. gotreply: make(chan reply),
  235. addReplyMatcher: make(chan *replyMatcher),
  236. log: cfg.Log,
  237. }
  238. if t.log == nil {
  239. t.log = log.Root()
  240. }
  241. tab, err := newTable(t, ln.Database(), cfg.Bootnodes, t.log)
  242. if err != nil {
  243. return nil, err
  244. }
  245. t.tab = tab
  246. go tab.loop()
  247. t.wg.Add(2)
  248. go t.loop()
  249. go t.readLoop(cfg.Unhandled)
  250. return t, nil
  251. }
  252. // Self returns the local node.
  253. func (t *UDPv4) Self() *enode.Node {
  254. return t.localNode.Node()
  255. }
  256. // Close shuts down the socket and aborts any running queries.
  257. func (t *UDPv4) Close() {
  258. t.closeOnce.Do(func() {
  259. close(t.closing)
  260. t.conn.Close()
  261. t.wg.Wait()
  262. t.tab.close()
  263. })
  264. }
  265. // ReadRandomNodes reads random nodes from the local table.
  266. func (t *UDPv4) ReadRandomNodes(buf []*enode.Node) int {
  267. return t.tab.ReadRandomNodes(buf)
  268. }
  269. // LookupRandom finds random nodes in the network.
  270. func (t *UDPv4) LookupRandom() []*enode.Node {
  271. if t.tab.len() == 0 {
  272. // All nodes were dropped, refresh. The very first query will hit this
  273. // case and run the bootstrapping logic.
  274. <-t.tab.refresh()
  275. }
  276. return t.lookupRandom()
  277. }
  278. func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
  279. if t.tab.len() == 0 {
  280. // All nodes were dropped, refresh. The very first query will hit this
  281. // case and run the bootstrapping logic.
  282. <-t.tab.refresh()
  283. }
  284. return unwrapNodes(t.lookup(encodePubkey(key)))
  285. }
  286. func (t *UDPv4) lookupRandom() []*enode.Node {
  287. var target encPubkey
  288. crand.Read(target[:])
  289. return unwrapNodes(t.lookup(target))
  290. }
  291. func (t *UDPv4) lookupSelf() []*enode.Node {
  292. return unwrapNodes(t.lookup(encodePubkey(&t.priv.PublicKey)))
  293. }
  294. // lookup performs a network search for nodes close to the given target. It approaches the
  295. // target by querying nodes that are closer to it on each iteration. The given target does
  296. // not need to be an actual node identifier.
  297. func (t *UDPv4) lookup(targetKey encPubkey) []*node {
  298. var (
  299. target = enode.ID(crypto.Keccak256Hash(targetKey[:]))
  300. asked = make(map[enode.ID]bool)
  301. seen = make(map[enode.ID]bool)
  302. reply = make(chan []*node, alpha)
  303. pendingQueries = 0
  304. result *nodesByDistance
  305. )
  306. // Don't query further if we hit ourself.
  307. // Unlikely to happen often in practice.
  308. asked[t.Self().ID()] = true
  309. // Generate the initial result set.
  310. t.tab.mutex.Lock()
  311. result = t.tab.closest(target, bucketSize, false)
  312. t.tab.mutex.Unlock()
  313. for {
  314. // ask the alpha closest nodes that we haven't asked yet
  315. for i := 0; i < len(result.entries) && pendingQueries < alpha; i++ {
  316. n := result.entries[i]
  317. if !asked[n.ID()] {
  318. asked[n.ID()] = true
  319. pendingQueries++
  320. go t.lookupWorker(n, targetKey, reply)
  321. }
  322. }
  323. if pendingQueries == 0 {
  324. // we have asked all closest nodes, stop the search
  325. break
  326. }
  327. select {
  328. case nodes := <-reply:
  329. for _, n := range nodes {
  330. if n != nil && !seen[n.ID()] {
  331. seen[n.ID()] = true
  332. result.push(n, bucketSize)
  333. }
  334. }
  335. case <-t.tab.closeReq:
  336. return nil // shutdown, no need to continue.
  337. }
  338. pendingQueries--
  339. }
  340. return result.entries
  341. }
  342. func (t *UDPv4) lookupWorker(n *node, targetKey encPubkey, reply chan<- []*node) {
  343. fails := t.db.FindFails(n.ID(), n.IP())
  344. r, err := t.findnode(n.ID(), n.addr(), targetKey)
  345. if err == errClosed {
  346. // Avoid recording failures on shutdown.
  347. reply <- nil
  348. return
  349. } else if len(r) == 0 {
  350. fails++
  351. t.db.UpdateFindFails(n.ID(), n.IP(), fails)
  352. t.log.Trace("Findnode failed", "id", n.ID(), "failcount", fails, "err", err)
  353. if fails >= maxFindnodeFailures {
  354. t.log.Trace("Too many findnode failures, dropping", "id", n.ID(), "failcount", fails)
  355. t.tab.delete(n)
  356. }
  357. } else if fails > 0 {
  358. // Reset failure counter because it counts _consecutive_ failures.
  359. t.db.UpdateFindFails(n.ID(), n.IP(), 0)
  360. }
  361. // Grab as many nodes as possible. Some of them might not be alive anymore, but we'll
  362. // just remove those again during revalidation.
  363. for _, n := range r {
  364. t.tab.addSeenNode(n)
  365. }
  366. reply <- r
  367. }
  368. // Resolve searches for a specific node with the given ID and tries to get the most recent
  369. // version of the node record for it. It returns n if the node could not be resolved.
  370. func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
  371. // Try asking directly. This works if the node is still responding on the endpoint we have.
  372. if rn, err := t.RequestENR(n); err == nil {
  373. return rn
  374. }
  375. // Check table for the ID, we might have a newer version there.
  376. if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
  377. n = intable
  378. if rn, err := t.RequestENR(n); err == nil {
  379. return rn
  380. }
  381. }
  382. // Otherwise perform a network lookup.
  383. var key enode.Secp256k1
  384. if n.Load(&key) != nil {
  385. return n // no secp256k1 key
  386. }
  387. result := t.LookupPubkey((*ecdsa.PublicKey)(&key))
  388. for _, rn := range result {
  389. if rn.ID() == n.ID() {
  390. if rn, err := t.RequestENR(rn); err == nil {
  391. return rn
  392. }
  393. }
  394. }
  395. return n
  396. }
  397. func (t *UDPv4) ourEndpoint() rpcEndpoint {
  398. n := t.Self()
  399. a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  400. return makeEndpoint(a, uint16(n.TCP()))
  401. }
  402. // Ping sends a ping message to the given node.
  403. func (t *UDPv4) Ping(n *enode.Node) error {
  404. _, err := t.ping(n)
  405. return err
  406. }
  407. // ping sends a ping message to the given node and waits for a reply.
  408. func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
  409. rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
  410. if err = <-rm.errc; err == nil {
  411. seq = seqFromTail(rm.reply.(*pongV4).Rest)
  412. }
  413. return seq, err
  414. }
  415. // sendPing sends a ping message to the given node and invokes the callback
  416. // when the reply arrives.
  417. func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
  418. req := t.makePing(toaddr)
  419. packet, hash, err := t.encode(t.priv, req)
  420. if err != nil {
  421. errc := make(chan error, 1)
  422. errc <- err
  423. return &replyMatcher{errc: errc}
  424. }
  425. // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
  426. // reference the ping we're about to send.
  427. rm := t.pending(toid, toaddr.IP, p_pongV4, func(p interface{}) (matched bool, requestDone bool) {
  428. matched = bytes.Equal(p.(*pongV4).ReplyTok, hash)
  429. if matched && callback != nil {
  430. callback()
  431. }
  432. return matched, matched
  433. })
  434. // Send the packet.
  435. t.localNode.UDPContact(toaddr)
  436. t.write(toaddr, toid, req.name(), packet)
  437. return rm
  438. }
  439. func (t *UDPv4) makePing(toaddr *net.UDPAddr) *pingV4 {
  440. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  441. return &pingV4{
  442. Version: 4,
  443. From: t.ourEndpoint(),
  444. To: makeEndpoint(toaddr, 0),
  445. Expiration: uint64(time.Now().Add(expiration).Unix()),
  446. Rest: []rlp.RawValue{seq},
  447. }
  448. }
  449. // findnode sends a findnode request to the given node and waits until
  450. // the node has sent up to k neighbors.
  451. func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
  452. t.ensureBond(toid, toaddr)
  453. // Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
  454. // active until enough nodes have been received.
  455. nodes := make([]*node, 0, bucketSize)
  456. nreceived := 0
  457. rm := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) {
  458. reply := r.(*neighborsV4)
  459. for _, rn := range reply.Nodes {
  460. nreceived++
  461. n, err := t.nodeFromRPC(toaddr, rn)
  462. if err != nil {
  463. t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
  464. continue
  465. }
  466. nodes = append(nodes, n)
  467. }
  468. return true, nreceived >= bucketSize
  469. })
  470. t.send(toaddr, toid, &findnodeV4{
  471. Target: target,
  472. Expiration: uint64(time.Now().Add(expiration).Unix()),
  473. })
  474. return nodes, <-rm.errc
  475. }
  476. // RequestENR sends enrRequest to the given node and waits for a response.
  477. func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
  478. addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  479. t.ensureBond(n.ID(), addr)
  480. req := &enrRequestV4{
  481. Expiration: uint64(time.Now().Add(expiration).Unix()),
  482. }
  483. packet, hash, err := t.encode(t.priv, req)
  484. if err != nil {
  485. return nil, err
  486. }
  487. // Add a matcher for the reply to the pending reply queue. Responses are matched if
  488. // they reference the request we're about to send.
  489. rm := t.pending(n.ID(), addr.IP, p_enrResponseV4, func(r interface{}) (matched bool, requestDone bool) {
  490. matched = bytes.Equal(r.(*enrResponseV4).ReplyTok, hash)
  491. return matched, matched
  492. })
  493. // Send the packet and wait for the reply.
  494. t.write(addr, n.ID(), req.name(), packet)
  495. if err := <-rm.errc; err != nil {
  496. return nil, err
  497. }
  498. // Verify the response record.
  499. respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*enrResponseV4).Record)
  500. if err != nil {
  501. return nil, err
  502. }
  503. if respN.ID() != n.ID() {
  504. return nil, fmt.Errorf("invalid ID in response record")
  505. }
  506. if respN.Seq() < n.Seq() {
  507. return n, nil // response record is older
  508. }
  509. if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
  510. return nil, fmt.Errorf("invalid IP in response record: %v", err)
  511. }
  512. return respN, nil
  513. }
  514. // pending adds a reply matcher to the pending reply queue.
  515. // see the documentation of type replyMatcher for a detailed explanation.
  516. func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
  517. ch := make(chan error, 1)
  518. p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
  519. select {
  520. case t.addReplyMatcher <- p:
  521. // loop will handle it
  522. case <-t.closing:
  523. ch <- errClosed
  524. }
  525. return p
  526. }
  527. // handleReply dispatches a reply packet, invoking reply matchers. It returns
  528. // whether any matcher considered the packet acceptable.
  529. func (t *UDPv4) handleReply(from enode.ID, fromIP net.IP, req packetV4) bool {
  530. matched := make(chan bool, 1)
  531. select {
  532. case t.gotreply <- reply{from, fromIP, req, matched}:
  533. // loop will handle it
  534. return <-matched
  535. case <-t.closing:
  536. return false
  537. }
  538. }
  539. // loop runs in its own goroutine. it keeps track of
  540. // the refresh timer and the pending reply queue.
  541. func (t *UDPv4) loop() {
  542. defer t.wg.Done()
  543. var (
  544. plist = list.New()
  545. timeout = time.NewTimer(0)
  546. nextTimeout *replyMatcher // head of plist when timeout was last reset
  547. contTimeouts = 0 // number of continuous timeouts to do NTP checks
  548. ntpWarnTime = time.Unix(0, 0)
  549. )
  550. <-timeout.C // ignore first timeout
  551. defer timeout.Stop()
  552. resetTimeout := func() {
  553. if plist.Front() == nil || nextTimeout == plist.Front().Value {
  554. return
  555. }
  556. // Start the timer so it fires when the next pending reply has expired.
  557. now := time.Now()
  558. for el := plist.Front(); el != nil; el = el.Next() {
  559. nextTimeout = el.Value.(*replyMatcher)
  560. if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
  561. timeout.Reset(dist)
  562. return
  563. }
  564. // Remove pending replies whose deadline is too far in the
  565. // future. These can occur if the system clock jumped
  566. // backwards after the deadline was assigned.
  567. nextTimeout.errc <- errClockWarp
  568. plist.Remove(el)
  569. }
  570. nextTimeout = nil
  571. timeout.Stop()
  572. }
  573. for {
  574. resetTimeout()
  575. select {
  576. case <-t.closing:
  577. for el := plist.Front(); el != nil; el = el.Next() {
  578. el.Value.(*replyMatcher).errc <- errClosed
  579. }
  580. return
  581. case p := <-t.addReplyMatcher:
  582. p.deadline = time.Now().Add(respTimeout)
  583. plist.PushBack(p)
  584. case r := <-t.gotreply:
  585. var matched bool // whether any replyMatcher considered the reply acceptable.
  586. for el := plist.Front(); el != nil; el = el.Next() {
  587. p := el.Value.(*replyMatcher)
  588. if p.from == r.from && p.ptype == r.data.kind() && p.ip.Equal(r.ip) {
  589. ok, requestDone := p.callback(r.data)
  590. matched = matched || ok
  591. // Remove the matcher if callback indicates that all replies have been received.
  592. if requestDone {
  593. p.reply = r.data
  594. p.errc <- nil
  595. plist.Remove(el)
  596. }
  597. // Reset the continuous timeout counter (time drift detection)
  598. contTimeouts = 0
  599. }
  600. }
  601. r.matched <- matched
  602. case now := <-timeout.C:
  603. nextTimeout = nil
  604. // Notify and remove callbacks whose deadline is in the past.
  605. for el := plist.Front(); el != nil; el = el.Next() {
  606. p := el.Value.(*replyMatcher)
  607. if now.After(p.deadline) || now.Equal(p.deadline) {
  608. p.errc <- errTimeout
  609. plist.Remove(el)
  610. contTimeouts++
  611. }
  612. }
  613. // If we've accumulated too many timeouts, do an NTP time sync check
  614. if contTimeouts > ntpFailureThreshold {
  615. if time.Since(ntpWarnTime) >= ntpWarningCooldown {
  616. ntpWarnTime = time.Now()
  617. go checkClockDrift()
  618. }
  619. contTimeouts = 0
  620. }
  621. }
  622. }
  623. }
  624. const (
  625. macSize = 256 / 8
  626. sigSize = 520 / 8
  627. headSize = macSize + sigSize // space of packet frame data
  628. )
  629. var (
  630. headSpace = make([]byte, headSize)
  631. // Neighbors replies are sent across multiple packets to
  632. // stay below the packet size limit. We compute the maximum number
  633. // of entries by stuffing a packet until it grows too large.
  634. maxNeighbors int
  635. )
  636. func init() {
  637. p := neighborsV4{Expiration: ^uint64(0)}
  638. maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
  639. for n := 0; ; n++ {
  640. p.Nodes = append(p.Nodes, maxSizeNode)
  641. size, _, err := rlp.EncodeToReader(p)
  642. if err != nil {
  643. // If this ever happens, it will be caught by the unit tests.
  644. panic("cannot encode: " + err.Error())
  645. }
  646. if headSize+size+1 >= maxPacketSize {
  647. maxNeighbors = n
  648. break
  649. }
  650. }
  651. }
  652. func (t *UDPv4) send(toaddr *net.UDPAddr, toid enode.ID, req packetV4) ([]byte, error) {
  653. packet, hash, err := t.encode(t.priv, req)
  654. if err != nil {
  655. return hash, err
  656. }
  657. return hash, t.write(toaddr, toid, req.name(), packet)
  658. }
  659. func (t *UDPv4) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
  660. _, err := t.conn.WriteToUDP(packet, toaddr)
  661. t.log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
  662. return err
  663. }
  664. func (t *UDPv4) encode(priv *ecdsa.PrivateKey, req packetV4) (packet, hash []byte, err error) {
  665. name := req.name()
  666. b := new(bytes.Buffer)
  667. b.Write(headSpace)
  668. b.WriteByte(req.kind())
  669. if err := rlp.Encode(b, req); err != nil {
  670. t.log.Error(fmt.Sprintf("Can't encode %s packet", name), "err", err)
  671. return nil, nil, err
  672. }
  673. packet = b.Bytes()
  674. sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
  675. if err != nil {
  676. t.log.Error(fmt.Sprintf("Can't sign %s packet", name), "err", err)
  677. return nil, nil, err
  678. }
  679. copy(packet[macSize:], sig)
  680. // add the hash to the front. Note: this doesn't protect the
  681. // packet in any way. Our public key will be part of this hash in
  682. // The future.
  683. hash = crypto.Keccak256(packet[macSize:])
  684. copy(packet, hash)
  685. return packet, hash, nil
  686. }
  687. // readLoop runs in its own goroutine. it handles incoming UDP packets.
  688. func (t *UDPv4) readLoop(unhandled chan<- ReadPacket) {
  689. defer t.wg.Done()
  690. if unhandled != nil {
  691. defer close(unhandled)
  692. }
  693. buf := make([]byte, maxPacketSize)
  694. for {
  695. nbytes, from, err := t.conn.ReadFromUDP(buf)
  696. if netutil.IsTemporaryError(err) {
  697. // Ignore temporary read errors.
  698. t.log.Debug("Temporary UDP read error", "err", err)
  699. continue
  700. } else if err != nil {
  701. // Shut down the loop for permament errors.
  702. if err != io.EOF {
  703. t.log.Debug("UDP read error", "err", err)
  704. }
  705. return
  706. }
  707. if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
  708. select {
  709. case unhandled <- ReadPacket{buf[:nbytes], from}:
  710. default:
  711. }
  712. }
  713. }
  714. }
  715. func (t *UDPv4) handlePacket(from *net.UDPAddr, buf []byte) error {
  716. packet, fromKey, hash, err := decodeV4(buf)
  717. if err != nil {
  718. t.log.Debug("Bad discv4 packet", "addr", from, "err", err)
  719. return err
  720. }
  721. fromID := fromKey.id()
  722. if err == nil {
  723. err = packet.preverify(t, from, fromID, fromKey)
  724. }
  725. t.log.Trace("<< "+packet.name(), "id", fromID, "addr", from, "err", err)
  726. if err == nil {
  727. packet.handle(t, from, fromID, hash)
  728. }
  729. return err
  730. }
  731. func decodeV4(buf []byte) (packetV4, encPubkey, []byte, error) {
  732. if len(buf) < headSize+1 {
  733. return nil, encPubkey{}, nil, errPacketTooSmall
  734. }
  735. hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
  736. shouldhash := crypto.Keccak256(buf[macSize:])
  737. if !bytes.Equal(hash, shouldhash) {
  738. return nil, encPubkey{}, nil, errBadHash
  739. }
  740. fromKey, err := recoverNodeKey(crypto.Keccak256(buf[headSize:]), sig)
  741. if err != nil {
  742. return nil, fromKey, hash, err
  743. }
  744. var req packetV4
  745. switch ptype := sigdata[0]; ptype {
  746. case p_pingV4:
  747. req = new(pingV4)
  748. case p_pongV4:
  749. req = new(pongV4)
  750. case p_findnodeV4:
  751. req = new(findnodeV4)
  752. case p_neighborsV4:
  753. req = new(neighborsV4)
  754. case p_enrRequestV4:
  755. req = new(enrRequestV4)
  756. case p_enrResponseV4:
  757. req = new(enrResponseV4)
  758. default:
  759. return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype)
  760. }
  761. s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
  762. err = s.Decode(req)
  763. return req, fromKey, hash, err
  764. }
  765. // checkBond checks if the given node has a recent enough endpoint proof.
  766. func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
  767. return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
  768. }
  769. // ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
  770. // This ensures there is a valid endpoint proof on the remote end.
  771. func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
  772. tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
  773. if tooOld || t.db.FindFails(toid, toaddr.IP) > maxFindnodeFailures {
  774. rm := t.sendPing(toid, toaddr, nil)
  775. <-rm.errc
  776. // Wait for them to ping back and process our pong.
  777. time.Sleep(respTimeout)
  778. }
  779. }
  780. // expired checks whether the given UNIX time stamp is in the past.
  781. func expired(ts uint64) bool {
  782. return time.Unix(int64(ts), 0).Before(time.Now())
  783. }
  784. func seqFromTail(tail []rlp.RawValue) uint64 {
  785. if len(tail) == 0 {
  786. return 0
  787. }
  788. var seq uint64
  789. rlp.DecodeBytes(tail[0], &seq)
  790. return seq
  791. }
  792. // PING/v4
  793. func (req *pingV4) name() string { return "PING/v4" }
  794. func (req *pingV4) kind() byte { return p_pingV4 }
  795. func (req *pingV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  796. if expired(req.Expiration) {
  797. return errExpired
  798. }
  799. key, err := decodePubkey(fromKey)
  800. if err != nil {
  801. return errors.New("invalid public key")
  802. }
  803. req.senderKey = key
  804. return nil
  805. }
  806. func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  807. // Reply.
  808. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  809. t.send(from, fromID, &pongV4{
  810. To: makeEndpoint(from, req.From.TCP),
  811. ReplyTok: mac,
  812. Expiration: uint64(time.Now().Add(expiration).Unix()),
  813. Rest: []rlp.RawValue{seq},
  814. })
  815. // Ping back if our last pong on file is too far in the past.
  816. n := wrapNode(enode.NewV4(req.senderKey, from.IP, int(req.From.TCP), from.Port))
  817. if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
  818. t.sendPing(fromID, from, func() {
  819. t.tab.addVerifiedNode(n)
  820. })
  821. } else {
  822. t.tab.addVerifiedNode(n)
  823. }
  824. // Update node database and endpoint predictor.
  825. t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
  826. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  827. }
  828. // PONG/v4
  829. func (req *pongV4) name() string { return "PONG/v4" }
  830. func (req *pongV4) kind() byte { return p_pongV4 }
  831. func (req *pongV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  832. if expired(req.Expiration) {
  833. return errExpired
  834. }
  835. if !t.handleReply(fromID, from.IP, req) {
  836. return errUnsolicitedReply
  837. }
  838. return nil
  839. }
  840. func (req *pongV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  841. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  842. t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
  843. }
  844. // FINDNODE/v4
  845. func (req *findnodeV4) name() string { return "FINDNODE/v4" }
  846. func (req *findnodeV4) kind() byte { return p_findnodeV4 }
  847. func (req *findnodeV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  848. if expired(req.Expiration) {
  849. return errExpired
  850. }
  851. if !t.checkBond(fromID, from.IP) {
  852. // No endpoint proof pong exists, we don't process the packet. This prevents an
  853. // attack vector where the discovery protocol could be used to amplify traffic in a
  854. // DDOS attack. A malicious actor would send a findnode request with the IP address
  855. // and UDP port of the target as the source address. The recipient of the findnode
  856. // packet would then send a neighbors packet (which is a much bigger packet than
  857. // findnode) to the victim.
  858. return errUnknownNode
  859. }
  860. return nil
  861. }
  862. func (req *findnodeV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  863. // Determine closest nodes.
  864. target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
  865. t.tab.mutex.Lock()
  866. closest := t.tab.closest(target, bucketSize, true).entries
  867. t.tab.mutex.Unlock()
  868. // Send neighbors in chunks with at most maxNeighbors per packet
  869. // to stay below the packet size limit.
  870. p := neighborsV4{Expiration: uint64(time.Now().Add(expiration).Unix())}
  871. var sent bool
  872. for _, n := range closest {
  873. if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
  874. p.Nodes = append(p.Nodes, nodeToRPC(n))
  875. }
  876. if len(p.Nodes) == maxNeighbors {
  877. t.send(from, fromID, &p)
  878. p.Nodes = p.Nodes[:0]
  879. sent = true
  880. }
  881. }
  882. if len(p.Nodes) > 0 || !sent {
  883. t.send(from, fromID, &p)
  884. }
  885. }
  886. // NEIGHBORS/v4
  887. func (req *neighborsV4) name() string { return "NEIGHBORS/v4" }
  888. func (req *neighborsV4) kind() byte { return p_neighborsV4 }
  889. func (req *neighborsV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  890. if expired(req.Expiration) {
  891. return errExpired
  892. }
  893. if !t.handleReply(fromID, from.IP, req) {
  894. return errUnsolicitedReply
  895. }
  896. return nil
  897. }
  898. func (req *neighborsV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  899. }
  900. // ENRREQUEST/v4
  901. func (req *enrRequestV4) name() string { return "ENRREQUEST/v4" }
  902. func (req *enrRequestV4) kind() byte { return p_enrRequestV4 }
  903. func (req *enrRequestV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  904. if expired(req.Expiration) {
  905. return errExpired
  906. }
  907. if !t.checkBond(fromID, from.IP) {
  908. return errUnknownNode
  909. }
  910. return nil
  911. }
  912. func (req *enrRequestV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  913. t.send(from, fromID, &enrResponseV4{
  914. ReplyTok: mac,
  915. Record: *t.localNode.Node().Record(),
  916. })
  917. }
  918. // ENRRESPONSE/v4
  919. func (req *enrResponseV4) name() string { return "ENRRESPONSE/v4" }
  920. func (req *enrResponseV4) kind() byte { return p_enrResponseV4 }
  921. func (req *enrResponseV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
  922. if !t.handleReply(fromID, from.IP, req) {
  923. return errUnsolicitedReply
  924. }
  925. return nil
  926. }
  927. func (req *enrResponseV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  928. }