vmcommon

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2024 License: GPL-3.0 Imports: 11 Imported by: 0

README

Dharitri

drt-vm-common

Common structs between VM and node

Documentation

Index

Constants

View Source
const (
	// MetadataUpgradeable is the bit for upgradable flag
	MetadataUpgradeable = 1
	// MetadataReadable is the bit for readable flag
	MetadataReadable = 4
	// MetadataGuarded is the bit for guarded account flag
	MetadataGuarded = 8
)

Const group for the first byte of the metadata

View Source
const (
	// MetadataPayable is the bit for payable flag
	MetadataPayable = 2
	// MetadataPayableBySC is the bit for payable flag
	MetadataPayableBySC = 4
)

Const group for the second byte of the metadata

View Source
const BuiltInFunctionDCTSetBurnRoleForAll = "DCTSetBurnRoleForAll"

BuiltInFunctionDCTSetBurnRoleForAll represents the defined built in function name for dct set burn role for all

View Source
const BuiltInFunctionDCTTransferRoleAddAddress = "DCTTransferRoleAddAddress"

BuiltInFunctionDCTTransferRoleAddAddress represents the defined built in function name for dct transfer role add address

View Source
const BuiltInFunctionDCTTransferRoleDeleteAddress = "DCTTransferRoleDeleteAddress"

BuiltInFunctionDCTTransferRoleDeleteAddress represents the defined built in function name for transfer role delete address

View Source
const BuiltInFunctionDCTUnSetBurnRoleForAll = "DCTUnSetBurnRoleForAll"

BuiltInFunctionDCTUnSetBurnRoleForAll represents the defined built in function name for dct unset burn role for all

View Source
const DCTAddMetadata = "DCTAddMetadata"

DCTAddMetadata represents the defined built in function name for dct add metadata

View Source
const DCTDeleteMetadata = "DCTDeleteMetadata"

DCTDeleteMetadata represents the defined built in function name for dct delete metadata

View Source
const DCTRoleBurnForAll = "DCTRoleBurnForAll"

DCTRoleBurnForAll represents the role for burn for all

View Source
const MaxLengthForValueToOptTransfer = 32

MaxLengthForValueToOptTransfer defines the maximum length for value to optimize cross shard transfer

View Source
const NumInitCharactersForScAddress = 10

NumInitCharactersForScAddress numbers of characters for smart contract address identifier

View Source
const ShardIdentiferLen = 2

ShardIdentiferLen number of characters for shard identifier in an address

View Source
const VMTypeLen = 2

VMTypeLen number of characters with VMType identifier in an address, these are the last 2 characters from the initial identifier

Variables

View Source
var ErrAsyncParams = errors.New("async parameters error")

ErrAsyncParams signals that there was an error with the async parameters

View Source
var ErrInvalidVMType = errors.New("invalid VM type")

ErrInvalidVMType signals that invalid vm type was provided

View Source
var ErrNilTransferIndexer = errors.New("nil NextOutputTransferIndexProvider")

ErrNilTransferIndexer signals that the provided transfer indexer is nil

View Source
var ErrSubtractionOverflow = errors.New("uint64 subtraction overflowed")

ErrSubtractionOverflow signals that uint64 subtraction overflowed

View Source
var ErrTransfersNotIndexed = errors.New("unindexed transfers found")

ErrTransfersNotIndexed signals that transfers were found unindexed

View Source
var SystemAccountAddress = bytes.Repeat([]byte{255}, 32)

SystemAccountAddress is the hard-coded address in which we save global settings on all shards

Functions

func FormatLogDataForCall added in v0.1.6

func FormatLogDataForCall(callType string, functionName string, functionArgs [][]byte) [][]byte

FormatLogDataForCall prepares Data field for a LogEntry

func IsAllowedToSaveUnderKey added in v0.0.6

func IsAllowedToSaveUnderKey(key []byte) bool

IsAllowedToSaveUnderKey returns if saving key-value in data tries under given key is allowed

func IsEmptyAddress added in v0.0.6

func IsEmptyAddress(address []byte) bool

IsEmptyAddress returns whether an address is empty

func IsMetachainIdentifier added in v0.0.6

func IsMetachainIdentifier(identifier []byte) bool

IsMetachainIdentifier verifies if the identifier is of type metachain

func IsSmartContractAddress added in v0.0.6

func IsSmartContractAddress(rcvAddress []byte) bool

IsSmartContractAddress verifies if a set address is of type smart contract

func IsSmartContractOnMetachain added in v0.0.6

func IsSmartContractOnMetachain(identifier []byte, rcvAddress []byte) bool

IsSmartContractOnMetachain verifies if an address is smart contract on metachain

func IsSystemAccountAddress added in v0.0.6

func IsSystemAccountAddress(address []byte) bool

IsSystemAccountAddress returns true if given address is system account address

func ParseVMTypeFromContractAddress added in v0.1.5

func ParseVMTypeFromContractAddress(contractAddress []byte) ([]byte, error)

ParseVMTypeFromContractAddress obtains the VMType from the contract address TODO maybe move to elgond-go-core

func SafeSubUint64 added in v0.0.6

