handler.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // Copyright 2020 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 snap
  17. import (
  18. "bytes"
  19. "fmt"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/light"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/ethereum/go-ethereum/p2p"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. "github.com/ethereum/go-ethereum/p2p/enr"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. "github.com/ethereum/go-ethereum/trie"
  32. )
  33. const (
  34. // softResponseLimit is the target maximum size of replies to data retrievals.
  35. softResponseLimit = 2 * 1024 * 1024
  36. // maxCodeLookups is the maximum number of bytecodes to serve. This number is
  37. // there to limit the number of disk lookups.
  38. maxCodeLookups = 1024
  39. // stateLookupSlack defines the ratio by how much a state response can exceed
  40. // the requested limit in order to try and avoid breaking up contracts into
  41. // multiple packages and proving them.
  42. stateLookupSlack = 0.1
  43. // maxTrieNodeLookups is the maximum number of state trie nodes to serve. This
  44. // number is there to limit the number of disk lookups.
  45. maxTrieNodeLookups = 1024
  46. // maxTrieNodeTimeSpent is the maximum time we should spend on looking up trie nodes.
  47. // If we spend too much time, then it's a fairly high chance of timing out
  48. // at the remote side, which means all the work is in vain.
  49. maxTrieNodeTimeSpent = 5 * time.Second
  50. )
  51. // Handler is a callback to invoke from an outside runner after the boilerplate
  52. // exchanges have passed.
  53. type Handler func(peer *Peer) error
  54. // Backend defines the data retrieval methods to serve remote requests and the
  55. // callback methods to invoke on remote deliveries.
  56. type Backend interface {
  57. // Chain retrieves the blockchain object to serve data.
  58. Chain() *core.BlockChain
  59. // RunPeer is invoked when a peer joins on the `eth` protocol. The handler
  60. // should do any peer maintenance work, handshakes and validations. If all
  61. // is passed, control should be given back to the `handler` to process the
  62. // inbound messages going forward.
  63. RunPeer(peer *Peer, handler Handler) error
  64. // PeerInfo retrieves all known `snap` information about a peer.
  65. PeerInfo(id enode.ID) interface{}
  66. // Handle is a callback to be invoked when a data packet is received from
  67. // the remote peer. Only packets not consumed by the protocol handler will
  68. // be forwarded to the backend.
  69. Handle(peer *Peer, packet Packet) error
  70. }
  71. // MakeProtocols constructs the P2P protocol definitions for `snap`.
  72. func MakeProtocols(backend Backend, dnsdisc enode.Iterator) []p2p.Protocol {
  73. // Filter the discovery iterator for nodes advertising snap support.
  74. dnsdisc = enode.Filter(dnsdisc, func(n *enode.Node) bool {
  75. var snap enrEntry
  76. return n.Load(&snap) == nil
  77. })
  78. protocols := make([]p2p.Protocol, len(ProtocolVersions))
  79. for i, version := range ProtocolVersions {
  80. version := version // Closure
  81. protocols[i] = p2p.Protocol{
  82. Name: ProtocolName,
  83. Version: version,
  84. Length: protocolLengths[version],
  85. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  86. return backend.RunPeer(newPeer(version, p, rw), func(peer *Peer) error {
  87. return handle(backend, peer)
  88. })
  89. },
  90. NodeInfo: func() interface{} {
  91. return nodeInfo(backend.Chain())
  92. },
  93. PeerInfo: func(id enode.ID) interface{} {
  94. return backend.PeerInfo(id)
  95. },
  96. Attributes: []enr.Entry{&enrEntry{}},
  97. DialCandidates: dnsdisc,
  98. }
  99. }
  100. return protocols
  101. }
  102. // handle is the callback invoked to manage the life cycle of a `snap` peer.
  103. // When this function terminates, the peer is disconnected.
  104. func handle(backend Backend, peer *Peer) error {
  105. for {
  106. if err := handleMessage(backend, peer); err != nil {
  107. peer.Log().Debug("Message handling failed in `snap`", "err", err)
  108. return err
  109. }
  110. }
  111. }
  112. // handleMessage is invoked whenever an inbound message is received from a
  113. // remote peer on the `snap` protocol. The remote connection is torn down upon
  114. // returning any error.
  115. func handleMessage(backend Backend, peer *Peer) error {
  116. // Read the next message from the remote peer, and ensure it's fully consumed
  117. msg, err := peer.rw.ReadMsg()
  118. if err != nil {
  119. return err
  120. }
  121. if msg.Size > maxMessageSize {
  122. return fmt.Errorf("%w: %v > %v", errMsgTooLarge, msg.Size, maxMessageSize)
  123. }
  124. defer msg.Discard()
  125. start := time.Now()
  126. // Track the emount of time it takes to serve the request and run the handler
  127. if metrics.Enabled {
  128. h := fmt.Sprintf("%s/%s/%d/%#02x", p2p.HandleHistName, ProtocolName, peer.Version(), msg.Code)
  129. defer func(start time.Time) {
  130. sampler := func() metrics.Sample {
  131. return metrics.ResettingSample(
  132. metrics.NewExpDecaySample(1028, 0.015),
  133. )
  134. }
  135. metrics.GetOrRegisterHistogramLazy(h, nil, sampler).Update(time.Since(start).Microseconds())
  136. }(start)
  137. }
  138. // Handle the message depending on its contents
  139. switch {
  140. case msg.Code == GetAccountRangeMsg:
  141. // Decode the account retrieval request
  142. var req GetAccountRangePacket
  143. if err := msg.Decode(&req); err != nil {
  144. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  145. }
  146. if req.Bytes > softResponseLimit {
  147. req.Bytes = softResponseLimit
  148. }
  149. // Retrieve the requested state and bail out if non existent
  150. tr, err := trie.New(req.Root, backend.Chain().StateCache().TrieDB())
  151. if err != nil {
  152. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  153. }
  154. it, err := backend.Chain().Snapshots().AccountIterator(req.Root, req.Origin)
  155. if err != nil {
  156. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  157. }
  158. // Iterate over the requested range and pile accounts up
  159. var (
  160. accounts []*AccountData
  161. size uint64
  162. last common.Hash
  163. )
  164. for it.Next() && size < req.Bytes {
  165. hash, account := it.Hash(), common.CopyBytes(it.Account())
  166. // Track the returned interval for the Merkle proofs
  167. last = hash
  168. // Assemble the reply item
  169. size += uint64(common.HashLength + len(account))
  170. accounts = append(accounts, &AccountData{
  171. Hash: hash,
  172. Body: account,
  173. })
  174. // If we've exceeded the request threshold, abort
  175. if bytes.Compare(hash[:], req.Limit[:]) >= 0 {
  176. break
  177. }
  178. }
  179. it.Release()
  180. // Generate the Merkle proofs for the first and last account
  181. proof := light.NewNodeSet()
  182. if err := tr.Prove(req.Origin[:], 0, proof); err != nil {
  183. log.Warn("Failed to prove account range", "origin", req.Origin, "err", err)
  184. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  185. }
  186. if last != (common.Hash{}) {
  187. if err := tr.Prove(last[:], 0, proof); err != nil {
  188. log.Warn("Failed to prove account range", "last", last, "err", err)
  189. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  190. }
  191. }
  192. var proofs [][]byte
  193. for _, blob := range proof.NodeList() {
  194. proofs = append(proofs, blob)
  195. }
  196. // Send back anything accumulated
  197. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{
  198. ID: req.ID,
  199. Accounts: accounts,
  200. Proof: proofs,
  201. })
  202. case msg.Code == AccountRangeMsg:
  203. // A range of accounts arrived to one of our previous requests
  204. res := new(AccountRangePacket)
  205. if err := msg.Decode(res); err != nil {
  206. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  207. }
  208. // Ensure the range is monotonically increasing
  209. for i := 1; i < len(res.Accounts); i++ {
  210. if bytes.Compare(res.Accounts[i-1].Hash[:], res.Accounts[i].Hash[:]) >= 0 {
  211. return fmt.Errorf("accounts not monotonically increasing: #%d [%x] vs #%d [%x]", i-1, res.Accounts[i-1].Hash[:], i, res.Accounts[i].Hash[:])
  212. }
  213. }
  214. requestTracker.Fulfil(peer.id, peer.version, AccountRangeMsg, res.ID)
  215. return backend.Handle(peer, res)
  216. case msg.Code == GetStorageRangesMsg:
  217. // Decode the storage retrieval request
  218. var req GetStorageRangesPacket
  219. if err := msg.Decode(&req); err != nil {
  220. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  221. }
  222. if req.Bytes > softResponseLimit {
  223. req.Bytes = softResponseLimit
  224. }
  225. // TODO(karalabe): Do we want to enforce > 0 accounts and 1 account if origin is set?
  226. // TODO(karalabe): - Logging locally is not ideal as remote faulst annoy the local user
  227. // TODO(karalabe): - Dropping the remote peer is less flexible wrt client bugs (slow is better than non-functional)
  228. // Calculate the hard limit at which to abort, even if mid storage trie
  229. hardLimit := uint64(float64(req.Bytes) * (1 + stateLookupSlack))
  230. // Retrieve storage ranges until the packet limit is reached
  231. var (
  232. slots [][]*StorageData
  233. proofs [][]byte
  234. size uint64
  235. )
  236. for _, account := range req.Accounts {
  237. // If we've exceeded the requested data limit, abort without opening
  238. // a new storage range (that we'd need to prove due to exceeded size)
  239. if size >= req.Bytes {
  240. break
  241. }
  242. // The first account might start from a different origin and end sooner
  243. var origin common.Hash
  244. if len(req.Origin) > 0 {
  245. origin, req.Origin = common.BytesToHash(req.Origin), nil
  246. }
  247. var limit = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  248. if len(req.Limit) > 0 {
  249. limit, req.Limit = common.BytesToHash(req.Limit), nil
  250. }
  251. // Retrieve the requested state and bail out if non existent
  252. it, err := backend.Chain().Snapshots().StorageIterator(req.Root, account, origin)
  253. if err != nil {
  254. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  255. }
  256. // Iterate over the requested range and pile slots up
  257. var (
  258. storage []*StorageData
  259. last common.Hash
  260. abort bool
  261. )
  262. for it.Next() {
  263. if size >= hardLimit {
  264. abort = true
  265. break
  266. }
  267. hash, slot := it.Hash(), common.CopyBytes(it.Slot())
  268. // Track the returned interval for the Merkle proofs
  269. last = hash
  270. // Assemble the reply item
  271. size += uint64(common.HashLength + len(slot))
  272. storage = append(storage, &StorageData{
  273. Hash: hash,
  274. Body: slot,
  275. })
  276. // If we've exceeded the request threshold, abort
  277. if bytes.Compare(hash[:], limit[:]) >= 0 {
  278. break
  279. }
  280. }
  281. slots = append(slots, storage)
  282. it.Release()
  283. // Generate the Merkle proofs for the first and last storage slot, but
  284. // only if the response was capped. If the entire storage trie included
  285. // in the response, no need for any proofs.
  286. if origin != (common.Hash{}) || abort {
  287. // Request started at a non-zero hash or was capped prematurely, add
  288. // the endpoint Merkle proofs
  289. accTrie, err := trie.New(req.Root, backend.Chain().StateCache().TrieDB())
  290. if err != nil {
  291. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  292. }
  293. var acc state.Account
  294. if err := rlp.DecodeBytes(accTrie.Get(account[:]), &acc); err != nil {
  295. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  296. }
  297. stTrie, err := trie.New(acc.Root, backend.Chain().StateCache().TrieDB())
  298. if err != nil {
  299. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  300. }
  301. proof := light.NewNodeSet()
  302. if err := stTrie.Prove(origin[:], 0, proof); err != nil {
  303. log.Warn("Failed to prove storage range", "origin", req.Origin, "err", err)
  304. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  305. }
  306. if last != (common.Hash{}) {
  307. if err := stTrie.Prove(last[:], 0, proof); err != nil {
  308. log.Warn("Failed to prove storage range", "last", last, "err", err)
  309. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  310. }
  311. }
  312. for _, blob := range proof.NodeList() {
  313. proofs = append(proofs, blob)
  314. }
  315. // Proof terminates the reply as proofs are only added if a node
  316. // refuses to serve more data (exception when a contract fetch is
  317. // finishing, but that's that).
  318. break
  319. }
  320. }
  321. // Send back anything accumulated
  322. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{
  323. ID: req.ID,
  324. Slots: slots,
  325. Proof: proofs,
  326. })
  327. case msg.Code == StorageRangesMsg:
  328. // A range of storage slots arrived to one of our previous requests
  329. res := new(StorageRangesPacket)
  330. if err := msg.Decode(res); err != nil {
  331. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  332. }
  333. // Ensure the ranges are monotonically increasing
  334. for i, slots := range res.Slots {
  335. for j := 1; j < len(slots); j++ {
  336. if bytes.Compare(slots[j-1].Hash[:], slots[j].Hash[:]) >= 0 {
  337. return fmt.Errorf("storage slots not monotonically increasing for account #%d: #%d [%x] vs #%d [%x]", i, j-1, slots[j-1].Hash[:], j, slots[j].Hash[:])
  338. }
  339. }
  340. }
  341. requestTracker.Fulfil(peer.id, peer.version, StorageRangesMsg, res.ID)
  342. return backend.Handle(peer, res)
  343. case msg.Code == GetByteCodesMsg:
  344. // Decode bytecode retrieval request
  345. var req GetByteCodesPacket
  346. if err := msg.Decode(&req); err != nil {
  347. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  348. }
  349. if req.Bytes > softResponseLimit {
  350. req.Bytes = softResponseLimit
  351. }
  352. if len(req.Hashes) > maxCodeLookups {
  353. req.Hashes = req.Hashes[:maxCodeLookups]
  354. }
  355. // Retrieve bytecodes until the packet size limit is reached
  356. var (
  357. codes [][]byte
  358. bytes uint64
  359. )
  360. for _, hash := range req.Hashes {
  361. if hash == emptyCode {
  362. // Peers should not request the empty code, but if they do, at
  363. // least sent them back a correct response without db lookups
  364. codes = append(codes, []byte{})
  365. } else if blob, err := backend.Chain().ContractCode(hash); err == nil {
  366. codes = append(codes, blob)
  367. bytes += uint64(len(blob))
  368. }
  369. if bytes > req.Bytes {
  370. break
  371. }
  372. }
  373. // Send back anything accumulated
  374. return p2p.Send(peer.rw, ByteCodesMsg, &ByteCodesPacket{
  375. ID: req.ID,
  376. Codes: codes,
  377. })
  378. case msg.Code == ByteCodesMsg:
  379. // A batch of byte codes arrived to one of our previous requests
  380. res := new(ByteCodesPacket)
  381. if err := msg.Decode(res); err != nil {
  382. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  383. }
  384. requestTracker.Fulfil(peer.id, peer.version, ByteCodesMsg, res.ID)
  385. return backend.Handle(peer, res)
  386. case msg.Code == GetTrieNodesMsg:
  387. // Decode trie node retrieval request
  388. var req GetTrieNodesPacket
  389. if err := msg.Decode(&req); err != nil {
  390. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  391. }
  392. if req.Bytes > softResponseLimit {
  393. req.Bytes = softResponseLimit
  394. }
  395. // Make sure we have the state associated with the request
  396. triedb := backend.Chain().StateCache().TrieDB()
  397. accTrie, err := trie.NewSecure(req.Root, triedb)
  398. if err != nil {
  399. // We don't have the requested state available, bail out
  400. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{ID: req.ID})
  401. }
  402. snap := backend.Chain().Snapshots().Snapshot(req.Root)
  403. if snap == nil {
  404. // We don't have the requested state snapshotted yet, bail out.
  405. // In reality we could still serve using the account and storage
  406. // tries only, but let's protect the node a bit while it's doing
  407. // snapshot generation.
  408. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{ID: req.ID})
  409. }
  410. // Retrieve trie nodes until the packet size limit is reached
  411. var (
  412. nodes [][]byte
  413. bytes uint64
  414. loads int // Trie hash expansions to cound database reads
  415. )
  416. for _, pathset := range req.Paths {
  417. switch len(pathset) {
  418. case 0:
  419. // Ensure we penalize invalid requests
  420. return fmt.Errorf("%w: zero-item pathset requested", errBadRequest)
  421. case 1:
  422. // If we're only retrieving an account trie node, fetch it directly
  423. blob, resolved, err := accTrie.TryGetNode(pathset[0])
  424. loads += resolved // always account database reads, even for failures
  425. if err != nil {
  426. break
  427. }
  428. nodes = append(nodes, blob)
  429. bytes += uint64(len(blob))
  430. default:
  431. // Storage slots requested, open the storage trie and retrieve from there
  432. account, err := snap.Account(common.BytesToHash(pathset[0]))
  433. loads++ // always account database reads, even for failures
  434. if err != nil {
  435. break
  436. }
  437. stTrie, err := trie.NewSecure(common.BytesToHash(account.Root), triedb)
  438. loads++ // always account database reads, even for failures
  439. if err != nil {
  440. break
  441. }
  442. for _, path := range pathset[1:] {
  443. blob, resolved, err := stTrie.TryGetNode(path)
  444. loads += resolved // always account database reads, even for failures
  445. if err != nil {
  446. break
  447. }
  448. nodes = append(nodes, blob)
  449. bytes += uint64(len(blob))
  450. // Sanity check limits to avoid DoS on the store trie loads
  451. if bytes > req.Bytes || loads > maxTrieNodeLookups || time.Since(start) > maxTrieNodeTimeSpent {
  452. break
  453. }
  454. }
  455. }
  456. // Abort request processing if we've exceeded our limits
  457. if bytes > req.Bytes || loads > maxTrieNodeLookups || time.Since(start) > maxTrieNodeTimeSpent {
  458. break
  459. }
  460. }
  461. // Send back anything accumulated
  462. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{
  463. ID: req.ID,
  464. Nodes: nodes,
  465. })
  466. case msg.Code == TrieNodesMsg:
  467. // A batch of trie nodes arrived to one of our previous requests
  468. res := new(TrieNodesPacket)
  469. if err := msg.Decode(res); err != nil {
  470. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  471. }
  472. requestTracker.Fulfil(peer.id, peer.version, TrieNodesMsg, res.ID)
  473. return backend.Handle(peer, res)
  474. default:
  475. return fmt.Errorf("%w: %v", errInvalidMsgCode, msg.Code)
  476. }
  477. }
  478. // NodeInfo represents a short summary of the `snap` sub-protocol metadata
  479. // known about the host peer.
  480. type NodeInfo struct{}
  481. // nodeInfo retrieves some `snap` protocol metadata about the running host node.
  482. func nodeInfo(chain *core.BlockChain) *NodeInfo {
  483. return &NodeInfo{}
  484. }