Documentation ¶
Overview ¶
Package blockchain implements bitcoin block handling and chain selection rules.
The bitcoin block handling and chain selection rules are an integral, and quite likely the most important, part of bitcoin. Unfortunately, at the time of this writing, these rules are also largely undocumented and had to be ascertained from the jaxnetd source code. At its core, bitcoin is a distributed consensus of which blocks are valid and which ones will comprise the main block chain (public ledger) that ultimately determines accepted transactions, so it is extremely important that fully validating nodes agree on all rules.
At a high level, this package provides support for inserting new blocks into the block chain according to the aforementioned rules. It includes functionality such as rejecting duplicate blocks, ensuring blocks and transactions follow all rules, orphan handling, and best chain selection along with reorganization.
Since this package does not deal with other bitcoin specifics such as network communication or wallets, it provides a notification system which gives the caller a high level of flexibility in how they want to react to certain events such as orphan blocks which need their parents requested and newly connected main chain blocks which might result in wallet updates.
Bitcoin Chain Processing Overview ¶
Before a block is allowed into the block chain, it must go through an intensive series of validation rules. The following list serves as a general outline of those rules to provide some intuition into what is going on under the hood, but is by no means exhaustive:
- Reject duplicate blocks
- Perform a series of sanity checks on the block and its transactions such as verifying proof of work, timestamps, number and character of transactions, transaction amounts, script complexity, and merkle root calculations
- Compare the block against predetermined checkpoints for expected timestamps and difficulty based on elapsed time since the checkpoint
- Save the most recent orphan blocks for a limited time in case their parent blocks become available
- Stop processing if the block is an orphan as the rest of the processing depends on the block's position within the block chain
- Perform a series of more thorough checks that depend on the block's position within the block chain such as verifying block difficulties adhere to difficulty retarget rules, timestamps are after the median of the last several blocks, all transactions are finalized, checkpoint blocks match, and block versions are in line with the previous blocks
- Determine how the block fits into the chain and perform different actions accordingly in order to ensure any side chains which have higher difficulty than the main chain become the new main chain
- When a block is being connected to the main chain (either through reorganization of a side chain to the main chain or just extending the main chain), perform further checks on the block's transactions such as verifying transaction duplicates, script complexity for the combination of connected scripts, coinbase maturity, double spends, and connected transaction values
- Run the transaction scripts to verify the spender is allowed to spend the coins
- Insert the block into the block database
Errors ¶
Errors returned by this package are either the raw errors provided by underlying calls or of type blockchain.RuleError. This allows the caller to differentiate between unexpected errors, such as database errors, versus errors due to rule violations through type assertions. In addition, callers can programmatically determine the specific rule violation by examining the ErrorCode field of the type asserted blockchain.RuleError.
Bitcoin Improvement Proposals ¶
This package includes spec changes outlined by the following BIPs:
BIP0016 (https://en.bitcoin.it/wiki/BIP_0016) BIP0030 (https://en.bitcoin.it/wiki/BIP_0030) BIP0034 (https://en.bitcoin.it/wiki/BIP_0034)
Index ¶
- Constants
- func DisableLog()
- func LockTimeToSequence(isSeconds bool, locktime uint32) uint32
- func UseLogger(logger zerolog.Logger)
- func VerifyStateSanity(db database.DB) error
- type BlockChain
- func (b *BlockChain) BestSnapshot() *chaindata.BestState
- func (b *BlockChain) BlockByHash(hash *chainhash.Hash) (*jaxutil.Block, error)
- func (b *BlockChain) BlockByHeight(blockHeight int32) (*jaxutil.Block, error)
- func (b *BlockChain) BlockHashByHeight(blockHeight int32) (*chainhash.Hash, error)
- func (b *BlockChain) BlockHeightByHash(hash *chainhash.Hash) (int32, error)
- func (b *BlockChain) BlockIDsByHash(hash *chainhash.Hash) (int32, int64, int64, error)
- func (b *BlockChain) BlockLocatorFromHash(hash *chainhash.Hash) BlockLocator
- func (b *BlockChain) BlockSerialIDByHash(block *chainhash.Hash) (int64, int64, error)
- func (b *BlockChain) CalcKForHeight(height int32) uint32
- func (b *BlockChain) CalcNextBlockVersion() wire.BVersion
- func (b *BlockChain) CalcNextK() uint32
- func (b *BlockChain) CalcNextRequiredDifficulty(timestamp time.Time) (uint32, error)
- func (b *BlockChain) CalcSequenceLock(tx *jaxutil.Tx, utxoView *chaindata.UtxoViewpoint, mempool bool) (*chaindata.SequenceLock, error)
- func (b *BlockChain) Chain() chainctx.IChainCtx
- func (b *BlockChain) ChainBlockGenerator() chaindata.ChainBlockGenerator
- func (b *BlockChain) CheckConnectBlockTemplate(block *jaxutil.Block, skipAuxValidation bool) error
- func (b *BlockChain) Checkpoints() []chaincfg.Checkpoint
- func (b *BlockChain) DB() database.DB
- func (b *BlockChain) FetchSpendJournal(targetBlock *jaxutil.Block) ([]chaindata.SpentTxOut, error)
- func (b *BlockChain) FetchUtxoEntry(outpoint wire.OutPoint) (*chaindata.UtxoEntry, error)
- func (b *BlockChain) FetchUtxoView(tx *jaxutil.Tx) (*chaindata.UtxoViewpoint, error)
- func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash
- func (b *BlockChain) HasCheckpoints() bool
- func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error)
- func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error)
- func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error)
- func (b *BlockChain) HeightToHashRange(startHeight int32, endHash *chainhash.Hash, maxResults int) ([]chainhash.Hash, error)
- func (b *BlockChain) IntervalBlockHashes(endHash *chainhash.Hash, interval int) ([]chainhash.Hash, error)
- func (b *BlockChain) IsCheckpointCandidate(block *jaxutil.Block) (bool, error)
- func (b *BlockChain) IsCurrent() bool
- func (b *BlockChain) IsDeploymentActive(deploymentID uint32) (bool, error)
- func (b *BlockChain) IsKnownOrphan(hash *chainhash.Hash) bool
- func (b *BlockChain) LatestBlockLocator() (BlockLocator, error)
- func (b *BlockChain) LatestCheckpoint() *chaincfg.Checkpoint
- func (b *BlockChain) ListEADAddresses() (map[string]*wire.EADAddresses, error)
- func (b *BlockChain) ListUtxoEntry(limit int) (map[wire.OutPoint]*chaindata.UtxoEntry, error)
- func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash
- func (b *BlockChain) LocateHeaders(locator BlockLocator, hashStop *chainhash.Hash) []wire.HeaderBox
- func (b *BlockChain) MMRTree() *mmr.BlocksMMRTree
- func (b *BlockChain) MainChainHasBlock(hash *chainhash.Hash) bool
- func (b *BlockChain) ProcessBlock(block *jaxutil.Block, blockActualMMR chainhash.Hash, ...) (bool, bool, error)
- func (b *BlockChain) SaveBestChainSerialIDs() error
- func (b *BlockChain) ShardCount() (uint32, error)
- func (b *BlockChain) Subscribe(callback NotificationCallback)
- func (b *BlockChain) ThresholdState(deploymentID uint32) (ThresholdState, error)
- type BlockLocator
- type BlockNotification
- type Config
- type IndexManager
- type Notification
- type NotificationCallback
- type NotificationType
- type ThresholdState
Examples ¶
Constants ¶
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 ¶
This section is empty.
Functions ¶
func DisableLog ¶
func DisableLog()
DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.
func LockTimeToSequence ¶
LockTimeToSequence converts the passed relative locktime to a sequence number in accordance to BIP-68. See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
- (Compatibility)
func VerifyStateSanity ¶ added in v0.4.8
VerifyStateSanity attempts to load and initialize the chain state from the database. When the db does not yet contain any chain state, both it and the chain state are initialized to the genesis block.
Types ¶
type BlockChain ¶
type BlockChain struct { TimeSource chaindata.MedianTimeSource SigCache *txscript.SigCache HashCache *txscript.HashCache // 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) (*BlockChain, error)
New returns a BlockChain instance using the provided configuration details.
func (*BlockChain) BestSnapshot ¶
func (b *BlockChain) BestSnapshot() *chaindata.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 ¶
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) (*jaxutil.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) (*chainhash.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 *chainhash.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) BlockIDsByHash ¶
BlockIDsByHash returns the height, serialID and previous serialID of the block with the given hash.
This function is safe for concurrent access.
func (*BlockChain) BlockLocatorFromHash ¶
func (b *BlockChain) BlockLocatorFromHash(hash *chainhash.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) BlockSerialIDByHash ¶
BlockSerialIDByHash returns the serialID and previous serialID of the block with the given hash.
This function is safe for concurrent access.
func (*BlockChain) CalcKForHeight ¶ added in v0.4.0
func (b *BlockChain) CalcKForHeight(height int32) uint32
CalcKForHeight calculates the required k coefficient
This function is safe for concurrent access. nolint: revive
func (*BlockChain) CalcNextBlockVersion ¶
func (b *BlockChain) CalcNextBlockVersion() wire.BVersion
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) CalcNextK ¶
func (b *BlockChain) CalcNextK() uint32
CalcNextK calculates the required k coefficient
This function is safe for concurrent access. nolint: revive
func (*BlockChain) CalcNextRequiredDifficulty ¶
func (b *BlockChain) CalcNextRequiredDifficulty(timestamp time.Time) (uint32, error)
CalcNextRequiredDifficulty calculates the required difficulty for the block after the end of the current best chain based on the difficulty retarget rules.
This function is safe for concurrent access.
func (*BlockChain) CalcSequenceLock ¶
func (b *BlockChain) CalcSequenceLock(tx *jaxutil.Tx, utxoView *chaindata.UtxoViewpoint, mempool bool) (*chaindata.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) Chain ¶
func (b *BlockChain) Chain() chainctx.IChainCtx
func (*BlockChain) ChainBlockGenerator ¶
func (b *BlockChain) ChainBlockGenerator() chaindata.ChainBlockGenerator
func (*BlockChain) CheckConnectBlockTemplate ¶
func (b *BlockChain) CheckConnectBlockTemplate(block *jaxutil.Block, skipAuxValidation bool) error
CheckConnectBlockTemplate fully validates that connecting the passed block to the main chain does not violate any consensus rules, aside from the proof of work requirement. The block must connect to the current tip of the main chain.
This function is safe for concurrent access.
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) DB ¶ added in v0.4.10
func (b *BlockChain) DB() database.DB
func (*BlockChain) FetchSpendJournal ¶
func (b *BlockChain) FetchSpendJournal(targetBlock *jaxutil.Block) ([]chaindata.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) FetchUtxoEntry ¶
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 *jaxutil.Tx) (*chaindata.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) GetOrphanRoot ¶
func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.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) 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 *chainhash.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) HeaderByHash ¶
func (b *BlockChain) HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error)
HeaderByHash returns the block header identified by the given hash or an error if it doesn't exist. Note that this will return headers from both the main and side chains.
func (*BlockChain) HeightRange ¶
func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error)
HeightRange returns a range of block hashes for the given start and end heights. It is inclusive of the start height and exclusive of the end height. The end height will be limited to the current main chain height.
This function is safe for concurrent access.
func (*BlockChain) HeightToHashRange ¶
func (b *BlockChain) HeightToHashRange(startHeight int32, endHash *chainhash.Hash, maxResults int) ([]chainhash.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) IntervalBlockHashes ¶
func (b *BlockChain) IntervalBlockHashes(endHash *chainhash.Hash, interval int) ([]chainhash.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 *jaxutil.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 *chainhash.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) ListEADAddresses ¶
func (b *BlockChain) ListEADAddresses() (map[string]*wire.EADAddresses, error)
func (*BlockChain) ListUtxoEntry ¶
func (*BlockChain) LocateBlocks ¶
func (b *BlockChain) LocateBlocks(locator BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.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 *chainhash.Hash) []wire.HeaderBox
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 wire.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) MMRTree ¶ added in v0.4.0
func (b *BlockChain) MMRTree() *mmr.BlocksMMRTree
func (*BlockChain) MainChainHasBlock ¶
func (b *BlockChain) MainChainHasBlock(hash *chainhash.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) ProcessBlock ¶
func (b *BlockChain) ProcessBlock(block *jaxutil.Block, blockActualMMR chainhash.Hash, flags chaindata.BehaviorFlags) (bool, bool, error)
ProcessBlock is the main workhorse for handling insertion of new blocks into the blockchain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, and insertion into the blockchain 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.
Example ¶
This example demonstrates how to create a new chain instance and use ProcessBlock to attempt to add a block to the chain. As the package overview documentation describes, this includes all of the Bitcoin consensus rules. This example intentionally attempts to insert a duplicate genesis block to illustrate how an invalid block is handled.
// Create a new database to store the accepted blocks into. Typically // this would be opening an existing database and would not be deleting // and creating a new database like this, but it is done here so this is // a complete working example and does not leave temporary files laying // around. dbPath := filepath.Join(os.TempDir(), "my_processblock") _ = os.RemoveAll(dbPath) db, err := database.Create("ffldb", chainctx.BeaconChain, dbPath, chaincfg.MainNetParams.Net) if err != nil { fmt.Printf("Failed to create database: %v\n", err) return } defer os.RemoveAll(dbPath) defer db.Close() // Create a new GetBlockChain instance using the underlying database for // the main bitcoin network. This example does not demonstrate some // of the other available configuration options such as specifying a // notification callback and signature cache. Also, the caller would // ordinarily keep a reference to the median time source and add time // values obtained from other peers on the network so the local time is // adjusted to be in agreement with other peers. // hash, _ := chainhash.NewHashFromStr("aaa") testChain, err := New(&Config{ DB: db, ChainParams: &chaincfg.MainNetParams, TimeSource: chaindata.NewMedianTime(), ChainCtx: chainctx.NewBeaconChain(&chaincfg.Params{ Name: "test", Net: 0, DefaultRPCPort: "", DNSSeeds: []chaincfg.DNSSeed{}, CoinbaseMaturity: 0, Checkpoints: []chaincfg.Checkpoint{}, RuleChangeActivationThreshold: 0, MinerConfirmationWindow: 0, Deployments: [2]chaincfg.ConsensusDeployment{}, RelayNonStdTxs: false, Bech32HRPSegwit: "", PubKeyHashAddrID: 0, ScriptHashAddrID: 0, PrivateKeyID: 0, WitnessPubKeyHashAddrID: 0, WitnessScriptHashAddrID: 0, EADAddressID: 0, HDPrivateKeyID: [4]byte{}, HDPublicKeyID: [4]byte{}, HDCoinType: 0, AutoExpand: false, InitialExpansionRule: 1, InitialExpansionLimit: 0, }), }) if err != nil { fmt.Printf("Failed to create chain instance: %v\n", err) return } // Process a block. For this example, we are going to intentionally // cause an error by trying to process the genesis block which already // exists. msgBlock := wire.EmptyBeaconBlock() genesisBlock := jaxutil.NewBlock(&msgBlock) isMainChain, isOrphan, err := testChain.ProcessBlock(genesisBlock, testChain.MMRTree().CurrentRoot(), 0) if err != nil { fmt.Printf("Failed to process block: %v\n", err) return } fmt.Printf("Block accepted. Is it on the main chain?: %v", isMainChain) fmt.Printf("Block accepted. Is it an orphan?: %v", isOrphan)
Output: Failed to process block: already have block 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
func (*BlockChain) SaveBestChainSerialIDs ¶ added in v0.4.3
func (b *BlockChain) SaveBestChainSerialIDs() error
func (*BlockChain) ShardCount ¶
func (b *BlockChain) ShardCount() (uint32, error)
ShardCount returns the actual number of shards in network, based on information form latest beacon header.
This function is safe for concurrent access.
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) 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 []*wire.BlockLocatorMeta
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 BlockNotification ¶ added in v0.4.2
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.DB // ChainParams identifies which chain parameters the chain is associated // with. // // This field is required. ChainParams *chaincfg.Params ChainCtx chainctx.IChainCtx BlockGen chaindata.ChainBlockGenerator // 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{} // 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 chaindata.MedianTimeSource // SigCache defines a signature cache to use when when validating // signatures. This is typically most useful when individual // transactions are already being validated prior to their inclusion in // a block such as what is usually done via a transaction memory pool. // // This field can be nil if the caller is not interested in using a // signature cache. SigCache *txscript.SigCache // IndexManager defines an index manager to use when initializing the // chain and connecting and disconnecting blocks. // // This field can be nil if the caller does not wish to make use of an // index manager. IndexManager IndexManager // HashCache defines a transaction hash mid-state cache to use when // validating transactions. This cache has the potential to greatly // speed up transaction validation as re-using the pre-calculated // mid-state eliminates the O(N^2) validation complexity due to the // SigHashAll flag. // // This field can be nil if the caller is not interested in using a // signature cache. HashCache *txscript.HashCache DBFullRescan bool }
Config is a descriptor which specifies the blockchain instance configuration.
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, *jaxutil.Block, chainhash.Hash, []chaindata.SpentTxOut) 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, *jaxutil.Block, []chaindata.SpentTxOut) 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 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: *jaxutil.Block
- NTBlockConnected: *jaxutil.Block
- NTBlockDisconnected: *jaxutil.Block
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 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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package fullblocktests provides a set of block consensus validation tests.
|
Package fullblocktests provides a set of block consensus validation tests. |
Package indexers implements optional block chain indexes.
|
Package indexers implements optional block chain indexes. |