func SafeSubUint64(a, b uint64) (uint64, error)

SafeSubUint64 performs subtraction on uint64 and returns an error if it overflows

func ValidateToken added in v0.0.9

func ValidateToken(tokenID []byte) bool

ValidateToken - validates the token ID

func ZeroValueIfNil added in v0.0.9

func ZeroValueIfNil(value *big.Int) *big.Int

ZeroValueIfNil returns 0 if the input is nil, otherwise returns the input

Types

type AcceptPayableChecker added in v0.0.9

type AcceptPayableChecker interface {
	SetPayableChecker(payableHandler PayableChecker) error
	IsInterfaceNil() bool
}

AcceptPayableChecker defines the methods to accept a payable handler through a set function

type AccountDataHandler added in v0.0.6

type AccountDataHandler interface {
	RetrieveValue(key []byte) ([]byte, uint32, error)
	SaveKeyValue(key []byte, value []byte) error
	MigrateDataTrieLeaves(args ArgsMigrateDataTrieLeaves) error
	IsInterfaceNil() bool
}

AccountDataHandler models what how to manipulate data held by a SC account

type AccountHandler added in v0.0.6

type AccountHandler interface {
	AddressBytes() []byte
	IncreaseNonce(nonce uint64)
	GetNonce() uint64
	IsInterfaceNil() bool
}

AccountHandler models a state account, which can journalize and revert It knows about code and data, as data structures not hashes

type AccountsAdapter added in v0.0.6

type AccountsAdapter interface {
	GetExistingAccount(address []byte) (AccountHandler, error)
	LoadAccount(address []byte) (AccountHandler, error)
	SaveAccount(account AccountHandler) error
	RemoveAccount(address []byte) error
	Commit() ([]byte, error)
	JournalLen() int
	RevertToSnapshot(snapshot int) error
	GetCode(codeHash []byte) []byte

	RootHash() ([]byte, error)
	IsInterfaceNil() bool
}

AccountsAdapter is used for the structure that manages the accounts on top of a trie.PatriciaMerkleTrie implementation

type ArgsMigrateDataTrieLeaves added in v0.1.5

type ArgsMigrateDataTrieLeaves struct {
	OldVersion   core.TrieNodeVersion
	NewVersion   core.TrieNodeVersion
	TrieMigrator DataTrieMigrator
}

ArgsMigrateDataTrieLeaves is the argument structure for the MigrateDataTrieLeaves function

type AsyncArguments added in v0.1.5

type AsyncArguments struct {
	CallID                       []byte
	CallerCallID                 []byte
	CallbackAsyncInitiatorCallID []byte
	GasAccumulated               uint64
}

type BaseOperationCost added in v0.0.6

type BaseOperationCost struct {
	StorePerByte      uint64
	ReleasePerByte    uint64
	DataCopyPerByte   uint64
	PersistPerByte    uint64
	CompilePerByte    uint64
	AoTPreparePerByte uint64
}

BaseOperationCost defines cost for base operation cost

type BlockchainHook

type BlockchainHook interface {
	// NewAddress yields the address of a new SC account, when one such account is created.
	// The result should only depend on the creator address and nonce.
	// Returning an empty address lets the VM decide what the new address should be.
	NewAddress(creatorAddress []byte, creatorNonce uint64, vmType []byte) ([]byte, error)

	// GetStorageData should yield the storage value for a certain account and index.
	// Should return an empty byte array if the key is missing from the account storage,
	// or if account does not exist.
	GetStorageData(accountAddress []byte, index []byte) ([]byte, uint32, error)

	// GetBlockhash returns the hash of the block with the asked nonce if available
	GetBlockhash(nonce uint64) ([]byte, error)

	// LastNonce returns the nonce from from the last committed block
	LastNonce() uint64

	// LastRound returns the round from the last committed block
	LastRound() uint64

	// LastTimeStamp returns the timeStamp from the last committed block
	LastTimeStamp() uint64

	// LastRandomSeed returns the random seed from the last committed block
	LastRandomSeed() []byte

	// LastEpoch returns the epoch from the last committed block
	LastEpoch() uint32

	// GetStateRootHash returns the state root hash from the last committed block
	GetStateRootHash() []byte

	// CurrentNonce returns the nonce from the current block
	CurrentNonce() uint64

	// CurrentRound returns the round from the current block
	CurrentRound() uint64

	// CurrentTimeStamp return the timestamp from the current block
	CurrentTimeStamp() uint64

	// CurrentRandomSeed returns the random seed from the current header
	CurrentRandomSeed() []byte

	// CurrentEpoch returns the current epoch
	CurrentEpoch() uint32

	// ProcessBuiltInFunction will process the builtIn function for the created input
	ProcessBuiltInFunction(input *ContractCallInput) (*VMOutput, error)

	// GetBuiltinFunctionNames returns the names of protocol built-in functions
	GetBuiltinFunctionNames() FunctionNames

	// GetAllState returns the full state of the account, all the key-value saved
	GetAllState(address []byte) (map[string][]byte, error)

	// GetUserAccount returns a user account
	GetUserAccount(address []byte) (UserAccountHandler, error)

	// GetCode returns the code for the given account
	GetCode(UserAccountHandler) []byte

	// GetShardOfAddress returns the shard ID of a given address
	GetShardOfAddress(address []byte) uint32

	// IsSmartContract returns whether the address points to a smart contract
	IsSmartContract(address []byte) bool

	// IsPayable checks weather the provided address can receive MOA or not
	IsPayable(sndAddress []byte, recvAddress []byte) (bool, error)

	// SaveCompiledCode saves to cache and storage the compiled code
	SaveCompiledCode(codeHash []byte, code []byte)

	// GetCompiledCode returns the compiled code if it finds in the cache or storage
	GetCompiledCode(codeHash []byte) (bool, []byte)

	// ClearCompiledCodes clears the cache and storage of compiled codes
	ClearCompiledCodes()

	// GetDCTToken loads the DCT digital token for the given key
	GetDCTToken(address []byte, tokenID []byte, nonce uint64) (*dct.DCToken, error)

	// IsPaused returns true if the tokenID is paused globally
	IsPaused(tokenID []byte) bool

	// IsLimitedTransfer return true if the tokenID has limited transfers
	IsLimitedTransfer(tokenID []byte) bool

	// GetSnapshot gets the number of entries in the journal as a snapshot id
	GetSnapshot() int

	// RevertToSnapshot reverts snaphots up to the specified one
	RevertToSnapshot(snapshot int) error

	// ExecuteSmartContractCallOnOtherVM runs contract on another VM
	ExecuteSmartContractCallOnOtherVM(input *ContractCallInput) (*VMOutput, error)

	// IsInterfaceNil returns true if there is no value under the interface
	IsInterfaceNil() bool
}

