vm

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2020 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ModuleName               = types.ModuleName
	StoreKey                 = types.StoreKey
	RouterKey                = types.RouterKey
	QuerierRoute             = types.QuerierRoute
	DefaultParamspace        = keeper.DefaultParamspace
	EventTypeContractCreated = types.EventTypeContractCreated
	AttributeKeyAddress      = types.AttributeKeyAddress
)
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 (
	GasLimitBoundDivisor uint64 = 1024    // The bound divisor of the gas limit, used in update calculations.
	MinGasLimit          uint64 = 5000    // Minimum the gas limit may ever be.
	GenesisGasLimit      uint64 = 4712388 // Gas limit of the Genesis block.

	MaximumExtraDataSize  uint64 = 32    // Maximum size extra data may be after Genesis.
	ExpByteGas            uint64 = 10    // Times ceil(log256(exponent)) for the EXP instruction.
	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.

	Sha3Gas     uint64 = 30 // Once per SHA3 operation.
	Sha3WordGas uint64 = 6  // Once per word of the SHA3 operation's data.

	SstoreSentryGas   uint64 = 2300  // Minimum gas required to be present for an SSTORE call, not consumed
	SstoreNoopGas     uint64 = 800   // Once per SSTORE operation if the value doesn't change.
	SstoreDirtyGas    uint64 = 800   // Once per SSTORE operation if a dirty value is changed.
	SstoreInitGas     uint64 = 20000 // Once per SSTORE operation from clean zero to non-zero
	SstoreInitRefund  uint64 = 19200 // Once per SSTORE operation for resetting to the original zero value
	SstoreCleanGas    uint64 = 5000  // Once per SSTORE operation from clean non-zero to something else
	SstoreCleanRefund uint64 = 4200  // Once per SSTORE operation for resetting to the original non-zero value
	SstoreClearRefund uint64 = 15000 // Once per SSTORE operation for clearing an originally existing storage slot

	JumpdestGas uint64 = 1 // Once per JUMPDEST operation.

	CreateDataGas         uint64 = 200   //
	CallCreateDepth       uint64 = 1024  // Maximum depth of call/create stack.
	ExpGas                uint64 = 10    // Once per EXP instruction
	LogGas                uint64 = 375   // Per LOG* operation.
	CopyGas               uint64 = 3     //
	StackLimit            uint64 = 1024  // 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
	SelfdestructRefundGas uint64 = 24000 // Refunded following a selfdestruct 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.

	// These have been changed during the course of the chain
	CallGas         uint64 = 700  // Static portion of gas for CALL-derivates after EIP 150 (Tangerine)
	BalanceGas      uint64 = 700  // The cost of a BALANCE operation after EIP 1884 (part of Istanbul)
	ExtcodeSizeGas  uint64 = 700  // Cost of EXTCODESIZE after EIP 150 (Tangerine)
	SloadGas        uint64 = 800  // Cost of SLOAD after EIP 1884 (part of Istanbul)
	ExtcodeHashGas  uint64 = 700  // Cost of EXTCODEHASH after EIP 1884 (part in Istanbul)
	SelfdestructGas uint64 = 5000 // Cost of SELFDESTRUCT post EIP 150 (Tangerine)

	// EXP has a dynamic portion depending on the size of the exponent
	ExpByte uint64 = 50 // was raised to 50 during Eip158 (Spurious Dragon)

	// Extcodecopy has a dynamic AND a static cost. This represents only the
	// static portion of the gas. It was changed during EIP 150 (Tangerine)
	ExtcodeCopyBase uint64 = 700

	// CreateBySelfdestructGas is used when the refunded account is one that does
	// not exist. This logic is similar to call.
	// Introduced in Tangerine Whistle (Eip 150)
	CreateBySelfdestructGas uint64 = 25000

	MaxCodeSize = 49152 // 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 = 150   // Gas needed for an elliptic curve addition
	Bn256ScalarMulGas       uint64 = 6000  // Gas needed for an elliptic curve scalar multiplication
	Bn256PairingBaseGas     uint64 = 45000 // Base price for an elliptic curve pairing check
	Bn256PairingPerPointGas uint64 = 34000 // Per-point price for an elliptic curve pairing check
)
View Source
const (
	DefaultBlockGasLimit = sdk.Gas(100000000)
)
View Source
const (
	GasReservedForOutOfVm = 10000
)

