nvm

package
v2.1.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2019 License: LGPL-3.0 Imports: 31 Imported by: 2

Documentation

Index

Constants

View Source
const (
	ExecutionFailedErr  = 1
	ExecutionTimeOutErr = 2

	// ExecutionTimeout max v8 execution timeout.
	ExecutionTimeout                 = 15 * 1000 * 1000
	OriginExecutionTimeout           = 5 * 1000 * 1000
	CompatibleExecutionTimeout       = 20 * 1000 * 1000
	TimeoutGasLimitCost              = 100000000
	MaxLimitsOfExecutionInstructions = 10000000 // TODO: set max gasLimit with execution 5s *0.8
)
View Source
const (
	// InnerTransferFailed failed status for transaction execute result.
	InnerTransferFailed = 0

	// InnerTransferExecutionSuccess success status for transaction execute result.
	InnerTransferExecutionSuccess = 1
)
View Source
const (
	JSLibRootName    = "lib/"
	JSLibRootNameLen = 4
)

const

View Source
const (
	EventNameSpaceContract    = "chain.contract" //ToRefine: move to core
	InnerTransactionErrPrefix = "inner transation err ["
	InnerTransactionResult    = "] result ["
	InnerTransactionErrEnding = "] engine index:%v"
)

define

View Source
const (
	SuccessTransferFunc = iota
	SuccessTransfer
	ErrTransferGetEngine
	ErrTransferAddressParse
	ErrTransferGetAccount
	ErrTransferStringToUint128
	ErrTransferSubBalance
	ErrTransferAddBalance
	ErrTransferRecordEvent
	ErrTransferAddress
)

transfer err code enum

View Source
const (
	// crypto
	CryptoSha256GasBase         = 20000
	CryptoSha3256GasBase        = 20000
	CryptoRipemd160GasBase      = 20000
	CryptoRecoverAddressGasBase = 100000
	CryptoMd5GasBase            = 6000
	CryptoBase64GasBase         = 3000

	//In blockChain
	GetTxByHashGasBase     = 1000
	GetAccountStateGasBase = 2000
	TransferGasBase        = 2000
	VerifyAddressGasBase   = 100
	GetPreBlockHashGasBase = 2000
	GetPreBlockSeedGasBase = 2000

	//inner nvm
	GetContractSourceGasBase = 5000
	InnerContractGasBase     = 32000

	//random
	GetTxRandomGasBase = 1000

	//nr
	GetLatestNebulasRankGasBase        = 20000
	GetLatestNebulasRankSummaryGasBase = 20000
)

define gas consume

View Source
const (
	// EventBaseGasCount the gas count of a new event
	EventBaseGasCount = 20
)
View Source
const (
	MaxInnerContractLevel = 3
)

inner nvm

Variables

View Source
var (
	// StorageKeyPattern the pattern of varible key stored in stateDB
	/*
		const fieldNameRe = /^[a-zA-Z_$][a-zA-Z0-9_]+$/;
		var combineStorageMapKey = function (fieldName, key) {
			return "@" + fieldName + "[" + key + "]";
		};
	*/
	StorageKeyPattern = regexp.MustCompile("^@([a-zA-Z_$][a-zA-Z0-9_]+?)\\[(.*?)\\]$")
	// DefaultDomainKey the default domain key
	DefaultDomainKey = "_"
	// ErrInvalidStorageKey invalid storage key error
	ErrInvalidStorageKey = errors.New("invalid storage key")
)
View Source
var (
	ErrEngineRepeatedStart      = errors.New("engine repeated start")
	ErrEngineNotStart           = errors.New("engine not start")
	ErrContextConstructArrEmpty = errors.New("context construct err by args empty")
	ErrEngineNotFound           = errors.New("Failed to get engine")

	ErrDisallowCallPrivateFunction     = errors.New("disallow call private function")
	ErrExecutionTimeout                = errors.New("execution timeout")
	ErrInsufficientGas                 = errors.New("insufficient gas")
	ErrExceedMemoryLimits              = errors.New("exceed memory limits")
	ErrInjectTracingInstructionFailed  = errors.New("inject tracing instructions failed")
	ErrTranspileTypeScriptFailed       = errors.New("transpile TypeScript failed")
	ErrUnsupportedSourceType           = errors.New("unsupported source type")
	ErrArgumentsFormat                 = errors.New("arguments format error")
	ErrLimitHasEmpty                   = errors.New("limit args has empty")
	ErrSetMemorySmall                  = errors.New("set memory small than v8 limit")
	ErrDisallowCallNotStandardFunction = errors.New("disallow call not standard function")

	ErrMaxInnerContractLevelLimit = errors.New("out of limit nvm count")
	ErrInnerTransferFailed        = errors.New("inner transfer failed")
	ErrInnerInsufficientGas       = errors.New("preparation inner nvm insufficient gas")
	ErrInnerInsufficientMem       = errors.New("preparation inner nvm insufficient mem")

	ErrOutOfNvmMaxGasLimit = errors.New("out of nvm max gas limit")
)

