vmhost

package
v1.5.29 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: GPL-3.0 Imports: 25 Imported by: 4

Documentation

Overview

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

Index

Constants

View Source
const (
	// BreakpointNoneString is the human-readable name of BreakpointNone
	BreakpointNoneString = "BreakpointNone"

	// BreakpointExecutionFailedString is the human-readable name of BreakpointExecutionFailed
	BreakpointExecutionFailedString = "BreakpointExecutionFailed"

	// BreakpointAsyncCallString is the human-readable name of BreakpointAsyncCall
	BreakpointAsyncCallString = "BreakpointAsyncCall"

	// BreakpointSignalErrorString is the human-readable name of BreakpointSignalError
	BreakpointSignalErrorString = "BreakpointSignalError"

	// BreakpointOutOfGasString is the human-readable name of BreakpointOutOfGas
	BreakpointOutOfGasString = "BreakpointOutOfGas"

	// UnknownBreakpointString is the human-readable label for an unknown breakpoint value
	UnknownBreakpointString = "unknown breakpoint"

	// BackTransferString is the human-readable label for execution type
	BackTransferString = "BackTransfer"

	// DirectCallString is the human-readable label for execution type
	DirectCallString = "DirectCall"

	// ExecuteOnDestContextString is the human-readable label for execution type
	ExecuteOnDestContextString = "ExecuteOnDestContext"

	// ExecuteOnSameContextString is the human-readable label for execution type
	ExecuteOnSameContextString = "ExecuteOnSameContext"

	// AsyncCallString is the human-readable label for execution type
	AsyncCallString = "AsyncCall"

	// AsyncCallbackString is the human-readable label for execution type
	AsyncCallbackString = "AsyncCallback"

	// TransferAndExecuteString is the human-readable label for execution type
	TransferAndExecuteString = "TransferAndExecute"

	// UpgradeFromSourceString is the human-readable label for execution type
	UpgradeFromSourceString = "UpgradeFromSource"

	// TransferValueOnlyString is the human-readable label for transfer type
	TransferValueOnlyString = "transferValueOnly"

	// DeploySmartContractString is the human-readable label for transfer type
	DeploySmartContractString = "DeploySmartContract"

	// DeployFromSourceString is the human-readable label for transfer type
	DeployFromSourceString = "DeployFromSource"
)
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"

	// UpgradeFunctionName specifies if the call is an upgradeContract call
	UpgradeFunctionName = "upgradeContract"

	// ContractsUpgradeFunctionName specifies the contract's function called at upgrade
	ContractsUpgradeFunctionName = "upgrade"

	// DeleteFunctionName specifies if the call is an deleteContract call
	DeleteFunctionName = "deleteContract"
)
View Source
const (
	// MultiESDTTransferFixOnCallBackFlag defines the flag that activates the multi esdt transfer fix on callback
	MultiESDTTransferFixOnCallBackFlag core.EnableEpochFlag = "MultiESDTTransferFixOnCallBackFlag"
	// RemoveNonUpdatedStorageFlag defines the flag that activates the remove non updated storage fix
	RemoveNonUpdatedStorageFlag core.EnableEpochFlag = "RemoveNonUpdatedStorageFlag"
	// CreateNFTThroughExecByCallerFlag defines the flag that activates the create nft through exec by caller fix
	CreateNFTThroughExecByCallerFlag core.EnableEpochFlag = "CreateNFTThroughExecByCallerFlag"
	// StorageAPICostOptimizationFlag defines the flag that activates the storage api cost optimization
	StorageAPICostOptimizationFlag core.EnableEpochFlag = "StorageAPICostOptimizationFlag"
	// CheckExecuteOnReadOnlyFlag defines the flag that activates the check execute on read only
	CheckExecuteOnReadOnlyFlag core.EnableEpochFlag = "CheckExecuteOnReadOnlyFlag"
	// FailExecutionOnEveryAPIErrorFlag defines the flag that activates the fail execution on every api error
	FailExecutionOnEveryAPIErrorFlag core.EnableEpochFlag = "FailExecutionOnEveryAPIErrorFlag"
	// ManagedCryptoAPIsFlag defines the flag that activates the manage crypto apis
	ManagedCryptoAPIsFlag core.EnableEpochFlag = "ManagedCryptoAPIsFlag"
	// DisableExecByCallerFlag defines the flag that activates disable exec by caller
	DisableExecByCallerFlag core.EnableEpochFlag = "DisableExecByCallerFlag"
	// RefactorContextFlag defines the flag that activates the refactor context
	RefactorContextFlag core.EnableEpochFlag = "RefactorContextFlag"
	// RuntimeMemStoreLimitFlag defines the flag that activates the runtime mem store limit
	RuntimeMemStoreLimitFlag core.EnableEpochFlag = "RuntimeMemStoreLimitFlag"
	// RuntimeCodeSizeFixFlag defines the flag that activates the runtime code size fix
	RuntimeCodeSizeFixFlag core.EnableEpochFlag = "RuntimeCodeSizeFixFlag"
	// FixOOGReturnCodeFlag defines the flag that activates the fix oog return code
	FixOOGReturnCodeFlag core.EnableEpochFlag = "FixOOGReturnCodeFlag"
	// DynamicGasCostForDataTrieStorageLoadFlag defines the flag that activates the dynamic gas cost for data trie storage load
	DynamicGasCostForDataTrieStorageLoadFlag core.EnableEpochFlag = "DynamicGasCostForDataTrieStorageLoadFlag"
)
View Source
const AddressSize = 32

AddressSize is the size of an account address, in bytes.

View Source
const AsyncDataPrefix = "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 LegacyAsyncCallGroupID = "LegacyAsync"

LegacyAsyncCallGroupID is the AsyncCallGroup identifier reserved for the implementation of the legacy asyncCall() EEI function

View Source
const TimeLockKeyPrefix = "TIMELOCK"

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

View Source
const VMVersion = "v1.5"

