vm

package
v0.18.15 Latest Latest
Warning

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

Go to latest
Published: May 17, 2022 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// BloomByteLength represents the number of bytes used in a header log bloom.
	BloomByteLength = 256

	// BloomBitLength represents the number of bits used in a header log bloom.
	BloomBitLength = 8 * BloomByteLength
)
View Source
const (
	TxGas                    = ethparams.TxGas
	TxGasContractCreationGas = ethparams.TxGasContractCreation
)

Variables

View Source
var (
	// refunds
	RefundQuotientFrankenstein uint64 = 3

	// defaults
	DefaultDifficulty       *big.Int = big.NewInt(1)
	SimulationBlockGasLimit uint64   = 100_000_000
	DefaultBlockGasLimit    uint64   = math.MaxInt64
	DefaultGasPrice         *big.Int = big.NewInt(1_000_000_000)
)

Functions

func Bloom9

func Bloom9(data []byte) []byte

Bloom9 returns the bloom filter for the given data

func BloomLookup

func BloomLookup(bin Bloom, topic bytesBacked) bool

BloomLookup is a convenience-method to check presence int he bloom filter

func CopyCommitStateDB

func CopyCommitStateDB(from, to *CommitStateDB)

func EthereumConfig

func EthereumConfig(chainID string) *ethparams.ChainConfig

func GetHashFn

func GetHashFn(s *CommitStateDB, header *abci.Header) ethvm.GetHashFunc

GetHashFn implements vm.GetHashFunc for OneLedger protocol. It handles 3 cases:

  1. The requested height matches the current height (and thus same epoch number, could take from cache)
  2. The requested height is from an previous height from the same chain epoch
  3. The requested height is from a height greater than the latest one

func IntrinsicGas

func IntrinsicGas(data []byte, accessList ethtypes.AccessList, isContractCreation bool) (uint64, error)

IntrinsicGas computes the 'intrinsic gas' for a message with the given data.

func IsEmptyHash

func IsEmptyHash(hash string) bool

func IsZeroAmount

func IsZeroAmount(amount *big.Int) bool

chec if zero amount in coin

func LogsBloom

func LogsBloom(logs []*ethtypes.Log) []byte

LogsBloom returns the bloom bytes for the given logs

Types

type Bloom

type Bloom [BloomByteLength]byte

Bloom represents a 2048 bit bloom filter.

func BytesToBloom

func BytesToBloom(b []byte) Bloom

BytesToBloom converts a byte slice to a bloom filter. It panics if b is not of suitable size.

func (*Bloom) Add

func (b *Bloom) Add(d []byte, buf []byte)

Add adds d to the filter. Future calls of Test(d) will return true.

func (Bloom) Big

func (b Bloom) Big() *big.Int

Big converts b to a big integer. Note: Converting a bloom filter to a big.Int and then calling GetBytes does not return the same bytes, since big.Int will trim leading zeroes

func (Bloom) Bytes

func (b Bloom) Bytes() []byte

Bytes returns the backing byte slice of the bloom

func (Bloom) MarshalText

func (b Bloom) MarshalText() ([]byte, error)

MarshalText encodes b as a hex string with 0x prefix.

func (*Bloom) SetBytes

func (b *Bloom) SetBytes(d []byte)

SetBytes sets the content of b to the given bytes. It panics if d is not of suitable size.

func (Bloom) Test

func (b Bloom) Test(topic []byte) bool

Test checks if the given topic is present in the bloom filter

func (*Bloom) UnmarshalText

func (b *Bloom) UnmarshalText(input []byte) error

UnmarshalText b as a hex string with 0x prefix.

type CommitStateDB

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

func NewCommitStateDB

func NewCommitStateDB(cs *evm.ContractStore, ak balance.AccountKeeper, logger *log.Logger) *CommitStateDB

NewCommitStateDB returns a reference to a newly initialized CommitStateDB which implements Geth's state.StateDB interface.

