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