Error Types

View Source
var (
	ErrKeyNotFound = storage.ErrKeyNotFound
)

common err

Functions

func AttachLibVersionDelegateFunc added in v1.0.5

func AttachLibVersionDelegateFunc(handler unsafe.Pointer, require *C.char) *C.char

AttachLibVersionDelegateFunc delegate func for lib version choose

func Base64Func added in v1.0.5

func Base64Func(data *C.char, gasCnt *C.size_t) *C.char

Base64Func ..

func ClearSourceModuleCache

func ClearSourceModuleCache()

ClearModuleCache ..

func DisposeV8Engine

func DisposeV8Engine()

DisposeV8Engine dispose the v8 engine.

func EventTriggerFunc added in v1.0.0

func EventTriggerFunc(handler unsafe.Pointer, topic, data *C.char, gasCnt *C.size_t)

EventTriggerFunc export EventTriggerFunc

func GetAccountStateFunc added in v1.0.0

func GetAccountStateFunc(handler unsafe.Pointer, address *C.char, gasCnt *C.size_t,
	result **C.char, exceptionInfo **C.char) int

GetAccountStateFunc returns account info by address

func GetContractSourceFunc

func GetContractSourceFunc(handler unsafe.Pointer, address *C.char, gasCnt *C.size_t) *C.char

GetContractSourceFunc get contract code by address

func GetLatestNebulasRankFunc

func GetLatestNebulasRankFunc(handler unsafe.Pointer, address *C.char,
	gasCnt *C.size_t, result **C.char, exceptionInfo **C.char) int

GetLatestNebulasRankFunc returns nebulas rank value of given account address

func GetLatestNebulasRankSummaryFunc

func GetLatestNebulasRankSummaryFunc(handler unsafe.Pointer,
	gasCnt *C.size_t, result **C.char, exceptionInfo **C.char) int

GetLatestNebulasRankSummaryFunc returns nebulas rank summary info.

func GetPreBlockHashFunc added in v1.0.5

func GetPreBlockHashFunc(handler unsafe.Pointer, offset C.ulonglong,
	gasCnt *C.size_t, result **C.char, exceptionInfo **C.char) int

GetPreBlockHashFunc returns hash of the block before current tail by n

func GetPreBlockSeedFunc added in v1.0.5

func GetPreBlockSeedFunc(handler unsafe.Pointer, offset C.ulonglong,
	gasCnt *C.size_t, result **C.char, exceptionInfo **C.char) int

GetPreBlockSeedFunc returns hash of the block before current tail by n

func GetTxByHashFunc added in v1.0.0

func GetTxByHashFunc(handler unsafe.Pointer, hash *C.char, gasCnt *C.size_t) *C.char

GetTxByHashFunc returns tx info by hash

func GetTxRandomFunc

