state

package
v0.1.27 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2022 License: LGPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

Package state provides a caching layer atop the Ethereum state trie.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAddressNotPresent = errors.New("address not present in state")
)
View Source
var MaxTrieCacheGen = uint16(120)

MaxTrieCacheGen limit after which to evict trie nodes from memory.

Functions

This section is empty.

Types

type Account

type Account struct {
	Nonce    uint64
	Balance  *big.Int
	Root     common.Hash // merkle root of the storage trie
	CodeHash []byte
}

Account is the Ethereum consensus representation of accounts. These objects are stored in the main account trie.

type Code

type Code []byte

Code ...

func (Code) String

func (c Code) String() string

type DB

type DB struct {

	// Measurements gathered during execution for debugging purposes
	AccountReads   time.Duration
	AccountHashes  time.Duration
	AccountUpdates time.Duration
	AccountCommits time.Duration
	StorageReads   time.Duration
	StorageHashes  time.Duration
	StorageUpdates time.Duration
	StorageCommits time.Duration
	// contains filtered or unexported fields
}

DB 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

func New

func New(root common.Hash, db Database) (*DB, error)

New creates a new state from a given trie.

func (*DB) AddBalance

func (db *DB) AddBalance(addr common.Address, amount *big.Int)

AddBalance adds amount to the account associated with addr.

func (*DB) AddLog

func (db *DB) AddLog(log *types.Log)

AddLog ...

func (*DB) AddPreimage

func (db *DB) AddPreimage(hash common.Hash, preimage []byte)

AddPreimage records a SHA3 preimage seen by the VM.

func (*DB) AddRefund

func (db *DB) AddRefund(gas uint64)

AddRefund adds gas to the refund counter

func (*DB) AddReward

func (db *DB) AddReward(snapshot *stk.ValidatorWrapper, reward *big.Int, shareLookup map[common.Address]numeric.Dec) error

AddReward distributes the reward to all the delegators based on stake percentage.

func (*DB) BlockHash

func (db *DB) BlockHash() common.Hash

BlockHash returns the current block hash set by Prepare.

func (*DB) Commit

func (db *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error)

Commit writes the state to the underlying in-memory trie database.

func (*DB) Copy

func (db *DB) Copy() *DB

Copy creates a deep, independent copy of the state. Snapshots of the copied state cannot be applied to the copy.

func (*DB) CreateAccount

func (db *DB) CreateAccount(addr common.Address)

CreateAccount explicitly creates a state object. If a state object with the address already exists the balance is carried over to the new account.

CreateAccount is called during the EVM CREATE operation. The situation might arise that a contract does the following:

  1. sends funds to sha(account ++ (nonce + 1))
  2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)

Carrying over the balance ensures that Ether doesn't disappear.

func (*DB) Database

func (db *DB) Database() Database

Database retrieves the low level database supporting the lower level trie ops.

func (*DB) DiffAndCleanCache added in v0.1.8

func (s *DB) DiffAndCleanCache(shardId uint32, to *DB) (int, error)

DiffAndCleanCache clean block tire data from redis, Used to reduce redis storage and increase hit rate

func (*DB) Dump

func (s *DB) Dump(opts *DumpConfig) []byte

Dump returns a JSON string representing the entire state as a single json-object

func (*DB) DumpToCollector

func (s *DB) DumpToCollector(c DumpCollector, conf *DumpConfig) (nextKey []byte)

DumpToCollector iterates the state according to the given options and inserts the items into a collector for aggregation or serialization.

func (*DB) Empty

func (db *DB) Empty(addr common.Address) bool

Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)

func (*DB) Error

func (db *DB) Error() error

func (*DB) Exist

func (db *DB) Exist(addr common.Address) bool

Exist reports whether the given account address exists in the state. Notably this also returns true for suicided accounts.

func (*DB) Finalise

func (db *DB) Finalise(deleteEmptyObjects bool)

Finalise finalises the state by removing the db destructed objects and clears the journal as well as the refunds.

