wasmgo

package
v0.0.0-...-c626c17 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2019 License: MIT Imports: 28 Imported by: 0

README

wasmgo

Fork from https://github.com/go-interpreter/wagon Fork from https://github.com/perlin-network/life

NOTE: wasmgo requires Go >= 1.9.x.

examples

package main

import (
	"github.com/eosspark/eos-go/chain"
	"github.com/eosspark/eos-go/chain/types"
	"github.com/eosspark/eos-go/common"
	"github.com/eosspark/eos-go/crypto"
	"github.com/eosspark/eos-go/crypto/rlp"
	"github.com/eosspark/eos-go/wasmgo"
	"io/ioutil"
	"log"
)

func main() {

	name := "hello.wasm"
	code, err := ioutil.ReadFile(name)
	if err != nil {
		log.Fatal(err)
	}

	wasmgo := wasmgo.NewWasmGo()
	param, _ := rlp.EncodeToBytes(common.N("walker")) //[]byte{0x00, 0x00, 0x00, 0x00, 0x5c, 0x05, 0xa3, 0xe1}
	applyContext := &chain.ApplyContext{
		Receiver: common.N("hello"),
		Act: &types.Action{
			Account: common.N("hello"),
			Name:    common.N("hi"),
			Data:    param,
		},
	}

	codeVersion := crypto.NewSha256Byte([]byte(code))
	wasmgo.Apply(codeVersion, code, applyContext)
	
	//"hello, walker"
	//fmt.Println(applyContext.PendingConsoleOutput)

}

Documentation

Index

Constants

View Source
const (
	// DefaultCallStackSize is the default call stack size.
	DefaultCallStackSize = 512

	// DefaultPageSize is the linear memory page size.
	DefaultPageSize = 65536

	// JITCodeSizeThreshold is the lower-bound code size threshold for the JIT compiler.
	JITCodeSizeThreshold = 30
)
View Source
const (
	MaximumLinearMemory     = 33 * 1024 * 1024 //bytes
	MaximumMutableGlobals   = 1024             //bytes
	MaximumTableElements    = 1024             //elements
	MaximumSectionElements  = 1024             //elements
	MaximumLinearMemoryInit = 64 * 1024        //bytes
	MaximumFuncLocalBytes   = 8192             //bytes
	MaximumCallDepth        = 250              //nested calls
	MaximumCodeSize         = 1024 * 1024      //bytes 20 * 1024  *1024
	WasmPageSize            = 64 * 1024        //bytes

)

Variables

LE is a simple alias to `binary.LittleEndian`.

Functions

func GetOrCreateCheckTimeSig

func GetOrCreateCheckTimeSig(m *wasm.Module) int

func Init

func Init(d bool, de uint16)

func Inject

func Inject(m *wasm.Module)

func InjectBody

func InjectBody(d *disasm.Disassembly) *disasm.Disassembly

func Validate

func Validate(d bool, code []byte) error

func ValidateBody

func ValidateBody(d *disasm.Disassembly) error

func ValidateModule

func ValidateModule(m *wasm.Module) error

Types

type EnvContext

