Documentation
¶
Overview ¶
Package state provides a caching layer atop the Ethereum state trie.
Index ¶
- Constants
- func NewHookedState(stateDb *StateDB, hooks *tracing.Hooks) *hookedStateDB
- func NewStateSync(root common.Hash, database ethdb.KeyValueReader, ...) *trie.Sync
- type AccessEvents
- func (ae *AccessEvents) AddAccount(addr common.Address, isWrite bool, availableGas uint64) uint64
- func (ae *AccessEvents) AddTxDestination(addr common.Address, sendsValue, doesntExist bool)
- func (ae *AccessEvents) AddTxOrigin(originAddr common.Address)
- func (ae *AccessEvents) BasicDataGas(addr common.Address, isWrite bool, availableGas uint64, chargeWarmCosts bool) uint64
- func (ae *AccessEvents) CodeChunksRangeGas(contractAddr common.Address, startPC, size uint64, codeLen uint64, ...) (uint64, uint64)
- func (ae *AccessEvents) CodeHashGas(addr common.Address, isWrite bool, availableGas uint64, chargeWarmCosts bool) uint64
- func (ae *AccessEvents) ContractCreateInitGas(addr common.Address, availableGas uint64) (uint64, uint64)
- func (ae *AccessEvents) ContractCreatePreCheckGas(addr common.Address, availableGas uint64) uint64
- func (ae *AccessEvents) Copy() *AccessEvents
- func (ae *AccessEvents) Keys() [][]byte
- func (ae *AccessEvents) Merge(other *AccessEvents)
- func (ae *AccessEvents) MessageCallGas(destination common.Address, availableGas uint64) uint64
- func (ae *AccessEvents) SlotGas(addr common.Address, slot common.Hash, isWrite bool, availableGas uint64, ...) uint64
- func (ae *AccessEvents) ValueTransferGas(callerAddr, targetAddr common.Address, availableGas uint64) uint64
- type AccountDelete
- type AccountIterator
- type AccountUpdate
- type CodeBatch
- type CodeDB
- type CodeReader
- func (r *CodeReader) Code(addr common.Address, codeHash common.Hash) []byte
- func (r *CodeReader) CodeSize(addr common.Address, codeHash common.Hash) int
- func (r *CodeReader) CodeWithPrefix(addr common.Address, codeHash common.Hash) []byte
- func (r *CodeReader) GetCodeStats() ContractCodeReaderStats
- func (r *CodeReader) Has(addr common.Address, codeHash common.Hash) bool
- type ContractCode
- type ContractCodeReader
- type ContractCodeReaderStater
- type ContractCodeReaderStats
- type Database
- type DatabaseType
- type Dump
- type DumpAccount
- type DumpCollector
- type DumpConfig
- type HistoricDB
- func (db *HistoricDB) Commit(update *StateUpdate) error
- func (db *HistoricDB) Iteratee(root common.Hash) (Iteratee, error)
- func (db *HistoricDB) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, _ Trie) (Trie, error)
- func (db *HistoricDB) OpenTrie(root common.Hash) (Trie, error)
- func (db *HistoricDB) Reader(stateRoot common.Hash) (Reader, error)
- func (db *HistoricDB) TrieDB() *triedb.Database
- func (db *HistoricDB) Type() DatabaseType
- type Iteratee
- type Iterator
- type MPTDatabase
- func (db *MPTDatabase) Commit(update *StateUpdate) error
- func (db *MPTDatabase) Iteratee(root common.Hash) (Iteratee, error)
- func (db *MPTDatabase) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, self Trie) (Trie, error)
- func (db *MPTDatabase) OpenTrie(root common.Hash) (Trie, error)
- func (db *MPTDatabase) Reader(stateRoot common.Hash) (Reader, error)
- func (db *MPTDatabase) ReadersWithCacheStats(stateRoot common.Hash) (Reader, Reader, error)
- func (db *MPTDatabase) StateReader(stateRoot common.Hash) (StateReader, error)
- func (db *MPTDatabase) TrieDB() *triedb.Database
- func (db *MPTDatabase) Type() DatabaseType
- func (db *MPTDatabase) WithSnapshot(snapshot *snapshot.Tree) Database
- type PreimageReader
- type Reader
- type ReaderStater
- type ReaderStats
- type ReaderWithBlockLevelAccessList
- func (r *ReaderWithBlockLevelAccessList) Account(addr common.Address) (*types.StateAccount, error)
- func (r *ReaderWithBlockLevelAccessList) Code(addr common.Address, codeHash common.Hash) ([]byte, error)
- func (r *ReaderWithBlockLevelAccessList) CodeSize(addr common.Address, codeHash common.Hash) (int, error)
- func (r *ReaderWithBlockLevelAccessList) Has(addr common.Address, codeHash common.Hash) bool
- func (r *ReaderWithBlockLevelAccessList) Storage(addr common.Address, slot common.Hash) (common.Hash, error)
- type SizeStats
- type SizeTracker
- type StateDB
- func (s *StateDB) AccessEvents() *AccessEvents
- func (s *StateDB) AddAddressToAccessList(addr common.Address)
- func (s *StateDB) AddBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int
- func (s *StateDB) AddLog(log *types.Log)
- func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte)
- func (s *StateDB) AddRefund(gas uint64)
- func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash)
- func (s *StateDB) AddressInAccessList(addr common.Address) bool
- func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (common.Hash, error)
- func (s *StateDB) CommitWithUpdate(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (common.Hash, *StateUpdate, error)
- func (s *StateDB) Copy() *StateDB
- func (s *StateDB) CreateAccount(addr common.Address)
- func (s *StateDB) CreateContract(addr common.Address)
- func (s *StateDB) Database() Database
- func (s *StateDB) Dump(opts *DumpConfig) []byte
- func (s *StateDB) DumpBinTrieLeaves(collector map[common.Hash]hexutil.Bytes) error
- func (s *StateDB) DumpToCollector(c DumpCollector, conf *DumpConfig) (nextKey []byte, err error)
- func (s *StateDB) Empty(addr common.Address) bool
- func (s *StateDB) Error() error
- func (s *StateDB) Exist(addr common.Address) bool
- func (s *StateDB) Finalise(deleteEmptyObjects bool) *bal.ConstructionBlockAccessList
- func (s *StateDB) GetBalance(addr common.Address) *uint256.Int
- func (s *StateDB) GetCode(addr common.Address) []byte
- func (s *StateDB) GetCodeHash(addr common.Address) common.Hash
- func (s *StateDB) GetCodeSize(addr common.Address) int
- func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash
- func (s *StateDB) GetLogs(hash common.Hash, blockNumber uint64, blockHash common.Hash, blockTime uint64) []*types.Log
- func (s *StateDB) GetNonce(addr common.Address) uint64
- func (s *StateDB) GetRefund() uint64
- func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash
- func (s *StateDB) GetStateAndCommittedState(addr common.Address, hash common.Hash) (common.Hash, common.Hash)
- func (s *StateDB) GetStorageRoot(addr common.Address) common.Hash
- func (s *StateDB) GetTransientState(addr common.Address, key common.Hash) common.Hash
- func (s *StateDB) GetTrie() Trie
- func (s *StateDB) HasSelfDestructed(addr common.Address) bool
- func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash
- func (s *StateDB) IsNewContract(addr common.Address) bool
- func (s *StateDB) IterativeDump(opts *DumpConfig, output *json.Encoder)
- func (s *StateDB) Logs() []*types.Log
- func (s *StateDB) LogsForBurnAccounts() []*types.Log
- func (s *StateDB) Preimages() map[common.Hash][]byte
- func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, dst *common.Address, ...)
- func (s *StateDB) RawDump(opts *DumpConfig) Dump
- func (s *StateDB) Reader() Reader
- func (s *StateDB) RevertToSnapshot(revid int)
- func (s *StateDB) SelfDestruct(addr common.Address)
- func (s *StateDB) SetBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason)
- func (s *StateDB) SetCode(addr common.Address, code []byte, reason tracing.CodeChangeReason) (prev []byte)
- func (s *StateDB) SetNonce(addr common.Address, nonce uint64, reason tracing.NonceChangeReason)
- func (s *StateDB) SetState(addr common.Address, key, value common.Hash) common.Hash
- func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash)
- func (s *StateDB) SetTransientState(addr common.Address, key, value common.Hash)
- func (s *StateDB) SetTxContext(thash common.Hash, ti int, blockAccessIndex uint32)
- func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool)
- func (s *StateDB) Snapshot() int
- func (s *StateDB) StartPrefetcher(namespace string, witness *stateless.Witness)
- func (s *StateDB) StopPrefetcher()
- func (s *StateDB) SubBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int
- func (s *StateDB) SubRefund(gas uint64)
- func (s *StateDB) Touch(addr common.Address)
- func (s *StateDB) TxIndex() int
- func (s *StateDB) Witness() *stateless.Witness
- type StateReader
- type StateReaderStater
- type StateReaderStats
- type StateUpdate
- func (sc *StateUpdate) Empty() bool
- func (sc *StateUpdate) EncodeMPTState() (map[common.Hash][]byte, map[common.Address][]byte, ...)
- func (sc *StateUpdate) EncodeUBTState() (map[common.Hash][]byte, map[common.Address][]byte, ...)
- func (sc *StateUpdate) ToTracingUpdate() (*tracing.StateUpdate, error)
- type Storage
- type StorageIterator
- type StorageKeyEncoding
- type Trie
- type UBTDatabase
- func (db *UBTDatabase) AllocRecorder() *bintrie.Recorder
- func (db *UBTDatabase) Commit(update *StateUpdate) error
- func (db *UBTDatabase) EnableAllocRecording() *bintrie.Recorder
- func (db *UBTDatabase) Iteratee(root common.Hash) (Iteratee, error)
- func (db *UBTDatabase) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, self Trie) (Trie, error)
- func (db *UBTDatabase) OpenTrie(root common.Hash) (Trie, error)
- func (db *UBTDatabase) Reader(stateRoot common.Hash) (Reader, error)
- func (db *UBTDatabase) ReadersWithCacheStats(stateRoot common.Hash) (Reader, Reader, error)
- func (db *UBTDatabase) StateReader(stateRoot common.Hash) (StateReader, error)
- func (db *UBTDatabase) TrieDB() *triedb.Database
- func (db *UBTDatabase) Type() DatabaseType
Constants ¶
const ( AccessWitnessReadFlag = mode(1) AccessWitnessWriteFlag = mode(2) )
const TriesInMemory = 128
TriesInMemory represents the number of layers that are kept in RAM.
Variables ¶
This section is empty.
Functions ¶
func NewHookedState ¶ added in v1.14.12
NewHookedState wraps the given stateDb with the given hooks
Types ¶
type AccessEvents ¶ added in v1.14.4
type AccessEvents struct {
// contains filtered or unexported fields
}
AccessEvents lists the locations of the state that are being accessed during the production of a block.
func NewAccessEvents ¶ added in v1.14.4
func NewAccessEvents() *AccessEvents
func (*AccessEvents) AddAccount ¶ added in v1.14.4
AddAccount returns the gas to be charged for each of the currently cold member fields of an account.
func (*AccessEvents) AddTxDestination ¶ added in v1.14.4
func (ae *AccessEvents) AddTxDestination(addr common.Address, sendsValue, doesntExist bool)
AddTxDestination adds the member fields of the sender account to the access event list, so that cold accesses are not charged, since they are covered by the 21000 gas.
func (*AccessEvents) AddTxOrigin ¶ added in v1.14.4
func (ae *AccessEvents) AddTxOrigin(originAddr common.Address)
AddTxOrigin adds the member fields of the sender account to the access event list, so that cold accesses are not charged, since they are covered by the 21000 gas.
func (*AccessEvents) BasicDataGas ¶ added in v1.14.9
func (ae *AccessEvents) BasicDataGas(addr common.Address, isWrite bool, availableGas uint64, chargeWarmCosts bool) uint64
BasicDataGas adds the account's basic data to the accessed data, and returns the amount of gas that it costs. Note that an access in write mode implies an access in read mode, whereas an access in read mode does not imply an access in write mode.
func (*AccessEvents) CodeChunksRangeGas ¶ added in v1.14.4
func (ae *AccessEvents) CodeChunksRangeGas(contractAddr common.Address, startPC, size uint64, codeLen uint64, isWrite bool, availableGas uint64) (uint64, uint64)
CodeChunksRangeGas is a helper function to touch every chunk in a code range and charge witness gas costs
func (*AccessEvents) CodeHashGas ¶ added in v1.14.4
func (ae *AccessEvents) CodeHashGas(addr common.Address, isWrite bool, availableGas uint64, chargeWarmCosts bool) uint64
CodeHashGas adds the account's code hash to the accessed data, and returns the amount of gas that it costs. in write mode. If false, the charged gas corresponds to an access in read mode. Note that an access in write mode implies an access in read mode, whereas an access in read mode does not imply an access in write mode.
func (*AccessEvents) ContractCreateInitGas ¶ added in v1.14.4
func (ae *AccessEvents) ContractCreateInitGas(addr common.Address, availableGas uint64) (uint64, uint64)
ContractCreateInitGas returns the access gas costs for the initialization of a contract creation.
func (*AccessEvents) ContractCreatePreCheckGas ¶ added in v1.14.9
func (ae *AccessEvents) ContractCreatePreCheckGas(addr common.Address, availableGas uint64) uint64
ContractCreatePreCheckGas charges access costs before a contract creation is initiated. It is just reads, because the address collision is done before the transfer, and so no write are guaranteed to happen at this point.
func (*AccessEvents) Copy ¶ added in v1.14.4
func (ae *AccessEvents) Copy() *AccessEvents
func (*AccessEvents) Keys ¶ added in v1.14.4
func (ae *AccessEvents) Keys() [][]byte
Keys returns, predictably, the list of keys that were touched during the buildup of the access witness.
func (*AccessEvents) Merge ¶ added in v1.14.4
func (ae *AccessEvents) Merge(other *AccessEvents)
Merge is used to merge the access events that were generated during the execution of a tx, with the accumulation of all access events that were generated during the execution of all txs preceding this one in a block.
func (*AccessEvents) MessageCallGas ¶ added in v1.14.4
func (ae *AccessEvents) MessageCallGas(destination common.Address, availableGas uint64) uint64
MessageCallGas returns the gas to be charged for each of the currently cold member fields of an account, that need to be touched when making a message call to that account.
func (*AccessEvents) SlotGas ¶ added in v1.14.4
func (ae *AccessEvents) SlotGas(addr common.Address, slot common.Hash, isWrite bool, availableGas uint64, chargeWarmCosts bool) uint64
SlotGas returns the amount of gas to be charged for a cold storage access.
func (*AccessEvents) ValueTransferGas ¶ added in v1.14.4
func (ae *AccessEvents) ValueTransferGas(callerAddr, targetAddr common.Address, availableGas uint64) uint64
ValueTransferGas returns the gas to be charged for each of the currently cold balance member fields of the caller and the callee accounts.
type AccountDelete ¶ added in v1.17.3
type AccountDelete struct {
Address common.Address // Address uniquely identifies the account.
Origin *types.StateAccount // Origin is the account state prior to deletion (never be null).
Storages map[common.Hash]common.Hash // Storages contains mutated storage slots.
StoragesOrigin map[common.Hash]common.Hash // StoragesOrigin holds original values of mutated slots; keys are hashes of raw storage slot keys.
}
AccountDelete represents a deletion operation for an Ethereum account.
type AccountIterator ¶ added in v1.17.3
type AccountIterator interface {
Iterator
// Address returns the raw account address the iterator is currently at.
// An error will be returned if the preimage is not available.
Address() (common.Address, error)
// Account returns the account the iterator is currently at.
// An error will be retained if the iterator becomes invalid.
Account() *types.StateAccount
}
AccountIterator is an iterator to step over all the accounts in the specific state.
type AccountUpdate ¶ added in v1.17.3
type AccountUpdate struct {
Address common.Address // Address uniquely identifies the account.
Data *types.StateAccount // Data is the updated account state; nil indicates deletion.
Origin *types.StateAccount // Origin is the previous account state; nil indicates non-existence.
Code *ContractCode // Code contains updated contract code; nil if unchanged.
Storages map[common.Hash]common.Hash // Storages contains updated storage slots.
// StoragesOriginByKey and StoragesOriginByHash both record original values
// of mutated storage slots:
// - StoragesOriginByKey uses raw storage slot keys.
// - StoragesOriginByHash uses hashed storage slot keys.
StoragesOriginByKey map[common.Hash]common.Hash
StoragesOriginByHash map[common.Hash]common.Hash
}
AccountUpdate represents an update operation for an Ethereum account.
type CodeBatch ¶ added in v1.17.2
type CodeBatch struct {
// contains filtered or unexported fields
}
type CodeDB ¶ added in v1.17.2
type CodeDB struct {
// contains filtered or unexported fields
}
CodeDB is responsible for managing the contract code and provides the access to it. It can be used as a global object, sharing it between multiple entities.
func NewCodeDB ¶ added in v1.17.2
func NewCodeDB(db ethdb.KeyValueStore) *CodeDB
NewCodeDB constructs the contract code database with the provided key value store.
func (*CodeDB) NewBatchWithSize ¶ added in v1.17.2
NewBatchWithSize returns the batch with pre-allocated capacity.
func (*CodeDB) Reader ¶ added in v1.17.2
func (d *CodeDB) Reader() *CodeReader
Reader returns the contract code reader.
type CodeReader ¶ added in v1.17.2
type CodeReader struct {
// contains filtered or unexported fields
}
CodeReader implements state.ContractCodeReader, accessing contract code either in local key-value store or the shared code cache.
Reader is safe for concurrent access.
func (*CodeReader) Code ¶ added in v1.17.2
Code implements state.ContractCodeReader, retrieving a particular contract's code. Null is returned if the contract code is not present.
func (*CodeReader) CodeSize ¶ added in v1.17.2
CodeSize implements state.ContractCodeReader, retrieving a particular contract code's size. Zero is returned if the contract code is not present.
func (*CodeReader) CodeWithPrefix ¶ added in v1.17.2
CodeWithPrefix retrieves the contract code for the specified account address and code hash. It is almost identical to Code, but uses rawdb.ReadCodeWithPrefix for database lookups. The intention is to gradually deprecate the old contract code scheme.
func (*CodeReader) GetCodeStats ¶ added in v1.17.2
func (r *CodeReader) GetCodeStats() ContractCodeReaderStats
GetCodeStats implements ContractCodeReaderStater, returning the statistics of the code reader.
type ContractCode ¶ added in v1.17.3
type ContractCode struct {
Hash common.Hash // Hash is the cryptographic hash of the current contract code.
Blob []byte // Blob is the binary representation of the current contract code.
OriginHash common.Hash // OriginHash is the cryptographic hash of the code before mutation.
// Derived fields, populated only when state tracking is enabled.
Duplicate bool // Duplicate indicates whether the updated code already exists.
OriginBlob []byte // OriginBlob is the original binary representation of the contract code.
}
ContractCode represents contract bytecode mutation along with its associated metadata.
type ContractCodeReader ¶ added in v1.15.0
type ContractCodeReader interface {
// Has returns the flag indicating whether the contract code with
// specified address and hash exists or not.
Has(addr common.Address, codeHash common.Hash) bool
// Code retrieves a particular contract's code. Returns nil code if the
// requested contract code doesn't exist.
Code(addr common.Address, codeHash common.Hash) []byte
// CodeSize retrieves a particular contracts code's size. Returns zero code
// size if the requested contract code doesn't exist.
CodeSize(addr common.Address, codeHash common.Hash) int
}
ContractCodeReader defines the interface for accessing contract code.
ContractCodeReader is supposed to be thread-safe.
type ContractCodeReaderStater ¶ added in v1.17.2
type ContractCodeReaderStater interface {
GetCodeStats() ContractCodeReaderStats
}
ContractCodeReaderStater wraps the method to retrieve the statistics of contract code reader.
type ContractCodeReaderStats ¶ added in v1.17.0
type ContractCodeReaderStats struct {
CacheHit int64 // Number of cache hits
CacheMiss int64 // Number of cache misses
CacheHitBytes int64 // Total bytes served from cache
CacheMissBytes int64 // Total bytes read on cache misses
}
ContractCodeReaderStats aggregates statistics for the contract code reader.
func (ContractCodeReaderStats) HitRate ¶ added in v1.17.0
func (s ContractCodeReaderStats) HitRate() float64
HitRate returns the cache hit rate in percentage.
type Database ¶ added in v1.6.7
type Database interface {
// Type returns the trie type backing this database (MPT or UBT).
Type() DatabaseType
// Reader returns a state reader associated with the specified state root.
Reader(root common.Hash) (Reader, error)
// Iteratee returns a state iteratee associated with the specified state root,
// through which the account iterator and storage iterator can be created.
Iteratee(root common.Hash) (Iteratee, error)
// OpenTrie opens the main account trie.
OpenTrie(root common.Hash) (Trie, error)
// OpenStorageTrie opens the storage trie of an account.
OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, trie Trie) (Trie, error)
// TrieDB returns the underlying trie database for managing trie nodes.
TrieDB() *triedb.Database
// Commit flushes all pending writes and finalizes the state transition,
// committing the changes to the underlying storage. It returns an error
// if the commit fails.
Commit(update *StateUpdate) error
}
Database wraps access to tries and contract code.
func NewDatabase ¶ added in v1.6.7
NewDatabase creates a state database with the provided data sources.
Deprecated, please use NewMPTDatabase or NewUBTDatabase directly.
func NewDatabaseForTesting ¶ added in v1.14.9
func NewDatabaseForTesting() Database
NewDatabaseForTesting is similar to NewDatabase, but it initializes the caching db by using an ephemeral memory db with default config for testing.
type DatabaseType ¶ added in v1.17.3
type DatabaseType int
DatabaseType represents the type of trie backing the state database.
const ( // TypeMPT indicates a Merkle Patricia Trie (MPT) backed database. TypeMPT DatabaseType = iota // TypeUBT indicates a Unified Binary Trie (UBT) backed database. TypeUBT )
func (DatabaseType) Is ¶ added in v1.17.3
func (typ DatabaseType) Is(t DatabaseType) bool
Is returns the flag indicating the database type equals to the given one.
type Dump ¶ added in v1.4.13
type Dump struct {
Root string `json:"root"`
Accounts map[string]DumpAccount `json:"accounts"`
// Next can be set to represent that this dump is only partial, and Next
// is where an iterator should be positioned in order to continue the dump.
Next hexutil.Bytes `json:"next,omitempty"` // nil if no more accounts
}
Dump represents the full dump in a collected format, as one large map.
type DumpAccount ¶ added in v1.4.13
type DumpAccount struct {
Balance string `json:"balance"`
Nonce uint64 `json:"nonce"`
Root hexutil.Bytes `json:"root"`
CodeHash hexutil.Bytes `json:"codeHash"`
Code hexutil.Bytes `json:"code,omitempty"`
Storage map[common.Hash]string `json:"storage,omitempty"`
Address *common.Address `json:"address,omitempty"` // Address only present in iterative (line-by-line) mode
AddressHash hexutil.Bytes `json:"key,omitempty"` // If we don't have address, we can output the key
}
DumpAccount represents an account in the state.
type DumpCollector ¶ added in v1.9.16
type DumpCollector interface {
// OnRoot is called with the state root
OnRoot(common.Hash)
// OnAccount is called once for each account in the trie
OnAccount(*common.Address, DumpAccount)
}
DumpCollector interface which the state trie calls during iteration
type DumpConfig ¶ added in v1.10.4
type DumpConfig struct {
SkipCode bool
SkipStorage bool
OnlyWithAddresses bool
Start []byte
Max uint64
}
DumpConfig is a set of options to control what portions of the state will be iterated and collected.
type HistoricDB ¶ added in v1.16.0
type HistoricDB struct {
// contains filtered or unexported fields
}
HistoricDB is the implementation of Database interface, with the ability to access historical state.
func NewHistoricDatabase ¶ added in v1.16.0
func NewHistoricDatabase(triedb *triedb.Database, codedb *CodeDB) *HistoricDB
NewHistoricDatabase creates a historic state database.
func (*HistoricDB) Commit ¶ added in v1.17.2
func (db *HistoricDB) Commit(update *StateUpdate) error
Commit flushes all pending writes and finalizes the state transition, committing the changes to the underlying storage. It returns an error if the commit fails.
func (*HistoricDB) Iteratee ¶ added in v1.17.3
func (db *HistoricDB) Iteratee(root common.Hash) (Iteratee, error)
Iteratee returns a state iteratee associated with the specified state root, through which the account iterator and storage iterator can be created.
func (*HistoricDB) OpenStorageTrie ¶ added in v1.16.0
func (db *HistoricDB) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, _ Trie) (Trie, error)
OpenStorageTrie opens the storage trie of an account. It's not supported by historic database.
func (*HistoricDB) OpenTrie ¶ added in v1.16.0
func (db *HistoricDB) OpenTrie(root common.Hash) (Trie, error)
OpenTrie opens the main account trie. It's not supported by historic database.
func (*HistoricDB) Reader ¶ added in v1.16.0
func (db *HistoricDB) Reader(stateRoot common.Hash) (Reader, error)
Reader implements Database interface, returning a reader of the specific state.
func (*HistoricDB) TrieDB ¶ added in v1.16.0
func (db *HistoricDB) TrieDB() *triedb.Database
TrieDB returns the underlying trie database for managing trie nodes.
func (*HistoricDB) Type ¶ added in v1.17.3
func (db *HistoricDB) Type() DatabaseType
Type returns the trie type of the underlying database.
type Iteratee ¶ added in v1.17.3
type Iteratee interface {
// NewAccountIterator creates an account iterator for the state specified by
// the given root. It begins at a specified starting position, corresponding
// to a particular initial key (or the next key if the specified one does
// not exist).
//
// The starting position here refers to the hash of the account address.
NewAccountIterator(start common.Hash) (AccountIterator, error)
// NewStorageIterator creates a storage iterator for the state specified by
// the address hash. It begins at a specified starting position, corresponding
// to a particular initial key (or the next key if the specified one does
// not exist).
//
// The starting position here refers to the hash of the slot key.
NewStorageIterator(addressHash common.Hash, start common.Hash) (StorageIterator, error)
}
Iteratee wraps the NewIterator methods for traversing the accounts and storages of the specific state.
type Iterator ¶ added in v1.17.3
type Iterator interface {
// Next steps the iterator forward one element. It returns false if the iterator
// is exhausted or if an error occurs. Any error encountered is retained and
// can be retrieved via Error().
Next() bool
// Error returns any failure that occurred during iteration, which might have
// caused a premature iteration exit.
Error() error
// Hash returns the hash of the account or storage slot the iterator is
// currently at.
Hash() common.Hash
// Release releases associated resources. Release should always succeed and
// can be called multiple times without causing error.
Release()
}
Iterator is an iterator to step over all the accounts or the specific storage in the specific state.
type MPTDatabase ¶ added in v1.17.3
type MPTDatabase struct {
// contains filtered or unexported fields
}
MPTDatabase is an implementation of Database interface for Merkle Patricia Tries. It leverages both trie and state snapshot to provide functionalities for state access.
func NewMPTDatabase ¶ added in v1.17.3
func NewMPTDatabase(tdb *triedb.Database, codedb *CodeDB) *MPTDatabase
NewMPTDatabase creates a state database with the Merkle Patricia Trie manner.
func (*MPTDatabase) Commit ¶ added in v1.17.3
func (db *MPTDatabase) Commit(update *StateUpdate) error
Commit flushes all pending writes and finalizes the state transition, committing the changes to the underlying storage. It returns an error if the commit fails.
func (*MPTDatabase) Iteratee ¶ added in v1.17.3
func (db *MPTDatabase) Iteratee(root common.Hash) (Iteratee, error)
Iteratee returns a state iteratee associated with the specified state root, through which the account iterator and storage iterator can be created.
func (*MPTDatabase) OpenStorageTrie ¶ added in v1.17.3
func (db *MPTDatabase) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, self Trie) (Trie, error)
OpenStorageTrie opens the storage trie of an account.
func (*MPTDatabase) OpenTrie ¶ added in v1.17.3
func (db *MPTDatabase) OpenTrie(root common.Hash) (Trie, error)
OpenTrie opens the main account trie at a specific root hash.
func (*MPTDatabase) Reader ¶ added in v1.17.3
func (db *MPTDatabase) Reader(stateRoot common.Hash) (Reader, error)
Reader implements Database, returning a reader associated with the specified state root.
func (*MPTDatabase) ReadersWithCacheStats ¶ added in v1.17.3
ReadersWithCacheStats creates a pair of state readers that share the same underlying state reader and internal state cache, while maintaining separate statistics respectively.
func (*MPTDatabase) StateReader ¶ added in v1.17.3
func (db *MPTDatabase) StateReader(stateRoot common.Hash) (StateReader, error)
StateReader returns a state reader associated with the specified state root.
func (*MPTDatabase) TrieDB ¶ added in v1.17.3
func (db *MPTDatabase) TrieDB() *triedb.Database
TrieDB retrieves any intermediate trie-node caching layer.
func (*MPTDatabase) Type ¶ added in v1.17.3
func (db *MPTDatabase) Type() DatabaseType
Type returns Merkle, indicating this database is backed by a Merkle Patricia Trie.
func (*MPTDatabase) WithSnapshot ¶ added in v1.17.3
func (db *MPTDatabase) WithSnapshot(snapshot *snapshot.Tree) Database
WithSnapshot configures the provided state snapshot. Note that this registration must be performed before the MPTDatabase is used.
type PreimageReader ¶ added in v1.17.3
type PreimageReader interface {
// Preimage returns the preimage of associated hash.
Preimage(hash common.Hash) []byte
}
PreimageReader wraps the function Preimage for accessing the preimage of a given hash.
type Reader ¶ added in v1.14.9
type Reader interface {
ContractCodeReader
StateReader
}
Reader defines the interface for accessing accounts, storage slots and contract code associated with a specific state.
Reader is assumed to be thread-safe and implementation must take care of the concurrency issue by themselves.
type ReaderStater ¶ added in v1.17.2
type ReaderStater interface {
GetStats() ReaderStats
}
ReaderStater defines the capability to retrieve aggregated statistics.
type ReaderStats ¶ added in v1.16.0
type ReaderStats struct {
CodeStats ContractCodeReaderStats
StateStats StateReaderStats
}
ReaderStats wraps the statistics of reader.
type ReaderWithBlockLevelAccessList ¶ added in v1.17.3
type ReaderWithBlockLevelAccessList struct {
Reader
AccessList *bal.ConstructionBlockAccessList
TxIndex int
}
ReaderWithBlockLevelAccessList provides state access that reflects the pre-transition state combined with the mutations made by transactions prior to TxIndex.
func NewReaderWithBlockLevelAccessList ¶ added in v1.17.3
func NewReaderWithBlockLevelAccessList(base Reader, accessList *bal.ConstructionBlockAccessList, txIndex int) *ReaderWithBlockLevelAccessList
NewReaderWithBlockLevelAccessList constructs a reader for accessing states with the mutations made by transactions prior to txIndex.
The txIndex refers to the call frame as such: - 0 for pre‑execution system contract calls. - 1 … n for transactions (in block order). - n + 1 for post‑execution system contract calls.
func (*ReaderWithBlockLevelAccessList) Account ¶ added in v1.17.3
func (r *ReaderWithBlockLevelAccessList) Account(addr common.Address) (*types.StateAccount, error)
Account implements Reader, returning the account with the specific address.
func (*ReaderWithBlockLevelAccessList) Code ¶ added in v1.17.3
func (r *ReaderWithBlockLevelAccessList) Code(addr common.Address, codeHash common.Hash) ([]byte, error)
Code implements Reader, returning the contract code with specified address and hash.
func (*ReaderWithBlockLevelAccessList) CodeSize ¶ added in v1.17.3
func (r *ReaderWithBlockLevelAccessList) CodeSize(addr common.Address, codeHash common.Hash) (int, error)
CodeSize implements Reader, returning the contract code size with specified address and hash.
type SizeStats ¶ added in v1.16.4
type SizeStats struct {
StateRoot common.Hash // State root hash at the time of measurement
BlockNumber uint64 // Associated block number at the time of measurement
Accounts int64 // Total number of accounts in the state
AccountBytes int64 // Total storage size used by all account data (in bytes)
Storages int64 // Total number of storage slots across all accounts
StorageBytes int64 // Total storage size used by all storage slot data (in bytes)
AccountTrienodes int64 // Total number of account trie nodes in the state
AccountTrienodeBytes int64 // Total storage size occupied by account trie nodes (in bytes)
StorageTrienodes int64 // Total number of storage trie nodes in the state
StorageTrienodeBytes int64 // Total storage size occupied by storage trie nodes (in bytes)
ContractCodes int64 // Total number of contract codes in the state
ContractCodeBytes int64 // Total size of all contract code (in bytes)
}
SizeStats represents either the current state size statistics or the size differences resulting from a state transition.
type SizeTracker ¶ added in v1.16.4
type SizeTracker struct {
// contains filtered or unexported fields
}
SizeTracker handles the state size initialization and tracks of state size metrics.
func NewSizeTracker ¶ added in v1.16.4
func NewSizeTracker(db ethdb.KeyValueStore, triedb *triedb.Database) (*SizeTracker, error)
NewSizeTracker creates a new state size tracker and starts it automatically
func (*SizeTracker) Notify ¶ added in v1.16.4
func (t *SizeTracker) Notify(update *StateUpdate)
Notify is an async method used to send the state update to the size tracker. It ignores empty updates (where no state changes occurred). If the channel is full, it drops the update to avoid blocking.
func (*SizeTracker) Query ¶ added in v1.16.4
func (t *SizeTracker) Query(root *common.Hash) (*SizeStats, error)
Query returns the state size specified by the root, or nil if not available. If the root is nil, query the size of latest chain head; If the root is non-nil, query the size of the specified state;
func (*SizeTracker) Stop ¶ added in v1.16.4
func (t *SizeTracker) Stop()
type StateDB ¶
type StateDB struct {
// Measurements gathered during execution for debugging purposes
AccountReads time.Duration
AccountHashes time.Duration
AccountUpdates time.Duration
AccountCommits time.Duration
StorageReads time.Duration
StorageUpdates time.Duration
StorageCommits time.Duration
DatabaseCommits time.Duration
CodeReads time.Duration
AccountLoaded int // Number of accounts retrieved from the database during the state transition
AccountUpdated int // Number of accounts updated during the state transition
AccountDeleted int // Number of accounts deleted during the state transition
StorageLoaded int // Number of storage slots retrieved from the database during the state transition
StorageUpdated atomic.Int64 // Number of storage slots updated during the state transition
StorageDeleted atomic.Int64 // Number of storage slots deleted during the state transition
// CodeLoadBytes is the total number of bytes read from contract code.
// This value may be smaller than the actual number of bytes read, since
// some APIs (e.g. CodeSize) may load the entire code from either the
// cache or the database when the size is not available in the cache.
CodeLoaded int // Number of contract code loaded during the state transition
CodeLoadBytes int // Total bytes of resolved code
CodeUpdated int // Number of contracts with code changes that persisted
CodeUpdateBytes int // Total bytes of persisted code written
// contains filtered or unexported fields
}
StateDB structs within the ethereum protocol are used to store anything within the merkle trie. StateDBs take care of caching and storing nested states. It's the general query interface to retrieve:
* Contracts * Accounts
Once the state is committed, tries cached in stateDB (including account trie, storage tries) will no longer be functional. A new state instance must be created with new root and updated database for accessing post- commit states.
func NewWithReader ¶ added in v1.16.0
NewWithReader creates a new state for the specified state root. Unlike New, this function accepts an additional Reader which is bound to the given root.
func (*StateDB) AccessEvents ¶ added in v1.14.9
func (s *StateDB) AccessEvents() *AccessEvents
func (*StateDB) AddAddressToAccessList ¶ added in v1.9.24
AddAddressToAccessList adds the given address to the access list
func (*StateDB) AddBalance ¶
func (s *StateDB) AddBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int
AddBalance adds amount to the account associated with addr.
func (*StateDB) AddPreimage ¶ added in v1.5.8
AddPreimage records a SHA3 preimage seen by the VM.
func (*StateDB) AddSlotToAccessList ¶ added in v1.9.24
AddSlotToAccessList adds the given (address, slot)-tuple to the access list
func (*StateDB) AddressInAccessList ¶ added in v1.9.24
AddressInAccessList returns true if the given address is in the access list.
func (*StateDB) Commit ¶ added in v1.3.1
func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (common.Hash, error)
Commit writes the state mutations into the configured data stores.
Once the state is committed, tries cached in stateDB (including account trie, storage tries) will no longer be functional. A new state instance must be created with new root and updated database for accessing post- commit states.
The associated block number of the state transition is also provided for more chain context.
noStorageWiping is a flag indicating whether storage wiping is permitted. Since self-destruction was deprecated with the Cancun fork and there are no empty accounts left that could be deleted by EIP-158, storage wiping should not occur.
func (*StateDB) CommitWithUpdate ¶ added in v1.16.4
func (s *StateDB) CommitWithUpdate(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (common.Hash, *StateUpdate, error)
CommitWithUpdate writes the state mutations and returns the state update for external processing (e.g., live tracing hooks or size tracker).
func (*StateDB) Copy ¶
Copy creates a deep, independent copy of the state. Snapshots of the copied state cannot be applied to the copy.
func (*StateDB) CreateAccount ¶
CreateAccount explicitly creates a new state object, assuming that the account did not previously exist in the state. If the account already exists, this function will silently overwrite it which might lead to a consensus bug eventually.
func (*StateDB) CreateContract ¶ added in v1.14.2
CreateContract is used whenever a contract is created. This may be preceded by CreateAccount, but that is not required if it already existed in the state due to funds sent beforehand. This operation sets the 'newContract'-flag, which is required in order to correctly handle EIP-6780 'delete-in-same-transaction' logic.
func (*StateDB) Database ¶ added in v1.8.0
Database retrieves the low level database supporting the lower level trie ops.
func (*StateDB) Dump ¶
func (s *StateDB) Dump(opts *DumpConfig) []byte
Dump returns a JSON string representing the entire state as a single json-object
func (*StateDB) DumpBinTrieLeaves ¶ added in v1.17.0
DumpBinTrieLeaves collects all binary trie leaf nodes into the provided map.
func (*StateDB) DumpToCollector ¶ added in v1.9.16
func (s *StateDB) DumpToCollector(c DumpCollector, conf *DumpConfig) (nextKey []byte, err error)
DumpToCollector iterates the state according to the given options and inserts the items into a collector for aggregation or serialization.
func (*StateDB) Empty ¶
Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)
func (*StateDB) Error ¶ added in v1.6.7
Error returns the memorized database failure occurred earlier.
func (*StateDB) Exist ¶ added in v1.3.1
Exist reports whether the given account address exists in the state. Notably this also returns true for self-destructed accounts within the current transaction.
func (*StateDB) Finalise ¶ added in v1.6.2
func (s *StateDB) Finalise(deleteEmptyObjects bool) *bal.ConstructionBlockAccessList
Finalise finalises the state by removing the destructed objects and clears the journal as well as the refunds. Finalise, however, will not push any updates into the tries just yet. Only IntermediateRoot or Commit will do that.
func (*StateDB) GetBalance ¶
GetBalance retrieves the balance from the given address or 0 if object not found
func (*StateDB) GetCodeHash ¶ added in v1.4.8
func (*StateDB) GetCodeSize ¶ added in v1.4.13
func (*StateDB) GetCommittedState ¶ added in v1.8.16
GetCommittedState retrieves the value associated with the specific key without any mutations caused in the current execution.
func (*StateDB) GetLogs ¶
func (s *StateDB) GetLogs(hash common.Hash, blockNumber uint64, blockHash common.Hash, blockTime uint64) []*types.Log
GetLogs returns the logs matching the specified transaction hash, and annotates them with the given blockNumber and blockHash.
func (*StateDB) GetNonce ¶
GetNonce retrieves the nonce from the given address or 0 if object not found
func (*StateDB) GetRefund ¶ added in v1.3.1
GetRefund returns the current value of the refund counter.
func (*StateDB) GetStateAndCommittedState ¶ added in v1.16.2
func (s *StateDB) GetStateAndCommittedState(addr common.Address, hash common.Hash) (common.Hash, common.Hash)
GetStateAndCommittedState returns the current value and the original value.
func (*StateDB) GetStorageRoot ¶ added in v1.13.0
GetStorageRoot retrieves the storage root from the given address or empty if object not found.
Note: the storage root returned corresponds to the trie since last Intermediate operation, some recent in-memory changes are excluded.
func (*StateDB) GetTransientState ¶ added in v1.11.0
GetTransientState gets transient storage for a given account.
func (*StateDB) HasSelfDestructed ¶ added in v1.12.1
func (*StateDB) IntermediateRoot ¶ added in v1.3.1
IntermediateRoot computes the current root hash of the state trie. It is called in between transactions to get the root hash that goes into transaction receipts.
func (*StateDB) IsNewContract ¶ added in v1.17.0
IsNewContract reports whether the contract at the given address was deployed during the current transaction.
func (*StateDB) IterativeDump ¶ added in v1.9.0
func (s *StateDB) IterativeDump(opts *DumpConfig, output *json.Encoder)
IterativeDump dumps out accounts as json-objects, delimited by linebreaks on stdout
func (*StateDB) LogsForBurnAccounts ¶ added in v1.17.3
LogsForBurnAccounts returns the eth burn logs for accounts scheduled for removal which still have positive balance. The purpose of this function is to handle a corner case of EIP-7708 where a self-destructed account might still receive funds between sending/burning its previous balance and actual removal. In this case the burning of these remaining balances still need to be logged. Specification EIP-7708: https://eips.ethereum.org/EIPS/eip-7708
This function should only be invoked at the transaction boundary, specifically before the Finalise.
func (*StateDB) Preimages ¶ added in v1.5.8
Preimages returns a list of SHA3 preimages that have been submitted.
func (*StateDB) Prepare ¶ added in v1.6.2
func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList)
Prepare handles the preparatory steps for executing a state transition with. This method must be invoked before state transition.
Berlin fork: - Add sender to access list (2929) - Add destination to access list (2929) - Add precompiles to access list (2929) - Add the contents of the optional tx access list (2930)
Potential EIPs: - Reset access list (Berlin) - Add coinbase to access list (EIP-3651) - Reset transient storage (EIP-1153)
func (*StateDB) RawDump ¶
func (s *StateDB) RawDump(opts *DumpConfig) Dump
RawDump returns the state. If the processing is aborted e.g. due to options reaching Max, the `Next` key is set on the returned Dump.
func (*StateDB) Reader ¶ added in v1.16.0
Reader retrieves the low level database reader supporting the lower level operations.
func (*StateDB) RevertToSnapshot ¶ added in v1.4.16
RevertToSnapshot reverts all state changes made since the given revision.
func (*StateDB) SelfDestruct ¶ added in v1.12.1
SelfDestruct marks the given account as selfdestructed.
The account's state object is still available until the state is committed, getStateObject will return a non-nil account after SelfDestruct.
func (*StateDB) SetBalance ¶ added in v1.4.16
func (*StateDB) SetStorage ¶ added in v1.9.2
SetStorage replaces the entire storage for the specified account with given storage. This function should only be used for debugging and the mutations must be discarded afterwards.
func (*StateDB) SetTransientState ¶ added in v1.11.0
SetTransientState sets transient storage for a given account. It adds the change to the journal so that it can be rolled back to its previous value if there is a revert.
func (*StateDB) SetTxContext ¶ added in v1.11.0
SetTxContext sets the current transaction hash and index which are used when the EVM emits new state logs. It should be invoked before transaction execution.
func (*StateDB) SlotInAccessList ¶ added in v1.9.24
func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool)
SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
func (*StateDB) Snapshot ¶ added in v1.4.16
Snapshot returns an identifier for the current revision of the state.
func (*StateDB) StartPrefetcher ¶ added in v1.10.0
StartPrefetcher initializes a new trie prefetcher to pull in nodes from the state trie concurrently while the state is mutated so that when we reach the commit phase, most of the needed data is already hot.
func (*StateDB) StopPrefetcher ¶ added in v1.10.0
func (s *StateDB) StopPrefetcher()
StopPrefetcher terminates a running prefetcher and reports any leftover stats from the gathered metrics.
func (*StateDB) SubBalance ¶ added in v1.5.5
func (s *StateDB) SubBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int
SubBalance subtracts amount from the account associated with addr.
func (*StateDB) SubRefund ¶ added in v1.8.16
SubRefund removes gas from the refund counter. This method will panic if the refund counter goes below zero
func (*StateDB) Touch ¶ added in v1.17.3
Touch accesses the specific account without returning anything.
type StateReader ¶ added in v1.15.0
type StateReader interface {
// Account retrieves the account associated with a particular address.
//
// - Returns a nil account if it does not exist
// - Returns an error only if an unexpected issue occurs
// - The returned account is safe to modify after the call
Account(addr common.Address) (*types.StateAccount, error)
// Storage retrieves the storage slot associated with a particular account
// address and slot key.
//
// - Returns an empty slot if it does not exist
// - Returns an error only if an unexpected issue occurs
// - The returned storage slot is safe to modify after the call
Storage(addr common.Address, slot common.Hash) (common.Hash, error)
}
StateReader defines the interface for accessing accounts and storage slots associated with a specific state.
StateReader is supposed to be thread-safe.
type StateReaderStater ¶ added in v1.17.2
type StateReaderStater interface {
GetStateStats() StateReaderStats
}
StateReaderStater wraps the method to retrieve the statistics of state reader.
type StateReaderStats ¶ added in v1.17.2
type StateReaderStats struct {
AccountCacheHit int64 // Number of account cache hits
AccountCacheMiss int64 // Number of account cache misses
StorageCacheHit int64 // Number of storage cache hits
StorageCacheMiss int64 // Number of storage cache misses
}
StateReaderStats aggregates statistics for the state reader.
func (StateReaderStats) AccountCacheHitRate ¶ added in v1.17.2
func (s StateReaderStats) AccountCacheHitRate() float64
AccountCacheHitRate returns the cache hit rate of account requests in percentage.
func (StateReaderStats) StorageCacheHitRate ¶ added in v1.17.2
func (s StateReaderStats) StorageCacheHitRate() float64
StorageCacheHitRate returns the cache hit rate of storage requests in percentage.
type StateUpdate ¶ added in v1.17.3
type StateUpdate struct {
OriginRoot common.Hash // Hash of the state before applying mutation
Root common.Hash // Hash of the state after applying mutation
BlockNumber uint64 // Associated block number
// Accounts contains mutated accounts, keyed by address hash.
Accounts map[common.Hash]*types.StateAccount
// Storages contains mutated storage slots, keyed by address
// hash and storage slot key hash.
Storages map[common.Hash]map[common.Hash]common.Hash
// AccountsOrigin holds the original values of mutated accounts, keyed by address.
AccountsOrigin map[common.Address]*types.StateAccount
// StoragesOrigin holds the original values of mutated storage slots.
// The key format depends on StorageKeyType:
// - if StorageKeyType is plain: keyed by account address and plain storage slot key.
// - if StorageKeyType is hashed: keyed by account address and storage slot key hash.
StoragesOrigin map[common.Address]map[common.Hash]common.Hash
StorageKeyType StorageKeyEncoding
Codes map[common.Address]*ContractCode // Codes contains the set of dirty codes
Nodes *trienode.MergedNodeSet // Aggregated dirty nodes caused by state changes
}
StateUpdate represents the difference between two states resulting from state execution. It contains information about mutated contract codes, accounts, and storage slots, along with their original values.
func NewStateUpdate ¶ added in v1.17.3
func NewStateUpdate(typ StorageKeyEncoding, originRoot common.Hash, root common.Hash, blockNumber uint64, deletes map[common.Hash]*AccountDelete, updates map[common.Hash]*AccountUpdate, nodes *trienode.MergedNodeSet) *StateUpdate
NewStateUpdate constructs a state update object by identifying the differences between two states through state execution. It combines the specified account deletions and account updates to create a complete state update.
func (*StateUpdate) Empty ¶ added in v1.17.3
func (sc *StateUpdate) Empty() bool
Empty returns a flag indicating the state transition is empty or not.
func (*StateUpdate) EncodeMPTState ¶ added in v1.17.3
func (sc *StateUpdate) EncodeMPTState() (map[common.Hash][]byte, map[common.Address][]byte, map[common.Hash]map[common.Hash][]byte, map[common.Address]map[common.Hash][]byte)
EncodeMPTState encodes all state mutations alongside their original value into the Merkle-Patricia-Trie representation.
It transforms account and storage updates into their corresponding MPT-encoded key-value mappings, using the same encoding rules as the Ethereum state trie.
func (*StateUpdate) EncodeUBTState ¶ added in v1.17.3
func (sc *StateUpdate) EncodeUBTState() (map[common.Hash][]byte, map[common.Address][]byte, map[common.Hash]map[common.Hash][]byte, map[common.Address]map[common.Hash][]byte)
EncodeUBTState encodes all state mutations alongside their original value into the Unified-Binary-Trie representation.
It transforms account and storage updates into their corresponding UBT-encoded key-value mappings, using the same encoding rules as the Ethereum state trie.
func (*StateUpdate) ToTracingUpdate ¶ added in v1.17.3
func (sc *StateUpdate) ToTracingUpdate() (*tracing.StateUpdate, error)
ToTracingUpdate converts the internal StateUpdate to an exported tracing.StateUpdate.
type StorageIterator ¶ added in v1.17.3
type StorageIterator interface {
Iterator
// Key returns the raw storage slot key the iterator is currently at.
// An error will be returned if the preimage is not available.
Key() (common.Hash, error)
// Slot returns the storage slot the iterator is currently at. An error will
// be retained if the iterator becomes invalid.
Slot() common.Hash
}
StorageIterator is an iterator to step over the specific storage in the specific state.
type StorageKeyEncoding ¶ added in v1.17.3
type StorageKeyEncoding int
StorageKeyEncoding specifies the encoding scheme of a storage key.
const ( // StorageKeyHashed represents a hashed key (e.g. Keccak256). StorageKeyHashed StorageKeyEncoding = iota // StorageKeyPlain represents a raw (unhashed) key. StorageKeyPlain )
type Trie ¶ added in v1.6.7
type Trie interface {
// GetKey returns the sha3 preimage of a hashed key that was previously used
// to store a value.
//
// TODO(fjl): remove this when StateTrie is removed
GetKey([]byte) []byte
// GetAccount abstracts an account read from the trie. It retrieves the
// account blob from the trie with provided account address and decodes it
// with associated decoding algorithm. If the specified account is not in
// the trie, nil will be returned. If the trie is corrupted(e.g. some nodes
// are missing or the account blob is incorrect for decoding), an error will
// be returned.
GetAccount(address common.Address) (*types.StateAccount, error)
// PrefetchAccount attempts to resolve specific accounts from the database
// to accelerate subsequent trie operations.
PrefetchAccount([]common.Address) error
// GetStorage returns the value for key stored in the trie. The value bytes
// must not be modified by the caller. If a node was not found in the database,
// a trie.MissingNodeError is returned.
GetStorage(addr common.Address, key []byte) ([]byte, error)
// PrefetchStorage attempts to resolve specific storage slots from the database
// to accelerate subsequent trie operations.
PrefetchStorage(addr common.Address, keys [][]byte) error
// UpdateAccount abstracts an account write to the trie. It encodes the
// provided account object with associated algorithm and then updates it
// in the trie with provided address.
UpdateAccount(address common.Address, account *types.StateAccount, codeLen int) error
// UpdateStorage associates key with value in the trie. If value has length zero,
// any existing value is deleted from the trie. The value bytes must not be modified
// by the caller while they are stored in the trie. If a node was not found in the
// database, a trie.MissingNodeError is returned.
UpdateStorage(addr common.Address, key, value []byte) error
// DeleteAccount abstracts an account deletion from the trie.
DeleteAccount(address common.Address) error
// DeleteStorage removes any existing value for key from the trie. If a node
// was not found in the database, a trie.MissingNodeError is returned.
DeleteStorage(addr common.Address, key []byte) error
// UpdateContractCode abstracts code write to the trie. It is expected
// to be moved to the stateWriter interface when the latter is ready.
UpdateContractCode(address common.Address, codeHash common.Hash, code []byte) error
// Hash returns the root hash of the trie. It does not write to the database and
// can be used even if the trie doesn't have one.
Hash() common.Hash
// Commit collects all dirty nodes in the trie and replace them with the
// corresponding node hash. All collected nodes(including dirty leaves if
// collectLeaf is true) will be encapsulated into a nodeset for return.
// The returned nodeset can be nil if the trie is clean(nothing to commit).
// Once the trie is committed, it's not usable anymore. A new trie must
// be created with new root and updated trie database for following usage
Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet)
// Witness returns a set containing all trie nodes that have been accessed.
// The returned map could be nil if the witness is empty.
Witness() map[string][]byte
// NodeIterator returns an iterator that returns nodes of the trie. Iteration
// starts at the key after the given start key. And error will be returned
// if fails to create node iterator.
NodeIterator(startKey []byte) (trie.NodeIterator, error)
// Prove constructs a Merkle proof for key. The result contains all encoded nodes
// on the path to the value at key. The value itself is also included in the last
// node and can be retrieved by verifying the proof.
//
// If the trie does not contain a value for key, the returned proof contains all
// nodes of the longest existing prefix of the key (at least the root), ending
// with the node that proves the absence of the key.
Prove(key []byte, proofDb ethdb.KeyValueWriter) error
// IsUBT returns true if the trie is unified binary trie based.
IsUBT() bool
}
Trie is a Ethereum Merkle Patricia trie.
type UBTDatabase ¶ added in v1.17.3
type UBTDatabase struct {
// contains filtered or unexported fields
}
UBTDatabase is an implementation of Database interface for Unified Binary Trie. It provides the same functionality as MPTDatabase but uses unified binary trie for state hashing instead of Merkle Patricia Tries.
func NewUBTDatabase ¶ added in v1.17.3
func NewUBTDatabase(triedb *triedb.Database, codedb *CodeDB) *UBTDatabase
NewUBTDatabase creates a state database with the Unified binary trie manner.
func (*UBTDatabase) AllocRecorder ¶ added in v1.17.4
func (db *UBTDatabase) AllocRecorder() *bintrie.Recorder
AllocRecorder returns the attached recorder, or nil if recording was never enabled on this database.
func (*UBTDatabase) Commit ¶ added in v1.17.3
func (db *UBTDatabase) Commit(update *StateUpdate) error
Commit flushes all pending writes and finalizes the state transition, committing the changes to the underlying storage. It returns an error if the commit fails.
func (*UBTDatabase) EnableAllocRecording ¶ added in v1.17.4
func (db *UBTDatabase) EnableAllocRecording() *bintrie.Recorder
EnableAllocRecording installs an alloc recorder shared across every binary trie opened from this database. The recorder captures account, storage, and code writes keyed by their original (unhashed) addresses, which is required for tooling like evm t8n to render the post-state as a types.GenesisAlloc.
func (*UBTDatabase) Iteratee ¶ added in v1.17.3
func (db *UBTDatabase) Iteratee(root common.Hash) (Iteratee, error)
Iteratee returns a state iteratee associated with the specified state root, through which the account iterator and storage iterator can be created.
func (*UBTDatabase) OpenStorageTrie ¶ added in v1.17.3
func (db *UBTDatabase) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, self Trie) (Trie, error)
OpenStorageTrie opens the storage trie of an account. In binary trie mode, all state objects share one unified trie, so the main trie is returned.
func (*UBTDatabase) OpenTrie ¶ added in v1.17.3
func (db *UBTDatabase) OpenTrie(root common.Hash) (Trie, error)
OpenTrie opens the main account trie at a specific root hash.
func (*UBTDatabase) Reader ¶ added in v1.17.3
func (db *UBTDatabase) Reader(stateRoot common.Hash) (Reader, error)
Reader implements Database, returning a reader associated with the specified state root.
func (*UBTDatabase) ReadersWithCacheStats ¶ added in v1.17.3
ReadersWithCacheStats creates a pair of state readers that share the same underlying state reader and internal state cache, while maintaining separate statistics respectively.
func (*UBTDatabase) StateReader ¶ added in v1.17.3
func (db *UBTDatabase) StateReader(stateRoot common.Hash) (StateReader, error)
StateReader returns a state reader associated with the specified state root.
func (*UBTDatabase) TrieDB ¶ added in v1.17.3
func (db *UBTDatabase) TrieDB() *triedb.Database
TrieDB retrieves any intermediate trie-node caching layer.
func (*UBTDatabase) Type ¶ added in v1.17.3
func (db *UBTDatabase) Type() DatabaseType
Type returns Binary, indicating this database is backed by a Universal Binary Trie.
Source Files
¶
- access_events.go
- access_list.go
- database.go
- database_code.go
- database_history.go
- database_iterator.go
- database_mpt.go
- database_ubt.go
- dump.go
- iterator.go
- journal.go
- metrics.go
- reader.go
- reader_eip_7928.go
- reader_stater.go
- state_object.go
- state_sizer.go
- statedb.go
- statedb_hooked.go
- stateupdate.go
- sync.go
- transient_storage.go
- trie_prefetcher.go