core

package
v0.78.1-pre Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2020 License: MIT Imports: 30 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 (
	// MaxContractDescriptionLen is the maximum length for contract description.
	MaxContractDescriptionLen = 65536
	// MaxContractScriptSize is the maximum script size for a contract.
	MaxContractScriptSize = 1024 * 1024
	// MaxContractParametersNum is the maximum number of parameters for a contract.
	MaxContractParametersNum = 252
	// MaxContractStringLen is the maximum length for contract metadata strings.
	MaxContractStringLen = 252
	// MaxAssetNameLen is the maximum length of asset name.
	MaxAssetNameLen = 1024
	// MaxAssetPrecision is the maximum precision of asset.
	MaxAssetPrecision = 8
	// BlocksPerYear is a multiplier for asset renewal.
	BlocksPerYear = 2000000
	// DefaultAssetLifetime is the default lifetime of an asset (which differs
	// from assets created by register tx).
	DefaultAssetLifetime = 1 + BlocksPerYear
)
View Source
const (
	// MaxStorageKeyLen is the maximum length of a key for storage items.
	MaxStorageKeyLen = 1024
)

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 error = errors.New("invalid block index")
)

Functions

func GoverningTokenID

func GoverningTokenID() util.Uint256

GoverningTokenID returns the governing token (NEO) hash.

func ScriptFromWitness

func ScriptFromWitness(hash util.Uint160, witness *transaction.Witness) ([]byte, error)

ScriptFromWitness returns verification script for provided witness. If hash is not equal to the witness script hash, error is returned.

func UtilityTokenID

func UtilityTokenID() util.Uint256

UtilityTokenID returns the utility token (GAS) hash.

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) AddStateRoot added in v0.76.0

func (bc *Blockchain) AddStateRoot(r *state.MPTRoot) error

AddStateRoot add new (possibly unverified) state root to the blockchain.

func (*Blockchain) ApplyPolicyToTxSet

func (bc *Blockchain) ApplyPolicyToTxSet(txes []mempool.TxWithFee) []mempool.TxWithFee

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(value util.Fixed8, startHeight, endHeight uint32) (util.Fixed8, util.Fixed8, error)

CalculateClaimable calculates the amount of GAS which can be claimed for a transaction with value. First return value is GAS generated between startHeight and endHeight. Second return value is GAS returned from accumulated SystemFees between startHeight and endHeight.

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() (hash util.Uint256)

CurrentBlockHash returns the highest processed block hash.

func (*Blockchain) CurrentHeaderHash

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

CurrentHeaderHash returns the hash of the latest known header.

func (*Blockchain) FeePerByte

func (bc *Blockchain) FeePerByte(t *transaction.Transaction) util.Fixed8

FeePerByte returns network fee divided by the size of the transaction.

func (*Blockchain) ForEachNEP5Transfer added in v0.77.0

func (bc *Blockchain) ForEachNEP5Transfer(acc util.Uint160, tr *state.NEP5Transfer, f func() (bool, error)) error

ForEachNEP5Transfer executes f for each nep5 transfer in log.

func (*Blockchain) ForEachTransfer added in v0.77.0

func (bc *Blockchain) ForEachTransfer(acc util.Uint160, tr *state.Transfer, f func() (bool, error)) error

ForEachTransfer executes f for each transfer in log.

func (*Blockchain) GetAccountState

func (bc *Blockchain) GetAccountState(scriptHash util.Uint160) *state.Account

GetAccountState returns the account state from its script hash.

func (*Blockchain) GetAppExecResult

func (bc *Blockchain) GetAppExecResult(hash util.Uint256) (*state.AppExecResult, error)

GetAppExecResult returns application execution result by the given tx hash.

func (*Blockchain) GetAssetState

func (bc *Blockchain) GetAssetState(assetID util.Uint256) *state.Asset

GetAssetState returns asset state from its assetID.

func (*Blockchain) GetBlock

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

GetBlock returns a Block by the given hash.

func (*Blockchain) GetConfig

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

GetConfig returns the config stored in the blockchain.

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 and non-registered SB validators

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) (hash util.Uint256)

GetHeaderHash returns the hash from the headerList by its height/index.

func (*Blockchain) GetMemPool

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

GetMemPool returns the memory pool of the blockchain.

func (*Blockchain) GetNEP5Balances

func (bc *Blockchain) GetNEP5Balances(acc util.Uint160) *state.NEP5Balances

GetNEP5Balances returns NEP5 balances for the acc.

func (*Blockchain) GetNEP5Metadata added in v0.77.0

