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