Variables

View Source
var (
	// functions aliases
	NewKeeper        = keeper.NewKeeper
	NewCommitStateDB = types.NewCommitStateDB
	NewMsgContract   = types.NewMsgContract
	NewParams        = types.NewParams
	DefaultParams    = types.DefaultParams

	CreateAddress  = common.CreateAddress
	CreateAddress2 = common.CreateAddress2
	GenPayload     = cli.GenPayload
	CodeFromFile   = cli.CodeFromFile

	ValidateGenesis = types.ValidateGenesis

	ErrOutOfGas                 = types.ErrOutOfGas
	ErrCodeStoreOutOfGas        = types.ErrCodeStoreOutOfGas
	ErrDepth                    = types.ErrDepth
	ErrTraceLimitReached        = types.ErrTraceLimitReached
	ErrInsufficientBalance      = types.ErrInsufficientBalance
	ErrContractAddressCollision = types.ErrContractAddressCollision
	ErrNoCompatibleInterpreter  = types.ErrNoCompatibleInterpreter
	ErrEmptyInputs              = types.ErrEmptyInputs
	ErrNoCodeExist              = types.ErrNoCodeExist
	ErrMaxCodeSizeExceeded      = types.ErrMaxCodeSizeExceeded
	ErrWriteProtection          = types.ErrWriteProtection
	ErrReturnDataOutOfBounds    = types.ErrReturnDataOutOfBounds
	ErrExecutionReverted        = types.ErrExecutionReverted
	ErrInvalidJump              = types.ErrInvalidJump
	ErrGasUintOverflow          = types.ErrGasUintOverflow
	ErrNoPayload                = types.ErrNoPayload
	ErrWrongCtx                 = types.ErrWrongCtx

	// variable aliases
	ModuleCdc = types.ModuleCdc
)
View Source
var PrecompiledContracts = map[string]PrecompiledContract{
	(sdk.BytesToAddress([]byte{1})).String(): &ecrecover{},
	(sdk.BytesToAddress([]byte{2})).String(): &sha256hash{},
	(sdk.BytesToAddress([]byte{3})).String(): &ripemd160hash{},
	(sdk.BytesToAddress([]byte{4})).String(): &dataCopy{},
	(sdk.BytesToAddress([]byte{5})).String(): &bigModExp{},
	(sdk.BytesToAddress([]byte{6})).String(): &bn256Add{},
	(sdk.BytesToAddress([]byte{7})).String(): &bn256ScalarMul{},
	(sdk.BytesToAddress([]byte{8})).String(): &bn256Pairing{},
	(sdk.BytesToAddress([]byte{9})).String(): &blake2F{},
}

PrecompiledContracts contains the default set of pre-compiled contracts used in the Istanbul release.

Functions

func DoStateTransition

func DoStateTransition(ctx sdk.Context, msg types.MsgContract, k Keeper, readonly bool) (*big.Int, *sdk.Result, error)

func EndBlocker

func EndBlocker(ctx sdk.Context, keeper keeper.Keeper) []abci.ValidatorUpdate

func NewHandler

func NewHandler(k Keeper) sdk.Handler

NewHandler returns a handler for "vm" type messages.

func NewQuerier

func NewQuerier(k keeper.Keeper) sdk.Querier

func RightPadBytes

func RightPadBytes(slice []byte, l int) []byte

RightPadBytes zero-pads slice to the right up to length l.

