vm

package
v0.0.0-...-7b0d77e Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2024 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CallValueTransferGas  uint64 = 9000  // Paid for CALL when the value transfer is non-zero.
	CallNewAccountGas     uint64 = 25000 // Paid for CALL when the destination address didn't exist prior.
	TxGas                 uint64 = 21000 // Per transaction not creating a contract. NOTE: Not payable on data of calls between transactions.
	TxGasContractCreation uint64 = 53000 // Per transaction that creates a contract. NOTE: Not payable on data of calls between transactions.
	TxDataZeroGas         uint64 = 4     // Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions.
	QuadCoeffDiv          uint64 = 512   // Divisor for the quadratic particle of the memory cost equation.
	LogDataGas            uint64 = 8     // Per byte in a LOG* operation's data.
	CallStipend           uint64 = 2300  // Free gas given at beginning of call.

	Keccak256Gas     uint64 = 30 // Once per KECCAK256 operation.
	Keccak256WordGas uint64 = 6  // Once per word of the KECCAK256 operation's data.

	SstoreSetGas    uint64 = 20000 // Once per SLOAD operation.
	SstoreResetGas  uint64 = 5000  // Once per SSTORE operation if the zeroness changes from zero.
	SstoreClearGas  uint64 = 5000  // Once per SSTORE operation if the zeroness doesn't change.
	SstoreRefundGas uint64 = 15000 // Once per SSTORE operation if the zeroness changes to zero.

	NetSstoreNoopGas  uint64 = 200   // Once per SSTORE operation if the value doesn't change.
	NetSstoreInitGas  uint64 = 20000 // Once per SSTORE operation from clean zero.
	NetSstoreCleanGas uint64 = 5000  // Once per SSTORE operation from clean non-zero.
	NetSstoreDirtyGas uint64 = 200   // Once per SSTORE operation from dirty.

	NetSstoreClearRefund      uint64 = 15000 // Once per SSTORE operation for clearing an originally existing storage slot
	NetSstoreResetRefund      uint64 = 4800  // Once per SSTORE operation for resetting to the original non-zero value
	NetSstoreResetClearRefund uint64 = 19800 // Once per SSTORE operation for resetting to the original zero value

	JumpdestGas      uint64 = 1               // Once per JUMPDEST operation.
	CreateDataGas    uint64 = 200             //
	CallCreateDepth         = 1024            // Maximum depth of call/create stack.
	ExpGas           uint64 = 10              // Once per EXP instruction
	LogGas           uint64 = 375             // Per LOG* operation.
	CopyGas          uint64 = 3               //
	StackLimit              = CallCreateDepth // Maximum size of VM stack allowed.
	LogTopicGas      uint64 = 375             // Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas.
	CreateGas        uint64 = 32000           // Once per CREATE operation & contract-creation transaction.
	Create2Gas       uint64 = 32000           // Once per CREATE2 operation
	SuicideRefundGas uint64 = 24000           // Refunded following a suicide operation.
	MemoryGas        uint64 = 3               // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL.
	TxDataNonZeroGas uint64 = 68              // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.

	MaxCodeSize = 24576 // Maximum bytecode to permit for a contract

	EcrecoverGas            uint64 = 3000   // Elliptic curve sender recovery gas price
	Sha256BaseGas           uint64 = 60     // Base price for a SHA256 operation
	Sha256PerWordGas        uint64 = 12     // Per-word price for a SHA256 operation
	Ripemd160BaseGas        uint64 = 600    // Base price for a RIPEMD160 operation
	Ripemd160PerWordGas     uint64 = 120    // Per-word price for a RIPEMD160 operation
	IdentityBaseGas         uint64 = 15     // Base price for a data copy operation
	IdentityPerWordGas      uint64 = 3      // Per-work price for a data copy operation
	ModExpQuadCoeffDiv      uint64 = 20     // Divisor for the quadratic particle of the big int modular exponentiation
	Bn256AddGas             uint64 = 500    // Gas needed for an elliptic curve addition
	Bn256ScalarMulGas       uint64 = 40000  // Gas needed for an elliptic curve scalar multiplication
	Bn256PairingBaseGas     uint64 = 100000 // Base price for an elliptic curve pairing check
	Bn256PairingPerPointGas uint64 = 80000  // Per-point price for an elliptic curve pairing check

	Bls12381G1AddGas          uint64 = 600    // Price for BLS12-381 elliptic curve G1 point addition
	Bls12381G1MulGas          uint64 = 12000  // Price for BLS12-381 elliptic curve G1 point scalar multiplication
	Bls12381G2AddGas          uint64 = 4500   // Price for BLS12-381 elliptic curve G2 point addition
	Bls12381G2MulGas          uint64 = 55000  // Price for BLS12-381 elliptic curve G2 point scalar multiplication
	Bls12381PairingBaseGas    uint64 = 115000 // Base gas price for BLS12-381 elliptic curve pairing check
	Bls12381PairingPerPairGas uint64 = 23000  // Per-point pair gas price for BLS12-381 elliptic curve pairing check
	Bls12381MapG1Gas          uint64 = 5500   // Gas price for BLS12-381 mapping field element to G1 operation
	Bls12381MapG2Gas          uint64 = 110000 // Gas price for BLS12-381 mapping field element to G2 operation
)
View Source
const (
	GasQuickStep   uint64 = 2
	GasFastestStep uint64 = 3
	GasFastStep    uint64 = 5
	GasMidStep     uint64 = 8
	GasSlowStep    uint64 = 10
	GasExtStep     uint64 = 20
)

