wavm

package
v0.6.2-alpha.3 Latest Latest
Warning

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

Go to latest
Published: May 24, 2019 License: GPL-3.0 Imports: 34 Imported by: 0

Documentation

Overview

Package compile is used internally by wagon to convert standard structured WebAssembly bytecode into an unstructured form suitable for execution by it's VM. The conversion process consists of translating block instruction sequences and branch operators (br, br_if, br_table) to absolute jumps to PC values. For instance, an instruction sequence like:

loop
  i32.const 1
  get_local 0
  i32.add
  set_local 0
  get_local 1
  i32.const 1
  i32.add
  tee_local 1
  get_local 2
  i32.eq
  br_if 0
end

Is "compiled" to:

i32.const 1
i32.add
set_local 0
get_local 1
i32.const 1
i32.add
tee_local 1
get_local 2
i32.eq
jmpnz <addr> <preserve> <discard>

Where jmpnz is a jump-if-not-zero operator that takes certain arguments plus the jump address as immediates. This is in contrast with original WebAssembly bytecode, where the target of branch operators are relative block depths instead.

Index

Constants

View Source
const (
	OpNameGetBalanceFromAddress = "GetBalanceFromAddress"
	OpNameGetBlockNumber        = "GetBlockNumber"
	OpNameGetGas                = "GetGas"
	OpNameGetBlockHash          = "GetBlockHash"
	OpNameGetBlockProduser      = "GetBlockProduser"
	OpNameGetTimestamp          = "GetTimestamp"
	OpNameGetOrigin             = "GetOrigin"
	OpNameGetSender             = "GetSender"
	OpNameGetGasLimit           = "GetGasLimit"
	OpNameGetValue              = "GetValue"
	OpNameSHA3                  = "SHA3"
	OpNameGetContractAddress    = "GetContractAddress"
	OpNameAssert                = "Assert"

	OpNameEvent = "Event"

	OpNamePrintAddress  = "PrintAddress"
	OpNamePrintStr      = "PrintStr"
	OpNamePrintQStr     = "PrintQStr"
	OpNamePrintUint64T  = "PrintUint64T"
	OpNamePrintUint32T  = "PrintUint32T"
	OpNamePrintInt64T   = "PrintInt64T"
	OpNamePrintInt32T   = "PrintInt32T"
	OpNamePrintUint256T = "PrintUint256T"

	OpNameFromI64 = "FromI64"
	OpNameFromU64 = "FromU64"
	OpNameToI64   = "ToI64"
	OpNameToU64   = "ToU64"
	OpNameConcat  = "Concat"
	OpNameEqual   = "Equal"

	OpNameSendFromContract     = "SendFromContract"
	OpNameTransferFromContract = "TransferFromContract"

	OpNameContractCall = "ContractCall"

	//将字符串转化为地址
	OpNameAddressFrom     = "AddressFrom"
	OpNameAddressToString = "AddressToString"
	OpNameU256From        = "U256From"
	OpNameU256ToString    = "U256ToString"

	OpNameAddKeyInfo          = "AddKeyInfo"
	OpNameWriteWithPointer    = "WriteWithPointer"
	OpNameReadWithPointer     = "ReadWithPointer"
	OpNameInitializeVariables = "InitializeVariables"

	//uint256
	OpNameU256FromU64 = "U256FromU64"
	OpNameU256FromI64 = "U256FromI64"
	OpNameU256Add     = "U256_Add"
	OpNameU256Sub     = "U256_Sub"
	OpNameU256Mul     = "U256_Mul"
	OpNameU256Div     = "U256_Div"
	OpNameU256Mod     = "U256_Mod"
	OpNameU256Pow     = "U256_Pow"
	OpNameU256Cmp     = "U256_Cmp"

	//math
	OpNamePow = "Pow"

	//add gas
	OpNameAddGas = "AddGas"

	OpNameRevert = "Revert"

	//qlang
	OpNameSender = "Sender"
	OpNameLoad   = "Load"
	OpNameStore  = "Store"
)
View Source
const AddressLength = 20
View Source
const FallBackFunctionName = "Fallback"
View Source
const FallBackPayableFunctionName = "$Fallback"

Variables

