handler.go 18 KB

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