BlockchainHook is the interface for VM blockchain callbacks

type BuiltInCost added in v0.0.6

type BuiltInCost struct {
	ChangeOwnerAddress      uint64
	ClaimDeveloperRewards   uint64
	SaveUserName            uint64
	SaveKeyValue            uint64
	DCTTransfer             uint64
	DCTBurn                 uint64
	DCTLocalMint            uint64
	DCTLocalBurn            uint64
	DCTNFTCreate            uint64
	DCTNFTAddQuantity       uint64
	DCTNFTBurn              uint64
	DCTNFTTransfer          uint64
	DCTNFTChangeCreateOwner uint64
	DCTNFTMultiTransfer     uint64
	DCTNFTAddURI            uint64
	DCTNFTUpdateAttributes  uint64
	SetGuardian             uint64
	GuardAccount            uint64
	TrieLoadPerNode         uint64
	TrieStorePerNode        uint64
}

BuiltInCost defines cost for built-in methods

type BuiltInFunctionContainer added in v0.0.6

type BuiltInFunctionContainer interface {
	Get(key string) (BuiltinFunction, error)
	Add(key string, function BuiltinFunction) error
	Replace(key string, function BuiltinFunction) error
	Remove(key string)
	Len() int
	Keys() map[string]struct{}
	IsInterfaceNil() bool
}

BuiltInFunctionContainer defines the methods for the built-in protocol container

type BuiltInFunctionFactory added in v0.0.9

type BuiltInFunctionFactory interface {
	DCTGlobalSettingsHandler() DCTGlobalSettingsHandler
	NFTStorageHandler() SimpleDCTNFTStorageHandler
	BuiltInFunctionContainer() BuiltInFunctionContainer
	SetPayableHandler(handler PayableHandler) error
	CreateBuiltInFunctionContainer() error
	IsInterfaceNil() bool
}

BuiltInFunctionFactory will handle built-in functions and components

type BuiltinFunction added in v0.0.6

type BuiltinFunction interface {
	ProcessBuiltinFunction(acntSnd, acntDst UserAccountHandler, vmInput *ContractCallInput) (*VMOutput, error)
	SetNewGasConfig(gasCost *GasCost)
	IsActive() bool
	IsInterfaceNil() bool
}

BuiltinFunction defines the methods for the built-in protocol smart contract functions

type CallArgsParser added in v0.0.9

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

CallArgsParser will handle parsing transaction data to function and arguments

type CodeMetadata added in v0.0.2

type CodeMetadata struct {
	Payable     bool
	PayableBySC bool
	Upgradeable bool
	Readable    bool
	Guarded     bool
}

CodeMetadata represents smart contract code metadata

func CodeMetadataFromBytes added in v0.0.2

func CodeMetadataFromBytes(bytes []byte) CodeMetadata

CodeMetadataFromBytes creates a metadata object from bytes

func (*CodeMetadata) ToBytes added in v0.0.2

func (metadata *CodeMetadata) ToBytes() []byte

ToBytes converts the metadata to bytes

type ContractCallInput

type ContractCallInput struct {
	VMInput

	// RecipientAddr is the smart contract public key, "to".
	RecipientAddr []byte

	// Function is the name of the smart contract function that will be called.
	// The function must be public
	Function string

	// AllowInitFunction specifies whether calling the initialization method of
	// the smart contract is allowed or not
	AllowInitFunction bool
}

ContractCallInput VM input when calling a function from an existing contract

type ContractCreateInput

