vmhost

package
v1.4.77 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2023 License: GPL-3.0 Imports: 18 Imported by: 1

Documentation

Overview

Package vm contains the top-level components and definitions of the VM

Index

Constants

View Source
const (
	// AsyncCallPending is the status of an async call that awaits complete execution
	AsyncCallPending AsyncCallStatus = iota

	// AsyncCallResolved is the status of an async call that was executed completely and successfully
	AsyncCallResolved

	// AsyncCallRejected is the status of an async call that was executed completely but unsuccessfully
	AsyncCallRejected

	// AddressLen specifies the length of the address
	AddressLen = 32

	// HashLen specifies the lenghth of a hash
	HashLen = 32

	// BalanceLen specifies the number of bytes on which the balance is stored
	BalanceLen = 32

	// CodeMetadataLen specifies the length of the code metadata
	CodeMetadataLen = 2

	// InitFunctionName specifies the name for the init function
	InitFunctionName = "init"

	// InitFunctionNameEth specifies the name for the init function on Ethereum
	InitFunctionNameEth = "solidity.ctor"

	// UpgradeFunctionName specifies if the call is an upgradeContract call
	UpgradeFunctionName = "upgradeContract"
)
View Source
const AsyncDataPrefix = ProtectedStoragePrefix + "ASYNC"

AsyncDataPrefix is the storage key prefix used for AsyncContext-related storage.

View Source
const CallbackFunctionName = "callBack"

CallbackFunctionName is the name of the default asynchronous callback function of a smart contract

View Source
const ProtectedStoragePrefix = "A" + "R" + "W" + "E" + "N@"

ProtectedStoragePrefix is the storage key prefix that will be protected by VM explicitly, and implicitly by the node due to '@'; the protection can be disabled temporarily by the StorageContext

View Source
const TimeLockKeyPrefix = ProtectedStoragePrefix + "TIMELOCK"

TimeLockKeyPrefix is the storage key prefix used for timelock-related storage.

View Source
const VMVersion = "v1.4"

VMVersion returns the current vm version

View Source
const WASMPageSize = 65536

WASMPageSize size in bytes of a WASM Linear Memory Page

Variables

View Source
var ErrAccountNotPayable = errors.New("sending value to non payable contract")

ErrAccountNotPayable signals that the value transfer to a non payable contract is not possible

View Source
var ErrAllOperandsAreEqualToZero = errors.New("all operands are equal to 0")

ErrAllOperandsAreEqualToZero signals that all operands are equal to 0

View Source
var ErrArgIndexOutOfRange = errors.New("argument index out of range")

ErrArgIndexOutOfRange signals that the argument index is out of range

View Source
var ErrArgOutOfRange = errors.New("argument out of range")

ErrArgOutOfRange signals that the argument is out of range

View Source
var ErrAsyncContextDoesNotExist = errors.New("async context does not exist")

ErrAsyncContextDoesNotExist signals that the async context does not exist

View Source
var ErrBadBounds = errors.New("bad bounds")

ErrBadBounds signals that a certain variable is out of bounds

View Source
var ErrBadLowerBounds = fmt.Errorf("%w (lower)", ErrBadBounds)

ErrBadLowerBounds signals that a certain variable is lower than allowed

View Source
var ErrBadUpperBounds = fmt.Errorf("%w (upper)", ErrBadBounds)

ErrBadUpperBounds signals that a certain variable is higher than allowed

View Source
var ErrBigFloatWrongPrecision = errors.New("precision of the big float must be 53")

ErrBigFloatWrongPrecision signals that the precision has a wrong value

View Source
var ErrBitwiseNegative = errors.New("bitwise operations only allowed on positive integers")

ErrBitwiseNegative signals that an attempt to apply a bitwise operation on negative numbers has been made

View Source
var ErrBuiltinCallOnSameContextDisallowed = errors.New("calling built-in function on the same context is disallowed")

ErrBuiltinCallOnSameContextDisallowed signals that calling a built-in function on the same context is not allowed

View Source
var ErrCallBackFuncCalledInRun = fmt.Errorf("%w (calling callBack() directly is forbidden)", ErrInvalidFunction)

ErrCallBackFuncCalledInRun signals that a callback func was called directly, which is forbidden

View Source
var ErrCallBackFuncNotExpected = fmt.Errorf("%w (unexpected callback was received)", ErrInvalidFunction)

ErrCallBackFuncNotExpected signals that an unexpected callback was received

View Source
var ErrCannotWriteOnReadOnly = errors.New("cannot write on read only mode")

ErrCannotWriteOnReadOnly signals that write operation on read only is not allowed

View Source
var ErrCannotWriteProtectedKey = errors.New("cannot write to protected key")

ErrCannotWriteProtectedKey signals an attempt to write to a protected key, while storage protection is enforced

View Source
var ErrContractInvalid = fmt.Errorf("invalid contract code")

ErrContractInvalid signals that the contract code is invalid

View Source
var ErrContractNotFound = fmt.Errorf("%w (not found)", ErrContractInvalid)

ErrContractNotFound signals that the contract was not found

View Source
var ErrDeploymentOverExistingAccount = errors.New("cannot deploy over existing account")