VMVersion returns the current vm version

View Source
const WASMPageSize = uint32(65536)

WASMPageSize is the size in bytes of a WASM linear memory page

Variables

View Source
var (
	ErrInvalidLengthAsyncCall        = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowAsyncCall          = fmt.Errorf("proto: integer overflow")
	ErrUnexpectedEndOfGroupAsyncCall = fmt.Errorf("proto: unexpected end of group")
)
View Source
var DefaultVMType = []byte{0xF, 0xF}

DefaultVMType is an exposed value to use in tests

View Source
var ErrAccountNotFound = errors.New("account not found")

ErrAccountNotFound is an exposed value to use in tests

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 ErrAsyncCallGroupExistsAlready = errors.New("async call group exists already")

ErrAsyncCallGroupExistsAlready signals that an AsyncCallGroup with the same name already exists

View Source
var ErrAsyncCallNotFound = errors.New("async call not found")

ErrAsyncCallNotFound signals that the requested AsyncCall was not found

View Source
var ErrAsyncInit = errors.New("async context initialization error")

ErrAsyncInit signals an async context initialization error

View Source
var ErrAsyncNoCallbackForClosure = errors.New("no callback for closure, cannot call callback directly")

ErrAsyncNoCallbackForClosure signals that closure can't be obtained

View Source
var ErrAsyncNoMultiLevel = errors.New("multi-level async calls are not allowed yet")

ErrAsyncNoMultiLevel signals that no multi-level async calls are allowed

View Source
var ErrAsyncNoOutputFromCallback = errors.New("callback VMOutput should not be nil")

ErrAsyncNoOutputFromCallback signals that an error happen while producing the output of a callback

View Source
var ErrAsyncNotAllowed = errors.New("async call is not allowed at this location")

ErrAsyncNotAllowed signals that the requested AsyncCall is not allowed

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 ErrBigIntCannotBeRepresentedAsInt64 = errors.New("big int cannot be represented as int64")

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

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)", executor.ErrInvalidFunction)

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

View Source
var ErrCannotInterpretCallbackArgs = errors.New("cannot interpret callback args")

ErrCannotInterpretCallbackArgs signals that the cross-shard callback arguments are invalid

View Source
var ErrCannotUseBuiltinAsCallback = errors.New("cannot use built-in function as callback")

ErrCannotUseBuiltinAsCallback signals that the specified callback was set to a built-in function, which is forbidden

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 ErrContextCallbackDisabled = errors.New("context callback disabled")

ErrContextCallbackDisabled signals that group callbacks cannot be set nor executed

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 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)", executor.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 ErrInvalidFunctionName = fmt.Errorf("%w (invalid name)", executor.ErrInvalidFunction)

ErrInvalidFunctionName signals that the function name is invalid

View Source
var ErrInvalidGasProvided = errors.New("invalid gas provided")

ErrInvalidGasProvided signals that an unacceptable GasProvided value was specified

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 ErrLegacyAsyncCallInvalid = errors.New("legacy async call invalid")

ErrLegacyAsyncCallInvalid signals that the legacy async call is invalid

View Source
var ErrLegacyAsyncCallNotFound = errors.New("legacy async call not found")

ErrLegacyAsyncCallNotFound signals that a legacy async call was expected, but is missing

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 ErrNilCallArgsParser = errors.New("nil call args parser")

ErrNilCallArgsParser signals that nil call arguments parser 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 ErrNilDestinationCallVMOutput = errors.New("nil destination call VMOutput")

ErrNilDestinationCallVMOutput signals that the destination call execution returned a nil VMOutput

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 ErrNilExecutor = errors.New("nil Executor")

ErrNilExecutor signals that the provided Executor is nil

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

ErrNilHasher signals that the provided Hasher is nil

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

ErrNilHostParameters signals that nil host parameters was provided

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

ErrNilVMHost signals that the provided VMHost is nil

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

ErrNilVMType signals that the provided VMType is nil

View Source
var ErrNoAsyncParentContext = errors.New("this should not be called for async calls (only callbacks and direct calls)")

ErrNoAsyncParentContext signals that load parent was called for an async call

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 ErrNoManagedMapUnderThisHandle = errors.New("no managed map under the given handle")

ErrNoManagedMapUnderThisHandle signals that there is no buffer for the given handle

View Source
var ErrNoStoredAsyncContextFound = errors.New("no async context found in storage")

ErrNoStoredAsyncContextFound signals that no persisted data was found for the AsyncContext to load

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 ErrOnlyOneLegacyAsyncCallAllowed = errors.New("only one legacy async call allowed")

ErrOnlyOneLegacyAsyncCallAllowed signals that there was an attempt to create more than one legacy async calls, which is forbidden

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 ErrUnknownCallType = errors.New("unknown call type")

ErrUnknownCallType signals that the call type is not recognized

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 ParentAddress = MakeTestSCAddress("parentSC")

ParentAddress is an exposed value to use in tests

View Source
var SCAddressPrefix = []byte("\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x0f")

SCAddressPrefix is the prefix of any smart contract address used for testing.

View Source
var SerializableAsyncCallExecutionMode_name = map[int32]string{
	0: "SerializableSyncExecution",
	1: "SerializableAsyncBuiltinFuncIntraShard",
	2: "SerializableAsyncBuiltinFuncCrossShard",
	3: "SerializableAsyncUnknown",
}
View Source
var SerializableAsyncCallExecutionMode_value = map[string]int32{
	"SerializableSyncExecution":              0,
	"SerializableAsyncBuiltinFuncIntraShard": 1,
	"SerializableAsyncBuiltinFuncCrossShard": 2,
	"SerializableAsyncUnknown":               3,
}
View Source
var SerializableAsyncCallStatus_name = map[int32]string{
	0: "SerializableAsyncCallPending",
	1: "SerializableAsyncCallResolved",
	2: "SerializableAsyncCallRejected",
}
View Source
var SerializableAsyncCallStatus_value = map[string]int32{
	"SerializableAsyncCallPending":  0,
	"SerializableAsyncCallResolved": 1,
	"SerializableAsyncCallRejected": 2,
}
View Source
var UserAddress = []byte("userAccount.....................")