type EnvContext interface {
	//action
	GetActionData() []byte
	GetReceiver() common.AccountName
	GetCode() common.AccountName
	GetAct() common.ActionName
	ContextFreeAction() bool

	//authorization
	RequireAuthorization(account int64)
	HasAuthorization(account int64) bool
	RequireAuthorization2(account int64, permission int64)
	RequireRecipient(recipient int64)
	IsAccount(n int64) bool
	HasRecipient(code int64) bool

	//console
	//ResetConsole()
	ContextAppend(str string)

	//database
	//primaryKey
	DbStoreI64(scope uint64, table uint64, payer uint64, id uint64, buffer []byte) int
	DbUpdateI64(iterator int, payer uint64, buffer []byte)
	DbRemoveI64(iterator int)
	DbGetI64(iterator int, buffer []byte, bufferSize int) int
	DbNextI64(iterator int, primary *uint64) int
	DbPreviousI64(iterator int, primary *uint64) int
	DbFindI64(code uint64, scope uint64, table uint64, id uint64) int
	DbLowerboundI64(code uint64, scope uint64, table uint64, id uint64) int
	DbUpperboundI64(code uint64, scope uint64, table uint64, id uint64) int
	DbEndI64(code uint64, scope uint64, table uint64) int

	//index64 secondaryKey
	Idx64Store(scope uint64, table uint64, payer uint64, id uint64, value *uint64) int
	Idx64Remove(iterator int)
	Idx64Update(iterator int, payer uint64, value *uint64)
	Idx64FindSecondary(code uint64, scope uint64, table uint64, secondary *uint64, primary *uint64) int
	Idx64Lowerbound(code uint64, scope uint64, table uint64, secondary *uint64, primary *uint64) int
	Idx64Upperbound(code uint64, scope uint64, table uint64, secondary *uint64, primary *uint64) int
	Idx64End(code uint64, scope uint64, table uint64) int
	Idx64Next(iterator int, primary *uint64) int
	Idx64Previous(iterator int, primary *uint64) int
	Idx64FindPrimary(code uint64, scope uint64, table uint64, secondary *uint64, primary uint64) int

	//index128 secondaryKey
	Idx128Store(scope uint64, table uint64, payer uint64, id uint64, value *eos_math.Uint128) int
	Idx128Remove(iterator int)
	Idx128Update(iterator int, payer uint64, value *eos_math.Uint128)
	Idx128FindSecondary(code uint64, scope uint64, table uint64, secondary *eos_math.Uint128, primary *uint64) int
	Idx128Lowerbound(code uint64, scope uint64, table uint64, secondary *eos_math.Uint128, primary *uint64) int
	Idx128Upperbound(code uint64, scope uint64, table uint64, secondary *eos_math.Uint128, primary *uint64) int
	Idx128End(code uint64, scope uint64, table uint64) int
	Idx128Next(iterator int, primary *uint64) int
	Idx128Previous(iterator int, primary *uint64) int
	Idx128FindPrimary(code uint64, scope uint64, table uint64, secondary *eos_math.Uint128, primary uint64) int

	//index256 secondaryKey
	Idx256Store(scope uint64, table uint64, payer uint64, id uint64, value *eos_math.Uint256) int
	Idx256Remove(iterator int)
	Idx256Update(iterator int, payer uint64, value *eos_math.Uint256)
	Idx256FindSecondary(code uint64, scope uint64, table uint64, secondary *eos_math.Uint256, primary *uint64) int
	Idx256Lowerbound(code uint64, scope uint64, table uint64, secondary *eos_math.Uint256, primary *uint64) int
	Idx256Upperbound(code uint64, scope uint64, table uint64, secondary *eos_math.Uint256, primary *uint64) int
	Idx256End(code uint64, scope uint64, table uint64) int
	Idx256Next(iterator int, primary *uint64) int
	Idx256Previous(iterator int, primary *uint64) int
	Idx256FindPrimary(code uint64, scope uint64, table uint64, secondary *eos_math.Uint256, primary uint64) int

	//index Double secondaryKey
	IdxDoubleStore(scope uint64, table uint64, payer uint64, id uint64, value *eos_math.Float64) int
	IdxDoubleRemove(iterator int)
	IdxDoubleUpdate(iterator int, payer uint64, value *eos_math.Float64)
	IdxDoubleFindSecondary(code uint64, scope uint64, table uint64, secondary *eos_math.Float64, primary *uint64) int
	IdxDoubleLowerbound(code uint64, scope uint64, table uint64, secondary *eos_math.Float64, primary *uint64) int
	IdxDoubleUpperbound(code uint64, scope uint64, table uint64, secondary *eos_math.Float64, primary *uint64) int
	IdxDoubleEnd(code uint64, scope uint64, table uint64) int
	IdxDoubleNext(iterator int, primary *uint64) int
	IdxDoublePrevious(iterator int, primary *uint64) int
	IdxDoubleFindPrimary(code uint64, scope uint64, table uint64, secondary *eos_math.Float64, primary uint64) int

	//index LongDouble secondaryKey
	IdxLongDoubleStore(scope uint64, table uint64, payer uint64, id uint64, value *eos_math.Float128) int
	IdxLongDoubleRemove(iterator int)
	IdxLongDoubleUpdate(iterator int, payer uint64, value *eos_math.Float128)
	IdxLongDoubleFindSecondary(code uint64, scope uint64, table uint64, secondary *eos_math.Float128, primary *uint64) int
	IdxLongDoubleLowerbound(code uint64, scope uint64, table uint64, secondary *eos_math.Float128, primary *uint64) int
	IdxLongDoubleUpperbound(code uint64, scope uint64, table uint64, secondary *eos_math.Float128, primary *uint64) int
	IdxLongDoubleEnd(code uint64, scope uint64, table uint64) int
	IdxLongDoubleNext(iterator int, primary *uint64) int
	IdxLongDoublePrevious(iterator int, primary *uint64) int
	IdxLongDoubleFindPrimary(code uint64, scope uint64, table uint64, secondary *eos_math.Float128, primary uint64) int

	//permission
	GetPermissionLastUsed(account common.AccountName, permission common.PermissionName) common.TimePoint
	GetAccountCreateTime(account common.AccountName) common.TimePoint

	SetAccountLimits(account common.AccountName, ramBytes int64, netWeight int64, cpuWeigth int64) bool
	GetAccountLimits(account common.AccountName, ramBytes *int64, netWeight *int64, cpuWeigth *int64)
	SetBlockchainParametersPacked(parameters []byte)
	GetBlockchainParametersPacked() []byte
	GetBlockchainParameters() *types.ChainConfig
	SetBlockchainParameters(cfg *types.ChainConfig)

	IsPrivileged(n common.AccountName) bool
	SetPrivileged(n common.AccountName, isPriv bool)
	ValidateRamUsageInsert(account common.AccountName)

	//producer
	SetProposedProducers(producers []byte) int64
	GetActiveProducersInBytes() []byte

	//system
	CheckTime()
	//CurrentTime() int64
	CurrentTime() common.TimePoint
	//PublicationTime() int64
	PublicationTime() common.TimePoint

	//transaction
	// ExecuteInline(action []byte)
	// ExecuteContextFreeInline(action []byte)
	InlineActionTooBig(dataLen int) bool
	ExecuteInline(act *types.Action)
	ExecuteContextFreeInline(act *types.Action)
	//ScheduleDeferredTransaction(sendId *eos_math.Uint128, payer common.AccountName, trx []byte, replaceExisting bool)
	ScheduleDeferredTransaction(sendId *eos_math.Uint128, payer common.AccountName, trx *types.Transaction, replaceExisting bool)
	CancelDeferredTransaction(sendId *eos_math.Uint128) bool
	//GetPackedTransaction() []byte
	//GetPackedTransaction() *types.SignedTransaction
	GetPackedTransaction() *types.Transaction
	//Expiration() int
	Expiration() common.TimePointSec
	TaposBlockNum() int
	TaposBlockPrefix() int
	//GetAction(typ uint32, index int, bufferSize int) (int, []byte)
	GetAction(typ uint32, index int) *types.Action
	GetContextFreeData(intdex int, bufferSize int) (int, []byte)

	PauseBillingTimer()
	ResumeBillingTimer()

	CheckAuthorization(actions []*types.Action, providedKeys *PublicKeySet, providedPermissions *PermissionLevelSet, delayUS uint64)
	CheckAuthorization2(n common.AccountName, permission common.PermissionName, providedKeys *PublicKeySet, providedPermissions *PermissionLevelSet, delayUS uint64)
}

