core

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2023 License: GPL-3.0 Imports: 12 Imported by: 1

Documentation

Index

Constants

View Source
const AddressLen = 32
View Source
const AddressLenEth = 20
View Source
const ArgumentLenEth = 32
View Source
const AsyncDataPrefix = "asyncCalls"
View Source
const BalanceLen = 32
View Source
const CallBackFunctionName = "callBack"
View Source
const CallbackDefault = "callBack"
View Source
const CodeMetadataLen = 2
View Source
const HashLen = 32
View Source
const InitFunctionName = "init"
View Source
const InitFunctionNameEth = "solidity.ctor"
View Source
const TimeLockKeyPrefix = "timelock"
View Source
const UpgradeFunctionName = "upgradeContract"

Variables

View Source
var ErrAccountNotPayable = errors.New("sending value to non payable contract")
View Source
var ErrArgIndexOutOfRange = errors.New("argument index out of range")
View Source
var ErrArgOutOfRange = errors.New("argument out of range")
View Source
var ErrAsyncCallsDisallowed = errors.New("async calls disallowed")
View Source
var ErrAsyncContextDoesNotExist = errors.New("async context does not exist")
View Source
var ErrBadBounds = errors.New("bad bounds")
View Source
var ErrBadLowerBounds = fmt.Errorf("%w (lower)", ErrBadBounds)
View Source
var ErrBadUpperBounds = fmt.Errorf("%w (upper)", ErrBadBounds)
View Source
var ErrBitwiseNegative = errors.New("bitwise operations only allowed on positive integers")
View Source
var ErrCallBackFuncCalledInRun = fmt.Errorf("%w (calling callBack() directly is forbidden)", ErrInvalidFunction)
View Source
var ErrCallBackFuncNotExpected = fmt.Errorf("%w (unexpected callback was received)", ErrInvalidFunction)
View Source
var ErrContractInvalid = fmt.Errorf("invalid contract code")
View Source
var ErrContractNotFound = fmt.Errorf("%w (not found)", ErrContractInvalid)
View Source
var ErrDeploymentOverExistingAccount = errors.New("cannot deploy over existing account")
View Source
var ErrDivZero = errors.New("division by 0")
View Source
var ErrExecutionFailed = errors.New("execution failed")
View Source
var ErrFailedTransfer = errors.New("failed transfer")
View Source
var ErrFailedTransferDuringAsyncCall = fmt.Errorf("%w (failed during async call)", ErrFailedTransfer)
View Source
var ErrFuncNotFound = fmt.Errorf("%w (not found)", ErrInvalidFunction)
View Source
var ErrFunctionNonvoidSignature = fmt.Errorf("%w (nonvoid signature)", ErrInvalidFunction)
View Source
var ErrGasUsageError = errors.New("gas use error")
View Source
var ErrInitFuncCalledInRun = fmt.Errorf("%w (calling init() directly is forbidden)", ErrInvalidFunction)
View Source
var ErrInvalidAPICall = errors.New("invalid API call")
View Source
var ErrInvalidAccount = errors.New("account does not exist")
View Source
var ErrInvalidCallOnReadOnlyMode = errors.New("operation not permitted in read only mode")
View Source
var ErrInvalidFunction = errors.New("invalid function")
View Source
var ErrInvalidFunctionName = fmt.Errorf("%w (invalid name)", ErrInvalidFunction)
View Source
var ErrInvalidPublicKeySize = errors.New("invalid public key size")
View Source
var ErrInvalidUpgradeArguments = fmt.Errorf("%w (invalid arguments)", ErrUpgradeFailed)
View Source
var ErrMaxInstancesReached = fmt.Errorf("%w (max instances reached)", ErrExecutionFailed)
View Source
var ErrMemoryDeclarationMissing = fmt.Errorf("%w (missing memory declaration)", ErrContractInvalid)
View Source
var ErrNegativeLength = errors.New("negative length")
View Source
var ErrNilCallbackFunction = errors.New("nil callback function")
View Source
var ErrNilCallbackVMOutput = errors.New("nil callback VMOutput")
View Source
var ErrNilContract = errors.New("nil contract")
View Source
var ErrNotEnoughGas = errors.New("not enough gas")
View Source
var ErrReturnCodeNotOk = errors.New("return not is not ok")
View Source
var ErrShiftNegative = errors.New("bitwise shift operations only allowed on positive integers and by a positive amount")
View Source
var ErrSignalError = errors.New("error signalled by smartcontract")
View Source
var ErrStorageValueOutOfRange = errors.New("storage value out of range")
View Source
var ErrStoreDharitriReservedKey = errors.New("cannot write to storage under Dharitri reserved key")
View Source
var ErrTransferInsufficientFunds = fmt.Errorf("%w (insufficient funds)", ErrFailedTransfer)
View Source
var ErrTransferNegativeValue = fmt.Errorf("%w (negative value)", ErrFailedTransfer)
View Source
var ErrUnhandledRuntimeBreakpoint = errors.New("unhandled runtime breakpoint")
View Source
var ErrUpgradeFailed = errors.New("upgrade failed")
View Source
var ErrUpgradeNotAllowed = errors.New("upgrade not allowed")
View Source
var Zero = big.NewInt(0)