UserAddress is an exposed value to use in tests

View Source
var Zero = big.NewInt(0)

Zero is the big integer 0

Functions

func AddArgument

func AddArgument(input *vmcommon.ContractCallInput, argument []byte)

AddArgument adds the provided argument to the ContractCallInput

func AddFinishData

func AddFinishData(vmOutput *vmcommon.VMOutput, data []byte)

AddFinishData appends the provided []byte to the ReturnData of the given vmOutput

func AddNewOutputAccount

func AddNewOutputAccount(vmOutput *vmcommon.VMOutput, address []byte, balanceDelta int64, data []byte) *vmcommon.OutputAccount

AddNewOutputAccount creates a new vmcommon.OutputAccount from the provided arguments and adds it to OutputAccounts of the provided vmOutput

func AddNewOutputAccountWithSender

func AddNewOutputAccountWithSender(vmOutput *vmcommon.VMOutput, address []byte, senderAddress []byte, balanceDelta int64, data []byte) *vmcommon.OutputAccount

AddNewOutputAccountWithSender creates a new vmcommon.OutputAccount from the provided arguments and adds it to OutputAccounts of the provided vmOutput

func BooleanToInt

func BooleanToInt(b bool) int

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

func CopyTxHashes

func CopyTxHashes(input *vmcommon.ContractCallInput, sourceInput *vmcommon.ContractCallInput)

CopyTxHashes copies the tx hashes from a source ContractCallInput into another

func CustomStorageKey

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

CustomStorageKey generates a storage key of a specific type.

func DefaultTestContractCallInput

func DefaultTestContractCallInput() *vmcommon.ContractCallInput

DefaultTestContractCallInput creates a vmcommon.ContractCallInput struct with default values.

func DisableLoggingForTests

func DisableLoggingForTests()

DisableLoggingForTests sets log level to *:NONE

func GetSCCode

func GetSCCode(fileName string) []byte

GetSCCode retrieves the bytecode of a WASM module from a file.

func GetTestSCCode

func GetTestSCCode(scName string, prefixToTestSCs string) []byte

GetTestSCCode retrieves the bytecode of a WASM testing module.

func GuardedGetBytesSlice

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

GuardedGetBytesSlice extracts a subslice from a given slice, guarding against overstepping the bounds.

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 order of a byte slice.

func MakeContractCallInput

func MakeContractCallInput(
	caller []byte,
	recipient []byte,
	function string,
	value int,
) *vmcommon.ContractCallInput

MakeContractCallInput creates a ContractCallInput and sets the provided arguments

func MakeEmptyContractCallInput

func MakeEmptyContractCallInput() *vmcommon.ContractCallInput

MakeEmptyContractCallInput instantiates an empty ContractCallInput

func MakeEmptyVMOutput

func MakeEmptyVMOutput() *vmcommon.VMOutput

MakeEmptyVMOutput creates a vmcommon.VMOutput struct with default values

func MakeTestSCAddress

func MakeTestSCAddress(identifier string) []byte

MakeTestSCAddress generates a new smart contract address to be used for testing based on the given identifier.

func PadBytesLeft

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

PadBytesLeft adds a specified number of zeros to the left of a byte slice.

func SetCallParties

func SetCallParties(input *vmcommon.ContractCallInput, caller []byte, recipient []byte)

SetCallParties sets the caller and recipient of the given ContractCallInput

func SetLoggingForTests

func SetLoggingForTests()

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

func SetLoggingForTestsWithLogger

func SetLoggingForTestsWithLogger(loggerName string)

SetLoggingForTestsWithLogger configures the logger package with a certain logger

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

Types

type AsyncCall

type AsyncCall struct {
	CallID        []byte
	Status        AsyncCallStatus
	ExecutionMode AsyncCallExecutionMode

	Destination []byte
	Data        []byte
	GasLimit    uint64
	GasLocked   uint64

	ValueBytes      []byte
	SuccessCallback string
	ErrorCallback   string

	CallbackClosure []byte

	IsBuiltinFunctionCall bool
}

AsyncCall holds the information about an individual async call

func (*AsyncCall) Clone

func (ac *AsyncCall) Clone() *AsyncCall

Clone creates a deep clone of the AsyncCall

func (*AsyncCall) GetCallbackName

func (ac *AsyncCall) GetCallbackName() string

GetCallbackName returns the name of the callback to execute, depending on the status of the async call

func (*AsyncCall) GetData

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

GetData returns the transaction data of the async call

func (*AsyncCall) GetDestination

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

GetDestination returns the destination of an async call

func (*AsyncCall) GetGasLimit

func (ac *AsyncCall) GetGasLimit() uint64

GetGasLimit returns the gas limit of the current async call

func (*AsyncCall) GetGasLocked

func (ac *AsyncCall) GetGasLocked() uint64

GetGasLocked returns the gas locked for the async callback

func (*AsyncCall) GetIdentifier

func (ac *AsyncCall) GetIdentifier() []byte

GetIdentifier returns the identifier of an async call

func (*AsyncCall) GetTotalGas

func (ac *AsyncCall) GetTotalGas() uint64

GetTotalGas returns the sum of the gas limit and gas locked

func (*AsyncCall) GetValue

func (ac *AsyncCall) GetValue() []byte

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

func (*AsyncCall) HasCallback

func (ac *AsyncCall) HasCallback() bool

HasCallback returns true if there is a callback to execute, depending on the status of the async call

func (*AsyncCall) HasDefinedAnyCallback

func (ac *AsyncCall) HasDefinedAnyCallback() bool

HasDefinedAnyCallback returns true if this AsyncCall defines at least one non-empty callback name

