github.com/ethereum/go-ethereum@v1.16.1/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 // headStateHistoryIndexKey tracks the ID of the latest state history that has 80 // been indexed. 81 headStateHistoryIndexKey = []byte("LastStateHistoryIndex") 82 83 // txIndexTailKey tracks the oldest block whose transactions have been indexed. 84 txIndexTailKey = []byte("TransactionIndexTail") 85 86 // fastTxLookupLimitKey tracks the transaction lookup limit during fast sync. 87 // This flag is deprecated, it's kept to avoid reporting errors when inspect 88 // database. 89 fastTxLookupLimitKey = []byte("FastTransactionLookupLimit") 90 91 // badBlockKey tracks the list of bad blocks seen by local 92 badBlockKey = []byte("InvalidBlock") 93 94 // uncleanShutdownKey tracks the list of local crashes 95 uncleanShutdownKey = []byte("unclean-shutdown") // config prefix for the db 96 97 // transitionStatusKey tracks the eth2 transition status. 98 transitionStatusKey = []byte("eth2-transition") 99 100 // snapSyncStatusFlagKey flags that status of snap sync. 101 snapSyncStatusFlagKey = []byte("SnapSyncStatus") 102 103 // Data item prefixes (use single byte to avoid mixing data types, avoid `i`, used for indexes). 104 headerPrefix = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header 105 headerTDSuffix = []byte("t") // headerPrefix + num (uint64 big endian) + hash + headerTDSuffix -> td (deprecated) 106 headerHashSuffix = []byte("n") // headerPrefix + num (uint64 big endian) + headerHashSuffix -> hash 107 headerNumberPrefix = []byte("H") // headerNumberPrefix + hash -> num (uint64 big endian) 108 109 blockBodyPrefix = []byte("b") // blockBodyPrefix + num (uint64 big endian) + hash -> block body 110 blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts 111 112 txLookupPrefix = []byte("l") // txLookupPrefix + hash -> transaction/receipt lookup metadata 113 bloomBitsPrefix = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits 114 SnapshotAccountPrefix = []byte("a") // SnapshotAccountPrefix + account hash -> account trie value 115 SnapshotStoragePrefix = []byte("o") // SnapshotStoragePrefix + account hash + storage hash -> storage trie value 116 CodePrefix = []byte("c") // CodePrefix + code hash -> account code 117 skeletonHeaderPrefix = []byte("S") // skeletonHeaderPrefix + num (uint64 big endian) -> header 118 119 // Path-based storage scheme of merkle patricia trie. 120 TrieNodeAccountPrefix = []byte("A") // TrieNodeAccountPrefix + hexPath -> trie node 121 TrieNodeStoragePrefix = []byte("O") // TrieNodeStoragePrefix + accountHash + hexPath -> trie node 122 stateIDPrefix = []byte("L") // stateIDPrefix + state root -> state id 123 124 // State history indexing within path-based storage scheme 125 StateHistoryIndexPrefix = []byte("m") // The global prefix of state history index data 126 StateHistoryAccountMetadataPrefix = []byte("ma") // StateHistoryAccountMetadataPrefix + account address hash => account metadata 127 StateHistoryStorageMetadataPrefix = []byte("ms") // StateHistoryStorageMetadataPrefix + account address hash + storage slot hash => slot metadata 128 StateHistoryAccountBlockPrefix = []byte("mba") // StateHistoryAccountBlockPrefix + account address hash + blockID => account block 129 StateHistoryStorageBlockPrefix = []byte("mbs") // StateHistoryStorageBlockPrefix + account address hash + storage slot hash + blockID => slot block 130 131 // VerklePrefix is the database prefix for Verkle trie data, which includes: 132 // (a) Trie nodes 133 // (b) In-memory trie node journal 134 // (c) Persistent state ID 135 // (d) State ID lookups, etc. 136 VerklePrefix = []byte("v") 137 138 PreimagePrefix = []byte("secure-key-") // PreimagePrefix + hash -> preimage 139 configPrefix = []byte("ethereum-config-") // config prefix for the db 140 genesisPrefix = []byte("ethereum-genesis-") // genesis state prefix for the db 141 142 CliqueSnapshotPrefix = []byte("clique-") 143 144 BestUpdateKey = []byte("update-") // bigEndian64(syncPeriod) -> RLP(types.LightClientUpdate) (nextCommittee only referenced by root hash) 145 FixedCommitteeRootKey = []byte("fixedRoot-") // bigEndian64(syncPeriod) -> committee root hash 146 SyncCommitteeKey = []byte("committee-") // bigEndian64(syncPeriod) -> serialized committee 147 148 // new log index 149 filterMapsPrefix = "fm-" 150 filterMapsRangeKey = []byte(filterMapsPrefix + "R") 151 filterMapRowPrefix = []byte(filterMapsPrefix + "r") // filterMapRowPrefix + mapRowIndex (uint64 big endian) -> filter row 152 filterMapLastBlockPrefix = []byte(filterMapsPrefix + "b") // filterMapLastBlockPrefix + mapIndex (uint32 big endian) -> block number (uint64 big endian) 153 filterMapBlockLVPrefix = []byte(filterMapsPrefix + "p") // filterMapBlockLVPrefix + num (uint64 big endian) -> log value pointer (uint64 big endian) 154 155 // old log index 156 bloomBitsMetaPrefix = []byte("iB") 157 158 preimageCounter = metrics.NewRegisteredCounter("db/preimage/total", nil) 159 preimageHitsCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil) 160 preimageMissCounter = metrics.NewRegisteredCounter("db/preimage/miss", nil) 161 ) 162 163 // LegacyTxLookupEntry is the legacy TxLookupEntry definition with some unnecessary 164 // fields. 165 type LegacyTxLookupEntry struct { 166 BlockHash common.Hash 167 BlockIndex uint64 168 Index uint64 169 } 170 171 // encodeBlockNumber encodes a block number as big endian uint64 172 func encodeBlockNumber(number uint64) []byte { 173 enc := make([]byte, 8) 174 binary.BigEndian.PutUint64(enc, number) 175 return enc 176 } 177 178 // headerKeyPrefix = headerPrefix + num (uint64 big endian) 179 func headerKeyPrefix(number uint64) []byte { 180 return append(headerPrefix, encodeBlockNumber(number)...) 181 } 182 183 // headerKey = headerPrefix + num (uint64 big endian) + hash 184 func headerKey(number uint64, hash common.Hash) []byte { 185 return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 186 } 187 188 // headerHashKey = headerPrefix + num (uint64 big endian) + headerHashSuffix 189 func headerHashKey(number uint64) []byte { 190 return append(append(headerPrefix, encodeBlockNumber(number)...), headerHashSuffix...) 191 } 192 193 // headerNumberKey = headerNumberPrefix + hash 194 func headerNumberKey(hash common.Hash) []byte { 195 return append(headerNumberPrefix, hash.Bytes()...) 196 } 197 198 // blockBodyKey = blockBodyPrefix + num (uint64 big endian) + hash 199 func blockBodyKey(number uint64, hash common.Hash) []byte { 200 return append(append(blockBodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 201 } 202 203 // blockReceiptsKey = blockReceiptsPrefix + num (uint64 big endian) + hash 204 func blockReceiptsKey(number uint64, hash common.Hash) []byte { 205 return append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 206 } 207 208 // txLookupKey = txLookupPrefix + hash 209 func txLookupKey(hash common.Hash) []byte { 210 return append(txLookupPrefix, hash.Bytes()...) 211 } 212 213 // accountSnapshotKey = SnapshotAccountPrefix + hash 214 func accountSnapshotKey(hash common.Hash) []byte { 215 return append(SnapshotAccountPrefix, hash.Bytes()...) 216 } 217 218 // storageSnapshotKey = SnapshotStoragePrefix + account hash + storage hash 219 func storageSnapshotKey(accountHash, storageHash common.Hash) []byte { 220 buf := make([]byte, len(SnapshotStoragePrefix)+common.HashLength+common.HashLength) 221 n := copy(buf, SnapshotStoragePrefix) 222 n += copy(buf[n:], accountHash.Bytes()) 223 copy(buf[n:], storageHash.Bytes()) 224 return buf 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 // skeletonHeaderKey = skeletonHeaderPrefix + num (uint64 big endian) 233 func skeletonHeaderKey(number uint64) []byte { 234 return append(skeletonHeaderPrefix, encodeBlockNumber(number)...) 235 } 236 237 // preimageKey = PreimagePrefix + hash 238 func preimageKey(hash common.Hash) []byte { 239 return append(PreimagePrefix, hash.Bytes()...) 240 } 241 242 // codeKey = CodePrefix + hash 243 func codeKey(hash common.Hash) []byte { 244 return append(CodePrefix, hash.Bytes()...) 245 } 246 247 // IsCodeKey reports whether the given byte slice is the key of contract code, 248 // if so return the raw code hash as well. 249 func IsCodeKey(key []byte) (bool, []byte) { 250 if bytes.HasPrefix(key, CodePrefix) && len(key) == common.HashLength+len(CodePrefix) { 251 return true, key[len(CodePrefix):] 252 } 253 return false, nil 254 } 255 256 // configKey = configPrefix + hash 257 func configKey(hash common.Hash) []byte { 258 return append(configPrefix, hash.Bytes()...) 259 } 260 261 // genesisStateSpecKey = genesisPrefix + hash 262 func genesisStateSpecKey(hash common.Hash) []byte { 263 return append(genesisPrefix, hash.Bytes()...) 264 } 265 266 // stateIDKey = stateIDPrefix + root (32 bytes) 267 func stateIDKey(root common.Hash) []byte { 268 return append(stateIDPrefix, root.Bytes()...) 269 } 270 271 // accountTrieNodeKey = TrieNodeAccountPrefix + nodePath. 272 func accountTrieNodeKey(path []byte) []byte { 273 return append(TrieNodeAccountPrefix, path...) 274 } 275 276 // storageTrieNodeKey = TrieNodeStoragePrefix + accountHash + nodePath. 277 func storageTrieNodeKey(accountHash common.Hash, path []byte) []byte { 278 buf := make([]byte, len(TrieNodeStoragePrefix)+common.HashLength+len(path)) 279 n := copy(buf, TrieNodeStoragePrefix) 280 n += copy(buf[n:], accountHash.Bytes()) 281 copy(buf[n:], path) 282 return buf 283 } 284 285 // IsLegacyTrieNode reports whether a provided database entry is a legacy trie 286 // node. The characteristics of legacy trie node are: 287 // - the key length is 32 bytes 288 // - the key is the hash of val 289 func IsLegacyTrieNode(key []byte, val []byte) bool { 290 if len(key) != common.HashLength { 291 return false 292 } 293 return bytes.Equal(key, crypto.Keccak256(val)) 294 } 295 296 // ResolveAccountTrieNodeKey reports whether a provided database entry is an 297 // account trie node in path-based state scheme, and returns the resolved 298 // node path if so. 299 func ResolveAccountTrieNodeKey(key []byte) (bool, []byte) { 300 if !bytes.HasPrefix(key, TrieNodeAccountPrefix) { 301 return false, nil 302 } 303 // The remaining key should only consist a hex node path 304 // whose length is in the range 0 to 64 (64 is excluded 305 // since leaves are always wrapped with shortNode). 306 if len(key) >= len(TrieNodeAccountPrefix)+common.HashLength*2 { 307 return false, nil 308 } 309 return true, key[len(TrieNodeAccountPrefix):] 310 } 311 312 // IsAccountTrieNode reports whether a provided database entry is an account 313 // trie node in path-based state scheme. 314 func IsAccountTrieNode(key []byte) bool { 315 ok, _ := ResolveAccountTrieNodeKey(key) 316 return ok 317 } 318 319 // ResolveStorageTrieNode reports whether a provided database entry is a storage 320 // trie node in path-based state scheme, and returns the resolved account hash 321 // and node path if so. 322 func ResolveStorageTrieNode(key []byte) (bool, common.Hash, []byte) { 323 if !bytes.HasPrefix(key, TrieNodeStoragePrefix) { 324 return false, common.Hash{}, nil 325 } 326 // The remaining key consists of 2 parts: 327 // - 32 bytes account hash 328 // - hex node path whose length is in the range 0 to 64 329 if len(key) < len(TrieNodeStoragePrefix)+common.HashLength { 330 return false, common.Hash{}, nil 331 } 332 if len(key) >= len(TrieNodeStoragePrefix)+common.HashLength+common.HashLength*2 { 333 return false, common.Hash{}, nil 334 } 335 accountHash := common.BytesToHash(key[len(TrieNodeStoragePrefix) : len(TrieNodeStoragePrefix)+common.HashLength]) 336 return true, accountHash, key[len(TrieNodeStoragePrefix)+common.HashLength:] 337 } 338 339 // IsStorageTrieNode reports whether a provided database entry is a storage 340 // trie node in path-based state scheme. 341 func IsStorageTrieNode(key []byte) bool { 342 ok, _, _ := ResolveStorageTrieNode(key) 343 return ok 344 } 345 346 // filterMapRowKey = filterMapRowPrefix + mapRowIndex (uint64 big endian) 347 func filterMapRowKey(mapRowIndex uint64, base bool) []byte { 348 extLen := 8 349 if base { 350 extLen = 9 351 } 352 l := len(filterMapRowPrefix) 353 key := make([]byte, l+extLen) 354 copy(key[:l], filterMapRowPrefix) 355 binary.BigEndian.PutUint64(key[l:l+8], mapRowIndex) 356 return key 357 } 358 359 // filterMapLastBlockKey = filterMapLastBlockPrefix + mapIndex (uint32 big endian) 360 func filterMapLastBlockKey(mapIndex uint32) []byte { 361 l := len(filterMapLastBlockPrefix) 362 key := make([]byte, l+4) 363 copy(key[:l], filterMapLastBlockPrefix) 364 binary.BigEndian.PutUint32(key[l:], mapIndex) 365 return key 366 } 367 368 // filterMapBlockLVKey = filterMapBlockLVPrefix + num (uint64 big endian) 369 func filterMapBlockLVKey(number uint64) []byte { 370 l := len(filterMapBlockLVPrefix) 371 key := make([]byte, l+8) 372 copy(key[:l], filterMapBlockLVPrefix) 373 binary.BigEndian.PutUint64(key[l:], number) 374 return key 375 } 376 377 // accountHistoryIndexKey = StateHistoryAccountMetadataPrefix + addressHash 378 func accountHistoryIndexKey(addressHash common.Hash) []byte { 379 return append(StateHistoryAccountMetadataPrefix, addressHash.Bytes()...) 380 } 381 382 // storageHistoryIndexKey = StateHistoryStorageMetadataPrefix + addressHash + storageHash 383 func storageHistoryIndexKey(addressHash common.Hash, storageHash common.Hash) []byte { 384 return append(append(StateHistoryStorageMetadataPrefix, addressHash.Bytes()...), storageHash.Bytes()...) 385 } 386 387 // accountHistoryIndexBlockKey = StateHistoryAccountBlockPrefix + addressHash + blockID 388 func accountHistoryIndexBlockKey(addressHash common.Hash, blockID uint32) []byte { 389 var buf [4]byte 390 binary.BigEndian.PutUint32(buf[:], blockID) 391 return append(append(StateHistoryAccountBlockPrefix, addressHash.Bytes()...), buf[:]...) 392 } 393 394 // storageHistoryIndexBlockKey = StateHistoryStorageBlockPrefix + addressHash + storageHash + blockID 395 func storageHistoryIndexBlockKey(addressHash common.Hash, storageHash common.Hash, blockID uint32) []byte { 396 var buf [4]byte 397 binary.BigEndian.PutUint32(buf[:], blockID) 398 return append(append(append(StateHistoryStorageBlockPrefix, addressHash.Bytes()...), storageHash.Bytes()...), buf[:]...) 399 }