Zero is the big integer 0

Functions

func AddHostContext

func AddHostContext(ctx VMHost) int

func BooleanToInt

func BooleanToInt(b bool) int

func CustomStorageKey

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

func GetCryptoContext

func GetCryptoContext(context unsafe.Pointer) crypto.VMCrypto

func GetSCCode

func GetSCCode(fileName string) []byte

func GuardedGetBytesSlice

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

func GuardedMakeByteSlice2D

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

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

func PadBytesLeft

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

func RemoveAllHostContexts

func RemoveAllHostContexts()

func RemoveHostContext

func RemoveHostContext(idx int)

func TimeTrack

func TimeTrack(start time.Time, message string)

func U64MulToBigInt

func U64MulToBigInt(x, y uint64) *big.Int

func U64ToLEB128 added in v0.0.3

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, context unsafe.Pointer, failExecution bool) bool

Types

type AsyncCallExecutionMode

type AsyncCallExecutionMode uint
const (
	SyncCall AsyncCallExecutionMode = iota
	AsyncBuiltinFunc
	AsyncUnknown
)

type AsyncCallInfo

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

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

func (*AsyncCallInfo) GetData

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

func (*AsyncCallInfo) GetDestination

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

func (*AsyncCallInfo) GetGasLimit

func (aci *AsyncCallInfo) GetGasLimit() uint64

func (*AsyncCallInfo) GetValueBytes

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

type AsyncCallInfoHandler

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

type AsyncCallStatus

type AsyncCallStatus uint8

AsyncCallStatus represents the different status an async call can have

const (
	AsyncCallPending AsyncCallStatus = iota
	AsyncCallResolved
	AsyncCallRejected
)

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

type BigIntContext interface {
	StateStack

	Put(value int64) int32
	GetOne(id int32) *big.Int
	GetTwo(id1, id2 int32) (*big.Int, *big.Int)
	GetThree(id1, id2, id3 int32) (*big.Int, *big.Int, *big.Int)
}

func GetBigIntContext

func GetBigIntContext(context unsafe.Pointer) BigIntContext

type BlockchainContext

type BlockchainContext interface {
	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, error)
	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(address []byte) (bool, error)
}

func GetBlockchainContext

func GetBlockchainContext(context unsafe.Pointer) BlockchainContext

type BreakpointValue

type BreakpointValue uint64
const (
	BreakpointNone BreakpointValue = iota
	BreakpointExecutionFailed
	BreakpointAsyncCall
	BreakpointSignalError
	BreakpointOutOfGas
)

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 MeteringContext

type MeteringContext interface {
	GasSchedule() *config.GasCost
	UseGas(gas uint64)
	FreeGas(gas uint64)
	RestoreGas(gas uint64)
	GasLeft() uint64
	BoundGasLimit(value int64) uint64
	BlockGasLimit() uint64
	DeductInitialGasForExecution(contract []byte) error
	DeductInitialGasForDirectDeployment(input CodeDeployInput) error
	DeductInitialGasForIndirectDeployment(input CodeDeployInput) error
	DeductAndLockGasIfAsyncStep() error
	UnlockGasIfAsyncStep()
	GetGasLockedForAsyncStep() uint64
}

func GetMeteringContext

func GetMeteringContext(context unsafe.Pointer) MeteringContext