func GetTxRandomFunc(handler unsafe.Pointer, gasCnt *C.size_t, result **C.char, exceptionInfo **C.char) int

GetTxRandomFunc return random

func InitV8Engine

func InitV8Engine()

InitV8Engine initialize the v8 engine.

func InnerContractFunc

func InnerContractFunc(handler unsafe.Pointer, address *C.char, funcName *C.char, v *C.char, args *C.char, gasCnt *C.size_t) *C.char

InnerContractFunc multi run contract. output[c standard]: if err return nil else return "*"

func Md5Func added in v1.0.5

func Md5Func(data *C.char, gasCnt *C.size_t) *C.char

Md5Func ..

func NewNebulasVM added in v1.0.0

func NewNebulasVM() core.NVM

NewNebulasVM create new NebulasVM

func RecoverAddressFunc added in v1.0.5

func RecoverAddressFunc(alg int, data, sign *C.char, gasCnt *C.size_t) *C.char

RecoverAddressFunc ..

func RequireDelegateFunc added in v1.0.0

func RequireDelegateFunc(handler unsafe.Pointer, filename *C.char, lineOffset *C.size_t) *C.char

RequireDelegateFunc delegate func for require.

func Ripemd160Func added in v1.0.5

func Ripemd160Func(data *C.char, gasCnt *C.size_t) *C.char

Ripemd160Func ..

func Sha256Func added in v1.0.5

func Sha256Func(data *C.char, gasCnt *C.size_t) *C.char

Sha256Func ..

func Sha3256Func added in v1.0.5

func Sha3256Func(data *C.char, gasCnt *C.size_t) *C.char

Sha3256Func ..

func StorageDelFunc

func StorageDelFunc(handler unsafe.Pointer, key *C.char, gasCnt *C.size_t) int

StorageDelFunc export StorageDelFunc

func StorageGetFunc

func StorageGetFunc(handler unsafe.Pointer, key *C.char, gasCnt *C.size_t) *C.char

StorageGetFunc export StorageGetFunc

func StoragePutFunc

func StoragePutFunc(handler unsafe.Pointer, key *C.char, value *C.char, gasCnt *C.size_t) int

StoragePutFunc export StoragePutFunc

func TransferByAddress

func TransferByAddress(handler unsafe.Pointer, from *core.Address, to *core.Address, value *util.Uint128) int

TransferByAddress value from to

func TransferFunc added in v1.0.0

func TransferFunc(handler unsafe.Pointer, to *C.char, v *C.char, gasCnt *C.size_t) int

TransferFunc transfer vale to address

func V8Log

func V8Log(level int, msg *C.char)

V8Log export V8Log

func VerifyAddressFunc added in v1.0.0

func VerifyAddressFunc(handler unsafe.Pointer, address *C.char, gasCnt *C.size_t) int

VerifyAddressFunc verify address is valid

Types

type Account added in v1.0.0

type Account interface {
	Address() byteutils.Hash
	Balance() *util.Uint128
	Nonce() uint64
	AddBalance(value *util.Uint128) error
	SubBalance(value *util.Uint128) error
	Put(key []byte, value []byte) error
	Get(key []byte) ([]byte, error)
	Del(key []byte) error
	ContractMeta() *corepb.ContractMeta
}

Account interface breaks cycle import dependency and hides unused services.

type Block added in v1.0.0

type Block interface {
	Hash() byteutils.Hash
	Height() uint64 // ToAdd: timestamp interface
	Timestamp() int64
	RandomSeed() string
	RandomAvailable() bool
	DateAvailable() bool
	NR() core.NR
}

Block interface breaks cycle import dependency and hides unused services.

type Context added in v1.0.0

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

Context nvm engine context

func NewContext added in v1.0.0

func NewContext(block Block, tx Transaction, contract Account, state WorldState) (*Context, error)

NewContext create a engine context

func NewInnerContext

func NewInnerContext(block Block, tx Transaction, contract Account, state WorldState, head unsafe.Pointer, index uint32, ctxRand *ContextRand) (*Context, error)