func (*AsyncCall) IsInterfaceNil

func (ac *AsyncCall) IsInterfaceNil() bool

IsInterfaceNil returns true if there is no value under the interface

func (*AsyncCall) IsLocal

func (ac *AsyncCall) IsLocal() bool

IsLocal returns true if the async call allows for local execution

func (*AsyncCall) IsRemote

func (ac *AsyncCall) IsRemote() bool

IsRemote returns true if the async call must be sent remotely

func (*AsyncCall) Reject

func (ac *AsyncCall) Reject()

Reject sets the rejected status for this async call

func (*AsyncCall) UpdateStatus

func (ac *AsyncCall) UpdateStatus(returnCode vmcommon.ReturnCode)

UpdateStatus sets the status of the async call depending on the provided ReturnCode

type AsyncCallExecutionMode

type AsyncCallExecutionMode uint

AsyncCallExecutionMode encodes the execution modes of an AsyncCall

const (
	// SyncExecution indicates that the async call can be executed synchronously,
	// with its corresponding callback
	SyncExecution 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 AsyncCallGroup

type AsyncCallGroup struct {
	Callback     string
	GasLocked    uint64
	CallbackData []byte
	Identifier   string
	AsyncCalls   []*AsyncCall
}

AsyncCallGroup is a structure containing a group of async calls and a callback that should be called when all these async calls are resolved

func FromSerializableAsyncCallGroups

func FromSerializableAsyncCallGroups(serializableAsyncCallGroups []*SerializableAsyncCallGroup) []*AsyncCallGroup

FromSerializableAsyncCallGroups - deserialize all call groups from protobuf

func NewAsyncCallGroup

func NewAsyncCallGroup(identifier string) *AsyncCallGroup

NewAsyncCallGroup creates a new instance of AsyncCallGroup

func (*AsyncCallGroup) AddAsyncCall

func (acg *AsyncCallGroup) AddAsyncCall(call *AsyncCall)

AddAsyncCall adds a given AsyncCall to the AsyncCallGroup

func (*AsyncCallGroup) Clone

func (acg *AsyncCallGroup) Clone() *AsyncCallGroup

Clone creates a deep clone of the AsyncCallGroup

func (*AsyncCallGroup) DeleteAsyncCall

func (acg *AsyncCallGroup) DeleteAsyncCall(index int)

DeleteAsyncCall removes an AsyncCall from this AsyncCallGroup, given its index

func (*AsyncCallGroup) DeleteCompletedAsyncCalls

func (acg *AsyncCallGroup) DeleteCompletedAsyncCalls()

DeleteCompletedAsyncCalls removes all completed AsyncCalls, keeping only those with status AsyncCallPending

func (*AsyncCallGroup) FindByDestination

func (acg *AsyncCallGroup) FindByDestination(destination []byte) (int, bool)

FindByDestination returns the index of an AsyncCall in this AsyncCallGroup that matches the provided destination

func (*AsyncCallGroup) HasCallback

func (acg *AsyncCallGroup) HasCallback() bool

HasCallback verifies whether a callback function has been set for this AsyncCallGroup

func (*AsyncCallGroup) HasPendingCalls

func (acg *AsyncCallGroup) HasPendingCalls() bool

HasPendingCalls verifies whether the AsyncCallGroup has any AsyncCalls left to return from the destination call

func (*AsyncCallGroup) IsComplete

func (acg *AsyncCallGroup) IsComplete() bool

IsComplete verifies whether all AsyncCalls have been completed

func (*AsyncCallGroup) IsInterfaceNil

func (acg *AsyncCallGroup) IsInterfaceNil() bool

IsInterfaceNil returns true if there is no value under the interface

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 AsyncCallLocation

type AsyncCallLocation interface {
	GetAsyncCall() *AsyncCall
	GetGroupIndex() int
	GetCallIndex() int
	GetError() error
}

AsyncCallLocation defines the functionality for async calls

type AsyncCallStatus

type AsyncCallStatus uint8

AsyncCallStatus represents the different status an async call can have

type AsyncContext

type AsyncContext interface {
	StateStack

	InitStateFromInput(input *vmcommon.ContractCallInput) error
	HasPendingCallGroups() bool
	IsComplete() bool
	GetCallGroup(groupID string) (*AsyncCallGroup, bool)
	SetContextCallback(callbackName string, data []byte, gas uint64) error
	HasCallback() bool
	GetCallerAddress() []byte
	GetParentAddress() []byte
	GetCallerCallID() []byte
	GetReturnData() []byte
	SetReturnData(data []byte)

	Execute() error
	RegisterAsyncCall(groupID string, call *AsyncCall) error
	RegisterLegacyAsyncCall(address []byte, data []byte, value []byte) error

	LoadParentContext() error
	Save() error
	DeleteFromCallID(address []byte) error

	GetCallID() []byte
	GetCallbackAsyncInitiatorCallID() []byte
	IsCrossShard() bool

	Clone() AsyncContext

	UpdateCurrentAsyncCallStatus(
		address []byte,
		callID []byte,
		vmInput *vmcommon.VMInput) (*AsyncCall, bool, error)

	CompleteChildConditional(isChildComplete bool, callID []byte, gasToAccumulate uint64) error
	NotifyChildIsComplete(callID []byte, gasToAccumulate uint64) error

	SetResults(vmOutput *vmcommon.VMOutput)
	GetGasAccumulated() uint64

	SetAsyncArgumentsForCall(input *vmcommon.ContractCallInput)
	SetAsyncArgumentsForCallback(
		input *vmcommon.ContractCallInput,
		asyncCall *AsyncCall,
		gasAccumulated uint64)

	HasLegacyGroup() bool

	SetCallbackParentCall(asyncCall *AsyncCall)
	GetCallbackClosure() ([]byte, error)

	GetAsyncCallByCallID(callID []byte) AsyncCallLocation
	LoadParentContextFromStackOrStorage() (AsyncContext, error)
	ExecuteSyncCallbackAndFinishOutput(
		asyncCall *AsyncCall,
		vmOutput *vmcommon.VMOutput,
		destinationCallInput *vmcommon.ContractCallInput,
		gasAccumulated uint64,
		err error) (bool, *vmcommon.VMOutput)

	/*
		for tests / test framework usage
	*/
	SetCallID(callID []byte)
	SetCallIDForCallInGroup(groupIndex int, callIndex int, callID []byte)
}

AsyncContext defines the functionality needed for interacting with the asynchronous execution context

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 uint64) []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()
	ExecuteSmartContractCallOnOtherVM(input *vmcommon.ContractCallInput) (*vmcommon.VMOutput, error)
}