Gas costs

View Source
const (
	CALL_string         = "call"
	CALLCODE_string     = "callcode"
	DELEGATECALL_string = "delegatecall"
	STATICCALL_string   = "staticcall"
	CREATE_string       = "create"
	SUICIDE             = "suicide"
)
View Source
const (
	DUP1 = 0x80 + iota
	DUP2
	DUP3
	DUP4
	DUP5
	DUP6
	DUP7
	DUP8
	DUP9
	DUP10
	DUP11
	DUP12
	DUP13
	DUP14
	DUP15
	DUP16
)

0x80 range - dups.

View Source
const (
	SWAP1 = 0x90 + iota
	SWAP2
	SWAP3
	SWAP4
	SWAP5
	SWAP6
	SWAP7
	SWAP8
	SWAP9
	SWAP10
	SWAP11
	SWAP12
	SWAP13
	SWAP14
	SWAP15
	SWAP16
)

0x90 range - swaps.

Variables

View Source
var (
	ErrOutOfGas                       = util.ErrorString("out of gas")
	ErrIntrinsicGas                   = util.ErrorString("intrinsic gas too low")
	ErrCodeStoreOutOfGas              = util.ErrorString("contract creation code storage out of gas")
	ErrDepth                          = util.ErrorString("max call depth exceeded")
	ErrInsufficientBalanceForTransfer = util.ErrorString("insufficient balance for transfer")
	ErrContractAddressCollision       = util.ErrorString("contract address collision")
	ErrInsufficientBalanceForGas      = util.ErrorString("insufficient balance to pay for gas")
	ErrNonceTooHigh                   = util.ErrorString("nonce too high")
	ErrNonceTooLow                    = util.ErrorString("nonce too low")
	ErrWriteProtection                = util.ErrorString("write protection")
	ErrTraceLimitReached              = util.ErrorString("the number of logs reached the specified limit")
)

TODO compress to error codes List execution errors

View Source
var Bls12381MultiExpDiscountTable = [128]uint64{} /* 128 elements not displayed */

Gas discount table for BLS12-381 G1 and G2 multi exponentiation operations

View Source
var (
	ErrExecutionReverted = errors.New("evm: execution reverted")
)
View Source
var (
	// GasTableCalifornicum contain the gas re-prices for
	// the constantinople phase.
	GasTableCalifornicum = GasTable{
		ExtcodeSize: 700,
		ExtcodeCopy: 700,
		ExtcodeHash: 700,
		Balance:     700,
		SLoad:       800,
		Calls:       700,
		Suicide:     5000,
		ExpByte:     50,

		CreateBySuicide:     25000,
		WarmStorageReadCost: 100,
	}
)

Variables containing gas prices for different ethereum phases.

View Source
var PrecompiledContractAddrPrefix = make([]byte, common.AddressLength-1)
View Source
var PrecompiledContractsCalifornicum = Precompiles{
	&ecrecover{},
	&sha256hash{},
	&ripemd160hash{},
	&dataCopy{},
	&bigModExp{},
	&bn256Add{},
	&bn256ScalarMul{},
	&bn256Pairing{},
}

PrecompiledContractsCalifornicum contains the default set of pre-compiled Ethereum contracts used in the Californicum release.