CONTRACT: Stores used for state must be cache-wrapped as the ordering of the key/value space matters in determining the merkle root.

func (*CommitStateDB) AddAddressToAccessList

func (s *CommitStateDB) AddAddressToAccessList(addr ethcmn.Address)

AddAddressToAccessList adds the given address to the access list

func (*CommitStateDB) AddBalance

func (s *CommitStateDB) AddBalance(addr ethcmn.Address, amount *big.Int)

AddBalance adds amount to the account associated with addr.

func (*CommitStateDB) AddLog

func (s *CommitStateDB) AddLog(log *ethtypes.Log)

AddLog adds a new log to the state and sets the log metadata from the state.

func (*CommitStateDB) AddPreimage

func (s *CommitStateDB) AddPreimage(hash ethcmn.Hash, preimage []byte)

AddPreimage records a SHA3 preimage seen by the VM.

func (*CommitStateDB) AddRefund

func (s *CommitStateDB) AddRefund(gas uint64)

AddRefund adds gas to the refund counter.

func (*CommitStateDB) AddSlotToAccessList

func (s *CommitStateDB) AddSlotToAccessList(addr ethcmn.Address, slot ethcmn.Hash)

AddSlotToAccessList adds the given (address, slot)-tuple to the access list

func (*CommitStateDB) AddressInAccessList

func (s *CommitStateDB) AddressInAccessList(addr ethcmn.Address) bool

AddressInAccessList returns true if the given address is in the access list.

func (*CommitStateDB) Copy

func (s *CommitStateDB) Copy() *CommitStateDB

Copy creates a deep, independent copy of the state.

NOTE: Snapshots of the copied state cannot be applied to the copy.

func (*CommitStateDB) CreateAccount

