github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/core/rawdb/accessors_chain.go (about)

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