blockchain

package
v0.0.0-...-7ee7fde Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2020 License: Apache-2.0 Imports: 33 Imported by: 14

Documentation

Overview

Copyright (c) 2018-2020. The asimov developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2016-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2018-2020. The asimov developers Copyright (c) 2013-2017 The btcsuite developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Index

Constants

View Source
const (
	TemplateHeaderLength int = 18

	// 2M limit
	TemplateDataFieldLength int = 1 << 21
)
View Source
const (
	// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
	MinCoinbaseScriptLen = 2

	// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
	MaxCoinbaseScriptLen = 100

	// MaxBlockSigOpsCost is the maximum number of signature operations
	// allowed for a block.
	MaxBlockSigOpsCost = 200000

	// NormalGas is the number of gas used in normal utxo per byte.
	// Estimate a normal tx takes 1k bytes, and refer an ethereum's notmal tx costs 21000 gas.
	NormalGas = 21
)
View Source
const CheckpointConfirmations = 2016

CheckpointConfirmations is the number of blocks before the end of the current best block chain that a good checkpoint candidate must be.

Variables

View Source
var CoinBasePreOut = protos.NewOutPoint(&zeroHash, math.MaxUint32)
View Source
var TransferCreationOut = protos.NewOutPoint(&zeroHash, asiutil.TransferCreationIdx)

define OutPoint for transfer creation and mint

View Source
var TransferMintOut = protos.NewOutPoint(&zeroHash, asiutil.TransferMintIdx)

Functions

func AddressVerifySignature

func AddressVerifySignature(data []byte, expectedAddr *common.Address, signs []byte) error

AddressVerifySignature check whether or not the address match the signature

func BuildMerkleTreeStore

func BuildMerkleTreeStore(transactions []*asiutil.Tx) []*common.Hash

BuildMerkleTreeStore creates a merkle tree from a slice of transactions, stores it using a linear array, and returns a slice of the backing array. A linear array was chosen as opposed to an actual tree structure since it uses about half as much memory. The following describes a merkle tree and how it is stored in a linear array.

A merkle tree is a tree in which every non-leaf node is the hash of its children nodes. A diagram depicting how this works for bitcoin transactions where h(x) is a double sha256 follows:

         root = h1234 = h(h12 + h34)
        /                           \
  h12 = h(h1 + h2)            h34 = h(h3 + h4)
   /            \              /            \
h1 = h(tx1)  h2 = h(tx2)    h3 = h(tx3)  h4 = h(tx4)

The above stored as a linear array is as follows:

[h1 h2 h3 h4 h12 h34 root]

As the above shows, the merkle root is always the last element in the array.

The number of inputs is not always a power of two which results in a balanced tree structure as above. In that case, parent nodes with no children are also zero and parent nodes with only a single left node are calculated by concatenating the left node with itself before hashing. Since this function uses nodes that are pointers to the hashes, empty nodes will be nil.

This presents an additional case wherein the wtxid of the coinbase transaction is the zeroHash.

func CalcBlockSubsidy

func CalcBlockSubsidy(height int32, chainParams *chaincfg.Params) int64

CalcBlockSubsidy returns the subsidy amount a block at the provided height should have. This is mainly used for determining how much the coinbase for newly generated blocks awards as well as validating the coinbase for blocks has the expected value.

The subsidy is halved every SubsidyReductionInterval blocks. Mathematically this is: baseSubsidy / 2^(height/SubsidyReductionInterval)

At the target block generation rate for the main network, this is approximately every 4 years.

func CalcGasLimit

func CalcGasLimit(gasUsed, gasLimit uint64, gasFloor, gasCeil uint64) uint64

CalcGasLimit computes the gas limit of the next block after parent. It aims to keep the baseline gas above the provided floor, and increase it towards the ceil if the blocks are full. If the ceil is exceeded, it will always decrease the gas allowance.

func CheckBlockSanity

func CheckBlockSanity(block *asiutil.Block, parent *blockNode) error

CheckBlockSanity performs some preliminary checks on a block to ensure it is sane before continuing with block processing. These checks are context free.

func CheckTransactionInputs

func CheckTransactionInputs(tx *asiutil.Tx, txHeight int32, utxoView *txo.UtxoViewpoint,
	b *BlockChain) (int64, *map[protos.Asset]int64, error)

CheckTransactionInputs performs a series of checks on the inputs to a transaction to ensure they are valid. An example of some of the checks include verifying all inputs exist, ensuring the coinbase seasoning requirements are met, detecting double spends, validating all values and fees are in the legal range and the total output amount doesn't exceed the input amount, and verifying the signatures to prove the spender was the owner of the bitcoins and therefore allowed to spend them. As it checks the inputs, it also calculates the total fees for the transaction and returns that value.

NOTE: The transaction MUST have already been sanity checked with the CheckTransactionSanity function prior to calling this function.

func CheckTransactionSanity

func CheckTransactionSanity(tx *asiutil.Tx) error

CheckTransactionSanity performs some preliminary checks on a transaction to ensure it is sane. These checks are context free.

func CheckVTransactionInputs

func CheckVTransactionInputs(tx *asiutil.Tx, utxoView *txo.UtxoViewpoint) error

func CountP2SHSigOps

func CountP2SHSigOps(tx *asiutil.Tx, isCoinBaseTx bool, utxoView *txo.UtxoViewpoint) (int, error)

CountP2SHSigOps returns the number of signature operations for all input transactions which are of the pay-to-script-hash type. This uses the precise, signature operation counting mechanism from the script engine which requires access to the input transaction scripts.

func CountSigOps

func CountSigOps(tx *asiutil.Tx) int

CountSigOps returns the number of signature operations for all transaction input and output scripts in the provided transaction. This uses the quicker, but imprecise, signature operation counting mechanism from txscript.

func DecodeCreateContractData

func DecodeCreateContractData(data []byte) (uint16, string, []byte, bool)

Create contract protocol is consist of header and content: header=[template category] [name length] [name]

2bytes              2bytes        255 bytes at most

content=[header]+[constructor]

func DecodeTemplateContractData

func DecodeTemplateContractData(data []byte) (uint16, []byte, []byte, []byte, []byte, error)