type ContractCreateInput struct {
	VMInput

	// ContractCode is the code of the contract being created, assembled into a byte array.
	ContractCode []byte

	// ContractCodeMetadata is the code metadata of the contract being created.
	ContractCodeMetadata []byte
}

ContractCreateInput VM input when creating a new contract. Here we have no RecipientAddr because the address (PK) of the created account will be provided by the vmcommon. We also do not need to specify a Function field, because on creation `init` is always called.

type Coordinator added in v0.0.6

type Coordinator interface {
	NumberOfShards() uint32
	ComputeId(address []byte) uint32
	SelfId() uint32
	SameShard(firstAddress, secondAddress []byte) bool
	CommunicationIdentifier(destShardID uint32) string
	IsInterfaceNil() bool
}

Coordinator defines what a shard state coordinator should hold

type CryptoHook

type CryptoHook interface {
	// Sha256 cryptographic function
	Sha256(data []byte) ([]byte, error)

	// Keccak256 cryptographic function
	Keccak256(data []byte) ([]byte, error)

	// Ripemd160 cryptographic function
	Ripemd160(data []byte) ([]byte, error)

	// Ecrecover calculates the corresponding Ethereum address for the public key which created the given signature
	// https://ewasm.readthedocs.io/en/mkdocs/system_contracts/
	Ecrecover(hash []byte, recoveryID []byte, r []byte, s []byte) ([]byte, error)

	// IsInterfaceNil returns true if there is no value under the interface
	IsInterfaceNil() bool
}

CryptoHook interface for VM krypto functions

type DCTGlobalSettingsHandler added in v0.0.7

type DCTGlobalSettingsHandler interface {
	IsPaused(dctTokenKey []byte) bool
	IsLimitedTransfer(dctTokenKey []byte) bool
	IsInterfaceNil() bool
}

DCTGlobalSettingsHandler provides global settings functions for an DCT token

type DCTNFTStorageHandler added in v0.0.9

type DCTNFTStorageHandler interface {
	SaveDCTNFTToken(senderAddress []byte, acnt UserAccountHandler, dctTokenKey []byte, nonce uint64, dctData *dct.DCToken, mustUpdateAllFields bool, isReturnWithError bool) ([]byte, error)
	GetDCTNFTTokenOnSender(acnt UserAccountHandler, dctTokenKey []byte, nonce uint64) (*dct.DCToken, error)
	GetDCTNFTTokenOnDestination(acnt UserAccountHandler, dctTokenKey []byte, nonce uint64) (*dct.DCToken, bool, error)
	GetDCTNFTTokenOnDestinationWithCustomSystemAccount(accnt UserAccountHandler, dctTokenKey []byte, nonce uint64, systemAccount UserAccountHandler) (*dct.DCToken, bool, error)
	WasAlreadySentToDestinationShardAndUpdateState(tickerID []byte, nonce uint64, dstAddress []byte) (bool, error)
	SaveNFTMetaDataToSystemAccount(tx data.TransactionHandler) error
	AddToLiquiditySystemAcc(dctTokenKey []byte, nonce uint64, transferValue *big.Int) error
	IsInterfaceNil() bool
}

DCTNFTStorageHandler will handle the storage for the nft metadata

type DCTRoleHandler added in v0.0.6

type DCTRoleHandler interface {
	CheckAllowedToExecute(account UserAccountHandler, tokenID []byte, action []byte) error
	IsInterfaceNil() bool
}

DCTRoleHandler provides IsAllowedToExecute function for an DCT

type DCTTransfer added in v0.0.6

type DCTTransfer struct {
	// DCTValue is the value (amount of tokens) transferred by the transaction.
	// Before reaching the VM this value is subtracted from sender balance (CallerAddr)
	// and to added to the smart contract balance.
	// It is often, but not always zero in SC calls.
	DCTValue *big.Int

	// DCTTokenName is the name of the token which was transferred by the transaction to the SC
	DCTTokenName []byte

	// DCTTokenType is the type of the transferred token
	DCTTokenType uint32

	// DCTTokenNonce is the nonce for the given NFT token
	DCTTokenNonce uint64
}

DCTTransfer defines the structure for and DCT / NFT transfer

type DCTTransferParser added in v0.0.6

type DCTTransferParser interface {
	ParseDCTTransfers(sndAddr []byte, rcvAddr []byte, function string, args [][]byte) (*ParsedDCTTransfers, error)
	IsInterfaceNil() bool
}

DCTTransferParser can parse single and multi DCT / NFT transfers

type DataTrieMigrator added in v0.1.5

type DataTrieMigrator interface {
	ConsumeStorageLoadGas() bool
	AddLeafToMigrationQueue(leafData core.TrieData, newLeafVersion core.TrieNodeVersion) (bool, error)
	GetLeavesToBeMigrated() []core.TrieData
	IsInterfaceNil() bool
}

DataTrieMigrator is the interface that defines the methods needed for migrating data trie leaves

type EnableEpochsHandler added in v0.0.9