func RunPrecompiledContract

func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error)

RunPrecompiledContract runs and evaluates the output of a precompiled contract.

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 AccountKeeper

type AccountKeeper = types.AccountKeeper

type AccountRef

type AccountRef sdk.AccAddress

AccountRef implements ContractRef

func (AccountRef) Address

func (ar AccountRef) Address() sdk.AccAddress

Address casts AccountRef to a Address

type AppModule

type AppModule struct {
	AppModuleBasic
	// contains filtered or unexported fields
}

func NewAppModule

func NewAppModule(keeper Keeper) AppModule

func (AppModule) BeginBlock

func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock)

BeginBlock function for module at start of each block

func (AppModule) EndBlock

func (am AppModule) EndBlock(ctx sdk.Context, end abci.RequestEndBlock) []abci.ValidatorUpdate

EndBlock function for module at end of block

func (AppModule) ExportGenesis

func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage

ExportGenesis exports the genesis state to be used by daemon

func (AppModule) GenerateGenesisState

func (am AppModule) GenerateGenesisState(input *module.SimulationState)

GenerateGenesisState creates a randomized GenState of the vm module.

func (AppModule) InitGenesis

func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate

InitGenesis instantiates the genesis state

func (AppModule) NewHandler

func (am AppModule) NewHandler() sdk.Handler

func (AppModule) NewQuerierHandler

func (am AppModule) NewQuerierHandler() sdk.Querier

func (AppModule) ProposalContents

func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent

ProposalContents doesn't return any content functions for governance proposals.

func (AppModule) QuerierRoute

func (am AppModule) QuerierRoute() string

func (AppModule) RandomizedParams

func (am AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange

RandomizedParams creates randomized staking param changes for the simulator.

func (AppModule) RegisterInvariants

func (am AppModule) RegisterInvariants(sdk.InvariantRegistry)

func (AppModule) Route

func (am AppModule) Route() string

func (AppModule) WeightedOperations

func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation

WeightedOperations returns the all the staking module operations with their respective weights.

func (*AppModule) WithAccountKeeper

func (am *AppModule) WithAccountKeeper(ak AccountKeeper) *AppModule

type AppModuleBasic

type AppModuleBasic struct{}

func (AppModuleBasic) DefaultGenesis

func (a AppModuleBasic) DefaultGenesis() json.RawMessage

func (AppModuleBasic) GetQueryCmd

func (a AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command

GetQueryCmd returns the root query command for the vm module.

func (AppModuleBasic) GetTxCmd

func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command

func (AppModuleBasic) Name

func (a AppModuleBasic) Name() string

func (AppModuleBasic) RegisterCodec

func (a AppModuleBasic) RegisterCodec(cdc *codec.Codec)

func (AppModuleBasic) RegisterRESTRoutes

func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router)

func (AppModuleBasic) ValidateGenesis

func (a AppModuleBasic) ValidateGenesis(value json.RawMessage) error

type CanTransferFunc

type CanTransferFunc func(sdk.AccAddress, *big.Int) bool

CanTransferFunc is the signature of a transfer guard function

type ChainConfig

type ChainConfig struct {
	ChainID string `json:"chainId"` // chainId identifies the current chain and is used for replay protection
}

ChainConfig is the core config which determines the blockchain settings.

ChainConfig is stored in the database on a per block basis. This means that any network, identified by its genesis block, can have its own set of configuration options.

type CommitStateDB

type CommitStateDB = types.CommitStateDB

type Config

type Config struct {
	Debug                   bool   // Enables debugging
	Tracer                  Tracer // Opcode logger
	NoRecursion             bool   // Disables call, callcode, delegate call and create
	EnablePreimageRecording bool   // Enables recording of SHA3/keccak preimages

	JumpTable                 [256]operation // EVM instruction table, automatically populated if unset
	OpConstGasConfig          *[256]uint64
	ContractCreationGasConfig *types.VMContractCreationGasParams
	MaxCodeSize               uint64
	MaxCallCreateDepth        uint64

	EWASMInterpreter string // External EWASM interpreter options
	EVMInterpreter   string // External EVM interpreter options
}

type Context

type Context struct {
	// CanTransfer returns whether the account contains
	// sufficient tolen to transfer the value
	CanTransfer CanTransferFunc
	// Transfer transfers ether from one account to the other
	Transfer TransferFunc
	// GetHash returns the hash corresponding to n
	GetHash GetHashFunc

	// Msg information
	Origin   sdk.AccAddress
	GasPrice *big.Int

	// Block information
	CoinBase    sdk.AccAddress
	GasLimit    uint64
	BlockNumber *big.Int
	Time        *big.Int
}

Context provides the VM with auxiliary information. Once provided it shouldn't be modified

type Contract

type Contract struct {
	// CallerAddress is the result of the caller which initialised this
	// contract. However when the "call method" is delegated this value
	// needs to be initialised to that of the caller's caller.
	CallerAddress sdk.AccAddress

	Code     []byte
	CodeHash sdk.Hash
	CodeAddr *sdk.AccAddress
	Input    []byte

	Gas uint64
	// contains filtered or unexported fields
}

Contract implements ContractRef

func NewContract

func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uint64) *Contract