View Source
var PrecompiledContractsFicus = Precompiles{
	&ecrecover{},
	&sha256hash{},
	&ripemd160hash{},
	&dataCopy{},
	&bigModExp{},
	&bn256Add{},
	&bn256ScalarMul{},
	&bn256Pairing{},
	&blake2F{},
	nil,
	&bls12381G1Add{},
	&bls12381G1Mul{},
	&bls12381G1MultiExp{},
	&bls12381G2Add{},
	&bls12381G2Mul{},
	&bls12381G2MultiExp{},
	&bls12381Pairing{},
	&bls12381MapG1{},
	&bls12381MapG2{},
}

Functions

func BalanceGTE

func BalanceGTE(acc StateAccount, val *big.Int) bool

func IntrinsicGas

func IntrinsicGas(data []byte, contractCreation bool) (uint64, error)

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

func WriteLogs

func WriteLogs(writer io.Writer, logs []*types.Log)

WriteLogs writes vm logs in a readable format to the given writer

func WriteTrace

func WriteTrace(writer io.Writer, logs []StructLog)

WriteTrace writes a formatted trace to the given writer

Types

type Block

type Block struct {
	Number types.BlockNum
	BlockInfo
}

type BlockInfo

type BlockInfo struct {
	Author     common.Address // Provides information for COINBASE
	GasLimit   uint64         // Provides information for GASLIMIT
	Time       uint64         // Provides information for TIME
	Difficulty *big.Int       // Provides information for DIFFICULTY
}

type CallFrame

type CallFrame = struct {
	// CallerAddress is the result of the caller which initialized this
	// contract. However when the "call method" is delegated this value
	// needs to be initialized to that of the caller's caller.
	CallerAccount StateAccount
	Account       StateAccount
	Input         []byte
	Gas           uint64
	Value         *big.Int
}

type CallTraceAction

type CallTraceAction struct {
	From     common.Address `json:"from"`
	CallType string         `json:"callType"`
	Gas      hexutil.Big    `json:"gas"`
	Input    hexutil.Bytes  `json:"input"`
	To       common.Address `json:"to"`
	Value    hexutil.Big    `json:"value"`
}

type CodeAndHash

type CodeAndHash struct {
	Code     []byte
	CodeHash *common.Hash
}

type Config

type Config struct {
	// Debug enabled debugging Interpreter options
	Debug bool
	// Tracer is the op code logger
	Tracer Tracer
}

Config are the configuration options for the Interpreter

type Contract

type Contract struct {
	CallFrame
	// contains filtered or unexported fields
}

Contract represents an ethereum contract in the state database. It contains the contract code, calling arguments.

func NewContract

func NewContract(frame CallFrame, code CodeAndHash) (ret Contract)

NewContract returns a new contract environment for the execution of EVM.

func (*Contract) Account

func (c *Contract) Account() StateAccount

Address returns the contracts account

func (*Contract) Address

func (c *Contract) Address() *common.Address

Address returns the contracts address

func (*Contract) GetCode

func (self *Contract) GetCode() []byte

func (*Contract) GetOp

func (self *Contract) GetOp(n uint64) OpCode

GetOp returns the n'th element in the contract's byte array

func (*Contract) UseGas

func (self *Contract) UseGas(gas uint64) (ok bool)

UseGas attempts the use gas and subtracts it and returns true on success

func (*Contract) ValidJumpdest

func (self *Contract) ValidJumpdest(evm *EVM, dest *uint256.Int) bool

TODO optimize and refactor

type ContractAccWrapper

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

func (ContractAccWrapper) Account

func (c ContractAccWrapper) Account() StateAccount

Address returns the contracts account

func (ContractAccWrapper) Address

func (c ContractAccWrapper) Address() *common.Address

Address returns the contracts address

type ContractRef

type ContractRef interface {
	Address() *common.Address
	Account() StateAccount
}

type CreateTraceAction

type CreateTraceAction struct {
	From  common.Address `json:"from"`
	Gas   hexutil.Big    `json:"gas"`
	Init  hexutil.Bytes  `json:"init"`
	Value hexutil.Big    `json:"value"`
}

type CreateTraceResult

type CreateTraceResult struct {
	// Do not change the ordering of these fields -- allows for easier comparison with other clients
	Address *common.Address `json:"address,omitempty"`
	Code    hexutil.Bytes   `json:"code"`
	GasUsed *hexutil.Big    `json:"gasUsed"`
}