BlockchainContext defines the functionality needed for interacting with 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
)

func (BreakpointValue) String

func (b BreakpointValue) String() string

String returns the human-readable name of a BreakpointValue

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 ContractCallInputBuilder

type ContractCallInputBuilder struct {
	vmcommon.ContractCallInput
}

ContractCallInputBuilder extends a ContractCallInput for extra building functionality during testing

func CreateTestContractCallInputBuilder

func CreateTestContractCallInputBuilder() *ContractCallInputBuilder

CreateTestContractCallInputBuilder is a builder for ContractCallInputBuilder

func (*ContractCallInputBuilder) Build

func (contractInput *ContractCallInputBuilder) Build() *vmcommon.ContractCallInput

Build completes the build of a ContractCallInput

func (*ContractCallInputBuilder) WithArguments

func (contractInput *ContractCallInputBuilder) WithArguments(arguments ...[]byte) *ContractCallInputBuilder

WithArguments provides the arguments to be called for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithCallType

func (contractInput *ContractCallInputBuilder) WithCallType(callType vm.CallType) *ContractCallInputBuilder

WithCallType provides the arguments to be called for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithCallerAddr

func (contractInput *ContractCallInputBuilder) WithCallerAddr(address []byte) *ContractCallInputBuilder

WithCallerAddr provides the caller address of ContractCallInputBuilder

func (*ContractCallInputBuilder) WithCurrentTxHash

func (contractInput *ContractCallInputBuilder) WithCurrentTxHash(txHash []byte) *ContractCallInputBuilder

WithCurrentTxHash provides the CurrentTxHash for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithESDTTokenName

func (contractInput *ContractCallInputBuilder) WithESDTTokenName(esdtTokenName []byte) *ContractCallInputBuilder

WithESDTTokenName provides the ESDTTokenName for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithESDTValue

func (contractInput *ContractCallInputBuilder) WithESDTValue(esdtValue *big.Int) *ContractCallInputBuilder

WithESDTValue provides the ESDTValue for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithFunction

func (contractInput *ContractCallInputBuilder) WithFunction(function string) *ContractCallInputBuilder

WithFunction provides the function to be called for ContractCallInputBuilder

func (*ContractCallInputBuilder) WithGasProvided

func (contractInput *ContractCallInputBuilder) WithGasProvided(gas uint64) *ContractCallInputBuilder

WithGasProvided provides the gas of ContractCallInputBuilder

func (*ContractCallInputBuilder) WithRecipientAddr

func (contractInput *ContractCallInputBuilder) WithRecipientAddr(address []byte) *ContractCallInputBuilder

WithRecipientAddr provides the recepient address of ContractCallInputBuilder

type ContractCreateInputBuilder

type ContractCreateInputBuilder struct {
	vmcommon.ContractCreateInput
}

ContractCreateInputBuilder extends a ContractCreateInput for extra building functionality during testing

func (*ContractCreateInputBuilder) Build

Build completes the build of a ContractCreateInput

func (*ContractCreateInputBuilder) WithArguments

func (contractInput *ContractCreateInputBuilder) WithArguments(arguments ...[]byte) *ContractCreateInputBuilder

WithArguments provides the Arguments for a ContractCreateInputBuilder

func (*ContractCreateInputBuilder) WithCallValue

func (contractInput *ContractCreateInputBuilder) WithCallValue(callValue int64) *ContractCreateInputBuilder

WithCallValue provides the CallValue for a ContractCreateInputBuilder

func (*ContractCreateInputBuilder) WithCallerAddr

func (contractInput *ContractCreateInputBuilder) WithCallerAddr(address []byte) *ContractCreateInputBuilder

WithCallerAddr provides the CallerAddr for a ContractCreateInputBuilder

func (*ContractCreateInputBuilder) WithContractCode

func (contractInput *ContractCreateInputBuilder) WithContractCode(code []byte) *ContractCreateInputBuilder

WithContractCode provides the ContractCode for a ContractCreateInputBuilder

func (*ContractCreateInputBuilder) WithGasProvided

func (contractInput *ContractCreateInputBuilder) WithGasProvided(gas uint64) *ContractCreateInputBuilder

WithGasProvided provides the GasProvided for a ContractCreateInputBuilder

type ESDTTransfersArgs

type ESDTTransfersArgs struct {
	Destination    []byte
	OriginalCaller []byte
	Sender         []byte
	Transfers      []*vmcommon.ESDTTransfer
	Function       string
	Arguments      [][]byte
}

ESDTTransfersArgs defines the structure for ESDTTransferArgs, used in TransferAndExecute

type EnableEpochsHandler added in v1.5.11

type EnableEpochsHandler interface {
	IsFlagDefined(flag core.EnableEpochFlag) bool
	IsFlagEnabled(flag core.EnableEpochFlag) bool
	IsFlagEnabledInEpoch(flag core.EnableEpochFlag, epoch uint32) bool
	GetActivationEpoch(flag core.EnableEpochFlag) uint32
	IsInterfaceNil() bool
}

EnableEpochsHandler is used to verify which flags are set in a specific epoch based on EnableEpochs config

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 InstanceTracker

type InstanceTracker interface {
	StateStack

	TrackedInstances() map[string]executor.Instance
}

