vm

package
v0.0.0-...-de85661 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2022 License: Unlicense Imports: 22 Imported by: 0

Documentation

Index

Constants

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 (
	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                 = errors.New("out of gas")
	ErrCodeStoreOutOfGas        = errors.New("contract creation code storage out of gas")
	ErrDepth                    = errors.New("max call depth exceeded")
	ErrInsufficientBalance      = errors.New("insufficient balance for transfer")
	ErrContractAddressCollision = errors.New("contract address collision")
	ErrExecutionReverted        = errors.New("execution reverted")
	ErrMaxCodeSizeExceeded      = errors.New("max code size exceeded")
	ErrInvalidJump              = errors.New("invalid jump destination")
	ErrWriteProtection          = errors.New("write protection")
	ErrReturnDataOutOfBounds    = errors.New("return data out of bounds")
	ErrGasUintOverflow          = errors.New("gas uint64 overflow")
	ErrInvalidCode              = errors.New("invalid code: must not begin with 0xef")
	ErrNonceUintOverflow        = errors.New("nonce uint64 overflow")
)

List evm execution errors

View Source
var (
	PrecompiledAddressesBerlin    []entity.Address
	PrecompiledAddressesIstanbul  []entity.Address
	PrecompiledAddressesByzantium []entity.Address
	PrecompiledAddressesHomestead []entity.Address
)
View Source
var PrecompiledContractsHomestead = map[entity.Address]PrecompiledContract{
	entity.BytesToAddress([]byte{1}): &ecrecover{},
	entity.BytesToAddress([]byte{2}): &sha256hash{},
	entity.BytesToAddress([]byte{3}): &ripemd160hash{},
	entity.BytesToAddress([]byte{4}): &dataCopy{},
}

Functions

func ActivateableEips

func ActivateableEips() []string

func ActivePrecompiles

func ActivePrecompiles(rules entity.Rules) []entity.Address

ActivePrecompiles returns the precompiles enabled with the current configuration.

func CanTransfer

func CanTransfer(db *operationdb.OperationDB, addr entity.Address, amount *big.Int) bool

func EnableEIP

func EnableEIP(eipNum int, jt *JumpTable) error

EnableEIP enables the given EIP on the config. This operation writes in-place, and callers need to ensure that the globally defined jump tables are not polluted.

func GetHashFn

func GetHashFn(ref *block2.Header, chain ChainContext) func(n uint64) entity.Hash

func RunPrecompiledContract

func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error)

RunPrecompiledContract运行并评估预编译协定的输出。 它回来了 -返回的字节, -剩余气体, -发生的任何错误

func Transfer

func Transfer(db *operationdb.OperationDB, sender, recipient entity.Address, amount *big.Int)

Transfer使用给定的Db从发送方减去金额,然后将金额添加到接收方

func ValidEip

func ValidEip(eipNum int) bool

Types

type AccountRef

type AccountRef entity.Address

func (AccountRef) Address

func (ar AccountRef) Address() entity.Address

type BlockContext

type BlockContext struct {
	//判断是否有足够的gas转账
	CanTransfer CanTransferFunc
	//转账
	Transfer TransferFunc
	// 获取hash
	GetHash GetHashFunc

	// 区块信息
	Coinbase    entity.Address
	GasLimit    uint64
	BlockNumber *big.Int
	Time        *big.Int
	Difficulty  *big.Int
	BaseFee     *big.Int
	Random      *entity.Hash
}

func NewOVMBlockContext

func NewOVMBlockContext(header *block2.Header, chain ChainContext, author *entity.Address) BlockContext

type CanTransferFunc

type CanTransferFunc func(*operationdb.OperationDB, entity.Address, *big.Int) bool

是否有足够的余额

type ChainContext

type ChainContext interface {
	// 共识引擎
	Engine() consensus.Engine

	// 返回其对应hash
	GetHeader(entity.Hash, uint64) *block2.Header
}

type Config

type Config struct {
	Debug bool // 启用调试
	//Tracer                  EVMLogger // 操作码日志
	NoBaseFee               bool // 强制将费用设置为0
	EnablePreimageRecording bool // 是否运行录制sha3前录像

	JumpTable *JumpTable // 虚拟机指令表,未设置自动填充

	ExtraEips []int // 其他eip
}

type Contract

type Contract struct {
	// CallerAddress是初始化此合同的呼叫者的结果
	CallerAddress entity.Address

	Code     []byte
	CodeHash entity.Hash
	CodeAddr *entity.Address
	Input    []byte

	Gas uint64
	// contains filtered or unexported fields
}