Template protocol is consist of header and content: header=[type] [name length][byte code length][abi length][source length]

2bytes 4bytes       4bytes            4bytes      4bytes

content=[name]+[byte code]+[abi]+[source]

func DeserializeUtxoEntry

func DeserializeUtxoEntry(serialized []byte) (*txo.UtxoEntry, error)

DeserializeUtxoEntry decodes a utxo entry from the passed serialized byte slice into a new UtxoEntry using a format that is suitable for long-term storage. The format is described in detail above.

func ExtractCoinbaseHeight

func ExtractCoinbaseHeight(coinbaseTx *asiutil.Tx) (int32, error)

ExtractCoinbaseHeight attempts to extract the height of the block from the scriptSig of a coinbase transaction. Coinbase heights are only present in blocks of version 2 or later. This was added as part of BIP0034.

func FetchUtxosMain

func FetchUtxosMain(view *txo.UtxoViewpoint, db database.Transactor, outpoints map[protos.OutPoint]struct{}) error

FetchUtxosMain fetches unspent transaction output data about the provided set of outpoints from the point of view of the end of the main chain at the time of the call.

Upon completion of this function, the view will contain an entry for each requested outpoint. Spent outputs, or those which otherwise don't exist, will result in a nil entry in the view.

func GetSigOpCost

func GetSigOpCost(tx *asiutil.Tx, isCoinBaseTx bool, utxoView *txo.UtxoViewpoint) (int, error)

GetSigOpCost returns the unified sig op cost for the passed transaction respecting current active soft-forks which modified sig op cost counting.

func GetUsd

func GetUsd(asset *protos.Asset, value int64) int64

we should get the value from the market maker contract.

func HashMerkleBranches

func HashMerkleBranches(left *common.Hash, right *common.Hash) *common.Hash

HashMerkleBranches takes two hashes, treated as the left and right tree nodes, and returns the hash of their concatenation. This is a helper function used to aid in the generation of a merkle tree.

func IsActive

func IsActive(addr *common.Address, curNode *blockNode) bool

func IsCoinBase

func IsCoinBase(tx *asiutil.Tx) bool

IsCoinBase determines whether or not a transaction is a coinbase. A coinbase is a special transaction created by miners that has no inputs. This is represented in the block chain by a transaction with a single input that has a previous output transaction index set to the maximum value along with a zero hash.

This function only differs from IsCoinBaseTx in that it works with a higher level util transaction as opposed to a raw protos transaction.

func IsCoinBaseTx

func IsCoinBaseTx(msgTx *protos.MsgTx) bool

IsCoinBaseTx determines whether or not a transaction is a coinbase. A coinbase is a special transaction created by miners that has no inputs. This is represented in the block chain by a transaction with a single input that has a previous output transaction index set to the maximum value along with a zero hash.

This function only differs from IsCoinBase in that it works with a raw protos transaction as opposed to a higher level util transaction.

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *asiutil.Tx, blockHeight int32, blockTime int64) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func IsTransferCreateOrMintTx

func IsTransferCreateOrMintTx(msgTx *protos.MsgTx) bool

func MergeFees

func MergeFees(totalp *map[protos.Asset]int64, feep *map[protos.Asset]int64) error

suppose both parameters are valid (Divisible)

func SequenceLockActive

func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
	timePast int64) bool

SequenceLockActive determines if a transaction's sequence locks have been met, meaning that all the inputs of a given transaction have reached a height or time sufficient for their relative lock-time maturity.

func SpentTxOutHeaderCode

func SpentTxOutHeaderCode(stxo *txo.SpentTxOut) uint64

SpentTxOutHeaderCode returns the calculated header code to be used when serializing the provided stxo entry.

func SpentTxOutSerializeSize

func SpentTxOutSerializeSize(stxo *txo.SpentTxOut) int

SpentTxOutSerializeSize returns the number of bytes it would take to serialize the passed stxo according to the format described above.

func ValidateTransactionScripts

func ValidateTransactionScripts(tx *asiutil.Tx, utxoView *txo.UtxoViewpoint,
	flags txscript.ScriptFlags) error

ValidateTransactionScripts validates the scripts for the passed transaction using multiple goroutines.

Types

type BestState

type BestState struct {
	Hash      common.Hash // The hash of the block.
	StateRoot common.Hash // hash of the state root, used to fetch the root information.
	Height    int32       // The height of the block.
	SlotIndex uint16      // The slot index per round of the block.
	Round     uint32      // The round of the block.
	Weight    uint64      // The total weight of the blocks from genesis to current block.
	BlockSize uint64      // The size of the block.
	NumTxns   uint64      // The number of txns in the block.
	TotalTxns uint64      // The total number of txns in the chain.
	TimeStamp int64       // timestamp of the block.

	GasLimit uint64 // The gaslimit of the block.
	GasUsed  uint64 // The used gas of the block.
}

BestState houses information about the current best block and other info related to the state of the main chain as it exists from the point of view of the current best block.

The BestSnapshot method can be used to obtain access to this information in a concurrent safe manner and the data will not be changed out from under the caller when chain state changes occur as the function name implies. However, the returned snapshot must be treated as immutable since it is shared by all callers.

type BlockChain

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

BlockChain provides functions for working with the bitcoin block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, checkpoint handling, and best chain selection with reorganization.

func New

func New(config *Config, fconfig *chaincfg.FConfig) (*BlockChain, error)

New returns a BlockChain instance using the provided configuration details.

func (*BlockChain) BestSnapshot

func (b *BlockChain) BestSnapshot() *BestState

BestSnapshot returns information about the current best chain block and related state as of the current point in time. The returned instance must be treated as immutable since it is shared by all callers.

This function is safe for concurrent access.

func (*BlockChain) BlockByHash

func (b *BlockChain) BlockByHash(hash *common.Hash) (*asiutil.Block, error)

BlockByHash returns the block from the main chain with the given hash with the appropriate chain height set.

This function is safe for concurrent access.

func (*BlockChain) BlockByHeight

func (b *BlockChain) BlockByHeight(blockHeight int32) (*asiutil.Block, error)

BlockByHeight returns the block at the given height in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockHashByHeight

func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*common.Hash, error)

BlockHashByHeight returns the hash of the block at the given height in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockHeightByHash

func (b *BlockChain) BlockHeightByHash(hash *common.Hash) (int32, error)

BlockHeightByHash returns the height of the block with the given hash in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockLocatorFromHash

func (b *BlockChain) BlockLocatorFromHash(hash *common.Hash) BlockLocator

BlockLocatorFromHash returns a block locator for the passed block hash. See BlockLocator for details on the algorithm used to create a block locator.

In addition to the general algorithm referenced above, this function will return the block locator for the latest known tip of the main (best) chain if the passed hash is not currently known.

This function is safe for concurrent access.

func (*BlockChain) BlockTimeByHeight

func (b *BlockChain) BlockTimeByHeight(blockHeight int32) (int64, error)

func (*BlockChain) CalcNextBlockVersion

func (b *BlockChain) CalcNextBlockVersion() (int32, error)

CalcNextBlockVersion calculates the expected version of the block after the end of the current best chain based on the state of started and locked in rule change deployments.

This function is safe for concurrent access.

func (*BlockChain) CalcSequenceLock

func (b *BlockChain) CalcSequenceLock(tx *asiutil.Tx, utxoView *txo.UtxoViewpoint, mempool bool) (*SequenceLock, error)

CalcSequenceLock computes a relative lock-time SequenceLock for the passed transaction using the passed UtxoViewpoint to obtain the past median time for blocks in which the referenced inputs of the transactions were included within. The generated SequenceLock lock can be used in conjunction with a block height, and adjusted median block time to determine if all the inputs referenced within a transaction have reached sufficient maturity allowing the candidate transaction to be included in a block.

This function is safe for concurrent access.

func (*BlockChain) CalculateBalance

func (b *BlockChain) CalculateBalance(view *txo.UtxoViewpoint, block *asiutil.Block, address common.Address, asset *protos.Asset, voucherId int64) (int64, error)

fetch the balance of one asset for address, if it's erc721, return voucher id if there's voucherId in the balance and voucherId > 0. otherwise return the count of asset.

func (*BlockChain) ChainRUnlock

func (b *BlockChain) ChainRUnlock()

unlock the chainLock, this method is use

func (*BlockChain) CheckTransferValidate

func (b *BlockChain) CheckTransferValidate(
	stateDB *state.StateDB,
	vtx *virtualtx.VirtualTransaction,
	block *asiutil.Block,
	gasLimit uint64) (leftOverGas uint64, err error)

validate asset in the tx.

func (*BlockChain) Checkpoints

func (b *BlockChain) Checkpoints() []chaincfg.Checkpoint

Checkpoints returns a slice of checkpoints (regardless of whether they are already known). When there are no checkpoints for the chain, it will return nil.

This function is safe for concurrent access.

func (*BlockChain) ConnectTransaction

func (b *BlockChain) ConnectTransaction(block *asiutil.Block, txidx int, view *txo.UtxoViewpoint, tx *asiutil.Tx,
	stxos *[]txo.SpentTxOut, stateDB *state.StateDB, fee int64) (
	receipt *types.Receipt, err error, gasUsed uint64, vtx *protos.MsgTx, feeLockItems map[protos.Asset]*txo.LockItem)

ConnectTransaction updates the view by adding all new utxos created by the passed transaction and marking all utxos that the transactions spend as spent. In addition, when the 'stxos' argument is not nil, it will be updated to append an entry for each spent txout. An error will be returned if the view does not contain the required utxos.

func (*BlockChain) CountRoundMinerInfo

func (b *BlockChain) CountRoundMinerInfo(round uint32, thisnode *blockNode) (sortedValidatorList common.AddressList,
	expectedBlocks []uint16, actualBlocks []uint16, mapping map[string]*ainterface.ValidatorInfo, err error)

This method is statistic miners per round. It is used only in coinbase tx data.

@return sortedValidatorList validators of pre-round, in order

expectedBlocks      expected blocks of pre-round each validator may mined.
actualBlocks        actual blocks of pre-round each validator mined.
mapping             new candidates for validators

func (*BlockChain) EthDB

func (b *BlockChain) EthDB() database.Database

func (*BlockChain) FetchHeader

func (b *BlockChain) FetchHeader(hash *common.Hash) (protos.BlockHeader, error)

FetchHeader returns the block header identified by the given hash or an error if it doesn't exist.

func (*BlockChain) FetchSpendJournal

func (b *BlockChain) FetchSpendJournal(targetBlock *asiutil.Block, targetvblock *asiutil.VBlock) ([]txo.SpentTxOut, error)

FetchSpendJournal attempts to retrieve the spend journal, or the set of outputs spent for the target block. This provides a view of all the outputs that will be consumed once the target block is connected to the end of the main chain.

This function is safe for concurrent access.

func (*BlockChain) FetchTemplate

func (b *BlockChain) FetchTemplate(view *txo.UtxoViewpoint, hash *common.Hash) (uint16, []byte, []byte, []byte, []byte, error)

FetchTemplate return decoded values for template data. It fetches data from tx map first. If not exist, it will search from db.

func (*BlockChain) FetchUtxoEntry

func (b *BlockChain) FetchUtxoEntry(outpoint protos.OutPoint) (*txo.UtxoEntry, error)

FetchUtxoEntry loads and returns the requested unspent transaction output from the point of view of the end of the main chain.

NOTE: Requesting an output for which there is no data will NOT return an error. Instead both the entry and the error will be nil. This is done to allow pruning of spent transaction outputs. In practice this means the caller must check if the returned entry is nil before invoking methods on it.

This function is safe for concurrent access however the returned entry (if any) is NOT.

func (*BlockChain) FetchUtxoView

func (b *BlockChain) FetchUtxoView(tx *asiutil.Tx, dolock bool) (*txo.UtxoViewpoint, error)

FetchUtxoView loads unspent transaction outputs for the inputs referenced by the passed transaction from the point of view of the end of the main chain. It also attempts to fetch the utxos for the outputs of the transaction itself so the returned view can be examined for duplicate transactions.

This function is safe for concurrent access however the returned view is NOT.

func (*BlockChain) FetchUtxoViewByAddress

func (b *BlockChain) FetchUtxoViewByAddress(view *txo.UtxoViewpoint, address []byte) (*[]protos.OutPoint, error)