InstanceTracker defines the functionality needed for interacting with the instance tracker

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)
	NewManagedMap() int32
	ManagedMapPut(mMapHandle int32, keyHandle int32, valueHandle int32) error
	ManagedMapGet(mMapHandle int32, keyHandle int32, outValueHandle int32) error
	ManagedMapRemove(mMapHandle int32, keyHandle int32, outValueHandle int32) error
	ManagedMapContains(mMapHandle int32, keyHandle int32) (bool, error)
	GetBackTransfers() ([]*vmcommon.ESDTTransfer, *big.Int)
	AddValueOnlyBackTransfer(value *big.Int)
	AddBackTransfers(transfers []*vmcommon.ESDTTransfer)
	PopBackTransferIfAsyncCallBack(vmInput *vmcommon.ContractCallInput)
}

ManagedTypesContext defines the functionality needed for interacting with 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)
	UseGasBoundedAndAddTracedGas(functionName string, gas uint64) error
	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
	ComputeExtraGasLockedForAsync() uint64
	UseGasForAsyncStep() error
	UseGasBounded(gasToUse uint64) error
	GetGasLocked() uint64
	UpdateGasStateOnSuccess(vmOutput *vmcommon.VMOutput) error
	UpdateGasStateOnFailure(vmOutput *vmcommon.VMOutput)
	TrackGasUsedByOutOfVMFunction(builtinInput *vmcommon.ContractCallInput, builtinOutput *vmcommon.VMOutput, postBuiltinInput *vmcommon.ContractCallInput)
	DisableRestoreGas()
	EnableRestoreGas()
	StartGasTracing(functionName string)
	SetGasTracing(enableGasTracing bool)
	GetGasTrace() map[string]map[string][]uint64
}

MeteringContext defines the functionality needed for interacting with the metering context

type OldAsyncContext

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

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

that should be called when all these async calls are resolved

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)
	WriteLogWithIdentifier(address []byte, topics [][]byte, data [][]byte, identifier []byte)
	TransferValueOnly(destination []byte, sender []byte, value *big.Int, checkPayable bool) error
	Transfer(destination []byte, sender []byte, gasLimit uint64, gasLocked uint64, value *big.Int, asyncData []byte, input []byte, callType vm.CallType) error
	TransferESDT(transfersArgs *ESDTTransfersArgs, callInput *vmcommon.ContractCallInput) (uint64, error)
	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
	NextOutputTransferIndex() uint32
	GetCrtTransferIndex() uint32
	SetCrtTransferIndex(index uint32)
	IsInterfaceNil() bool
}

OutputContext defines the functionality needed for interacting with the output context

type RuntimeContext

type RuntimeContext interface {
	StateStack

	GetVMExecutor() executor.Executor
	ReplaceVMExecutor(vmExecutor executor.Executor)
	InitStateFromContractCallInput(input *vmcommon.ContractCallInput)
	SetCustomCallFunction(callFunction string)
	GetVMInput() *vmcommon.ContractCallInput
	SetVMInput(vmInput *vmcommon.ContractCallInput)
	GetContextAddress() []byte
	GetOriginalCallerAddress() []byte
	SetCodeAddress(scAddress []byte)
	GetSCCode() ([]byte, error)
	GetSCCodeSize() uint64
	GetVMType() []byte
	FunctionName() string
	Arguments() [][]byte
	GetCurrentTxHash() []byte
	GetOriginalTxHash() []byte
	ExtractCodeUpgradeFromArgs() ([]byte, []byte, error)
	SignalUserError(message string)
	FailExecution(err error)
	MustVerifyNextContractCode()
	SetRuntimeBreakpointValue(value BreakpointValue)
	GetRuntimeBreakpointValue() BreakpointValue
	GetInstanceStackSize() uint64
	CountSameContractInstancesOnStack(address []byte) uint64
	IsFunctionImported(name string) bool
	ReadOnly() bool
	SetReadOnly(readOnly bool)
	StartWasmerInstance(contract []byte, gasLimit uint64, newCode bool) error
	ClearWarmInstanceCache()
	SetMaxInstanceStackSize(uint64)
	VerifyContractCode() error
	GetInstance() executor.Instance
	GetInstanceTracker() InstanceTracker
	FunctionNameChecked() (string, error)
	CallSCFunction(functionName string) error
	GetPointsUsed() uint64
	SetPointsUsed(gasPoints uint64)
	BaseOpsErrorShouldFailExecution() bool
	SyncExecAPIErrorShouldFailExecution() bool
	CryptoAPIErrorShouldFailExecution() bool
	BigIntAPIErrorShouldFailExecution() bool
	BigFloatAPIErrorShouldFailExecution() bool
	ManagedBufferAPIErrorShouldFailExecution() bool
	ManagedMapAPIErrorShouldFailExecution() bool
	CleanInstance()

	AddError(err error, otherInfo ...string)
	GetAllErrors() error

	ValidateCallbackName(callbackName string) error
	HasFunction(functionName string) bool
	GetPrevTxHash() []byte
	EndExecution()
	ValidateInstances() error
}

RuntimeContext defines the functionality needed for interacting with the runtime context

type SerializableAsyncCall