合同表示状态数据库中的以太坊合同。它包含合同代码,调用参数。合同执行ContractRef

func NewContract

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

返回ovm新合同环境

func (*Contract) Address

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

func (*Contract) AsDelegate

func (c *Contract) AsDelegate() *Contract

AsDelegate将协定设置为委托调用并返回当前协定(用于链接调用)

func (*Contract) Caller

func (c *Contract) Caller() entity.Address

调用者返回合同的调用者。当契约是委托调用时,调用方将递归调用调用方,包括调用方的调用方的委托调用。

func (*Contract) GetOp

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

GetOp返回协定字节数组中的第n个元素

func (*Contract) SetCallCode

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

func (*Contract) SetCodeOptionalHash

func (c *Contract) SetCodeOptionalHash(addr *entity.Address, codeAndHash *codeAndHash)

SetCodeOptionalHash可以用于提供代码,但提供哈希是可选的。 如果未提供哈希,jumpdest分析将不会保存到父上下文中

func (*Contract) UseGas

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

type ContractRef

type ContractRef interface {
	Address() entity.Address
}

type ErrInvalidOpCode

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

ErrInvalidOpCode wraps an evm error when an invalid opcode is encountered.

func (*ErrInvalidOpCode) Error

func (e *ErrInvalidOpCode) Error() string

type ErrStackOverflow

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

ErrStackOverflow wraps an evm error when the items on the stack exceeds the maximum allowance.

func (*ErrStackOverflow) Error

func (e *ErrStackOverflow) Error() string

type ErrStackUnderflow

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

ErrStackUnderflow wraps an evm error when the items on the stack less than the minimal requirement.

func (*ErrStackUnderflow) Error

func (e *ErrStackUnderflow) Error() string

type GetHashFunc

type GetHashFunc func(uint64) entity.Hash

返回第几块的hash

type JumpTable

type JumpTable [256]*operation

包含虚拟机操作码

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

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

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

func (m *Memory) Len() int

Len returns the length of the backing slice

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 OVM

type OVM struct {
	// 区块配置信息
	Context BlockContext
	TxContext
	// 操作数据库访问配置
	Operationdb *operationdb.OperationDB

	// 初始化虚拟机配置选项
	Config Config
	// contains filtered or unexported fields
}

func NewOVM

func NewOVM(blockCtx BlockContext, txCtx TxContext, operation *operationdb.OperationDB, chainConfig *entity.ChainConfig, config Config) *OVM

func (*OVM) Call

func (ovm *OVM) Call(caller ContractRef, addr entity.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

func (*OVM) CallCode

func (ovm *OVM) CallCode(caller ContractRef, addr entity.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

CallCode使用给定的输入作为参数来执行与addr关联的契约。它还处理所需的任何必要的价值转移,并采取必要步骤创建帐户,并在执行错误或价值转移失败时反转状态。 CallCode与Call的不同之处在于,它以调用方作为上下文来执行给定的地址代码。

func (*OVM) Cancel

func (ovm *OVM) Cancel()

取消取消任何正在运行的EVM操作。这可以同时调用,多次调用是安全的。

func (*OVM) Cancelled

func (ovm *OVM) Cancelled() bool

如果调用了Cancel,则Cancelled返回true

func (*OVM) Create

func (ovm *OVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr entity.Address, leftOverGas uint64, err error)

Create使用代码作为部署代码创建新合同。

func (*OVM) Create2

func (ovm *OVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr entity.Address, leftOverGas uint64, err error)

Create2使用代码作为部署代码创建一个新契约。 Create2与Create的不同之处在于Create2使用keccak256(0xff++msg.sender++salt++keccak256(init_代码))[12:],而不是通常的sender和nonce散列作为合同初始化的地址。

func (*OVM) DelegateCall

func (ovm *OVM) DelegateCall(caller ContractRef, addr entity.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

DelegateCall使用给定的输入作为参数来执行与addr关联的约定。它在执行错误时反转状态。 DelegateCall与CallCode的不同之处在于,它以调用者为上下文执行给定的地址代码,并且调用者被设置为调用者的调用者。

func (*OVM) Reset

func (ovm *OVM) Reset(txCtx TxContext, operationdb *operationdb.OperationDB)

重置使用新的事务上下文重置EVM。重置这不是线程安全的,只能非常谨慎地执行。

func (*OVM) StaticCall

func (ovm *OVM) StaticCall(caller ContractRef, addr entity.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

StaticCall使用给定的输入作为参数来执行与addr关联的契约,同时不允许在调用期间对状态进行任何修改。 尝试执行此类修改的操作码将导致异常,而不是执行修改。

type OVMInterpreter

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

OVM解释器

func NewOVMInterpreter

func NewOVMInterpreter(ovm *OVM, cfg Config) *OVMInterpreter

func (*OVMInterpreter) Run

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

type OVMLogger

type OVMLogger interface {
	// Transaction level
	CaptureTxStart(gasLimit uint64)
	CaptureTxEnd(restGas uint64)
	// Top call frame
	CaptureStart(env *OVM, from entity.Address, to entity.Address, create bool, input []byte, gas uint64, value *big.Int)
	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error)
	// Rest of call frames
	CaptureEnter(typ OpCode, from entity.Address, to entity.Address, input []byte, gas uint64, value *big.Int)
	CaptureExit(output []byte, gasUsed uint64, err error)
	// Opcode level
	CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error)
	CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error)
}

OVMLoger用于从OVM事务执行中收集执行跟踪。 对于具有当前VM状态的VM的每个步骤,都会调用CaptureState。 注意,引用类型是实际的VM数据结构;如果需要在当前通话结束后保留,请复制。

type OpCode

type OpCode byte

虚拟机操作码

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
	RANDOM      OpCode = 0x44 // Same as DIFFICULTY
	GASLIMIT    OpCode = 0x45
	CHAINID     OpCode = 0x46
	SELFBALANCE OpCode = 0x47
	BASEFEE     OpCode = 0x48
)

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

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