type EnableEpochsHandler interface {
	IsGlobalMintBurnFlagEnabled() bool
	IsDCTTransferRoleFlagEnabled() bool
	IsBuiltInFunctionsFlagEnabled() bool
	IsCheckCorrectTokenIDForTransferRoleFlagEnabled() bool
	IsMultiDCTTransferFixOnCallBackFlagEnabled() bool
	IsFixOOGReturnCodeFlagEnabled() bool
	IsRemoveNonUpdatedStorageFlagEnabled() bool
	IsCreateNFTThroughExecByCallerFlagEnabled() bool
	IsStorageAPICostOptimizationFlagEnabled() bool
	IsFailExecutionOnEveryAPIErrorFlagEnabled() bool
	IsManagedCryptoAPIsFlagEnabled() bool
	IsSCDeployFlagEnabled() bool
	IsAheadOfTimeGasUsageFlagEnabled() bool
	IsRepairCallbackFlagEnabled() bool
	IsDisableExecByCallerFlagEnabled() bool
	IsRefactorContextFlagEnabled() bool
	IsCheckFunctionArgumentFlagEnabled() bool
	IsCheckExecuteOnReadOnlyFlagEnabled() bool
	IsFixAsyncCallbackCheckFlagEnabled() bool
	IsSaveToSystemAccountFlagEnabled() bool
	IsCheckFrozenCollectionFlagEnabled() bool
	IsSendAlwaysFlagEnabled() bool
	IsValueLengthCheckFlagEnabled() bool
	IsCheckTransferFlagEnabled() bool
	IsTransferToMetaFlagEnabled() bool
	IsDCTNFTImprovementV1FlagEnabled() bool
	IsFixOldTokenLiquidityEnabled() bool
	IsRuntimeMemStoreLimitEnabled() bool
	IsMaxBlockchainHookCountersFlagEnabled() bool
	IsWipeSingleNFTLiquidityDecreaseEnabled() bool
	IsAlwaysSaveTokenMetaDataEnabled() bool
	IsRuntimeCodeSizeFixEnabled() bool
	IsChangeUsernameEnabled() bool
	IsDynamicGasCostForDataTrieStorageLoadEnabled() bool
	IsSetGuardianEnabled() bool
	IsScToScEventLogEnabled() bool
	IsConsistentTokensValuesLengthCheckEnabled() bool
	IsAutoBalanceDataTriesEnabled() bool
	IsMigrateDataTrieEnabled() bool
	IsChangeOwnerAddressCrossShardThroughSCEnabled() bool
	FixGasRemainingForSaveKeyValueBuiltinFunctionEnabled() bool

	MultiDCTTransferAsyncCallBackEnableEpoch() uint32
	FixOOGReturnCodeEnableEpoch() uint32
	RemoveNonUpdatedStorageEnableEpoch() uint32
	CreateNFTThroughExecByCallerEnableEpoch() uint32
	FixFailExecutionOnErrorEnableEpoch() uint32
	ManagedCryptoAPIEnableEpoch() uint32
	DisableExecByCallerEnableEpoch() uint32
	RefactorContextEnableEpoch() uint32
	CheckExecuteReadOnlyEnableEpoch() uint32
	StorageAPICostOptimizationEnableEpoch() uint32

	IsInterfaceNil() bool
}

EnableEpochsHandler is used to verify which flags are set in the current epoch based on EnableEpochs config

type EpochNotifier added in v0.0.6

type EpochNotifier interface {
	RegisterNotifyHandler(handler EpochSubscriberHandler)
	IsInterfaceNil() bool
}

EpochNotifier can notify upon an epoch change and provide the current epoch

type EpochSubscriberHandler added in v0.0.6

type EpochSubscriberHandler interface {
	EpochConfirmed(epoch uint32, timestamp uint64)
	IsInterfaceNil() bool
}

EpochSubscriberHandler defines the behavior of a component that can be notified if a new epoch was confirmed

type ExtendedDCTGlobalSettingsHandler added in v0.0.9

type ExtendedDCTGlobalSettingsHandler interface {
	IsPaused(dctTokenKey []byte) bool
	IsLimitedTransfer(dctTokenKey []byte) bool
	IsBurnForAll(dctTokenKey []byte) bool
	IsSenderOrDestinationWithTransferRole(sender, destination, tokenID []byte) bool
	IsInterfaceNil() bool
}

ExtendedDCTGlobalSettingsHandler provides global settings functions for an DCT token

type FunctionNames added in v0.0.2

type FunctionNames = map[string]struct{}

FunctionNames (alias) is a map of function names

type GasCost added in v0.0.6

type GasCost struct {
	BaseOperationCost BaseOperationCost
	BuiltInCost       BuiltInCost
}

GasCost holds all the needed gas costs for system smart contracts

type GuardedAccountHandler added in v0.1.2

type GuardedAccountHandler interface {
	GetActiveGuardian(handler UserAccountHandler) ([]byte, error)
	SetGuardian(uah UserAccountHandler, guardianAddress []byte, txGuardianAddress []byte, guardianServiceUID []byte) error
	CleanOtherThanActive(uah UserAccountHandler)
	IsInterfaceNil() bool
}

GuardedAccountHandler allows setting and getting the configured account guardian

type LogEntry

