github.com/ethereum/go-ethereum@v1.14.3/core/rawdb/schema.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 contains a collection of low level database accessors.
    18  package rawdb
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/binary"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/metrics"
    27  )
    28  
    29  // The fields below define the low level database schema prefixing.
    30  var (
    31  	// databaseVersionKey tracks the current database version.
    32  	databaseVersionKey = []byte("DatabaseVersion")
    33  
    34  	// headHeaderKey tracks the latest known header's hash.
    35  	headHeaderKey = []byte("LastHeader")
    36  
    37  	// headBlockKey tracks the latest known full block's hash.
    38  	headBlockKey = []byte("LastBlock")
    39  
    40  	// headFastBlockKey tracks the latest known incomplete block's hash during fast sync.
    41  	headFastBlockKey = []byte("LastFast")
    42  
    43  	// headFinalizedBlockKey tracks the latest known finalized block hash.
    44  	headFinalizedBlockKey = []byte("LastFinalized")
    45  
    46  	// persistentStateIDKey tracks the id of latest stored state(for path-based only).
    47  	persistentStateIDKey = []byte("LastStateID")
    48  
    49  	// lastPivotKey tracks the last pivot block used by fast sync (to reenable on sethead).
    50  	lastPivotKey = []byte("LastPivot")
    51  
    52  	// fastTrieProgressKey tracks the number of trie entries imported during fast sync.
    53  	fastTrieProgressKey = []byte("TrieSync")
    54  
    55  	// snapshotDisabledKey flags that the snapshot should not be maintained due to initial sync.
    56  	snapshotDisabledKey = []byte("SnapshotDisabled")
    57  
    58  	// SnapshotRootKey tracks the hash of the last snapshot.
    59  	SnapshotRootKey = []byte("SnapshotRoot")
    60  
    61  	// snapshotJournalKey tracks the in-memory diff layers across restarts.
    62  	snapshotJournalKey = []byte("SnapshotJournal")
    63  
    64  	// snapshotGeneratorKey tracks the snapshot generation marker across restarts.
    65  	snapshotGeneratorKey = []byte("SnapshotGenerator")
    66  
    67  	// snapshotRecoveryKey tracks the snapshot recovery marker across restarts.
    68  	snapshotRecoveryKey = []byte("SnapshotRecovery")
    69  
    70  	// snapshotSyncStatusKey tracks the snapshot sync status across restarts.
    71  	snapshotSyncStatusKey = []byte("SnapshotSyncStatus")
    72  
    73  	// skeletonSyncStatusKey tracks the skeleton sync status across restarts.
    74  	skeletonSyncStatusKey = []byte("SkeletonSyncStatus")
    75  
    76  	// trieJournalKey tracks the in-memory trie node layers across restarts.
    77  	trieJournalKey = []byte("TrieJournal")
    78  
    79  	// txIndexTailKey tracks the oldest block whose transactions have been indexed.
    80  	txIndexTailKey = []byte("TransactionIndexTail")
    81  
    82  	// fastTxLookupLimitKey tracks the transaction lookup limit during fast sync.
    83  	// This flag is deprecated, it's kept to avoid reporting errors when inspect
    84  	// database.
    85  	fastTxLookupLimitKey = []byte("FastTransactionLookupLimit")
    86  
    87  	// badBlockKey tracks the list of bad blocks seen by local
    88  	badBlockKey = []byte("InvalidBlock")
    89  
    90  	// uncleanShutdownKey tracks the list of local crashes
    91  	uncleanShutdownKey = []byte("unclean-shutdown") // config prefix for the db
    92  
    93  	// transitionStatusKey tracks the eth2 transition status.
    94  	transitionStatusKey = []byte("eth2-transition")
    95  
    96  	// snapSyncStatusFlagKey flags that status of snap sync.
    97  	snapSyncStatusFlagKey = []byte("SnapSyncStatus")
    98  
    99  	// Data item prefixes (use single byte to avoid mixing data types, avoid `i`, used for indexes).
   100  	headerPrefix       = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
   101  	headerTDSuffix     = []byte("t") // headerPrefix + num (uint64 big endian) + hash + headerTDSuffix -> td
   102  	headerHashSuffix   = []byte("n") // headerPrefix + num (uint64 big endian) + headerHashSuffix -> hash
   103  	headerNumberPrefix = []byte("H") // headerNumberPrefix + hash -> num (uint64 big endian)
   104  
   105  	blockBodyPrefix     = []byte("b") // blockBodyPrefix + num (uint64 big endian) + hash -> block body
   106  	blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
   107  
   108  	txLookupPrefix        = []byte("l") // txLookupPrefix + hash -> transaction/receipt lookup metadata
   109  	bloomBitsPrefix       = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits
   110  	SnapshotAccountPrefix = []byte("a") // SnapshotAccountPrefix + account hash -> account trie value
   111  	SnapshotStoragePrefix = []byte("o") // SnapshotStoragePrefix + account hash + storage hash -> storage trie value
   112  	CodePrefix            = []byte("c") // CodePrefix + code hash -> account code
   113  	skeletonHeaderPrefix  = []byte("S") // skeletonHeaderPrefix + num (uint64 big endian) -> header
   114  
   115  	// Path-based storage scheme of merkle patricia trie.
   116  	TrieNodeAccountPrefix = []byte("A") // TrieNodeAccountPrefix + hexPath -> trie node
   117  	TrieNodeStoragePrefix = []byte("O") // TrieNodeStoragePrefix + accountHash + hexPath -> trie node
   118  	stateIDPrefix         = []byte("L") // stateIDPrefix + state root -> state id
   119  
   120  	PreimagePrefix = []byte("secure-key-")       // PreimagePrefix + hash -> preimage
   121  	configPrefix   = []byte("ethereum-config-")  // config prefix for the db
   122  	genesisPrefix  = []byte("ethereum-genesis-") // genesis state prefix for the db
   123  
   124  	// BloomBitsIndexPrefix is the data table of a chain indexer to track its progress
   125  	BloomBitsIndexPrefix = []byte("iB")
   126  
   127  	ChtPrefix           = []byte("chtRootV2-") // ChtPrefix + chtNum (uint64 big endian) -> trie root hash
   128  	ChtTablePrefix      = []byte("cht-")
   129  	ChtIndexTablePrefix = []byte("chtIndexV2-")
   130  
   131  	BloomTriePrefix      = []byte("bltRoot-") // BloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
   132  	BloomTrieTablePrefix = []byte("blt-")
   133  	BloomTrieIndexPrefix = []byte("bltIndex-")
   134  
   135  	CliqueSnapshotPrefix = []byte("clique-")
   136  
   137  	BestUpdateKey         = []byte("update-")    // bigEndian64(syncPeriod) -> RLP(types.LightClientUpdate)  (nextCommittee only referenced by root hash)
   138  	FixedCommitteeRootKey = []byte("fixedRoot-") // bigEndian64(syncPeriod) -> committee root hash
   139  	SyncCommitteeKey      = []byte("committee-") // bigEndian64(syncPeriod) -> serialized committee
   140  
   141  	preimageCounter    = metrics.NewRegisteredCounter("db/preimage/total", nil)
   142  	preimageHitCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil)
   143  )
   144  
   145  // LegacyTxLookupEntry is the legacy TxLookupEntry definition with some unnecessary
   146  // fields.
   147  type LegacyTxLookupEntry struct {
   148  	BlockHash  common.Hash
   149  	BlockIndex uint64
   150  	Index      uint64
   151  }
   152  
   153  // encodeBlockNumber encodes a block number as big endian uint64
   154  func encodeBlockNumber(number uint64) []byte {
   155  	enc := make([]byte, 8)
   156  	binary.BigEndian.PutUint64(enc, number)
   157  	return enc
   158  }
   159  
   160  // headerKeyPrefix = headerPrefix + num (uint64 big endian)
   161  func headerKeyPrefix(number uint64) []byte {
   162  	return append(headerPrefix, encodeBlockNumber(number)...)
   163  }
   164  
   165  // headerKey = headerPrefix + num (uint64 big endian) + hash
   166  func headerKey(number uint64, hash common.Hash) []byte {
   167  	return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   168  }
   169  
   170  // headerTDKey = headerPrefix + num (uint64 big endian) + hash + headerTDSuffix
   171  func headerTDKey(number uint64, hash common.Hash) []byte {
   172  	return append(headerKey(number, hash), headerTDSuffix...)
   173  }
   174  
   175  // headerHashKey = headerPrefix + num (uint64 big endian) + headerHashSuffix
   176  func headerHashKey(number uint64) []byte {
   177  	return append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...)
   178  }
   179  
   180  // headerNumberKey = headerNumberPrefix + hash
   181  func headerNumberKey(hash common.Hash) []byte {
   182  	return append(headerNumberPrefix, hash.Bytes()...)
   183  }
   184  
   185  // blockBodyKey = blockBodyPrefix + num (uint64 big endian) + hash
   186  func blockBodyKey(number uint64, hash common.Hash) []byte {
   187  	return append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   188  }
   189  
   190  // blockReceiptsKey = blockReceiptsPrefix + num (uint64 big endian) + hash
   191  func blockReceiptsKey(number uint64, hash common.Hash) []byte {
   192  	return append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   193  }
   194  
   195  // txLookupKey = txLookupPrefix + hash
   196  func txLookupKey(hash common.Hash) []byte {
   197  	return append(txLookupPrefix, hash.Bytes()...)
   198  }
   199  
   200  // accountSnapshotKey = SnapshotAccountPrefix + hash
   201  func accountSnapshotKey(hash common.Hash) []byte {
   202  	return append(SnapshotAccountPrefix, hash.Bytes()...)
   203  }
   204  
   205  // storageSnapshotKey = SnapshotStoragePrefix + account hash + storage hash
   206  func storageSnapshotKey(accountHash, storageHash common.Hash) []byte {
   207  	buf := make([]byte, len(SnapshotStoragePrefix)+common.HashLength+common.HashLength)
   208  	n := copy(buf, SnapshotStoragePrefix)
   209  	n += copy(buf[n:], accountHash.Bytes())
   210  	copy(buf[n:], storageHash.Bytes())
   211  	return buf
   212  }
   213  
   214  // storageSnapshotsKey = SnapshotStoragePrefix + account hash + storage hash
   215  func storageSnapshotsKey(accountHash common.Hash) []byte {
   216  	return append(SnapshotStoragePrefix, accountHash.Bytes()...)
   217  }
   218  
   219  // bloomBitsKey = bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash
   220  func bloomBitsKey(bit uint, section uint64, hash common.Hash) []byte {
   221  	key := append(append(bloomBitsPrefix, make([]byte, 10)...), hash.Bytes()...)
   222  
   223  	binary.BigEndian.PutUint16(key[1:], uint16(bit))
   224  	binary.BigEndian.PutUint64(key[3:], section)
   225  
   226  	return key
   227  }
   228  
   229  // skeletonHeaderKey = skeletonHeaderPrefix + num (uint64 big endian)
   230  func skeletonHeaderKey(number uint64) []byte {
   231  	return append(skeletonHeaderPrefix, encodeBlockNumber(number)...)
   232  }
   233  
   234  // preimageKey = PreimagePrefix + hash
   235  func preimageKey(hash common.Hash) []byte {
   236  	return append(PreimagePrefix, hash.Bytes()...)
   237  }
   238  
   239  // codeKey = CodePrefix + hash
   240  func codeKey(hash common.Hash) []byte {
   241  	return append(CodePrefix, hash.Bytes()...)
   242  }
   243  
   244  // IsCodeKey reports whether the given byte slice is the key of contract code,
   245  // if so return the raw code hash as well.
   246  func IsCodeKey(key []byte) (bool, []byte) {
   247  	if bytes.HasPrefix(key, CodePrefix) && len(key) == common.HashLength+len(CodePrefix) {
   248  		return true, key[len(CodePrefix):]
   249  	}
   250  	return false, nil
   251  }
   252  
   253  // configKey = configPrefix + hash
   254  func configKey(hash common.Hash) []byte {
   255  	return append(configPrefix, hash.Bytes()...)
   256  }
   257  
   258  // genesisStateSpecKey = genesisPrefix + hash
   259  func genesisStateSpecKey(hash common.Hash) []byte {
   260  	return append(genesisPrefix, hash.Bytes()...)
   261  }
   262  
   263  // stateIDKey = stateIDPrefix + root (32 bytes)
   264  func stateIDKey(root common.Hash) []byte {
   265  	return append(stateIDPrefix, root.Bytes()...)
   266  }
   267  
   268  // accountTrieNodeKey = TrieNodeAccountPrefix + nodePath.
   269  func accountTrieNodeKey(path []byte) []byte {
   270  	return append(TrieNodeAccountPrefix, path...)
   271  }
   272  
   273  // storageTrieNodeKey = TrieNodeStoragePrefix + accountHash + nodePath.
   274  func storageTrieNodeKey(accountHash common.Hash, path []byte) []byte {
   275  	buf := make([]byte, len(TrieNodeStoragePrefix)+common.HashLength+len(path))
   276  	n := copy(buf, TrieNodeStoragePrefix)
   277  	n += copy(buf[n:], accountHash.Bytes())
   278  	copy(buf[n:], path)
   279  	return buf
   280  }
   281  
   282  // IsLegacyTrieNode reports whether a provided database entry is a legacy trie
   283  // node. The characteristics of legacy trie node are:
   284  // - the key length is 32 bytes
   285  // - the key is the hash of val
   286  func IsLegacyTrieNode(key []byte, val []byte) bool {
   287  	if len(key) != common.HashLength {
   288  		return false
   289  	}
   290  	return bytes.Equal(key, crypto.Keccak256(val))
   291  }
   292  
   293  // ResolveAccountTrieNodeKey reports whether a provided database entry is an
   294  // account trie node in path-based state scheme, and returns the resolved
   295  // node path if so.
   296  func ResolveAccountTrieNodeKey(key []byte) (bool, []byte) {
   297  	if !bytes.HasPrefix(key, TrieNodeAccountPrefix) {
   298  		return false, nil
   299  	}
   300  	// The remaining key should only consist a hex node path
   301  	// whose length is in the range 0 to 64 (64 is excluded
   302  	// since leaves are always wrapped with shortNode).
   303  	if len(key) >= len(TrieNodeAccountPrefix)+common.HashLength*2 {
   304  		return false, nil
   305  	}
   306  	return true, key[len(TrieNodeAccountPrefix):]
   307  }
   308  
   309  // IsAccountTrieNode reports whether a provided database entry is an account
   310  // trie node in path-based state scheme.
   311  func IsAccountTrieNode(key []byte) bool {
   312  	ok, _ := ResolveAccountTrieNodeKey(key)
   313  	return ok
   314  }
   315  
   316  // ResolveStorageTrieNode reports whether a provided database entry is a storage
   317  // trie node in path-based state scheme, and returns the resolved account hash
   318  // and node path if so.
   319  func ResolveStorageTrieNode(key []byte) (bool, common.Hash, []byte) {
   320  	if !bytes.HasPrefix(key, TrieNodeStoragePrefix) {
   321  		return false, common.Hash{}, nil
   322  	}
   323  	// The remaining key consists of 2 parts:
   324  	// - 32 bytes account hash
   325  	// - hex node path whose length is in the range 0 to 64
   326  	if len(key) < len(TrieNodeStoragePrefix)+common.HashLength {
   327  		return false, common.Hash{}, nil
   328  	}
   329  	if len(key) >= len(TrieNodeStoragePrefix)+common.HashLength+common.HashLength*2 {
   330  		return false, common.Hash{}, nil
   331  	}
   332  	accountHash := common.BytesToHash(key[len(TrieNodeStoragePrefix) : len(TrieNodeStoragePrefix)+common.HashLength])
   333  	return true, accountHash, key[len(TrieNodeStoragePrefix)+common.HashLength:]
   334  }
   335  
   336  // IsStorageTrieNode reports whether a provided database entry is a storage
   337  // trie node in path-based state scheme.
   338  func IsStorageTrieNode(key []byte) bool {
   339  	ok, _, _ := ResolveStorageTrieNode(key)
   340  	return ok
   341  }