View Source
var (
	// OpJmp unconditionally jumps to the provided address.
	OpJmp byte = 0x0c
	// OpJmpZ jumps to the given address if the value at the top of the stack is zero.
	OpJmpZ byte = 0x03
	// OpJmpNz jumps to the given address if the value at the top of the
	// stack is not zero. It also discards elements and optionally preserves
	// the topmost value on the stack
	OpJmpNz byte = 0x0d
	// OpDiscard discards a given number of elements from the execution stack.
	OpDiscard byte = 0x0b
	// OpDiscardPreserveTop discards a given number of elements from the
	// execution stack, while preserving the value on the top of the stack.
	OpDiscardPreserveTop byte = 0x05
)
View Source
var (
	OpReturn  byte = 0x0f
	OpBrTable byte = 0x0e
)

Functions

func Compile

func Compile(disassembly []disasm.Instr, module *wasm.Module, mutable Mutable) ([]byte, []*vnt.BranchTable)

Compile rewrites WebAssembly bytecode from its disassembly. TODO(vibhavp): Add options for optimizing code. Operators like i32.reinterpret/f32 are no-ops, and can be safely removed.

func CompileModule

func CompileModule(module *wasm.Module, chainctx ChainContext, mutable Mutable) ([]vnt.Compiled, error)

func GetAbi

func GetAbi(abibyte []byte) (abi.ABI, error)

func WriteTrace

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

WriteTrace writes a formatted trace to the given writer

Types

type ChainContext

type ChainContext struct {
	// CanTransfer returns whether the account contains
	// sufficient ether to transfer the value
	CanTransfer func(inter.StateDB, common.Address, *big.Int) bool
	// Transfer transfers ether from one account to the other
	Transfer func(inter.StateDB, common.Address, common.Address, *big.Int)
	// GetHash returns the hash corresponding to n
	GetHash func(uint64) common.Hash
	// Message information
	Origin   common.Address // Provides information for ORIGIN
	GasPrice *big.Int       // Provides information for GASPRICE

	// Block information
	Coinbase       common.Address // Provides information for COINBASE
	GasLimit       uint64         // Provides information for GASLIMIT
	BlockNumber    *big.Int       // Provides information for NUMBER
	Time           *big.Int       // Provides information for TIME
	Difficulty     *big.Int       // Provides information for DIFFICULTY
	StateDB        *state.StateDB
	Contract       *contract.WASMContract
	Code           []byte  //Wasm contract code
	Abi            abi.ABI //Wasm contract abi
	Wavm           *WAVM
	IsCreated      bool
	StorageMapping map[uint64]storage.StorageMapping
	GasRule        gas.Gas
	GasCounter     gas.GasCounter
	GasTable       params.GasTable
}

type Code

type Code struct {
	Body     disasm.Instr
	Children []*Code
}

func (Code) Recursive

func (c Code) Recursive() []disasm.Instr

type CodeBlock

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

type Config

type Config struct {
	// Debug enabled debugging Interpreter options
	Debug bool
	// Tracer is the op code logger
	Tracer                   vm.Tracer
	NoRecursion              bool
	MaxMemoryPages           int
	MaxTableSize             int
	MaxValueSlots            int
	MaxCallStackDepth        int
	DefaultMemoryPages       int
	DefaultTableSize         int
	GasLimit                 uint64
	DisableFloatingPoint     bool
	ReturnOnGasLimitExceeded bool
}

Config are the configuration options for the Interpreter

type DebugLog

type DebugLog struct {
	PrintMsg string `json:"printMsg"`
}

type EnvFunctions

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

func (*EnvFunctions) AddGas

func (ef *EnvFunctions) AddGas(proc *exec.WavmProcess, cost uint64)

func (*EnvFunctions) AddKeyInfo

func (ef *EnvFunctions) AddKeyInfo(proc *exec.WavmProcess, valAddr, valType, keyAddr, keyType, isArrayIndex uint64)

func (*EnvFunctions) AddressFrom

func (ef *EnvFunctions) AddressFrom(proc *exec.WavmProcess, idx uint64) uint64

func (*EnvFunctions) AddressToString

func (ef *EnvFunctions) AddressToString(proc *exec.WavmProcess, idx uint64) uint64

func (*EnvFunctions) Assert

func (ef *EnvFunctions) Assert(proc *exec.WavmProcess, condition uint64, msgIdx uint64)

func (*EnvFunctions) Concat

func (ef *EnvFunctions) Concat(proc *exec.WavmProcess, str1Idx uint64, str2Idx uint64) uint64

func (*EnvFunctions) Equal

func (ef *EnvFunctions) Equal(proc *exec.WavmProcess, str1Idx uint64, str2Idx uint64) uint64

func (*EnvFunctions) GetBalanceFromAddress

func (ef *EnvFunctions) GetBalanceFromAddress(proc *exec.WavmProcess, locIndex uint64) uint64

GetBalanceFromAddress get balance from address