func (bc *Blockchain) GetNEP5Metadata(h util.Uint160) (*state.NEP5Metadata, error)

GetNEP5Metadata returns NEP5 metadata for the contract h. Note: it is currently saved only for migrated contracts.

func (*Blockchain) GetScriptHashesForVerifying

func (bc *Blockchain) GetScriptHashesForVerifying(t *transaction.Transaction) ([]util.Uint160, error)

GetScriptHashesForVerifying returns all the ScriptHashes of a transaction which will be use to verify whether the transaction is bonafide or not. Golang implementation of GetScriptHashesForVerifying method in C# (https://github.com/neo-project/neo/blob/master/neo/Network/P2P/Payloads/Transaction.cs#L190)

func (*Blockchain) GetStandByValidators

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

GetStandByValidators returns validators from the configuration.

func (*Blockchain) GetStateProof added in v0.76.0

func (bc *Blockchain) GetStateProof(root util.Uint256, key []byte) ([][]byte, error)

GetStateProof returns proof of having key in the MPT with the specified root.

func (*Blockchain) GetStateRoot added in v0.76.0

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

GetStateRoot returns state root for a given height.

func (*Blockchain) GetStorageItem

func (bc *Blockchain) GetStorageItem(scripthash util.Uint160, key []byte) *state.StorageItem

GetStorageItem returns an item from storage.

func (*Blockchain) GetStorageItems

func (bc *Blockchain) GetStorageItems(hash util.Uint160) (map[string]*state.StorageItem, error)

GetStorageItems returns all storage items for a given scripthash.

func (*Blockchain) GetTestVM

func (bc *Blockchain) GetTestVM(tx *transaction.Transaction) *vm.VM

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

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.

func (*Blockchain) GetTransactionResults

func (bc *Blockchain) GetTransactionResults(t *transaction.Transaction) []*transaction.Result

GetTransactionResults returns the transaction results aggregate by assetID. Golang of GetTransationResults method in C# (https://github.com/neo-project/neo/blob/master/neo/Network/P2P/Payloads/Transaction.cs#L207)

func (*Blockchain) GetUnspentCoinState

func (bc *Blockchain) GetUnspentCoinState(hash util.Uint256) *state.UnspentCoin

GetUnspentCoinState returns unspent coin state for given tx hash.

func (*Blockchain) GetValidators

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

GetValidators returns validators. Golang implementation of GetValidators method in C# (https://github.com/neo-project/neo/blob/c64748ecbac3baeb8045b16af0d518398a6ced24/neo/Persistence/Snapshot.cs#L182)

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) IsLowPriority

func (bc *Blockchain) IsLowPriority(fee util.Fixed8) bool

IsLowPriority checks given fee for being less than configured LowPriorityThreshold.

func (*Blockchain) LastBatch

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

LastBatch returns last persisted storage batch.

func (*Blockchain) NetworkFee

func (bc *Blockchain) NetworkFee(t *transaction.Transaction) util.Fixed8

NetworkFee returns network fee.

func (*Blockchain) PoolTx

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

PoolTx verifies and tries to add given transaction into the mempool.

func (*Blockchain) References

func (bc *Blockchain) References(t *transaction.Transaction) ([]transaction.InOut, error)

References maps transaction's inputs into a slice of InOuts, effectively joining each Input with the corresponding Output. @TODO: unfortunately we couldn't attach this method to the Transaction struct in the transaction package because of a import cycle problem. Perhaps we should think to re-design the code base to avoid this situation.

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) StateHeight added in v0.76.0

func (bc *Blockchain) StateHeight() uint32

StateHeight returns height of the verified state root.

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<- *state.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) SystemFee

func (bc *Blockchain) SystemFee(t *transaction.Transaction) util.Fixed8

SystemFee returns system fee.

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<- *state.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) VerifyTx

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

VerifyTx verifies whether a transaction is bonafide or not. Block parameter is used for easy interop access and can be omitted for transactions that are not yet added into any block. Golang implementation of Verify method in C# (https://github.com/neo-project/neo/blob/master/neo/Network/P2P/Payloads/Transaction.cs#L270).

type Blockchainer