NewContract creates a new Contract object

func (*Contract) Address

func (c *Contract) Address() sdk.AccAddress

Address returns the contract address

func (*Contract) AsDelegate

func (c *Contract) AsDelegate() *Contract

AsDelegate sets the contract to be a delegate call and returns the current contract (for chaining calls)

func (*Contract) Caller

func (c *Contract) Caller() sdk.AccAddress

Caller returns the caller of the contract.

Caller will recursively call caller when the contract is a delegate call, including that of caller's caller.

func (*Contract) GetByte

func (c *Contract) GetByte(n uint64) byte

GetByte returns the n'th byte in the contract's byte array

func (*Contract) GetOp

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

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

func (*Contract) SetCallCode

func (c *Contract) SetCallCode(addr *sdk.AccAddress, hash sdk.Hash, code []byte)

SetCallCode sets the code of the contract and address of the backing data object

func (*Contract) SetCodeOptionalHash

func (c *Contract) SetCodeOptionalHash(addr *sdk.AccAddress, codeAndHash *codeAndHash)

SetCodeOptionalHash can be used to provide code, but it's optional to provide hash. In case hash is not provided, the jumpdest analysis will not be saved to the parent context

func (*Contract) UseGas

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

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

func (*Contract) Value

func (c *Contract) Value() *big.Int

Value returns the contract value (sent to it from it's caller)

type ContractRef

type ContractRef interface {
	Address() sdk.AccAddress
}

ContractRef is a interface to the contract's backing object

type EVM

type EVM struct {
	Context

	// StateDB gives access to the underlying state
	StateDB *CommitStateDB
	// contains filtered or unexported fields
}

func NewEVM

func NewEVM(ctx Context, statedb *CommitStateDB, vmConfig Config) *EVM

func (*EVM) Call

func (evm *EVM) Call(caller ContractRef, addr sdk.AccAddress, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

func (*EVM) CallCode

func (evm *EVM) CallCode(caller ContractRef, addr sdk.AccAddress, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

func (*EVM) Create

func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr sdk.AccAddress, leftOverGas uint64, err error)

Create creates a new contract using code as deployment code

func (*EVM) Create2

func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr sdk.AccAddress, leftOverGas uint64, err error)

Create2 creates a new contract using code as deployment code.

The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:] instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.

func (*EVM) DelegateCall