type EVM

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

EVM is the Ethereum Virtual Machine base object and provides the necessary tools to run a contract on the given state with the provided context. It should be noted that any error generated through any of the calls should be considered a revert-state-and-consume-all-gas operation, no checks on specific errors should ever be performed. The interpreter makes sure that any errors generated are to be considered faulty code.

func (*EVM) AddLog

func (self *EVM) AddLog(log LogRecord)

func (*EVM) Call

func (self *EVM) Call(caller ContractRef, callee StateAccount, input []byte, gas uint64, value *big.Int) (ret []byte, gas_left uint64, err error)

call executes the contract associated with the addr with the given input as parameters. It also handles any necessary value transfer required and takes the necessary steps to create accounts and reverses the state in case of an execution error or failed value transfer.

func (*EVM) GetBlock

func (self *EVM) GetBlock() Block

func (*EVM) GetDepth

func (self *EVM) GetDepth() uint16

func (*EVM) GetRules

func (self *EVM) GetRules() Rules

func (*EVM) Init

func (self *EVM) Init(get_hash GetHashFunc, state State, opts Opts, chainConfig params.ChainConfig, vmConfig Config) *EVM

func (*EVM) Main

func (self *EVM) Main(trx *Transaction) (ret ExecutionResult, execError error)

func (*EVM) RegisterPrecompiledContract

func (self *EVM) RegisterPrecompiledContract(address *common.Address, contract PrecompiledContract)

func (*EVM) SetBlock

func (self *EVM) SetBlock(blk *Block, rules Rules) (rules_changed bool)

type ExecutionResult

type ExecutionResult struct {
	CodeRetval      []byte
	NewContractAddr common.Address
	Logs            []LogRecord
	GasUsed         uint64
	ExecutionErr    util.ErrorString
	ConsensusErr    util.ErrorString
}

type GasTable

type GasTable struct {
	ExtcodeSize uint64
	ExtcodeCopy uint64
	ExtcodeHash uint64
	Balance     uint64
	SLoad       uint64
	Calls       uint64
	Suicide     uint64

	ExpByte uint64

	// CreateBySuicide occurs when the
	// refunded account is one that does
	// not exist. This logic is similar
	// to call. May be left nil. Nil means
	// not charged.
	CreateBySuicide uint64
	// EIP1153
	WarmStorageReadCost uint64
}

GasTable organizes gas prices for different ethereum phases.

type GetHashFunc

type GetHashFunc = func(types.BlockNum) *big.Int

type InstructionSet

type InstructionSet = [256]*operation

type LogConfig

type LogConfig struct {
	DisableMemory  bool // disable memory capture
	DisableStack   bool // disable stack capture
	DisableStorage bool // disable storage capture
	Debug          bool // print output during capture end
	Limit          int  // maximum length of output, but zero means unlimited
}

LogConfig are the configuration options for structured logger the EVM

type LogRecord

type LogRecord struct {
	Address common.Address
	Topics  []common.Hash
	Data    []byte
}

type Memory

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

Memory implements a simple memory model for the ethereum virtual machine.

func (*Memory) Copy

func (m *Memory) Copy(dst, src, len uint64)

func (*Memory) GetCopy

func (m *Memory) GetCopy(offset, size int64) (cpy []byte)

Get returns offset + size as a new slice

func (*Memory) GetPtr

func (m *Memory) GetPtr(offset, size int64) []byte

GetPtr returns the offset + size

func (*Memory) Init

func (self *Memory) Init(pool *MemoryPool) *Memory

func (*Memory) Len

func (m *Memory) Len() uint64

Len returns the length of the backing slice

func (*Memory) Print

func (m *Memory) Print()

Print dumps the content of the memory.

func (*Memory) Release

func (self *Memory) Release()

func (*Memory) Resize

func (m *Memory) Resize(size uint64)

Resize resizes the memory to size

func (*Memory) Set

func (m *Memory) Set(offset, size uint64, value []byte)

Set sets offset + size to value

func (*Memory) Set32

func (m *Memory) Set32(offset uint64, val *uint256.Int)

Set32 sets the 32 bytes starting at offset to the value of val, left-padded with zeroes to 32 bytes.

type MemoryPool

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

func (*MemoryPool) Init