ErrDeploymentOverExistingAccount signals that an attempt to deploy a new SC over an already existing account has been made

View Source
var ErrDivZero = errors.New("division by 0")

ErrDivZero signals that an attempt to divide by 0 has been made

View Source
var ErrEmptyProtectedKeyPrefix = errors.New("protectedKeyPrefix is empty or nil")

ErrEmptyProtectedKeyPrefix signals that the protected key prefix is empty or nil

View Source
var ErrExecutionFailed = errors.New("execution failed")

ErrExecutionFailed signals that the execution failed

View Source
var ErrExecutionFailedWithTimeout = errors.New("execution failed with timeout")

ErrExecutionFailedWithTimeout signals that the execution failed with timeout

View Source
var ErrExecutionPanicked = errors.New("VM execution panicked")

ErrExecutionPanicked signals that the execution failed irrecoverably

View Source
var ErrExponentTooBigOrTooSmall = errors.New("exponent is either too small or too big")

ErrExponentTooBigOrTooSmall signals that the exponent is too big or too small

View Source
var ErrFailedTransfer = errors.New("failed transfer")

ErrFailedTransfer signals that the transfer operation has failed

View Source
var ErrFuncNotFound = fmt.Errorf("%w (not found)", ErrInvalidFunction)

ErrFuncNotFound signals that the the function does not exist

View Source
var ErrFunctionNonvoidSignature = fmt.Errorf("%w (nonvoid signature)", ErrInvalidFunction)

ErrFunctionNonvoidSignature signals that the signature for the function is invalid

View Source
var ErrInfinityFloatOperation = errors.New("infinity operations are not allowed")

ErrInfinityFloatOperation signals that operations with infinity are not allowed

View Source
var ErrInitFuncCalledInRun = fmt.Errorf("%w (calling init() directly is forbidden)", ErrInvalidFunction)

ErrInitFuncCalledInRun signals that the init func was called directly, which is forbidden

View Source
var ErrInputAndOutputGasDoesNotMatch = errors.New("input and output gas does not match")

ErrInputAndOutputGasDoesNotMatch is raised when the output gas (gas used + gas locked + gas remaining) is not equal to the input gas

View Source
var ErrInvalidAccount = errors.New("account does not exist")

ErrInvalidAccount signals that a certain account does not exist

View Source
var ErrInvalidArgument = errors.New("invalid argument")

ErrInvalidArgument is given when argument is invalid

View Source
var ErrInvalidBuiltInFunctionCall = errors.New("invalid built in function call")

ErrInvalidBuiltInFunctionCall signals that built in function was used in the wrong context

View Source
var ErrInvalidCallOnReadOnlyMode = errors.New("operation not permitted in read only mode")

ErrInvalidCallOnReadOnlyMode signals that an operation is not permitted due to read only mode

View Source
var ErrInvalidFunction = errors.New("invalid function")

ErrInvalidFunction signals that the function is invalid

View Source
var ErrInvalidFunctionName = fmt.Errorf("%w (invalid name)", ErrInvalidFunction)

ErrInvalidFunctionName signals that the function name is invalid

View Source
var ErrInvalidPublicKeySize = errors.New("invalid public key size")

ErrInvalidPublicKeySize signals that the public key size is invalid

View Source
var ErrInvalidTokenIndex = errors.New("invalid token index")

ErrInvalidTokenIndex is given when argument is invalid

View Source
var ErrInvalidUpgradeArguments = fmt.Errorf("%w (invalid arguments)", ErrUpgradeFailed)

ErrInvalidUpgradeArguments signals that the upgrade process failed due to invalid arguments

View Source
var ErrLengthOfBufferNotCorrect = errors.New("length of buffer is not correct")

ErrLengthOfBufferNotCorrect signals that length of the buffer is not correct

View Source
var ErrMaxInstancesReached = fmt.Errorf("%w (max instances reached)", ErrExecutionFailed)

ErrMaxInstancesReached signals that the max number of Wasmer instances has been reached.

View Source
var ErrMemoryDeclarationMissing = fmt.Errorf("%w (missing memory declaration)", ErrContractInvalid)

ErrMemoryDeclarationMissing signals that a memory declaration is missing

View Source
var ErrMemoryLimit = errors.New("memory limit reached")

ErrMemoryLimit signals that too much memory was allocated by the contract

View Source
var ErrNegativeLength = errors.New("negative length")

ErrNegativeLength signals that the given length is less than 0

View Source
var ErrNilBlockChainHook = errors.New("nil blockchain hook")

ErrNilBlockChainHook signals that nil blockchain hook was provided

View Source
var ErrNilBuiltInFunctionsContainer = errors.New("nil built in functions container")

ErrNilBuiltInFunctionsContainer signals that nil built in functions container was provided

View Source
var ErrNilCallbackFunction = errors.New("nil callback function")

ErrNilCallbackFunction signals that a nil callback function has been provided

View Source
var ErrNilContract = errors.New("nil contract")

ErrNilContract signals that the contract is nil

View Source
var ErrNilESDTData = errors.New("nil esdt data")

ErrNilESDTData is given when ESDT data is missing

View Source
var ErrNilESDTTransferParser = errors.New("nil esdt transfer parser")