type Frame

type Frame struct {
	FunctionID   int
	Code         []byte
	Regs         []int64
	Locals       []int64
	IP           int
	ReturnReg    int
	Continuation int32
}

Frame represents a call frame.

func (*Frame) Destroy

func (f *Frame) Destroy(vm *VirtualMachine)

Destroy destroys a frame. Must be called on return.

func (*Frame) Init

func (f *Frame) Init(vm *VirtualMachine, functionID int, code compiler.InterpreterCode)

Init initializes a frame. Must be called on `call` and `call_indirect`.

type FunctionImport

type FunctionImport func(vm *VirtualMachine) int64

FunctionImport represents the function import type. If len(sig.ReturnTypes) == 0, the return value will be ignored.

type ImportResolver

type ImportResolver interface {
	ResolveFunc(module, field string) FunctionImport
	ResolveGlobal(module, field string) int64
}

ImportResolver is an interface for allowing one to define imports to WebAssembly modules ran under a single VirtualMachine instance.

type NopResolver

type NopResolver struct{}

NopResolver is a nil WebAssembly module import resolver.

func (*NopResolver) ResolveFunc

func (r *NopResolver) ResolveFunc(module, field string) FunctionImport

func (*NopResolver) ResolveGlobal

func (r *NopResolver) ResolveGlobal(module, field string) int64