func (*DB) ForEachStorage

func (db *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error

ForEachStorage ...

func (*DB) GetBalance

func (db *DB) GetBalance(addr common.Address) *big.Int

GetBalance retrieves the balance from the given address or 0 if object not found

func (*DB) GetCode

func (db *DB) GetCode(addr common.Address) []byte

GetCode ...

func (*DB) GetCodeHash

func (db *DB) GetCodeHash(addr common.Address) common.Hash

GetCodeHash ...

func (*DB) GetCodeSize

func (db *DB) GetCodeSize(addr common.Address) int

GetCodeSize ...

func (*DB) GetCommittedState

func (db *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash

GetCommittedState retrieves a value from the given account's committed storage trie.

func (*DB) GetLogs

func (db *DB) GetLogs(hash common.Hash) []*types.Log

GetLogs ...

func (*DB) GetNonce

func (db *DB) GetNonce(addr common.Address) uint64

GetNonce ...

func (*DB) GetOrNewStateObject

func (db *DB) GetOrNewStateObject(addr common.Address) *Object

GetOrNewStateObject retrieves a state object or create a new state object if nil.

func (*DB) GetProof

func (db *DB) GetProof(a common.Address) ([][]byte, error)

GetProof returns the MerkleProof for a given Account

func (*DB) GetRefund

func (db *DB) GetRefund() uint64

GetRefund returns the current value of the refund counter.

func (*DB) GetState

func (db *DB) GetState(addr common.Address, hash common.Hash) common.Hash

GetState retrieves a value from the given account's storage trie.

func (*DB) GetStorageProof

func (db *DB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error)

GetStorageProof returns the StorageProof for given key

func (*DB) GetValidatorFirstElectionEpoch

func (db *DB) GetValidatorFirstElectionEpoch(addr common.Address) *big.Int

GetValidatorFirstElectionEpoch gets the epoch when the validator was first elected

func (*DB) HasSuicided

func (db *DB) HasSuicided(addr common.Address) bool

HasSuicided ...

func (*DB) IntermediateRoot

func (db *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash

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 (*DB) IsValidator

func (db *DB) IsValidator(addr common.Address) bool

IsValidator checks whether it is a validator object

func (*DB) IterativeDump

func (s *DB) IterativeDump(opts *DumpConfig, output *json.Encoder)

IterativeDump dumps out accounts as json-objects, delimited by linebreaks on stdout

func (*DB) IteratorDump

func (s *DB) IteratorDump(opts *DumpConfig) IteratorDump

IteratorDump dumps out a batch of accounts starts with the given start key

func (*DB) Logs

func (db *DB) Logs() []*types.Log

Logs ...

func (*DB) Prefetch added in v0.1.8

func (s *DB) Prefetch(parallel int)

Prefetch If redis is empty, the hit rate will be too low and the synchronization block speed will be slow this function will parallel load the latest block statedb to redis this function used by debug or first time to init tikv cluster

func (*DB) Preimages

func (db *DB) Preimages() map[common.Hash][]byte

Preimages returns a list of SHA3 preimages that have been submitted.

func (*DB) Prepare

func (db *DB) Prepare(thash, bhash common.Hash, ti int)

Prepare sets the current transaction hash and index and block hash which is used when the EVM emits new state logs.

func (*DB) RawDump

func (s *DB) RawDump(opts *DumpConfig) Dump

RawDump returns the entire state an a single large object

func (*DB) Reset

func (db *DB) Reset(root common.Hash) error

Reset clears out all ephemeral state objects from the state db, but keeps the underlying state trie to avoid reloading data for the next operations.

func (*DB) RevertToSnapshot

func (db *DB) RevertToSnapshot(revid int)

RevertToSnapshot reverts all state changes made since the given revision.

func (*DB) SetBalance

func (db *DB) SetBalance(addr common.Address, amount *big.Int)

SetBalance ...

func (*DB) SetCode

func (db *DB) SetCode(addr common.Address, code []byte)

SetCode ...

func (*DB) SetNonce

func (db *DB) SetNonce(addr common.Address, nonce uint64)

SetNonce ...

func (*DB) SetState

func (db *DB) SetState(addr common.Address, key, value common.Hash)

SetState ...

func (*DB) SetTxHashETH

func (db *DB) SetTxHashETH(ethTxHash common.Hash)

func (*DB) SetValidatorFirstElectionEpoch

func (db *DB) SetValidatorFirstElectionEpoch(addr common.Address, epoch *big.Int)

SetValidatorFirstElectionEpoch sets the epoch when the validator is first elected

func (*DB) SetValidatorFlag

func (db *DB) SetValidatorFlag(addr common.Address)

SetValidatorFlag checks whether it is a validator object

func (*DB) Snapshot

func (db *DB) Snapshot() int

Snapshot returns an identifier for the current revision of the state.

func (*DB) StorageTrie

func (db *DB) StorageTrie(addr common.Address) Trie

StorageTrie returns the storage trie of an account. The return value is a copy and is nil for non-existent accounts.

func (*DB) SubBalance

func (db *DB) SubBalance(addr common.Address, amount *big.Int)

SubBalance subtracts amount from the account associated with addr.

func (*DB) SubRefund

func (db *DB) SubRefund(gas uint64)

SubRefund removes gas from the refund counter. This method will panic if the refund counter goes below zero

func (*DB) Suicide

func (db *DB) Suicide(addr common.Address) bool

Suicide marks the given account as suicided. This clears the account balance.

The account's state object is still available until the state is committed, getStateObject will return a non-nil account after Suicide.

func (*DB) TxHash

func (s *DB) TxHash() common.Hash

func (*DB) TxHashETH

func (s *DB) TxHashETH() common.Hash

func (*DB) TxIndex

func (db *DB) TxIndex() int

TxIndex returns the current transaction index set by Prepare.

func (*DB) UnsetValidatorFlag

func (db *DB) UnsetValidatorFlag(addr common.Address)

UnsetValidatorFlag checks whether it is a validator object

func (*DB) UpdateValidatorWrapper

func (db *DB) UpdateValidatorWrapper(
	addr common.Address, val *stk.ValidatorWrapper,
) error

UpdateValidatorWrapper updates staking information of a given validator (including delegation info)

func (*DB) UpdateValidatorWrapperWithRevert

func (db *DB) UpdateValidatorWrapperWithRevert(
	addr common.Address, val *stk.ValidatorWrapper,
) error

UpdateValidatorWrapperWithRevert updates staking information of a given validator (including delegation info)

func (*DB) ValidatorWrapper

func (db *DB) ValidatorWrapper(
	addr common.Address,
	sendOriginal bool,
	copyDelegations bool,
) (*stk.ValidatorWrapper, error)

ValidatorWrapper retrieves the existing validator in the cache, if sendOriginal else it will return a copy of the wrapper - which needs to be explicitly committed with UpdateValidatorWrapper to conserve memory, the copy can optionally avoid deep copying delegations Revert in UpdateValidatorWrapper does not work if sendOriginal == true

type Database

type Database interface {
	// OpenTrie opens the main account trie.
	OpenTrie(root common.Hash) (Trie, error)

	// OpenStorageTrie opens the storage trie of an account.
	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)

	// CopyTrie returns an independent copy of the given trie.
	CopyTrie(Trie) Trie

	// ContractCode retrieves a particular contract's code.
	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)

	// ContractCodeSize retrieves a particular contracts code's size.
	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)

	// TrieDB retrieves the low level trie database used for data storage.
	TrieDB() *trie.Database
}