NewInnerContext create a child engine context

type ContextRand

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

ContextRand ..

type InnerContractEvent

type InnerContractEvent struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Value    string `json:"value"`
	Err      string `json:"error"`
	Function string `json:"function,omitempty"`
	Args     string `json:"args,omitempty"`
}

InnerTransferContractEvent event for inner transfer in contract

type Module added in v1.0.0

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

Module module structure.

func NewModule added in v1.0.0

func NewModule(id, source string, lineOffset int) *Module

NewModule create new module and return it.

type Modules added in v1.0.0

type Modules map[string]*Module

Modules module maps.

func NewModules added in v1.0.0

func NewModules() Modules

NewModules create new modules and return it.

func (Modules) Add added in v1.0.0

func (ms Modules) Add(m *Module)

Add add source to module.

func (Modules) Get added in v1.0.0

func (ms Modules) Get(id string) *Module

Get get module from Modules by id.

type MultiV8error

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

MultiV8error err info, err only in InnerContractFunc .so not to deine #

type NebulasVM added in v1.0.0

type NebulasVM struct{}

NebulasVM type of NebulasVM

func (*NebulasVM) CheckV8Run added in v1.0.1

func (nvm *NebulasVM) CheckV8Run() error

CheckV8Run to check V8 env is OK

func (*NebulasVM) CreateEngine added in v1.0.0

func (nvm *NebulasVM) CreateEngine(block *core.Block, tx *core.Transaction, contract state.Account, state core.WorldState) (core.SmartContractEngine, error)

CreateEngine start engine

type Payload

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

Payload struct in getPayloadByAddress

type SerializableAccount added in v1.0.0

type SerializableAccount struct {
	Nonce   uint64 `json:"nonce"`
	Balance string `json:"balance"`
}

SerializableAccount serializable account state

type SerializableBlock added in v1.0.0

type SerializableBlock struct {
	Timestamp int64  `json:"timestamp"`
	Hash      string `json:"hash"`
	Height    uint64 `json:"height"`
	Seed      string `json:"seed,omitempty"`
}

SerializableBlock serializable block

type SerializableTransaction added in v1.0.0

type SerializableTransaction struct {
	Hash      string `json:"hash"`
	From      string `json:"from"`
	To        string `json:"to"`
	Value     string `json:"value"`
	Nonce     uint64 `json:"nonce"`
	Timestamp int64  `json:"timestamp"`
	GasPrice  string `json:"gasPrice"`
	GasLimit  string `json:"gasLimit"`
}

SerializableTransaction serializable transaction

type Transaction added in v1.0.0

type Transaction interface {
	ChainID() uint32
	Hash() byteutils.Hash
	From() *core.Address
	To() *core.Address
	Value() *util.Uint128
	Nonce() uint64
	Timestamp() int64
	GasPrice() *util.Uint128
	GasLimit() *util.Uint128
	NewInnerTransaction(from, to *core.Address, value *util.Uint128, payloadType string, payload []byte) (*core.Transaction, error)
}

Transaction interface breaks cycle import dependency and hides unused services.

type TransferFromContractEvent added in v1.0.2

type TransferFromContractEvent struct {
	Amount string `json:"amount"`
	From   string `json:"from"`
	To     string `json:"to"`
}

TransferFromContractEvent event for transfer in contract

type TransferFromContractFailureEvent added in v1.0.5

type TransferFromContractFailureEvent struct {
	Amount string `json:"amount"`
	From   string `json:"from"`
	To     string `json:"to"`
	Status uint8  `json:"status"`
	Error  string `json:"error"`
}

TransferFromContractFailureEvent event for transfer in contract

type V8Engine

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

V8Engine v8 engine.

func NewV8Engine

func NewV8Engine(ctx *Context) *V8Engine

NewV8Engine return new V8Engine instance.

func (*V8Engine) AddModule added in v1.0.0

func (e *V8Engine) AddModule(id, source string, sourceLineOffset int) error