ErrNilESDTTransferParser signals that nil esdt transfer parser was provided

View Source
var ErrNilEnableEpochsHandler = errors.New("nil enable epochs handler")

ErrNilEnableEpochsHandler signals that enable epochs handler is nil

View Source
var ErrNilEpochNotifier = errors.New("nil epoch notifier")

ErrNilEpochNotifier signals that epoch notifier is nil

View Source
var ErrNilHasher = errors.New("nil hasher")

ErrNilHasher signals that the provided hasher is nil

View Source
var ErrNilHost = errors.New("nil host")

ErrNilHost signals that a nil host was provided

View Source
var ErrNilHostParameters = errors.New("nil host parameters")

ErrNilHostParameters signals that nil host parameters was provided

View Source
var ErrNilVMHost = errors.New("nil VM Host")

ErrNilVMHost signals that the VM Host is nil

View Source
var ErrNilVMType = errors.New("nil vm type")

ErrNilVMType signals that a nil VMType was provided

View Source
var ErrNoBigFloatUnderThisHandle = errors.New("no bigFloat under the given handle")

ErrNoBigFloatUnderThisHandle signals that there is no bigInt for the given handle

View Source
var ErrNoBigIntUnderThisHandle = errors.New("no bigInt under the given handle")

ErrNoBigIntUnderThisHandle signals that there is no bigInt for the given handle

View Source
var ErrNoEllipticCurveUnderThisHandle = errors.New("no elliptic curve under the given handle")

ErrNoEllipticCurveUnderThisHandle singals that there is no elliptic curve for the given handle

View Source
var ErrNoManagedBufferUnderThisHandle = errors.New("no managed buffer under the given handle")

ErrNoManagedBufferUnderThisHandle signals that there is no buffer for the given handle

View Source
var ErrNonPayableFunctionEgld = errors.New("function does not accept EGLD payment")

ErrNonPayableFunctionEgld signals that a non-payable function received non-zero call value

View Source
var ErrNonPayableFunctionEsdt = errors.New("function does not accept ESDT payment")

ErrNonPayableFunctionEsdt signals that a non-payable function received non-zero ESDT call value

View Source
var ErrNotEnoughGas = errors.New("not enough gas")

ErrNotEnoughGas signals that there is not enough gas for the operation

View Source
var ErrPointNotOnCurve = errors.New("point is not on curve")

ErrPointNotOnCurve signals that the point to be used is not on curve

View Source
var ErrPositiveExponent = errors.New("exponent must be negative")

ErrPositiveExponent signals that the exponent is greater or equal to 0

View Source
var ErrReturnCodeNotOk = errors.New("return code is not ok")

ErrReturnCodeNotOk signals that the returned code is different than vmcommon.Ok

View Source
var ErrShiftNegative = errors.New("bitwise shift operations only allowed on positive integers and by a positive amount")

ErrShiftNegative signals that an attempt to apply a bitwise shift operation on negative numbers has been made

View Source
var ErrSignalError = errors.New("error signalled by smartcontract")

ErrSignalError is given when the smart contract signals an error

View Source
var ErrStorageValueOutOfRange = errors.New("storage value out of range")

ErrStorageValueOutOfRange signals that the storage value is out of range

View Source
var ErrStoreReservedKey = errors.New("cannot write to storage under reserved key")

ErrStoreReservedKey signals that an attempt to write under an reserved key has been made

View Source
var ErrSyncExecutionNotInSameShard = errors.New("sync execution request is not in the same shard")

ErrSyncExecutionNotInSameShard signals that the sync execution request is not in the same shard

View Source
var ErrTooManyESDTTransfers = errors.New("too many ESDT transfers")

ErrTooManyESDTTransfers signals that too many ESDT transfers are in sc call

View Source
var ErrTransferInsufficientFunds = fmt.Errorf("%w (insufficient funds)", ErrFailedTransfer)

ErrTransferInsufficientFunds signals that the transfer has failed due to insufficient funds

View Source
var ErrTransferNegativeValue = fmt.Errorf("%w (negative value)", ErrFailedTransfer)

ErrTransferNegativeValue signals that the transfer has failed due to the fact that the value is less than 0

View Source
var ErrTransferValueOnESDTCall = errors.New("transfer value on esdt call")

ErrTransferValueOnESDTCall signals that balance transfer was given in esdt call

View Source
var ErrUnhandledRuntimeBreakpoint = errors.New("unhandled runtime breakpoint")

ErrUnhandledRuntimeBreakpoint signals that the runtime breakpoint is unhandled

View Source
var ErrUpgradeFailed = errors.New("upgrade failed")

ErrUpgradeFailed signals that the upgrade encountered an error

View Source
var ErrUpgradeNotAllowed = errors.New("upgrade not allowed")

ErrUpgradeNotAllowed signals that an upgrade is not allowed

View Source
var ErrVMIsClosing = errors.New("vm is closing")

ErrVMIsClosing signals that vm is closing

View Source
var One = big.NewInt(1)

One is the big integer 1

View Source
var Zero = big.NewInt(0)

Zero is the big integer 0

Functions

func BooleanToInt

func BooleanToInt(b bool) int

BooleanToInt returns 1 if the given bool is true, 0 otherwise

