util

package
v2.10.2+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2021 License: GPL-3.0 Imports: 12 Imported by: 30

Documentation

Index

Constants

View Source
const (
	// CommonQuotaMultiplier defines base quota multiplier for all accounts
	CommonQuotaMultiplier uint8 = 10

	// QuotaAccumulationBlockCount defines max quota accumulation count
	QuotaAccumulationBlockCount uint64 = 75
)

Variables

View Source
var (
	// AttovPerVite defines decimals of vite
	AttovPerVite = big.NewInt(1e18)
	// CreateContractDataLengthMin defines create contract request block data prefix length before seed fork
	CreateContractDataLengthMin = 13
	// CreateContractDataLengthMinRand defines create contract request block data prefix length after seed fork
	CreateContractDataLengthMinRand = 14
)
View Source
var (
	ErrInvalidMethodParam        = errors.New("invalid method param")
	ErrInvalidQuotaMultiplier    = errors.New("invalid quota multiplier")
	ErrRewardIsNotDrained        = errors.New("reward is not drained")
	ErrInsufficientBalance       = errors.New("insufficient balance for transfer")
	ErrCalcPoWTwice              = errors.New("calc PoW twice referring to one snapshot block")
	ErrAbiMethodNotFound         = errors.New("abi: method not found")
	ErrInvalidResponseLatency    = errors.New("invalid response latency")
	ErrInvalidRandomDegree       = errors.New("invalid random degree")
	ErrAddressNotMatch           = errors.New("current address not match")
	ErrTransactionTypeNotSupport = errors.New("transaction type not supported")
	ErrVersionNotSupport         = errors.New("feature not supported in current snapshot height")
	ErrBlockTypeNotSupported     = errors.New("block type not supported")
	ErrDataNotExist              = errors.New("data not exist")
	ErrContractNotExists         = errors.New("contract not exists")
	ErrNoReliableStatus          = errors.New("no reliable status")

	ErrAddressCollision = errors.New("contract address collision")
	ErrIDCollision      = errors.New("id collision")
	ErrRewardNotDue     = errors.New("reward not due")

	ErrExecutionReverted = errors.New("execution reverted")
	ErrDepth             = errors.New("max call depth exceeded")

	ErrGasUintOverflow           = errors.New("gas uint64 overflow")
	ErrStorageModifyLimitReached = errors.New("contract storage modify count limit reached")
	ErrMemSizeOverflow           = errors.New("memory size uint64 overflow")
	ErrReturnDataOutOfBounds     = errors.New("vm: return data out of bounds")
	ErrBlockQuotaLimitReached    = errors.New("quota limit for block reached")
	ErrAccountQuotaLimitReached  = errors.New("quota limit for account reached")
	ErrOutOfQuota                = errors.New("out of quota")
	ErrInvalidCodeLength         = errors.New("invalid code length")
	ErrInvalidUnconfirmedQuota   = errors.New("calc quota failed, invalid unconfirmed quota")

	ErrStackLimitReached      = errors.New("stack limit reached")
	ErrStackUnderflow         = errors.New("stack underflow")
	ErrInvalidJumpDestination = errors.New("invalid jump destination")
	ErrInvalidOpCode          = errors.New("invalid opcode")

	ErrChainForked          = errors.New("chain forked")
	ErrContractCreationFail = errors.New("contract creation failed")

	ErrExecutionCanceled = errors.New("vm execution canceled")
)
View Source
var PoolOfIntPools = &intPoolPool{
	pools: make([]*IntPool, 0, poolDefaultCap),
}
View Source
var (
	// SolidityPPContractType defines contract type of solidity++ byte code
	SolidityPPContractType uint8 = 1
)

Functions

func AddBalance

func AddBalance(db dbInterface, id *types.TokenTypeId, amount *big.Int)

AddBalance add balance of certain token to current account. Used in response block. Panics when db error.

func BlockGasCost

func BlockGasCost(data []byte, baseGas uint64, snapshotCount uint8, quotaTable *QuotaTable) (uint64, error)

BlockGasCost calculate base quota cost of a block

func CalcQuotaUsed

func CalcQuotaUsed(useQuota bool, quotaTotal, quotaAddition, quotaLeft uint64, err error) (qStakeUsed uint64, qUsed uint64)

CalcQuotaUsed calculate stake quota and total quota used by a block

func CheckFork

func CheckFork(db dbInterface, f func(uint64) bool) bool

CheckFork check whether current snapshot block height is over certain hard fork

func ComputeSendBlockHash

func ComputeSendBlockHash(receiveBlock *ledger.AccountBlock, sendBlock *ledger.AccountBlock, index uint8) types.Hash

func DataQuotaCost

func DataQuotaCost(data []byte, quotaTable *QuotaTable) (uint64, error)