func (evm *EVM) DelegateCall(caller ContractRef, addr sdk.AccAddress, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

func (*EVM) Interpreter

func (evm *EVM) Interpreter() Interpreter

Interpreter returns the current interpreter

func (*EVM) StaticCall

func (evm *EVM) StaticCall(caller ContractRef, addr sdk.AccAddress, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

type EVMInterpreter

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

EVMInterpreter represents an EVM interpreter

func NewEVMInterpreter

func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter

CanRun tells if the contract, passed as an argument, can be run by the current interpreter.

func (*EVMInterpreter) CanRun

func (in *EVMInterpreter) CanRun(code []byte) bool

func (*EVMInterpreter) Run

func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error)

Run loops and evaluates the contract's code with the given input data and returns the return byte-slice and an error if one occurred.

It's important to note that any errors returned by the interpreter should be considered a revert-and-consume-all-gas operation except for errExecutionReverted which means revert-and-keep-gas-left.

func (*EVMInterpreter) SetReturnData

func (in *EVMInterpreter) SetReturnData(d []byte)

for test

type GenesisState

type GenesisState = types.GenesisState

type GetHashFunc

type GetHashFunc func() sdk.Hash

GetHashFunc returns the nth block hash in the blockchain and is used by the BLOCKHASH EVM op code. GetHashFunc func(sdk.Context) types.Hash

type Interpreter

type Interpreter interface {
	// Run loops and evaluates the contract's code with the given input data and returns
	// the return byte-slice and an error if one occurred.
	Run(contract *Contract, input []byte, static bool) ([]byte, error)
	// CanRun tells if the contract, passed as an argument, can be
	// run by the current interpreter. This is meant so that the
	// caller can do something like:
	//
	// “`golang
	// for _, interpreter := range interpreters {
	//   if interpreter.CanRun(contract.code) {
	//     interpreter.Run(contract.code, input)
	//   }
	// }
	// “`
	CanRun([]byte) bool
}

Interpreter is used to run Ethereum based contracts and will utilise the passed environment to query external sources for state information. The Interpreter will run the byte code VM based on the passed configuration.

type JumpTable

type JumpTable [256]operation

JumpTable contains the EVM opcodes supported at a given fork.

type Keeper

type Keeper = keeper.Keeper

type Log

type Log = types.Log

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 Memory

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

func NewMemory

func NewMemory() *Memory

func (*Memory) Data

func (m *Memory) Data() []byte

Data returns the backing slice

func (*Memory) Get

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

Get returns offset + size as new slice

func (*Memory) GetCopy

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

GetCopy

func (*Memory) GetPtr

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

GetPtr returns the offset +size

func (*Memory) Len

func (m *Memory) Len() int

Len returns the length of the backing slice

func (*Memory) Print

func (m *Memory) Print()

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)

func (*Memory) Set32

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

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

type MsgContract

type MsgContract = types.MsgContract

type OpCode

type OpCode byte

OpCode is an VM opcode

const (
	STOP OpCode = iota
	ADD
	MUL
	SUB
	DIV
	SDIV
	MOD
	SMOD
	ADDMOD
	MULMOD
	EXP
	SIGNEXTEND
)

0x0 range - arithmetic ops.

const (
	LT OpCode = iota + 0x10
	GT
	SLT
	SGT
	EQ
	ISZERO
	AND
	OR
	XOR
	NOT
	BYTE
	SHL
	SHR
	SAR

	SHA3 = 0x20
)

0x10 range - comparison ops.

const (
	ADDRESS OpCode = 0x30 + iota
	BALANCE
	ORIGIN
	CALLER
	CALLVALUE
	CALLDATALOAD
	CALLDATASIZE
	CALLDATACOPY
	CODESIZE
	CODECOPY
	GASPRICE
	EXTCODESIZE
	EXTCODECOPY
	RETURNDATASIZE
	RETURNDATACOPY
	EXTCODEHASH
)

0x30 range - closure state.

const (
	BLOCKHASH OpCode = 0x40 + iota
	COINBASE
	TIMESTAMP
	NUMBER
	DIFFICULTY
	GASLIMIT
	CHAINID     = 0x46
	SELFBALANCE = 0x47
)