0xa0 range - logging ops.

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

func (op OpCode) String() string

type Operationdb

type Operationdb interface {
	CreateAccount(entity.Address)

	SubBalance(entity.Address, *big.Int)
	AddBalance(entity.Address, *big.Int)
	GetBalance(entity.Address) *big.Int

	GetNonce(entity.Address) uint64
	SetNonce(entity.Address, uint64)

	GetCodeHash(entity.Address) entity.Hash
	GetCode(entity.Address) []byte
	SetCode(entity.Address, []byte)
	GetCodeSize(entity.Address) int

	AddRefund(uint64)
	SubRefund(uint64)
	GetRefund() uint64

	GetCommittedState(entity.Address, entity.Hash) entity.Hash
	GetState(entity.Address, entity.Hash) entity.Hash
	SetState(entity.Address, entity.Hash, entity.Hash)

	Suicide(entity.Address) bool
	HasSuicided(entity.Address) bool

	// Exist报告给定帐户是否存在于状态。值得注意的是,对于自杀账户,这也应该是真的。
	Exist(entity.Address) bool
	// Empty返回给定帐户是否为空。根据EIP161定义为空(余额=nonce=代码=0)。
	Empty(entity.Address) bool

	//PrepareAccessList(发送方区块链地址,目的地*区块链地址,预编译[]区块链地址,TXAccess数据库访问列表)
	AddressInAccessList(addr entity.Address) bool
	SlotInAccessList(addr entity.Address, slot entity.Hash) (addressOk bool, slotOk bool)
	// AddAddressToAccessList将给定地址添加到访问列表中。即使功能/分叉尚未激活,也可以安全执行此操作
	AddAddressToAccessList(addr entity.Address)
	// AddSlotToAccessList将给定的(地址、插槽)添加到访问列表中。即使功能/分叉尚未激活,也可以安全执行此操作
	AddSlotToAccessList(addr entity.Address, slot entity.Hash)

	RevertToSnapshot(int)
	Snapshot() int

	AddLog(*block2.Log)
	AddPreimage(entity.Hash, []byte)

	ForEachStorage(entity.Address, func(entity.Hash, entity.Hash) bool) error
}

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
}

type ScopeContext

type ScopeContext struct {
	Memory   *Memory
	Stack    *Stack
	Contract *Contract
}

type Stack

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

堆栈是用于基本堆栈操作的对象。 弹出到堆栈中的项目预计将被更改和修改。堆栈不负责添加新初始化的对象。

func (*Stack) Back

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

Back returns the n'th item in stack

func (*Stack) Data

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

数据返回基础uint256。Int数组。

type TransferFunc

type TransferFunc func(*operationdb.OperationDB, entity.Address, entity.Address, *big.Int)

交易执行函数

type TxContext

type TxContext struct {
	Origin   entity.Address
	GasPrice *big.Int
}

事务信息

func NewEVMTxContext

func NewEVMTxContext(msg block2.Message) TxContext

NewEVMTxContext为单个事务创建新的事务配置。

Jump to

Keyboard shortcuts

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