core

package
v0.98.1-pre Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2021 License: MIT Imports: 47 Imported by: 4

Documentation

Overview

Package core implements Neo ledger functionality. It's built around the Blockchain structure that maintains state of the ledger.

Events

You can subscribe to Blockchain events using a set of Subscribe and Unsubscribe methods. These methods accept channels that will be used to send appropriate events, so you can control buffering. Channels are never closed by Blockchain, you can close them after unsubscription.

Unlike RPC-level subscriptions these don't allow event filtering because it doesn't improve overall efficiency much (when you're using Blockchain you're in the same process with it and filtering on your side is not that different from filtering on Blockchain side).

The same level of ordering guarantees as with RPC subscriptions is provided, albeit for a set of event channels, so at first transaction execution is announced via appropriate channels, then followed by notifications generated during this execution, then followed by transaction announcement and then followed by block announcement. Transaction announcements are ordered the same way they're stored in the block.

Be careful using these subscriptions, this mechanism is not intended to be used by lots of subscribers and failing to read from event channels can affect other Blockchain operations.

Index

Constants

View Source
const (

	// HeaderVerificationGasLimit is the maximum amount of GAS for block header verification.
	HeaderVerificationGasLimit = 3_00000000 // 3 GAS

)

Tuning parameters.

Variables

View Source
var (
	// ErrAlreadyExists is returned when trying to add some already existing
	// transaction into the pool (not specifying whether it exists in the
	// chain or mempool).
	ErrAlreadyExists = errors.New("already exists")
	// ErrOOM is returned when adding transaction to the memory pool because
	// it reached its full capacity.
	ErrOOM = errors.New("no space left in the memory pool")
	// ErrPolicy is returned on attempt to add transaction that doesn't
	// comply with node's configured policy into the mempool.
	ErrPolicy = errors.New("not allowed by policy")
	// ErrInvalidBlockIndex is returned when trying to add block with index
	// other than expected height of the blockchain.
	ErrInvalidBlockIndex = errors.New("invalid block index")
	// ErrHasConflicts is returned when trying to add some transaction which
	// conflicts with other transaction in the chain or pool according to
	// Conflicts attribute.
	ErrHasConflicts = errors.New("has conflicts")
)
View Source
var (
	ErrHdrHashMismatch     = errors.New("previous header hash doesn't match")
	ErrHdrIndexMismatch    = errors.New("previous header index doesn't match")
	ErrHdrInvalidTimestamp = errors.New("block is not newer than the previous one")
	ErrHdrStateRootSetting = errors.New("state root setting mismatch")
	ErrHdrInvalidStateRoot = errors.New("state root for previous block is invalid")
)

Various errors that could be returns upon header verification.

View Source
var (
	ErrTxExpired         = errors.New("transaction has expired")
	ErrInsufficientFunds = errors.New("insufficient funds")
	ErrTxSmallNetworkFee = errors.New("too small network fee")
	ErrTxTooBig          = errors.New("too big transaction")
	ErrMemPoolConflict   = errors.New("invalid transaction due to conflicts with the memory pool")
	ErrInvalidScript     = errors.New("invalid script")
	ErrInvalidAttribute  = errors.New("invalid attribute")
)

Various errors that could be returned upon verification.

View Source
var (
	ErrWitnessHashMismatch         = errors.New("witness hash mismatch")
	ErrNativeContractWitness       = errors.New("native contract witness must have empty verification script")
	ErrVerificationFailed          = errors.New("signature check failed")
	ErrInvalidInvocation           = errors.New("invalid invocation script")
	ErrInvalidSignature            = fmt.Errorf("%w: invalid signature", ErrVerificationFailed)
	ErrInvalidVerification         = errors.New("invalid verification script")
	ErrUnknownVerificationContract = errors.New("unknown verification contract")
	ErrInvalidVerificationContract = errors.New("verification contract is missing `verify` method")
)

Various witness verification errors.

Functions

func SpawnVM added in v0.90.0

func SpawnVM(ic *interop.Context) *vm.VM

SpawnVM returns a VM with script getter and interop functions set up for current blockchain.

Types

type Blockchain

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

Blockchain represents the blockchain. It maintans internal state representing the state of the ledger that can be accessed in various ways and changed by adding new blocks or headers.

func NewBlockchain

func NewBlockchain(s storage.Store, cfg config.ProtocolConfiguration, log *zap.Logger) (*Blockchain, error)

