v4_udp.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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/discover/v4wire"
  32. "github.com/ethereum/go-ethereum/p2p/enode"
  33. "github.com/ethereum/go-ethereum/p2p/netutil"
  34. )
  35. // Errors
  36. var (
  37. errExpired = errors.New("expired")
  38. errUnsolicitedReply = errors.New("unsolicited reply")
  39. errUnknownNode = errors.New("unknown node")
  40. errTimeout = errors.New("RPC timeout")
  41. errClockWarp = errors.New("reply deadline too far in the future")
  42. errClosed = errors.New("socket closed")
  43. errLowPort = errors.New("low port")
  44. )
  45. const (
  46. respTimeout = 500 * time.Millisecond
  47. expiration = 20 * time.Second
  48. bondExpiration = 24 * time.Hour
  49. maxFindnodeFailures = 5 // nodes exceeding this limit are dropped
  50. ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
  51. ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
  52. driftThreshold = 10 * time.Second // Allowed clock drift before warning user
  53. // Discovery packets are defined to be no larger than 1280 bytes.
  54. // Packets larger than this size will be cut at the end and treated
  55. // as invalid because their hash won't match.
  56. maxPacketSize = 1280
  57. )
  58. // UDPv4 implements the v4 wire protocol.
  59. type UDPv4 struct {
  60. conn UDPConn
  61. log log.Logger
  62. netrestrict *netutil.Netlist
  63. priv *ecdsa.PrivateKey
  64. localNode *enode.LocalNode
  65. db *enode.DB
  66. tab *Table
  67. closeOnce sync.Once
  68. wg sync.WaitGroup
  69. addReplyMatcher chan *replyMatcher
  70. gotreply chan reply
  71. closeCtx context.Context
  72. cancelCloseCtx context.CancelFunc
  73. }
  74. // replyMatcher represents a pending reply.
  75. //
  76. // Some implementations of the protocol wish to send more than one
  77. // reply packet to findnode. In general, any neighbors packet cannot
  78. // be matched up with a specific findnode packet.
  79. //
  80. // Our implementation handles this by storing a callback function for
  81. // each pending reply. Incoming packets from a node are dispatched
  82. // to all callback functions for that node.
  83. type replyMatcher struct {
  84. // these fields must match in the reply.
  85. from enode.ID
  86. ip net.IP
  87. ptype byte
  88. // time when the request must complete
  89. deadline time.Time
  90. // callback is called when a matching reply arrives. If it returns matched == true, the
  91. // reply was acceptable. The second return value indicates whether the callback should
  92. // be removed from the pending reply queue. If it returns false, the reply is considered
  93. // incomplete and the callback will be invoked again for the next matching reply.
  94. callback replyMatchFunc
  95. // errc receives nil when the callback indicates completion or an
  96. // error if no further reply is received within the timeout.
  97. errc chan error
  98. // reply contains the most recent reply. This field is safe for reading after errc has
  99. // received a value.
  100. reply v4wire.Packet
  101. }
  102. type replyMatchFunc func(v4wire.Packet) (matched bool, requestDone bool)
  103. // reply is a reply packet from a certain node.
  104. type reply struct {
  105. from enode.ID
  106. ip net.IP
  107. data v4wire.Packet
  108. // loop indicates whether there was
  109. // a matching request by sending on this channel.
  110. matched chan<- bool
  111. }
  112. func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
  113. cfg = cfg.withDefaults()
  114. closeCtx, cancel := context.WithCancel(context.Background())
  115. t := &UDPv4{
  116. conn: c,
  117. priv: cfg.PrivateKey,
  118. netrestrict: cfg.NetRestrict,
  119. localNode: ln,
  120. db: ln.Database(),
  121. gotreply: make(chan reply),
  122. addReplyMatcher: make(chan *replyMatcher),
  123. closeCtx: closeCtx,
  124. cancelCloseCtx: cancel,
  125. log: cfg.Log,
  126. }
  127. tab, err := newTable(t, ln.Database(), cfg.Bootnodes, t.log)
  128. if err != nil {
  129. return nil, err
  130. }
  131. t.tab = tab
  132. go tab.loop()
  133. t.wg.Add(2)
  134. go t.loop()
  135. go t.readLoop(cfg.Unhandled)
  136. return t, nil
  137. }
  138. // Self returns the local node.
  139. func (t *UDPv4) Self() *enode.Node {
  140. return t.localNode.Node()
  141. }
  142. // Close shuts down the socket and aborts any running queries.
  143. func (t *UDPv4) Close() {
  144. t.closeOnce.Do(func() {
  145. t.cancelCloseCtx()
  146. t.conn.Close()
  147. t.wg.Wait()
  148. t.tab.close()
  149. })
  150. }
  151. // Resolve searches for a specific node with the given ID and tries to get the most recent
  152. // version of the node record for it. It returns n if the node could not be resolved.
  153. func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
  154. // Try asking directly. This works if the node is still responding on the endpoint we have.
  155. if rn, err := t.RequestENR(n); err == nil {
  156. return rn
  157. }
  158. // Check table for the ID, we might have a newer version there.
  159. if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
  160. n = intable
  161. if rn, err := t.RequestENR(n); err == nil {
  162. return rn
  163. }
  164. }
  165. // Otherwise perform a network lookup.
  166. var key enode.Secp256k1
  167. if n.Load(&key) != nil {
  168. return n // no secp256k1 key
  169. }
  170. result := t.LookupPubkey((*ecdsa.PublicKey)(&key))
  171. for _, rn := range result {
  172. if rn.ID() == n.ID() {
  173. if rn, err := t.RequestENR(rn); err == nil {
  174. return rn
  175. }
  176. }
  177. }
  178. return n
  179. }
  180. func (t *UDPv4) ourEndpoint() v4wire.Endpoint {
  181. n := t.Self()
  182. a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  183. return v4wire.NewEndpoint(a, uint16(n.TCP()))
  184. }
  185. // Ping sends a ping message to the given node.
  186. func (t *UDPv4) Ping(n *enode.Node) error {
  187. _, err := t.ping(n)
  188. return err
  189. }
  190. // ping sends a ping message to the given node and waits for a reply.
  191. func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
  192. rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
  193. if err = <-rm.errc; err == nil {
  194. seq = rm.reply.(*v4wire.Pong).ENRSeq
  195. }
  196. return seq, err
  197. }
  198. // sendPing sends a ping message to the given node and invokes the callback
  199. // when the reply arrives.
  200. func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
  201. req := t.makePing(toaddr)
  202. packet, hash, err := v4wire.Encode(t.priv, req)
  203. if err != nil {
  204. errc := make(chan error, 1)
  205. errc <- err
  206. return &replyMatcher{errc: errc}
  207. }
  208. // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
  209. // reference the ping we're about to send.
  210. rm := t.pending(toid, toaddr.IP, v4wire.PongPacket, func(p v4wire.Packet) (matched bool, requestDone bool) {
  211. matched = bytes.Equal(p.(*v4wire.Pong).ReplyTok, hash)
  212. if matched && callback != nil {
  213. callback()
  214. }
  215. return matched, matched
  216. })
  217. // Send the packet.
  218. t.localNode.UDPContact(toaddr)
  219. t.write(toaddr, toid, req.Name(), packet)
  220. return rm
  221. }
  222. func (t *UDPv4) makePing(toaddr *net.UDPAddr) *v4wire.Ping {
  223. return &v4wire.Ping{
  224. Version: 4,
  225. From: t.ourEndpoint(),
  226. To: v4wire.NewEndpoint(toaddr, 0),
  227. Expiration: uint64(time.Now().Add(expiration).Unix()),
  228. ENRSeq: t.localNode.Node().Seq(),
  229. }
  230. }
  231. // LookupPubkey finds the closest nodes to the given public key.
  232. func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
  233. if t.tab.len() == 0 {
  234. // All nodes were dropped, refresh. The very first query will hit this
  235. // case and run the bootstrapping logic.
  236. <-t.tab.refresh()
  237. }
  238. return t.newLookup(t.closeCtx, encodePubkey(key)).run()
  239. }
  240. // RandomNodes is an iterator yielding nodes from a random walk of the DHT.
  241. func (t *UDPv4) RandomNodes() enode.Iterator {
  242. return newLookupIterator(t.closeCtx, t.newRandomLookup)
  243. }
  244. // lookupRandom implements transport.
  245. func (t *UDPv4) lookupRandom() []*enode.Node {
  246. return t.newRandomLookup(t.closeCtx).run()
  247. }
  248. // lookupSelf implements transport.
  249. func (t *UDPv4) lookupSelf() []*enode.Node {
  250. return t.newLookup(t.closeCtx, encodePubkey(&t.priv.PublicKey)).run()
  251. }
  252. func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup {
  253. var target encPubkey
  254. crand.Read(target[:])
  255. return t.newLookup(ctx, target)
  256. }
  257. func (t *UDPv4) newLookup(ctx context.Context, targetKey encPubkey) *lookup {
  258. target := enode.ID(crypto.Keccak256Hash(targetKey[:]))
  259. ekey := v4wire.Pubkey(targetKey)
  260. it := newLookup(ctx, t.tab, target, func(n *node) ([]*node, error) {
  261. return t.findnode(n.ID(), n.addr(), ekey)
  262. })
  263. return it
  264. }
  265. // findnode sends a findnode request to the given node and waits until
  266. // the node has sent up to k neighbors.
  267. func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target v4wire.Pubkey) ([]*node, error) {
  268. t.ensureBond(toid, toaddr)
  269. // Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
  270. // active until enough nodes have been received.
  271. nodes := make([]*node, 0, bucketSize)
  272. nreceived := 0
  273. rm := t.pending(toid, toaddr.IP, v4wire.NeighborsPacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
  274. reply := r.(*v4wire.Neighbors)
  275. for _, rn := range reply.Nodes {
  276. nreceived++
  277. n, err := t.nodeFromRPC(toaddr, rn)
  278. if err != nil {
  279. t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
  280. continue
  281. }
  282. nodes = append(nodes, n)
  283. }
  284. return true, nreceived >= bucketSize
  285. })
  286. t.send(toaddr, toid, &v4wire.Findnode{
  287. Target: target,
  288. Expiration: uint64(time.Now().Add(expiration).Unix()),
  289. })
  290. // Ensure that callers don't see a timeout if the node actually responded. Since
  291. // findnode can receive more than one neighbors response, the reply matcher will be
  292. // active until the remote node sends enough nodes. If the remote end doesn't have
  293. // enough nodes the reply matcher will time out waiting for the second reply, but
  294. // there's no need for an error in that case.
  295. err := <-rm.errc
  296. if errors.Is(err, errTimeout) && rm.reply != nil {
  297. err = nil
  298. }
  299. return nodes, err
  300. }
  301. // RequestENR sends ENRRequest to the given node and waits for a response.
  302. func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
  303. addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  304. t.ensureBond(n.ID(), addr)
  305. req := &v4wire.ENRRequest{
  306. Expiration: uint64(time.Now().Add(expiration).Unix()),
  307. }
  308. packet, hash, err := v4wire.Encode(t.priv, req)
  309. if err != nil {
  310. return nil, err
  311. }
  312. // Add a matcher for the reply to the pending reply queue. Responses are matched if
  313. // they reference the request we're about to send.
  314. rm := t.pending(n.ID(), addr.IP, v4wire.ENRResponsePacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
  315. matched = bytes.Equal(r.(*v4wire.ENRResponse).ReplyTok, hash)
  316. return matched, matched
  317. })
  318. // Send the packet and wait for the reply.
  319. t.write(addr, n.ID(), req.Name(), packet)
  320. if err := <-rm.errc; err != nil {
  321. return nil, err
  322. }
  323. // Verify the response record.
  324. respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*v4wire.ENRResponse).Record)
  325. if err != nil {
  326. return nil, err
  327. }
  328. if respN.ID() != n.ID() {
  329. return nil, fmt.Errorf("invalid ID in response record")
  330. }
  331. if respN.Seq() < n.Seq() {
  332. return n, nil // response record is older
  333. }
  334. if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
  335. return nil, fmt.Errorf("invalid IP in response record: %v", err)
  336. }
  337. return respN, nil
  338. }
  339. // pending adds a reply matcher to the pending reply queue.
  340. // see the documentation of type replyMatcher for a detailed explanation.
  341. func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
  342. ch := make(chan error, 1)
  343. p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
  344. select {
  345. case t.addReplyMatcher <- p:
  346. // loop will handle it
  347. case <-t.closeCtx.Done():
  348. ch <- errClosed
  349. }
  350. return p
  351. }
  352. // handleReply dispatches a reply packet, invoking reply matchers. It returns
  353. // whether any matcher considered the packet acceptable.
  354. func (t *UDPv4) handleReply(from enode.ID, fromIP net.IP, req v4wire.Packet) bool {
  355. matched := make(chan bool, 1)
  356. select {
  357. case t.gotreply <- reply{from, fromIP, req, matched}:
  358. // loop will handle it
  359. return <-matched
  360. case <-t.closeCtx.Done():
  361. return false
  362. }
  363. }
  364. // loop runs in its own goroutine. it keeps track of
  365. // the refresh timer and the pending reply queue.
  366. func (t *UDPv4) loop() {
  367. defer t.wg.Done()
  368. var (
  369. plist = list.New()
  370. timeout = time.NewTimer(0)
  371. nextTimeout *replyMatcher // head of plist when timeout was last reset
  372. contTimeouts = 0 // number of continuous timeouts to do NTP checks
  373. ntpWarnTime = time.Unix(0, 0)
  374. )
  375. <-timeout.C // ignore first timeout
  376. defer timeout.Stop()
  377. resetTimeout := func() {
  378. if plist.Front() == nil || nextTimeout == plist.Front().Value {
  379. return
  380. }
  381. // Start the timer so it fires when the next pending reply has expired.
  382. now := time.Now()
  383. for el := plist.Front(); el != nil; el = el.Next() {
  384. nextTimeout = el.Value.(*replyMatcher)
  385. if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
  386. timeout.Reset(dist)
  387. return
  388. }
  389. // Remove pending replies whose deadline is too far in the
  390. // future. These can occur if the system clock jumped
  391. // backwards after the deadline was assigned.
  392. nextTimeout.errc <- errClockWarp
  393. plist.Remove(el)
  394. }
  395. nextTimeout = nil
  396. timeout.Stop()
  397. }
  398. for {
  399. resetTimeout()
  400. select {
  401. case <-t.closeCtx.Done():
  402. for el := plist.Front(); el != nil; el = el.Next() {
  403. el.Value.(*replyMatcher).errc <- errClosed
  404. }
  405. return
  406. case p := <-t.addReplyMatcher:
  407. p.deadline = time.Now().Add(respTimeout)
  408. plist.PushBack(p)
  409. case r := <-t.gotreply:
  410. var matched bool // whether any replyMatcher considered the reply acceptable.
  411. for el := plist.Front(); el != nil; el = el.Next() {
  412. p := el.Value.(*replyMatcher)
  413. if p.from == r.from && p.ptype == r.data.Kind() && p.ip.Equal(r.ip) {
  414. ok, requestDone := p.callback(r.data)
  415. matched = matched || ok
  416. p.reply = r.data
  417. // Remove the matcher if callback indicates that all replies have been received.
  418. if requestDone {
  419. p.errc <- nil
  420. plist.Remove(el)
  421. }
  422. // Reset the continuous timeout counter (time drift detection)
  423. contTimeouts = 0
  424. }
  425. }
  426. r.matched <- matched
  427. case now := <-timeout.C:
  428. nextTimeout = nil
  429. // Notify and remove callbacks whose deadline is in the past.
  430. for el := plist.Front(); el != nil; el = el.Next() {
  431. p := el.Value.(*replyMatcher)
  432. if now.After(p.deadline) || now.Equal(p.deadline) {
  433. p.errc <- errTimeout
  434. plist.Remove(el)
  435. contTimeouts++
  436. }
  437. }
  438. // If we've accumulated too many timeouts, do an NTP time sync check
  439. if contTimeouts > ntpFailureThreshold {
  440. if time.Since(ntpWarnTime) >= ntpWarningCooldown {
  441. ntpWarnTime = time.Now()
  442. go checkClockDrift()
  443. }
  444. contTimeouts = 0
  445. }
  446. }
  447. }
  448. }
  449. func (t *UDPv4) send(toaddr *net.UDPAddr, toid enode.ID, req v4wire.Packet) ([]byte, error) {
  450. packet, hash, err := v4wire.Encode(t.priv, req)
  451. if err != nil {
  452. return hash, err
  453. }
  454. return hash, t.write(toaddr, toid, req.Name(), packet)
  455. }
  456. func (t *UDPv4) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
  457. _, err := t.conn.WriteToUDP(packet, toaddr)
  458. t.log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
  459. return err
  460. }
  461. // readLoop runs in its own goroutine. it handles incoming UDP packets.
  462. func (t *UDPv4) readLoop(unhandled chan<- ReadPacket) {
  463. defer t.wg.Done()
  464. if unhandled != nil {
  465. defer close(unhandled)
  466. }
  467. buf := make([]byte, maxPacketSize)
  468. for {
  469. nbytes, from, err := t.conn.ReadFromUDP(buf)
  470. if netutil.IsTemporaryError(err) {
  471. // Ignore temporary read errors.
  472. t.log.Debug("Temporary UDP read error", "err", err)
  473. continue
  474. } else if err != nil {
  475. // Shut down the loop for permanent errors.
  476. if !errors.Is(err, io.EOF) {
  477. t.log.Debug("UDP read error", "err", err)
  478. }
  479. return
  480. }
  481. if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
  482. select {
  483. case unhandled <- ReadPacket{buf[:nbytes], from}:
  484. default:
  485. }
  486. }
  487. }
  488. }
  489. func (t *UDPv4) handlePacket(from *net.UDPAddr, buf []byte) error {
  490. rawpacket, fromKey, hash, err := v4wire.Decode(buf)
  491. if err != nil {
  492. t.log.Debug("Bad discv4 packet", "addr", from, "err", err)
  493. return err
  494. }
  495. packet := t.wrapPacket(rawpacket)
  496. fromID := fromKey.ID()
  497. if err == nil && packet.preverify != nil {
  498. err = packet.preverify(packet, from, fromID, fromKey)
  499. }
  500. t.log.Trace("<< "+packet.Name(), "id", fromID, "addr", from, "err", err)
  501. if err == nil && packet.handle != nil {
  502. packet.handle(packet, from, fromID, hash)
  503. }
  504. return err
  505. }
  506. // checkBond checks if the given node has a recent enough endpoint proof.
  507. func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
  508. return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
  509. }
  510. // ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
  511. // This ensures there is a valid endpoint proof on the remote end.
  512. func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
  513. tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
  514. if tooOld || t.db.FindFails(toid, toaddr.IP) > maxFindnodeFailures {
  515. rm := t.sendPing(toid, toaddr, nil)
  516. <-rm.errc
  517. // Wait for them to ping back and process our pong.
  518. time.Sleep(respTimeout)
  519. }
  520. }
  521. func (t *UDPv4) nodeFromRPC(sender *net.UDPAddr, rn v4wire.Node) (*node, error) {
  522. if rn.UDP <= 1024 {
  523. return nil, errLowPort
  524. }
  525. if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
  526. return nil, err
  527. }
  528. if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
  529. return nil, errors.New("not contained in netrestrict list")
  530. }
  531. key, err := v4wire.DecodePubkey(crypto.S256(), rn.ID)
  532. if err != nil {
  533. return nil, err
  534. }
  535. n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
  536. err = n.ValidateComplete()
  537. return n, err
  538. }
  539. func nodeToRPC(n *node) v4wire.Node {
  540. var key ecdsa.PublicKey
  541. var ekey v4wire.Pubkey
  542. if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
  543. ekey = v4wire.EncodePubkey(&key)
  544. }
  545. return v4wire.Node{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
  546. }
  547. // wrapPacket returns the handler functions applicable to a packet.
  548. func (t *UDPv4) wrapPacket(p v4wire.Packet) *packetHandlerV4 {
  549. var h packetHandlerV4
  550. h.Packet = p
  551. switch p.(type) {
  552. case *v4wire.Ping:
  553. h.preverify = t.verifyPing
  554. h.handle = t.handlePing
  555. case *v4wire.Pong:
  556. h.preverify = t.verifyPong
  557. case *v4wire.Findnode:
  558. h.preverify = t.verifyFindnode
  559. h.handle = t.handleFindnode
  560. case *v4wire.Neighbors:
  561. h.preverify = t.verifyNeighbors
  562. case *v4wire.ENRRequest:
  563. h.preverify = t.verifyENRRequest
  564. h.handle = t.handleENRRequest
  565. case *v4wire.ENRResponse:
  566. h.preverify = t.verifyENRResponse
  567. }
  568. return &h
  569. }
  570. // packetHandlerV4 wraps a packet with handler functions.
  571. type packetHandlerV4 struct {
  572. v4wire.Packet
  573. senderKey *ecdsa.PublicKey // used for ping
  574. // preverify checks whether the packet is valid and should be handled at all.
  575. preverify func(p *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error
  576. // handle handles the packet.
  577. handle func(req *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte)
  578. }
  579. // PING/v4
  580. func (t *UDPv4) verifyPing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  581. req := h.Packet.(*v4wire.Ping)
  582. senderKey, err := v4wire.DecodePubkey(crypto.S256(), fromKey)
  583. if err != nil {
  584. return err
  585. }
  586. if v4wire.Expired(req.Expiration) {
  587. return errExpired
  588. }
  589. h.senderKey = senderKey
  590. return nil
  591. }
  592. func (t *UDPv4) handlePing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  593. req := h.Packet.(*v4wire.Ping)
  594. // Reply.
  595. t.send(from, fromID, &v4wire.Pong{
  596. To: v4wire.NewEndpoint(from, req.From.TCP),
  597. ReplyTok: mac,
  598. Expiration: uint64(time.Now().Add(expiration).Unix()),
  599. ENRSeq: t.localNode.Node().Seq(),
  600. })
  601. // Ping back if our last pong on file is too far in the past.
  602. n := wrapNode(enode.NewV4(h.senderKey, from.IP, int(req.From.TCP), from.Port))
  603. if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
  604. t.sendPing(fromID, from, func() {
  605. t.tab.addVerifiedNode(n)
  606. })
  607. } else {
  608. t.tab.addVerifiedNode(n)
  609. }
  610. // Update node database and endpoint predictor.
  611. t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
  612. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  613. }
  614. // PONG/v4
  615. func (t *UDPv4) verifyPong(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  616. req := h.Packet.(*v4wire.Pong)
  617. if v4wire.Expired(req.Expiration) {
  618. return errExpired
  619. }
  620. if !t.handleReply(fromID, from.IP, req) {
  621. return errUnsolicitedReply
  622. }
  623. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  624. t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
  625. return nil
  626. }
  627. // FINDNODE/v4
  628. func (t *UDPv4) verifyFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  629. req := h.Packet.(*v4wire.Findnode)
  630. if v4wire.Expired(req.Expiration) {
  631. return errExpired
  632. }
  633. if !t.checkBond(fromID, from.IP) {
  634. // No endpoint proof pong exists, we don't process the packet. This prevents an
  635. // attack vector where the discovery protocol could be used to amplify traffic in a
  636. // DDOS attack. A malicious actor would send a findnode request with the IP address
  637. // and UDP port of the target as the source address. The recipient of the findnode
  638. // packet would then send a neighbors packet (which is a much bigger packet than
  639. // findnode) to the victim.
  640. return errUnknownNode
  641. }
  642. return nil
  643. }
  644. func (t *UDPv4) handleFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  645. req := h.Packet.(*v4wire.Findnode)
  646. // Determine closest nodes.
  647. target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
  648. closest := t.tab.findnodeByID(target, bucketSize, true).entries
  649. // Send neighbors in chunks with at most maxNeighbors per packet
  650. // to stay below the packet size limit.
  651. p := v4wire.Neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
  652. var sent bool
  653. for _, n := range closest {
  654. if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
  655. p.Nodes = append(p.Nodes, nodeToRPC(n))
  656. }
  657. if len(p.Nodes) == v4wire.MaxNeighbors {
  658. t.send(from, fromID, &p)
  659. p.Nodes = p.Nodes[:0]
  660. sent = true
  661. }
  662. }
  663. if len(p.Nodes) > 0 || !sent {
  664. t.send(from, fromID, &p)
  665. }
  666. }
  667. // NEIGHBORS/v4
  668. func (t *UDPv4) verifyNeighbors(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  669. req := h.Packet.(*v4wire.Neighbors)
  670. if v4wire.Expired(req.Expiration) {
  671. return errExpired
  672. }
  673. if !t.handleReply(fromID, from.IP, h.Packet) {
  674. return errUnsolicitedReply
  675. }
  676. return nil
  677. }
  678. // ENRREQUEST/v4
  679. func (t *UDPv4) verifyENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  680. req := h.Packet.(*v4wire.ENRRequest)
  681. if v4wire.Expired(req.Expiration) {
  682. return errExpired
  683. }
  684. if !t.checkBond(fromID, from.IP) {
  685. return errUnknownNode
  686. }
  687. return nil
  688. }
  689. func (t *UDPv4) handleENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  690. t.send(from, fromID, &v4wire.ENRResponse{
  691. ReplyTok: mac,
  692. Record: *t.localNode.Node().Record(),
  693. })
  694. }
  695. // ENRRESPONSE/v4
  696. func (t *UDPv4) verifyENRResponse(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  697. if !t.handleReply(fromID, from.IP, h.Packet) {
  698. return errUnsolicitedReply
  699. }
  700. return nil
  701. }