func CustomStorageKey

func CustomStorageKey(keyType string, associatedKey []byte) []byte

CustomStorageKey appends the given key type to the given associated key

func DisableLoggingForTests

func DisableLoggingForTests()

DisableLoggingForTests sets log level to *:NONE

func GetCryptoContext

func GetCryptoContext(vmHostPtr unsafe.Pointer) crypto.VMCrypto

GetCryptoContext returns the crypto context

func GetSCCode

func GetSCCode(fileName string) []byte

GetSCCode returns the SC code from a given file

func GuardedGetBytesSlice

func GuardedGetBytesSlice(data []byte, offset int32, length int32) ([]byte, error)

GuardedGetBytesSlice returns a chunk from the given data

func GuardedMakeByteSlice2D

func GuardedMakeByteSlice2D(length int32) ([][]byte, error)

GuardedMakeByteSlice2D creates a new two-dimensional byte slice of the given dimension.

func IfNil

func IfNil(checker nilInterfaceChecker) bool

IfNil tests if the provided interface pointer or underlying object is nil

func InverseBytes

func InverseBytes(data []byte) []byte

InverseBytes reverses the bytes of the given byte slice

func PadBytesLeft

func PadBytesLeft(data []byte, size int) []byte

PadBytesLeft adds a padding of the given size to the left the byte slice

func SetLoggingForTests

func SetLoggingForTests()

SetLoggingForTests configures the logger package with *:TRACE and enabled logger names

func U64ToLEB128

func U64ToLEB128(n uint64) (out []byte)

U64ToLEB128 encodes an uint64 using LEB128 (Little Endian Base 128), used in WASM bytecode See https://en.wikipedia.org/wiki/LEB128 Copied from https://github.com/filecoin-project/go-leb128/blob/master/leb128.go

func WithFault

func WithFault(err error, vmHostPtr unsafe.Pointer, failExecution bool) bool

WithFault returns true if the error is not nil, and uses the remaining gas if the execution has failed

func WithFaultAndHost

func WithFaultAndHost(host VMHost, err error, failExecution bool) bool

WithFaultAndHost fails the execution with the provided error

func WithFaultAndHostIfFailAlwaysActive

func WithFaultAndHostIfFailAlwaysActive(err error, host VMHost, failExecution bool)

WithFaultAndHostIfFailAlwaysActive returns true if the error is not nil, and uses the remaining gas if the execution has failed

func WithFaultIfFailAlwaysActive

func WithFaultIfFailAlwaysActive(err error, vmHostPtr unsafe.Pointer, failExecution bool)

WithFaultIfFailAlwaysActive returns true if the error is not nil, and uses the remaining gas if the execution has failed

Types

type AsyncCallExecutionMode

type AsyncCallExecutionMode uint

AsyncCallExecutionMode encodes the execution modes of an AsyncCall

const (
	// SyncCall indicates that the async call can be executed synchronously,
	// with its corresponding callback
	SyncCall AsyncCallExecutionMode = iota

	// AsyncBuiltinFuncIntraShard indicates that the async call is an intra-shard built in function call
	AsyncBuiltinFuncIntraShard

	// AsyncBuiltinFuncCrossShard indicates that the async call is a cross-shard call to a
	// built-in function, which is executed half in-shard, half cross-shard
	AsyncBuiltinFuncCrossShard

	// ESDTTransferOnCallBack indicated that the async call is actually a callback with ESDT transfer
	ESDTTransferOnCallBack

	// AsyncUnknown indicates that the async call cannot be executed locally, and
	// must be forwarded to the destination account
	AsyncUnknown
)

type AsyncCallInfo

type AsyncCallInfo struct {
	Destination []byte
	Data        []byte
	GasLimit    uint64
	GasLocked   uint64
	ValueBytes  []byte
}

AsyncCallInfo contains the information required to handle the asynchronous call of another SmartContract

func (*AsyncCallInfo) GetData

func (aci *AsyncCallInfo) GetData() []byte

GetData returns the transaction data of the async call

func (*AsyncCallInfo) GetDestination

func (aci *AsyncCallInfo) GetDestination() []byte

GetDestination returns the destination of an async call

func (*AsyncCallInfo) GetGasLimit

func (aci *AsyncCallInfo) GetGasLimit() uint64

GetGasLimit returns the gas limit of the current async call

func (*AsyncCallInfo) GetGasLocked

func (aci *AsyncCallInfo) GetGasLocked() uint64

GetGasLocked returns the gas locked for the async callback

func (*AsyncCallInfo) GetValueBytes

func (aci *AsyncCallInfo) GetValueBytes() []byte

GetValueBytes returns the byte representation of the value of the async call

type AsyncCallInfoHandler

type AsyncCallInfoHandler interface {
	GetDestination() []byte
	GetData() []byte
	GetGasLimit() uint64
	GetGasLocked() uint64
	GetValueBytes() []byte
}

AsyncCallInfoHandler defines the functionality for working with AsyncCallInfo

type AsyncCallStatus

type AsyncCallStatus uint8

AsyncCallStatus represents the different status an async call can have

type AsyncContext

type AsyncContext struct {
	Callback   string
	AsyncCalls []*AsyncGeneratedCall
}

