github.com/4000d/go-ethereum@v1.8.2-0.20180223170251-423c8bb1d821/core/database_util.go (about)

     1  // Copyright 2015 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 core
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/metrics"
    32  	"github.com/ethereum/go-ethereum/params"
    33  	"github.com/ethereum/go-ethereum/rlp"
    34  )
    35  
    36  // DatabaseReader wraps the Get method of a backing data store.
    37  type DatabaseReader interface {
    38  	Get(key []byte) (value []byte, err error)
    39  }
    40  
    41  // DatabaseDeleter wraps the Delete method of a backing data store.
    42  type DatabaseDeleter interface {
    43  	Delete(key []byte) error
    44  }
    45  
    46  var (
    47  	headHeaderKey = []byte("LastHeader")
    48  	headBlockKey  = []byte("LastBlock")
    49  	headFastKey   = []byte("LastFast")
    50  
    51  	// Data item prefixes (use single byte to avoid mixing data types, avoid `i`).
    52  	headerPrefix        = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
    53  	tdSuffix            = []byte("t") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td
    54  	numSuffix           = []byte("n") // headerPrefix + num (uint64 big endian) + numSuffix -> hash
    55  	blockHashPrefix     = []byte("H") // blockHashPrefix + hash -> num (uint64 big endian)
    56  	bodyPrefix          = []byte("b") // bodyPrefix + num (uint64 big endian) + hash -> block body
    57  	blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
    58  	lookupPrefix        = []byte("l") // lookupPrefix + hash -> transaction/receipt lookup metadata
    59  	bloomBitsPrefix     = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits
    60  
    61  	preimagePrefix = "secure-key-"              // preimagePrefix + hash -> preimage
    62  	configPrefix   = []byte("ethereum-config-") // config prefix for the db
    63  
    64  	// Chain index prefixes (use `i` + single byte to avoid mixing data types).
    65  	BloomBitsIndexPrefix = []byte("iB") // BloomBitsIndexPrefix is the data table of a chain indexer to track its progress
    66  
    67  	// used by old db, now only used for conversion
    68  	oldReceiptsPrefix = []byte("receipts-")
    69  	oldTxMetaSuffix   = []byte{0x01}
    70  
    71  	ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error
    72  
    73  	preimageCounter    = metrics.NewRegisteredCounter("db/preimage/total", nil)
    74  	preimageHitCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil)
    75  )
    76  
    77  // TxLookupEntry is a positional metadata to help looking up the data content of
    78  // a transaction or receipt given only its hash.
    79  type TxLookupEntry struct {
    80  	BlockHash  common.Hash
    81  	BlockIndex uint64
    82  	Index      uint64
    83  }
    84  
    85  // encodeBlockNumber encodes a block number as big endian uint64
    86  func encodeBlockNumber(number uint64) []byte {
    87  	enc := make([]byte, 8)
    88  	binary.BigEndian.PutUint64(enc, number)
    89  	return enc
    90  }
    91  
    92  // GetCanonicalHash retrieves a hash assigned to a canonical block number.
    93  func GetCanonicalHash(db DatabaseReader, number uint64) common.Hash {
    94  	data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
    95  	if len(data) == 0 {
    96  		return common.Hash{}
    97  	}
    98  	return common.BytesToHash(data)
    99  }
   100  
   101  // missingNumber is returned by GetBlockNumber if no header with the
   102  // given block hash has been stored in the database
   103  const missingNumber = uint64(0xffffffffffffffff)
   104  
   105  // GetBlockNumber returns the block number assigned to a block hash
   106  // if the corresponding header is present in the database
   107  func GetBlockNumber(db DatabaseReader, hash common.Hash) uint64 {
   108  	data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...))
   109  	if len(data) != 8 {
   110  		return missingNumber
   111  	}
   112  	return binary.BigEndian.Uint64(data)
   113  }
   114  
   115  // GetHeadHeaderHash retrieves the hash of the current canonical head block's
   116  // header. The difference between this and GetHeadBlockHash is that whereas the
   117  // last block hash is only updated upon a full block import, the last header
   118  // hash is updated already at header import, allowing head tracking for the
   119  // light synchronization mechanism.
   120  func GetHeadHeaderHash(db DatabaseReader) common.Hash {
   121  	data, _ := db.Get(headHeaderKey)
   122  	if len(data) == 0 {
   123  		return common.Hash{}
   124  	}
   125  	return common.BytesToHash(data)
   126  }
   127  
   128  // GetHeadBlockHash retrieves the hash of the current canonical head block.
   129  func GetHeadBlockHash(db DatabaseReader) common.Hash {
   130  	data, _ := db.Get(headBlockKey)
   131  	if len(data) == 0 {
   132  		return common.Hash{}
   133  	}
   134  	return common.BytesToHash(data)
   135  }
   136  
   137  // GetHeadFastBlockHash retrieves the hash of the current canonical head block during
   138  // fast synchronization. The difference between this and GetHeadBlockHash is that
   139  // whereas the last block hash is only updated upon a full block import, the last
   140  // fast hash is updated when importing pre-processed blocks.
   141  func GetHeadFastBlockHash(db DatabaseReader) common.Hash {
   142  	data, _ := db.Get(headFastKey)
   143  	if len(data) == 0 {
   144  		return common.Hash{}
   145  	}
   146  	return common.BytesToHash(data)
   147  }
   148  
   149  // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil
   150  // if the header's not found.
   151  func GetHeaderRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
   152  	data, _ := db.Get(headerKey(hash, number))
   153  	return data
   154  }
   155  
   156  // GetHeader retrieves the block header corresponding to the hash, nil if none
   157  // found.
   158  func GetHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header {
   159  	data := GetHeaderRLP(db, hash, number)
   160  	if len(data) == 0 {
   161  		return nil
   162  	}
   163  	header := new(types.Header)
   164  	if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
   165  		log.Error("Invalid block header RLP", "hash", hash, "err", err)
   166  		return nil
   167  	}
   168  	return header
   169  }
   170  
   171  // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
   172  func GetBodyRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue {
   173  	data, _ := db.Get(blockBodyKey(hash, number))
   174  	return data
   175  }
   176  
   177  func headerKey(hash common.Hash, number uint64) []byte {
   178  	return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   179  }
   180  
   181  func blockBodyKey(hash common.Hash, number uint64) []byte {
   182  	return append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   183  }
   184  
   185  // GetBody retrieves the block body (transactons, uncles) corresponding to the
   186  // hash, nil if none found.
   187  func GetBody(db DatabaseReader, hash common.Hash, number uint64) *types.Body {
   188  	data := GetBodyRLP(db, hash, number)
   189  	if len(data) == 0 {
   190  		return nil
   191  	}
   192  	body := new(types.Body)
   193  	if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
   194  		log.Error("Invalid block body RLP", "hash", hash, "err", err)
   195  		return nil
   196  	}
   197  	return body
   198  }
   199  
   200  // GetTd retrieves a block's total difficulty corresponding to the hash, nil if
   201  // none found.
   202  func GetTd(db DatabaseReader, hash common.Hash, number uint64) *big.Int {
   203  	data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...))
   204  	if len(data) == 0 {
   205  		return nil
   206  	}
   207  	td := new(big.Int)
   208  	if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
   209  		log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err)
   210  		return nil
   211  	}
   212  	return td
   213  }
   214  
   215  // GetBlock retrieves an entire block corresponding to the hash, assembling it
   216  // back from the stored header and body. If either the header or body could not
   217  // be retrieved nil is returned.
   218  //
   219  // Note, due to concurrent download of header and block body the header and thus
   220  // canonical hash can be stored in the database but the body data not (yet).
   221  func GetBlock(db DatabaseReader, hash common.Hash, number uint64) *types.Block {
   222  	// Retrieve the block header and body contents
   223  	header := GetHeader(db, hash, number)
   224  	if header == nil {
   225  		return nil
   226  	}
   227  	body := GetBody(db, hash, number)
   228  	if body == nil {
   229  		return nil
   230  	}
   231  	// Reassemble the block and return
   232  	return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles)
   233  }
   234  
   235  // GetBlockReceipts retrieves the receipts generated by the transactions included
   236  // in a block given by its hash.
   237  func GetBlockReceipts(db DatabaseReader, hash common.Hash, number uint64) types.Receipts {
   238  	data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...))
   239  	if len(data) == 0 {
   240  		return nil
   241  	}
   242  	storageReceipts := []*types.ReceiptForStorage{}
   243  	if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
   244  		log.Error("Invalid receipt array RLP", "hash", hash, "err", err)
   245  		return nil
   246  	}
   247  	receipts := make(types.Receipts, len(storageReceipts))
   248  	for i, receipt := range storageReceipts {
   249  		receipts[i] = (*types.Receipt)(receipt)
   250  	}
   251  	return receipts
   252  }
   253  
   254  // GetTxLookupEntry retrieves the positional metadata associated with a transaction
   255  // hash to allow retrieving the transaction or receipt by hash.
   256  func GetTxLookupEntry(db DatabaseReader, hash common.Hash) (common.Hash, uint64, uint64) {
   257  	// Load the positional metadata from disk and bail if it fails
   258  	data, _ := db.Get(append(lookupPrefix, hash.Bytes()...))
   259  	if len(data) == 0 {
   260  		return common.Hash{}, 0, 0
   261  	}
   262  	// Parse and return the contents of the lookup entry
   263  	var entry TxLookupEntry
   264  	if err := rlp.DecodeBytes(data, &entry); err != nil {
   265  		log.Error("Invalid lookup entry RLP", "hash", hash, "err", err)
   266  		return common.Hash{}, 0, 0
   267  	}
   268  	return entry.BlockHash, entry.BlockIndex, entry.Index
   269  }
   270  
   271  // GetTransaction retrieves a specific transaction from the database, along with
   272  // its added positional metadata.
   273  func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
   274  	// Retrieve the lookup metadata and resolve the transaction from the body
   275  	blockHash, blockNumber, txIndex := GetTxLookupEntry(db, hash)
   276  
   277  	if blockHash != (common.Hash{}) {
   278  		body := GetBody(db, blockHash, blockNumber)
   279  		if body == nil || len(body.Transactions) <= int(txIndex) {
   280  			log.Error("Transaction referenced missing", "number", blockNumber, "hash", blockHash, "index", txIndex)
   281  			return nil, common.Hash{}, 0, 0
   282  		}
   283  		return body.Transactions[txIndex], blockHash, blockNumber, txIndex
   284  	}
   285  	// Old transaction representation, load the transaction and it's metadata separately
   286  	data, _ := db.Get(hash.Bytes())
   287  	if len(data) == 0 {
   288  		return nil, common.Hash{}, 0, 0
   289  	}
   290  	var tx types.Transaction
   291  	if err := rlp.DecodeBytes(data, &tx); err != nil {
   292  		return nil, common.Hash{}, 0, 0
   293  	}
   294  	// Retrieve the blockchain positional metadata
   295  	data, _ = db.Get(append(hash.Bytes(), oldTxMetaSuffix...))
   296  	if len(data) == 0 {
   297  		return nil, common.Hash{}, 0, 0
   298  	}
   299  	var entry TxLookupEntry
   300  	if err := rlp.DecodeBytes(data, &entry); err != nil {
   301  		return nil, common.Hash{}, 0, 0
   302  	}
   303  	return &tx, entry.BlockHash, entry.BlockIndex, entry.Index
   304  }
   305  
   306  // GetReceipt retrieves a specific transaction receipt from the database, along with
   307  // its added positional metadata.
   308  func GetReceipt(db DatabaseReader, hash common.Hash) (*types.Receipt, common.Hash, uint64, uint64) {
   309  	// Retrieve the lookup metadata and resolve the receipt from the receipts
   310  	blockHash, blockNumber, receiptIndex := GetTxLookupEntry(db, hash)
   311  
   312  	if blockHash != (common.Hash{}) {
   313  		receipts := GetBlockReceipts(db, blockHash, blockNumber)
   314  		if len(receipts) <= int(receiptIndex) {
   315  			log.Error("Receipt refereced missing", "number", blockNumber, "hash", blockHash, "index", receiptIndex)
   316  			return nil, common.Hash{}, 0, 0
   317  		}
   318  		return receipts[receiptIndex], blockHash, blockNumber, receiptIndex
   319  	}
   320  	// Old receipt representation, load the receipt and set an unknown metadata
   321  	data, _ := db.Get(append(oldReceiptsPrefix, hash[:]...))
   322  	if len(data) == 0 {
   323  		return nil, common.Hash{}, 0, 0
   324  	}
   325  	var receipt types.ReceiptForStorage
   326  	err := rlp.DecodeBytes(data, &receipt)
   327  	if err != nil {
   328  		log.Error("Invalid receipt RLP", "hash", hash, "err", err)
   329  	}
   330  	return (*types.Receipt)(&receipt), common.Hash{}, 0, 0
   331  }
   332  
   333  // GetBloomBits retrieves the compressed bloom bit vector belonging to the given
   334  // section and bit index from the.
   335  func GetBloomBits(db DatabaseReader, bit uint, section uint64, head common.Hash) ([]byte, error) {
   336  	key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...)
   337  
   338  	binary.BigEndian.PutUint16(key[1:], uint16(bit))
   339  	binary.BigEndian.PutUint64(key[3:], section)
   340  
   341  	return db.Get(key)
   342  }
   343  
   344  // WriteCanonicalHash stores the canonical hash for the given block number.
   345  func WriteCanonicalHash(db ethdb.Putter, hash common.Hash, number uint64) error {
   346  	key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)
   347  	if err := db.Put(key, hash.Bytes()); err != nil {
   348  		log.Crit("Failed to store number to hash mapping", "err", err)
   349  	}
   350  	return nil
   351  }
   352  
   353  // WriteHeadHeaderHash stores the head header's hash.
   354  func WriteHeadHeaderHash(db ethdb.Putter, hash common.Hash) error {
   355  	if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
   356  		log.Crit("Failed to store last header's hash", "err", err)
   357  	}
   358  	return nil
   359  }
   360  
   361  // WriteHeadBlockHash stores the head block's hash.
   362  func WriteHeadBlockHash(db ethdb.Putter, hash common.Hash) error {
   363  	if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
   364  		log.Crit("Failed to store last block's hash", "err", err)
   365  	}
   366  	return nil
   367  }
   368  
   369  // WriteHeadFastBlockHash stores the fast head block's hash.
   370  func WriteHeadFastBlockHash(db ethdb.Putter, hash common.Hash) error {
   371  	if err := db.Put(headFastKey, hash.Bytes()); err != nil {
   372  		log.Crit("Failed to store last fast block's hash", "err", err)
   373  	}
   374  	return nil
   375  }
   376  
   377  // WriteHeader serializes a block header into the database.
   378  func WriteHeader(db ethdb.Putter, header *types.Header) error {
   379  	data, err := rlp.EncodeToBytes(header)
   380  	if err != nil {
   381  		return err
   382  	}
   383  	hash := header.Hash().Bytes()
   384  	num := header.Number.Uint64()
   385  	encNum := encodeBlockNumber(num)
   386  	key := append(blockHashPrefix, hash...)
   387  	if err := db.Put(key, encNum); err != nil {
   388  		log.Crit("Failed to store hash to number mapping", "err", err)
   389  	}
   390  	key = append(append(headerPrefix, encNum...), hash...)
   391  	if err := db.Put(key, data); err != nil {
   392  		log.Crit("Failed to store header", "err", err)
   393  	}
   394  	return nil
   395  }
   396  
   397  // WriteBody serializes the body of a block into the database.
   398  func WriteBody(db ethdb.Putter, hash common.Hash, number uint64, body *types.Body) error {
   399  	data, err := rlp.EncodeToBytes(body)
   400  	if err != nil {
   401  		return err
   402  	}
   403  	return WriteBodyRLP(db, hash, number, data)
   404  }
   405  
   406  // WriteBodyRLP writes a serialized body of a block into the database.
   407  func WriteBodyRLP(db ethdb.Putter, hash common.Hash, number uint64, rlp rlp.RawValue) error {
   408  	key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   409  	if err := db.Put(key, rlp); err != nil {
   410  		log.Crit("Failed to store block body", "err", err)
   411  	}
   412  	return nil
   413  }
   414  
   415  // WriteTd serializes the total difficulty of a block into the database.
   416  func WriteTd(db ethdb.Putter, hash common.Hash, number uint64, td *big.Int) error {
   417  	data, err := rlp.EncodeToBytes(td)
   418  	if err != nil {
   419  		return err
   420  	}
   421  	key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)
   422  	if err := db.Put(key, data); err != nil {
   423  		log.Crit("Failed to store block total difficulty", "err", err)
   424  	}
   425  	return nil
   426  }
   427  
   428  // WriteBlock serializes a block into the database, header and body separately.
   429  func WriteBlock(db ethdb.Putter, block *types.Block) error {
   430  	// Store the body first to retain database consistency
   431  	if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
   432  		return err
   433  	}
   434  	// Store the header too, signaling full block ownership
   435  	if err := WriteHeader(db, block.Header()); err != nil {
   436  		return err
   437  	}
   438  	return nil
   439  }
   440  
   441  // WriteBlockReceipts stores all the transaction receipts belonging to a block
   442  // as a single receipt slice. This is used during chain reorganisations for
   443  // rescheduling dropped transactions.
   444  func WriteBlockReceipts(db ethdb.Putter, hash common.Hash, number uint64, receipts types.Receipts) error {
   445  	// Convert the receipts into their storage form and serialize them
   446  	storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
   447  	for i, receipt := range receipts {
   448  		storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
   449  	}
   450  	bytes, err := rlp.EncodeToBytes(storageReceipts)
   451  	if err != nil {
   452  		return err
   453  	}
   454  	// Store the flattened receipt slice
   455  	key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   456  	if err := db.Put(key, bytes); err != nil {
   457  		log.Crit("Failed to store block receipts", "err", err)
   458  	}
   459  	return nil
   460  }
   461  
   462  // WriteTxLookupEntries stores a positional metadata for every transaction from
   463  // a block, enabling hash based transaction and receipt lookups.
   464  func WriteTxLookupEntries(db ethdb.Putter, block *types.Block) error {
   465  	// Iterate over each transaction and encode its metadata
   466  	for i, tx := range block.Transactions() {
   467  		entry := TxLookupEntry{
   468  			BlockHash:  block.Hash(),
   469  			BlockIndex: block.NumberU64(),
   470  			Index:      uint64(i),
   471  		}
   472  		data, err := rlp.EncodeToBytes(entry)
   473  		if err != nil {
   474  			return err
   475  		}
   476  		if err := db.Put(append(lookupPrefix, tx.Hash().Bytes()...), data); err != nil {
   477  			return err
   478  		}
   479  	}
   480  	return nil
   481  }
   482  
   483  // WriteBloomBits writes the compressed bloom bits vector belonging to the given
   484  // section and bit index.
   485  func WriteBloomBits(db ethdb.Putter, bit uint, section uint64, head common.Hash, bits []byte) {
   486  	key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...)
   487  
   488  	binary.BigEndian.PutUint16(key[1:], uint16(bit))
   489  	binary.BigEndian.PutUint64(key[3:], section)
   490  
   491  	if err := db.Put(key, bits); err != nil {
   492  		log.Crit("Failed to store bloom bits", "err", err)
   493  	}
   494  }
   495  
   496  // DeleteCanonicalHash removes the number to hash canonical mapping.
   497  func DeleteCanonicalHash(db DatabaseDeleter, number uint64) {
   498  	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...))
   499  }
   500  
   501  // DeleteHeader removes all block header data associated with a hash.
   502  func DeleteHeader(db DatabaseDeleter, hash common.Hash, number uint64) {
   503  	db.Delete(append(blockHashPrefix, hash.Bytes()...))
   504  	db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
   505  }
   506  
   507  // DeleteBody removes all block body data associated with a hash.
   508  func DeleteBody(db DatabaseDeleter, hash common.Hash, number uint64) {
   509  	db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
   510  }
   511  
   512  // DeleteTd removes all block total difficulty data associated with a hash.
   513  func DeleteTd(db DatabaseDeleter, hash common.Hash, number uint64) {
   514  	db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...))
   515  }
   516  
   517  // DeleteBlock removes all block data associated with a hash.
   518  func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) {
   519  	DeleteBlockReceipts(db, hash, number)
   520  	DeleteHeader(db, hash, number)
   521  	DeleteBody(db, hash, number)
   522  	DeleteTd(db, hash, number)
   523  }
   524  
   525  // DeleteBlockReceipts removes all receipt data associated with a block hash.
   526  func DeleteBlockReceipts(db DatabaseDeleter, hash common.Hash, number uint64) {
   527  	db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...))
   528  }
   529  
   530  // DeleteTxLookupEntry removes all transaction data associated with a hash.
   531  func DeleteTxLookupEntry(db DatabaseDeleter, hash common.Hash) {
   532  	db.Delete(append(lookupPrefix, hash.Bytes()...))
   533  }
   534  
   535  // PreimageTable returns a Database instance with the key prefix for preimage entries.
   536  func PreimageTable(db ethdb.Database) ethdb.Database {
   537  	return ethdb.NewTable(db, preimagePrefix)
   538  }
   539  
   540  // WritePreimages writes the provided set of preimages to the database. `number` is the
   541  // current block number, and is used for debug messages only.
   542  func WritePreimages(db ethdb.Database, number uint64, preimages map[common.Hash][]byte) error {
   543  	table := PreimageTable(db)
   544  	batch := table.NewBatch()
   545  	hitCount := 0
   546  	for hash, preimage := range preimages {
   547  		if _, err := table.Get(hash.Bytes()); err != nil {
   548  			batch.Put(hash.Bytes(), preimage)
   549  			hitCount++
   550  		}
   551  	}
   552  	preimageCounter.Inc(int64(len(preimages)))
   553  	preimageHitCounter.Inc(int64(hitCount))
   554  	if hitCount > 0 {
   555  		if err := batch.Write(); err != nil {
   556  			return fmt.Errorf("preimage write fail for block %d: %v", number, err)
   557  		}
   558  	}
   559  	return nil
   560  }
   561  
   562  // GetBlockChainVersion reads the version number from db.
   563  func GetBlockChainVersion(db DatabaseReader) int {
   564  	var vsn uint
   565  	enc, _ := db.Get([]byte("BlockchainVersion"))
   566  	rlp.DecodeBytes(enc, &vsn)
   567  	return int(vsn)
   568  }
   569  
   570  // WriteBlockChainVersion writes vsn as the version number to db.
   571  func WriteBlockChainVersion(db ethdb.Putter, vsn int) {
   572  	enc, _ := rlp.EncodeToBytes(uint(vsn))
   573  	db.Put([]byte("BlockchainVersion"), enc)
   574  }
   575  
   576  // WriteChainConfig writes the chain config settings to the database.
   577  func WriteChainConfig(db ethdb.Putter, hash common.Hash, cfg *params.ChainConfig) error {
   578  	// short circuit and ignore if nil config. GetChainConfig
   579  	// will return a default.
   580  	if cfg == nil {
   581  		return nil
   582  	}
   583  
   584  	jsonChainConfig, err := json.Marshal(cfg)
   585  	if err != nil {
   586  		return err
   587  	}
   588  
   589  	return db.Put(append(configPrefix, hash[:]...), jsonChainConfig)
   590  }
   591  
   592  // GetChainConfig will fetch the network settings based on the given hash.
   593  func GetChainConfig(db DatabaseReader, hash common.Hash) (*params.ChainConfig, error) {
   594  	jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...))
   595  	if len(jsonChainConfig) == 0 {
   596  		return nil, ErrChainConfigNotFound
   597  	}
   598  
   599  	var config params.ChainConfig
   600  	if err := json.Unmarshal(jsonChainConfig, &config); err != nil {
   601  		return nil, err
   602  	}
   603  
   604  	return &config, nil
   605  }
   606  
   607  // FindCommonAncestor returns the last common ancestor of two block headers
   608  func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header {
   609  	for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
   610  		a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
   611  		if a == nil {
   612  			return nil
   613  		}
   614  	}
   615  	for an := a.Number.Uint64(); an < b.Number.Uint64(); {
   616  		b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
   617  		if b == nil {
   618  			return nil
   619  		}
   620  	}
   621  	for a.Hash() != b.Hash() {
   622  		a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1)
   623  		if a == nil {
   624  			return nil
   625  		}
   626  		b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1)
   627  		if b == nil {
   628  			return nil
   629  		}
   630  	}
   631  	return a
   632  }