Database wraps access to tries and contract code.

func NewDatabase

func NewDatabase(db ethdb.Database) Database

NewDatabase creates a backing store for state. The returned database is safe for concurrent use, but does not retain any recent trie nodes in memory. To keep some historical state in memory, use the NewDatabaseWithCache constructor.

func NewDatabaseWithCache

func NewDatabaseWithCache(db ethdb.Database, cache int) Database

NewDatabaseWithCache creates a backing store for state. The returned database is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a large memory cache.

type Dump

type Dump struct {
	Root     string                         `json:"root"`
	Accounts map[common.Address]DumpAccount `json:"accounts"`
}

Dump represents the full dump in a collected format, as one large map.

func (*Dump) OnAccountEnd

func (d *Dump) OnAccountEnd(addr common.Address, account DumpAccount)

OnAccount implements DumpCollector interface

func (*Dump) OnAccountStart

func (d *Dump) OnAccountStart(addr common.Address, account DumpAccount)

OnAccount implements DumpCollector interface

func (*Dump) OnAccountState

func (d *Dump) OnAccountState(_ common.Address, StateSecureKey hexutil.Bytes, key, value []byte)

OnAccount implements DumpCollector interface

func (*Dump) OnRoot

func (d *Dump) OnRoot(root common.Hash)

