core

package
v0.101.1 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2023 License: MIT Imports: 48 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 CreateGenesisBlock added in v0.99.1

func CreateGenesisBlock(cfg config.ProtocolConfiguration) (*block.Block, error)

CreateGenesisBlock creates a genesis block based on the given configuration.

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 {
	HeaderHashes
	// 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.Blockchain, 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) 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, newestTimestamp uint64, f func(*state.NEP11Transfer) (bool, error)) error

ForEachNEP11Transfer executes f for each NEP-11 transfer in log starting from the transfer with the newest timestamp up to the oldest transfer. It continues iteration until false is returned from f. The last non-nil error is returned.

func (*Blockchain) ForEachNEP17Transfer added in v0.92.0

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

ForEachNEP17Transfer executes f for each NEP-17 transfer in log starting from the transfer with the newest timestamp up to the oldest transfer. It continues iteration until false is returned from f. The last non-nil error is returned.

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.Blockchain

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) GetMaxNotValidBeforeDelta added in v0.99.0

func (bc *Blockchain) GetMaxNotValidBeforeDelta() uint32

GetMaxNotValidBeforeDelta returns maximum NotValidBeforeDelta Notary limit.

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) GetNotaryServiceFeePerKey added in v0.98.2

func (bc *Blockchain) GetNotaryServiceFeePerKey() int64

GetNotaryServiceFeePerKey returns NotaryServiceFeePerKey which is a reward per notary request key for designated notary nodes.

func (*Blockchain) GetStateModule added in v0.94.0

func (bc *Blockchain) GetStateModule() StateRoot

GetStateModule returns state root service instance.

func (*Blockchain) GetStateRoot added in v0.76.0

func (bc *Blockchain) GetStateRoot(height uint32) (*state.MPTRoot, error)

GetStateRoot returns state root for the given height.

func (*Blockchain) GetStateSyncModule added in v0.97.3

func (bc *Blockchain) GetStateSyncModule() *statesync.Module

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) GetStoragePrice added in v0.92.0

func (bc *Blockchain) GetStoragePrice() int64

GetStoragePrice returns current storage price.

func (*Blockchain) GetTestHistoricVM added in v0.99.0

func (bc *Blockchain) GetTestHistoricVM(t trigger.Type, tx *transaction.Transaction, nextBlockHeight uint32) (*interop.Context, error)

GetTestHistoricVM returns an interop context with VM set up for a test run.

func (*Blockchain) GetTestVM

func (bc *Blockchain) GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) (*interop.Context, error)

GetTestVM returns an interop context with VM set up for a test run.

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) InitVerificationContext added in v0.98.1

func (bc *Blockchain) InitVerificationContext(ic *interop.Context, hash util.Uint160, witness *transaction.Witness) error

InitVerificationContext initializes context 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(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(func(*transaction.Transaction, *mempool.Pool, bool) bool, *mempool.Pool, *block.Block))

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

func (*Blockchain) Reset added in v0.99.5

func (bc *Blockchain) Reset(height uint32) error

Reset resets chain state to the specified height if possible. This method performs direct DB changes and can be called on non-running Blockchain only.

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 native.NotaryService)

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 native.OracleService)

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. Make sure you're not changing the received blocks, as it may affect the functionality of Blockchain and other subscribers.

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. Make sure you're not changing the received execution results, as it may affect the functionality of Blockchain and other subscribers.

func (*Blockchain) SubscribeForNotifications added in v0.75.0

func (bc *Blockchain) SubscribeForNotifications(ch chan *state.ContainedNotificationEvent)

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. Make sure you're not changing the received notification events, as it may affect the functionality of Blockchain and other subscribers.

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. Make sure you're not changing the received transactions, as it may affect the functionality of Blockchain and other subscribers.

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, but the method can read from this channel (discarding any read data).

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, but the method can read from this channel (discarding any read data).

func (*Blockchain) UnsubscribeFromNotifications added in v0.75.0

func (bc *Blockchain) UnsubscribeFromNotifications(ch chan *state.ContainedNotificationEvent)

UnsubscribeFromNotifications unsubscribes given channel from new execution-generated notifications, you can close it afterwards. Passing non-subscribed channel is a no-op, but the method can read from this channel (discarding any read data).

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, but the method can read from this channel (discarding any read data).

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 HeaderHashes added in v0.100.0

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

HeaderHashes is a header hash manager part of the Blockchain. It can't be used without Blockchain.

func (*HeaderHashes) CurrentHeaderHash added in v0.100.0

func (h *HeaderHashes) CurrentHeaderHash() util.Uint256

CurrentHeaderHash returns the hash of the latest known header.

func (*HeaderHashes) GetHeaderHash added in v0.100.0

func (h *HeaderHashes) GetHeaderHash(i uint32) util.Uint256

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

func (*HeaderHashes) HeaderHeight added in v0.100.0

func (h *HeaderHashes) HeaderHeight() uint32

HeaderHeight returns the index/height of the highest header.

type StateRoot added in v0.99.1

type StateRoot interface {
	CurrentLocalHeight() uint32
	CurrentLocalStateRoot() util.Uint256
	CurrentValidatedHeight() uint32
	FindStates(root util.Uint256, prefix, start []byte, max int) ([]storage.KeyValue, error)
	GetState(root util.Uint256, key []byte) ([]byte, error)
	GetStateProof(root util.Uint256, key []byte) ([][]byte, error)
	GetStateRoot(height uint32) (*state.MPTRoot, error)
	GetLatestStateHeight(root util.Uint256) (uint32, error)
}

StateRoot represents local state root module.

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 Trie).
Package mpt implements MPT (Merkle-Patricia Trie).
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.
dbconfig
Package dbconfig is a micropackage that contains storage DB configuration options.
Package dbconfig is a micropackage that contains storage DB configuration options.
dboper
Package dboper contains a type used to represent single DB operation.
Package dboper contains a type used to represent single DB operation.
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