handler.go 17 KB

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