NewBlockchain returns a new blockchain object the will use the given Store as its underlying storage. For it to work correctly you need to spawn a goroutine for its Run method after this initialization.

func (*Blockchain) AddBlock

func (bc *Blockchain) AddBlock(block *block.Block) error

AddBlock accepts successive block for the Blockchain, verifies it and stores internally. Eventually it will be persisted to the backing storage.

func (*Blockchain) AddHeaders

func (bc *Blockchain) AddHeaders(headers ...*block.Header) error

AddHeaders processes the given headers and add them to the HeaderHashList. It expects headers to be sorted by index.

func (*Blockchain) ApplyPolicyToTxSet

func (bc *Blockchain) ApplyPolicyToTxSet(txes []*transaction.Transaction) []*transaction.Transaction

ApplyPolicyToTxSet applies configured policies to given transaction set. It expects slice to be ordered by fee and returns a subslice of it.

func (*Blockchain) BlockHeight

func (bc *Blockchain) BlockHeight() uint32

BlockHeight returns the height/index of the highest block.

func (*Blockchain) CalculateClaimable

func (bc *Blockchain) CalculateClaimable(acc util.Uint160, endHeight uint32) (*big.Int, error)

CalculateClaimable calculates the amount of GAS generated by owning specified amount of NEO between specified blocks.

func (*Blockchain) Close

func (bc *Blockchain) Close()

Close stops Blockchain's internal loop, syncs changes to persistent storage and closes it. The Blockchain is no longer functional after the call to Close.

func (*Blockchain) CurrentBlockHash

func (bc *Blockchain) CurrentBlockHash() util.Uint256

CurrentBlockHash returns the highest processed block hash.

func (*Blockchain) CurrentHeaderHash

func (bc *Blockchain) CurrentHeaderHash() util.Uint256

CurrentHeaderHash returns the hash of the latest known header.

func (*Blockchain) FeePerByte

func (bc *Blockchain) FeePerByte() int64

FeePerByte returns transaction network fee per byte.

func (*Blockchain) ForEachNEP11Transfer added in v0.98.0

func (bc *Blockchain) ForEachNEP11Transfer(acc util.Uint160, f func(*state.NEP11Transfer) (bool, error)) error

ForEachNEP11Transfer executes f for each NEP-11 transfer in log.

func (*Blockchain) ForEachNEP17Transfer added in v0.92.0

func (bc *Blockchain) ForEachNEP17Transfer(acc util.Uint160, f func(*state.NEP17Transfer) (bool, error)) error

ForEachNEP17Transfer executes f for each NEP-17 transfer in log.

func (*Blockchain) GetAppExecResults added in v0.92.0

func (bc *Blockchain) GetAppExecResults(hash util.Uint256, trig trigger.Type) ([]state.AppExecResult, error)

GetAppExecResults returns application execution results with the specified trigger by the given tx hash or block hash.

func (*Blockchain) GetBaseExecFee added in v0.92.0

func (bc *Blockchain) GetBaseExecFee() int64

GetBaseExecFee return execution price for `NOP`.

func (*Blockchain) GetBlock

func (bc *Blockchain) GetBlock(hash util.Uint256) (*block.Block, error)

GetBlock returns a Block by the given hash.

func (*Blockchain) GetCommittee added in v0.92.0

func (bc *Blockchain) GetCommittee() (keys.PublicKeys, error)

GetCommittee returns the sorted list of public keys of nodes in committee.

func (*Blockchain) GetConfig

func (bc *Blockchain) GetConfig() config.ProtocolConfiguration

GetConfig returns the config stored in the blockchain.

func (*Blockchain) GetContractScriptHash added in v0.91.0

func (bc *Blockchain) GetContractScriptHash(id int32) (util.Uint160, error)

GetContractScriptHash returns contract script hash by its ID.

func (*Blockchain) GetContractState

func (bc *Blockchain) GetContractState(hash util.Uint160) *state.Contract

GetContractState returns contract by its script hash.

func (*Blockchain) GetEnrollments

func (bc *Blockchain) GetEnrollments() ([]state.Validator, error)

GetEnrollments returns all registered validators.

func (*Blockchain) GetGoverningTokenBalance added in v0.90.0

func (bc *Blockchain) GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32)

GetGoverningTokenBalance returns governing token (NEO) balance and the height of the last balance change for the account.

func (*Blockchain) GetHeader

func (bc *Blockchain) GetHeader(hash util.Uint256) (*block.Header, error)

GetHeader returns data block header identified with the given hash value.

func (*Blockchain) GetHeaderHash

