accessors_chain.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. "errors"
  21. "fmt"
  22. "math/big"
  23. "sort"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/params"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. )
  32. // ReadCanonicalHash retrieves the hash assigned to a canonical block number.
  33. func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash {
  34. var data []byte
  35. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  36. data, _ = reader.Ancient(chainFreezerHashTable, number)
  37. if len(data) == 0 {
  38. // Get it by hash from leveldb
  39. data, _ = db.Get(headerHashKey(number))
  40. }
  41. return nil
  42. })
  43. return common.BytesToHash(data)
  44. }
  45. // WriteCanonicalHash stores the hash assigned to a canonical block number.
  46. func WriteCanonicalHash(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  47. if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil {
  48. log.Crit("Failed to store number to hash mapping", "err", err)
  49. }
  50. }
  51. // DeleteCanonicalHash removes the number to hash canonical mapping.
  52. func DeleteCanonicalHash(db ethdb.KeyValueWriter, number uint64) {
  53. if err := db.Delete(headerHashKey(number)); err != nil {
  54. log.Crit("Failed to delete number to hash mapping", "err", err)
  55. }
  56. }
  57. // ReadAllHashes retrieves all the hashes assigned to blocks at a certain heights,
  58. // both canonical and reorged forks included.
  59. func ReadAllHashes(db ethdb.Iteratee, number uint64) []common.Hash {
  60. prefix := headerKeyPrefix(number)
  61. hashes := make([]common.Hash, 0, 1)
  62. it := db.NewIterator(prefix, nil)
  63. defer it.Release()
  64. for it.Next() {
  65. if key := it.Key(); len(key) == len(prefix)+32 {
  66. hashes = append(hashes, common.BytesToHash(key[len(key)-32:]))
  67. }
  68. }
  69. return hashes
  70. }
  71. type NumberHash struct {
  72. Number uint64
  73. Hash common.Hash
  74. }
  75. // ReadAllHashesInRange retrieves all the hashes assigned to blocks at certain
  76. // heights, both canonical and reorged forks included.
  77. // This method considers both limits to be _inclusive_.
  78. func ReadAllHashesInRange(db ethdb.Iteratee, first, last uint64) []*NumberHash {
  79. var (
  80. start = encodeBlockNumber(first)
  81. keyLength = len(headerPrefix) + 8 + 32
  82. hashes = make([]*NumberHash, 0, 1+last-first)
  83. it = db.NewIterator(headerPrefix, start)
  84. )
  85. defer it.Release()
  86. for it.Next() {
  87. key := it.Key()
  88. if len(key) != keyLength {
  89. continue
  90. }
  91. num := binary.BigEndian.Uint64(key[len(headerPrefix) : len(headerPrefix)+8])
  92. if num > last {
  93. break
  94. }
  95. hash := common.BytesToHash(key[len(key)-32:])
  96. hashes = append(hashes, &NumberHash{num, hash})
  97. }
  98. return hashes
  99. }
  100. // ReadAllCanonicalHashes retrieves all canonical number and hash mappings at the
  101. // certain chain range. If the accumulated entries reaches the given threshold,
  102. // abort the iteration and return the semi-finish result.
  103. func ReadAllCanonicalHashes(db ethdb.Iteratee, from uint64, to uint64, limit int) ([]uint64, []common.Hash) {
  104. // Short circuit if the limit is 0.
  105. if limit == 0 {
  106. return nil, nil
  107. }
  108. var (
  109. numbers []uint64
  110. hashes []common.Hash
  111. )
  112. // Construct the key prefix of start point.
  113. start, end := headerHashKey(from), headerHashKey(to)
  114. it := db.NewIterator(nil, start)
  115. defer it.Release()
  116. for it.Next() {
  117. if bytes.Compare(it.Key(), end) >= 0 {
  118. break
  119. }
  120. if key := it.Key(); len(key) == len(headerPrefix)+8+1 && bytes.Equal(key[len(key)-1:], headerHashSuffix) {
  121. numbers = append(numbers, binary.BigEndian.Uint64(key[len(headerPrefix):len(headerPrefix)+8]))
  122. hashes = append(hashes, common.BytesToHash(it.Value()))
  123. // If the accumulated entries reaches the limit threshold, return.
  124. if len(numbers) >= limit {
  125. break
  126. }
  127. }
  128. }
  129. return numbers, hashes
  130. }
  131. // ReadHeaderNumber returns the header number assigned to a hash.
  132. func ReadHeaderNumber(db ethdb.KeyValueReader, hash common.Hash) *uint64 {
  133. data, _ := db.Get(headerNumberKey(hash))
  134. if len(data) != 8 {
  135. return nil
  136. }
  137. number := binary.BigEndian.Uint64(data)
  138. return &number
  139. }
  140. // WriteHeaderNumber stores the hash->number mapping.
  141. func WriteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  142. key := headerNumberKey(hash)
  143. enc := encodeBlockNumber(number)
  144. if err := db.Put(key, enc); err != nil {
  145. log.Crit("Failed to store hash to number mapping", "err", err)
  146. }
  147. }
  148. // DeleteHeaderNumber removes hash->number mapping.
  149. func DeleteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash) {
  150. if err := db.Delete(headerNumberKey(hash)); err != nil {
  151. log.Crit("Failed to delete hash to number mapping", "err", err)
  152. }
  153. }
  154. // ReadHeadHeaderHash retrieves the hash of the current canonical head header.
  155. func ReadHeadHeaderHash(db ethdb.KeyValueReader) common.Hash {
  156. data, _ := db.Get(headHeaderKey)
  157. if len(data) == 0 {
  158. return common.Hash{}
  159. }
  160. return common.BytesToHash(data)
  161. }
  162. // WriteHeadHeaderHash stores the hash of the current canonical head header.
  163. func WriteHeadHeaderHash(db ethdb.KeyValueWriter, hash common.Hash) {
  164. if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
  165. log.Crit("Failed to store last header's hash", "err", err)
  166. }
  167. }
  168. // ReadHeadBlockHash retrieves the hash of the current canonical head block.
  169. func ReadHeadBlockHash(db ethdb.KeyValueReader) common.Hash {
  170. data, _ := db.Get(headBlockKey)
  171. if len(data) == 0 {
  172. return common.Hash{}
  173. }
  174. return common.BytesToHash(data)
  175. }
  176. // WriteHeadBlockHash stores the head block's hash.
  177. func WriteHeadBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  178. if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
  179. log.Crit("Failed to store last block's hash", "err", err)
  180. }
  181. }
  182. // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block.
  183. func ReadHeadFastBlockHash(db ethdb.KeyValueReader) common.Hash {
  184. data, _ := db.Get(headFastBlockKey)
  185. if len(data) == 0 {
  186. return common.Hash{}
  187. }
  188. return common.BytesToHash(data)
  189. }
  190. // WriteHeadFastBlockHash stores the hash of the current fast-sync head block.
  191. func WriteHeadFastBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  192. if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil {
  193. log.Crit("Failed to store last fast block's hash", "err", err)
  194. }
  195. }
  196. // ReadFinalizedBlockHash retrieves the hash of the finalized block.
  197. func ReadFinalizedBlockHash(db ethdb.KeyValueReader) common.Hash {
  198. data, _ := db.Get(headFinalizedBlockKey)
  199. if len(data) == 0 {
  200. return common.Hash{}
  201. }
  202. return common.BytesToHash(data)
  203. }
  204. // WriteFinalizedBlockHash stores the hash of the finalized block.
  205. func WriteFinalizedBlockHash(db ethdb.KeyValueWriter, hash common.Hash) {
  206. if err := db.Put(headFinalizedBlockKey, hash.Bytes()); err != nil {
  207. log.Crit("Failed to store last finalized block's hash", "err", err)
  208. }
  209. }
  210. // ReadLastPivotNumber retrieves the number of the last pivot block. If the node
  211. // full synced, the last pivot will always be nil.
  212. func ReadLastPivotNumber(db ethdb.KeyValueReader) *uint64 {
  213. data, _ := db.Get(lastPivotKey)
  214. if len(data) == 0 {
  215. return nil
  216. }
  217. var pivot uint64
  218. if err := rlp.DecodeBytes(data, &pivot); err != nil {
  219. log.Error("Invalid pivot block number in database", "err", err)
  220. return nil
  221. }
  222. return &pivot
  223. }
  224. // WriteLastPivotNumber stores the number of the last pivot block.
  225. func WriteLastPivotNumber(db ethdb.KeyValueWriter, pivot uint64) {
  226. enc, err := rlp.EncodeToBytes(pivot)
  227. if err != nil {
  228. log.Crit("Failed to encode pivot block number", "err", err)
  229. }
  230. if err := db.Put(lastPivotKey, enc); err != nil {
  231. log.Crit("Failed to store pivot block number", "err", err)
  232. }
  233. }
  234. // ReadTxIndexTail retrieves the number of oldest indexed block
  235. // whose transaction indices has been indexed. If the corresponding entry
  236. // is non-existent in database it means the indexing has been finished.
  237. func ReadTxIndexTail(db ethdb.KeyValueReader) *uint64 {
  238. data, _ := db.Get(txIndexTailKey)
  239. if len(data) != 8 {
  240. return nil
  241. }
  242. number := binary.BigEndian.Uint64(data)
  243. return &number
  244. }
  245. // WriteTxIndexTail stores the number of oldest indexed block
  246. // into database.
  247. func WriteTxIndexTail(db ethdb.KeyValueWriter, number uint64) {
  248. if err := db.Put(txIndexTailKey, encodeBlockNumber(number)); err != nil {
  249. log.Crit("Failed to store the transaction index tail", "err", err)
  250. }
  251. }
  252. // ReadFastTxLookupLimit retrieves the tx lookup limit used in fast sync.
  253. func ReadFastTxLookupLimit(db ethdb.KeyValueReader) *uint64 {
  254. data, _ := db.Get(fastTxLookupLimitKey)
  255. if len(data) != 8 {
  256. return nil
  257. }
  258. number := binary.BigEndian.Uint64(data)
  259. return &number
  260. }
  261. // WriteFastTxLookupLimit stores the txlookup limit used in fast sync into database.
  262. func WriteFastTxLookupLimit(db ethdb.KeyValueWriter, number uint64) {
  263. if err := db.Put(fastTxLookupLimitKey, encodeBlockNumber(number)); err != nil {
  264. log.Crit("Failed to store transaction lookup limit for fast sync", "err", err)
  265. }
  266. }
  267. // ReadHeaderRange returns the rlp-encoded headers, starting at 'number', and going
  268. // backwards towards genesis. This method assumes that the caller already has
  269. // placed a cap on count, to prevent DoS issues.
  270. // Since this method operates in head-towards-genesis mode, it will return an empty
  271. // slice in case the head ('number') is missing. Hence, the caller must ensure that
  272. // the head ('number') argument is actually an existing header.
  273. //
  274. // N.B: Since the input is a number, as opposed to a hash, it's implicit that
  275. // this method only operates on canon headers.
  276. func ReadHeaderRange(db ethdb.Reader, number uint64, count uint64) []rlp.RawValue {
  277. var rlpHeaders []rlp.RawValue
  278. if count == 0 {
  279. return rlpHeaders
  280. }
  281. i := number
  282. if count-1 > number {
  283. // It's ok to request block 0, 1 item
  284. count = number + 1
  285. }
  286. limit, _ := db.Ancients()
  287. // First read live blocks
  288. if i >= limit {
  289. // If we need to read live blocks, we need to figure out the hash first
  290. hash := ReadCanonicalHash(db, number)
  291. for ; i >= limit && count > 0; i-- {
  292. if data, _ := db.Get(headerKey(i, hash)); len(data) > 0 {
  293. rlpHeaders = append(rlpHeaders, data)
  294. // Get the parent hash for next query
  295. hash = types.HeaderParentHashFromRLP(data)
  296. } else {
  297. break // Maybe got moved to ancients
  298. }
  299. count--
  300. }
  301. }
  302. if count == 0 {
  303. return rlpHeaders
  304. }
  305. // read remaining from ancients
  306. max := count * 700
  307. data, err := db.AncientRange(chainFreezerHeaderTable, i+1-count, count, max)
  308. if err == nil && uint64(len(data)) == count {
  309. // the data is on the order [h, h+1, .., n] -- reordering needed
  310. for i := range data {
  311. rlpHeaders = append(rlpHeaders, data[len(data)-1-i])
  312. }
  313. }
  314. return rlpHeaders
  315. }
  316. // ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
  317. func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  318. var data []byte
  319. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  320. // First try to look up the data in ancient database. Extra hash
  321. // comparison is necessary since ancient database only maintains
  322. // the canonical data.
  323. data, _ = reader.Ancient(chainFreezerHeaderTable, number)
  324. if len(data) > 0 && crypto.Keccak256Hash(data) == hash {
  325. return nil
  326. }
  327. // If not, try reading from leveldb
  328. data, _ = db.Get(headerKey(number, hash))
  329. return nil
  330. })
  331. return data
  332. }
  333. // HasHeader verifies the existence of a block header corresponding to the hash.
  334. func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool {
  335. if isCanon(db, number, hash) {
  336. return true
  337. }
  338. if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
  339. return false
  340. }
  341. return true
  342. }
  343. // ReadHeader retrieves the block header corresponding to the hash.
  344. func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header {
  345. data := ReadHeaderRLP(db, hash, number)
  346. if len(data) == 0 {
  347. return nil
  348. }
  349. header := new(types.Header)
  350. if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
  351. log.Error("Invalid block header RLP", "hash", hash, "err", err)
  352. return nil
  353. }
  354. return header
  355. }
  356. // WriteHeader stores a block header into the database and also stores the hash-
  357. // to-number mapping.
  358. func WriteHeader(db ethdb.KeyValueWriter, header *types.Header) {
  359. var (
  360. hash = header.Hash()
  361. number = header.Number.Uint64()
  362. )
  363. // Write the hash -> number mapping
  364. WriteHeaderNumber(db, hash, number)
  365. // Write the encoded header
  366. data, err := rlp.EncodeToBytes(header)
  367. if err != nil {
  368. log.Crit("Failed to RLP encode header", "err", err)
  369. }
  370. key := headerKey(number, hash)
  371. if err := db.Put(key, data); err != nil {
  372. log.Crit("Failed to store header", "err", err)
  373. }
  374. }
  375. // DeleteHeader removes all block header data associated with a hash.
  376. func DeleteHeader(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  377. deleteHeaderWithoutNumber(db, hash, number)
  378. if err := db.Delete(headerNumberKey(hash)); err != nil {
  379. log.Crit("Failed to delete hash to number mapping", "err", err)
  380. }
  381. }
  382. // deleteHeaderWithoutNumber removes only the block header but does not remove
  383. // the hash to number mapping.
  384. func deleteHeaderWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  385. if err := db.Delete(headerKey(number, hash)); err != nil {
  386. log.Crit("Failed to delete header", "err", err)
  387. }
  388. }
  389. // isCanon is an internal utility method, to check whether the given number/hash
  390. // is part of the ancient (canon) set.
  391. func isCanon(reader ethdb.AncientReaderOp, number uint64, hash common.Hash) bool {
  392. h, err := reader.Ancient(chainFreezerHashTable, number)
  393. if err != nil {
  394. return false
  395. }
  396. return bytes.Equal(h, hash[:])
  397. }
  398. // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
  399. func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  400. // First try to look up the data in ancient database. Extra hash
  401. // comparison is necessary since ancient database only maintains
  402. // the canonical data.
  403. var data []byte
  404. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  405. // Check if the data is in ancients
  406. if isCanon(reader, number, hash) {
  407. data, _ = reader.Ancient(chainFreezerBodiesTable, number)
  408. return nil
  409. }
  410. // If not, try reading from leveldb
  411. data, _ = db.Get(blockBodyKey(number, hash))
  412. return nil
  413. })
  414. return data
  415. }
  416. // ReadCanonicalBodyRLP retrieves the block body (transactions and uncles) for the canonical
  417. // block at number, in RLP encoding.
  418. func ReadCanonicalBodyRLP(db ethdb.Reader, number uint64) rlp.RawValue {
  419. var data []byte
  420. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  421. data, _ = reader.Ancient(chainFreezerBodiesTable, number)
  422. if len(data) > 0 {
  423. return nil
  424. }
  425. // Block is not in ancients, read from leveldb by hash and number.
  426. // Note: ReadCanonicalHash cannot be used here because it also
  427. // calls ReadAncients internally.
  428. hash, _ := db.Get(headerHashKey(number))
  429. data, _ = db.Get(blockBodyKey(number, common.BytesToHash(hash)))
  430. return nil
  431. })
  432. return data
  433. }
  434. // WriteBodyRLP stores an RLP encoded block body into the database.
  435. func WriteBodyRLP(db ethdb.KeyValueWriter, hash common.Hash, number uint64, rlp rlp.RawValue) {
  436. if err := db.Put(blockBodyKey(number, hash), rlp); err != nil {
  437. log.Crit("Failed to store block body", "err", err)
  438. }
  439. }
  440. // HasBody verifies the existence of a block body corresponding to the hash.
  441. func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool {
  442. if isCanon(db, number, hash) {
  443. return true
  444. }
  445. if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
  446. return false
  447. }
  448. return true
  449. }
  450. // ReadBody retrieves the block body corresponding to the hash.
  451. func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body {
  452. data := ReadBodyRLP(db, hash, number)
  453. if len(data) == 0 {
  454. return nil
  455. }
  456. body := new(types.Body)
  457. if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
  458. log.Error("Invalid block body RLP", "hash", hash, "err", err)
  459. return nil
  460. }
  461. return body
  462. }
  463. // WriteBody stores a block body into the database.
  464. func WriteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64, body *types.Body) {
  465. data, err := rlp.EncodeToBytes(body)
  466. if err != nil {
  467. log.Crit("Failed to RLP encode body", "err", err)
  468. }
  469. WriteBodyRLP(db, hash, number, data)
  470. }
  471. // DeleteBody removes all block body data associated with a hash.
  472. func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  473. if err := db.Delete(blockBodyKey(number, hash)); err != nil {
  474. log.Crit("Failed to delete block body", "err", err)
  475. }
  476. }
  477. // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding.
  478. func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  479. var data []byte
  480. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  481. // Check if the data is in ancients
  482. if isCanon(reader, number, hash) {
  483. data, _ = reader.Ancient(chainFreezerDifficultyTable, number)
  484. return nil
  485. }
  486. // If not, try reading from leveldb
  487. data, _ = db.Get(headerTDKey(number, hash))
  488. return nil
  489. })
  490. return data
  491. }
  492. // ReadTd retrieves a block's total difficulty corresponding to the hash.
  493. func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int {
  494. data := ReadTdRLP(db, hash, number)
  495. if len(data) == 0 {
  496. return nil
  497. }
  498. td := new(big.Int)
  499. if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
  500. log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
  501. return nil
  502. }
  503. return td
  504. }
  505. // WriteTd stores the total difficulty of a block into the database.
  506. func WriteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64, td *big.Int) {
  507. data, err := rlp.EncodeToBytes(td)
  508. if err != nil {
  509. log.Crit("Failed to RLP encode block total difficulty", "err", err)
  510. }
  511. if err := db.Put(headerTDKey(number, hash), data); err != nil {
  512. log.Crit("Failed to store block total difficulty", "err", err)
  513. }
  514. }
  515. // DeleteTd removes all block total difficulty data associated with a hash.
  516. func DeleteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  517. if err := db.Delete(headerTDKey(number, hash)); err != nil {
  518. log.Crit("Failed to delete block total difficulty", "err", err)
  519. }
  520. }
  521. // HasReceipts verifies the existence of all the transaction receipts belonging
  522. // to a block.
  523. func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool {
  524. if isCanon(db, number, hash) {
  525. return true
  526. }
  527. if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil {
  528. return false
  529. }
  530. return true
  531. }
  532. // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding.
  533. func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
  534. var data []byte
  535. db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
  536. // Check if the data is in ancients
  537. if isCanon(reader, number, hash) {
  538. data, _ = reader.Ancient(chainFreezerReceiptTable, number)
  539. return nil
  540. }
  541. // If not, try reading from leveldb
  542. data, _ = db.Get(blockReceiptsKey(number, hash))
  543. return nil
  544. })
  545. return data
  546. }
  547. // ReadRawReceipts retrieves all the transaction receipts belonging to a block.
  548. // The receipt metadata fields are not guaranteed to be populated, so they
  549. // should not be used. Use ReadReceipts instead if the metadata is needed.
  550. func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts {
  551. // Retrieve the flattened receipt slice
  552. data := ReadReceiptsRLP(db, hash, number)
  553. if len(data) == 0 {
  554. return nil
  555. }
  556. // Convert the receipts from their storage form to their internal representation
  557. storageReceipts := []*types.ReceiptForStorage{}
  558. if err := rlp.DecodeBytes(data, &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. return receipts
  567. }
  568. // ReadReceipts retrieves all the transaction receipts belonging to a block, including
  569. // its corresponding metadata fields. If it is unable to populate these metadata
  570. // fields then nil is returned.
  571. //
  572. // The current implementation populates these metadata fields by reading the receipts'
  573. // corresponding block body, so if the block body is not found it will return nil even
  574. // if the receipt itself is stored.
  575. func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
  576. // We're deriving many fields from the block body, retrieve beside the receipt
  577. receipts := ReadRawReceipts(db, hash, number)
  578. if receipts == nil {
  579. return nil
  580. }
  581. body := ReadBody(db, hash, number)
  582. if body == nil {
  583. log.Error("Missing body but have receipt", "hash", hash, "number", number)
  584. return nil
  585. }
  586. if err := receipts.DeriveFields(config, hash, number, body.Transactions); err != nil {
  587. log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err)
  588. return nil
  589. }
  590. return receipts
  591. }
  592. // WriteReceipts stores all the transaction receipts belonging to a block.
  593. func WriteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) {
  594. // Convert the receipts into their storage form and serialize them
  595. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  596. for i, receipt := range receipts {
  597. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  598. }
  599. bytes, err := rlp.EncodeToBytes(storageReceipts)
  600. if err != nil {
  601. log.Crit("Failed to encode block receipts", "err", err)
  602. }
  603. // Store the flattened receipt slice
  604. if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil {
  605. log.Crit("Failed to store block receipts", "err", err)
  606. }
  607. }
  608. // DeleteReceipts removes all receipt data associated with a block hash.
  609. func DeleteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  610. if err := db.Delete(blockReceiptsKey(number, hash)); err != nil {
  611. log.Crit("Failed to delete block receipts", "err", err)
  612. }
  613. }
  614. // storedReceiptRLP is the storage encoding of a receipt.
  615. // Re-definition in core/types/receipt.go.
  616. type storedReceiptRLP struct {
  617. PostStateOrStatus []byte
  618. CumulativeGasUsed uint64
  619. Logs []*types.LogForStorage
  620. }
  621. // ReceiptLogs is a barebone version of ReceiptForStorage which only keeps
  622. // the list of logs. When decoding a stored receipt into this object we
  623. // avoid creating the bloom filter.
  624. type receiptLogs struct {
  625. Logs []*types.Log
  626. }
  627. // DecodeRLP implements rlp.Decoder.
  628. func (r *receiptLogs) DecodeRLP(s *rlp.Stream) error {
  629. var stored storedReceiptRLP
  630. if err := s.Decode(&stored); err != nil {
  631. return err
  632. }
  633. r.Logs = make([]*types.Log, len(stored.Logs))
  634. for i, log := range stored.Logs {
  635. r.Logs[i] = (*types.Log)(log)
  636. }
  637. return nil
  638. }
  639. // DeriveLogFields fills the logs in receiptLogs with information such as block number, txhash, etc.
  640. func deriveLogFields(receipts []*receiptLogs, hash common.Hash, number uint64, txs types.Transactions) error {
  641. logIndex := uint(0)
  642. if len(txs) != len(receipts) {
  643. return errors.New("transaction and receipt count mismatch")
  644. }
  645. for i := 0; i < len(receipts); i++ {
  646. txHash := txs[i].Hash()
  647. // The derived log fields can simply be set from the block and transaction
  648. for j := 0; j < len(receipts[i].Logs); j++ {
  649. receipts[i].Logs[j].BlockNumber = number
  650. receipts[i].Logs[j].BlockHash = hash
  651. receipts[i].Logs[j].TxHash = txHash
  652. receipts[i].Logs[j].TxIndex = uint(i)
  653. receipts[i].Logs[j].Index = logIndex
  654. logIndex++
  655. }
  656. }
  657. return nil
  658. }
  659. // ReadLogs retrieves the logs for all transactions in a block. The log fields
  660. // are populated with metadata. In case the receipts or the block body
  661. // are not found, a nil is returned.
  662. func ReadLogs(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) [][]*types.Log {
  663. // Retrieve the flattened receipt slice
  664. data := ReadReceiptsRLP(db, hash, number)
  665. if len(data) == 0 {
  666. return nil
  667. }
  668. receipts := []*receiptLogs{}
  669. if err := rlp.DecodeBytes(data, &receipts); err != nil {
  670. // Receipts might be in the legacy format, try decoding that.
  671. // TODO: to be removed after users migrated
  672. if logs := readLegacyLogs(db, hash, number, config); logs != nil {
  673. return logs
  674. }
  675. log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
  676. return nil
  677. }
  678. body := ReadBody(db, hash, number)
  679. if body == nil {
  680. log.Error("Missing body but have receipt", "hash", hash, "number", number)
  681. return nil
  682. }
  683. if err := deriveLogFields(receipts, hash, number, body.Transactions); err != nil {
  684. log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err)
  685. return nil
  686. }
  687. logs := make([][]*types.Log, len(receipts))
  688. for i, receipt := range receipts {
  689. logs[i] = receipt.Logs
  690. }
  691. return logs
  692. }
  693. // readLegacyLogs is a temporary workaround for when trying to read logs
  694. // from a block which has its receipt stored in the legacy format. It'll
  695. // be removed after users have migrated their freezer databases.
  696. func readLegacyLogs(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) [][]*types.Log {
  697. receipts := ReadReceipts(db, hash, number, config)
  698. if receipts == nil {
  699. return nil
  700. }
  701. logs := make([][]*types.Log, len(receipts))
  702. for i, receipt := range receipts {
  703. logs[i] = receipt.Logs
  704. }
  705. return logs
  706. }
  707. // ReadBlock retrieves an entire block corresponding to the hash, assembling it
  708. // back from the stored header and body. If either the header or body could not
  709. // be retrieved nil is returned.
  710. //
  711. // Note, due to concurrent download of header and block body the header and thus
  712. // canonical hash can be stored in the database but the body data not (yet).
  713. func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
  714. header := ReadHeader(db, hash, number)
  715. if header == nil {
  716. return nil
  717. }
  718. body := ReadBody(db, hash, number)
  719. if body == nil {
  720. return nil
  721. }
  722. return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
  723. }
  724. // WriteBlock serializes a block into the database, header and body separately.
  725. func WriteBlock(db ethdb.KeyValueWriter, block *types.Block) {
  726. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  727. WriteHeader(db, block.Header())
  728. }
  729. // WriteAncientBlocks writes entire block data into ancient store and returns the total written size.
  730. func WriteAncientBlocks(db ethdb.AncientWriter, blocks []*types.Block, receipts []types.Receipts, td *big.Int) (int64, error) {
  731. var (
  732. tdSum = new(big.Int).Set(td)
  733. stReceipts []*types.ReceiptForStorage
  734. )
  735. return db.ModifyAncients(func(op ethdb.AncientWriteOp) error {
  736. for i, block := range blocks {
  737. // Convert receipts to storage format and sum up total difficulty.
  738. stReceipts = stReceipts[:0]
  739. for _, receipt := range receipts[i] {
  740. stReceipts = append(stReceipts, (*types.ReceiptForStorage)(receipt))
  741. }
  742. header := block.Header()
  743. if i > 0 {
  744. tdSum.Add(tdSum, header.Difficulty)
  745. }
  746. if err := writeAncientBlock(op, block, header, stReceipts, tdSum); err != nil {
  747. return err
  748. }
  749. }
  750. return nil
  751. })
  752. }
  753. func writeAncientBlock(op ethdb.AncientWriteOp, block *types.Block, header *types.Header, receipts []*types.ReceiptForStorage, td *big.Int) error {
  754. num := block.NumberU64()
  755. if err := op.AppendRaw(chainFreezerHashTable, num, block.Hash().Bytes()); err != nil {
  756. return fmt.Errorf("can't add block %d hash: %v", num, err)
  757. }
  758. if err := op.Append(chainFreezerHeaderTable, num, header); err != nil {
  759. return fmt.Errorf("can't append block header %d: %v", num, err)
  760. }
  761. if err := op.Append(chainFreezerBodiesTable, num, block.Body()); err != nil {
  762. return fmt.Errorf("can't append block body %d: %v", num, err)
  763. }
  764. if err := op.Append(chainFreezerReceiptTable, num, receipts); err != nil {
  765. return fmt.Errorf("can't append block %d receipts: %v", num, err)
  766. }
  767. if err := op.Append(chainFreezerDifficultyTable, num, td); err != nil {
  768. return fmt.Errorf("can't append block %d total difficulty: %v", num, err)
  769. }
  770. return nil
  771. }
  772. // DeleteBlock removes all block data associated with a hash.
  773. func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  774. DeleteReceipts(db, hash, number)
  775. DeleteHeader(db, hash, number)
  776. DeleteBody(db, hash, number)
  777. DeleteTd(db, hash, number)
  778. }
  779. // DeleteBlockWithoutNumber removes all block data associated with a hash, except
  780. // the hash to number mapping.
  781. func DeleteBlockWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
  782. DeleteReceipts(db, hash, number)
  783. deleteHeaderWithoutNumber(db, hash, number)
  784. DeleteBody(db, hash, number)
  785. DeleteTd(db, hash, number)
  786. }
  787. const badBlockToKeep = 10
  788. type badBlock struct {
  789. Header *types.Header
  790. Body *types.Body
  791. }
  792. // badBlockList implements the sort interface to allow sorting a list of
  793. // bad blocks by their number in the reverse order.
  794. type badBlockList []*badBlock
  795. func (s badBlockList) Len() int { return len(s) }
  796. func (s badBlockList) Less(i, j int) bool {
  797. return s[i].Header.Number.Uint64() < s[j].Header.Number.Uint64()
  798. }
  799. func (s badBlockList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  800. // ReadBadBlock retrieves the bad block with the corresponding block hash.
  801. func ReadBadBlock(db ethdb.Reader, hash common.Hash) *types.Block {
  802. blob, err := db.Get(badBlockKey)
  803. if err != nil {
  804. return nil
  805. }
  806. var badBlocks badBlockList
  807. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  808. return nil
  809. }
  810. for _, bad := range badBlocks {
  811. if bad.Header.Hash() == hash {
  812. return types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles)
  813. }
  814. }
  815. return nil
  816. }
  817. // ReadAllBadBlocks retrieves all the bad blocks in the database.
  818. // All returned blocks are sorted in reverse order by number.
  819. func ReadAllBadBlocks(db ethdb.Reader) []*types.Block {
  820. blob, err := db.Get(badBlockKey)
  821. if err != nil {
  822. return nil
  823. }
  824. var badBlocks badBlockList
  825. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  826. return nil
  827. }
  828. var blocks []*types.Block
  829. for _, bad := range badBlocks {
  830. blocks = append(blocks, types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles))
  831. }
  832. return blocks
  833. }
  834. // WriteBadBlock serializes the bad block into the database. If the cumulated
  835. // bad blocks exceeds the limitation, the oldest will be dropped.
  836. func WriteBadBlock(db ethdb.KeyValueStore, block *types.Block) {
  837. blob, err := db.Get(badBlockKey)
  838. if err != nil {
  839. log.Warn("Failed to load old bad blocks", "error", err)
  840. }
  841. var badBlocks badBlockList
  842. if len(blob) > 0 {
  843. if err := rlp.DecodeBytes(blob, &badBlocks); err != nil {
  844. log.Crit("Failed to decode old bad blocks", "error", err)
  845. }
  846. }
  847. for _, b := range badBlocks {
  848. if b.Header.Number.Uint64() == block.NumberU64() && b.Header.Hash() == block.Hash() {
  849. log.Info("Skip duplicated bad block", "number", block.NumberU64(), "hash", block.Hash())
  850. return
  851. }
  852. }
  853. badBlocks = append(badBlocks, &badBlock{
  854. Header: block.Header(),
  855. Body: block.Body(),
  856. })
  857. sort.Sort(sort.Reverse(badBlocks))
  858. if len(badBlocks) > badBlockToKeep {
  859. badBlocks = badBlocks[:badBlockToKeep]
  860. }
  861. data, err := rlp.EncodeToBytes(badBlocks)
  862. if err != nil {
  863. log.Crit("Failed to encode bad blocks", "err", err)
  864. }
  865. if err := db.Put(badBlockKey, data); err != nil {
  866. log.Crit("Failed to write bad blocks", "err", err)
  867. }
  868. }
  869. // DeleteBadBlocks deletes all the bad blocks from the database
  870. func DeleteBadBlocks(db ethdb.KeyValueWriter) {
  871. if err := db.Delete(badBlockKey); err != nil {
  872. log.Crit("Failed to delete bad blocks", "err", err)
  873. }
  874. }
  875. // FindCommonAncestor returns the last common ancestor of two block headers
  876. func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header {
  877. for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
  878. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  879. if a == nil {
  880. return nil
  881. }
  882. }
  883. for an := a.Number.Uint64(); an < b.Number.Uint64(); {
  884. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  885. if b == nil {
  886. return nil
  887. }
  888. }
  889. for a.Hash() != b.Hash() {
  890. a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
  891. if a == nil {
  892. return nil
  893. }
  894. b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1)
  895. if b == nil {
  896. return nil
  897. }
  898. }
  899. return a
  900. }
  901. // ReadHeadHeader returns the current canonical head header.
  902. func ReadHeadHeader(db ethdb.Reader) *types.Header {
  903. headHeaderHash := ReadHeadHeaderHash(db)
  904. if headHeaderHash == (common.Hash{}) {
  905. return nil
  906. }
  907. headHeaderNumber := ReadHeaderNumber(db, headHeaderHash)
  908. if headHeaderNumber == nil {
  909. return nil
  910. }
  911. return ReadHeader(db, headHeaderHash, *headHeaderNumber)
  912. }
  913. // ReadHeadBlock returns the current canonical head block.
  914. func ReadHeadBlock(db ethdb.Reader) *types.Block {
  915. headBlockHash := ReadHeadBlockHash(db)
  916. if headBlockHash == (common.Hash{}) {
  917. return nil
  918. }
  919. headBlockNumber := ReadHeaderNumber(db, headBlockHash)
  920. if headBlockNumber == nil {
  921. return nil
  922. }
  923. return ReadBlock(db, headBlockHash, *headBlockNumber)
  924. }