github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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  	"errors"
    24  
    25  	leveldb "github.com/syndtr/goleveldb/leveldb/errors"
    26  
    27  	"github.com/scroll-tech/go-ethereum/common"
    28  	"github.com/scroll-tech/go-ethereum/ethdb/memorydb"
    29  	"github.com/scroll-tech/go-ethereum/metrics"
    30  )
    31  
    32  // The fields below define the low level database schema prefixing.
    33  var (
    34  	// databaseVersionKey tracks the current database version.
    35  	databaseVersionKey = []byte("DatabaseVersion")
    36  
    37  	// headHeaderKey tracks the latest known header's hash.
    38  	headHeaderKey = []byte("LastHeader")
    39  
    40  	// headBlockKey tracks the latest known full block's hash.
    41  	headBlockKey = []byte("LastBlock")
    42  
    43  	// headFastBlockKey tracks the latest known incomplete block's hash during fast sync.
    44  	headFastBlockKey = []byte("LastFast")
    45  
    46  	// lastPivotKey tracks the last pivot block used by fast sync (to reenable on sethead).
    47  	lastPivotKey = []byte("LastPivot")
    48  
    49  	// fastTrieProgressKey tracks the number of trie entries imported during fast sync.
    50  	fastTrieProgressKey = []byte("TrieSync")
    51  
    52  	// snapshotDisabledKey flags that the snapshot should not be maintained due to initial sync.
    53  	snapshotDisabledKey = []byte("SnapshotDisabled")
    54  
    55  	// SnapshotRootKey tracks the hash of the last snapshot.
    56  	SnapshotRootKey = []byte("SnapshotRoot")
    57  
    58  	// snapshotJournalKey tracks the in-memory diff layers across restarts.
    59  	snapshotJournalKey = []byte("SnapshotJournal")
    60  
    61  	// snapshotGeneratorKey tracks the snapshot generation marker across restarts.
    62  	snapshotGeneratorKey = []byte("SnapshotGenerator")
    63  
    64  	// snapshotRecoveryKey tracks the snapshot recovery marker across restarts.
    65  	snapshotRecoveryKey = []byte("SnapshotRecovery")
    66  
    67  	// snapshotSyncStatusKey tracks the snapshot sync status across restarts.
    68  	snapshotSyncStatusKey = []byte("SnapshotSyncStatus")
    69  
    70  	// txIndexTailKey tracks the oldest block whose transactions have been indexed.
    71  	txIndexTailKey = []byte("TransactionIndexTail")
    72  
    73  	// fastTxLookupLimitKey tracks the transaction lookup limit during fast sync.
    74  	fastTxLookupLimitKey = []byte("FastTransactionLookupLimit")
    75  
    76  	// badBlockKey tracks the list of bad blocks seen by local
    77  	badBlockKey = []byte("InvalidBlock")
    78  
    79  	// uncleanShutdownKey tracks the list of local crashes
    80  	uncleanShutdownKey = []byte("unclean-shutdown") // config prefix for the db
    81  
    82  	// Data item prefixes (use single byte to avoid mixing data types, avoid `i`, used for indexes).
    83  	headerPrefix       = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
    84  	headerTDSuffix     = []byte("t") // headerPrefix + num (uint64 big endian) + hash + headerTDSuffix -> td
    85  	headerHashSuffix   = []byte("n") // headerPrefix + num (uint64 big endian) + headerHashSuffix -> hash
    86  	headerNumberPrefix = []byte("H") // headerNumberPrefix + hash -> num (uint64 big endian)
    87  
    88  	blockBodyPrefix     = []byte("b") // blockBodyPrefix + num (uint64 big endian) + hash -> block body
    89  	blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts
    90  
    91  	txLookupPrefix        = []byte("l") // txLookupPrefix + hash -> transaction/receipt lookup metadata
    92  	bloomBitsPrefix       = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits
    93  	SnapshotAccountPrefix = []byte("a") // SnapshotAccountPrefix + account hash -> account trie value
    94  	SnapshotStoragePrefix = []byte("o") // SnapshotStoragePrefix + account hash + storage hash -> storage trie value
    95  	CodePrefix            = []byte("c") // CodePrefix + code hash -> account code
    96  
    97  	PreimagePrefix = []byte("secure-key-")      // PreimagePrefix + hash -> preimage
    98  	configPrefix   = []byte("ethereum-config-") // config prefix for the db
    99  
   100  	// Chain index prefixes (use `i` + single byte to avoid mixing data types).
   101  	BloomBitsIndexPrefix = []byte("iB") // BloomBitsIndexPrefix is the data table of a chain indexer to track its progress
   102  
   103  	preimageCounter    = metrics.NewRegisteredCounter("db/preimage/total", nil)
   104  	preimageHitCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil)
   105  
   106  	// Scroll L1 message store
   107  	syncedL1BlockNumberKey            = []byte("LastSyncedL1BlockNumber")
   108  	l1MessageLegacyPrefix             = []byte("l1")
   109  	l1MessagePrefix                   = []byte("L1") // l1MessagePrefix + queueIndex (uint64 big endian) -> L1MessageTx
   110  	firstQueueIndexNotInL2BlockPrefix = []byte("q")  // firstQueueIndexNotInL2BlockPrefix + L2 block hash -> enqueue index
   111  	highestSyncedQueueIndexKey        = []byte("HighestSyncedQueueIndex")
   112  
   113  	// Scroll rollup event store
   114  	rollupEventSyncedL1BlockNumberKey = []byte("R-LastRollupEventSyncedL1BlockNumber")
   115  	batchChunkRangesPrefix            = []byte("R-bcr")
   116  	batchMetaPrefix                   = []byte("R-bm")
   117  	finalizedL2BlockNumberKey         = []byte("R-finalized")
   118  
   119  	// Row consumption
   120  	rowConsumptionPrefix = []byte("rc") // rowConsumptionPrefix + hash -> row consumption by block
   121  
   122  	// Skipped transactions
   123  	numSkippedTransactionsKey    = []byte("NumberOfSkippedTransactions")
   124  	skippedTransactionPrefix     = []byte("skip") // skippedTransactionPrefix + tx hash -> skipped transaction
   125  	skippedTransactionHashPrefix = []byte("sh")   // skippedTransactionHashPrefix + index -> tx hash
   126  )
   127  
   128  // Use the updated "L1" prefix on all new networks
   129  // to avoid overlap with txLookupPrefix.
   130  // Use the legacy "l1" prefix on Scroll Sepolia.
   131  func SetL1MessageLegacyPrefix() {
   132  	l1MessagePrefix = l1MessageLegacyPrefix
   133  }
   134  
   135  const (
   136  	// freezerHeaderTable indicates the name of the freezer header table.
   137  	freezerHeaderTable = "headers"
   138  
   139  	// freezerHashTable indicates the name of the freezer canonical hash table.
   140  	freezerHashTable = "hashes"
   141  
   142  	// freezerBodiesTable indicates the name of the freezer block body table.
   143  	freezerBodiesTable = "bodies"
   144  
   145  	// freezerReceiptTable indicates the name of the freezer receipts table.
   146  	freezerReceiptTable = "receipts"
   147  
   148  	// freezerDifficultyTable indicates the name of the freezer total difficulty table.
   149  	freezerDifficultyTable = "diffs"
   150  )
   151  
   152  // FreezerNoSnappy configures whether compression is disabled for the ancient-tables.
   153  // Hashes and difficulties don't compress well.
   154  var FreezerNoSnappy = map[string]bool{
   155  	freezerHeaderTable:     false,
   156  	freezerHashTable:       true,
   157  	freezerBodiesTable:     false,
   158  	freezerReceiptTable:    false,
   159  	freezerDifficultyTable: true,
   160  }
   161  
   162  // LegacyTxLookupEntry is the legacy TxLookupEntry definition with some unnecessary
   163  // fields.
   164  type LegacyTxLookupEntry struct {
   165  	BlockHash  common.Hash
   166  	BlockIndex uint64
   167  	Index      uint64
   168  }
   169  
   170  // encodeBlockNumber encodes a block number as big endian uint64
   171  func encodeBlockNumber(number uint64) []byte {
   172  	enc := make([]byte, 8)
   173  	binary.BigEndian.PutUint64(enc, number)
   174  	return enc
   175  }
   176  
   177  // headerKeyPrefix = headerPrefix + num (uint64 big endian)
   178  func headerKeyPrefix(number uint64) []byte {
   179  	return append(headerPrefix, encodeBlockNumber(number)...)
   180  }
   181  
   182  // headerKey = headerPrefix + num (uint64 big endian) + hash
   183  func headerKey(number uint64, hash common.Hash) []byte {
   184  	return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   185  }
   186  
   187  // headerTDKey = headerPrefix + num (uint64 big endian) + hash + headerTDSuffix
   188  func headerTDKey(number uint64, hash common.Hash) []byte {
   189  	return append(headerKey(number, hash), headerTDSuffix...)
   190  }
   191  
   192  // headerHashKey = headerPrefix + num (uint64 big endian) + headerHashSuffix
   193  func headerHashKey(number uint64) []byte {
   194  	return append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...)
   195  }
   196  
   197  // headerNumberKey = headerNumberPrefix + hash
   198  func headerNumberKey(hash common.Hash) []byte {
   199  	return append(headerNumberPrefix, hash.Bytes()...)
   200  }
   201  
   202  // blockBodyKey = blockBodyPrefix + num (uint64 big endian) + hash
   203  func blockBodyKey(number uint64, hash common.Hash) []byte {
   204  	return append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   205  }
   206  
   207  // blockReceiptsKey = blockReceiptsPrefix + num (uint64 big endian) + hash
   208  func blockReceiptsKey(number uint64, hash common.Hash) []byte {
   209  	return append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)
   210  }
   211  
   212  // txLookupKey = txLookupPrefix + hash
   213  func txLookupKey(hash common.Hash) []byte {
   214  	return append(txLookupPrefix, hash.Bytes()...)
   215  }
   216  
   217  // accountSnapshotKey = SnapshotAccountPrefix + hash
   218  func accountSnapshotKey(hash common.Hash) []byte {
   219  	return append(SnapshotAccountPrefix, hash.Bytes()...)
   220  }
   221  
   222  // storageSnapshotKey = SnapshotStoragePrefix + account hash + storage hash
   223  func storageSnapshotKey(accountHash, storageHash common.Hash) []byte {
   224  	return append(append(SnapshotStoragePrefix, accountHash.Bytes()...), storageHash.Bytes()...)
   225  }
   226  
   227  // storageSnapshotsKey = SnapshotStoragePrefix + account hash + storage hash
   228  func storageSnapshotsKey(accountHash common.Hash) []byte {
   229  	return append(SnapshotStoragePrefix, accountHash.Bytes()...)
   230  }
   231  
   232  // bloomBitsKey = bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash
   233  func bloomBitsKey(bit uint, section uint64, hash common.Hash) []byte {
   234  	key := append(append(bloomBitsPrefix, make([]byte, 10)...), hash.Bytes()...)
   235  
   236  	binary.BigEndian.PutUint16(key[1:], uint16(bit))
   237  	binary.BigEndian.PutUint64(key[3:], section)
   238  
   239  	return key
   240  }
   241  
   242  // preimageKey = PreimagePrefix + hash
   243  func preimageKey(hash common.Hash) []byte {
   244  	return append(PreimagePrefix, hash.Bytes()...)
   245  }
   246  
   247  // codeKey = CodePrefix + hash
   248  func codeKey(hash common.Hash) []byte {
   249  	return append(CodePrefix, hash.Bytes()...)
   250  }
   251  
   252  // IsCodeKey reports whether the given byte slice is the key of contract code,
   253  // if so return the raw code hash as well.
   254  func IsCodeKey(key []byte) (bool, []byte) {
   255  	if bytes.HasPrefix(key, CodePrefix) && len(key) == common.HashLength+len(CodePrefix) {
   256  		return true, key[len(CodePrefix):]
   257  	}
   258  	return false, nil
   259  }
   260  
   261  // configKey = configPrefix + hash
   262  func configKey(hash common.Hash) []byte {
   263  	return append(configPrefix, hash.Bytes()...)
   264  }
   265  
   266  // encodeBigEndian encodes an index as big endian uint64
   267  func encodeBigEndian(index uint64) []byte {
   268  	enc := make([]byte, 8)
   269  	binary.BigEndian.PutUint64(enc, index)
   270  	return enc
   271  }
   272  
   273  // L1MessageKey = l1MessagePrefix + queueIndex (uint64 big endian)
   274  func L1MessageKey(queueIndex uint64) []byte {
   275  	return append(l1MessagePrefix, encodeBigEndian(queueIndex)...)
   276  }
   277  
   278  // FirstQueueIndexNotInL2BlockKey = firstQueueIndexNotInL2BlockPrefix + L2 block hash
   279  func FirstQueueIndexNotInL2BlockKey(l2BlockHash common.Hash) []byte {
   280  	return append(firstQueueIndexNotInL2BlockPrefix, l2BlockHash.Bytes()...)
   281  }
   282  
   283  // rowConsumptionKey = rowConsumptionPrefix + hash
   284  func rowConsumptionKey(hash common.Hash) []byte {
   285  	return append(rowConsumptionPrefix, hash.Bytes()...)
   286  }
   287  
   288  func isNotFoundErr(err error) bool {
   289  	return errors.Is(err, leveldb.ErrNotFound) || errors.Is(err, memorydb.ErrMemorydbNotFound)
   290  }
   291  
   292  // SkippedTransactionKey = skippedTransactionPrefix + tx hash
   293  func SkippedTransactionKey(txHash common.Hash) []byte {
   294  	return append(skippedTransactionPrefix, txHash.Bytes()...)
   295  }
   296  
   297  // SkippedTransactionHashKey = skippedTransactionHashPrefix + index (uint64 big endian)
   298  func SkippedTransactionHashKey(index uint64) []byte {
   299  	return append(skippedTransactionHashPrefix, encodeBigEndian(index)...)
   300  }
   301  
   302  // batchChunkRangesKey = batchChunkRangesPrefix + batch index (uint64 big endian)
   303  func batchChunkRangesKey(batchIndex uint64) []byte {
   304  	return append(batchChunkRangesPrefix, encodeBigEndian(batchIndex)...)
   305  }
   306  
   307  // batchMetaKey = batchMetaPrefix + batch index (uint64 big endian)
   308  func batchMetaKey(batchIndex uint64) []byte {
   309  	return append(batchMetaPrefix, encodeBigEndian(batchIndex)...)
   310  }