type LogEntry struct {
	Identifier []byte
	Address    []byte
	Topics     [][]byte
	Data       [][]byte
}

LogEntry represents an entry in the contract execution log. TODO: document all fields.

func (*LogEntry) GetFirstDataItem added in v0.1.6

func (logEntry *LogEntry) GetFirstDataItem() []byte

GetFirstDataItem returns the first item from the Data field of a LogEntry

type Marshalizer added in v0.0.6

type Marshalizer interface {
	Marshal(obj interface{}) ([]byte, error)
	Unmarshal(obj interface{}, buff []byte) error
	IsInterfaceNil() bool
}

Marshalizer defines the 2 basic operations: serialize (marshal) and deserialize (unmarshal)

type NextOutputTransferIndexProvider added in v0.1.5

type NextOutputTransferIndexProvider interface {
	NextOutputTransferIndex() uint32
	GetCrtTransferIndex() uint32
	SetCrtTransferIndex(index uint32)
	IsInterfaceNil() bool
}

NextOutputTransferIndexProvider interface abstracts a type that manages a transfer index counter

type OutputAccount

type OutputAccount struct {
	// Address is the public key of the account.
	Address []byte

	// Nonce is the new account nonce.
	Nonce uint64

	// Balance is the account balance after running a SC.
	// Only used for some tests now, please ignore. Might be removed in the future.
	Balance *big.Int

	// StorageUpdates is a map containing pointers to StorageUpdate structs,
	// indexed with strings produced by `string(StorageUpdate.Offset)`, for fast
	// access by the Offset of the StorageUpdate. These StorageUpdate structs
	// will be processed by the Node to modify the storage of the SmartContract.
	// Please note that it is likely that not all existing account storage keys
	// show up here.
	StorageUpdates map[string]*StorageUpdate

	// Code is the assembled code of a smart contract account.
	// This field will be populated when a new SC must be created after the transaction.
	Code []byte

	// CodeMetadata is the metadata of the code
	// Like "Code", this field will be populated when a new SC must be created after the transaction.
	CodeMetadata []byte

	// CodeDeployerAddress will be populated in case of contract deployment or upgrade (both direct and indirect)
	CodeDeployerAddress []byte

	// BalanceDelta is by how much the balance should change following the SC execution.
	// A negative value indicates that balance should decrease.
	BalanceDelta *big.Int

	// OutputTransfers represents the cross shard calls for this account
	OutputTransfers []OutputTransfer

	// GasUsed will be populated if the contract was called in the same shard
	GasUsed uint64

	// BytesAddedToStorage for this output account
	BytesAddedToStorage uint64

	// BytesDeletedFromStorage for this output account
	BytesDeletedFromStorage uint64

	// BytesConsumedByTxAsNetworking for this output account
	BytesConsumedByTxAsNetworking uint64
}

OutputAccount shows the state of an account after contract execution. It can be an existing account or a new account created by the transaction. Note: the current implementation might also return unmodified accounts.

func (*OutputAccount) MergeOutputAccounts added in v0.0.6

func (o *OutputAccount) MergeOutputAccounts(outAcc *OutputAccount)

MergeOutputAccounts merges the given account into the current one

func (*OutputAccount) MergeStorageUpdates added in v0.0.6

func (o *OutputAccount) MergeStorageUpdates(outAcc *OutputAccount)

MergeStorageUpdates will copy all the storage updates from the given output account

type OutputTransfer added in v0.0.4

type OutputTransfer struct {
	// Index of the transfer
	Index uint32
	// Value to be transferred
	Value *big.Int
	// GasLimit to used for the call
	GasLimit uint64
	// GasLocked holds the amount of gas to be kept aside for the eventual callback execution
	GasLocked uint64
	// AsyncData to be used in cross call
	AsyncData []byte
	// Data to be used in cross call
	Data []byte
	// CallType is set if it is a smart contract invocation
	CallType vm.CallType
	// SenderAddress is the actual sender for the given output transfer, this is needed when
	// contract A calls contract B and contract B does the transfers
	SenderAddress []byte
}

OutputTransfer contains the fields needed to create transfers to another shard

type ParsedDCTTransfers added in v0.0.6

type ParsedDCTTransfers struct {
	DCTTransfers []*DCTTransfer
	RcvAddr      []byte
	CallFunction string
	CallArgs     [][]byte
}

ParsedDCTTransfers defines the struct for the parsed dct transfers

type PayableChecker added in v0.0.9

type PayableChecker interface {
	CheckPayable(vmInput *ContractCallInput, dstAddress []byte, minLenArguments int) error
	DetermineIsSCCallAfter(vmInput *ContractCallInput, destAddress []byte, minLenArguments int) bool
	IsInterfaceNil() bool
}

PayableChecker will handle checking if transfer can happen of DCT tokens towards destination

type PayableHandler added in v0.0.6

type PayableHandler interface {
	IsPayable(sndAddress, rcvAddress []byte) (bool, error)
	IsInterfaceNil() bool
}

PayableHandler provides IsPayable function which returns if an account is payable or not

type ReturnCode

type ReturnCode int

ReturnCode is an enum with the possible error codes returned by the VM