AsyncContext is a structure containing a group of async calls and a callback

that should be called when all these async calls are resolved

type AsyncContextInfo

type AsyncContextInfo struct {
	CallerAddr      []byte
	ReturnData      []byte
	AsyncContextMap map[string]*AsyncContext
}

AsyncContextInfo is the structure resulting after a smart contract call that has initiated one or more async calls. It will

type AsyncGeneratedCall

type AsyncGeneratedCall struct {
	Status          AsyncCallStatus
	Destination     []byte
	Data            []byte
	GasLimit        uint64
	ValueBytes      []byte
	SuccessCallback string
	ErrorCallback   string
	ProvidedGas     uint64
}

AsyncGeneratedCall holds the information abount an async call

func (*AsyncGeneratedCall) GetData

func (ac *AsyncGeneratedCall) GetData() []byte

GetData returns the transaction data of the async call

func (*AsyncGeneratedCall) GetDestination

func (ac *AsyncGeneratedCall) GetDestination() []byte

GetDestination returns the destination of an async call

func (*AsyncGeneratedCall) GetGasLimit

func (ac *AsyncGeneratedCall) GetGasLimit() uint64

GetGasLimit returns the gas limit of the current async call

func (*AsyncGeneratedCall) GetGasLocked

func (ac *AsyncGeneratedCall) GetGasLocked() uint64

GetGasLocked returns the gas locked for the async callback

func (*AsyncGeneratedCall) GetValueBytes

func (ac *AsyncGeneratedCall) GetValueBytes() []byte

GetValueBytes returns the byte representation of the value of the async call

func (*AsyncGeneratedCall) IsInterfaceNil

func (ac *AsyncGeneratedCall) IsInterfaceNil() bool

IsInterfaceNil returns true if there is no value under the interface

type BlockchainContext

type BlockchainContext interface {
	StateStack

	NewAddress(creatorAddress []byte) ([]byte, error)
	AccountExists(addr []byte) bool
	GetBalance(addr []byte) []byte
	GetBalanceBigInt(addr []byte) *big.Int
	GetNonce(addr []byte) (uint64, error)
	CurrentEpoch() uint32
	GetStateRootHash() []byte
	LastTimeStamp() uint64
	LastNonce() uint64
	LastRound() uint64
	LastEpoch() uint32
	CurrentRound() uint64
	CurrentNonce() uint64
	CurrentTimeStamp() uint64
	CurrentRandomSeed() []byte
	LastRandomSeed() []byte
	IncreaseNonce(addr []byte)
	GetCodeHash(addr []byte) []byte
	GetCode(addr []byte) ([]byte, error)
	GetCodeSize(addr []byte) (int32, error)
	BlockHash(number int64) []byte
	GetOwnerAddress() ([]byte, error)
	GetShardOfAddress(addr []byte) uint32
	IsSmartContract(addr []byte) bool
	IsPayable(sndAddress, rcvAddress []byte) (bool, error)
	SaveCompiledCode(codeHash []byte, code []byte)
	GetCompiledCode(codeHash []byte) (bool, []byte)
	GetESDTToken(address []byte, tokenID []byte, nonce uint64) (*esdt.ESDigitalToken, error)
	IsLimitedTransfer(tokenID []byte) bool
	IsPaused(tokenID []byte) bool
	GetUserAccount(address []byte) (vmcommon.UserAccountHandler, error)
	ProcessBuiltInFunction(input *vmcommon.ContractCallInput) (*vmcommon.VMOutput, error)
	GetSnapshot() int
	RevertToSnapshot(snapshot int)
	ClearCompiledCodes()
}

BlockchainContext defines the functionality needed for interacting with the blockchain context

func GetBlockchainContext

func GetBlockchainContext(vmHostPtr unsafe.Pointer) BlockchainContext

GetBlockchainContext returns the blockchain context

type BreakpointValue

type BreakpointValue uint64

BreakpointValue encodes Wasmer runtime breakpoint types

const (
	// BreakpointNone means the lack of a breakpoint
	BreakpointNone BreakpointValue = iota

	// BreakpointExecutionFailed means that Wasmer must stop immediately
	// due to failure indicated by VM
	BreakpointExecutionFailed

	// BreakpointAsyncCall means that Wasmer must stop immediately
	// so the VM can execute an AsyncCall
	BreakpointAsyncCall

	// BreakpointSignalError means that Wasmer must stop immediately
	// due to a contract-signalled error
	BreakpointSignalError

	// BreakpointOutOfGas means that Wasmer must stop immediately
	// due to gas being exhausted
	BreakpointOutOfGas

	// BreakpointMemoryLimit means that Wasmer must stop immediately
	// due to over-allocation of WASM memory
	BreakpointMemoryLimit
)

type CallArgsParser

type CallArgsParser interface {
	ParseData(data string) (string, [][]byte, error)
	IsInterfaceNil() bool
}

CallArgsParser defines the functionality to parse transaction data for a smart contract call

type CodeDeployInput

type CodeDeployInput struct {
	ContractCode         []byte
	ContractCodeMetadata []byte
	ContractAddress      []byte
	CodeDeployerAddress  []byte
}