type Resolver

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

Resolver defines imports for WebAssembly modules ran in Life.

func (*Resolver) ResolveFunc

func (r *Resolver) ResolveFunc(module, field string) FunctionImport

ResolveFunc defines a set of import functions that may be called within a WebAssembly module.

func (*Resolver) ResolveGlobal

func (r *Resolver) ResolveGlobal(module, field string) int64

ResolveGlobal defines a set of global variables for use within a WebAssembly module.

type VMConfig

type VMConfig struct {
	EnableJIT                bool
	MaxMemoryPages           int
	MaxTableSize             int
	MaxValueSlots            int
	MaxCallStackDepth        int
	DefaultMemoryPages       int
	DefaultTableSize         int
	GasLimit                 uint64
	DisableFloatingPoint     bool
	ReturnOnGasLimitExceeded bool
}

VMConfig denotes a set of options passed to a single VirtualMachine insta.ce

type VirtualMachine

type VirtualMachine struct {
	WasmGo *WasmGo

	Config           VMConfig
	Module           *compiler.Module
	FunctionCode     []compiler.InterpreterCode
	FunctionImports  []FunctionImport
	CallStack        []Frame
	CurrentFrame     int
	Table            []uint32
	Globals          []int64
	Memory           []byte
	NumValueSlots    int
	Yielded          int64
	InsideExecute    bool
	Delegate         func()
	Exited           bool
	ExitError        interface{}
	ReturnValue      int64
	Gas              uint64
	GasLimitExceeded bool
}

VirtualMachine is a WebAssembly execution environment.

func NewVirtualMachine

func NewVirtualMachine(
	wasmGo *WasmGo,
	code []byte,
	config VMConfig,
	impResolver ImportResolver,
	gasPolicy compiler.GasPolicy,
) (_retVM *VirtualMachine, retErr error)

NewVirtualMachine instantiates a virtual machine for a given WebAssembly module, with specific execution options specified under a VMConfig, and a WebAssembly module import resolver.

func (*VirtualMachine) AddAndCheckGas

func (vm *VirtualMachine) AddAndCheckGas(delta uint64) bool

func (*VirtualMachine) Execute

func (vm *VirtualMachine) Execute()

Execute starts the virtual machines main instruction processing loop. This function may return at any point and is guaranteed to return at least once every 10000 instructions. Caller is responsible for detecting VM status in a loop.

func (*VirtualMachine) GetCurrentFrame

func (vm *VirtualMachine) GetCurrentFrame() *Frame

GetCurrentFrame returns the current frame.

func (*VirtualMachine) GetFunctionExport

func (vm *VirtualMachine) GetFunctionExport(key string) (int, bool)

GetFunctionExport returns the function export with the given name.

func (*VirtualMachine) GetGlobalExport

func (vm *VirtualMachine) GetGlobalExport(key string) (int, bool)

GetGlobalExport returns the global export with the given name.

func (*VirtualMachine) Ignite

func (vm *VirtualMachine) Ignite(functionID int, params ...int64)

Ignite initializes the first call frame.

func (*VirtualMachine) PrintStackTrace

func (vm *VirtualMachine) PrintStackTrace()

PrintStackTrace prints the entire VM stack trace for debugging.

func (*VirtualMachine) Reset

func (vm *VirtualMachine) Reset()

GetCurrentFrame returns the current frame.

func (*VirtualMachine) Run

func (vm *VirtualMachine) Run(entryID int, params ...int64) (int64, error)

Run runs a WebAssembly modules function denoted by its ID with a specified set of parameters. Panics on logical errors.

func (*VirtualMachine) RunWithGasLimit

func (vm *VirtualMachine) RunWithGasLimit(entryID, limit int, params ...int64) (int64, error)

RunWithGasLimit runs a WebAssembly modules function denoted by its ID with a specified set of parameters for a specified amount of instructions (also known as gas) denoted by `limit`. Panics on logical errors.

type WasmGo

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

func NewWasmGo

func NewWasmGo() *WasmGo

func (*WasmGo) Apply

func (w *WasmGo) Apply(codeId *crypto.Sha256, code []byte, context EnvContext)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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