const (
	// Ok is returned when execution was completed normally.
	Ok ReturnCode = 0

	// FunctionNotFound is returned when the input specifies a function name that does not exist or is not public.
	FunctionNotFound ReturnCode = 1

	// FunctionWrongSignature is returned when the wrong number of arguments is provided.
	FunctionWrongSignature ReturnCode = 2

	// ContractNotFound is returned when the called contract does not exist.
	ContractNotFound ReturnCode = 3

	// UserError is returned for various execution errors.
	UserError ReturnCode = 4

	// OutOfGas is returned when VM execution runs out of gas.
	OutOfGas ReturnCode = 5

	// AccountCollision is returned when created account already exists.
	AccountCollision ReturnCode = 6

	// OutOfFunds is returned when the caller (sender) runs out of funds.
	OutOfFunds ReturnCode = 7

	// CallStackOverFlow is returned when stack overflow occurs.
	CallStackOverFlow ReturnCode = 8

	// ContractInvalid is returned when the contract is invalid.
	ContractInvalid ReturnCode = 9

	// ExecutionFailed is returned when the execution of the specified function has failed.
	ExecutionFailed ReturnCode = 10

	// UpgradeFailed is returned when the upgrade of the contract has failed
	UpgradeFailed ReturnCode = 11

	// SimulateFailed is returned when tx simulation fails execution
	SimulateFailed ReturnCode = 12
)

func (ReturnCode) String

func (rc ReturnCode) String() string

type RoundNotifier added in v0.1.5

type RoundNotifier interface {
	RegisterNotifyHandler(handler RoundSubscriberHandler)
	IsInterfaceNil() bool
}

RoundNotifier can notify upon an epoch change and provide the current epoch

type RoundSubscriberHandler added in v0.1.5

type RoundSubscriberHandler interface {
	RoundConfirmed(round uint64, timestamp uint64)
	IsInterfaceNil() bool
}

RoundSubscriberHandler defines the behavior of a component that can be notified if a new epoch was confirmed

type SimpleDCTNFTStorageHandler added in v0.0.9

type SimpleDCTNFTStorageHandler interface {
	GetDCTNFTTokenOnDestination(accnt UserAccountHandler, dctTokenKey []byte, nonce uint64) (*dct.DCToken, bool, error)
	SaveNFTMetaDataToSystemAccount(tx data.TransactionHandler) error
	IsInterfaceNil() bool
}

SimpleDCTNFTStorageHandler will handle get of DCT data and save metadata to system acc

type StorageUpdate

type StorageUpdate struct {
	// Offset is the storage key.
	Offset []byte

	// Data is the new storage value.
	// Zero indicates missing data for the key (or even a missing key),
	// therefore a value of zero here indicates that
	// the storage map entry with the given key can be deleted.
	Data []byte

	// Written represents that this storage was change and needs to be persisted
	// into the chain
	Written bool
}

StorageUpdate represents a change in the account storage (insert, update or delete) Note: current implementation might also return unmodified storage entries.

type UserAccountHandler added in v0.0.2

type UserAccountHandler interface {
	GetCodeMetadata() []byte
	SetCodeMetadata(codeMetadata []byte)
	GetCodeHash() []byte
	GetRootHash() []byte
	AccountDataHandler() AccountDataHandler
	AddToBalance(value *big.Int) error
	GetBalance() *big.Int
	ClaimDeveloperRewards([]byte) (*big.Int, error)
	GetDeveloperReward() *big.Int
	ChangeOwnerAddress([]byte, []byte) error
	SetOwnerAddress([]byte)
	GetOwnerAddress() []byte
	SetUserName(userName []byte)
	GetUserName() []byte
	AccountHandler
}

UserAccountHandler models a user account, which can journalize account's data with some extra features like balance, developer rewards, owner

type VMExecutionHandler

type VMExecutionHandler interface {
	closing.Closer

	// RunSmartContractCreate computes how a smart contract creation should be performed
	RunSmartContractCreate(input *ContractCreateInput) (*VMOutput, error)

	// RunSmartContractCall computes the result of a smart contract call and how the system must change after the execution
	RunSmartContractCall(input *ContractCallInput) (*VMOutput, error)

	// GasScheduleChange sets a new gas schedule for the VM
	GasScheduleChange(newGasSchedule map[string]map[string]uint64)

	// GetVersion returns the version of the VM instance
	GetVersion() string

	// IsInterfaceNil returns true if there is no value under the interface
	IsInterfaceNil() bool
}

VMExecutionHandler interface for any Dharitri VM endpoint

type VMInput