AddModule add module.

func (*V8Engine) Call

func (e *V8Engine) Call(source, sourceType, function, args string) (string, error)

Call function in a script

func (*V8Engine) CollectTracingStats added in v1.0.0

func (e *V8Engine) CollectTracingStats()

CollectTracingStats collect tracing data from v8 engine.

func (*V8Engine) Context added in v1.0.0

func (e *V8Engine) Context() *Context

Context returns engine context

func (*V8Engine) DeployAndInit

func (e *V8Engine) DeployAndInit(source, sourceType, args string) (string, error)

DeployAndInit a contract

func (*V8Engine) Dispose

func (e *V8Engine) Dispose()

Dispose dispose all resources.

func (*V8Engine) EnableInnerContract

func (e *V8Engine) EnableInnerContract()

func (*V8Engine) ExecutionInstructions added in v1.0.0

func (e *V8Engine) ExecutionInstructions() uint64

ExecutionInstructions returns the execution instructions

func (*V8Engine) GetNVMLeftResources

func (e *V8Engine) GetNVMLeftResources() (uint64, uint64)

GetNVMLeftResources return current NVM verb total resource

func (*V8Engine) InjectTracingInstructions added in v1.0.0

func (e *V8Engine) InjectTracingInstructions(source string) (string, int, error)

InjectTracingInstructions process the source to inject tracing instructions.

func (*V8Engine) RunContractScript added in v1.0.0

func (e *V8Engine) RunContractScript(source, sourceType, function, args string) (string, error)

RunContractScript execute script in Smart Contract's way.

func (*V8Engine) RunScriptSource

func (e *V8Engine) RunScriptSource(source string, sourceLineOffset int) (string, error)

RunScriptSource run js source.

func (*V8Engine) SetEnableLimit added in v1.0.0

func (e *V8Engine) SetEnableLimit(isLimit bool)

SetEnableLimit eval switch

func (*V8Engine) SetExecutionLimits added in v1.0.0

func (e *V8Engine) SetExecutionLimits(limitsOfExecutionInstructions, limitsOfTotalMemorySize uint64) error

SetExecutionLimits set execution limits of V8 Engine, prevent Halting Problem.

func (*V8Engine) SetTestingFlag added in v1.0.0

func (e *V8Engine) SetTestingFlag(flag bool)

SetTestingFlag set testing flag, default is False.

func (*V8Engine) SetTimeOut added in v1.0.5

func (e *V8Engine) SetTimeOut(timeout uint64)

SetTimeOut set nvm timeout, if not set, the default is 5*1000*1000

func (*V8Engine) TranspileTypeScript added in v1.0.0

func (e *V8Engine) TranspileTypeScript(source string) (string, int, error)

TranspileTypeScript transpile typescript to javascript and return it.

type WorldState added in v1.0.0

type WorldState interface {
	GetOrCreateUserAccount(addr byteutils.Hash) (state.Account, error)
	GetTx(txHash byteutils.Hash) ([]byte, error)
	RecordEvent(txHash byteutils.Hash, event *state.Event)
	GetBlockHashByHeight(height uint64) ([]byte, error)
	GetBlock(txHash byteutils.Hash) ([]byte, error)
	CreateContractAccount(owner byteutils.Hash, birthPlace byteutils.Hash, contractMeta *corepb.ContractMeta) (state.Account, error)
	Dynasty() ([]byteutils.Hash, error)
	DynastyRoot() byteutils.Hash
	FetchEvents(byteutils.Hash) ([]*state.Event, error)
	GetContractAccount(addr byteutils.Hash) (state.Account, error)
	PutTx(txHash byteutils.Hash, txBytes []byte) error
	RecordGas(from string, gas *util.Uint128) error
	Reset(addr byteutils.Hash, isResetChangeLog bool) error //Need to consider risk
}

WorldState interface breaks cycle import dependency and hides unused services.

Jump to

Keyboard shortcuts

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