func (*EnvFunctions) GetBlockHash

func (ef *EnvFunctions) GetBlockHash(proc *exec.WavmProcess, blockNum uint64) uint64

GetBlockHash get the block hash

func (*EnvFunctions) GetBlockNumber

func (ef *EnvFunctions) GetBlockNumber(proc *exec.WavmProcess) uint64

GetBlockNumber get the block number

func (*EnvFunctions) GetBlockProduser

func (ef *EnvFunctions) GetBlockProduser(proc *exec.WavmProcess) uint64

GetBlockProduser get the block produser address

func (*EnvFunctions) GetContractAddress

func (ef *EnvFunctions) GetContractAddress(proc *exec.WavmProcess) uint64

GetContractAddress get contract address

func (*EnvFunctions) GetFuncTable

func (ef *EnvFunctions) GetFuncTable() map[string]wasm.Function

GetFuncTable get the env function table

func (*EnvFunctions) GetGas

func (ef *EnvFunctions) GetGas(proc *exec.WavmProcess) uint64

GetGas get the rest gas

func (*EnvFunctions) GetGasLimit

func (ef *EnvFunctions) GetGasLimit(proc *exec.WavmProcess) uint64

GetGasLimit get the block gaslimit

func (*EnvFunctions) GetOrigin

func (ef *EnvFunctions) GetOrigin(proc *exec.WavmProcess) uint64

GetOrigin get tx origin

func (*EnvFunctions) GetSender

func (ef *EnvFunctions) GetSender(proc *exec.WavmProcess) uint64

GetSender get tx sender

func (*EnvFunctions) GetTimestamp

func (ef *EnvFunctions) GetTimestamp(proc *exec.WavmProcess) uint64

GetTimestamp get the block timestamp

func (*EnvFunctions) GetValue

func (ef *EnvFunctions) GetValue(proc *exec.WavmProcess) uint64

GetValue get tranfer vnt amount of a tx

func (*EnvFunctions) InitFuncTable

func (ef *EnvFunctions) InitFuncTable(context *ChainContext)

InitFuncTable init event and contract_call function

func (*EnvFunctions) InitializeVariables

func (ef *EnvFunctions) InitializeVariables(proc *exec.WavmProcess)

func (*EnvFunctions) Load

func (ef *EnvFunctions) Load(proc *exec.WavmProcess, keyptr uint64, dataptr uint64) uint64

Load for qlang

func (*EnvFunctions) Pow

func (ef *EnvFunctions) Pow(proc *exec.WavmProcess, base, exponent uint64) uint64

func (*EnvFunctions) PrintAddress

func (ef *EnvFunctions) PrintAddress(proc *exec.WavmProcess, remarkIdx uint64, strIdx uint64)

Print an Address

func (*EnvFunctions) PrintInt32T

func (ef *EnvFunctions) PrintInt32T(proc *exec.WavmProcess, remarkIdx uint64, intValue uint64)

PrintInt32T Print a int32

func (*EnvFunctions) PrintInt64T

func (ef *EnvFunctions) PrintInt64T(proc *exec.WavmProcess, remarkIdx uint64, intValue uint64)

PrintInt64T Print a int64

func (*EnvFunctions) PrintQStr

func (ef *EnvFunctions) PrintQStr(proc *exec.WavmProcess, remarkIdx uint64, strIdx uint64)

Print a string

func (*EnvFunctions) PrintStr

func (ef *EnvFunctions) PrintStr(proc *exec.WavmProcess, remarkIdx uint64, strIdx uint64)

Print a string

func (*EnvFunctions) PrintUint256T

func (ef *EnvFunctions) PrintUint256T(proc *exec.WavmProcess, remarkIdx uint64, idx uint64)

PrintUint256T Print a uint256

func (*EnvFunctions) PrintUint32T

func (ef *EnvFunctions) PrintUint32T(proc *exec.WavmProcess, remarkIdx uint64, intValue uint64)

Print a uint32

func (*EnvFunctions) PrintUint64T

func (ef *EnvFunctions) PrintUint64T(proc *exec.WavmProcess, remarkIdx uint64, intValue uint64)

Print a uint64

func (*EnvFunctions) ReadWithPointer

func (ef *EnvFunctions) ReadWithPointer(proc *exec.WavmProcess, offsetAddr, baseAddr uint64)

func (*EnvFunctions) Revert

func (ef *EnvFunctions) Revert(proc *exec.WavmProcess, msgIdx uint64)

todo 考虑revert的完整实现 contractcall里需要用到revert

func (*EnvFunctions) SHA3