func (bc *Blockchain) GetHeaderHash(i int) util.Uint256

GetHeaderHash returns hash of the header/block with specified index, if Blockchain doesn't have a hash for this height, zero Uint256 value is returned.

func (*Blockchain) GetMaxVerificationGAS added in v0.92.0

func (bc *Blockchain) GetMaxVerificationGAS() int64

GetMaxVerificationGAS returns maximum verification GAS Policy limit.

func (*Blockchain) GetMemPool

func (bc *Blockchain) GetMemPool() *mempool.Pool

GetMemPool returns the memory pool of the blockchain.

func (*Blockchain) GetNEP11Contracts added in v0.98.0

func (bc *Blockchain) GetNEP11Contracts() []util.Uint160

GetNEP11Contracts returns the list of deployed NEP-11 contracts.

func (*Blockchain) GetNEP17Contracts added in v0.97.1

func (bc *Blockchain) GetNEP17Contracts() []util.Uint160

GetNEP17Contracts returns the list of deployed NEP-17 contracts.

func (*Blockchain) GetNativeContractScriptHash added in v0.92.0

func (bc *Blockchain) GetNativeContractScriptHash(name string) (util.Uint160, error)

GetNativeContractScriptHash returns native contract script hash by its name.

func (*Blockchain) GetNatives added in v0.93.0

func (bc *Blockchain) GetNatives() []state.NativeContract

GetNatives returns list of native contracts.

func (*Blockchain) GetNextBlockValidators added in v0.90.0

func (bc *Blockchain) GetNextBlockValidators() ([]*keys.PublicKey, error)

GetNextBlockValidators returns next block validators.

func (*Blockchain) GetNotaryBalance added in v0.92.0

func (bc *Blockchain) GetNotaryBalance(acc util.Uint160) *big.Int

GetNotaryBalance returns Notary deposit amount for the specified account.

func (*Blockchain) GetNotaryContractScriptHash added in v0.92.0

func (bc *Blockchain) GetNotaryContractScriptHash() util.Uint160

GetNotaryContractScriptHash returns Notary native contract hash.

func (*Blockchain) GetNotaryDepositExpiration added in v0.92.0

func (bc *Blockchain) GetNotaryDepositExpiration(acc util.Uint160) uint32

GetNotaryDepositExpiration returns Notary deposit expiration height for the specified account.

func (*Blockchain) GetPolicer added in v0.92.0

func (bc *Blockchain) GetPolicer() blockchainer.Policer

GetPolicer provides access to policy values via Policer interface.

func (*Blockchain) GetStandByCommittee added in v0.91.0

func (bc *Blockchain) GetStandByCommittee() keys.PublicKeys

GetStandByCommittee returns standby committee from the configuration.

func (*Blockchain) GetStandByValidators

func (bc *Blockchain) GetStandByValidators() keys.PublicKeys

GetStandByValidators returns validators from the configuration.

func (*Blockchain) GetStateModule added in v0.94.0

func (bc *Blockchain) GetStateModule() blockchainer.StateRoot

GetStateModule returns state root service instance.

func (*Blockchain) GetStateSyncModule added in v0.97.3

func (bc *Blockchain) GetStateSyncModule() blockchainer.StateSync

GetStateSyncModule returns new state sync service instance.

func (*Blockchain) GetStorageItem

func (bc *Blockchain) GetStorageItem(id int32, key []byte) state.StorageItem

GetStorageItem returns an item from storage.

func (*Blockchain) GetStorageItems

func (bc *Blockchain) GetStorageItems(id int32) ([]state.StorageItemWithKey, error)

GetStorageItems returns all storage items for a given contract id.

func (*Blockchain) GetStoragePrice added in v0.92.0

func (bc *Blockchain) GetStoragePrice() int64

GetStoragePrice returns current storage price.

func (*Blockchain) GetTestVM

func (bc *Blockchain) GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*vm.VM, func())

GetTestVM returns a VM setup for a test run of some sort of code and finalizer function.

func (*Blockchain) GetTokenLastUpdated added in v0.98.0

func (bc *Blockchain) GetTokenLastUpdated(acc util.Uint160) (map[int32]uint32, error)

GetTokenLastUpdated returns a set of contract ids with the corresponding last updated block indexes. In case of an empty account, latest stored state synchronisation point is returned under Math.MinInt32 key.

func (*Blockchain) GetTransaction

func (bc *Blockchain) GetTransaction(hash util.Uint256) (*transaction.Transaction, uint32, error)