type VMInput struct {
	// CallerAddr is the public key of the wallet initiating the transaction, "from".
	CallerAddr []byte

	// Arguments are the call parameters to the smart contract function call
	// For contract creation, these are the parameters to the @init function.
	// For contract call, these are the parameters to the function referenced in ContractCallInput.Function.
	// If the number of arguments does not match the function arity,
	// the transaction will return FunctionWrongSignature ReturnCode.
	Arguments [][]byte

	// AsyncArguments are used only internally by the promises framework
	AsyncArguments *AsyncArguments

	// CallValue is the MOAX value (amount of tokens) transferred by the transaction.
	// Before reaching the VM this value is subtracted from sender balance (CallerAddr)
	// and to added to the smart contract balance.
	// It is often, but not always zero in SC calls.
	CallValue *big.Int

	// CallType is the type of SmartContract call
	// Based on this value, the VM is informed of whether the call is direct,
	// asynchronous, or asynchronous callback.
	CallType vm.CallType

	// GasPrice multiplied by the gas burned by the transaction yields the transaction fee.
	// A larger GasPrice will incentivize block proposers to include the transaction in a block sooner,
	// but will cost the sender more.
	// The total fee should be GasPrice x (GasProvided - VMOutput.GasRemaining - VMOutput.GasRefund).
	// Note: the order of operations on the sender balance is:
	// 1. subtract GasPrice x GasProvided
	// 2. call VM, which will subtract CallValue if enough funds remain
	// 3. reimburse GasPrice x (VMOutput.GasRemaining + VMOutput.GasRefund)
	GasPrice uint64

	// GasProvided is the maximum gas allowed for the smart contract execution.
	// If the transaction consumes more gas than this value, it will immediately terminate
	// and return OutOfGas ReturnCode.
	// The sender will not be charged based on GasProvided, only on the gas burned,
	// so it doesn't cost the sender more to have a higher gas limit.
	GasProvided uint64

	// GasLocked is the amount of gas that must be kept unused during the current
	// call, because it will be used later for a callback. This field is only
	// used during asynchronous calls.
	GasLocked uint64

	// OriginalTxHash
	OriginalTxHash []byte

	// CurrentTxHash
	CurrentTxHash []byte

	// PrevTxHash
	PrevTxHash []byte

	// DCTTransfers
	DCTTransfers []*DCTTransfer

	// ReturnCallAfterError
	ReturnCallAfterError bool

	// GuardianSigned specifies whether the transaction was signed by the guardian
	TxGuardian []byte

	// OriginalCallerAddr is the public key of the wallet originally initiating the transaction
	OriginalCallerAddr []byte
}

VMInput contains the common fields between the 2 types of SC call.

type VMOutput

type VMOutput struct {
	// ReturnData is the function call returned result.
	// This value does not influence the account state in any way.
	// The value should be accessible in a UI.
	// ReturnData is part of the transaction receipt.
	ReturnData [][]byte

	// ReturnCode is the function call error code.
	// If it is not `Ok`, the transaction failed in some way - gas is, however, consumed anyway.
	// This value does not influence the account state in any way.
	// The value should be accessible to a UI.
	// ReturnCode is part of the transaction receipt.
	ReturnCode ReturnCode

	// ReturnMessage is a message set by the SmartContract, destined for the
	// caller
	ReturnMessage string

	// GasRemaining = VMInput.GasProvided - gas used.
	// It is necessary to compute how much to charge the sender for the transaction.
	GasRemaining uint64

	// GasRefund is how much gas the sender earned during the transaction.
	// Certain operations, like freeing up storage, actually return gas instead of consuming it.
	// Based on GasRefund, the sender could in principle be rewarded instead of taxed.
	GasRefund *big.Int

	// OutputAccounts contains data about all accounts changed as a result of the
	// Transaction. It is a map containing pointers to OutputAccount structs,
	// indexed with strings produced by `string(OutputAccount.Address)`, for fast
	// access by the Address of the OutputAccount.
	// This information tells the Node how to update the account data.
	// It can contain new accounts or existing changed accounts.
	// Note: the current implementation might also retrieve accounts that were not changed.
	OutputAccounts map[string]*OutputAccount

	// DeletedAccounts is a list of public keys of accounts that need to be deleted
	// as a result of the transaction.
	DeletedAccounts [][]byte

	// TouchedAccounts is a list of public keys of accounts that were somehow involved in the VM execution.
	// TODO: investigate what we need to to about these.
	TouchedAccounts [][]byte

	// Logs is a list of event data logged by the vmcommon.
	// Smart contracts can choose to log certain events programatically.
	// There are 3 main use cases for events and logs:
	// 1. smart contract return values for the user interface;
	// 2. asynchronous triggers with data;
	// 3. a cheaper form of storage (e.g. storing historical data that can be rendered by the frontend).
	// The logs should be accessible to the UI.
	// The logs are part of the transaction receipt.
	Logs []*LogEntry
}

VMOutput is the return data and final account state after a SC execution.

func (*VMOutput) GetFirstReturnData added in v0.0.1

func (vmOutput *VMOutput) GetFirstReturnData(asType vm.ReturnDataKind) (interface{}, error)

GetFirstReturnData is a helper function that returns the first ReturnData of VMOutput, interpreted as specified.

func (*VMOutput) GetNextAvailableOutputTransferIndex added in v0.1.5

func (vmOutput *VMOutput) GetNextAvailableOutputTransferIndex() uint32

GetMaxOutputTransferIndex returns the maximum output transfer index

func (*VMOutput) ReindexTransfers added in v0.1.5

func (vmOutput *VMOutput) ReindexTransfers(nextIndexProvider NextOutputTransferIndexProvider) error

ReindexTransfers from VMOutput

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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