handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 { return metrics.NewExpDecaySample(1028, 0.015) }
  121. metrics.GetOrRegisterHistogramLazy(h, nil, sampler).Update(time.Since(start).Microseconds())
  122. }(time.Now())
  123. }
  124. // Handle the message depending on its contents
  125. switch {
  126. case msg.Code == GetAccountRangeMsg:
  127. // Decode the account retrieval request
  128. var req GetAccountRangePacket
  129. if err := msg.Decode(&req); err != nil {
  130. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  131. }
  132. if req.Bytes > softResponseLimit {
  133. req.Bytes = softResponseLimit
  134. }
  135. // Retrieve the requested state and bail out if non existent
  136. tr, err := trie.New(req.Root, backend.Chain().StateCache().TrieDB())
  137. if err != nil {
  138. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  139. }
  140. it, err := backend.Chain().Snapshots().AccountIterator(req.Root, req.Origin)
  141. if err != nil {
  142. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  143. }
  144. // Iterate over the requested range and pile accounts up
  145. var (
  146. accounts []*AccountData
  147. size uint64
  148. last common.Hash
  149. )
  150. for it.Next() && size < req.Bytes {
  151. hash, account := it.Hash(), common.CopyBytes(it.Account())
  152. // Track the returned interval for the Merkle proofs
  153. last = hash
  154. // Assemble the reply item
  155. size += uint64(common.HashLength + len(account))
  156. accounts = append(accounts, &AccountData{
  157. Hash: hash,
  158. Body: account,
  159. })
  160. // If we've exceeded the request threshold, abort
  161. if bytes.Compare(hash[:], req.Limit[:]) >= 0 {
  162. break
  163. }
  164. }
  165. it.Release()
  166. // Generate the Merkle proofs for the first and last account
  167. proof := light.NewNodeSet()
  168. if err := tr.Prove(req.Origin[:], 0, proof); err != nil {
  169. log.Warn("Failed to prove account range", "origin", req.Origin, "err", err)
  170. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  171. }
  172. if last != (common.Hash{}) {
  173. if err := tr.Prove(last[:], 0, proof); err != nil {
  174. log.Warn("Failed to prove account range", "last", last, "err", err)
  175. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{ID: req.ID})
  176. }
  177. }
  178. var proofs [][]byte
  179. for _, blob := range proof.NodeList() {
  180. proofs = append(proofs, blob)
  181. }
  182. // Send back anything accumulated
  183. return p2p.Send(peer.rw, AccountRangeMsg, &AccountRangePacket{
  184. ID: req.ID,
  185. Accounts: accounts,
  186. Proof: proofs,
  187. })
  188. case msg.Code == AccountRangeMsg:
  189. // A range of accounts arrived to one of our previous requests
  190. res := new(AccountRangePacket)
  191. if err := msg.Decode(res); err != nil {
  192. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  193. }
  194. // Ensure the range is monotonically increasing
  195. for i := 1; i < len(res.Accounts); i++ {
  196. if bytes.Compare(res.Accounts[i-1].Hash[:], res.Accounts[i].Hash[:]) >= 0 {
  197. return fmt.Errorf("accounts not monotonically increasing: #%d [%x] vs #%d [%x]", i-1, res.Accounts[i-1].Hash[:], i, res.Accounts[i].Hash[:])
  198. }
  199. }
  200. return backend.Handle(peer, res)
  201. case msg.Code == GetStorageRangesMsg:
  202. // Decode the storage retrieval request
  203. var req GetStorageRangesPacket
  204. if err := msg.Decode(&req); err != nil {
  205. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  206. }
  207. if req.Bytes > softResponseLimit {
  208. req.Bytes = softResponseLimit
  209. }
  210. // TODO(karalabe): Do we want to enforce > 0 accounts and 1 account if origin is set?
  211. // TODO(karalabe): - Logging locally is not ideal as remote faulst annoy the local user
  212. // TODO(karalabe): - Dropping the remote peer is less flexible wrt client bugs (slow is better than non-functional)
  213. // Calculate the hard limit at which to abort, even if mid storage trie
  214. hardLimit := uint64(float64(req.Bytes) * (1 + stateLookupSlack))
  215. // Retrieve storage ranges until the packet limit is reached
  216. var (
  217. slots [][]*StorageData
  218. proofs [][]byte
  219. size uint64
  220. )
  221. for _, account := range req.Accounts {
  222. // If we've exceeded the requested data limit, abort without opening
  223. // a new storage range (that we'd need to prove due to exceeded size)
  224. if size >= req.Bytes {
  225. break
  226. }
  227. // The first account might start from a different origin and end sooner
  228. var origin common.Hash
  229. if len(req.Origin) > 0 {
  230. origin, req.Origin = common.BytesToHash(req.Origin), nil
  231. }
  232. var limit = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  233. if len(req.Limit) > 0 {
  234. limit, req.Limit = common.BytesToHash(req.Limit), nil
  235. }
  236. // Retrieve the requested state and bail out if non existent
  237. it, err := backend.Chain().Snapshots().StorageIterator(req.Root, account, origin)
  238. if err != nil {
  239. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  240. }
  241. // Iterate over the requested range and pile slots up
  242. var (
  243. storage []*StorageData
  244. last common.Hash
  245. abort bool
  246. )
  247. for it.Next() {
  248. if size >= hardLimit {
  249. abort = true
  250. break
  251. }
  252. hash, slot := it.Hash(), common.CopyBytes(it.Slot())
  253. // Track the returned interval for the Merkle proofs
  254. last = hash
  255. // Assemble the reply item
  256. size += uint64(common.HashLength + len(slot))
  257. storage = append(storage, &StorageData{
  258. Hash: hash,
  259. Body: slot,
  260. })
  261. // If we've exceeded the request threshold, abort
  262. if bytes.Compare(hash[:], limit[:]) >= 0 {
  263. break
  264. }
  265. }
  266. slots = append(slots, storage)
  267. it.Release()
  268. // Generate the Merkle proofs for the first and last storage slot, but
  269. // only if the response was capped. If the entire storage trie included
  270. // in the response, no need for any proofs.
  271. if origin != (common.Hash{}) || abort {
  272. // Request started at a non-zero hash or was capped prematurely, add
  273. // the endpoint Merkle proofs
  274. accTrie, err := trie.New(req.Root, backend.Chain().StateCache().TrieDB())
  275. if err != nil {
  276. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  277. }
  278. var acc state.Account
  279. if err := rlp.DecodeBytes(accTrie.Get(account[:]), &acc); err != nil {
  280. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  281. }
  282. stTrie, err := trie.New(acc.Root, backend.Chain().StateCache().TrieDB())
  283. if err != nil {
  284. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  285. }
  286. proof := light.NewNodeSet()
  287. if err := stTrie.Prove(origin[:], 0, proof); err != nil {
  288. log.Warn("Failed to prove storage range", "origin", req.Origin, "err", err)
  289. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  290. }
  291. if last != (common.Hash{}) {
  292. if err := stTrie.Prove(last[:], 0, proof); err != nil {
  293. log.Warn("Failed to prove storage range", "last", last, "err", err)
  294. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{ID: req.ID})
  295. }
  296. }
  297. for _, blob := range proof.NodeList() {
  298. proofs = append(proofs, blob)
  299. }
  300. // Proof terminates the reply as proofs are only added if a node
  301. // refuses to serve more data (exception when a contract fetch is
  302. // finishing, but that's that).
  303. break
  304. }
  305. }
  306. // Send back anything accumulated
  307. return p2p.Send(peer.rw, StorageRangesMsg, &StorageRangesPacket{
  308. ID: req.ID,
  309. Slots: slots,
  310. Proof: proofs,
  311. })
  312. case msg.Code == StorageRangesMsg:
  313. // A range of storage slots arrived to one of our previous requests
  314. res := new(StorageRangesPacket)
  315. if err := msg.Decode(res); err != nil {
  316. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  317. }
  318. // Ensure the ranges ae monotonically increasing
  319. for i, slots := range res.Slots {
  320. for j := 1; j < len(slots); j++ {
  321. if bytes.Compare(slots[j-1].Hash[:], slots[j].Hash[:]) >= 0 {
  322. 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[:])
  323. }
  324. }
  325. }
  326. return backend.Handle(peer, res)
  327. case msg.Code == GetByteCodesMsg:
  328. // Decode bytecode retrieval request
  329. var req GetByteCodesPacket
  330. if err := msg.Decode(&req); err != nil {
  331. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  332. }
  333. if req.Bytes > softResponseLimit {
  334. req.Bytes = softResponseLimit
  335. }
  336. if len(req.Hashes) > maxCodeLookups {
  337. req.Hashes = req.Hashes[:maxCodeLookups]
  338. }
  339. // Retrieve bytecodes until the packet size limit is reached
  340. var (
  341. codes [][]byte
  342. bytes uint64
  343. )
  344. for _, hash := range req.Hashes {
  345. if hash == emptyCode {
  346. // Peers should not request the empty code, but if they do, at
  347. // least sent them back a correct response without db lookups
  348. codes = append(codes, []byte{})
  349. } else if blob, err := backend.Chain().ContractCode(hash); err == nil {
  350. codes = append(codes, blob)
  351. bytes += uint64(len(blob))
  352. }
  353. if bytes > req.Bytes {
  354. break
  355. }
  356. }
  357. // Send back anything accumulated
  358. return p2p.Send(peer.rw, ByteCodesMsg, &ByteCodesPacket{
  359. ID: req.ID,
  360. Codes: codes,
  361. })
  362. case msg.Code == ByteCodesMsg:
  363. // A batch of byte codes arrived to one of our previous requests
  364. res := new(ByteCodesPacket)
  365. if err := msg.Decode(res); err != nil {
  366. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  367. }
  368. return backend.Handle(peer, res)
  369. case msg.Code == GetTrieNodesMsg:
  370. // Decode trie node retrieval request
  371. var req GetTrieNodesPacket
  372. if err := msg.Decode(&req); err != nil {
  373. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  374. }
  375. if req.Bytes > softResponseLimit {
  376. req.Bytes = softResponseLimit
  377. }
  378. // Make sure we have the state associated with the request
  379. triedb := backend.Chain().StateCache().TrieDB()
  380. accTrie, err := trie.NewSecure(req.Root, triedb)
  381. if err != nil {
  382. // We don't have the requested state available, bail out
  383. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{ID: req.ID})
  384. }
  385. snap := backend.Chain().Snapshots().Snapshot(req.Root)
  386. if snap == nil {
  387. // We don't have the requested state snapshotted yet, bail out.
  388. // In reality we could still serve using the account and storage
  389. // tries only, but let's protect the node a bit while it's doing
  390. // snapshot generation.
  391. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{ID: req.ID})
  392. }
  393. // Retrieve trie nodes until the packet size limit is reached
  394. var (
  395. nodes [][]byte
  396. bytes uint64
  397. loads int // Trie hash expansions to cound database reads
  398. )
  399. for _, pathset := range req.Paths {
  400. switch len(pathset) {
  401. case 0:
  402. // Ensure we penalize invalid requests
  403. return fmt.Errorf("%w: zero-item pathset requested", errBadRequest)
  404. case 1:
  405. // If we're only retrieving an account trie node, fetch it directly
  406. blob, resolved, err := accTrie.TryGetNode(pathset[0])
  407. loads += resolved // always account database reads, even for failures
  408. if err != nil {
  409. break
  410. }
  411. nodes = append(nodes, blob)
  412. bytes += uint64(len(blob))
  413. default:
  414. // Storage slots requested, open the storage trie and retrieve from there
  415. account, err := snap.Account(common.BytesToHash(pathset[0]))
  416. loads++ // always account database reads, even for failures
  417. if err != nil {
  418. break
  419. }
  420. stTrie, err := trie.NewSecure(common.BytesToHash(account.Root), triedb)
  421. loads++ // always account database reads, even for failures
  422. if err != nil {
  423. break
  424. }
  425. for _, path := range pathset[1:] {
  426. blob, resolved, err := stTrie.TryGetNode(path)
  427. loads += resolved // always account database reads, even for failures
  428. if err != nil {
  429. break
  430. }
  431. nodes = append(nodes, blob)
  432. bytes += uint64(len(blob))
  433. // Sanity check limits to avoid DoS on the store trie loads
  434. if bytes > req.Bytes || loads > maxTrieNodeLookups {
  435. break
  436. }
  437. }
  438. }
  439. // Abort request processing if we've exceeded our limits
  440. if bytes > req.Bytes || loads > maxTrieNodeLookups {
  441. break
  442. }
  443. }
  444. // Send back anything accumulated
  445. return p2p.Send(peer.rw, TrieNodesMsg, &TrieNodesPacket{
  446. ID: req.ID,
  447. Nodes: nodes,
  448. })
  449. case msg.Code == TrieNodesMsg:
  450. // A batch of trie nodes arrived to one of our previous requests
  451. res := new(TrieNodesPacket)
  452. if err := msg.Decode(res); err != nil {
  453. return fmt.Errorf("%w: message %v: %v", errDecode, msg, err)
  454. }
  455. return backend.Handle(peer, res)
  456. default:
  457. return fmt.Errorf("%w: %v", errInvalidMsgCode, msg.Code)
  458. }
  459. }
  460. // NodeInfo represents a short summary of the `snap` sub-protocol metadata
  461. // known about the host peer.
  462. type NodeInfo struct{}
  463. // nodeInfo retrieves some `snap` protocol metadata about the running host node.
  464. func nodeInfo(chain *core.BlockChain) *NodeInfo {
  465. return &NodeInfo{}
  466. }