GetTransaction returns a TX and its height by the given hash. The height is MaxUint32 if tx is in the mempool.

func (*Blockchain) GetUtilityTokenBalance added in v0.90.0

func (bc *Blockchain) GetUtilityTokenBalance(acc util.Uint160) *big.Int

GetUtilityTokenBalance returns utility token (GAS) balance for the acc.

func (*Blockchain) GetValidators

func (bc *Blockchain) GetValidators() ([]*keys.PublicKey, error)

GetValidators returns current validators.

func (*Blockchain) GoverningTokenHash added in v0.90.0

func (bc *Blockchain) GoverningTokenHash() util.Uint160

GoverningTokenHash returns the governing token (NEO) native contract hash.

func (*Blockchain) HasBlock

func (bc *Blockchain) HasBlock(hash util.Uint256) bool

HasBlock returns true if the blockchain contains the given block hash.

func (*Blockchain) HasTransaction

func (bc *Blockchain) HasTransaction(hash util.Uint256) bool

HasTransaction returns true if the blockchain contains he given transaction hash.

func (*Blockchain) HeaderHeight

func (bc *Blockchain) HeaderHeight() uint32

HeaderHeight returns the index/height of the highest header.

func (*Blockchain) InitVerificationVM added in v0.94.0

func (bc *Blockchain) InitVerificationVM(v *vm.VM, getContract func(util.Uint160) (*state.Contract, error), hash util.Uint160, witness *transaction.Witness) error

InitVerificationVM initializes VM for witness check.

func (*Blockchain) IsExtensibleAllowed added in v0.93.0

func (bc *Blockchain) IsExtensibleAllowed(u util.Uint160) bool

IsExtensibleAllowed determines if script hash is allowed to send extensible payloads.

func (*Blockchain) IsTxStillRelevant added in v0.92.0

func (bc *Blockchain) IsTxStillRelevant(t *transaction.Transaction, txpool *mempool.Pool, isPartialTx bool) bool

IsTxStillRelevant is a callback for mempool transaction filtering after the new block addition. It returns false for transactions added by the new block (passed via txpool) and does witness reverification for non-standard contracts. It operates under the assumption that full transaction verification was already done so we don't need to check basic things like size, input/output correctness, presence in blocks before the new one, etc.

func (*Blockchain) LastBatch

func (bc *Blockchain) LastBatch() *storage.MemBatch

LastBatch returns last persisted storage batch.

func (*Blockchain) ManagementContractHash added in v0.92.0

func (bc *Blockchain) ManagementContractHash() util.Uint160

ManagementContractHash returns management contract's hash.

func (*Blockchain) P2PSigExtensionsEnabled added in v0.92.0

func (bc *Blockchain) P2PSigExtensionsEnabled() bool

P2PSigExtensionsEnabled defines whether P2P signature extensions are enabled.

func (*Blockchain) PoolTx

func (bc *Blockchain) PoolTx(t *transaction.Transaction, pools ...*mempool.Pool) error

PoolTx verifies and tries to add given transaction into the mempool. If not given, the default mempool is used. Passing multiple pools is not supported.

func (*Blockchain) PoolTxWithData added in v0.92.0

func (bc *Blockchain) PoolTxWithData(t *transaction.Transaction, data interface{}, mp *mempool.Pool, feer mempool.Feer, verificationFunction func(bc blockchainer.Blockchainer, tx *transaction.Transaction, data interface{}) error) error

PoolTxWithData verifies and tries to add given transaction with additional data into the mempool.

func (*Blockchain) RegisterPostBlock added in v0.92.0

func (bc *Blockchain) RegisterPostBlock(f func(blockchainer.Blockchainer, *mempool.Pool, *block.Block))

RegisterPostBlock appends provided function to the list of functions which should be run after new block is stored.

func (*Blockchain) Run

func (bc *Blockchain) Run()

Run runs chain loop, it needs to be run as goroutine and executing it is critical for correct Blockchain operation.

func (*Blockchain) SetNotary added in v0.93.0

func (bc *Blockchain) SetNotary(mod services.Notary)

SetNotary sets notary module. It doesn't protected by mutex and must be called before `bc.Run()` to avoid data race.

func (*Blockchain) SetOracle added in v0.93.0

func (bc *Blockchain) SetOracle(mod services.Oracle)

SetOracle sets oracle module. It doesn't protected by mutex and must be called before `bc.Run()` to avoid data race.

func (*Blockchain) SubscribeForBlocks added in v0.75.0