DataQuotaCost calculate quota cost by request block data

func DealWithErr

func DealWithErr(v interface{})

DealWithErr panics if err is not nil. Used when chain forked or db error.

func FirstToLower

func FirstToLower(str string) string

FirstToLower change first character for string to lower case

func GetCodeFromCreateContractData added in v1.2.0

func GetCodeFromCreateContractData(data []byte, snapshotHeight uint64) []byte

GetCodeFromCreateContractData decode code and constructor params from create contract request block data

func GetContractCode added in v1.2.0

func GetContractCode(db dbInterface, addr *types.Address, status GlobalStatus) ([]byte, []byte)

GetContractCode get contract in certain snapshot block. if input addr == current address,

return contract code in latest contract account block.

if input addr != current address,

return contract code in snapshot block of global status.

Panics when db error.

func GetContractTypeFromCreateContractData added in v1.2.0

func GetContractTypeFromCreateContractData(data []byte) uint8

GetContractTypeFromCreateContractData decode contract type from create contract request block data

func GetCreateContractData added in v1.2.0

func GetCreateContractData(bytecode []byte, contractType uint8, snapshotCount uint8, snapshotWithSeedCount uint8, quotaMultiplier uint8, gid types.Gid) []byte

GetCreateContractData generate create contract request block data

func GetGidFromCreateContractData added in v1.2.0

func GetGidFromCreateContractData(data []byte) types.Gid

GetGidFromCreateContractData decode gid from create contract request block data

func GetQuotaMultiplierFromCreateContractData

func GetQuotaMultiplierFromCreateContractData(data []byte, snapshotHeight uint64) uint8

GetQuotaMultiplierFromCreateContractData decode quota multiplier from create contract request block data

func GetSnapshotCountFromCreateContractData

func GetSnapshotCountFromCreateContractData(data []byte) uint8

GetSnapshotCountFromCreateContractData decode snapshot block count(response latency) from create contract request block data

func GetSnapshotWithSeedCountCountFromCreateContractData

func GetSnapshotWithSeedCountCountFromCreateContractData(data []byte) uint8

GetSnapshotWithSeedCountCountFromCreateContractData decode snapshot block with seed count(random degree) from create contract request block data

func GetValue

func GetValue(db dbInterface, key []byte) []byte

GetValue get current contract storage value by key. Panics when db error.

func IsDelegateGid

func IsDelegateGid(gid types.Gid) bool

IsDelegateGid checks whether gid is global delegate consensus group id

func IsExistContractType added in v1.2.0

func IsExistContractType(contractType uint8) bool

IsExistContractType check contract type validation

func IsPoW

func IsPoW(block *ledger.AccountBlock) bool

IsPoW check whether a block calculated pow

func IsSnapshotGid

func IsSnapshotGid(gid types.Gid) bool

IsSnapshotGid checks whether gid is snapshot consensus group id

func IsViteToken

func IsViteToken(tokenID types.TokenTypeId) bool

IsViteToken checks whether tokenId is vite token

func MakeRequestBlock

func MakeRequestBlock(fromAddress types.Address, toAddress types.Address, blockType byte, amount *big.Int, tokenID types.TokenTypeId, data []byte) *ledger.AccountBlock

MakeRequestBlock returns a request block

func MultipleCost

func MultipleCost(cost uint64, quotaMultiplier uint8) (uint64, error)

MultipleCost multiply quota

func NewContractAddress added in v1.2.0

func NewContractAddress(accountAddress types.Address, accountBlockHeight uint64, prevBlockHash types.Hash) types.Address

NewContractAddress generate contract address in create contract request block

func PackContractCode added in v1.2.0

func PackContractCode(contractType uint8, code []byte) []byte

PackContractCode generate contract code on chain

func PrintMap added in v1.2.0

func PrintMap(m map[string][]byte) string

PrintMap is used to print storage map under debug mode

func RequestQuotaCost

func RequestQuotaCost(data []byte, quotaTable *QuotaTable) (uint64, error)

RequestQuotaCost calculate quota cost by a request block

func SetValue

func SetValue(db dbInterface, key []byte, value []byte)

SetValue update current contract storage value by key. Delete key when value is nil. Key len must be no more than 32 bytes. Panics when db error.

func SubBalance

func SubBalance(db dbInterface, id *types.TokenTypeId, amount *big.Int)

SubBalance sub balance of certain token to current account. Balance check must be performed before calling this method. Used in request block. Panics when db error.

func UseQuota

func UseQuota(quotaLeft, cost uint64) (uint64, error)

UseQuota check out of quota and return quota left

func UseQuotaWithFlag

func UseQuotaWithFlag(quotaLeft, cost uint64, flag bool) (uint64, error)

UseQuotaWithFlag check out of quota and return quota left