OnRoot implements DumpCollector interface

type DumpAccount

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
	SecureKey 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

type DumpCollector interface {
	// OnRoot is called with the state root
	OnRoot(common.Hash)
	// OnAccount is called once for each account in the trie
	OnAccountStart(common.Address, DumpAccount)
	// OnAccount is called once for each account in the trie
	OnAccountState(_ common.Address, StateSecureKey hexutil.Bytes, key, value []byte)
	OnAccountEnd(common.Address, DumpAccount)
}

DumpCollector interface which the state trie calls during iteration

type DumpConfig

type DumpConfig struct {
	SkipCode          bool
	SkipStorage       bool
	OnlyWithAddresses bool
	HoldStorage       bool
	Start             []byte
	End               []byte
	StateStart        []byte
	StateEnd          []byte
	Max               uint64
}

DumpConfig is a set of options to control what portions of the statewill be iterated and collected.

type IteratorDump

type IteratorDump struct {
	Root     string                         `json:"root"`
	Accounts map[common.Address]DumpAccount `json:"accounts"`
	Next     []byte                         `json:"next,omitempty"` // nil if no more accounts
}

IteratorDump is an implementation for iterating over data.

func (*IteratorDump) OnAccountEnd

func (d *IteratorDump) OnAccountEnd(addr common.Address, account DumpAccount)

OnAccount implements DumpCollector interface

func (*IteratorDump) OnAccountStart

func (d *IteratorDump) OnAccountStart(addr common.Address, account DumpAccount)

OnAccount implements DumpCollector interface

func (*IteratorDump) OnAccountState

func (d *IteratorDump) OnAccountState(_ common.Address, StateSecureKey hexutil.Bytes, key, value []byte)

OnAccount implements DumpCollector interface

func (*IteratorDump) OnRoot

func (d *IteratorDump) OnRoot(root common.Hash)

OnRoot implements DumpCollector interface

type ManagedState

type ManagedState struct {
	*DB
	// contains filtered or unexported fields
}

ManagedState ...

func ManageState

func ManageState(statedb *DB) *ManagedState

ManageState returns a new managed state with the statedb as it's backing layer

func (*ManagedState) GetNonce

func (ms *ManagedState) GetNonce(addr common.Address) uint64

GetNonce returns the canonical nonce for the managed or unmanaged account.

Because GetNonce mutates the DB, we must take a write lock.

func (*ManagedState) HasAccount

func (ms *ManagedState) HasAccount(addr common.Address) bool

HasAccount returns whether the given address is managed or not

func (*ManagedState) NewNonce

func (ms *ManagedState) NewNonce(addr common.Address) uint64

NewNonce returns the new canonical nonce for the managed account

func (*ManagedState) RemoveNonce

func (ms *ManagedState) RemoveNonce(addr common.Address, n uint64)

RemoveNonce removed the nonce from the managed state and all future pending nonces

func (*ManagedState) SetNonce

func (ms *ManagedState) SetNonce(addr common.Address, nonce uint64)

SetNonce sets the new canonical nonce for the managed state

