odr_requests.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. // Copyright 2016 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 les
  17. import (
  18. "encoding/binary"
  19. "errors"
  20. "fmt"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/rawdb"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/light"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. "github.com/ethereum/go-ethereum/trie"
  30. )
  31. var (
  32. errInvalidMessageType = errors.New("invalid message type")
  33. errInvalidEntryCount = errors.New("invalid number of response entries")
  34. errHeaderUnavailable = errors.New("header unavailable")
  35. errTxHashMismatch = errors.New("transaction hash mismatch")
  36. errUncleHashMismatch = errors.New("uncle hash mismatch")
  37. errReceiptHashMismatch = errors.New("receipt hash mismatch")
  38. errDataHashMismatch = errors.New("data hash mismatch")
  39. errCHTHashMismatch = errors.New("cht hash mismatch")
  40. errCHTNumberMismatch = errors.New("cht number mismatch")
  41. errUselessNodes = errors.New("useless nodes in merkle proof nodeset")
  42. )
  43. type LesOdrRequest interface {
  44. GetCost(*serverPeer) uint64
  45. CanSend(*serverPeer) bool
  46. Request(uint64, *serverPeer) error
  47. Validate(ethdb.Database, *Msg) error
  48. }
  49. func LesRequest(req light.OdrRequest) LesOdrRequest {
  50. switch r := req.(type) {
  51. case *light.BlockRequest:
  52. return (*BlockRequest)(r)
  53. case *light.ReceiptsRequest:
  54. return (*ReceiptsRequest)(r)
  55. case *light.TrieRequest:
  56. return (*TrieRequest)(r)
  57. case *light.CodeRequest:
  58. return (*CodeRequest)(r)
  59. case *light.ChtRequest:
  60. return (*ChtRequest)(r)
  61. case *light.BloomRequest:
  62. return (*BloomRequest)(r)
  63. case *light.TxStatusRequest:
  64. return (*TxStatusRequest)(r)
  65. default:
  66. return nil
  67. }
  68. }
  69. // BlockRequest is the ODR request type for block bodies
  70. type BlockRequest light.BlockRequest
  71. // GetCost returns the cost of the given ODR request according to the serving
  72. // peer's cost table (implementation of LesOdrRequest)
  73. func (r *BlockRequest) GetCost(peer *serverPeer) uint64 {
  74. return peer.getRequestCost(GetBlockBodiesMsg, 1)
  75. }
  76. // CanSend tells if a certain peer is suitable for serving the given request
  77. func (r *BlockRequest) CanSend(peer *serverPeer) bool {
  78. return peer.HasBlock(r.Hash, r.Number, false)
  79. }
  80. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  81. func (r *BlockRequest) Request(reqID uint64, peer *serverPeer) error {
  82. peer.Log().Debug("Requesting block body", "hash", r.Hash)
  83. return peer.requestBodies(reqID, []common.Hash{r.Hash})
  84. }
  85. // Valid processes an ODR request reply message from the LES network
  86. // returns true and stores results in memory if the message was a valid reply
  87. // to the request (implementation of LesOdrRequest)
  88. func (r *BlockRequest) Validate(db ethdb.Database, msg *Msg) error {
  89. log.Debug("Validating block body", "hash", r.Hash)
  90. // Ensure we have a correct message with a single block body
  91. if msg.MsgType != MsgBlockBodies {
  92. return errInvalidMessageType
  93. }
  94. bodies := msg.Obj.([]*types.Body)
  95. if len(bodies) != 1 {
  96. return errInvalidEntryCount
  97. }
  98. body := bodies[0]
  99. // Retrieve our stored header and validate block content against it
  100. if r.Header == nil {
  101. r.Header = rawdb.ReadHeader(db, r.Hash, r.Number)
  102. }
  103. if r.Header == nil {
  104. return errHeaderUnavailable
  105. }
  106. if r.Header.TxHash != types.DeriveSha(types.Transactions(body.Transactions), new(trie.Trie)) {
  107. return errTxHashMismatch
  108. }
  109. if r.Header.UncleHash != types.CalcUncleHash(body.Uncles) {
  110. return errUncleHashMismatch
  111. }
  112. // Validations passed, encode and store RLP
  113. data, err := rlp.EncodeToBytes(body)
  114. if err != nil {
  115. return err
  116. }
  117. r.Rlp = data
  118. return nil
  119. }
  120. // ReceiptsRequest is the ODR request type for block receipts by block hash
  121. type ReceiptsRequest light.ReceiptsRequest
  122. // GetCost returns the cost of the given ODR request according to the serving
  123. // peer's cost table (implementation of LesOdrRequest)
  124. func (r *ReceiptsRequest) GetCost(peer *serverPeer) uint64 {
  125. return peer.getRequestCost(GetReceiptsMsg, 1)
  126. }
  127. // CanSend tells if a certain peer is suitable for serving the given request
  128. func (r *ReceiptsRequest) CanSend(peer *serverPeer) bool {
  129. return peer.HasBlock(r.Hash, r.Number, false)
  130. }
  131. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  132. func (r *ReceiptsRequest) Request(reqID uint64, peer *serverPeer) error {
  133. peer.Log().Debug("Requesting block receipts", "hash", r.Hash)
  134. return peer.requestReceipts(reqID, []common.Hash{r.Hash})
  135. }
  136. // Valid processes an ODR request reply message from the LES network
  137. // returns true and stores results in memory if the message was a valid reply
  138. // to the request (implementation of LesOdrRequest)
  139. func (r *ReceiptsRequest) Validate(db ethdb.Database, msg *Msg) error {
  140. log.Debug("Validating block receipts", "hash", r.Hash)
  141. // Ensure we have a correct message with a single block receipt
  142. if msg.MsgType != MsgReceipts {
  143. return errInvalidMessageType
  144. }
  145. receipts := msg.Obj.([]types.Receipts)
  146. if len(receipts) != 1 {
  147. return errInvalidEntryCount
  148. }
  149. receipt := receipts[0]
  150. // Retrieve our stored header and validate receipt content against it
  151. if r.Header == nil {
  152. r.Header = rawdb.ReadHeader(db, r.Hash, r.Number)
  153. }
  154. if r.Header == nil {
  155. return errHeaderUnavailable
  156. }
  157. if r.Header.ReceiptHash != types.DeriveSha(receipt, new(trie.Trie)) {
  158. return errReceiptHashMismatch
  159. }
  160. // Validations passed, store and return
  161. r.Receipts = receipt
  162. return nil
  163. }
  164. type ProofReq struct {
  165. BHash common.Hash
  166. AccKey, Key []byte
  167. FromLevel uint
  168. }
  169. // ODR request type for state/storage trie entries, see LesOdrRequest interface
  170. type TrieRequest light.TrieRequest
  171. // GetCost returns the cost of the given ODR request according to the serving
  172. // peer's cost table (implementation of LesOdrRequest)
  173. func (r *TrieRequest) GetCost(peer *serverPeer) uint64 {
  174. return peer.getRequestCost(GetProofsV2Msg, 1)
  175. }
  176. // CanSend tells if a certain peer is suitable for serving the given request
  177. func (r *TrieRequest) CanSend(peer *serverPeer) bool {
  178. return peer.HasBlock(r.Id.BlockHash, r.Id.BlockNumber, true)
  179. }
  180. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  181. func (r *TrieRequest) Request(reqID uint64, peer *serverPeer) error {
  182. peer.Log().Debug("Requesting trie proof", "root", r.Id.Root, "key", r.Key)
  183. req := ProofReq{
  184. BHash: r.Id.BlockHash,
  185. AccKey: r.Id.AccKey,
  186. Key: r.Key,
  187. }
  188. return peer.requestProofs(reqID, []ProofReq{req})
  189. }
  190. // Valid processes an ODR request reply message from the LES network
  191. // returns true and stores results in memory if the message was a valid reply
  192. // to the request (implementation of LesOdrRequest)
  193. func (r *TrieRequest) Validate(db ethdb.Database, msg *Msg) error {
  194. log.Debug("Validating trie proof", "root", r.Id.Root, "key", r.Key)
  195. if msg.MsgType != MsgProofsV2 {
  196. return errInvalidMessageType
  197. }
  198. proofs := msg.Obj.(light.NodeList)
  199. // Verify the proof and store if checks out
  200. nodeSet := proofs.NodeSet()
  201. reads := &readTraceDB{db: nodeSet}
  202. if _, err := trie.VerifyProof(r.Id.Root, r.Key, reads); err != nil {
  203. return fmt.Errorf("merkle proof verification failed: %v", err)
  204. }
  205. // check if all nodes have been read by VerifyProof
  206. if len(reads.reads) != nodeSet.KeyCount() {
  207. return errUselessNodes
  208. }
  209. r.Proof = nodeSet
  210. return nil
  211. }
  212. type CodeReq struct {
  213. BHash common.Hash
  214. AccKey []byte
  215. }
  216. // ODR request type for node data (used for retrieving contract code), see LesOdrRequest interface
  217. type CodeRequest light.CodeRequest
  218. // GetCost returns the cost of the given ODR request according to the serving
  219. // peer's cost table (implementation of LesOdrRequest)
  220. func (r *CodeRequest) GetCost(peer *serverPeer) uint64 {
  221. return peer.getRequestCost(GetCodeMsg, 1)
  222. }
  223. // CanSend tells if a certain peer is suitable for serving the given request
  224. func (r *CodeRequest) CanSend(peer *serverPeer) bool {
  225. return peer.HasBlock(r.Id.BlockHash, r.Id.BlockNumber, true)
  226. }
  227. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  228. func (r *CodeRequest) Request(reqID uint64, peer *serverPeer) error {
  229. peer.Log().Debug("Requesting code data", "hash", r.Hash)
  230. req := CodeReq{
  231. BHash: r.Id.BlockHash,
  232. AccKey: r.Id.AccKey,
  233. }
  234. return peer.requestCode(reqID, []CodeReq{req})
  235. }
  236. // Valid processes an ODR request reply message from the LES network
  237. // returns true and stores results in memory if the message was a valid reply
  238. // to the request (implementation of LesOdrRequest)
  239. func (r *CodeRequest) Validate(db ethdb.Database, msg *Msg) error {
  240. log.Debug("Validating code data", "hash", r.Hash)
  241. // Ensure we have a correct message with a single code element
  242. if msg.MsgType != MsgCode {
  243. return errInvalidMessageType
  244. }
  245. reply := msg.Obj.([][]byte)
  246. if len(reply) != 1 {
  247. return errInvalidEntryCount
  248. }
  249. data := reply[0]
  250. // Verify the data and store if checks out
  251. if hash := crypto.Keccak256Hash(data); r.Hash != hash {
  252. return errDataHashMismatch
  253. }
  254. r.Data = data
  255. return nil
  256. }
  257. const (
  258. // helper trie type constants
  259. htCanonical = iota // Canonical hash trie
  260. htBloomBits // BloomBits trie
  261. // applicable for all helper trie requests
  262. auxRoot = 1
  263. // applicable for htCanonical
  264. auxHeader = 2
  265. )
  266. type HelperTrieReq struct {
  267. Type uint
  268. TrieIdx uint64
  269. Key []byte
  270. FromLevel, AuxReq uint
  271. }
  272. type HelperTrieResps struct { // describes all responses, not just a single one
  273. Proofs light.NodeList
  274. AuxData [][]byte
  275. }
  276. // ODR request type for requesting headers by Canonical Hash Trie, see LesOdrRequest interface
  277. type ChtRequest light.ChtRequest
  278. // GetCost returns the cost of the given ODR request according to the serving
  279. // peer's cost table (implementation of LesOdrRequest)
  280. func (r *ChtRequest) GetCost(peer *serverPeer) uint64 {
  281. return peer.getRequestCost(GetHelperTrieProofsMsg, 1)
  282. }
  283. // CanSend tells if a certain peer is suitable for serving the given request
  284. func (r *ChtRequest) CanSend(peer *serverPeer) bool {
  285. peer.lock.RLock()
  286. defer peer.lock.RUnlock()
  287. return peer.headInfo.Number >= r.Config.ChtConfirms && r.ChtNum <= (peer.headInfo.Number-r.Config.ChtConfirms)/r.Config.ChtSize
  288. }
  289. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  290. func (r *ChtRequest) Request(reqID uint64, peer *serverPeer) error {
  291. peer.Log().Debug("Requesting CHT", "cht", r.ChtNum, "block", r.BlockNum)
  292. var encNum [8]byte
  293. binary.BigEndian.PutUint64(encNum[:], r.BlockNum)
  294. req := HelperTrieReq{
  295. Type: htCanonical,
  296. TrieIdx: r.ChtNum,
  297. Key: encNum[:],
  298. AuxReq: auxHeader,
  299. }
  300. return peer.requestHelperTrieProofs(reqID, []HelperTrieReq{req})
  301. }
  302. // Valid processes an ODR request reply message from the LES network
  303. // returns true and stores results in memory if the message was a valid reply
  304. // to the request (implementation of LesOdrRequest)
  305. func (r *ChtRequest) Validate(db ethdb.Database, msg *Msg) error {
  306. log.Debug("Validating CHT", "cht", r.ChtNum, "block", r.BlockNum)
  307. if msg.MsgType != MsgHelperTrieProofs {
  308. return errInvalidMessageType
  309. }
  310. resp := msg.Obj.(HelperTrieResps)
  311. if len(resp.AuxData) != 1 {
  312. return errInvalidEntryCount
  313. }
  314. nodeSet := resp.Proofs.NodeSet()
  315. headerEnc := resp.AuxData[0]
  316. if len(headerEnc) == 0 {
  317. return errHeaderUnavailable
  318. }
  319. header := new(types.Header)
  320. if err := rlp.DecodeBytes(headerEnc, header); err != nil {
  321. return errHeaderUnavailable
  322. }
  323. // Verify the CHT
  324. var (
  325. node light.ChtNode
  326. encNumber [8]byte
  327. )
  328. binary.BigEndian.PutUint64(encNumber[:], r.BlockNum)
  329. reads := &readTraceDB{db: nodeSet}
  330. value, err := trie.VerifyProof(r.ChtRoot, encNumber[:], reads)
  331. if err != nil {
  332. return fmt.Errorf("merkle proof verification failed: %v", err)
  333. }
  334. if len(reads.reads) != nodeSet.KeyCount() {
  335. return errUselessNodes
  336. }
  337. if err := rlp.DecodeBytes(value, &node); err != nil {
  338. return err
  339. }
  340. if node.Hash != header.Hash() {
  341. return errCHTHashMismatch
  342. }
  343. if r.BlockNum != header.Number.Uint64() {
  344. return errCHTNumberMismatch
  345. }
  346. // Verifications passed, store and return
  347. r.Header = header
  348. r.Proof = nodeSet
  349. r.Td = node.Td
  350. return nil
  351. }
  352. type BloomReq struct {
  353. BloomTrieNum, BitIdx, SectionIndex, FromLevel uint64
  354. }
  355. // ODR request type for requesting headers by Canonical Hash Trie, see LesOdrRequest interface
  356. type BloomRequest light.BloomRequest
  357. // GetCost returns the cost of the given ODR request according to the serving
  358. // peer's cost table (implementation of LesOdrRequest)
  359. func (r *BloomRequest) GetCost(peer *serverPeer) uint64 {
  360. return peer.getRequestCost(GetHelperTrieProofsMsg, len(r.SectionIndexList))
  361. }
  362. // CanSend tells if a certain peer is suitable for serving the given request
  363. func (r *BloomRequest) CanSend(peer *serverPeer) bool {
  364. peer.lock.RLock()
  365. defer peer.lock.RUnlock()
  366. if peer.version < lpv2 {
  367. return false
  368. }
  369. return peer.headInfo.Number >= r.Config.BloomTrieConfirms && r.BloomTrieNum <= (peer.headInfo.Number-r.Config.BloomTrieConfirms)/r.Config.BloomTrieSize
  370. }
  371. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  372. func (r *BloomRequest) Request(reqID uint64, peer *serverPeer) error {
  373. peer.Log().Debug("Requesting BloomBits", "bloomTrie", r.BloomTrieNum, "bitIdx", r.BitIdx, "sections", r.SectionIndexList)
  374. reqs := make([]HelperTrieReq, len(r.SectionIndexList))
  375. var encNumber [10]byte
  376. binary.BigEndian.PutUint16(encNumber[:2], uint16(r.BitIdx))
  377. for i, sectionIdx := range r.SectionIndexList {
  378. binary.BigEndian.PutUint64(encNumber[2:], sectionIdx)
  379. reqs[i] = HelperTrieReq{
  380. Type: htBloomBits,
  381. TrieIdx: r.BloomTrieNum,
  382. Key: common.CopyBytes(encNumber[:]),
  383. }
  384. }
  385. return peer.requestHelperTrieProofs(reqID, reqs)
  386. }
  387. // Valid processes an ODR request reply message from the LES network
  388. // returns true and stores results in memory if the message was a valid reply
  389. // to the request (implementation of LesOdrRequest)
  390. func (r *BloomRequest) Validate(db ethdb.Database, msg *Msg) error {
  391. log.Debug("Validating BloomBits", "bloomTrie", r.BloomTrieNum, "bitIdx", r.BitIdx, "sections", r.SectionIndexList)
  392. // Ensure we have a correct message with a single proof element
  393. if msg.MsgType != MsgHelperTrieProofs {
  394. return errInvalidMessageType
  395. }
  396. resps := msg.Obj.(HelperTrieResps)
  397. proofs := resps.Proofs
  398. nodeSet := proofs.NodeSet()
  399. reads := &readTraceDB{db: nodeSet}
  400. r.BloomBits = make([][]byte, len(r.SectionIndexList))
  401. // Verify the proofs
  402. var encNumber [10]byte
  403. binary.BigEndian.PutUint16(encNumber[:2], uint16(r.BitIdx))
  404. for i, idx := range r.SectionIndexList {
  405. binary.BigEndian.PutUint64(encNumber[2:], idx)
  406. value, err := trie.VerifyProof(r.BloomTrieRoot, encNumber[:], reads)
  407. if err != nil {
  408. return err
  409. }
  410. r.BloomBits[i] = value
  411. }
  412. if len(reads.reads) != nodeSet.KeyCount() {
  413. return errUselessNodes
  414. }
  415. r.Proofs = nodeSet
  416. return nil
  417. }
  418. // TxStatusRequest is the ODR request type for transaction status
  419. type TxStatusRequest light.TxStatusRequest
  420. // GetCost returns the cost of the given ODR request according to the serving
  421. // peer's cost table (implementation of LesOdrRequest)
  422. func (r *TxStatusRequest) GetCost(peer *serverPeer) uint64 {
  423. return peer.getRequestCost(GetTxStatusMsg, len(r.Hashes))
  424. }
  425. // CanSend tells if a certain peer is suitable for serving the given request
  426. func (r *TxStatusRequest) CanSend(peer *serverPeer) bool {
  427. return peer.version >= lpv2
  428. }
  429. // Request sends an ODR request to the LES network (implementation of LesOdrRequest)
  430. func (r *TxStatusRequest) Request(reqID uint64, peer *serverPeer) error {
  431. peer.Log().Debug("Requesting transaction status", "count", len(r.Hashes))
  432. return peer.requestTxStatus(reqID, r.Hashes)
  433. }
  434. // Valid processes an ODR request reply message from the LES network
  435. // returns true and stores results in memory if the message was a valid reply
  436. // to the request (implementation of LesOdrRequest)
  437. func (r *TxStatusRequest) Validate(db ethdb.Database, msg *Msg) error {
  438. log.Debug("Validating transaction status", "count", len(r.Hashes))
  439. // Ensure we have a correct message with a single block body
  440. if msg.MsgType != MsgTxStatus {
  441. return errInvalidMessageType
  442. }
  443. status := msg.Obj.([]light.TxStatus)
  444. if len(status) != len(r.Hashes) {
  445. return errInvalidEntryCount
  446. }
  447. r.Status = status
  448. return nil
  449. }
  450. // readTraceDB stores the keys of database reads. We use this to check that received node
  451. // sets contain only the trie nodes necessary to make proofs pass.
  452. type readTraceDB struct {
  453. db ethdb.KeyValueReader
  454. reads map[string]struct{}
  455. }
  456. // Get returns a stored node
  457. func (db *readTraceDB) Get(k []byte) ([]byte, error) {
  458. if db.reads == nil {
  459. db.reads = make(map[string]struct{})
  460. }
  461. db.reads[string(k)] = struct{}{}
  462. return db.db.Get(k)
  463. }
  464. // Has returns true if the node set contains the given key
  465. func (db *readTraceDB) Has(key []byte) (bool, error) {
  466. _, err := db.Get(key)
  467. return err == nil, nil
  468. }