func (bc *Blockchain) SubscribeForBlocks(ch chan<- *block.Block)

SubscribeForBlocks adds given channel to new block event broadcasting, so when there is a new block added to the chain you'll receive it via this channel. Make sure it's read from regularly as not reading these events might affect other Blockchain functions.

func (*Blockchain) SubscribeForExecutions added in v0.75.0

func (bc *Blockchain) SubscribeForExecutions(ch chan<- *state.AppExecResult)

SubscribeForExecutions adds given channel to new transaction execution event broadcasting, so when an in-block transaction execution happens you'll receive the result of it via this channel. Make sure it's read from regularly as not reading these events might affect other Blockchain functions.

func (*Blockchain) SubscribeForNotifications added in v0.75.0

func (bc *Blockchain) SubscribeForNotifications(ch chan<- *subscriptions.NotificationEvent)

SubscribeForNotifications adds given channel to new notifications event broadcasting, so when an in-block transaction execution generates a notification you'll receive it via this channel. Only notifications from successful transactions are broadcasted, if you're interested in failed transactions use SubscribeForExecutions instead. Make sure this channel is read from regularly as not reading these events might affect other Blockchain functions.

func (*Blockchain) SubscribeForTransactions added in v0.75.0

func (bc *Blockchain) SubscribeForTransactions(ch chan<- *transaction.Transaction)

SubscribeForTransactions adds given channel to new transaction event broadcasting, so when there is a new transaction added to the chain (in a block) you'll receive it via this channel. Make sure it's read from regularly as not reading these events might affect other Blockchain functions.

func (*Blockchain) UnsubscribeFromBlocks added in v0.75.0

func (bc *Blockchain) UnsubscribeFromBlocks(ch chan<- *block.Block)

UnsubscribeFromBlocks unsubscribes given channel from new block notifications, you can close it afterwards. Passing non-subscribed channel is a no-op.

func (*Blockchain) UnsubscribeFromExecutions added in v0.75.0

func (bc *Blockchain) UnsubscribeFromExecutions(ch chan<- *state.AppExecResult)

UnsubscribeFromExecutions unsubscribes given channel from new execution notifications, you can close it afterwards. Passing non-subscribed channel is a no-op.

func (*Blockchain) UnsubscribeFromNotifications added in v0.75.0

func (bc *Blockchain) UnsubscribeFromNotifications(ch chan<- *subscriptions.NotificationEvent)

UnsubscribeFromNotifications unsubscribes given channel from new execution-generated notifications, you can close it afterwards. Passing non-subscribed channel is a no-op.

func (*Blockchain) UnsubscribeFromTransactions added in v0.75.0

func (bc *Blockchain) UnsubscribeFromTransactions(ch chan<- *transaction.Transaction)

UnsubscribeFromTransactions unsubscribes given channel from new transaction notifications, you can close it afterwards. Passing non-subscribed channel is a no-op.

func (*Blockchain) UtilityTokenHash added in v0.90.0

func (bc *Blockchain) UtilityTokenHash() util.Uint160

UtilityTokenHash returns the utility token (GAS) native contract hash.

func (*Blockchain) VerifyTx

func (bc *Blockchain) VerifyTx(t *transaction.Transaction) error

VerifyTx verifies whether transaction is bonafide or not relative to the current blockchain state. Note that this verification is completely isolated from the main node's mempool.

func (*Blockchain) VerifyWitness added in v0.92.0

func (bc *Blockchain) VerifyWitness(h util.Uint160, c hash.Hashable, w *transaction.Witness, gas int64) (int64, error)

VerifyWitness checks that w is a correct witness for c signed by h. It returns the amount of GAS consumed during verification and an error.

type StorageContext

type StorageContext struct {
	ID       int32
	ReadOnly bool
}

StorageContext contains storing id and read/write flag, it's used as a context for storage manipulation functions.

Directories

Path Synopsis
Package block contains Neo block definition.
Package block contains Neo block definition.
Package interop contains implementations of Neo interop functions.
Package interop contains implementations of Neo interop functions.
Package mpt implements MPT (Merkle-Patricia Tree).
Package mpt implements MPT (Merkle-Patricia Tree).
Package native contains Neo native contracts.
Package native contains Neo native contracts.
Package statesync implements module for the P2P state synchronisation process.
Package statesync implements module for the P2P state synchronisation process.
Package transaction contains Neo transaction definition.
Package transaction contains Neo transaction definition.

Jump to

Keyboard shortcuts

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