func (*ManagedState) SetState

func (ms *ManagedState) SetState(statedb *DB)

SetState sets the backing layer of the managed state

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object represents an Ethereum account which is being modified.

The usage pattern is as follows: First you need to obtain a state object. Account values can be accessed and modified through the object. Finally, call CommitTrie to write the modified storage trie into a database.

func (*Object) AddBalance

func (s *Object) AddBalance(amount *big.Int)

AddBalance removes amount from c's balance. It is used to add funds to the destination account of a transfer.

func (*Object) Address

func (s *Object) Address() common.Address

Address returns the address of the contract/account

func (*Object) Balance

func (s *Object) Balance() *big.Int

Balance ...

func (*Object) Code

func (s *Object) Code(db Database) []byte

Code returns the contract code associated with this object, if any.

func (*Object) CodeHash

func (s *Object) CodeHash() []byte

CodeHash ...

func (*Object) CommitTrie

func (s *Object) CommitTrie(db Database) error

CommitTrie the storage trie of the object to db. This updates the trie root.

func (*Object) EncodeRLP

func (s *Object) EncodeRLP(w io.Writer) error

EncodeRLP implements rlp.Encoder.

func (*Object) GetCommittedState

func (s *Object) GetCommittedState(db Database, key common.Hash) common.Hash

GetCommittedState retrieves a value from the committed account storage trie.

func (*Object) GetState

func (s *Object) GetState(db Database, key common.Hash) common.Hash

GetState retrieves a value from the account storage trie.

func (*Object) IsValidator

func (s *Object) IsValidator(db Database) bool

IsValidator checks whether it is a validator object

func (*Object) Nonce

func (s *Object) Nonce() uint64

Nonce ...

func (*Object) ReturnGas

func (s *Object) ReturnGas(gas *big.Int)

ReturnGas the gas back to the origin. Used by the Virtual machine or Closures

func (*Object) SetBalance

func (s *Object) SetBalance(amount *big.Int)

SetBalance ...

func (*Object) SetCode

func (s *Object) SetCode(codeHash common.Hash, code []byte)

SetCode ...

func (*Object) SetNonce

func (s *Object) SetNonce(nonce uint64)

SetNonce ...

func (*Object) SetState

func (s *Object) SetState(db Database, key, value common.Hash)

SetState updates a value in account storage.

func (*Object) SetStorage

func (s *Object) SetStorage(storage map[common.Hash]common.Hash)

SetStorage replaces the entire state storage with the given one.

After this function is called, all original state will be ignored and state lookup only happens in the fake state storage.

Note this function should only be used for debugging purpose.

func (*Object) SubBalance

func (s *Object) SubBalance(amount *big.Int)

SubBalance removes amount from c's balance. It is used to remove funds from the origin account of a transfer.

func (*Object) Value

func (s *Object) Value() *big.Int

Value Never called, but must be present to allow stateObject to be used as a vm.Account interface that also satisfies the vm.ContractRef interface. Interfaces are awesome.

type Storage

type Storage map[common.Hash]common.Hash

Storage ...

func (Storage) Copy

func (s Storage) Copy() Storage

Copy ...

func (Storage) String

func (s Storage) String() (str string)

type Trie

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 SecureTrie is removed
	GetKey([]byte) []byte

	// TryGet 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.
	TryGet(key []byte) ([]byte, error)

	// TryUpdate 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.
	TryUpdate(key, value []byte) error

	// TryDelete removes any existing value for key from the trie. If a node was not
	// found in the database, a trie.MissingNodeError is returned.
	TryDelete(key []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 writes all nodes to the trie's memory database, tracking the internal
	// and external (for account tries) references.
	Commit(onleaf trie.LeafCallback) (common.Hash, error)

	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
	// starts at the key after the given start key.
	NodeIterator(startKey []byte) trie.NodeIterator

	// 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, fromLevel uint, proofDb ethdb.KeyValueWriter) error
}

Trie is a Ethereum Merkle Patricia trie.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL