vm

package
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2020 License: Apache-2.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ModuleName        = types.ModuleName
	StoreKey          = types.StoreKey
	CodeKey           = types.CodeKey
	RouterKey         = types.RouterKey
	QuerierRoute      = types.QuerierRoute
	DefaultCodespace  = types.DefaultCodespace
	DefaultParamspace = keeper.DefaultParamspace
)
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 = 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

	Bn256AddGasByzantium             uint64 = 500    // Byzantium gas needed for an elliptic curve addition
	Bn256AddGasIstanbul              uint64 = 150    // Gas needed for an elliptic curve addition
	Bn256ScalarMulGasByzantium       uint64 = 40000  // Byzantium gas needed for an elliptic curve scalar multiplication
	Bn256ScalarMulGasIstanbul        uint64 = 6000   // Gas needed for an elliptic curve scalar multiplication
	Bn256PairingBaseGasByzantium     uint64 = 100000 // Byzantium base price for an elliptic curve pairing check
	Bn256PairingBaseGasIstanbul      uint64 = 45000  // Base price for an elliptic curve pairing check
	Bn256PairingPerPointGasByzantium uint64 = 80000  // Byzantium per-point price for an elliptic curve pairing check
	Bn256PairingPerPointGasIstanbul  uint64 = 34000  // Per-point price for an elliptic curve pairing check
)
View Source
const (
	DefaultGasLimit = 100000000
)

Variables

View Source
var (
	NewKeeper        = keeper.NewKeeper
	NewCommitStateDB = types.NewCommitStateDB

	CreateAddress  = common.CreateAddress
	CreateAddress2 = common.CreateAddress2

	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
)
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{},
}

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, gasLimit uint64, readonly bool) (*big.Int, sdk.Result)

func EndBlocker

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

func GetTestAccount

func GetTestAccount() auth.BaseAccount

func KeyTestPubAddr

func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress)

func ModuleAccountAddrs

func ModuleAccountAddrs() map[string]bool

func NewHandler

func NewHandler(k Keeper) sdk.Handler

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 sdk.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 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 (a AppModule) BeginBlock(sdk.Context, abci.RequestBeginBlock)

func (AppModule) EndBlock

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

func (AppModule) ExportGenesis

func (a AppModule) ExportGenesis(sdk.Context) json.RawMessage

func (AppModule) InitGenesis

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

func (AppModule) NewHandler

func (a AppModule) NewHandler() sdk.Handler

func (AppModule) NewQuerierHandler

func (a AppModule) NewQuerierHandler() sdk.Querier

func (AppModule) QuerierRoute

func (a AppModule) QuerierRoute() string

func (AppModule) RegisterInvariants

func (a AppModule) RegisterInvariants(sdk.InvariantRegistry)

func (AppModule) Route

func (a AppModule) Route() string

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

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
	CommonGasConfig  *types.VMCommonGasParams

	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

func (*Contract) Address

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

Address returns the contract address

func (*Contract) AsDelegate

func (c *Contract) AsDelegate() *Contract

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 sdk.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 sdk.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 sdk.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 sdk.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 sdk.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 sdk.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 sdk.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.

type GenesisState

type GenesisState = types.GenesisState

type GetHashFunc

type GetHashFunc func(uint64) 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, sdk.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 PrecompiledContract

type PrecompiledContract interface {
	RequiredGas(input []byte) uint64      // RequiredPrice calculates the contract gas use
	Run(input []byte) ([]byte, sdk.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
	GasLimit  uint64
	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(n uint64) 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, constGasConfig *[256]uint64, vmCommonGasConfig *types.VMCommonGasParams) (*big.Int, sdk.Result)

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         int                   `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 int, 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 int, 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 int, err error) error
	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, 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