func (*BlockChain) FetchUtxoViewByAddressAndAsset

func (b *BlockChain) FetchUtxoViewByAddressAndAsset(view *txo.UtxoViewpoint, address []byte, asset *protos.Asset) (*[]protos.OutPoint, error)

func (*BlockChain) FilterPackagedSignatures

func (b *BlockChain) FilterPackagedSignatures(signList []*asiutil.BlockSign) []*asiutil.BlockSign

filter packaged signatures and return remaining signatures.

func (*BlockChain) GenRollbackMsg

func (b *BlockChain) GenRollbackMsg(view *txo.UtxoViewpoint, tx *asiutil.Tx) (*protos.MsgTx, error)

generate rollback message if any error happens when connecting block.

func (*BlockChain) GenVtxMsg

func (b *BlockChain) GenVtxMsg(
	block *asiutil.Block,
	view *txo.UtxoViewpoint,
	tx *asiutil.Tx,
	vtx *virtualtx.VirtualTransaction) (*protos.MsgTx, error)

GenVtxMsg process createAsset, addAsset, transferAsset

func (*BlockChain) GetAcceptFees

func (b *BlockChain) GetAcceptFees(
	block *asiutil.Block,
	stateDB vm.StateDB,
	chainConfig *params.ChainConfig,
	height int32) (map[protos.Asset]int32, error)

TODO

func (*BlockChain) GetByteCode

func (b *BlockChain) GetByteCode(
	view *txo.UtxoViewpoint,
	block *asiutil.Block,
	gas uint64,
	stateDB vm.StateDB,
	chainConfig *params.ChainConfig,
	category uint16,
	name string) ([]byte, bool, uint64)

TODO

func (*BlockChain) GetConsensusMiningInfo

func (b *BlockChain) GetConsensusMiningInfo() (common.Address, string)

GetConsensusMiningInfo returns consensus system contract's address and abi

func (*BlockChain) GetDepthInActiveChain

func (b *BlockChain) GetDepthInActiveChain(height int32) int32

func (*BlockChain) GetNodeByHeight

func (b *BlockChain) GetNodeByHeight(targetHeight int32) (*blockNode, error)

func (*BlockChain) GetNodeByRoundSlot

func (b *BlockChain) GetNodeByRoundSlot(round uint32, slot uint16) *blockNode

func (*BlockChain) GetOrphanRoot

func (b *BlockChain) GetOrphanRoot(hash *common.Hash) *common.Hash

GetOrphanRoot returns the head of the chain for the provided hash from the map of orphan blocks.

This function is safe for concurrent access.

func (*BlockChain) GetStateCache

func (b *BlockChain) GetStateCache() state.Database

func (*BlockChain) GetSystemContractInfo

func (b *BlockChain) GetSystemContractInfo(delegateAddr common.Address) (common.Address, []byte, string)

GetSystemContractInfo returns delegate addresses, original addresses and abi information of system contracts

func (*BlockChain) GetTemplateInfo

func (b *BlockChain) GetTemplateInfo(
	contractAddr []byte,
	gas uint64,
	block *asiutil.Block,
	stateDB vm.StateDB,
	chainConfig *params.ChainConfig) (uint16, string, uint64)

Get template info which is stored in system registry centor

func (*BlockChain) GetTemplateWarehouseInfo

func (b *BlockChain) GetTemplateWarehouseInfo() (common.Address, string)

GetTemplateWarehouseInfo returns two values. @return templateWarehouseAddr the address of system contract named templateWarehouse

templateWarehouseAbi  abi of system contract named templateWarehouse

This method is used in fvm

func (*BlockChain) GetTip

func (b *BlockChain) GetTip() *blockNode

func (*BlockChain) GetValidators

func (b *BlockChain) GetValidators(round uint32) ([]*common.Address, map[common.Address]uint16, error)

GetValidators depends on current round miners and pre-round stateRoot.

func (*BlockChain) GetValidatorsByNode

func (b *BlockChain) GetValidatorsByNode(round uint32, preroundLastNode *blockNode) ([]*common.Address, map[common.Address]uint16, error)

GetValidatorsByNode depends on current round miners and pre-round last node.

func (*BlockChain) GetVmConfig

func (b *BlockChain) GetVmConfig() *vm.Config

func (*BlockChain) HasCheckpoints

func (b *BlockChain) HasCheckpoints() bool

HasCheckpoints returns whether this BlockChain has checkpoints defined.

This function is safe for concurrent access.

func (*BlockChain) HaveBlock

func (b *BlockChain) HaveBlock(hash *common.Hash) (bool, error)

HaveBlock returns whether or not the chain instance has the block represented by the passed hash. This includes checking the various places a block can be like part of the main chain, on a side chain, or in the orphan pool.

This function is safe for concurrent access.

func (*BlockChain) HeightToHashRange

func (b *BlockChain) HeightToHashRange(startHeight int32,
	endHash *common.Hash, maxResults int) ([]common.Hash, error)

HeightToHashRange returns a range of block hashes for the given start height and end hash, inclusive on both ends. The hashes are for all blocks that are ancestors of endHash with height greater than or equal to startHeight. The end hash must belong to a block that is known to be valid.

This function is safe for concurrent access.

func (*BlockChain) InitTemplate

func (b *BlockChain) InitTemplate(
	category uint16,
	templateName string,
	contractAddr common.Address,
	gas uint64,
	asset *protos.Asset,
	vmenv *vm.FVM) (error, uint64)

init template, this method is invoked after a create contract is executed.

func (*BlockChain) IntervalBlockHashes

func (b *BlockChain) IntervalBlockHashes(endHash *common.Hash, interval int,
) ([]common.Hash, error)

IntervalBlockHashes returns hashes for all blocks that are ancestors of endHash where the block height is a positive multiple of interval.

This function is safe for concurrent access.

func (*BlockChain) IsCheckpointCandidate

func (b *BlockChain) IsCheckpointCandidate(block *asiutil.Block) (bool, error)

IsCheckpointCandidate returns whether or not the passed block is a good checkpoint candidate.