func (s *CommitStateDB) CreateAccount(addr ethcmn.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 (*CommitStateDB) Empty

func (s *CommitStateDB) Empty(addr ethcmn.Address) bool

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

func (*CommitStateDB) Enabled

func (s *CommitStateDB) Enabled() bool

Enabled shows if commit state db is switched on/off

func (*CommitStateDB) Error

func (s *CommitStateDB) Error() error

Error returns the first non-nil error the StateDB encountered.

func (*CommitStateDB) Exist

func (s *CommitStateDB) Exist(addr ethcmn.Address) bool

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

func (*CommitStateDB) Finalise

func (s *CommitStateDB) Finalise(deleteEmptyObjects bool) error

Finalise finalizes the state objects (accounts) state by setting their state, removing the s destructed objects and clearing the journal as well as the refunds.

func (*CommitStateDB) Finality

func (s *CommitStateDB) Finality(events []abci.Event)

Finality used to increment tx counter, clear staff and etc. (no state change)

func (*CommitStateDB) ForEachStorage

func (s *CommitStateDB) ForEachStorage(addr ethcmn.Address, cb func(key, value ethcmn.Hash) bool) error

ForEachStorage iterates over each storage items, all invoke the provided callback on each key, value pair. Only used in tests https://github.com/ethereum/go-ethereum/search?q=ForEachStorage

func (*CommitStateDB) GetAccountKeeper

func (s *CommitStateDB) GetAccountKeeper() balance.AccountKeeper

func (*CommitStateDB) GetAvailableGas

func (s *CommitStateDB) GetAvailableGas() uint64

func (*CommitStateDB) GetBalance

func (s *CommitStateDB) GetBalance(addr ethcmn.Address) *big.Int

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

func (*CommitStateDB) GetBlockHash

func (s *CommitStateDB) GetBlockHash(height uint64) ethcmn.Hash

GetBlockHash from block store at specific height

func (*CommitStateDB) GetBlockStore

func (s *CommitStateDB) GetBlockStore() *store.BlockStore

GetBlockStore current to fetch a blocks

func (*CommitStateDB) GetBloomEvent

func (s *CommitStateDB) GetBloomEvent() *types.Event

GetBloomEvent for block ender

func (*CommitStateDB) GetCode

func (s *CommitStateDB) GetCode(addr ethcmn.Address) []byte

GetCode returns the code for a given account.

func (*CommitStateDB) GetCodeHash

func (s *CommitStateDB) GetCodeHash(addr ethcmn.Address) ethcmn.Hash

GetCodeHash returns the code hash for a given account.

func (*CommitStateDB) GetCodeSize

func (s *CommitStateDB) GetCodeSize(addr ethcmn.Address) int

GetCodeSize returns the code size for a given account.

func (*CommitStateDB) GetCommittedState

func (s *CommitStateDB) GetCommittedState(addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash

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

func (*CommitStateDB) GetContractStore

func (s *CommitStateDB) GetContractStore() *evm.ContractStore

func (*CommitStateDB) GetNonce

func (s *CommitStateDB) GetNonce(addr ethcmn.Address) uint64

GetNonce returns the nonce (sequence number) for a given account.

func (*CommitStateDB) GetOrNewStateObject

func (s *CommitStateDB) GetOrNewStateObject(addr ethcmn.Address) StateObject

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

func (*CommitStateDB) GetRefund

func (s *CommitStateDB) GetRefund() uint64

GetRefund returns the current value of the refund counter.

func (*CommitStateDB) GetState

func (s *CommitStateDB) GetState(addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash

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

func (*CommitStateDB) GetTxLogs

func (s *CommitStateDB) GetTxLogs() []*ethtypes.Log

GetTxLogs return current tx logs

func (*CommitStateDB) HasSuicided

func (s *CommitStateDB) HasSuicided(addr ethcmn.Address) bool

HasSuicided returns if the given account for the specified address has been killed.

func (*CommitStateDB) Prepare

func (s *CommitStateDB) Prepare(thash ethcmn.Hash)

Prepare sets the current transaction hash which is used when the EVM emits new state logs. (no state change)

func (*CommitStateDB) PrepareAccessList

func (s *CommitStateDB) PrepareAccessList(sender ethcmn.Address, dst *ethcmn.Address, precompiles []ethcmn.Address, list ethtypes.AccessList)

PrepareAccessList handles the preparatory steps for executing a state transition with regards to both EIP-2929 and EIP-2930:

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

This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.

func (*CommitStateDB) PrintState

func (s *CommitStateDB) PrintState()

func (*CommitStateDB) Reset

func (s *CommitStateDB) Reset()

Reset clears out all ephemeral state objects from the state db, but keeps the underlying account mapper and store keys to avoid reloading data for the next operations.

func (*CommitStateDB) RevertToSnapshot

func (s *CommitStateDB) RevertToSnapshot(revID int)

RevertToSnapshot reverts all state changes made since the given revision.

func (*CommitStateDB) SetBlockHash

func (s *CommitStateDB) SetBlockHash(hash ethcmn.Hash)

SetBlockHash set hash of the block

func (*CommitStateDB) SetBlockStore

func (s *CommitStateDB) SetBlockStore(blockStore *store.BlockStore)

SetBlockStore to fetch info about blocks

func (*CommitStateDB) SetCode

func (s *CommitStateDB) SetCode(addr ethcmn.Address, code []byte)

SetCode sets the code for a given account.

func (*CommitStateDB) SetNonce

func (s *CommitStateDB) SetNonce(addr ethcmn.Address, nonce uint64)

SetNonce sets the nonce (sequence number) of an account.

func (*CommitStateDB) SetState

func (s *CommitStateDB) SetState(addr ethcmn.Address, key, value ethcmn.Hash)

SetState sets the storage state with a key, value pair for an account.

func (*CommitStateDB) SlotInAccessList

func (s *CommitStateDB) SlotInAccessList(addr ethcmn.Address, slot ethcmn.Hash) (bool, bool)

SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.

func (*CommitStateDB) Snapshot

func (s *CommitStateDB) Snapshot() int

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

func (*CommitStateDB) SubBalance

func (s *CommitStateDB) SubBalance(addr ethcmn.Address, amount *big.Int)

SubBalance subtracts amount from the account associated with addr.

func (*CommitStateDB) SubRefund

func (s *CommitStateDB) SubRefund(gas uint64)

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

func (*CommitStateDB) Suicide

func (s *CommitStateDB) Suicide(addr ethcmn.Address) bool

Suicide marks the given account as suicided and 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 (*CommitStateDB) WithState

func (s *CommitStateDB) WithState(state *storage.State) *CommitStateDB

type EVMTransaction

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

func NewEVMTransaction

func NewEVMTransaction(stateDB *CommitStateDB, gaspool *ethcore.GasPool, header *abci.Header, from keys.Address, to *keys.Address, nonce uint64, value *big.Int, data []byte, accessList *ethtypes.AccessList, gas uint64, gasPrice *big.Int, isSimulation bool) *EVMTransaction

func (*EVMTransaction) AccessList

func (etx *EVMTransaction) AccessList() ethtypes.AccessList

func (*EVMTransaction) Apply

func (etx *EVMTransaction) Apply() (*ExecutionResult, error)

func (*EVMTransaction) Data

func (etx *EVMTransaction) Data() []byte

func (*EVMTransaction) From

func (etx *EVMTransaction) From() ethcmn.Address

func (*EVMTransaction) Gas

func (etx *EVMTransaction) Gas() uint64

func (*EVMTransaction) GasPrice

func (etx *EVMTransaction) GasPrice() *big.Int

func (*EVMTransaction) IsFake

func (etx *EVMTransaction) IsFake() bool

func (*EVMTransaction) NewEVM

func (etx *EVMTransaction) NewEVM() *ethvm.EVM

func (*EVMTransaction) Nonce

func (etx *EVMTransaction) Nonce() uint64

func (*EVMTransaction) SetVMDebug

func (etx *EVMTransaction) SetVMDebug(debug bool)

func (*EVMTransaction) To

func (etx *EVMTransaction) To() *ethcmn.Address

func (*EVMTransaction) Value

func (etx *EVMTransaction) Value() *big.Int

type ExecutionResult

type ExecutionResult struct {
	UsedGas         uint64         // Total used gas but include the refunded gas
	Err             error          // Any error encountered during the execution(listed in core/vm/errors.go)
	ReturnData      []byte         // Returned data from evm(function result or data supplied with revert opcode)
	ContractAddress ethcmn.Address // Contract address creation on success
}

ExecutionResult includes all output after executing given evm message no matter the execution itself is successful or not.

func ApplyMessage

func ApplyMessage(evm *ethvm.EVM, msg *EVMTransaction, gp *ethcore.GasPool) (*ExecutionResult, error)

ApplyMessage computes the new state by applying the given message against the old state within the environment.

ApplyMessage returns the bytes returned by any EVM execution (if it took place), the gas used (which includes gas refunds) and an error if it failed. An error always indicates a core error meaning that the message would always fail for that particular state and would never be accepted within a block.

func (*ExecutionResult) Failed

func (result *ExecutionResult) Failed() bool

Failed returns the indicator whether the execution is successful or not

func (*ExecutionResult) Return

func (result *ExecutionResult) Return() []byte

Return is a helper function to help caller distinguish between revert reason and function return. Return returns the data after execution if no error occurs.

func (*ExecutionResult) Revert

func (result *ExecutionResult) Revert() []byte

Revert returns the concrete revert reason if the execution is aborted by `REVERT` opcode. Note the reason can be nil if no data supplied with revert opcode.

func (*ExecutionResult) Unwrap

func (result *ExecutionResult) Unwrap() error

Unwrap returns the internal evm error which allows us for further analysis outside.

type Message

type Message interface {
	From() ethcmn.Address
	To() *ethcmn.Address

	GasPrice() *big.Int
	Gas() uint64
	Value() *big.Int

	Nonce() uint64
	IsFake() bool
	Data() []byte
	AccessList() ethtypes.AccessList

	Apply() (*ExecutionResult, error)
}

Message represents a message sent to a contract.

type RLPLog

type RLPLog struct {
	// Consensus fields:
	// address of the contract that generated the event
	Address common.Address `json:"address" gencodec:"required"`
	// list of topics provided by the contract.
	Topics []common.Hash `json:"topics" gencodec:"required"`
	// supplied by the contract, usually ABI-encoded
	Data []byte `json:"data" gencodec:"required"`

	// Derived fields. These fields are filled in by the node
	// but not secured by consensus.
	// block in which the transaction was included
	BlockNumber uint64 `json:"blockNumber" gencodec:"required"`
	// hash of the transaction
	TxHash common.Hash `json:"transactionHash" gencodec:"required"`
	// index of the transaction in the block
	TxIndex uint `json:"transactionIndex" gencodec:"required"`
	// hash of the block in which the transaction was included
	BlockHash common.Hash `json:"blockHash" gencodec:"required"`
	// index of the log in the block
	Index uint `json:"logIndex" gencodec:"required"`

	// The Removed field is true if this log was reverted due to a chain reorganisation.
	// You must pay attention to this field if you receive logs through a filter query.
	Removed bool `json:"removed" gencodec:"required"`
}

RLPLog used for properly RLP encoding of all field for the log

func RLPLogConvert

func RLPLogConvert(log types.Log) *RLPLog

RLPLogConvert go-ethereum log in order to serialize properly with RLP

func (*RLPLog) Decode

func (l *RLPLog) Decode(data []byte) (*types.Log, error)

Decode decodes log rlp bytes

func (*RLPLog) Encode

func (l *RLPLog) Encode() ([]byte, error)

Encode encodes log rlp bytes

type State

type State struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

func NewState

func NewState(key, value ethcmn.Hash) State

NewState creates a new State instance

type StateObject

type StateObject interface {
	GetCommittedState(db ethstate.Database, key ethcmn.Hash) ethcmn.Hash
	GetState(db ethstate.Database, key ethcmn.Hash) ethcmn.Hash
	SetState(db ethstate.Database, key, value ethcmn.Hash)

	Code(db ethstate.Database) []byte
	SetCode(codeHash ethcmn.Hash, code []byte)
	CodeHash() []byte

	AddBalance(amount *big.Int)
	SubBalance(amount *big.Int)
	SetBalance(amount *big.Int)

	Balance() *big.Int
	ReturnGas(gas *big.Int)
	Address() ethcmn.Address

	SetNonce(nonce uint64)
	Nonce() uint64
}

StateObject interface for interacting with state object

type StateTransition

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

The State Transitioning Model A state transition is a change made when a transaction is applied to the current world state The state transitioning model does all the necessary work to work out a valid new state root. 1) Nonce handling 2) Pre pay gas 3) Create a new state object if the recipient is \0*32 4) Value transfer == If contract creation ==

4a) Attempt to run transaction data
4b) If valid, use result as code for the new state object

== end == 5) Run Script section 6) Derive new state root

func NewStateTransition

func NewStateTransition(evm *ethvm.EVM, msg *EVMTransaction, gp *ethcore.GasPool) *StateTransition

NewStateTransition initialises and returns a new state transition object.

func (*StateTransition) TransitionDb

func (st *StateTransition) TransitionDb() (*ExecutionResult, error)

TransitionDb will transition the state by applying the current message and returning the evm execution result with following fields.

  • used gas: total gas used (including gas being refunded)
  • returndata: the returned data from evm
  • concrete execution error: various **EVM** error which aborts the execution, e.g. ErrOutOfGas, ErrExecutionReverted

However if any consensus issue encountered, return the error directly with nil evm execution result.

type Storage

type Storage []State

func (Storage) Copy

func (s Storage) Copy() Storage

Copy returns a copy of storage.

func (Storage) String

func (s Storage) String() string

String implements the stringer interface

Jump to

Keyboard shortcuts

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