Types

type ConsensusReader

type ConsensusReader interface {
	GetIndexByStartTime(t int64, genesisTime int64) (startIndex uint64, startTime int64, drained bool)
	GetIndexByEndTime(t int64, genesisTime int64) (endIndex uint64, endTime int64, withinADay bool)
	GetIndexByTime(t int64, genesisTime int64) uint64
	GetEndTimeByIndex(index uint64) int64
	GetConsensusDetailByDay(startIndex, endIndex uint64) ([]*core.DayStats, error)
}

ConsensusReader defines interfaces of consensus reader in vm module used by sbp reward calculation

type GlobalStatus

type GlobalStatus interface {
	Seed() (uint64, error)                // Random number, returns same number
	Random() (uint64, error)              // Random number, returns different number every time calls
	SnapshotBlock() *ledger.SnapshotBlock // Confirm snapshot block of send block
}

GlobalStatus contains confirm snapshot block and seed of contract response block

type IntPool

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

intPool is a pool of big integers that can be reused for all big.Int operations.

func (*IntPool) Get

func (p *IntPool) Get() *big.Int

get retrieves a big int from the pool, allocating one if the pool is empty. Note, the returned int's amount is arbitrary and will not be zeroed!

func (*IntPool) GetZero

func (p *IntPool) GetZero() *big.Int

getZero retrieves a big int from the pool, setting it to zero or allocating a new one if the pool is empty.

func (*IntPool) Put

func (p *IntPool) Put(is ...*big.Int)

put returns an allocated big int to the pool to be later reused by get calls. Note, the values as saved as is; neither put nor get zeroes the ints out!

type QuotaTable

type QuotaTable struct {
	AddQuota            uint64
	MulQuota            uint64
	SubQuota            uint64
	DivQuota            uint64
	SDivQuota           uint64
	ModQuota            uint64
	SModQuota           uint64
	AddModQuota         uint64
	MulModQuota         uint64
	ExpQuota            uint64
	ExpByteQuota        uint64
	SignExtendQuota     uint64
	LtQuota             uint64
	GtQuota             uint64
	SltQuota            uint64
	SgtQuota            uint64
	EqQuota             uint64
	IsZeroQuota         uint64
	AndQuota            uint64
	OrQuota             uint64
	XorQuota            uint64
	NotQuota            uint64
	ByteQuota           uint64
	ShlQuota            uint64
	ShrQuota            uint64
	SarQuota            uint64
	Blake2bQuota        uint64
	Blake2bWordQuota    uint64
	AddressQuota        uint64
	BalanceQuota        uint64
	CallerQuota         uint64
	CallValueQuota      uint64
	CallDataLoadQuota   uint64
	CallDataSizeQuota   uint64
	CallDataCopyQuota   uint64
	MemCopyWordQuota    uint64
	CodeSizeQuota       uint64
	CodeCopyQuota       uint64
	ReturnDataSizeQuota uint64
	ReturnDataCopyQuota uint64
	TimestampQuota      uint64
	HeightQuota         uint64
	TokenIDQuota        uint64
	AccountHeightQuota  uint64
	PreviousHashQuota   uint64
	FromBlockHashQuota  uint64
	SeedQuota           uint64
	RandomQuota         uint64
	PopQuota            uint64
	MloadQuota          uint64
	MstoreQuota         uint64
	Mstore8Quota        uint64
	SloadQuota          uint64
	SstoreResetQuota    uint64
	SstoreInitQuota     uint64
	SstoreCleanQuota    uint64
	SstoreNoopQuota     uint64
	SstoreMemQuota      uint64
	JumpQuota           uint64
	JumpiQuota          uint64
	PcQuota             uint64
	MsizeQuota          uint64
	JumpdestQuota       uint64
	PushQuota           uint64
	DupQuota            uint64
	SwapQuota           uint64
	LogQuota            uint64
	LogTopicQuota       uint64
	LogDataQuota        uint64
	CallMinusQuota      uint64
	MemQuotaDivision    uint64
	SnapshotQuota       uint64
	CodeQuota           uint64
	MemQuota            uint64

	TxQuota               uint64
	TxDataQuota           uint64
	CreateTxRequestQuota  uint64
	CreateTxResponseQuota uint64

	RegisterQuota                             uint64
	UpdateBlockProducingAddressQuota          uint64
	UpdateRewardWithdrawAddressQuota          uint64
	RevokeQuota                               uint64
	WithdrawRewardQuota                       uint64
	VoteQuota                                 uint64
	CancelVoteQuota                           uint64
	StakeQuota                                uint64
	CancelStakeQuota                          uint64
	DelegateStakeQuota                        uint64
	CancelDelegateStakeQuota                  uint64
	IssueQuota                                uint64
	ReIssueQuota                              uint64
	BurnQuota                                 uint64
	TransferOwnershipQuota                    uint64
	DisableReIssueQuota                       uint64
	GetTokenInfoQuota                         uint64
	DexFundDepositQuota                       uint64
	DexFundWithdrawQuota                      uint64
	DexFundOpenNewMarketQuota                 uint64
	DexFundPlaceOrderQuota                    uint64
	DexFundSettleOrdersQuota                  uint64
	DexFundTriggerPeriodJobQuota              uint64
	DexFundStakeForMiningQuota                uint64
	DexFundStakeForVipQuota                   uint64
	DexFundStakeForSuperVIPQuota              uint64
	DexFundDelegateStakeCallbackQuota         uint64
	DexFundCancelDelegateStakeCallbackQuota   uint64
	DexFundGetTokenInfoCallbackQuota          uint64
	DexFundAdminConfigQuota                   uint64
	DexFundTradeAdminConfigQuota              uint64
	DexFundMarketAdminConfigQuota             uint64
	DexFundTransferTokenOwnershipQuota        uint64
	DexFundNotifyTimeQuota                    uint64
	DexFundCreateNewInviterQuota              uint64
	DexFundBindInviteCodeQuota                uint64
	DexFundEndorseVxQuota                     uint64
	DexFundSettleMakerMinedVxQuota            uint64
	DexFundConfigMarketAgentsQuota            uint64
	DexFundPlaceAgentOrderQuota               uint64
	DexFundLockVxForDividendQuota             uint64
	DexFundSwitchConfigQuota                  uint64
	DexFundStakeForPrincipalSuperVIPQuota     uint64
	DexFundCancelStakeByIdQuota               uint64
	DexFundDelegateStakeCallbackV2Quota       uint64
	DexFundDelegateCancelStakeCallbackV2Quota uint64
	DexFundCancelOrderBySendHashQuota         uint64
	DexFundCommonAdminConfigQuota             uint64
}