The factors used to determine a good checkpoint are:

  • The block must be in the main chain
  • The block must be at least 'CheckpointConfirmations' blocks prior to the current end of the main chain
  • The timestamps for the blocks before and after the checkpoint must have timestamps which are also before and after the checkpoint, respectively (due to the median time allowance this is not always the case)
  • The block must not contain any strange transaction such as those with nonstandard scripts

The intent is that candidates are reviewed by a developer to make the final decision and then manually added to the list of checkpoints for a network.

This function is safe for concurrent access.

func (*BlockChain) IsCurrent

func (b *BlockChain) IsCurrent() bool

IsCurrent returns whether or not the chain believes it is current. Several factors are used to guess, but the key factors that allow the chain to believe it is current are:

  • Latest block height is after the latest checkpoint (if enabled)
  • Latest block has a timestamp newer than 24 hours ago

This function is safe for concurrent access.

func (*BlockChain) IsDeploymentActive

func (b *BlockChain) IsDeploymentActive(deploymentID uint32) (bool, error)

IsDeploymentActive returns true if the target deploymentID is active, and false otherwise.

This function is safe for concurrent access.

func (*BlockChain) IsKnownOrphan

func (b *BlockChain) IsKnownOrphan(hash *common.Hash) bool

IsKnownOrphan returns whether the passed hash is currently a known orphan. Keep in mind that only a limited number of orphans are held onto for a limited amount of time, so this function must not be used as an absolute way to test if a block is an orphan block. A full block (as opposed to just its hash) must be passed to ProcessBlock for that purpose. However, calling ProcessBlock with an orphan that already exists results in an error, so this function provides a mechanism for a caller to intelligently detect *recent* duplicate orphans and react accordingly.

This function is safe for concurrent access.

func (*BlockChain) LatestBlockLocator

func (b *BlockChain) LatestBlockLocator() (BlockLocator, error)

LatestBlockLocator returns a block locator for the latest known tip of the main (best) chain.

This function is safe for concurrent access.

func (*BlockChain) LatestCheckpoint

func (b *BlockChain) LatestCheckpoint() *chaincfg.Checkpoint

LatestCheckpoint returns the most recent checkpoint (regardless of whether it is already known). When there are no defined checkpoints for the active chain instance, it will return nil.

This function is safe for concurrent access.

func (*BlockChain) LocateBlocks

func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *common.Hash, maxHashes uint32) []common.Hash

LocateBlocks returns the hashes of the blocks after the first known block in the locator until the provided stop hash is reached, or up to the provided max number of block hashes.

In addition, there are two special cases:

  • When no locators are provided, the stop hash is treated as a request for that block, so it will either return the stop hash itself if it is known, or nil if it is unknown
  • When locators are provided, but none of them are known, hashes starting after the genesis block will be returned

This function is safe for concurrent access.

func (*BlockChain) LocateHeaders

func (b *BlockChain) LocateHeaders(locator BlockLocator, hashStop *common.Hash) []protos.BlockHeader

LocateHeaders returns the headers of the blocks after the first known block in the locator until the provided stop hash is reached, or up to a max of protos.MaxBlockHeadersPerMsg headers.

In addition, there are two special cases:

  • When no locators are provided, the stop hash is treated as a request for that header, so it will either return the header for the stop hash itself if it is known, or nil if it is unknown
  • When locators are provided, but none of them are known, headers starting after the genesis block will be returned

This function is safe for concurrent access.

func (*BlockChain) MainChainHasBlock

func (b *BlockChain) MainChainHasBlock(hash *common.Hash) bool

MainChainHasBlock returns whether or not the block with the given hash is in the main chain.

This function is safe for concurrent access.

func (*BlockChain) PostChainEvents

func (b *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log)

PostChainEvents iterates over the events generated by a chain insertion and posts them into the event feed.

func (*BlockChain) Prepare

func (b *BlockChain) Prepare(header *protos.BlockHeader, gasFloor, gasCeil uint64) (
	stateDB *state.StateDB, feepool map[protos.Asset]int32, contractOut *protos.TxOut, err error)

Prepare initializes the consensus fields of a block header according to the rules of a particular engine. The changes are executed inline. This method will lock the chain, and it will be released in Commit or Rollback method.

func (*BlockChain) ProcessBlock

func (b *BlockChain) ProcessBlock(block *asiutil.Block, vblock *asiutil.VBlock,
	receipts types.Receipts, logs []*types.Log,
	flags common.BehaviorFlags) (bool, bool, error)

ProcessBlock is the main workhorse for handling insertion of new blocks into the block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, and insertion into the block chain along with best chain selection and reorganization.

When no errors occurred during processing, the first return value indicates whether or not the block is on the main chain and the second indicates whether or not the block is an orphan.

This function is safe for concurrent access.

func (*BlockChain) Scope

func (b *BlockChain) Scope() *event.SubscriptionScope

func (*BlockChain) Subscribe

func (b *BlockChain) Subscribe(callback NotificationCallback)

Subscribe to block chain notifications. Registers a callback to be executed when various events take place. See the documentation on Notification and NotificationType for details on the types and contents of notifications.

func (*BlockChain) SubscribeLogsEvent