type Blockchainer interface {
	ApplyPolicyToTxSet([]mempool.TxWithFee) []mempool.TxWithFee
	GetConfig() config.ProtocolConfiguration
	AddHeaders(...*block.Header) error
	AddBlock(*block.Block) error
	AddStateRoot(r *state.MPTRoot) error
	BlockHeight() uint32
	CalculateClaimable(value util.Fixed8, startHeight, endHeight uint32) (util.Fixed8, util.Fixed8, error)
	Close()
	HeaderHeight() uint32
	GetBlock(hash util.Uint256) (*block.Block, error)
	GetContractState(hash util.Uint160) *state.Contract
	GetEnrollments() ([]*state.Validator, error)
	ForEachNEP5Transfer(util.Uint160, *state.NEP5Transfer, func() (bool, error)) error
	ForEachTransfer(util.Uint160, *state.Transfer, func() (bool, error)) error
	GetHeaderHash(int) util.Uint256
	GetHeader(hash util.Uint256) (*block.Header, error)
	CurrentHeaderHash() util.Uint256
	CurrentBlockHash() util.Uint256
	HasBlock(util.Uint256) bool
	HasTransaction(util.Uint256) bool
	GetAssetState(util.Uint256) *state.Asset
	GetAccountState(util.Uint160) *state.Account
	GetAppExecResult(util.Uint256) (*state.AppExecResult, error)
	GetNEP5Metadata(util.Uint160) (*state.NEP5Metadata, error)
	GetNEP5Balances(util.Uint160) *state.NEP5Balances
	GetValidators(txes ...*transaction.Transaction) ([]*keys.PublicKey, error)
	GetScriptHashesForVerifying(*transaction.Transaction) ([]util.Uint160, error)
	GetStateProof(root util.Uint256, key []byte) ([][]byte, error)
	GetStateRoot(height uint32) (*state.MPTRootState, error)
	GetStorageItem(scripthash util.Uint160, key []byte) *state.StorageItem
	GetStorageItems(hash util.Uint160) (map[string]*state.StorageItem, error)
	GetTestVM(tx *transaction.Transaction) *vm.VM
	GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error)
	GetUnspentCoinState(util.Uint256) *state.UnspentCoin
	References(t *transaction.Transaction) ([]transaction.InOut, error)
	mempool.Feer // fee interface
	PoolTx(*transaction.Transaction) error
	StateHeight() uint32
	SubscribeForBlocks(ch chan<- *block.Block)
	SubscribeForExecutions(ch chan<- *state.AppExecResult)
	SubscribeForNotifications(ch chan<- *state.NotificationEvent)
	SubscribeForTransactions(ch chan<- *transaction.Transaction)
	VerifyTx(*transaction.Transaction, *block.Block) error
	GetMemPool() *mempool.Pool
	UnsubscribeFromBlocks(ch chan<- *block.Block)
	UnsubscribeFromExecutions(ch chan<- *state.AppExecResult)
	UnsubscribeFromNotifications(ch chan<- *state.NotificationEvent)
	UnsubscribeFromTransactions(ch chan<- *transaction.Transaction)
}

Blockchainer is an interface that abstract the implementation of the blockchain.

type HeaderHashList

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

A HeaderHashList represents a list of header hashes. This data structure in not routine safe and should be used under some kind of protection against race conditions.

func NewHeaderHashList

func NewHeaderHashList(hashes ...util.Uint256) *HeaderHashList

NewHeaderHashList returns a new pointer to a HeaderHashList.

func NewHeaderHashListFromBytes

func NewHeaderHashListFromBytes(b []byte) (*HeaderHashList, error)

NewHeaderHashListFromBytes returns a new hash list from the given bytes.

func (*HeaderHashList) Add

func (l *HeaderHashList) Add(h ...util.Uint256)

Add appends the given hash to the list of hashes.

func (*HeaderHashList) Get

func (l *HeaderHashList) Get(i int) util.Uint256

Get returns the hash by the given index.

func (*HeaderHashList) Last

func (l *HeaderHashList) Last() util.Uint256

Last return the last hash in the HeaderHashList.

func (*HeaderHashList) Len

func (l *HeaderHashList) Len() int

Len returns the length of the underlying hashes slice.

func (*HeaderHashList) Slice

func (l *HeaderHashList) Slice(start, end int) []util.Uint256

Slice return a subslice of the underlying hashes. Subsliced from start to end. Example:

headers := headerList.Slice(0, 2000)

func (*HeaderHashList) Write

func (l *HeaderHashList) Write(bw *io.BinWriter, start, n int) error

WriteTo writes n underlying hashes to the given BinWriter starting from start.

type StorageContext

type StorageContext struct {
	ScriptHash util.Uint160
	ReadOnly   bool
}

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

Directories

Path Synopsis
Package mpt implements MPT (Merkle-Patricia Tree).
Package mpt implements MPT (Merkle-Patricia Tree).

Jump to

Keyboard shortcuts

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