func (self *MemoryPool) Init(capacity uint64) *MemoryPool

type OeTracer

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

OpenEthereum-style tracer

func NewOeTracer

func NewOeTracer(cfg *TracingConfig) *OeTracer

NewStructLogger returns a new eologger

func (*OeTracer) CaptureEnd

func (ot *OeTracer) CaptureEnd(output []byte, usedGas uint64, t time.Duration, err error) error

func (*OeTracer) CaptureEnter

func (ot *OeTracer) CaptureEnter(typ OpCode, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error

func (*OeTracer) CaptureExit

func (ot *OeTracer) CaptureExit(output []byte, usedGas uint64, t time.Duration, err error) error

func (*OeTracer) CaptureStart

func (ot *OeTracer) CaptureStart(env *EVM, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error

func (*OeTracer) CaptureState

func (ot *OeTracer) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, st *Stack, contract *Contract, depth uint16, err error) error

func (*OeTracer) GetResult

func (ot *OeTracer) GetResult() *TraceCallResult

func (*OeTracer) SetRetCode

func (ot *OeTracer) SetRetCode(output []byte)

type OpCode

type OpCode byte

OpCode is an EVM opcode

const (
	STOP       OpCode = 0x0
	ADD        OpCode = 0x1
	MUL        OpCode = 0x2
	SUB        OpCode = 0x3
	DIV        OpCode = 0x4
	SDIV       OpCode = 0x5
	MOD        OpCode = 0x6
	SMOD       OpCode = 0x7
	ADDMOD     OpCode = 0x8
	MULMOD     OpCode = 0x9
	EXP        OpCode = 0xa
	SIGNEXTEND OpCode = 0xb
)

0x0 range - arithmetic ops.

const (
	LT     OpCode = 0x10
	GT     OpCode = 0x11
	SLT    OpCode = 0x12
	SGT    OpCode = 0x13
	EQ     OpCode = 0x14
	ISZERO OpCode = 0x15
	AND    OpCode = 0x16
	OR     OpCode = 0x17
	XOR    OpCode = 0x18
	NOT    OpCode = 0x19
	BYTE   OpCode = 0x1a
	SHL    OpCode = 0x1b
	SHR    OpCode = 0x1c
	SAR    OpCode = 0x1d
)

0x10 range - comparison ops.

const (
	ADDRESS        OpCode = 0x30
	BALANCE        OpCode = 0x31
	ORIGIN         OpCode = 0x32
	CALLER         OpCode = 0x33
	CALLVALUE      OpCode = 0x34
	CALLDATALOAD   OpCode = 0x35
	CALLDATASIZE   OpCode = 0x36
	CALLDATACOPY   OpCode = 0x37
	CODESIZE       OpCode = 0x38
	CODECOPY       OpCode = 0x39
	GASPRICE       OpCode = 0x3a
	EXTCODESIZE    OpCode = 0x3b
	EXTCODECOPY    OpCode = 0x3c
	RETURNDATASIZE OpCode = 0x3d
	RETURNDATACOPY OpCode = 0x3e
	EXTCODEHASH    OpCode = 0x3f
)

0x30 range - closure state.

const (
	BLOCKHASH   OpCode = 0x40
	COINBASE    OpCode = 0x41
	TIMESTAMP   OpCode = 0x42
	NUMBER      OpCode = 0x43
	DIFFICULTY  OpCode = 0x44
	GASLIMIT    OpCode = 0x45
	CHAINID     OpCode = 0x46
	SELFBALANCE OpCode = 0x47
)

0x40 range - block operations.

const (
	POP      OpCode = 0x50
	MLOAD    OpCode = 0x51
	MSTORE   OpCode = 0x52
	MSTORE8  OpCode = 0x53
	SLOAD    OpCode = 0x54
	SSTORE   OpCode = 0x55
	JUMP     OpCode = 0x56
	JUMPI    OpCode = 0x57
	PC       OpCode = 0x58
	MSIZE    OpCode = 0x59
	GAS      OpCode = 0x5a
	JUMPDEST OpCode = 0x5b
	MCOPY    OpCode = 0x5e
	PUSH0    OpCode = 0x5f
)

0x50 range - 'storage' and execution.

const (
	PUSH1 OpCode = 0x60 + iota
	PUSH2
	PUSH3
	PUSH4
	PUSH5
	PUSH6
	PUSH7
	PUSH8
	PUSH9
	PUSH10
	PUSH11
	PUSH12
	PUSH13
	PUSH14
	PUSH15
	PUSH16
	PUSH17
	PUSH18
	PUSH19
	PUSH20
	PUSH21
	PUSH22
	PUSH23
	PUSH24
	PUSH25
	PUSH26
	PUSH27
	PUSH28
	PUSH29
	PUSH30
	PUSH31
	PUSH32
)

0x60 range.

const (
	LOG0 OpCode = 0xa0 + iota
	LOG1
	LOG2
	LOG3
	LOG4
)

0xa0 range - logging ops.

const (
	TLOAD  OpCode = 0xb3
	TSTORE OpCode = 0xb4
)

0xb0 range.

const (
	CREATE       OpCode = 0xf0
	CALL         OpCode = 0xf1
	CALLCODE     OpCode = 0xf2
	RETURN       OpCode = 0xf3
	DELEGATECALL OpCode = 0xf4
	CREATE2      OpCode = 0xf5

	STATICCALL   OpCode = 0xfa
	REVERT       OpCode = 0xfd
	INVALID      OpCode = 0xfe
	SELFDESTRUCT OpCode = 0xff
)

0xf0 range - closures.

const (
	KECCAK256 OpCode = 0x20
)

0x20 range - crypto.

func (OpCode) IsPush

func (op OpCode) IsPush() bool

IsPush specifies if an opcode is a PUSH opcode.

func (OpCode) IsStaticJump

func (op OpCode) IsStaticJump() bool

IsStaticJump specifies if an opcode is JUMP.

func (OpCode) String

func (op OpCode) String() string

type Opts

type Opts = struct {
	PreallocatedMem uint64
}

func DefaultOpts

func DefaultOpts() Opts

type ParityTrace

type ParityTrace struct {
	// Do not change the ordering of these fields -- allows for easier comparison with other clients
	Action              interface{}  `json:"action"` // Can be either CallTraceAction or CreateTraceAction
	BlockHash           *common.Hash `json:"blockHash,omitempty"`
	BlockNumber         *uint64      `json:"blockNumber,omitempty"`
	Error               string       `json:"error,omitempty"`
	Result              interface{}  `json:"result"`
	Subtraces           int          `json:"subtraces"`
	TraceAddress        []int        `json:"traceAddress"`
	TransactionHash     *common.Hash `json:"transactionHash,omitempty"`
	TransactionPosition *uint64      `json:"transactionPosition,omitempty"`
	Type                string       `json:"type"`
}

type PrecompiledContract

type PrecompiledContract interface {
	RequiredGas(ctx CallFrame, evm *EVM) uint64
	Run(ctx CallFrame, evm *EVM) ([]byte, error)
}

PrecompiledContract is the basic interface for native Go contracts. The implementation requires a deterministic gas count based on the input size of the Run method of the contract.

type Precompiles

type Precompiles [255]PrecompiledContract

func (*Precompiles) Get

func (self *Precompiles) Get(address *common.Address) (ret PrecompiledContract)

func (*Precompiles) Put

func (self *Precompiles) Put(address *common.Address, contract PrecompiledContract)

type Rules

type Rules struct {
	IsMagnolia     bool
	IsAspenPartOne bool
	IsAspenPartTwo bool
	IsFicus        bool
}

type Stack

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

stack is an object for basic stack operations. Items popped to the stack are expected to be changed and modified. stack does not take care of adding newly initialised objects.

func (*Stack) Back

func (st *Stack) Back(n int) *uint256.Int

Back returns the n'th item in stack

func (*Stack) Print

func (st *Stack) Print()

Print dumps the content of the stack

type State

type State interface {
	GetAccount(*common.Address) StateAccount
	AddLog(LogRecord)
	GetLogs() []LogRecord
	AddRefund(uint64)
	SubRefund(uint64)
	GetRefund() uint64
	RevertToSnapshot(int)
	Snapshot() int
	// EIP1153
	GetTransientState(addr *common.Address, key common.Hash) common.Hash
	SetTransientState(addr *common.Address, key, value common.Hash)
}

State is an EVM database for full state querying.

type StateAccount

type StateAccount interface {
	Address() *common.Address
	GetBalance() *big.Int
	GetNonce() *big.Int
	GetCodeHash() *common.Hash
	GetCode() []byte
	GetCodeSize() uint64
	GetCommittedState(*big.Int) *big.Int
	GetState(*big.Int) *big.Int
	HasSuicided() bool
	// Exist reports whether the given account exists in state.
	// Notably this should also return true for suicided accounts.
	IsNotNIL() bool
	// Empty returns whether the given account is empty. Empty
	// is defined according to EIP161 (balance = nonce = code = 0).
	IsEIP161Empty() bool
	SetCode([]byte)
	AddBalance(*big.Int)
	SubBalance(*big.Int)
	IncrementNonce()
	SetNonce(*big.Int)
	SetState(*big.Int, *big.Int)
	Suicide(*common.Address)
}

type StateDiffAccount

type StateDiffAccount struct {
	Balance interface{}                            `json:"balance"` // Can be either string "=" or mapping "*" => {"from": "hex", "to": "hex"}
	Code    interface{}                            `json:"code"`
	Nonce   interface{}                            `json:"nonce"`
	Storage map[common.Hash]map[string]interface{} `json:"storage"`
}

StateDiffAccount is the part of `trace_call` response that is under "stateDiff" tag

type StateDiffBalance

type StateDiffBalance struct {
	From *hexutil.Big `json:"from"`
	To   *hexutil.Big `json:"to"`
}

type StateDiffCode

type StateDiffCode struct {
	From hexutil.Bytes `json:"from"`
	To   hexutil.Bytes `json:"to"`
}

type StateDiffNonce

type StateDiffNonce struct {
	From hexutil.Uint64 `json:"from"`
	To   hexutil.Uint64 `json:"to"`
}

type StateDiffStorage

type StateDiffStorage struct {
	From common.Hash `json:"from"`
	To   common.Hash `json:"to"`
}

type Storage

type Storage map[common.Hash]common.Hash

Storage represents a contract's storage.

func (Storage) Copy

func (s Storage) Copy() Storage

Copy duplicates the current storage.

type StructLog

type StructLog struct {
	Pc            uint64                      `json:"pc"`
	Op            OpCode                      `json:"op"`
	Gas           uint64                      `json:"gas"`
	GasCost       uint64                      `json:"gasCost"`
	Memory        []byte                      `json:"memory"`
	MemorySize    uint64                      `json:"memSize"`
	Stack         []*uint256.Int              `json:"stack"`
	Storage       map[common.Hash]common.Hash `json:"-"`
	Depth         uint16                      `json:"depth"`
	RefundCounter uint64                      `json:"refund"`
	Err           error                       `json:"-"`
}

StructLog is emitted to the EVM each cycle and lists information about the current internal state prior to the execution of the statement.

func (*StructLog) ErrorString

func (s *StructLog) ErrorString() string

ErrorString formats the log's error as a string.

func (*StructLog) OpName

func (s *StructLog) OpName() string

OpName formats the operand name in a human-readable format.

type StructLogRes

type StructLogRes struct {
	Pc      uint64             `json:"pc"`
	Op      string             `json:"op"`
	Gas     uint64             `json:"gas"`
	GasCost uint64             `json:"gasCost"`
	Depth   uint16             `json:"depth"`
	Error   error              `json:"error,omitempty"`
	Stack   *[]string          `json:"stack,omitempty"`
	Memory  *[]string          `json:"memory,omitempty"`
	Storage *map[string]string `json:"storage,omitempty"`
}

StructLogRes stores a structured log emitted by the EVM while replaying a transaction in debug mode

func FormatLogs

func FormatLogs(logs []StructLog) []StructLogRes

FormatLogs formats EVM returned structured logs for json output

type StructLogger

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

StructLogger is an EVM state logger and implements Tracer.

StructLogger can capture state based on the given Log configuration and also keeps a track record of modified storage which is used in reporting snapshots of the contract their storage.

func NewStructLogger

func NewStructLogger(cfg *LogConfig) *StructLogger

NewStructLogger returns a new logger

func (*StructLogger) CaptureEnd

func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error

CaptureEnd is called after the call finishes to finalize the tracing.

func (*StructLogger) CaptureEnter

func (l *StructLogger) CaptureEnter(op OpCode, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error

func (*StructLogger) CaptureExit

func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, t time.Duration, err error) error

func (*StructLogger) CaptureStart

func (l *StructLogger) CaptureStart(env *EVM, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error

func (*StructLogger) CaptureState

func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth uint16, err error) error

CaptureState logs a new structured log message and pushes it out to the environment

CaptureState also tracks SSTORE ops to track dirty values.

func (*StructLogger) Error

func (l *StructLogger) Error() error

Error returns the VM error captured by the trace.

func (*StructLogger) Output

func (l *StructLogger) Output() []byte

Output returns the VM return value captured by the trace.

func (*StructLogger) StructLogs

func (l *StructLogger) StructLogs() []StructLog

StructLogs returns the captured log entries.

type SuicideTraceAction

type SuicideTraceAction struct {
	Address       common.Address `json:"address"`
	RefundAddress common.Address `json:"refundAddress"`
	Balance       hexutil.Big    `json:"balance"`
}

type TraceAction

type TraceAction struct {
	// Do not change the ordering of these fields -- allows for easier comparison with other clients
	Author         string         `json:"author,omitempty"`
	RewardType     string         `json:"rewardType,omitempty"`
	SelfDestructed string         `json:"address,omitempty"`
	Balance        string         `json:"balance,omitempty"`
	CallType       string         `json:"callType,omitempty"`
	From           common.Address `json:"from"`
	Gas            hexutil.Big    `json:"gas"`
	Init           hexutil.Bytes  `json:"init,omitempty"`
	Input          hexutil.Bytes  `json:"input,omitempty"`
	RefundAddress  string         `json:"refundAddress,omitempty"`
	To             string         `json:"to,omitempty"`
	Value          string         `json:"value,omitempty"`
}

TraceAction A parity formatted trace action

type TraceCallResult

type TraceCallResult struct {
	Output          hexutil.Bytes                        `json:"output"`
	StateDiff       map[common.Address]*StateDiffAccount `json:"stateDiff"`
	Trace           []*ParityTrace                       `json:"trace"`
	VmTrace         *VmTrace                             `json:"vmTrace"`
	TransactionHash *common.Hash                         `json:"transactionHash,omitempty"`
}

TraceCallResult is the response to `trace_call` method

type TraceResult

type TraceResult struct {
	// Do not change the ordering of these fields -- allows for easier comparison with other clients
	GasUsed *hexutil.Big  `json:"gasUsed"`
	Output  hexutil.Bytes `json:"output"`
}

TraceResult A parity formatted trace result

type Tracer

type Tracer interface {
	CaptureStart(env *EVM, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error
	CaptureEnter(op OpCode, from *common.Address, to *common.Address, precompile bool, create bool, input []byte, gas uint64, value *big.Int, code []byte) error
	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth uint16, err error) error
	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
	CaptureExit(output []byte, gasUsed uint64, t time.Duration, err error) error
}

Tracer is used to collect execution traces from an EVM transaction execution. CaptureState is called for each step of the VM with the current VM state. Note that reference types are actual VM data structures; make copies if you need to retain them beyond the current call.

type TracingConfig

type TracingConfig struct {
	VmTrace   bool
	Trace     bool
	StateDiff bool
}

type Transaction

type Transaction struct {
	From     common.Address  // Provides information for ORIGIN
	GasPrice *big.Int        // Provides information for GASPRICE
	To       *common.Address `rlp:"nil"`
	Nonce    *big.Int
	Value    *big.Int
	Gas      uint64
	Input    []byte
}

type VmTrace

type VmTrace struct {
	Code hexutil.Bytes `json:"code"`
	Ops  []*VmTraceOp  `json:"ops"`
}

VmTrace is the part of `trace_call` response that is under "vmTrace" tag

type VmTraceEx

type VmTraceEx struct {
	Mem   *VmTraceMem   `json:"mem"`
	Push  []string      `json:"push"`
	Store *VmTraceStore `json:"store"`
	Used  int           `json:"used"`
}

type VmTraceMem

type VmTraceMem struct {
	Data string `json:"data"`
	Off  int    `json:"off"`
}

type VmTraceOp

type VmTraceOp struct {
	Cost int        `json:"cost"`
	Ex   *VmTraceEx `json:"ex"`
	Pc   int        `json:"pc"`
	Sub  *VmTrace   `json:"sub"`
	Op   string     `json:"op,omitempty"`
	Idx  string     `json:"idx,omitempty"`
}

VmTraceOp is one element of the vmTrace ops trace

type VmTraceStore

type VmTraceStore struct {
	Key string `json:"key"`
	Val string `json:"val"`
}

Jump to

Keyboard shortcuts

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