odr_util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 light
  17. import (
  18. "bytes"
  19. "context"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. var sha3Nil = crypto.Keccak256Hash(nil)
  29. // GetHeaderByNumber retrieves the canonical block header corresponding to the
  30. // given number.
  31. func GetHeaderByNumber(ctx context.Context, odr OdrBackend, number uint64) (*types.Header, error) {
  32. // Try to find it in the local database first.
  33. db := odr.Database()
  34. hash := rawdb.ReadCanonicalHash(db, number)
  35. // If there is a canonical hash, there should have a header too.
  36. // But if it's pruned, re-fetch from network again.
  37. if (hash != common.Hash{}) {
  38. if header := rawdb.ReadHeader(db, hash, number); header != nil {
  39. return header, nil
  40. }
  41. }
  42. // Retrieve the header via ODR, ensure the requested header is covered
  43. // by local trusted CHT.
  44. chts, _, chtHead := odr.ChtIndexer().Sections()
  45. if number >= chts*odr.IndexerConfig().ChtSize {
  46. return nil, errNoTrustedCht
  47. }
  48. r := &ChtRequest{
  49. ChtRoot: GetChtRoot(db, chts-1, chtHead),
  50. ChtNum: chts - 1,
  51. BlockNum: number,
  52. Config: odr.IndexerConfig(),
  53. }
  54. if err := odr.Retrieve(ctx, r); err != nil {
  55. return nil, err
  56. }
  57. return r.Header, nil
  58. }
  59. // GetUntrustedHeaderByNumber retrieves specified block header without
  60. // correctness checking. Note this function should only be used in light
  61. // client checkpoint syncing.
  62. func GetUntrustedHeaderByNumber(ctx context.Context, odr OdrBackend, number uint64, peerId string) (*types.Header, error) {
  63. // todo(rjl493456442) it's a hack to retrieve headers which is not covered
  64. // by CHT. Fix it in LES4
  65. r := &ChtRequest{
  66. BlockNum: number,
  67. ChtNum: number / odr.IndexerConfig().ChtSize,
  68. Untrusted: true,
  69. PeerId: peerId,
  70. Config: odr.IndexerConfig(),
  71. }
  72. if err := odr.Retrieve(ctx, r); err != nil {
  73. return nil, err
  74. }
  75. return r.Header, nil
  76. }
  77. // GetCanonicalHash retrieves the canonical block hash corresponding to the number.
  78. func GetCanonicalHash(ctx context.Context, odr OdrBackend, number uint64) (common.Hash, error) {
  79. hash := rawdb.ReadCanonicalHash(odr.Database(), number)
  80. if hash != (common.Hash{}) {
  81. return hash, nil
  82. }
  83. header, err := GetHeaderByNumber(ctx, odr, number)
  84. if err != nil {
  85. return common.Hash{}, err
  86. }
  87. // number -> canonical mapping already be stored in db, get it.
  88. return header.Hash(), nil
  89. }
  90. // GetTd retrieves the total difficulty corresponding to the number and hash.
  91. func GetTd(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) (*big.Int, error) {
  92. td := rawdb.ReadTd(odr.Database(), hash, number)
  93. if td != nil {
  94. return td, nil
  95. }
  96. _, err := GetHeaderByNumber(ctx, odr, number)
  97. if err != nil {
  98. return nil, err
  99. }
  100. // <hash, number> -> td mapping already be stored in db, get it.
  101. return rawdb.ReadTd(odr.Database(), hash, number), nil
  102. }
  103. // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  104. func GetBodyRLP(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) (rlp.RawValue, error) {
  105. if data := rawdb.ReadBodyRLP(odr.Database(), hash, number); data != nil {
  106. return data, nil
  107. }
  108. // Retrieve the block header first and pass it for verification.
  109. header, err := GetHeaderByNumber(ctx, odr, number)
  110. if err != nil {
  111. return nil, errNoHeader
  112. }
  113. r := &BlockRequest{Hash: hash, Number: number, Header: header}
  114. if err := odr.Retrieve(ctx, r); err != nil {
  115. return nil, err
  116. }
  117. return r.Rlp, nil
  118. }
  119. // GetBody retrieves the block body (transactions, uncles) corresponding to the
  120. // hash.
  121. func GetBody(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) (*types.Body, error) {
  122. data, err := GetBodyRLP(ctx, odr, hash, number)
  123. if err != nil {
  124. return nil, err
  125. }
  126. body := new(types.Body)
  127. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  128. return nil, err
  129. }
  130. return body, nil
  131. }
  132. // GetBlock retrieves an entire block corresponding to the hash, assembling it
  133. // back from the stored header and body.
  134. func GetBlock(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) (*types.Block, error) {
  135. // Retrieve the block header and body contents
  136. header, err := GetHeaderByNumber(ctx, odr, number)
  137. if err != nil {
  138. return nil, errNoHeader
  139. }
  140. body, err := GetBody(ctx, odr, hash, number)
  141. if err != nil {
  142. return nil, err
  143. }
  144. // Reassemble the block and return
  145. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles), nil
  146. }
  147. // GetBlockReceipts retrieves the receipts generated by the transactions included
  148. // in a block given by its hash.
  149. func GetBlockReceipts(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) (types.Receipts, error) {
  150. // Assume receipts are already stored locally and attempt to retrieve.
  151. receipts := rawdb.ReadRawReceipts(odr.Database(), hash, number)
  152. if receipts == nil {
  153. header, err := GetHeaderByNumber(ctx, odr, number)
  154. if err != nil {
  155. return nil, errNoHeader
  156. }
  157. r := &ReceiptsRequest{Hash: hash, Number: number, Header: header}
  158. if err := odr.Retrieve(ctx, r); err != nil {
  159. return nil, err
  160. }
  161. receipts = r.Receipts
  162. }
  163. // If the receipts are incomplete, fill the derived fields
  164. if len(receipts) > 0 && receipts[0].TxHash == (common.Hash{}) {
  165. block, err := GetBlock(ctx, odr, hash, number)
  166. if err != nil {
  167. return nil, err
  168. }
  169. genesis := rawdb.ReadCanonicalHash(odr.Database(), 0)
  170. config := rawdb.ReadChainConfig(odr.Database(), genesis)
  171. if err := receipts.DeriveFields(config, block.Hash(), block.NumberU64(), block.Transactions()); err != nil {
  172. return nil, err
  173. }
  174. rawdb.WriteReceipts(odr.Database(), hash, number, receipts)
  175. }
  176. return receipts, nil
  177. }
  178. // GetBlockLogs retrieves the logs generated by the transactions included in a
  179. // block given by its hash.
  180. func GetBlockLogs(ctx context.Context, odr OdrBackend, hash common.Hash, number uint64) ([][]*types.Log, error) {
  181. // Retrieve the potentially incomplete receipts from disk or network
  182. receipts, err := GetBlockReceipts(ctx, odr, hash, number)
  183. if err != nil {
  184. return nil, err
  185. }
  186. logs := make([][]*types.Log, len(receipts))
  187. for i, receipt := range receipts {
  188. logs[i] = receipt.Logs
  189. }
  190. return logs, nil
  191. }
  192. // GetUntrustedBlockLogs retrieves the logs generated by the transactions included in a
  193. // block. The retrieved logs are regarded as untrusted and will not be stored in the
  194. // database. This function should only be used in light client checkpoint syncing.
  195. func GetUntrustedBlockLogs(ctx context.Context, odr OdrBackend, header *types.Header) ([][]*types.Log, error) {
  196. // Retrieve the potentially incomplete receipts from disk or network
  197. hash, number := header.Hash(), header.Number.Uint64()
  198. receipts := rawdb.ReadRawReceipts(odr.Database(), hash, number)
  199. if receipts == nil {
  200. r := &ReceiptsRequest{Hash: hash, Number: number, Header: header, Untrusted: true}
  201. if err := odr.Retrieve(ctx, r); err != nil {
  202. return nil, err
  203. }
  204. receipts = r.Receipts
  205. // Untrusted receipts won't be stored in the database. Therefore
  206. // derived fields computation is unnecessary.
  207. }
  208. // Return the logs without deriving any computed fields on the receipts
  209. logs := make([][]*types.Log, len(receipts))
  210. for i, receipt := range receipts {
  211. logs[i] = receipt.Logs
  212. }
  213. return logs, nil
  214. }
  215. // GetBloomBits retrieves a batch of compressed bloomBits vectors belonging to
  216. // the given bit index and section indexes.
  217. func GetBloomBits(ctx context.Context, odr OdrBackend, bit uint, sections []uint64) ([][]byte, error) {
  218. var (
  219. reqIndex []int
  220. reqSections []uint64
  221. db = odr.Database()
  222. result = make([][]byte, len(sections))
  223. )
  224. blooms, _, sectionHead := odr.BloomTrieIndexer().Sections()
  225. for i, section := range sections {
  226. sectionHead := rawdb.ReadCanonicalHash(db, (section+1)*odr.IndexerConfig().BloomSize-1)
  227. // If we don't have the canonical hash stored for this section head number,
  228. // we'll still look for an entry with a zero sectionHead (we store it with
  229. // zero section head too if we don't know it at the time of the retrieval)
  230. if bloomBits, _ := rawdb.ReadBloomBits(db, bit, section, sectionHead); len(bloomBits) != 0 {
  231. result[i] = bloomBits
  232. continue
  233. }
  234. // TODO(rjl493456442) Convert sectionIndex to BloomTrie relative index
  235. if section >= blooms {
  236. return nil, errNoTrustedBloomTrie
  237. }
  238. reqSections = append(reqSections, section)
  239. reqIndex = append(reqIndex, i)
  240. }
  241. // Find all bloombits in database, nothing to query via odr, return.
  242. if reqSections == nil {
  243. return result, nil
  244. }
  245. // Send odr request to retrieve missing bloombits.
  246. r := &BloomRequest{
  247. BloomTrieRoot: GetBloomTrieRoot(db, blooms-1, sectionHead),
  248. BloomTrieNum: blooms - 1,
  249. BitIdx: bit,
  250. SectionIndexList: reqSections,
  251. Config: odr.IndexerConfig(),
  252. }
  253. if err := odr.Retrieve(ctx, r); err != nil {
  254. return nil, err
  255. }
  256. for i, idx := range reqIndex {
  257. result[idx] = r.BloomBits[i]
  258. }
  259. return result, nil
  260. }
  261. // GetTransaction retrieves a canonical transaction by hash and also returns its position in the chain
  262. func GetTransaction(ctx context.Context, odr OdrBackend, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
  263. r := &TxStatusRequest{Hashes: []common.Hash{txHash}}
  264. if err := odr.Retrieve(ctx, r); err != nil || r.Status[0].Status != core.TxStatusIncluded {
  265. return nil, common.Hash{}, 0, 0, err
  266. }
  267. pos := r.Status[0].Lookup
  268. // first ensure that we have the header, otherwise block body retrieval will fail
  269. // also verify if this is a canonical block by getting the header by number and checking its hash
  270. if header, err := GetHeaderByNumber(ctx, odr, pos.BlockIndex); err != nil || header.Hash() != pos.BlockHash {
  271. return nil, common.Hash{}, 0, 0, err
  272. }
  273. body, err := GetBody(ctx, odr, pos.BlockHash, pos.BlockIndex)
  274. if err != nil || uint64(len(body.Transactions)) <= pos.Index || body.Transactions[pos.Index].Hash() != txHash {
  275. return nil, common.Hash{}, 0, 0, err
  276. }
  277. return body.Transactions[pos.Index], pos.BlockHash, pos.BlockIndex, pos.Index, nil
  278. }