CodeDeployInput contains code deploy state, whether it comes from a ContractCreateInput or a ContractCallInput

type GasTracing

type GasTracing interface {
	BeginTrace(scAddress string, functionName string)
	AddToCurrentTrace(usedGas uint64)
	AddTracedGas(scAddress string, functionName string, usedGas uint64)
	GetGasTrace() map[string]map[string][]uint64
	IsInterfaceNil() bool
}

GasTracing defines the functionality needed for a gas tracing

type HashComputer

type HashComputer interface {
	Compute(string) []byte
	Size() int
	IsInterfaceNil() bool
}

HashComputer provides hash computation

type InstanceBuilder

type InstanceBuilder interface {
	NewInstanceWithOptions(contractCode []byte, options wasmer.CompilationOptions) (wasmer.InstanceHandler, error)
	NewInstanceFromCompiledCodeWithOptions(compiledCode []byte, options wasmer.CompilationOptions) (wasmer.InstanceHandler, error)
}

InstanceBuilder defines the functionality needed to create Wasmer instances

type ManagedTypesContext

type ManagedTypesContext interface {
	StateStack

	GetRandReader() io.Reader
	ConsumeGasForThisBigIntNumberOfBytes(byteLen *big.Int)
	ConsumeGasForThisIntNumberOfBytes(byteLen int)
	ConsumeGasForBytes(bytes []byte)
	ConsumeGasForBigIntCopy(values ...*big.Int)
	ConsumeGasForBigFloatCopy(values ...*big.Float)
	NewBigInt(value *big.Int) int32
	NewBigIntFromInt64(int64Value int64) int32
	GetBigIntOrCreate(handle int32) *big.Int
	GetBigInt(id int32) (*big.Int, error)
	GetTwoBigInt(handle1 int32, handle2 int32) (*big.Int, *big.Int, error)
	PutBigFloat(value *big.Float) (int32, error)
	BigFloatPrecIsNotValid(precision uint) bool
	BigFloatExpIsNotValid(exponent int) bool
	EncodedBigFloatIsNotValid(encodedBigFloat []byte) bool
	GetBigFloatOrCreate(handle int32) (*big.Float, error)
	GetBigFloat(handle int32) (*big.Float, error)
	GetTwoBigFloats(handle1 int32, handle2 int32) (*big.Float, *big.Float, error)
	PutEllipticCurve(ec *elliptic.CurveParams) int32
	GetEllipticCurve(handle int32) (*elliptic.CurveParams, error)
	GetEllipticCurveSizeOfField(ecHandle int32) int32
	Get100xCurveGasCostMultiplier(ecHandle int32) int32
	GetScalarMult100xCurveGasCostMultiplier(ecHandle int32) int32
	GetUCompressed100xCurveGasCostMultiplier(ecHandle int32) int32
	GetPrivateKeyByteLengthEC(ecHandle int32) int32
	NewManagedBuffer() int32
	NewManagedBufferFromBytes(bytes []byte) int32
	SetBytes(mBufferHandle int32, bytes []byte)
	GetBytes(mBufferHandle int32) ([]byte, error)
	AppendBytes(mBufferHandle int32, bytes []byte) bool
	GetLength(mBufferHandle int32) int32
	GetSlice(mBufferHandle int32, startPosition int32, lengthOfSlice int32) ([]byte, error)
	DeleteSlice(mBufferHandle int32, startPosition int32, lengthOfSlice int32) ([]byte, error)
	InsertSlice(mBufferHandle int32, startPosition int32, slice []byte) ([]byte, error)
	ReadManagedVecOfManagedBuffers(managedVecHandle int32) ([][]byte, uint64, error)
	WriteManagedVecOfManagedBuffers(data [][]byte, destinationHandle int32)
}

ManagedTypesContext defines the functionality needed for interacting with the big int context

func GetManagedTypesContext

func GetManagedTypesContext(vmHostPtr unsafe.Pointer) ManagedTypesContext

GetManagedTypesContext returns the big int context

type MeteringContext

type MeteringContext interface {
	StateStack
	PopMergeActiveState()

	InitStateFromContractCallInput(input *vmcommon.VMInput)
	SetGasSchedule(gasMap config.GasScheduleMap)
	GasSchedule() *config.GasCost
	UseGas(gas uint64)
	UseAndTraceGas(gas uint64)
	UseGasAndAddTracedGas(functionName string, gas uint64)
	FreeGas(gas uint64)
	RestoreGas(gas uint64)
	GasLeft() uint64
	GasUsedForExecution() uint64
	GasSpentByContract() uint64
	GetGasForExecution() uint64
	GetGasProvided() uint64
	GetSCPrepareInitialCost() uint64
	BoundGasLimit(value int64) uint64
	BlockGasLimit() uint64
	DeductInitialGasForExecution(contract []byte) error
	DeductInitialGasForDirectDeployment(input CodeDeployInput) error
	DeductInitialGasForIndirectDeployment(input CodeDeployInput) error
	ComputeGasLockedForAsync() uint64
	UseGasForAsyncStep() error
	UseGasBounded(gasToUse uint64) error
	GetGasLocked() uint64
	UpdateGasStateOnSuccess(vmOutput *vmcommon.VMOutput) error
	UpdateGasStateOnFailure(vmOutput *vmcommon.VMOutput)
	TrackGasUsedByBuiltinFunction(builtinInput *vmcommon.ContractCallInput, builtinOutput *vmcommon.VMOutput, postBuiltinInput *vmcommon.ContractCallInput)
	StartGasTracing(functionName string)
	SetGasTracing(enableGasTracing bool)
	GetGasTrace() map[string]map[string][]uint64
}