0x40 range - block operations.

const (
	POP OpCode = 0x50 + iota
	MLOAD
	MSTORE
	MSTORE8
	SLOAD
	SSTORE
	JUMP
	JUMPI
	PC
	MSIZE
	GAS
	JUMPDEST
)

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
	DUP1
	DUP2
	DUP3
	DUP4
	DUP5
	DUP6
	DUP7
	DUP8
	DUP9
	DUP10
	DUP11
	DUP12
	DUP13
	DUP14
	DUP15
	DUP16
	SWAP1
	SWAP2
	SWAP3
	SWAP4
	SWAP5
	SWAP6
	SWAP7
	SWAP8
	SWAP9
	SWAP10
	SWAP11
	SWAP12
	SWAP13
	SWAP14
	SWAP15
	SWAP16
)

0x60 range.

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

0xa0 range - logging ops.

const (
	PUSH OpCode = 0xb0 + iota
	DUP
	SWAP
)

unofficial opcodes used for parsing.

const (
	CREATE OpCode = 0xf0 + iota
	CALL
	CALLCODE
	RETURN
	DELEGATECALL
	CREATE2
	STATICCALL = 0xfa

	REVERT       = 0xfd
	SELFDESTRUCT = 0xff
)

0xf0 range - closures.

func StringToOp

func StringToOp(str string) OpCode

StringToOp finds the opcode whose name is stored in `str`.

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 Params

type Params = types.Params

type PrecompiledContract

type PrecompiledContract interface {
	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
}

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 Stack

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

func (*Stack) Back

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

returns the n'th item in stack

func (*Stack) Data

func (st *Stack) Data() []*big.Int

func (*Stack) Print

func (st *Stack) Print()

type StateTransition

type StateTransition struct {
	Sender    sdk.AccAddress
	Recipient sdk.AccAddress
	Amount    sdk.Int
	Payload   []byte
	StateDB   *types.CommitStateDB
}

StateTransition defines data to transitionDB in vm

func (StateTransition) CanTransfer

func (st StateTransition) CanTransfer(acc sdk.AccAddress, amount *big.Int) bool

func (StateTransition) GetHashFn

func (st StateTransition) GetHashFn(header abci.Header) func() sdk.Hash

func (StateTransition) Transfer

func (st StateTransition) Transfer(from, to sdk.AccAddress, amount *big.Int)

func (StateTransition) TransitionCSDB

func (st StateTransition) TransitionCSDB(ctx sdk.Context, k Keeper) (*big.Int, *sdk.Result, error)

type Storage

type Storage map[sdk.Hash]sdk.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    int                   `json:"memSize"`
	Stack         []*big.Int            `json:"stack"`
	Storage       map[sdk.Hash]sdk.Hash `json:"-"`
	Depth         uint64                `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 StructLogger

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

StructLogger is an VM 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) CaptureFault

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

CaptureFault implements the Tracer interface to trace an execution fault while running an opcode.

func (*StructLogger) CaptureStart

func (l *StructLogger) CaptureStart(from sdk.AccAddress, to sdk.AccAddress, create bool, input []byte, gas uint64, value *big.Int) error

CaptureStart implements the Tracer interface to initialize the tracing operation.

func (*StructLogger) CaptureState

func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth uint64, 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 Tracer

type Tracer interface {
	CaptureStart(from sdk.AccAddress, to sdk.AccAddress, call bool, input []byte, gas uint64, value *big.Int) error
	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth uint64, err error) error
	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth uint64, err error) error
	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
}

Tracer is used to collect execution traces from an VM 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 TransferFunc

type TransferFunc func(sdk.AccAddress, sdk.AccAddress, *big.Int)

TransferFunc is the signature of a transfer function

Directories

Path Synopsis
client
cli

Jump to

Keyboard shortcuts

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