func (ef *EnvFunctions) SHA3(proc *exec.WavmProcess, dataIdx uint64) uint64

SHA3

func (*EnvFunctions) SendFromContract

func (ef *EnvFunctions) SendFromContract(proc *exec.WavmProcess, addrIdx uint64, amountIdx uint64)

func (*EnvFunctions) Sender

func (ef *EnvFunctions) Sender(proc *exec.WavmProcess, ptr uint64)

Sender for qlang

func (*EnvFunctions) Store

func (ef *EnvFunctions) Store(proc *exec.WavmProcess, keyptr uint64, dataptr uint64)

Store for qlang

func (*EnvFunctions) TransferFromContract

func (ef *EnvFunctions) TransferFromContract(proc *exec.WavmProcess, addrIdx uint64, amountIdx uint64) uint64

func (*EnvFunctions) U256Add

func (ef *EnvFunctions) U256Add(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256Cmp

func (ef *EnvFunctions) U256Cmp(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256Div

func (ef *EnvFunctions) U256Div(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256From

func (ef *EnvFunctions) U256From(proc *exec.WavmProcess, idx uint64) uint64

func (*EnvFunctions) U256FromI64

func (ef *EnvFunctions) U256FromI64(proc *exec.WavmProcess, x uint64) uint64

func (*EnvFunctions) U256FromU64

func (ef *EnvFunctions) U256FromU64(proc *exec.WavmProcess, x uint64) uint64

func (*EnvFunctions) U256Mod

func (ef *EnvFunctions) U256Mod(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256Mul

func (ef *EnvFunctions) U256Mul(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256Pow

func (ef *EnvFunctions) U256Pow(proc *exec.WavmProcess, base, exponent uint64) uint64

func (*EnvFunctions) U256Sub

func (ef *EnvFunctions) U256Sub(proc *exec.WavmProcess, x, y uint64) uint64

func (*EnvFunctions) U256ToString

func (ef *EnvFunctions) U256ToString(proc *exec.WavmProcess, idx uint64) uint64

func (*EnvFunctions) WriteWithPointer

func (ef *EnvFunctions) WriteWithPointer(proc *exec.WavmProcess, offsetAddr, baseAddr uint64)

type EnvModule

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

func (*EnvModule) GetEnvFunctions

func (m *EnvModule) GetEnvFunctions() EnvFunctions

func (*EnvModule) GetModule

func (m *EnvModule) GetModule() *wasm.Module

func (*EnvModule) InitModule

func (m *EnvModule) InitModule(ctx *ChainContext)

type IllegalInputError

type IllegalInputError string

func (IllegalInputError) Error

func (e IllegalInputError) Error() string

type InvalidFunctionNameError

type InvalidFunctionNameError string

func (InvalidFunctionNameError) Error

func (e InvalidFunctionNameError) Error() string

type InvalidPayableFunctionError

type InvalidPayableFunctionError string

func (InvalidPayableFunctionError) Error

type MismatchMutableFunctionError

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

func (MismatchMutableFunctionError) Error

type Mutable

type Mutable map[uint32]bool

func MutableFunction

func MutableFunction(abi abi.ABI, module *wasm.Module) Mutable

type NoFunctionError

type NoFunctionError string

func (NoFunctionError) Error

func (e NoFunctionError) Error() string

type OpCode

type OpCode struct {
	Op       byte
	FuncName string
}

func (OpCode) Byte

func (op OpCode) Byte() byte

func (OpCode) IsPush

func (op OpCode) IsPush() bool

func (OpCode) String

func (op OpCode) String() string

type Stack

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

func (Stack) Len

func (s Stack) Len() int

func (*Stack) Pop

func (s *Stack) Pop() *Code

func (*Stack) Push

func (s *Stack) Push(b *Code)

func (*Stack) Top

func (s *Stack) Top() *Code

type StructLog

type StructLog struct {
	Pc         uint64                      `json:"pc"`
	Op         vm.OPCode                   `json:"op"`
	Gas        uint64                      `json:"gas"`
	GasCost    uint64                      `json:"gasCost"`
	Memory     []byte                      `json:"-"`
	MemorySize int                         `json:"-"`
	Stack      []*big.Int                  `json:"-"`
	Storage    map[common.Hash]common.Hash `json:"-"`
	Depth      int                         `json:"depth"`
	Err        error                       `json:"error"`
}

func (*StructLog) ErrorString

func (s *StructLog) ErrorString() string

func (*StructLog) OpName

func (s *StructLog) OpName() string

type UnknownABITypeError

type UnknownABITypeError string

func (UnknownABITypeError) Error

func (e UnknownABITypeError) Error() string

type UnknownTypeError

type UnknownTypeError string

func (UnknownTypeError) Error

func (e UnknownTypeError) Error() string

type WAVM

type WAVM struct {
	// Context provides auxiliary blockchain related information
	vm.Context
	// StateDB gives access to the underlying state
	StateDB inter.StateDB

	Wavm *Wavm
	// contains filtered or unexported fields
}

func NewWAVM

func NewWAVM(ctx vm.Context, statedb inter.StateDB, chainConfig *params.ChainConfig, vmConfig vm.Config) *WAVM

func (*WAVM) Call

func (wavm *WAVM) Call(caller vm.ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas 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 (*WAVM) CallCode

func (wavm *WAVM) CallCode(caller vm.ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error)

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

CallCode differs from Call in the sense that it executes the given address' code with the caller as context.

func (*WAVM) Cancel

func (wavm *WAVM) Cancel()

func (*WAVM) ChainConfig

func (wavm *WAVM) ChainConfig() *params.ChainConfig

func (*WAVM) Create

func (wavm *WAVM) Create(caller vm.ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error)

func (*WAVM) DelegateCall

func (wavm *WAVM) DelegateCall(caller vm.ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

func (*WAVM) GetCallGasTemp

func (wavm *WAVM) GetCallGasTemp() uint64

func (*WAVM) GetChainConfig

func (wavm *WAVM) GetChainConfig() *params.ChainConfig

func (*WAVM) GetContext

func (wavm *WAVM) GetContext() vm.Context

func (*WAVM) GetOrigin

func (wavm *WAVM) GetOrigin() common.Address

func (*WAVM) GetStateDb

func (wavm *WAVM) GetStateDb() inter.StateDB

func (*WAVM) GetTime

func (wavm *WAVM) GetTime() *big.Int

func (*WAVM) SetCallGasTemp

func (wavm *WAVM) SetCallGasTemp(gas uint64)

func (*WAVM) StaticCall

func (wavm *WAVM) StaticCall(caller vm.ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error)

type WasmLogger

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

func NewWasmLogger

func NewWasmLogger(cfg *vm.LogConfig) *WasmLogger

func (*WasmLogger) CaptureEnd

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

func (*WasmLogger) CaptureFault

func (l *WasmLogger) CaptureFault(env vm.VM, pc uint64, op vm.OPCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract inter.Contract, depth int, err error) error

func (*WasmLogger) CaptureLog

func (l *WasmLogger) CaptureLog(env vm.VM, msg string) error

func (*WasmLogger) CaptureStart

func (l *WasmLogger) CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error

func (*WasmLogger) CaptureState

func (l *WasmLogger) CaptureState(env vm.VM, pc uint64, op vm.OPCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract inter.Contract, depth int, err error) error

func (*WasmLogger) DebugLogs

func (l *WasmLogger) DebugLogs() []DebugLog

DebugLogs returns the captured debug log entries.

func (*WasmLogger) StructLogs

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

WasmLogger returns the captured log entries.

type Wavm

type Wavm struct {
	VM           *exec.Interpreter
	Module       *wasm.Module
	ChainContext ChainContext
	GasRules     gas.Gas
	WavmConfig   Config
	IsCreated    bool

	MutableList Mutable
	// contains filtered or unexported fields
}

func NewWavm

func NewWavm(chainctx ChainContext, wavmConfig Config, iscreated bool) *Wavm

func (*Wavm) Apply

func (wavm *Wavm) Apply(input []byte, compiled []vnt.Compiled, mutable Mutable) (res []byte, err error)

func (*Wavm) ExecCodeWithFuncName

func (wavm *Wavm) ExecCodeWithFuncName(input []byte) ([]byte, error)

func (*Wavm) GetFallBackFunction

func (wavm *Wavm) GetFallBackFunction() (int64, string)

func (*Wavm) GetFuncName

func (wavm *Wavm) GetFuncName() string

func (*Wavm) InstantiateModule

func (wavm *Wavm) InstantiateModule(code []byte, memory []uint8) error

func (*Wavm) ResolveImports

func (wavm *Wavm) ResolveImports(name string) (*wasm.Module, error)

func (*Wavm) SetFuncName

func (wavm *Wavm) SetFuncName(name string)

func (*Wavm) Tracer

func (wavm *Wavm) Tracer() vm.Tracer

Directories

Path Synopsis
internal
stack
Package stack implements a growable uint64 stack
Package stack implements a growable uint64 stack

Jump to

Keyboard shortcuts

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