MeteringContext defines the functionality needed for interacting with the metering context

func GetMeteringContext

func GetMeteringContext(vmHostPtr unsafe.Pointer) MeteringContext

GetMeteringContext returns the metering context

type OutputContext

type OutputContext interface {
	StateStack
	PopMergeActiveState()
	CensorVMOutput()
	AddToActiveState(rightOutput *vmcommon.VMOutput)

	GetOutputAccount(address []byte) (*vmcommon.OutputAccount, bool)
	GetOutputAccounts() map[string]*vmcommon.OutputAccount
	DeleteOutputAccount(address []byte)
	WriteLog(address []byte, topics [][]byte, data []byte)
	TransferValueOnly(destination []byte, sender []byte, value *big.Int, checkPayable bool) error
	Transfer(destination []byte, sender []byte, gasLimit uint64, gasLocked uint64, value *big.Int, input []byte, callType vm.CallType) error
	TransferESDT(destination []byte, sender []byte, transfers []*vmcommon.ESDTTransfer, callInput *vmcommon.ContractCallInput) (uint64, error)
	SelfDestruct(address []byte, beneficiary []byte)
	GetRefund() uint64
	SetRefund(refund uint64)
	ReturnCode() vmcommon.ReturnCode
	SetReturnCode(returnCode vmcommon.ReturnCode)
	ReturnMessage() string
	SetReturnMessage(message string)
	ReturnData() [][]byte
	ClearReturnData()
	RemoveReturnData(index uint32)
	Finish(data []byte)
	PrependFinish(data []byte)
	DeleteFirstReturnData()
	GetVMOutput() *vmcommon.VMOutput
	RemoveNonUpdatedStorage()
	AddTxValueToAccount(address []byte, value *big.Int)
	DeployCode(input CodeDeployInput)
	CreateVMOutputInCaseOfError(err error) *vmcommon.VMOutput
}

OutputContext defines the functionality needed for interacting with the output context

func GetOutputContext

func GetOutputContext(vmHostPtr unsafe.Pointer) OutputContext

GetOutputContext returns the output context

type RuntimeContext

type RuntimeContext interface {
	StateStack

	InitStateFromContractCallInput(input *vmcommon.ContractCallInput)
	SetCustomCallFunction(callFunction string)
	GetVMInput() *vmcommon.ContractCallInput
	SetVMInput(vmInput *vmcommon.ContractCallInput)
	GetContextAddress() []byte
	SetCodeAddress(scAddress []byte)
	GetSCCode() ([]byte, error)
	GetSCCodeSize() uint64
	GetVMType() []byte
	Function() string
	Arguments() [][]byte
	GetCurrentTxHash() []byte
	GetOriginalTxHash() []byte
	ExtractCodeUpgradeFromArgs() ([]byte, []byte, error)
	SignalUserError(message string)
	FailExecution(err error)
	MustVerifyNextContractCode()
	SetRuntimeBreakpointValue(value BreakpointValue)
	GetRuntimeBreakpointValue() BreakpointValue
	GetAsyncCallInfo() *AsyncCallInfo
	SetAsyncCallInfo(asyncCallInfo *AsyncCallInfo)
	AddAsyncContextCall(contextIdentifier []byte, asyncCall *AsyncGeneratedCall) error
	GetAsyncContextInfo() *AsyncContextInfo
	GetAsyncContext(contextIdentifier []byte) (*AsyncContext, error)
	RunningInstancesCount() uint64
	IsFunctionImported(name string) bool
	ReadOnly() bool
	SetReadOnly(readOnly bool)
	StartWasmerInstance(contract []byte, gasLimit uint64, newCode bool) error
	ClearWarmInstanceCache()
	SetMaxInstanceCount(uint64)
	VerifyContractCode() error
	GetInstance() wasmer.InstanceHandler
	CallFunction(funcName string) error
	GetWarmInstance(codeHash []byte) (wasmer.InstanceHandler, bool)
	GetInstanceExports() wasmer.ExportsMap
	GetInitFunction() string
	GetFunctionToCall() (string, error)
	GetPointsUsed() uint64
	SetPointsUsed(gasPoints uint64)
	MemStore(offset int32, data []byte) error
	MemLoad(offset int32, length int32) ([]byte, error)
	MemLoadMultiple(offset int32, lengths []int32) ([][]byte, error)
	BaseOpsErrorShouldFailExecution() bool
	SyncExecAPIErrorShouldFailExecution() bool
	CryptoAPIErrorShouldFailExecution() bool
	BigIntAPIErrorShouldFailExecution() bool
	BigFloatAPIErrorShouldFailExecution() bool
	ManagedBufferAPIErrorShouldFailExecution() bool
	ExecuteAsyncCall(address []byte, data []byte, value []byte) error
	CleanInstance()
	AddError(err error, otherInfo ...string)
	GetAllErrors() error
	ReplaceInstanceBuilder(builder InstanceBuilder)
	EndExecution()
	ValidateInstances() error
}