QuotaTable is used to query quota used by op code and transactions

func QuotaTableByHeight

func QuotaTableByHeight(sbHeight uint64) *QuotaTable

QuotaTableByHeight returns different quota table by hard fork version

type VMConsensusReader

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

VMConsensusReader implements consensus reader interfaces

func NewVMConsensusReader

func NewVMConsensusReader(sr sbpStatReader) *VMConsensusReader

NewVMConsensusReader generate VMConsensusReader instance

func (*VMConsensusReader) GetConsensusDetailByDay

func (r *VMConsensusReader) GetConsensusDetailByDay(startIndex, endIndex uint64) ([]*core.DayStats, error)

GetConsensusDetailByDay returns the top 100 sbp block producing details of each cycle. Used for calculating sbp reward. Parameters:

startIndex: start cycle index(included)
endIndex: end cycle index(included)

Returns:

1: block producing details of each cycle
2: db error

func (*VMConsensusReader) GetEndTimeByIndex

func (r *VMConsensusReader) GetEndTimeByIndex(index uint64) int64

GetEndTimeByIndex calculate cycle end time of index Parameters:

index: cycle index

Returns:

end time of input cycle

func (*VMConsensusReader) GetIndexByEndTime

func (r *VMConsensusReader) GetIndexByEndTime(t int64, genesisTime int64) (uint64, int64, bool)

GetIndexByEndTime calculate first cycle index before t Parameters:

t: timestamp
genesisTime: genesis snapshot block timestamp

Returns:

1: first cycle index before input timestamp
2: start time of cycle
3: is reward drained, true - reward is drained,
   false - reward is not drained

Notes: if t <= genesis time + 24h, return index 0, within one day if t ∈ (genesis time + 24h, genesis time + 48h], return index 0

func (*VMConsensusReader) GetIndexByStartTime

func (r *VMConsensusReader) GetIndexByStartTime(t int64, genesisTime int64) (uint64, int64, bool)

GetIndexByStartTime calculate first cycle index after t Parameters:

t: timestamp
genesisTime: genesis snapshot block timestamp

Returns:

1: first cycle index after input timestamp
2: start time of cycle
3: is reward drained, true - reward is drained,
   false - reward is not drained

Notes:

index 0 : (genesis time, genesis time + 24h]
index 1: (genesis time + 24h, genesis time + 48h]
get first index after t and index start time
if t == -1, reward drained
if t == 0, return index 0
if t ∈ (genesis time, genesis time + 24h], return index 1

func (*VMConsensusReader) GetIndexByTime

func (r *VMConsensusReader) GetIndexByTime(t int64, genesisTime int64) uint64

GetIndexByTime calculate cycle index of t Parameters:

t: timestamp
genesisTime: genesis snapshot block timestamp

Returns:

cycle index of input timestamp

Jump to

Keyboard shortcuts

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