func (b *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription

SubscribeLogsEvent registers a subscription of []*types.Log.

func (*BlockChain) SubscribeRemovedLogsEvent

func (b *BlockChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription

SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.

func (*BlockChain) ThresholdState

func (b *BlockChain) ThresholdState(deploymentID uint32) (ThresholdState, error)

ThresholdState returns the current rule change threshold state of the given deployment ID for the block AFTER the end of the current best chain.

This function is safe for concurrent access.

type BlockLocator

type BlockLocator []*common.Hash

BlockLocator is used to help locate a specific block. The algorithm for building the block locator is to add the hashes in reverse order until the genesis block is reached. In order to keep the list of locator hashes to a reasonable number of entries, first the most recent previous 12 block hashes are added, then the step is doubled each loop iteration to exponentially decrease the number of hashes as a function of the distance from the block being located.

For example, assume a block chain with a side chain as depicted below:

genesis -> 1 -> 2 -> ... -> 15 -> 16  -> 17  -> 18
                              \-> 16a -> 17a

The block locator for block 17a would be the hashes of blocks: [17a 16a 15 14 13 12 11 10 9 8 7 6 4 genesis]

type Config

type Config struct {
	// DB defines the database which houses the blocks and will be used to
	// store all metadata created by this package such as the utxo set.
	//
	// This field is required.
	DB database.Transactor

	// Interrupt specifies a channel the caller can close to signal that
	// long running operations, such as catching up indexes or performing
	// database migrations, should be interrupted.
	//
	// This field can be nil if the caller does not desire the behavior.
	Interrupt <-chan struct{}

	// ChainParams identifies which chain parameters the chain is associated
	// with.
	//
	// This field is required.
	ChainParams *chaincfg.Params

	// Checkpoints hold caller-defined checkpoints that should be added to
	// the default checkpoints in ChainParams.  Checkpoints must be sorted
	// by height.
	//
	// This field can be nil if the caller does not wish to specify any
	// checkpoints.
	Checkpoints []chaincfg.Checkpoint

	// TimeSource defines the median time source to use for things such as
	// block processing and determining whether or not the chain is current.
	//
	// The caller is expected to keep a reference to the time source as well
	// and add time samples from other peers on the network so the local
	// time is adjusted to be in agreement with other peers.
	TimeSource MedianTimeSource

	// IndexManager defines an index manager to use when initializing the
	// chain and connecting and disconnecting blocks.
	IndexManager IndexManager

	// State DB
	StateDB database.Database

	TemplateIndex Indexer

	BtcClient ainterface.IBtcClient

	RoundManager ainterface.IRoundManager

	// ContractManager defines a contract manager to use when initializing the
	// chain and validating system state any time.
	ContractManager ainterface.ContractManager

	FeesChan chan interface{}
}

Config is a descriptor which specifies the blockchain instance configuration.

type DeploymentError

type DeploymentError uint32

DeploymentError identifies an error that indicates a deployment ID was specified that does not exist.

func (DeploymentError) Error

func (e DeploymentError) Error() string

Error returns the assertion error as a human-readable string and satisfies the error interface.

type EntryPair

type EntryPair struct {
	Key   protos.OutPoint
	Value *txo.UtxoEntry
}

pair for sorting to keep all peers the same order.

type EntryPairList

type EntryPairList []EntryPair

func (EntryPairList) Len

func (p EntryPairList) Len() int

func (EntryPairList) Less

func (p EntryPairList) Less(i, j int) bool

func (EntryPairList) Swap

func (p EntryPairList) Swap(i, j int)

type ErrorCode

type ErrorCode int

ErrorCode identifies a kind of error.

const (
	// ErrDuplicateBlock indicates a block with the same hash already
	// exists.
	ErrDuplicateBlock ErrorCode = iota

	// ErrBlockTooBig indicates the serialized block size exceeds the
	// maximum allowed size.
	ErrBlockTooBig

	// ErrBlockVersionTooOld indicates the block version is too old and is
	// no longer accepted since the majority of the network has upgraded
	// to a newer version.
	ErrBlockVersionTooOld

	// ErrHeightMismatch indicates the height is not continuous after the
	// prenode.
	ErrHeightMismatch

	// ErrTimeTooNew indicates the time is too far in the future as compared
	// the current time.
	ErrTimeTooNew

	// ErrTimeOutOfRange indicates the timestamp of the block is out of the range of
	// the expect timestamps that it should be.
	ErrTimeStampOutOfRange

	// ErrBadMerkleRoot indicates the calculated merkle root does not match
	// the expected value.
	ErrBadMerkleRoot

	// ErrBadPoaHash indicates the calculated poa hash does not match
	// the expected value.
	ErrBadPoaHash

	// ErrBadCheckpoint indicates a block that is expected to be at a
	// checkpoint height does not match the expected one.
	ErrBadCheckpoint

	// ErrForkTooOld indicates a block is attempting to fork the block chain
	// before the most recent checkpoint.
	ErrForkTooOld

	// ErrCheckpointTimeTooOld indicates a block has a timestamp before the
	// most recent checkpoint.
	ErrCheckpointTimeTooOld

	// ErrNoTransactions indicates the block does not have a least one
	// transaction.  A valid block must have at least the coinbase
	// transaction.
	ErrNoTransactions

	// ErrNoTxInputs indicates a transaction does not have any inputs.  A
	// valid transaction must have at least one input.
	ErrNoTxInputs

	// ErrTxTooBig indicates a transaction exceeds the maximum allowed size
	// when serialized.
	ErrTxTooBig

	// ErrBadTxOutValue indicates an output value for a transaction is
	// invalid in some way such as being out of range.
	ErrBadTxOutValue

	// ErrInvalidOutput indicates an output with contract call in not first output.
	ErrInvalidOutput

	// ErrDuplicateTxInputs indicates a transaction references the same
	// input more than once.
	ErrDuplicateTxInputs

	// ErrBadTxInput indicates a transaction input is invalid in some way
	// such as referencing a previous transaction outpoint which is out of
	// range or not referencing one at all.
	ErrBadTxInput

	// ErrMissingTxOut indicates a transaction output referenced by an input
	// either does not exist or has already been spent.
	ErrMissingTxOut

	// ErrUnfinalizedTx indicates a transaction has not been finalized.
	// A valid block may only contain finalized transactions.
	ErrUnfinalizedTx

	// ErrDuplicateTx indicates a block contains an identical transaction
	// (or at least two transactions which hash to the same value).  A
	// valid block may only contain unique transactions.
	ErrDuplicateTx

	// ErrImmatureSpend indicates a transaction is attempting to spend a
	// coinbase that has not yet reached the required maturity.
	ErrImmatureSpend

	// ErrSpendTooHigh indicates a transaction is attempting to spend more
	// value than the sum of all of its inputs.
	ErrSpendTooHigh

	// ErrAssetsNotEqual indicates the numbers of input asset and output asset are not equal
	ErrAssetsNotEqual

	// ErrBadFees indicates the total fees for a block are invalid due to
	// exceeding the maximum possible value.
	ErrBadFees

	// ErrTooManySigOps indicates the total number of signature operations
	// for a transaction or block exceed the maximum allowed limits.
	ErrTooManySigOps

	// ErrLastTxNotCoinbase indicates the first transaction in a block
	// is not a coinbase transaction.
	ErrLastTxNotCoinbase

	// ErrMultipleCoinbases indicates a block contains more than one
	// coinbase transaction.
	ErrMultipleCoinbases

	// ErrBadCoinbaseScriptLen indicates the length of the signature script
	// for a coinbase transaction is not within the valid range.
	ErrBadCoinbaseScriptLen

	// ErrBadCoinbaseValue indicates the amount of a coinbase value does
	// not match the expected value of the subsidy plus the sum of all fees.
	ErrBadCoinbaseValue

	// ErrBadCoinbaseData indicates the data of a coinbase txout does
	// not match the expected value.
	ErrBadCoinbaseData

	// ErrMissingCoinbaseHeight indicates the coinbase transaction for a
	// block does not start with the serialized block block height as
	// required for version 2 and higher blocks.
	ErrMissingCoinbaseHeight

	// ErrBadCoinbaseHeight indicates the serialized block height in the
	// coinbase transaction for version 2 and higher blocks does not match
	// the expected value.
	ErrBadCoinbaseHeight

	// ErrScriptMalformed indicates a transaction script is malformed in
	// some way.  For example, it might be longer than the maximum allowed
	// length or fail to parse.
	ErrScriptMalformed

	// ErrScriptValidation indicates the result of executing transaction
	// script failed.  The error covers any failure when executing scripts
	// such signature verification failures and execution past the end of
	// the stack.
	ErrScriptValidation

	// ErrPreviousBlockUnknown indicates that the previous block is not known.
	ErrPreviousBlockUnknown

	// ErrInvalidAncestorBlock indicates that an ancestor of this block has
	// already failed validation.
	ErrInvalidAncestorBlock

	// ErrPrevBlockNotBest indicates that the block's previous block is not the
	// current chain tip. This is not a block validation rule, but is required
	// for block proposals submitted via getblocktemplate RPC.
	ErrPrevBlockNotBest

	//ErrForbiddenAsset indicates the asset is forbidden to transfer as input or output
	ErrForbiddenAsset

	//ErrStateRootNotMatch indicates that the state root of block do not match we expect
	ErrStateRootNotMatch

	//ErrSignDuplicate indicates the sign hash already exist
	ErrSignDuplicate

	// ErrSignMiss indicates can not find block through sign blockhash or blockheight
	ErrSignMiss

	// ErrBadSigLength indicates the length of signature do not equal with HashSignLen
	ErrBadSigLength

	// ErrBadPreSigHeight indicates the blockHeight of preSig is out of validate range
	ErrBadPreSigHeight

	// ErrPreSigOrder indicates the order of preSig is not collect.
	ErrPreSigOrder

	// ErrInvalidSigData indicates the length of hash do not equal with HashLength
	ErrInvalidSigData

	// ErrSigAndKeyMismatch indicates sig do not match the key
	ErrSigAndKeyMismatch

	//ErrValidatorMismatch indicates the validator do not match validator that we want
	ErrValidatorMismatch

	// ErrNodeUnknown indicates the the node we want is nil or unknown
	ErrNodeUnknown

	// ErrSlotIndexOutOfRange indicates the SlotIndex of the block is bigger than RoundSize of ActiveNetParams
	ErrInvalidSlotIndex

	// ErrBadHashLength indicates the length of hash do not equal with HashLength
	ErrBadHashLength

	// ErrBadSlotOrRound indicates block has the less slot/round than parent
	ErrBadSlotOrRound

	// ErrInvalidBlockHash indicates the hash of block is invalid
	ErrInvalidBlockHash

	// ErrGasLimitOverFlow indicates txs total gaslimit is overflow by block gaslimit
	ErrGasLimitOverFlow

	// ErrHashMismatch indicates the block hash do not match the hash we want
	ErrHashMismatch

	// ErrBadBlockWeight indicates the block hash do not match the hash we want
	ErrBadBlockWeight

	//ErrGasMismatch indicates the block GasUsed do not match that we expect
	ErrGasMismatch

	// ErrBadGasLimit indicates the calculated gas limit does not match
	// the expected value.
	ErrBadGasLimit

	// ErrInvalidTemplate indicates Template is invalid
	ErrInvalidTemplate

	//ErrNoTemplate indicates fetch templateIndexKey returns empty entry
	ErrNoTemplate

	// ErrBadContractData indicates incorrect data protocol
	ErrBadContractData

	// ErrBadContractByteCode indicates get byte code from template error
	ErrBadContractByteCode

	// ErrFailedCreateContract indicates create contract failed
	ErrFailedCreateContract

	// ErrFailedInitTemplate indicates init template failed
	ErrFailedInitTemplate

	// ErrFailedCreateTemplate indicates create template error
	ErrFailedCreateTemplate

	// ErrFailedInitContractManager indicates init ContractManager failed
	ErrFailedInitContractManager

	// ErrInvalidPkScript indicates failed when get address from pkscript
	ErrInvalidPkScript

	//ErrFailedHeightToHashRange indicates failed when using height to Hash Range
	ErrBadHeightToHashRange

	// ErrInvalidBlock indicates the block is not yet validated
	ErrInvalidBlock

	//ErrStxoMismatch indicates that the numbers of stxos do not equal with we expect
	ErrStxoMismatch

	// ErrNotInMainChain indicates we can not find block in main chain by provided param
	ErrNotInMainChain

	// ErrFailedSerializedBlock indicates failed to get serialized bytes for block
	ErrFailedSerializedBlock
)

These constants are used to identify a specific RuleError.

func (ErrorCode) String

func (e ErrorCode) String() string

String returns the ErrorCode as a human-readable name.

type IndexManager

type IndexManager interface {
	// Init is invoked during chain initialize in order to allow the index
	// manager to initialize itself and any indexes it is managing.  The
	// channel parameter specifies a channel the caller can close to signal
	// that the process should be interrupted.  It can be nil if that
	// behavior is not desired.
	Init(*BlockChain, <-chan struct{}) error

	// ConnectBlock is invoked when a new block has been connected to the
	// main chain. The set of output spent within a block is also passed in
	// so indexers can access the previous output scripts input spent if
	// required.
	ConnectBlock(database.Tx, *asiutil.Block, []txo.SpentTxOut, *asiutil.VBlock) error

	// DisconnectBlock is invoked when a block has been disconnected from
	// the main chain. The set of outputs scripts that were spent within
	// this block is also returned so indexers can clean up the prior index
	// state for this block.
	DisconnectBlock(database.Tx, *asiutil.Block, []txo.SpentTxOut, *asiutil.VBlock) error
}

IndexManager provides a generic interface that the is called when blocks are connected and disconnected to and from the tip of the main chain for the purpose of supporting optional indexes.

type Indexer

type Indexer interface {
	// Key returns the key of the index as a byte slice.
	Key() []byte

	// Name returns the human-readable name of the index.
	Name() string

	// Init is invoked when the index manager is first initializing the
	// index.  This differs from the Create method in that it is called on
	// every load, including the case the index was just created.
	Init() error

	// Create is invoked when the indexer manager determines the index needs
	// to be created for the first time.
	Create(dbTx database.Tx) error

	//Check is invoked each time when node started. Checking if there is a new bucket
	//added to this indexer
	Check(dbTx database.Tx) error

	// ConnectBlock is invoked when a new block has been connected to the
	// main chain. The set of output spent within a block is also passed in
	// so indexers can access the pevious output scripts input spent if
	// required.
	ConnectBlock(database.Tx, *asiutil.Block, []txo.SpentTxOut, *asiutil.VBlock) error

	// DisconnectBlock is invoked when a block has been disconnected from
	// the main chain. The set of outputs scripts that were spent within
	// this block is also returned so indexers can clean up the prior index
	// state for this block
	DisconnectBlock(database.Tx, *asiutil.Block, []txo.SpentTxOut, *asiutil.VBlock) error

	// FetchBlockRegion returns the block region for the provided key
	// from the index.  The block region can in turn be used to load the
	// raw object bytes.  When there is no entry for the provided hash, nil
	// will be returned for the both the entry and the error.
	//
	// This function is safe for concurrent access.
	FetchBlockRegion([]byte) (*database.BlockRegion, error)
}

Indexer provides a generic interface for an indexer that is managed by an index manager such as the Manager type provided by this package.

type MedianTimeSource

type MedianTimeSource interface {
	// AdjustedTime returns the current time adjusted by the median time
	// offset as calculated from the time samples added by AddTimeSample.
	AdjustedTime() int64

	// AddTimeSample adds a time sample that is used when determining the
	// median time of the added samples.
	AddTimeSample(id string, timeVal int64)

	// Offset returns the number of seconds to adjust the local clock based
	// upon the median of the time samples added by AddTimeData.
	Offset() time.Duration
}

MedianTimeSource provides a mechanism to add several time samples which are used to determine a median time which is then used as an offset to the local clock.

func NewMedianTime

func NewMedianTime() MedianTimeSource

NewMedianTime returns a new instance of concurrency-safe implementation of the MedianTimeSource interface. The returned implementation contains the rules necessary for proper time handling in the chain consensus rules and expects the time samples to be added from the timestamp field of the version message received from remote peers that successfully connect and negotiate.

type Notification

type Notification struct {
	Type NotificationType
	Data interface{}
}

Notification defines notification that is sent to the caller via the callback function provided during the call to New and consists of a notification type as well as associated data that depends on the type as follows:

  • NTBlockAccepted: *asiutil.Block
  • NTBlockConnected: *asiutil.Block
  • NTBlockDisconnected: [*asiutil.Block, *asiutil.VBlock]

type NotificationCallback

type NotificationCallback func(*Notification)

NotificationCallback is used for a caller to provide a callback for notifications about various chain events.

type NotificationType

type NotificationType int

NotificationType represents the type of a notification message.

const (
	// NTBlockAccepted indicates the associated block was accepted into
	// the block chain.  Note that this does not necessarily mean it was
	// added to the main chain.  For that, use NTBlockConnected.
	NTBlockAccepted NotificationType = iota

	// NTBlockConnected indicates the associated block was connected to the
	// main chain.
	NTBlockConnected

	// NTBlockDisconnected indicates the associated block was disconnected
	// from the main chain.
	NTBlockDisconnected
)

Constants for the type of a notification message.

func (NotificationType) String

func (n NotificationType) String() string

String returns the NotificationType in human-readable form.

type RuleError

type RuleError struct {
	ErrorCode   ErrorCode // Describes the kind of error
	Description string    // Human readable description of the issue
}

RuleError identifies a rule violation. It is used to indicate that processing of a block or transaction failed due to one of the many validation rules. The caller can use type assertions to determine if a failure was specifically due to a rule violation and access the ErrorCode field to ascertain the specific reason for the rule violation.

func (RuleError) Error

func (e RuleError) Error() string

Error satisfies the error interface and prints human-readable errors.

type SequenceLock

type SequenceLock struct {
	Seconds     int64
	BlockHeight int32
}

SequenceLock represents the converted relative lock-time in seconds, and absolute block-height for a transaction input's relative lock-times. According to SequenceLock, after the referenced input has been confirmed within a block, a transaction spending that input can be included into a block either after 'seconds' (according to past median time), or once the 'BlockHeight' has been reached.

type ThresholdState

type ThresholdState byte

ThresholdState define the various threshold states used when voting on consensus changes.

const (
	// ThresholdDefined is the first state for each deployment and is the
	// state for the genesis block has by definition for all deployments.
	ThresholdDefined ThresholdState = iota

	// ThresholdStarted is the state for a deployment once its start time
	// has been reached.
	ThresholdStarted

	// ThresholdLockedIn is the state for a deployment during the retarget
	// period which is after the ThresholdStarted state period and the
	// number of blocks that have voted for the deployment equal or exceed
	// the required number of votes for the deployment.
	ThresholdLockedIn

	// ThresholdActive is the state for a deployment for all blocks after a
	// retarget period in which the deployment was in the ThresholdLockedIn
	// state.
	ThresholdActive

	// ThresholdFailed is the state for a deployment once its expiration
	// time has been reached and it did not reach the ThresholdLockedIn
	// state.
	ThresholdFailed
)

These constants are used to identify specific threshold states.

func (ThresholdState) String

func (t ThresholdState) String() string

String returns the ThresholdState as a human-readable name.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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