RuntimeContext defines the functionality needed for interacting with the runtime context

func GetRuntimeContext

func GetRuntimeContext(vmHostPtr unsafe.Pointer) RuntimeContext

GetRuntimeContext returns the runtime context

type StateStack

type StateStack interface {
	InitState()
	PushState()
	PopSetActiveState()
	PopDiscard()
	ClearStateStack()
}

StateStack defines the functionality for working with a state stack

type StorageContext

type StorageContext interface {
	StateStack

	SetAddress(address []byte)
	GetStorageUpdates(address []byte) map[string]*vmcommon.StorageUpdate
	GetStorageFromAddress(address []byte, key []byte) ([]byte, bool, error)
	GetStorage(key []byte) ([]byte, bool, error)
	GetStorageUnmetered(key []byte) ([]byte, bool, error)
	SetStorage(key []byte, value []byte) (StorageStatus, error)
	SetProtectedStorage(key []byte, value []byte) (StorageStatus, error)
	UseGasForStorageLoad(tracedFunctionName string, blockChainLoadCost uint64, usedCache bool)
	IsUseDifferentGasCostFlagSet() bool
}

StorageContext defines the functionality needed for interacting with the storage context

func GetStorageContext

func GetStorageContext(vmHostPtr unsafe.Pointer) StorageContext

GetStorageContext returns the storage context

type StorageStatus

type StorageStatus int

StorageStatus defines the states the storage can be in

const (
	// StorageUnchanged signals that the storage was not changed
	StorageUnchanged StorageStatus = iota

	// StorageModified signals that the storage has been modified
	StorageModified

	// StorageAdded signals that something was added to storage
	StorageAdded

	// StorageDeleted signals that something was removed from storage
	StorageDeleted
)

type VMHost

type VMHost interface {
	vmcommon.VMExecutionHandler
	Crypto() crypto.VMCrypto
	Blockchain() BlockchainContext
	Runtime() RuntimeContext
	ManagedTypes() ManagedTypesContext
	Output() OutputContext
	Metering() MeteringContext
	Storage() StorageContext
	EnableEpochsHandler() vmcommon.EnableEpochsHandler

	ExecuteESDTTransfer(destination []byte, sender []byte, esdtTransfers []*vmcommon.ESDTTransfer, callType vm.CallType) (*vmcommon.VMOutput, uint64, error)
	CreateNewContract(input *vmcommon.ContractCreateInput) ([]byte, error)
	ExecuteOnSameContext(input *vmcommon.ContractCallInput) (*AsyncContextInfo, error)
	ExecuteOnDestContext(input *vmcommon.ContractCallInput) (*vmcommon.VMOutput, *AsyncContextInfo, error)
	GetAPIMethods() *wasmer.Imports
	IsBuiltinFunctionName(functionName string) bool
	AreInSameShard(leftAddress []byte, rightAddress []byte) bool

	GetGasScheduleMap() config.GasScheduleMap
	GetContexts() (ManagedTypesContext, BlockchainContext, MeteringContext, OutputContext, RuntimeContext, StorageContext)
	SetRuntimeContext(runtime RuntimeContext)

	SetBuiltInFunctionsContainer(builtInFuncs vmcommon.BuiltInFunctionContainer)
	InitState()

	FixOOGReturnCodeEnabled() bool
	FixFailExecutionEnabled() bool
	CreateNFTOnExecByCallerEnabled() bool
	DisableExecByCaller() bool
	CheckExecuteReadOnly() bool
	Reset()
}

VMHost defines the functionality for working with the VM

func GetVMHost

func GetVMHost(vmHostPtr unsafe.Pointer) VMHost

GetVMHost returns the vm Context from the vm context map

type VMHostParameters

type VMHostParameters struct {
	VMType                              []byte
	BlockGasLimit                       uint64
	GasSchedule                         config.GasScheduleMap
	BuiltInFuncContainer                vmcommon.BuiltInFunctionContainer
	ESDTTransferParser                  vmcommon.ESDTTransferParser
	ProtectedKeyPrefix                  []byte
	WasmerSIGSEGVPassthrough            bool
	EpochNotifier                       vmcommon.EpochNotifier
	EnableEpochsHandler                 vmcommon.EnableEpochsHandler
	Hasher                              HashComputer
	TimeOutForSCExecutionInMilliseconds uint32
}

VMHostParameters represents the parameters to be passed to VMHost

type WrappableError

type WrappableError interface {
	error

	WrapWithMessage(errMessage string) WrappableError
	WrapWithStackTrace() WrappableError
	WrapWithError(err error, otherInfo ...string) WrappableError
	GetBaseError() error
	GetLastError() error
	GetAllErrors() []error
	GetAllErrorsAndOtherInfo() ([]error, []string)

	Unwrap() error
	Is(target error) bool
}

WrappableError - an interface that extends error and represents a multi-layer error

func WrapError

func WrapError(err error, otherInfo ...string) WrappableError

WrapError constructs a WrappableError from an error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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