type OutputContext

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

	GetOutputAccount(address []byte) (*vmcommon.OutputAccount, bool)
	DeleteOutputAccount(address []byte)
	WriteLog(address []byte, topics [][]byte, data []byte)
	TransferValueOnly(destination []byte, sender []byte, value *big.Int) error
	Transfer(destination []byte, sender []byte, gasLimit uint64, value *big.Int, input []byte, callType vmcommon.CallType) 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()
	Finish(data []byte)
	GetVMOutput() *vmcommon.VMOutput
	AddTxValueToAccount(address []byte, value *big.Int)
	DeployCode(input CodeDeployInput)
	CreateVMOutputInCaseOfError(err error) *vmcommon.VMOutput
}

func GetOutputContext

func GetOutputContext(context unsafe.Pointer) OutputContext

type RuntimeContext

type RuntimeContext interface {
	StateStack

	InitStateFromContractCallInput(input *vmcommon.ContractCallInput)
	SetCustomCallFunction(callFunction string)
	GetVMInput() *vmcommon.VMInput
	SetVMInput(vmInput *vmcommon.VMInput)
	GetSCAddress() []byte
	SetSCAddress(scAddress []byte)
	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)
	PushInstance()
	PopInstance()
	RunningInstancesCount() uint64
	ClearInstanceStack()
	IsWarmInstance() bool
	ResetWarmInstance()
	ReadOnly() bool
	SetReadOnly(readOnly bool)
	StartWasmerInstance(contract []byte, gasLimit uint64) error
	CleanWasmerInstance()
	SetMaxInstanceCount(uint64)
	VerifyContractCode() error
	GetInstanceExports() wasmer.ExportsMap
	GetInitFunction() wasmer.ExportedFunctionCallback
	GetFunctionToCall() (wasmer.ExportedFunctionCallback, error)
	GetPointsUsed() uint64
	SetPointsUsed(gasPoints uint64)
	MemStore(offset int32, data []byte) error
	MemLoad(offset int32, length int32) ([]byte, error)
	DharitriAPIErrorShouldFailExecution() bool
	CryptoAPIErrorShouldFailExecution() bool
	BigIntAPIErrorShouldFailExecution() bool
}

func GetRuntimeContext

func GetRuntimeContext(context unsafe.Pointer) RuntimeContext

type StateStack

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

type StorageContext

type StorageContext interface {
	StateStack

	SetAddress(address []byte)
	GetStorageUpdates(address []byte) map[string]*vmcommon.StorageUpdate
	GetStorageFromAddress(address []byte, key []byte) []byte
	GetStorage(key []byte) []byte
	GetStorageUnmetered(key []byte) []byte
	SetStorage(key []byte, value []byte) (StorageStatus, error)
}

func GetStorageContext

func GetStorageContext(context unsafe.Pointer) StorageContext

type StorageStatus

type StorageStatus int
const (
	StorageUnchanged StorageStatus = iota
	StorageModified
	StorageAdded
	StorageDeleted
)

type VMHost

type VMHost interface {
	Crypto() crypto.VMCrypto
	Blockchain() BlockchainContext
	Runtime() RuntimeContext
	BigInt() BigIntContext
	Output() OutputContext
	Metering() MeteringContext
	Storage() StorageContext
	IsCoreV2Enabled() bool

	CreateNewContract(input *vmcommon.ContractCreateInput) ([]byte, error)
	ExecuteOnSameContext(input *vmcommon.ContractCallInput) (*AsyncContextInfo, error)
	ExecuteOnDestContext(input *vmcommon.ContractCallInput) (*vmcommon.VMOutput, *AsyncContextInfo, error)
	EthereumCallData() []byte
	GetAPIMethods() *wasmer.Imports
	GetProtocolBuiltinFunctions() vmcommon.FunctionNames
	IsBuiltinFunctionName(functionName string) bool
}

func GetVmContext

func GetVmContext(context unsafe.Pointer) VMHost

type VMHostParameters

type VMHostParameters struct {
	VMType                     []byte
	BlockGasLimit              uint64
	GasSchedule                config.GasScheduleMap
	ProtocolBuiltinFunctions   vmcommon.FunctionNames
	DharitriProtectedKeyPrefix []byte
	CoreV2EnableEpoch          uint32
	UseWarmInstance            bool
}

VMHostParameters represents the parameters to be passed to VMHost

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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