type SerializableAsyncCall struct {
	CallID          []byte                             `protobuf:"bytes,1,opt,name=CallID,proto3" json:"CallID,omitempty"`
	Status          SerializableAsyncCallStatus        `protobuf:"varint,2,opt,name=Status,proto3,enum=vmhost.SerializableAsyncCallStatus" json:"Status,omitempty"`
	ExecutionMode   SerializableAsyncCallExecutionMode `` /* 127-byte string literal not displayed */
	Destination     []byte                             `protobuf:"bytes,5,opt,name=Destination,proto3" json:"Destination,omitempty"`
	Data            []byte                             `protobuf:"bytes,6,opt,name=Data,proto3" json:"Data,omitempty"`
	GasLimit        uint64                             `protobuf:"varint,7,opt,name=GasLimit,proto3" json:"GasLimit,omitempty"`
	GasLocked       uint64                             `protobuf:"varint,8,opt,name=GasLocked,proto3" json:"GasLocked,omitempty"`
	ValueBytes      []byte                             `protobuf:"bytes,9,opt,name=ValueBytes,proto3" json:"ValueBytes,omitempty"`
	SuccessCallback string                             `protobuf:"bytes,10,opt,name=SuccessCallback,proto3" json:"SuccessCallback,omitempty"`
	ErrorCallback   string                             `protobuf:"bytes,11,opt,name=ErrorCallback,proto3" json:"ErrorCallback,omitempty"`
	CallbackClosure []byte                             `protobuf:"bytes,12,opt,name=CallbackClosure,proto3" json:"CallbackClosure,omitempty"`
}

func (*SerializableAsyncCall) Descriptor

func (*SerializableAsyncCall) Descriptor() ([]byte, []int)

func (*SerializableAsyncCall) Equal

func (this *SerializableAsyncCall) Equal(that interface{}) bool

func (*SerializableAsyncCall) GetCallID

func (m *SerializableAsyncCall) GetCallID() []byte

func (*SerializableAsyncCall) GetCallbackClosure

func (m *SerializableAsyncCall) GetCallbackClosure() []byte

func (*SerializableAsyncCall) GetData

func (m *SerializableAsyncCall) GetData() []byte

func (*SerializableAsyncCall) GetDestination

func (m *SerializableAsyncCall) GetDestination() []byte

func (*SerializableAsyncCall) GetErrorCallback

func (m *SerializableAsyncCall) GetErrorCallback() string

func (*SerializableAsyncCall) GetExecutionMode

func (*SerializableAsyncCall) GetGasLimit

func (m *SerializableAsyncCall) GetGasLimit() uint64

func (*SerializableAsyncCall) GetGasLocked

func (m *SerializableAsyncCall) GetGasLocked() uint64

func (*SerializableAsyncCall) GetStatus

func (*SerializableAsyncCall) GetSuccessCallback

func (m *SerializableAsyncCall) GetSuccessCallback() string

func (*SerializableAsyncCall) GetValueBytes

func (m *SerializableAsyncCall) GetValueBytes() []byte

func (*SerializableAsyncCall) GoString

func (this *SerializableAsyncCall) GoString() string

func (*SerializableAsyncCall) Marshal

func (m *SerializableAsyncCall) Marshal() (dAtA []byte, err error)

func (*SerializableAsyncCall) MarshalTo

func (m *SerializableAsyncCall) MarshalTo(dAtA []byte) (int, error)

func (*SerializableAsyncCall) MarshalToSizedBuffer

func (m *SerializableAsyncCall) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*SerializableAsyncCall) ProtoMessage

func (*SerializableAsyncCall) ProtoMessage()

func (*SerializableAsyncCall) Reset

func (m *SerializableAsyncCall) Reset()

func (*SerializableAsyncCall) Size

func (m *SerializableAsyncCall) Size() (n int)

func (*SerializableAsyncCall) String

func (this *SerializableAsyncCall) String() string

func (*SerializableAsyncCall) Unmarshal

func (m *SerializableAsyncCall) Unmarshal(dAtA []byte) error

func (*SerializableAsyncCall) XXX_DiscardUnknown

func (m *SerializableAsyncCall) XXX_DiscardUnknown()

func (*SerializableAsyncCall) XXX_Marshal

func (m *SerializableAsyncCall) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*SerializableAsyncCall) XXX_Merge

func (m *SerializableAsyncCall) XXX_Merge(src proto.Message)

func (*SerializableAsyncCall) XXX_Size

func (m *SerializableAsyncCall) XXX_Size() int

func (*SerializableAsyncCall) XXX_Unmarshal

func (m *SerializableAsyncCall) XXX_Unmarshal(b []byte) error

type SerializableAsyncCallExecutionMode

type SerializableAsyncCallExecutionMode int32
const (
	SerializableSyncExecution              SerializableAsyncCallExecutionMode = 0
	SerializableAsyncBuiltinFuncIntraShard SerializableAsyncCallExecutionMode = 1
	SerializableAsyncBuiltinFuncCrossShard SerializableAsyncCallExecutionMode = 2
	SerializableAsyncUnknown               SerializableAsyncCallExecutionMode = 3
)

func (SerializableAsyncCallExecutionMode) EnumDescriptor

func (SerializableAsyncCallExecutionMode) EnumDescriptor() ([]byte, []int)

func (SerializableAsyncCallExecutionMode) String

type SerializableAsyncCallGroup

type SerializableAsyncCallGroup struct {
	Callback     string                   `protobuf:"bytes,1,opt,name=Callback,proto3" json:"Callback,omitempty"`
	GasLocked    uint64                   `protobuf:"varint,2,opt,name=GasLocked,proto3" json:"GasLocked,omitempty"`
	CallbackData []byte                   `protobuf:"bytes,3,opt,name=CallbackData,proto3" json:"CallbackData,omitempty"`
	Identifier   string                   `protobuf:"bytes,4,opt,name=Identifier,proto3" json:"Identifier,omitempty"`
	AsyncCalls   []*SerializableAsyncCall `protobuf:"bytes,5,rep,name=AsyncCalls,proto3" json:"AsyncCalls,omitempty"`
}

func ToSerializableAsyncCallGroups

func ToSerializableAsyncCallGroups(asyncCallGroups []*AsyncCallGroup) []*SerializableAsyncCallGroup

ToSerializableAsyncCallGroups serializes all call groups to protobuf

func (*SerializableAsyncCallGroup) Descriptor

func (*SerializableAsyncCallGroup) Descriptor() ([]byte, []int)

func (*SerializableAsyncCallGroup) Equal

func (this *SerializableAsyncCallGroup) Equal(that interface{}) bool

