v4_udp.go 28 KB

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