accessors_chain.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. // Copyright 2018 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 rawdb
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "math/big"
  21. "sort"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/params"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. // ReadCanonicalHash retrieves the hash assigned to a canonical block number.
  30. func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash {
  31. data, _ := db.Ancient(freezerHashTable, number)
  32. if len(data) == 0 {
  33. data, _ = db.Get(headerHashKey(number))
  34. // In the background freezer is moving data from leveldb to flatten files.
  35. // So during the first check for ancient db, the data is not yet in there,
  36. // but when we reach into leveldb, the data was already moved. That would
  37. // result in a not found error.
  38. if len(data) == 0 {
  39. data, _ = db.Ancient(freezerHashTable, number)
  40. }
  41. }
  42. if len(data) == 0 {
  43. return common.Hash{}
  44. }
  45. return common.BytesToHash(data)
  46. }
  47. // WriteCanonicalHash stores the hash assigned to a canonical block number.
  48. func WriteCanonicalHash(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  49. if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil {
  50. log.Crit("Failed to store number to hash mapping", "err", err)
  51. }
  52. }
  53. // DeleteCanonicalHash removes the number to hash canonical mapping.
  54. func DeleteCanonicalHash(db ethdb.KeyValueWriter, number uint64) {
  55. if err := db.Delete(headerHashKey(number)); err != nil {
  56. log.Crit("Failed to delete number to hash mapping", "err", err)
  57. }
  58. }
  59. // ReadAllHashes retrieves all the hashes assigned to blocks at a certain heights,
  60. // both canonical and reorged forks included.
  61. func ReadAllHashes(db ethdb.Iteratee, number uint64) []common.Hash {
  62. prefix := headerKeyPrefix(number)
  63. hashes := make([]common.Hash, 0, 1)
  64. it := db.NewIterator(prefix, nil)
  65. defer it.Release()
  66. for it.Next() {
  67. if key := it.Key(); len(key) == len(prefix)+32 {
  68. hashes = append(hashes, common.BytesToHash(key[len(key)-32:]))
  69. }
  70. }
  71. return hashes
  72. }
  73. // ReadAllCanonicalHashes retrieves all canonical number and hash mappings at the
  74. // certain chain range. If the accumulated entries reaches the given threshold,
  75. // abort the iteration and return the semi-finish result.
  76. func ReadAllCanonicalHashes(db ethdb.Iteratee, from uint64, to uint64, limit int) ([]uint64, []common.Hash) {
  77. // Short circuit if the limit is 0.
  78. if limit == 0 {
  79. return nil, nil
  80. }
  81. var (
  82. numbers []uint64
  83. hashes []common.Hash
  84. )
  85. // Construct the key prefix of start point.
  86. start, end := headerHashKey(from), headerHashKey(to)
  87. it := db.NewIterator(nil, start)
  88. defer it.Release()
  89. for it.Next() {
  90. if bytes.Compare(it.Key(), end) >= 0 {
  91. break
  92. }
  93. if key := it.Key(); len(key) == len(headerPrefix)+8+1 && bytes.Equal(key[len(key)-1:], headerHashSuffix) {
  94. numbers = append(numbers, binary.BigEndian.Uint64(key[len(headerPrefix):len(headerPrefix)+8]))
  95. hashes = append(hashes, common.BytesToHash(it.Value()))
  96. // If the accumulated entries reaches the limit threshold, return.
  97. if len(numbers) >= limit {
  98. break
  99. }
  100. }
  101. }
  102. return numbers, hashes
  103. }
  104. // ReadHeaderNumber returns the header number assigned to a hash.
  105. func ReadHeaderNumber(db ethdb.KeyValueReader, hash common.Hash) *uint64 {
  106. data, _ := db.Get(headerNumberKey(hash))
  107. if len(data) != 8 {
  108. return nil
  109. }
  110. number := binary.BigEndian.Uint64(data)
  111. return &number
  112. }
  113. // WriteHeaderNumber stores the hash->number mapping.
  114. func WriteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  115. key := headerNumberKey(hash)
  116. enc := encodeBlockNumber(number)
  117. if err := db.Put(key, enc); err != nil {
  118. log.Crit("Failed to store hash to number mapping", "err", err)
  119. }
  120. }
  121. // DeleteHeaderNumber removes hash->number mapping.
  122. func DeleteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash) {
  123. if err := db.Delete(headerNumberKey(hash)); err != nil {
  124. log.Crit("Failed to delete hash to number mapping", "err", err)
  125. }
  126. }
  127. // ReadHeadHeaderHash retrieves the hash of the current canonical head header.
  128. func ReadHeadHeaderHash(db ethdb.KeyValueReader) common.Hash {
  129. data, _ := db.Get(headHeaderKey)
  130. if len(data) == 0 {
  131. return common.Hash{}
  132. }
  133. return common.BytesToHash(data)
  134. }
  135. // WriteHeadHeaderHash stores the hash of the current canonical head header.
  136. func WriteHeadHeaderHash(db ethdb.KeyValueWriter, hash common.Hash) {
  137. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  138. log.Crit("Failed to store last header's hash", "err", err)
  139. }
  140. }
  141. // ReadHeadBlockHash retrieves the hash of the current canonical head block.
  142. func ReadHeadBlockHash(db ethdb.KeyValueReader) common.Hash {
  143. data, _ := db.Get(headBlockKey)
  144. if len(data) == 0 {
  145. return common.Hash{}
  146. }
  147. return common.BytesToHash(data)
  148. }
  149. // WriteHeadBlockHash stores the head block's hash.
  150. func WriteHeadBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  151. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  152. log.Crit("Failed to store last block's hash", "err", err)
  153. }
  154. }
  155. // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block.
  156. func ReadHeadFastBlockHash(db ethdb.KeyValueReader) common.Hash {
  157. data, _ := db.Get(headFastBlockKey)
  158. if len(data) == 0 {
  159. return common.Hash{}
  160. }
  161. return common.BytesToHash(data)
  162. }
  163. // WriteHeadFastBlockHash stores the hash of the current fast-sync head block.
  164. func WriteHeadFastBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  165. if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil {
  166. log.Crit("Failed to store last fast block's hash", "err", err)
  167. }
  168. }
  169. // ReadLastPivotNumber retrieves the number of the last pivot block. If the node
  170. // full synced, the last pivot will always be nil.
  171. func ReadLastPivotNumber(db ethdb.KeyValueReader) *uint64 {
  172. data, _ := db.Get(lastPivotKey)
  173. if len(data) == 0 {
  174. return nil
  175. }
  176. var pivot uint64
  177. if err := rlp.DecodeBytes(data, &pivot); err != nil {
  178. log.Error("Invalid pivot block number in database", "err", err)
  179. return nil
  180. }
  181. return &pivot
  182. }
  183. // WriteLastPivotNumber stores the number of the last pivot block.
  184. func WriteLastPivotNumber(db ethdb.KeyValueWriter, pivot uint64) {
  185. enc, err := rlp.EncodeToBytes(pivot)
  186. if err != nil {
  187. log.Crit("Failed to encode pivot block number", "err", err)
  188. }
  189. if err := db.Put(lastPivotKey, enc); err != nil {
  190. log.Crit("Failed to store pivot block number", "err", err)
  191. }
  192. }
  193. // ReadFastTrieProgress retrieves the number of tries nodes fast synced to allow
  194. // reporting correct numbers across restarts.
  195. func ReadFastTrieProgress(db ethdb.KeyValueReader) uint64 {
  196. data, _ := db.Get(fastTrieProgressKey)
  197. if len(data) == 0 {
  198. return 0
  199. }
  200. return new(big.Int).SetBytes(data).Uint64()
  201. }
  202. // WriteFastTrieProgress stores the fast sync trie process counter to support
  203. // retrieving it across restarts.
  204. func WriteFastTrieProgress(db ethdb.KeyValueWriter, count uint64) {
  205. if err := db.Put(fastTrieProgressKey, new(big.Int).SetUint64(count).Bytes()); err != nil {
  206. log.Crit("Failed to store fast sync trie progress", "err", err)
  207. }
  208. }
  209. // ReadTxIndexTail retrieves the number of oldest indexed block
  210. // whose transaction indices has been indexed. If the corresponding entry
  211. // is non-existent in database it means the indexing has been finished.
  212. func ReadTxIndexTail(db ethdb.KeyValueReader) *uint64 {
  213. data, _ := db.Get(txIndexTailKey)
  214. if len(data) != 8 {
  215. return nil
  216. }
  217. number := binary.BigEndian.Uint64(data)
  218. return &number
  219. }
  220. // WriteTxIndexTail stores the number of oldest indexed block
  221. // into database.
  222. func WriteTxIndexTail(db ethdb.KeyValueWriter, number uint64) {
  223. if err := db.Put(txIndexTailKey, encodeBlockNumber(number)); err != nil {
  224. log.Crit("Failed to store the transaction index tail", "err", err)
  225. }
  226. }
  227. // ReadFastTxLookupLimit retrieves the tx lookup limit used in fast sync.
  228. func ReadFastTxLookupLimit(db ethdb.KeyValueReader) *uint64 {
  229. data, _ := db.Get(fastTxLookupLimitKey)
  230. if len(data) != 8 {
  231. return nil
  232. }
  233. number := binary.BigEndian.Uint64(data)
  234. return &number
  235. }
  236. // WriteFastTxLookupLimit stores the txlookup limit used in fast sync into database.
  237. func WriteFastTxLookupLimit(db ethdb.KeyValueWriter, number uint64) {
  238. if err := db.Put(fastTxLookupLimitKey, encodeBlockNumber(number)); err != nil {
  239. log.Crit("Failed to store transaction lookup limit for fast sync", "err", err)
  240. }
  241. }
  242. // Quorum
  243. // ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
  244. func readHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) (rlp.RawValue, *types.Header) {
  245. // First try to look up the data in ancient database. Extra hash
  246. // comparison is necessary since ancient database only maintains
  247. // the canonical data.
  248. data, _ := db.Ancient(freezerHeaderTable, number)
  249. // Quorum: parse header to make sure we compare using the right hash (IBFT hash is based on a filtered header)
  250. if len(data) > 0 {
  251. header := decodeHeaderRLP(data)
  252. if header.Hash() == hash {
  253. return data, header
  254. }
  255. }
  256. // End Quorum
  257. // Then try to look up the data in leveldb.
  258. data, _ = db.Get(headerKey(number, hash))
  259. if len(data) > 0 {
  260. return data, decodeHeaderRLP(data) // Quorum: return decodeHeaderRLP(data)
  261. }
  262. // In the background freezer is moving data from leveldb to flatten files.
  263. // So during the first check for ancient db, the data is not yet in there,
  264. // but when we reach into leveldb, the data was already moved. That would
  265. // result in a not found error.
  266. data, _ = db.Ancient(freezerHeaderTable, number)
  267. // Quorum: parse header to make sure we compare using the right hash (IBFT hash is based on a filtered header)
  268. if len(data) > 0 {
  269. header := decodeHeaderRLP(data)
  270. if header.Hash() == hash {
  271. return data, header
  272. }
  273. }
  274. // End Quorum
  275. return nil, nil // Can't find the data anywhere.
  276. }
  277. // Quorum
  278. func decodeHeaderRLP(data rlp.RawValue) *types.Header {
  279. header := new(types.Header)
  280. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  281. log.Error("Invalid block header RLP", "err", err)
  282. return nil
  283. }
  284. return header
  285. }
  286. // ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
  287. func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  288. // Quorum: original code implemented inside `readHeaderRLP(...)` with some modifications from Quorum
  289. data, _ := readHeaderRLP(db, hash, number)
  290. return data
  291. }
  292. // HasHeader verifies the existence of a block header corresponding to the hash.
  293. func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool {
  294. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  295. return true
  296. }
  297. if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
  298. return false
  299. }
  300. return true
  301. }
  302. // ReadHeader retrieves the block header corresponding to the hash.
  303. func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header {
  304. data, header := readHeaderRLP(db, hash, number)
  305. if data == nil {
  306. log.Trace("header data not found in ancient or level db", "hash", hash)
  307. return nil
  308. }
  309. if header == nil {
  310. log.Error("Invalid block header RLP", "hash", hash)
  311. return nil
  312. }
  313. return header
  314. }
  315. // WriteHeader stores a block header into the database and also stores the hash-
  316. // to-number mapping.
  317. func WriteHeader(db ethdb.KeyValueWriter, header *types.Header) {
  318. var (
  319. hash = header.Hash()
  320. number = header.Number.Uint64()
  321. )
  322. // Write the hash -> number mapping
  323. WriteHeaderNumber(db, hash, number)
  324. // Write the encoded header
  325. data, err := rlp.EncodeToBytes(header)
  326. if err != nil {
  327. log.Crit("Failed to RLP encode header", "err", err)
  328. }
  329. key := headerKey(number, hash)
  330. if err := db.Put(key, data); err != nil {
  331. log.Crit("Failed to store header", "err", err)
  332. }
  333. }
  334. // DeleteHeader removes all block header data associated with a hash.
  335. func DeleteHeader(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  336. deleteHeaderWithoutNumber(db, hash, number)
  337. if err := db.Delete(headerNumberKey(hash)); err != nil {
  338. log.Crit("Failed to delete hash to number mapping", "err", err)
  339. }
  340. }
  341. // deleteHeaderWithoutNumber removes only the block header but does not remove
  342. // the hash to number mapping.
  343. func deleteHeaderWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  344. if err := db.Delete(headerKey(number, hash)); err != nil {
  345. log.Crit("Failed to delete header", "err", err)
  346. }
  347. }
  348. // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  349. func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  350. // First try to look up the data in ancient database. Extra hash
  351. // comparison is necessary since ancient database only maintains
  352. // the canonical data.
  353. data, _ := db.Ancient(freezerBodiesTable, number)
  354. if len(data) > 0 {
  355. h, _ := db.Ancient(freezerHashTable, number)
  356. if common.BytesToHash(h) == hash {
  357. return data
  358. }
  359. }
  360. // Then try to look up the data in leveldb.
  361. data, _ = db.Get(blockBodyKey(number, hash))
  362. if len(data) > 0 {
  363. return data
  364. }
  365. // In the background freezer is moving data from leveldb to flatten files.
  366. // So during the first check for ancient db, the data is not yet in there,
  367. // but when we reach into leveldb, the data was already moved. That would
  368. // result in a not found error.
  369. data, _ = db.Ancient(freezerBodiesTable, number)
  370. if len(data) > 0 {
  371. h, _ := db.Ancient(freezerHashTable, number)
  372. if common.BytesToHash(h) == hash {
  373. return data
  374. }
  375. }
  376. return nil // Can't find the data anywhere.
  377. }
  378. // ReadCanonicalBodyRLP retrieves the block body (transactions and uncles) for the canonical
  379. // block at number, in RLP encoding.
  380. func ReadCanonicalBodyRLP(db ethdb.Reader, number uint64) rlp.RawValue {
  381. // If it's an ancient one, we don't need the canonical hash
  382. data, _ := db.Ancient(freezerBodiesTable, number)
  383. if len(data) == 0 {
  384. // Need to get the hash
  385. data, _ = db.Get(blockBodyKey(number, ReadCanonicalHash(db, number)))
  386. // In the background freezer is moving data from leveldb to flatten files.
  387. // So during the first check for ancient db, the data is not yet in there,
  388. // but when we reach into leveldb, the data was already moved. That would
  389. // result in a not found error.
  390. if len(data) == 0 {
  391. data, _ = db.Ancient(freezerBodiesTable, number)
  392. }
  393. }
  394. return data
  395. }
  396. // WriteBodyRLP stores an RLP encoded block body into the database.
  397. func WriteBodyRLP(db ethdb.KeyValueWriter, hash common.Hash, number uint64, rlp rlp.RawValue) {
  398. if err := db.Put(blockBodyKey(number, hash), rlp); err != nil {
  399. log.Crit("Failed to store block body", "err", err)
  400. }
  401. }
  402. // HasBody verifies the existence of a block body corresponding to the hash.
  403. func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool {
  404. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  405. return true
  406. }
  407. if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
  408. return false
  409. }
  410. return true
  411. }
  412. // ReadBody retrieves the block body corresponding to the hash.
  413. func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body {
  414. data := ReadBodyRLP(db, hash, number)
  415. if len(data) == 0 {
  416. return nil
  417. }
  418. body := new(types.Body)
  419. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  420. log.Error("Invalid block body RLP", "hash", hash, "err", err)
  421. return nil
  422. }
  423. return body
  424. }
  425. // WriteBody stores a block body into the database.
  426. func WriteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64, body *types.Body) {
  427. data, err := rlp.EncodeToBytes(body)
  428. if err != nil {
  429. log.Crit("Failed to RLP encode body", "err", err)
  430. }
  431. WriteBodyRLP(db, hash, number, data)
  432. }
  433. // DeleteBody removes all block body data associated with a hash.
  434. func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  435. if err := db.Delete(blockBodyKey(number, hash)); err != nil {
  436. log.Crit("Failed to delete block body", "err", err)
  437. }
  438. }
  439. // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding.
  440. func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  441. // First try to look up the data in ancient database. Extra hash
  442. // comparison is necessary since ancient database only maintains
  443. // the canonical data.
  444. data, _ := db.Ancient(freezerDifficultyTable, number)
  445. if len(data) > 0 {
  446. h, _ := db.Ancient(freezerHashTable, number)
  447. if common.BytesToHash(h) == hash {
  448. return data
  449. }
  450. }
  451. // Then try to look up the data in leveldb.
  452. data, _ = db.Get(headerTDKey(number, hash))
  453. if len(data) > 0 {
  454. return data
  455. }
  456. // In the background freezer is moving data from leveldb to flatten files.
  457. // So during the first check for ancient db, the data is not yet in there,
  458. // but when we reach into leveldb, the data was already moved. That would
  459. // result in a not found error.
  460. data, _ = db.Ancient(freezerDifficultyTable, number)
  461. if len(data) > 0 {
  462. h, _ := db.Ancient(freezerHashTable, number)
  463. if common.BytesToHash(h) == hash {
  464. return data
  465. }
  466. }
  467. return nil // Can't find the data anywhere.
  468. }
  469. // ReadTd retrieves a block's total difficulty corresponding to the hash.
  470. func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int {
  471. data := ReadTdRLP(db, hash, number)
  472. if len(data) == 0 {
  473. return nil
  474. }
  475. td := new(big.Int)
  476. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  477. log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
  478. return nil
  479. }
  480. return td
  481. }
  482. // WriteTd stores the total difficulty of a block into the database.
  483. func WriteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64, td *big.Int) {
  484. data, err := rlp.EncodeToBytes(td)
  485. if err != nil {
  486. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  487. }
  488. if err := db.Put(headerTDKey(number, hash), data); err != nil {
  489. log.Crit("Failed to store block total difficulty", "err", err)
  490. }
  491. }
  492. // DeleteTd removes all block total difficulty data associated with a hash.
  493. func DeleteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  494. if err := db.Delete(headerTDKey(number, hash)); err != nil {
  495. log.Crit("Failed to delete block total difficulty", "err", err)
  496. }
  497. }
  498. // HasReceipts verifies the existence of all the transaction receipts belonging
  499. // to a block.
  500. func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool {
  501. if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash {
  502. return true
  503. }
  504. if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil {
  505. return false
  506. }
  507. return true
  508. }
  509. // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding.
  510. func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  511. // First try to look up the data in ancient database. Extra hash
  512. // comparison is necessary since ancient database only maintains
  513. // the canonical data.
  514. data, _ := db.Ancient(freezerReceiptTable, number)
  515. if len(data) > 0 {
  516. h, _ := db.Ancient(freezerHashTable, number)
  517. if common.BytesToHash(h) == hash {
  518. return data
  519. }
  520. }
  521. // Then try to look up the data in leveldb.
  522. data, _ = db.Get(blockReceiptsKey(number, hash))
  523. if len(data) > 0 {
  524. return data
  525. }
  526. // In the background freezer is moving data from leveldb to flatten files.
  527. // So during the first check for ancient db, the data is not yet in there,
  528. // but when we reach into leveldb, the data was already moved. That would
  529. // result in a not found error.
  530. data, _ = db.Ancient(freezerReceiptTable, number)
  531. if len(data) > 0 {
  532. h, _ := db.Ancient(freezerHashTable, number)
  533. if common.BytesToHash(h) == hash {
  534. return data
  535. }
  536. }
  537. return nil // Can't find the data anywhere.
  538. }
  539. // ReadRawReceipts retrieves all the transaction receipts belonging to a block.
  540. // The receipt metadata fields are not guaranteed to be populated, so they
  541. // should not be used. Use ReadReceipts instead if the metadata is needed.
  542. func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts {
  543. // Retrieve the flattened receipt slice
  544. data := ReadReceiptsRLP(db, hash, number)
  545. if len(data) == 0 {
  546. return nil
  547. }
  548. // split the data into the standard receipt rlp list and the quorum extraData bytes
  549. _, extraData, err := rlp.SplitList(data)
  550. if err != nil {
  551. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  552. return nil
  553. }
  554. // reslice data to remove extraData and get the receipt rlp list as the result from rlp.SplitList does not include the list header bytes
  555. vanillaDataWithListHeader := data[0 : len(data)-len(extraData)]
  556. // Convert the receipts from their storage form to their internal representation
  557. storageReceipts := []*types.ReceiptForStorage{}
  558. if err := rlp.DecodeBytes(vanillaDataWithListHeader, &storageReceipts); err != nil {
  559. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  560. return nil
  561. }
  562. receipts := make(types.Receipts, len(storageReceipts))
  563. for i, storageReceipt := range storageReceipts {
  564. receipts[i] = (*types.Receipt)(storageReceipt)
  565. }
  566. if len(extraData) > 0 {
  567. quorumExtraDataReceipts := []*types.QuorumReceiptExtraData{}
  568. if err := rlp.DecodeBytes(extraData, &quorumExtraDataReceipts); err != nil {
  569. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  570. return nil
  571. }
  572. for i, quorumExtraDataReceipt := range quorumExtraDataReceipts {
  573. if quorumExtraDataReceipt != nil {
  574. receipts[i].FillReceiptExtraDataFromStorage(quorumExtraDataReceipt)
  575. }
  576. }
  577. }
  578. return receipts
  579. }
  580. // ReadReceipts retrieves all the transaction receipts belonging to a block, including
  581. // its correspoinding metadata fields. If it is unable to populate these metadata
  582. // fields then nil is returned.
  583. //
  584. // The current implementation populates these metadata fields by reading the receipts'
  585. // corresponding block body, so if the block body is not found it will return nil even
  586. // if the receipt itself is stored.
  587. func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
  588. // We're deriving many fields from the block body, retrieve beside the receipt
  589. receipts := ReadRawReceipts(db, hash, number)
  590. if receipts == nil {
  591. return nil
  592. }
  593. body := ReadBody(db, hash, number)
  594. if body == nil {
  595. log.Error("Missing body but have receipt", "hash", hash, "number", number)
  596. return nil
  597. }
  598. if err := receipts.DeriveFields(config, hash, number, body.Transactions); err != nil {
  599. log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err)
  600. return nil
  601. }
  602. return receipts
  603. }
  604. // WriteReceipts stores all the transaction receipts belonging to a block.
  605. func WriteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) {
  606. // Convert the receipts into their storage form and serialize them
  607. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  608. quorumReceiptsExtraData := make([]*types.QuorumReceiptExtraData, len(receipts))
  609. extraDataEmpty := true
  610. for i, receipt := range receipts {
  611. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  612. quorumReceiptsExtraData[i] = &receipt.QuorumReceiptExtraData
  613. if !receipt.QuorumReceiptExtraData.IsEmpty() {
  614. extraDataEmpty = false
  615. }
  616. }
  617. bytes, err := rlp.EncodeToBytes(storageReceipts)
  618. if err != nil {
  619. log.Crit("Failed to encode block receipts", "err", err)
  620. }
  621. if !extraDataEmpty {
  622. bytesExtraData, err := rlp.EncodeToBytes(quorumReceiptsExtraData)
  623. if err != nil {
  624. log.Crit("Failed to encode block receipts", "err", err)
  625. }
  626. // the vanilla receipts and the extra data receipts are concatenated and stored as a single value
  627. bytes = append(bytes, bytesExtraData...)
  628. }
  629. // Store the flattened receipt slice
  630. if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil {
  631. log.Crit("Failed to store block receipts", "err", err)
  632. }
  633. }
  634. // DeleteReceipts removes all receipt data associated with a block hash.
  635. func DeleteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  636. if err := db.Delete(blockReceiptsKey(number, hash)); err != nil {
  637. log.Crit("Failed to delete block receipts", "err", err)
  638. }
  639. }
  640. // ReadBlock retrieves an entire block corresponding to the hash, assembling it
  641. // back from the stored header and body. If either the header or body could not
  642. // be retrieved nil is returned.
  643. //
  644. // Note, due to concurrent download of header and block body the header and thus
  645. // canonical hash can be stored in the database but the body data not (yet).
  646. func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
  647. header := ReadHeader(db, hash, number)
  648. if header == nil {
  649. return nil
  650. }
  651. body := ReadBody(db, hash, number)
  652. if body == nil {
  653. return nil
  654. }
  655. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  656. }
  657. // WriteBlock serializes a block into the database, header and body separately.
  658. func WriteBlock(db ethdb.KeyValueWriter, block *types.Block) {
  659. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  660. WriteHeader(db, block.Header())
  661. }
  662. // WriteAncientBlock writes entire block data into ancient store and returns the total written size.
  663. func WriteAncientBlock(db ethdb.AncientWriter, block *types.Block, receipts types.Receipts, td *big.Int) int {
  664. // Encode all block components to RLP format.
  665. headerBlob, err := rlp.EncodeToBytes(block.Header())
  666. if err != nil {
  667. log.Crit("Failed to RLP encode block header", "err", err)
  668. }
  669. bodyBlob, err := rlp.EncodeToBytes(block.Body())
  670. if err != nil {
  671. log.Crit("Failed to RLP encode body", "err", err)
  672. }
  673. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  674. for i, receipt := range receipts {
  675. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  676. }
  677. receiptBlob, err := rlp.EncodeToBytes(storageReceipts)
  678. if err != nil {
  679. log.Crit("Failed to RLP encode block receipts", "err", err)
  680. }
  681. tdBlob, err := rlp.EncodeToBytes(td)
  682. if err != nil {
  683. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  684. }
  685. // Write all blob to flatten files.
  686. err = db.AppendAncient(block.NumberU64(), block.Hash().Bytes(), headerBlob, bodyBlob, receiptBlob, tdBlob)
  687. if err != nil {
  688. log.Crit("Failed to write block data to ancient store", "err", err)
  689. }
  690. return len(headerBlob) + len(bodyBlob) + len(receiptBlob) + len(tdBlob) + common.HashLength
  691. }
  692. // DeleteBlock removes all block data associated with a hash.
  693. func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  694. DeleteReceipts(db, hash, number)
  695. DeleteHeader(db, hash, number)
  696. DeleteBody(db, hash, number)
  697. DeleteTd(db, hash, number)
  698. }
  699. // DeleteBlockWithoutNumber removes all block data associated with a hash, except
  700. // the hash to number mapping.
  701. func DeleteBlockWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  702. DeleteReceipts(db, hash, number)
  703. deleteHeaderWithoutNumber(db, hash, number)
  704. DeleteBody(db, hash, number)
  705. DeleteTd(db, hash, number)
  706. }
  707. const badBlockToKeep = 10
  708. type badBlock struct {
  709. Header *types.Header
  710. Body *types.Body
  711. }
  712. // badBlockList implements the sort interface to allow sorting a list of
  713. // bad blocks by their number in the reverse order.
  714. type badBlockList []*badBlock
  715. func (s badBlockList) Len() int { return len(s) }
  716. func (s badBlockList) Less(i, j int) bool {
  717. return s[i].Header.Number.Uint64() < s[j].Header.Number.Uint64()
  718. }
  719. func (s badBlockList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  720. // ReadBadBlock retrieves the bad block with the corresponding block hash.
  721. func ReadBadBlock(db ethdb.Reader, hash common.Hash) *types.Block {
  722. blob, err := db.Get(badBlockKey)
  723. if err != nil {
  724. return nil
  725. }
  726. var badBlocks badBlockList
  727. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  728. return nil
  729. }
  730. for _, bad := range badBlocks {
  731. if bad.Header.Hash() == hash {
  732. return types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles)
  733. }
  734. }
  735. return nil
  736. }
  737. // ReadAllBadBlocks retrieves all the bad blocks in the database.
  738. // All returned blocks are sorted in reverse order by number.
  739. func ReadAllBadBlocks(db ethdb.Reader) []*types.Block {
  740. blob, err := db.Get(badBlockKey)
  741. if err != nil {
  742. return nil
  743. }
  744. var badBlocks badBlockList
  745. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  746. return nil
  747. }
  748. var blocks []*types.Block
  749. for _, bad := range badBlocks {
  750. blocks = append(blocks, types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles))
  751. }
  752. return blocks
  753. }
  754. // WriteBadBlock serializes the bad block into the database. If the cumulated
  755. // bad blocks exceeds the limitation, the oldest will be dropped.
  756. func WriteBadBlock(db ethdb.KeyValueStore, block *types.Block) {
  757. blob, err := db.Get(badBlockKey)
  758. if err != nil {
  759. log.Warn("Failed to load old bad blocks", "error", err)
  760. }
  761. var badBlocks badBlockList
  762. if len(blob) > 0 {
  763. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  764. log.Crit("Failed to decode old bad blocks", "error", err)
  765. }
  766. }
  767. for _, b := range badBlocks {
  768. if b.Header.Number.Uint64() == block.NumberU64() && b.Header.Hash() == block.Hash() {
  769. log.Info("Skip duplicated bad block", "number", block.NumberU64(), "hash", block.Hash())
  770. return
  771. }
  772. }
  773. badBlocks = append(badBlocks, &badBlock{
  774. Header: block.Header(),
  775. Body: block.Body(),
  776. })
  777. sort.Sort(sort.Reverse(badBlocks))
  778. if len(badBlocks) > badBlockToKeep {
  779. badBlocks = badBlocks[:badBlockToKeep]
  780. }
  781. data, err := rlp.EncodeToBytes(badBlocks)
  782. if err != nil {
  783. log.Crit("Failed to encode bad blocks", "err", err)
  784. }
  785. if err := db.Put(badBlockKey, data); err != nil {
  786. log.Crit("Failed to write bad blocks", "err", err)
  787. }
  788. }
  789. // DeleteBadBlocks deletes all the bad blocks from the database
  790. func DeleteBadBlocks(db ethdb.KeyValueWriter) {
  791. if err := db.Delete(badBlockKey); err != nil {
  792. log.Crit("Failed to delete bad blocks", "err", err)
  793. }
  794. }
  795. // FindCommonAncestor returns the last common ancestor of two block headers
  796. func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header {
  797. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  798. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  799. if a == nil {
  800. return nil
  801. }
  802. }
  803. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  804. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  805. if b == nil {
  806. return nil
  807. }
  808. }
  809. for a.Hash() != b.Hash() {
  810. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  811. if a == nil {
  812. return nil
  813. }
  814. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  815. if b == nil {
  816. return nil
  817. }
  818. }
  819. return a
  820. }
  821. // ReadHeadHeader returns the current canonical head header.
  822. func ReadHeadHeader(db ethdb.Reader) *types.Header {
  823. headHeaderHash := ReadHeadHeaderHash(db)
  824. if headHeaderHash == (common.Hash{}) {
  825. return nil
  826. }
  827. headHeaderNumber := ReadHeaderNumber(db, headHeaderHash)
  828. if headHeaderNumber == nil {
  829. return nil
  830. }
  831. return ReadHeader(db, headHeaderHash, *headHeaderNumber)
  832. }
  833. // ReadHeadBlock returns the current canonical head block.
  834. func ReadHeadBlock(db ethdb.Reader) *types.Block {
  835. headBlockHash := ReadHeadBlockHash(db)
  836. if headBlockHash == (common.Hash{}) {
  837. return nil
  838. }
  839. headBlockNumber := ReadHeaderNumber(db, headBlockHash)
  840. if headBlockNumber == nil {
  841. return nil
  842. }
  843. return ReadBlock(db, headBlockHash, *headBlockNumber)
  844. }