func (*SerializableAsyncCallGroup) GetAsyncCalls

func (m *SerializableAsyncCallGroup) GetAsyncCalls() []*SerializableAsyncCall

func (*SerializableAsyncCallGroup) GetCallback

func (m *SerializableAsyncCallGroup) GetCallback() string

func (*SerializableAsyncCallGroup) GetCallbackData

func (m *SerializableAsyncCallGroup) GetCallbackData() []byte

func (*SerializableAsyncCallGroup) GetGasLocked

func (m *SerializableAsyncCallGroup) GetGasLocked() uint64

func (*SerializableAsyncCallGroup) GetIdentifier

func (m *SerializableAsyncCallGroup) GetIdentifier() string

func (*SerializableAsyncCallGroup) GoString

func (this *SerializableAsyncCallGroup) GoString() string

func (*SerializableAsyncCallGroup) Marshal

func (m *SerializableAsyncCallGroup) Marshal() (dAtA []byte, err error)

func (*SerializableAsyncCallGroup) MarshalTo

func (m *SerializableAsyncCallGroup) MarshalTo(dAtA []byte) (int, error)

func (*SerializableAsyncCallGroup) MarshalToSizedBuffer

func (m *SerializableAsyncCallGroup) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*SerializableAsyncCallGroup) ProtoMessage

func (*SerializableAsyncCallGroup) ProtoMessage()

func (*SerializableAsyncCallGroup) Reset

func (m *SerializableAsyncCallGroup) Reset()

func (*SerializableAsyncCallGroup) Size

func (m *SerializableAsyncCallGroup) Size() (n int)

func (*SerializableAsyncCallGroup) String

func (this *SerializableAsyncCallGroup) String() string

func (*SerializableAsyncCallGroup) Unmarshal

func (m *SerializableAsyncCallGroup) Unmarshal(dAtA []byte) error

func (*SerializableAsyncCallGroup) XXX_DiscardUnknown

func (m *SerializableAsyncCallGroup) XXX_DiscardUnknown()

func (*SerializableAsyncCallGroup) XXX_Marshal

func (m *SerializableAsyncCallGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*SerializableAsyncCallGroup) XXX_Merge

func (m *SerializableAsyncCallGroup) XXX_Merge(src proto.Message)

func (*SerializableAsyncCallGroup) XXX_Size

func (m *SerializableAsyncCallGroup) XXX_Size() int

func (*SerializableAsyncCallGroup) XXX_Unmarshal

func (m *SerializableAsyncCallGroup) XXX_Unmarshal(b []byte) error

type SerializableAsyncCallStatus

type SerializableAsyncCallStatus int32
const (
	SerializableAsyncCallPending  SerializableAsyncCallStatus = 0
	SerializableAsyncCallResolved SerializableAsyncCallStatus = 1
	SerializableAsyncCallRejected SerializableAsyncCallStatus = 2
)

func (SerializableAsyncCallStatus) EnumDescriptor

func (SerializableAsyncCallStatus) EnumDescriptor() ([]byte, []int)

func (SerializableAsyncCallStatus) String

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, uint32, bool, error)
	GetStorageFromAddressNoChecks(address []byte, key []byte) ([]byte, uint32, bool, error)
	GetStorage(key []byte) ([]byte, uint32, bool, error)
	GetStorageUnmetered(key []byte) ([]byte, uint32, bool, error)
	SetStorage(key []byte, value []byte) (StorageStatus, error)
	SetProtectedStorage(key []byte, value []byte) (StorageStatus, error)
	SetProtectedStorageToAddress(address []byte, key []byte, value []byte) (StorageStatus, error)
	SetProtectedStorageToAddressUnmetered(address []byte, key []byte, value []byte) (StorageStatus, error)
	UseGasForStorageLoad(tracedFunctionName string, trieDepth int64, blockchainLoadCost uint64, usedCache bool) error
	IsUseDifferentGasCostFlagSet() bool
	GetVmProtectedPrefix(prefix string) []byte
}

StorageContext defines the functionality needed for interacting with 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
	Async() AsyncContext
	ManagedTypes() ManagedTypesContext
	Output() OutputContext
	Metering() MeteringContext
	Storage() StorageContext
	EnableEpochsHandler() EnableEpochsHandler

	ExecuteESDTTransfer(transfersArgs *ESDTTransfersArgs, callType vm.CallType) (*vmcommon.VMOutput, uint64, error)
	CreateNewContract(input *vmcommon.ContractCreateInput, createContractCallType int) ([]byte, error)
	ExecuteOnSameContext(input *vmcommon.ContractCallInput) error
	ExecuteOnDestContext(input *vmcommon.ContractCallInput) (*vmcommon.VMOutput, bool, error)
	IsBuiltinFunctionName(functionName string) bool
	IsBuiltinFunctionCall(data []byte) bool
	AreInSameShard(leftAddress []byte, rightAddress []byte) bool

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

	SetBuiltInFunctionsContainer(builtInFuncs vmcommon.BuiltInFunctionContainer)
	InitState()

	CompleteLogEntriesWithCallType(vmOutput *vmcommon.VMOutput, callType string)

	Reset()
	SetGasTracing(enableGasTracing bool)
	GetGasTrace() map[string]map[string][]uint64
}

VMHost defines the functionality for working with the VM

type VMHostParameters

type VMHostParameters struct {
	VMType                              []byte
	OverrideVMExecutor                  executor.ExecutorAbstractFactory
	BlockGasLimit                       uint64
	GasSchedule                         config.GasScheduleMap
	BuiltInFuncContainer                vmcommon.BuiltInFunctionContainer
	ESDTTransferParser                  vmcommon.ESDTTransferParser
	ProtectedKeyPrefix                  []byte
	WasmerSIGSEGVPassthrough            bool
	EpochNotifier                       vmcommon.EpochNotifier
	EnableEpochsHandler                 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
hosttest

Jump to

Keyboard shortcuts

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