blockchain

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2024 License: ISC Imports: 31 Imported by: 0

README

blockchain

Build Status ISC License GoDoc

Package blockchain implements bitcoin block handling and chain selection rules. The test coverage is currently only around 60%, but will be increasing over time. See test_coverage.txt for the gocov coverage report. Alternatively, if you are running a POSIX OS, you can run the cov_report.sh script for a real-time report. Package blockchain is licensed under the liberal ISC license.

There is an associated blog post about the release of this package here.

This package has intentionally been designed so it can be used as a standalone package for any projects needing to handle processing of blocks into the bitcoin block chain.

Installation and Updating

$ go get -u github.com/btcsuite/btcd/blockchain

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

Examples

  • ProcessBlock Example
    Demonstrates how to create a new chain instance and use ProcessBlock to attempt to add a block to the chain. This example intentionally attempts to insert a duplicate genesis block to illustrate how an invalid block is handled.

  • CompactToBig Example
    Demonstrates how to convert the compact "bits" in a block header which represent the target difficulty to a big integer and display it using the typical hex notation.

  • BigToCompact Example
    Demonstrates how to convert a target difficulty into the compact "bits" in a block header which represent that target difficulty.

GPG Verification Key

All official release tags are signed by Conformal so users can ensure the code has not been tampered with and is coming from the btcsuite developers. To verify the signature perform the following:

  • Download the public key from the Conformal website at https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt

  • Import the public key into your GPG keyring:

    gpg --import GIT-GPG-KEY-conformal.txt
    
  • Verify the release tag with the following command where TAG_NAME is a placeholder for the specific tag:

    git tag -v TAG_NAME
    

License

Package blockchain is licensed under the copyfree ISC License.

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 bitcoind 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
  • Cache recent UTXOs in memory

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:

BIP0009 (https://en.bitcoin.it/wiki/BIP_0009)
BIP0016 (https://en.bitcoin.it/wiki/BIP_0016)
BIP0030 (https://en.bitcoin.it/wiki/BIP_0030)
BIP0034 (https://en.bitcoin.it/wiki/BIP_0034)
BIP0065 (https://en.bitcoin.it/wiki/BIP_0065)
BIP0066 (https://en.bitcoin.it/wiki/BIP_0066)
BIP0068 (https://en.bitcoin.it/wiki/BIP_0068)

Index

Examples

Constants

View Source
const (
	// CoinbaseWitnessDataLen is the required length of the only element within
	// the coinbase's witness data if the coinbase transaction contains a
	// witness commitment.
	CoinbaseWitnessDataLen = 32

	// CoinbaseWitnessPkScriptLength is the length of the public key script
	// containing an OP_RETURN, the WitnessMagicBytes, and the witness
	// commitment itself. In order to be a valid candidate for the output
	// containing the witness commitment
	CoinbaseWitnessPkScriptLength = 38
)
View Source
const (
	// MaxTimeOffsetSeconds is the maximum number of seconds a block time
	// is allowed to be ahead of the current time.  This is currently 2
	// hours.
	MaxTimeOffsetSeconds = 2 * 60 * 60

	// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
	MinCoinbaseScriptLen = 2

	// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
	MaxCoinbaseScriptLen = 100
)
View Source
const (
	// MaxBlockWeight defines the maximum block weight, where "block
	// weight" is interpreted as defined in BIP0141. A block's weight is
	// calculated as the sum of the of bytes in the existing transactions
	// and header, plus the weight of each byte within a transaction. The
	// weight of a "base" byte is 4, while the weight of a witness byte is
	// 1. As a result, for a block to be valid, the BlockWeight MUST be
	// less than, or equal to MaxBlockWeight.
	MaxBlockWeight = 4000000

	// MaxBlockBaseSize is the maximum number of bytes within a block
	// which can be allocated to non-witness data.
	MaxBlockBaseSize = 1000000

	// MaxBlockSigOpsCost is the maximum number of signature operations
	// allowed for a block. It is calculated via a weighted algorithm which
	// weights segregated witness sig ops lower than regular sig ops.
	MaxBlockSigOpsCost = 80000

	// WitnessScaleFactor determines the level of "discount" witness data
	// receives compared to "base" data. A scale factor of 4, denotes that
	// witness data is 1/4 as cheap as regular non-witness data.
	WitnessScaleFactor = 4

	// MinTxOutputWeight is the minimum possible weight for a transaction
	// output.
	MinTxOutputWeight = WitnessScaleFactor * wire.MinTxOutPayload

	// MaxOutputsPerBlock is the maximum number of transaction outputs there
	// can be in a block of max weight size.
	MaxOutputsPerBlock = MaxBlockWeight / MinTxOutputWeight
)
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.

View Source
const (
	// UtxoFlushPeriodicInterval is the interval at which a flush is performed
	// when the flush mode FlushPeriodic is used.  This is used when the initial
	// block download is complete and it's useful to flush periodically in case
	// of unforseen shutdowns.
	UtxoFlushPeriodicInterval = time.Minute * 5
)

Variables

View Source
var (
	// WitnessMagicBytes is the prefix marker within the public key script
	// of a coinbase output to indicate that this output holds the witness
	// commitment for a block.
	WitnessMagicBytes = []byte{
		txscript.OP_RETURN,
		txscript.OP_DATA_36,
		0xaa,
		0x21,
		0xa9,
		0xed,
	}
)

Functions

func BigToCompact

func BigToCompact(n *big.Int) uint32

BigToCompact converts a whole number N to a compact representation using an unsigned 32-bit number. The compact representation only provides 23 bits of precision, so values larger than (2^23 - 1) only encode the most significant digits of the number. See CompactToBig for details.

Example

This example demonstrates how to convert a target difficulty into the compact "bits" in a block header which represent that target difficulty .

package main

import (
	"fmt"
	"math/big"

	"github.com/utreexo/utreexod/blockchain"

	_ "github.com/utreexo/utreexod/database/ffldb"
)

func main() {
	// Convert the target difficulty from block 300000 in the main block
	// chain to compact form.
	t := "0000000000000000896c00000000000000000000000000000000000000000000"
	targetDifficulty, success := new(big.Int).SetString(t, 16)
	if !success {
		fmt.Println("invalid target difficulty")
		return
	}
	bits := blockchain.BigToCompact(targetDifficulty)

	fmt.Println(bits)

}
Output:

419465580

func BlockToAddLeaves

func BlockToAddLeaves(block *btcutil.Block, skiplist []uint32, remembers []uint32,
	outCount int) []utreexo.Leaf

BlockToAdds turns the newly created utxos in a block into leaves that will be commited to the utreexo accumulator.

skiplist will cause skip indexes of the utxos that match with the ones included in the slice. For example, if [0, 3, 11] is given as the skiplist, then utxos that appear in the 0th, 3rd, and 11th in the block will be skipped over.

func BlockToDelOPs

func BlockToDelOPs(
	blk *btcutil.Block) []wire.OutPoint

blockToDelOPs gives all the UTXOs in a block that need proofs in order to be deleted. All txinputs except for the coinbase input and utxos created within the same block (on the skiplist)

func BuildMerkleTreeStore

func BuildMerkleTreeStore(transactions []*btcutil.Tx, witness bool) []*chainhash.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.

The additional bool parameter indicates if we are generating the merkle tree using witness transaction id's rather than regular transaction id's. This also presents an additional case wherein the wtxid of the coinbase transaction is the zeroHash.

func CachedLeavesBackendPut added in v0.4.0

func CachedLeavesBackendPut(tx *leveldb.Transaction, k utreexo.Hash, v uint64) error

CachedLeavesBackendPut puts a key-value pair in the given leveldb tx.

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 CalcWork

func CalcWork(bits uint32) *big.Int

CalcWork calculates a work value from difficulty bits. Bitcoin increases the difficulty for generating a block by decreasing the value which the generated hash must be less than. This difficulty target is stored in each block header using a compact representation as described in the documentation for CompactToBig. The main chain is selected by choosing the chain that has the most proof of work (highest difficulty). Since a lower target difficulty value equates to higher actual difficulty, the work value which will be accumulated must be the inverse of the difficulty. Also, in order to avoid potential division by zero and really small floating point numbers, the result adds 1 to the denominator and multiplies the numerator by 2^256.

func ChainstateInitialized

func ChainstateInitialized(dbTx database.Tx) bool

ChainstateInitialized returns true if the chainstate has been previously initialized.

func CheckBlockSanity

func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) 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 CheckProofOfWork

func CheckProofOfWork(block *btcutil.Block, powLimit *big.Int) error

CheckProofOfWork ensures the block header bits which indicate the target difficulty is in min/max range and that the block hash is less than the target difficulty as claimed.

func CheckTransactionInputs

func CheckTransactionInputs(tx *btcutil.Tx, txHeight int32, utxoView *UtxoViewpoint, chainParams *chaincfg.Params) (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 *btcutil.Tx) error

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

func CompactToBig

func CompactToBig(compact uint32) *big.Int

CompactToBig converts a compact representation of a whole number N to an unsigned 32-bit number. The representation is similar to IEEE754 floating point numbers.

Like IEEE754 floating point, there are three basic components: the sign, the exponent, and the mantissa. They are broken out as follows:

  • the most significant 8 bits represent the unsigned base 256 exponent

  • bit 23 (the 24th bit) represents the sign bit

  • the least significant 23 bits represent the mantissa

    ------------------------------------------------- | Exponent | Sign | Mantissa | ------------------------------------------------- | 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] | -------------------------------------------------

The formula to calculate N is:

N = (-1^sign) * mantissa * 256^(exponent-3)

This compact form is only used in bitcoin to encode unsigned 256-bit numbers which represent difficulty targets, thus there really is not a need for a sign bit, but it is implemented here to stay consistent with bitcoind.

Example

This example demonstrates how to convert the compact "bits" in a block header which represent the target difficulty to a big integer and display it using the typical hex notation.

package main

import (
	"fmt"

	"github.com/utreexo/utreexod/blockchain"

	_ "github.com/utreexo/utreexod/database/ffldb"
)

func main() {
	// Convert the bits from block 300000 in the main block chain.
	bits := uint32(419465580)
	targetDifficulty := blockchain.CompactToBig(bits)

	// Display it in hex.
	fmt.Printf("%064x\n", targetDifficulty.Bytes())

}
Output:

0000000000000000896c00000000000000000000000000000000000000000000

func CountP2SHSigOps

func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *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 *btcutil.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 DedupeBlock

func DedupeBlock(blk *btcutil.Block) (inCount, outCount int, inskip []uint32, outskip []uint32)

DedupeBlock takes a bitcoin block, and returns two int slices: the indexes of inputs, and idexes of outputs which can be removed. These are indexes within the block as a whole, even the coinbase tx. So the coinbase tx in & output numbers affect the skip lists even though the coinbase ins/outs can never be deduped. it's simpler that way.

func DeserializeUtreexoRoots

func DeserializeUtreexoRoots(serializedUView []byte) (uint64, []utreexo.Hash, error)

DeserializeUtreexoRoots deserializes the provided byte slice into numLeaves and roots.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func ExtractAccumulatorAddDels

func ExtractAccumulatorAddDels(block *btcutil.Block, bestChain *chainView, remembers []uint32) (
	[]utreexo.Leaf, []utreexo.Hash, error)

ExtractAccumulatorAddDels extracts the additions and the deletions that will be used to modify the utreexo accumulator.

func ExtractCoinbaseHeight

func ExtractCoinbaseHeight(coinbaseTx *btcutil.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 ExtractMerkleBranch

func ExtractMerkleBranch(merkles []*chainhash.Hash, txHash chainhash.Hash) []*chainhash.Hash

ExtractMerkleBranch returns the merkle branches needed to prove the txHash. The returned merkle branch does not contain the passed in tx hash.

func ExtractWitnessCommitment

func ExtractWitnessCommitment(tx *btcutil.Tx) ([]byte, bool)

ExtractWitnessCommitment attempts to locate, and return the witness commitment for a block. The witness commitment is of the form: SHA256(witness root || witness nonce). The function additionally returns a boolean indicating if the witness root was located within any of the txOut's in the passed transaction. The witness commitment is stored as the data push for an OP_RETURN with special magic bytes to aide in location.

func FileExists

func FileExists(name string) bool

FilesExists returns whether or not the named file or directory exists.

func GetBlockWeight

func GetBlockWeight(blk *btcutil.Block) int64

GetBlockWeight computes the value of the weight metric for a given block. Currently the weight metric is simply the sum of the block's serialized size without any witness data scaled proportionally by the WitnessScaleFactor, and the block's serialized size including any witness data.

func GetSigOpCost

func GetSigOpCost(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint, bip16, segWit bool) (int, error)

GetSigOpCost returns the unified sig op cost for the passed transaction respecting current active soft-forks which modified sig op cost counting. The unified sig op cost for a transaction is computed as the sum of: the legacy sig op count scaled according to the WitnessScaleFactor, the sig op count for all p2sh inputs scaled by the WitnessScaleFactor, and finally the unscaled sig op count for any inputs spending witness programs.

func GetTransactionWeight

func GetTransactionWeight(tx *btcutil.Tx) int64

GetTransactionWeight computes the value of the weight metric for a given transaction. Currently the weight metric is simply the sum of the transactions's serialized size without any witness data scaled proportionally by the WitnessScaleFactor, and the transaction's serialized size including any witness data.

func HashMerkleBranches

func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.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 HashMerkleRoot

func HashMerkleRoot(merkles []*chainhash.Hash, target chainhash.Hash, pos int) chainhash.Hash

HashMerkleRoot calculates the merkle root given the target, its position, and all the branches needed to hash up to the root.

func HashToBig

func HashToBig(hash *chainhash.Hash) *big.Int

HashToBig converts a chainhash.Hash into a big.Int that can be used to perform math comparisons.

func IsCoinBase

func IsCoinBase(tx *btcutil.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 wire transaction.

func IsCoinBaseTx

func IsCoinBaseTx(msgTx *wire.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 wire transaction as opposed to a higher level util transaction.

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func IsSupportedDbType

func IsSupportedDbType(dbType string) bool

IsSupportedDbType returns whether or not the passed database type is currently supported.

func IsUnspendable

func IsUnspendable(o *wire.TxOut) bool

IsUnspendable determines whether a tx is spendable or not. returns true if spendable, false if unspendable.

func LockTimeToSequence

func LockTimeToSequence(isSeconds bool, locktime uint32) uint32

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 NodesBackendDelete added in v0.4.0

func NodesBackendDelete(tx *leveldb.Transaction, k uint64) error

NodesBackendDelete deletes the corresponding key-value pair from the given leveldb tx.

func NodesBackendPut added in v0.4.0

func NodesBackendPut(tx *leveldb.Transaction, k uint64, v utreexo.Leaf) error

NodesBackendPut puts a key-value pair in the given leveldb tx.

func OutpointKey

func OutpointKey(outpoint wire.OutPoint) *[]byte

OutpointKey returns a key suitable for use as a database key in the utxo set while making use of a free list. A new buffer is allocated if there are not already any available on the free list. The returned byte slice should be returned to the free list by using the RecycleOutpointKey function when the caller is done with it _unless_ the slice will need to live for longer than the caller can calculate such as when used to write to the database.

func ProofSanity

func ProofSanity(ud *wire.UData, outPoints []wire.OutPoint) error

ProofSanity checks that the UData that was given proves the same outPoints that is included in the corresponding block.

func RecycleOutpointKey

func RecycleOutpointKey(key *[]byte)

RecycleOutpointKey puts the provided byte slice, which should have been obtained via the outpointKey function, back on the free list.

func SequenceLockActive

func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
	medianTimePast time.Time) 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 SerializeUtreexoRoots

func SerializeUtreexoRoots(numLeaves uint64, roots []utreexo.Hash) ([]byte, error)

SerializeUtreexoRoots serializes the numLeaves and the roots into a byte slice.

func ShouldHaveSerializedBlockHeight

func ShouldHaveSerializedBlockHeight(header *wire.BlockHeader) bool

ShouldHaveSerializedBlockHeight determines if a block should have a serialized block height embedded within the scriptSig of its coinbase transaction. Judgement is based on the block version in the block header. Blocks with version 2 and above satisfy this criteria. See BIP0034 for further information.

func SolveBlock

func SolveBlock(header *wire.BlockHeader) bool

SolveBlock attempts to find a nonce which makes the passed block header hash to a value less than the target difficulty. When a successful solution is found true is returned and the nonce field of the passed header is updated with the solution. False is returned if no solution exists.

func TxToDelLeaves

func TxToDelLeaves(tx *btcutil.Tx, chain *BlockChain) ([]wire.LeafData, error)

TxToDelLeaves takes a tx and generates the leaf datas for all the inputs. The leaf datas represent a utxoviewpoinnt just for the tx, along with the accumulator proof that proves all the txIns' inclusion.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info.

func UtxoCacheInitialized

func UtxoCacheInitialized(dbTx database.Tx) bool

UtxoCacheInitialized returns true if the utxo cache has already been initialized. Will return false if this is the first time starting up the node or if the node has been previously started as a utreexo node.

func ValidateTransactionScripts

func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint,
	flags txscript.ScriptFlags, sigCache *txscript.SigCache,
	hashCache *txscript.HashCache) error

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

func ValidateWitnessCommitment

func ValidateWitnessCommitment(blk *btcutil.Block) error

ValidateWitnessCommitment validates the witness commitment (if any) found within the coinbase transaction of the passed block.

Types

type AssertError

type AssertError string

AssertError identifies an error that indicates an internal code consistency issue and should be treated as a critical and unrecoverable error.

func (AssertError) Error

func (e AssertError) Error() string

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

type BehaviorFlags

type BehaviorFlags uint32

BehaviorFlags is a bitmask defining tweaks to the normal behavior when performing chain processing and consensus rules checks.

const (
	// BFFastAdd may be set to indicate that several checks can be avoided
	// for the block since it is already known to fit into the chain due to
	// already proving it correct links into the chain up to a known
	// checkpoint.  This is primarily used for headers-first mode.
	BFFastAdd BehaviorFlags = 1 << iota

	// BFNoPoWCheck may be set to indicate the proof of work check which
	// ensures a block hashes to a value less than the required target will
	// not be performed.
	BFNoPoWCheck

	// BFNone is a convenience value to specifically indicate no flags.
	BFNone BehaviorFlags = 0
)

type BestState

type BestState struct {
	Hash        chainhash.Hash // The hash of the block.
	Height      int32          // The height of the block.
	Bits        uint32         // The difficulty bits of the block.
	BlockSize   uint64         // The size of the block.
	BlockWeight uint64         // The weight of the block.
	NumTxns     uint64         // The number of txns in the block.
	TotalTxns   uint64         // The total number of txns in the chain.
	MedianTime  time.Time      // Median time as per CalcPastMedianTime.
}

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 ChainSetup

func ChainSetup(dbName string, params *chaincfg.Params) (*BlockChain, func(), error)

ChainSetup is used to create a new db and chain instance with the genesis block already inserted. In addition to the new chain instance, it returns a teardown function the caller should invoke when done testing to clean up.

func New

func New(config *Config) (*BlockChain, error)

New returns a BlockChain instance using the provided configuration details.

func (*BlockChain) AssumeUtreexoHash

func (b *BlockChain) AssumeUtreexoHash() chainhash.Hash

AssumeUtreexoHash returns the blockhash of the assumed utreexo point.

func (*BlockChain) AssumeUtreexoHeight

func (b *BlockChain) AssumeUtreexoHeight() int32

AssumeUtreexoHeight returns the height of the assumed utreexo point.

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 *chainhash.Hash) (*btcutil.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) (*btcutil.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) 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) CachedStateSize

func (b *BlockChain) CachedStateSize() uint64

CachedStateSize returns the total size of the cached state of the blockchain in bytes.

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) 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 *btcutil.Tx, utxoView *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) ChainTips

func (b *BlockChain) ChainTips() []ChainTip

ChainTips returns all the chain tips the node itself is aware of. Each tip is represented by its height, block hash, branch length, and status.

This function is safe for concurrent access.

func (*BlockChain) CheckConnectBlockTemplate

func (b *BlockChain) CheckConnectBlockTemplate(block *btcutil.Block) 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) FetchSpendJournal

func (b *BlockChain) FetchSpendJournal(targetBlock *btcutil.Block) ([]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) FetchSpendJournalUnsafe

func (b *BlockChain) FetchSpendJournalUnsafe(targetBlock *btcutil.Block) ([]SpentTxOut, error)

FetchSpendJournalUnsafe 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 NOT safe for concurrent access.

func (*BlockChain) FetchUtreexoViewpoint

func (b *BlockChain) FetchUtreexoViewpoint(blockHash *chainhash.Hash) (*UtreexoViewpoint, error)

FetchUtreexoViewpoint returns the utreexo viewpoint at the given block hash. returns nil if it wasn't found.

This function is safe for concurrent access.

func (*BlockChain) FetchUtxoEntry

func (b *BlockChain) FetchUtxoEntry(outpoint wire.OutPoint) (*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 *btcutil.Tx) (*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) FlushIndexes added in v0.4.0

func (b *BlockChain) FlushIndexes(mode FlushMode, onConnect bool) error

FlushUtxoCache flushes the indexes if a flush is needed with the given flush mode. If the flush is on a block connect and not a reorg, the onConnect bool should be true.

This function is safe for concurrent access.

func (*BlockChain) FlushUtxoCache

func (b *BlockChain) FlushUtxoCache(mode FlushMode) error

FlushUtxoCache flushes the UTXO state to the database if a flush is needed with the given flush mode.

This function is safe for concurrent access.

func (*BlockChain) GenerateUData

func (b *BlockChain) GenerateUData(dels []wire.LeafData) (*wire.UData, error)

GenerateUData generates a utreexo data based on the current state of the utreexo viewpoint.

This function is safe for concurrent access.

func (*BlockChain) GenerateUDataPartial

func (b *BlockChain) GenerateUDataPartial(dels []wire.LeafData, positions []uint64) (*wire.UData, error)

GenerateUDataPartial generates a utreexo data based on the current state of the utreexo viewpoint. It leaves out the full proof hashes and only fetches the requested positions.

This function is safe for concurrent access.

func (*BlockChain) GetLeafHashPositions

func (b *BlockChain) GetLeafHashPositions(leafHashes []utreexo.Hash) []uint64

GetLeafHashPositions returns the positions of the passed in leaf hashes.

This function is safe for concurrent access.

func (*BlockChain) GetNeededPositions

func (b *BlockChain) GetNeededPositions(packedPositions []chainhash.Hash) []chainhash.Hash

GetNeededPositions returns the positions of the needed hashes in order to verify the positions passed in.

This function is safe for concurrent access.

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

func (b *BlockChain) GetUtreexoView() *UtreexoViewpoint

GetUtreexoView returns the underlying utreexo viewpoint.

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

func (b *BlockChain) IndexLookupNode(hash *chainhash.Hash) *blockNode

IndexLookupNode returns the block node identified by the provided hash. It will return nil if there is no entry for the hash.

This function is safe for concurrent access.

func (*BlockChain) IndexNodeStatus

func (b *BlockChain) IndexNodeStatus(node *blockNode) blockStatus

IndexNodeStatus provides concurrent-safe access to the status field of a node.

This function is safe for concurrent access.

func (*BlockChain) InitConsistentState

func (b *BlockChain) InitConsistentState(tip *blockNode, interrupt <-chan struct{}) error

InitConsistentState checks the consistency status of the utxo state and replays blocks if it lags behind the best state of the blockchain.

It needs to be ensured that the chainView passed to this method does not get changed during the execution of this method.

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

func (b *BlockChain) InvalidateBlock(hash *chainhash.Hash) error

InvalidateBlock invalidates the requested block and all its descedents. If a block in the best chain is invalidated, the active chain tip will be the parent of the invalidated block.

This function is safe for concurrent access.

func (*BlockChain) IsAssumeUtreexo

func (b *BlockChain) IsAssumeUtreexo() bool

IsAssumeUtreexo returns true if the assume utreexo points are set.

func (*BlockChain) IsCheckpointCandidate

func (b *BlockChain) IsCheckpointCandidate(block *btcutil.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) IsUtreexoViewActive

func (b *BlockChain) IsUtreexoViewActive() bool

IsUtreexoViewActive returns true if the node depends on the utreexoView instead of a full UTXO set. Returns false if it's not.

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 *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.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 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) 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) PackedPositions

func (b *BlockChain) PackedPositions(leafHashes []utreexo.Hash) []chainhash.Hash

PackedPositions fetches and returns the positions of the leafHashes as chainhash.Hash.

This function is safe for concurrent access.

func (*BlockChain) PastMedianTime

func (b *BlockChain) PastMedianTime(blockHeader *wire.BlockHeader) (time.Time, error)

PastMedianTime returns the past median time from the PoV of the passed block header. The past median time is the median time of the 11 blocks prior to the passed block header.

NOTE: This is part of the chainfg.BlockClock interface

func (*BlockChain) ProcessBlock

func (b *BlockChain) ProcessBlock(block *btcutil.Block, flags 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.

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.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/utreexo/utreexod/blockchain"
	"github.com/utreexo/utreexod/btcutil"
	"github.com/utreexo/utreexod/chaincfg"
	"github.com/utreexo/utreexod/database"

	_ "github.com/utreexo/utreexod/database/ffldb"
)

func main() {
	// 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(), "exampleprocessblock")
	_ = os.RemoveAll(dbPath)
	db, err := database.Create("ffldb", 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 BlockChain 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.
	chain, err := blockchain.New(&blockchain.Config{
		DB:          db,
		ChainParams: &chaincfg.MainNetParams,
		TimeSource:  blockchain.NewMedianTime(),
	})
	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.
	genesisBlock := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)
	isMainChain, isOrphan, err := chain.ProcessBlock(genesisBlock,
		blockchain.BFNone)
	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) ProcessBlockHeader

func (b *BlockChain) ProcessBlockHeader(header *wire.BlockHeader) error

ProcessBlockHeader is the main workhorse for handling insertion of new block headers into the block chain using headers-first semantics. It includes functionality such as rejecting headers that do not connect to an existing known header, ensuring headers follow all rules that do not depend on having all ancestor block data available, and insertion into the block index.

Block headers that have already been inserted are ignored, unless they have subsequently been marked invalid, in which case an appropriate error is returned.

It should be noted that this function intentionally does not accept block headers that do not connect to an existing known header or to headers which are already known to be a part of an invalid branch. This means headers must be processed in order.

This function is safe for concurrent access.

func (*BlockChain) PruneFromAccumulator

func (b *BlockChain) PruneFromAccumulator(leaves []wire.LeafData) error

PruneFromAccumulator uncaches the given hashes from the accumulator. No action is taken if the hashes are not already cached.

func (*BlockChain) ReconsiderBlock

func (b *BlockChain) ReconsiderBlock(hash *chainhash.Hash) error

ReconsiderBlock reconsiders the validity of the block with the given hash.

func (*BlockChain) ReconstructUData

func (b *BlockChain) ReconstructUData(ud *wire.UData, blockHash chainhash.Hash) ([]utreexo.Hash, error)

ReconstructUData is a wrapper around reconstructUData and provides a convenient function for udata reconstruction. NOTE: ReconstructUData will only work on udata for blocks that are part of the best chain. It will return an error when trying to reconstruct a udata for a block in a side chain.

This function is safe for concurrent access.

func (*BlockChain) SetNewBestStateFromAssumedUtreexoPoint

func (b *BlockChain) SetNewBestStateFromAssumedUtreexoPoint()

SetNewBestStateFromAssumedUtreexoPoint sets the best state for the node based on the current blockIndex and the assumed utreexo point. Also marks all the blocks in the blockIndex prior to the assumed utreexo point as valid.

func (*BlockChain) SetUtreexoStateFromAssumePoint

func (b *BlockChain) SetUtreexoStateFromAssumePoint()

SetUtreexoStateFromAssumePoint sets an initialized utreexoviewpoint from the assumedUtreexoPoint.

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.

func (*BlockChain) TstSetCoinbaseMaturity

func (b *BlockChain) TstSetCoinbaseMaturity(maturity uint16)

TstSetCoinbaseMaturity makes the ability to set the coinbase maturity available when running tests.

func (*BlockChain) VerifyUData

func (b *BlockChain) VerifyUData(ud *wire.UData, txIns []*wire.TxIn, remember bool) error

VerifyUData processes the given UData and then verifies that the proof validates with the underlying UtreexoViewpoint for the txIns that are given.

NOTE: the caller must not include any txIns for tx that isn't already included a block (ex: CPFP txs) as this will make the accumulator verification fail.

The passed in txIns must be in the same order they appear in the transaction. A mixed up ordering will make the verification fail.

This function does not modify the underlying UtreexoViewpoint. This function is safe for concurrent access.

type BlockLocator

type BlockLocator []*chainhash.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 CachedLeavesBackEnd added in v0.2.0

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

CachedLeavesBackEnd implements the CachedLeavesInterface interface. The cache assumes that anything in the cache doesn't exist in the db and vise-versa.

func InitCachedLeavesBackEnd added in v0.2.0

func InitCachedLeavesBackEnd(db *leveldb.DB, maxMemoryUsage int64) (*CachedLeavesBackEnd, error)

InitCachedLeavesBackEnd returns a newly initialized CachedLeavesBackEnd which implements utreexo.CachedLeavesInterface.

func (*CachedLeavesBackEnd) Delete added in v0.2.0

func (m *CachedLeavesBackEnd) Delete(k utreexo.Hash)

Delete removes the given key from the underlying map. No-op if the key doesn't exist.

func (*CachedLeavesBackEnd) Flush added in v0.4.0

func (m *CachedLeavesBackEnd) Flush(ldbTx *leveldb.Transaction) error

Flush resets the cache and saves all the key values onto the database.

func (*CachedLeavesBackEnd) ForEach added in v0.2.0

func (m *CachedLeavesBackEnd) ForEach(fn func(utreexo.Hash, uint64) error) error

ForEach calls the given function for each of the elements in the underlying map.

func (*CachedLeavesBackEnd) Get added in v0.2.0

Get returns the data from the underlying cache or the database.

func (*CachedLeavesBackEnd) IsFlushNeeded added in v0.4.0

func (m *CachedLeavesBackEnd) IsFlushNeeded() bool

IsFlushNeeded returns true if the backend needs to be flushed.

func (*CachedLeavesBackEnd) Length added in v0.2.0

func (m *CachedLeavesBackEnd) Length() int

Length returns the amount of items in the underlying db and the cache.

func (*CachedLeavesBackEnd) Put added in v0.2.0

func (m *CachedLeavesBackEnd) Put(k utreexo.Hash, v uint64)

Put puts the given data to the underlying cache. If the cache is full, it evicts the earliest entries to make room.

func (*CachedLeavesBackEnd) UsageStats added in v0.4.0

func (m *CachedLeavesBackEnd) UsageStats() (int64, int64)

UsageStats returns the currently cached elements and the total amount the cache can hold.

type ChainTip

type ChainTip struct {
	// Height of the tip.
	Height int32

	// BlockHash hash of the tip.
	BlockHash chainhash.Hash

	// BranchLen is the amount of blocks connecting this tip with the best chain.
	// Returns 0 if the chain tip is a part of the best chain.
	BranchLen int32

	// Status is the validity status of the branch this tip is in.
	Status TipStatus
}

ChainTip represents the last block in a branch of the block tree.

type ChainTipProof

type ChainTipProof struct {
	ProvedAtHash *chainhash.Hash
	AccProof     *utreexo.Proof
	HashesProven []utreexo.Hash
}

ChainTipProof represents all the information that is needed to prove that a utxo exists in the chain tip with utreexo accumulator proof.

func (*ChainTipProof) DecodeString

func (ctp *ChainTipProof) DecodeString(proof string) error

DecodeString takes a string and decodes and deserializes the chain-tip proof from the string.

func (*ChainTipProof) Deserialize

func (ctp *ChainTipProof) Deserialize(r io.Reader) error

Deserialize decodes a chain-tip proof from the given reader.

func (*ChainTipProof) Serialize

func (ctp *ChainTipProof) Serialize(w io.Writer) error

Serialize encodes the chain-tip proof into the passed in writer.

func (*ChainTipProof) String

func (ctp *ChainTipProof) String() string

String returns a hex encoded string of the chain-tip proof.

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

	// The maximum size in bytes of the UTXO cache.
	//
	// This field is required.
	UtxoCacheMaxSize uint64

	// 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

	// AssumeUtreexoPoint holds the utreexo point in where the chain starts
	// syncing from.
	AssumeUtreexoPoint chaincfg.AssumeUtreexo

	// 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

	// 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

	// UtreexoView defines a utreexo accumulator state to be used to store
	// the UTXO set instead of a key-value store.
	//
	// This field can be nil as being a utreexo node is optional.
	UtreexoView *UtreexoViewpoint

	// Prune specifies the target database usage (in bytes) the database will target for with
	// block and spend journal files.  Prune at 0 specifies that no blocks will be deleted.
	Prune uint64
}

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

	// ErrBlockWeightTooHigh indicates that the block's computed weight
	// metric exceeds the maximum allowed value.
	ErrBlockWeightTooHigh

	// 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

	// ErrInvalidTime indicates the time in the passed block has a precision
	// that is more than one second.  The chain consensus rules require
	// timestamps to have a maximum precision of one second.
	ErrInvalidTime

	// ErrTimeTooOld indicates the time is either before the median time of
	// the last several blocks per the chain consensus rules or prior to the
	// most recent checkpoint.
	ErrTimeTooOld

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

	// ErrDifficultyTooLow indicates the difficulty for the block is lower
	// than the difficulty required by the most recent checkpoint.
	ErrDifficultyTooLow

	// ErrUnexpectedDifficulty indicates specified bits do not align with
	// the expected value either because it doesn't match the calculated
	// valued based on difficulty regarted rules or it is out of the valid
	// range.
	ErrUnexpectedDifficulty

	// ErrHighHash indicates the block does not hash to a value which is
	// lower than the required target difficultly.
	ErrHighHash

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

	// 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

	// ErrNoTxOutputs indicates a transaction does not have any outputs.  A
	// valid transaction must have at least one output.
	ErrNoTxOutputs

	// 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

	// 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

	// ErrOverwriteTx indicates a block contains a transaction that has
	// the same hash as a previous transaction which has not been fully
	// spent.
	ErrOverwriteTx

	// 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

	// 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

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

	// 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

	// 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

	// ErrUnexpectedWitness indicates that a block includes transactions
	// with witness data, but doesn't also have a witness commitment within
	// the coinbase transaction.
	ErrUnexpectedWitness

	// ErrInvalidWitnessCommitment indicates that a block's witness
	// commitment is not well formed.
	ErrInvalidWitnessCommitment

	// ErrWitnessCommitmentMismatch indicates that the witness commitment
	// included in the block's coinbase transaction doesn't match the
	// manually computed witness commitment.
	ErrWitnessCommitmentMismatch

	// 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

	// ErrKnownInvalidBlock indicates that this block has previously failed
	// validation.
	ErrKnownInvalidBlock

	// ErrMissingParent indicates that the block was an orphan.
	ErrMissingParent
)

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 ExcludedUtxo

type ExcludedUtxo struct {
	// Height is where this utxo was created.
	Height int32

	// Outpoint represents the utxo txid:vout.
	Outpoint wire.OutPoint
}

ExcludedUtxo is the utxo that was excluded because it was spent and created within a given block interval. It includes the creation height and the outpoint of the utxo.

func BlockToDelLeaves

func BlockToDelLeaves(stxos []SpentTxOut, chain *BlockChain, block *btcutil.Block,
	inskip []uint32, excludeAfter int32) (delLeaves []wire.LeafData, excluded []ExcludedUtxo, err error)

BlockToDelLeaves takes a non-utreexo block and stxos and turns the block into leaves that are to be deleted.

inskip and excludeAfter are optional arguments. inskip will skip indexes of the txIns that match with the ones included in the slice. For example, if [0, 3, 11] is given as the inskip list, then txIns that appear in the 0th, 3rd, and 11th in the block will be skipped over.

excludeAfter will exclude all txIns that were created after a certain block height. For example, 1000 as the excludeAfter value will skip the generation of leaf datas for txIns that reference utxos created on and after the height 1000.

NOTE To opt out of the optional arguments inskip and excludeAfter, just pass nil for inskip and -1 for excludeAfter.

type FlushMode

type FlushMode uint8

FlushMode is used to indicate the different urgency types for a flush.

const (
	// FlushRequired is the flush mode that means a flush must be performed
	// regardless of the cache state.  For example right before shutting down.
	FlushRequired FlushMode = iota

	// FlushPeriodic is the flush mode that means a flush can be performed
	// when it would be almost needed.  This is used to periodically signal when
	// no I/O heavy operations are expected soon, so there is time to flush.
	FlushPeriodic

	// FlushIfNeeded is the flush mode that means a flush must be performed only
	// if the cache is exceeding a safety threshold very close to its maximum
	// size.  This is used mostly internally in between operations that can
	// increase the cache size.
	FlushIfNeeded
)

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, *btcutil.Block, []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, *btcutil.Block, []SpentTxOut) error

	// PruneBlock is invoked when an older block is deleted after it's been
	// processed. This lowers the storage requirement for a node.
	PruneBlocks(database.Tx, int32, func(int32) (*chainhash.Hash, error)) error

	// Flush flushes the relevant indexes if they need to be flushed.
	Flush(*chainhash.Hash, FlushMode, bool) 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 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() time.Time

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

	// 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 NodesBackEnd added in v0.2.0

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

NodesBackEnd implements the NodesInterface interface.

func InitNodesBackEnd added in v0.2.0

func InitNodesBackEnd(db *leveldb.DB, maxTotalMemoryUsage int64) (*NodesBackEnd, error)

InitNodesBackEnd returns a newly initialized NodesBackEnd which implements utreexo.NodesInterface.

func (*NodesBackEnd) Delete added in v0.2.0

func (m *NodesBackEnd) Delete(k uint64)

Delete removes the given key from the underlying map. No-op if the key doesn't exist.

func (*NodesBackEnd) Flush added in v0.4.0

func (m *NodesBackEnd) Flush(ldbTx *leveldb.Transaction) error

flush saves all the cached entries to disk and resets the cache map.

func (*NodesBackEnd) ForEach added in v0.2.0

func (m *NodesBackEnd) ForEach(fn func(uint64, utreexo.Leaf) error) error

ForEach calls the given function for each of the elements in the underlying map.

func (*NodesBackEnd) Get added in v0.2.0

func (m *NodesBackEnd) Get(k uint64) (utreexo.Leaf, bool)

Get returns the leaf from the underlying map.

func (*NodesBackEnd) IsFlushNeeded added in v0.4.0

func (m *NodesBackEnd) IsFlushNeeded() bool

IsFlushNeeded returns true if the backend needs to be flushed.

func (*NodesBackEnd) Length added in v0.2.0

func (m *NodesBackEnd) Length() int

Length returns the amount of items in the underlying database.

func (*NodesBackEnd) Put added in v0.2.0

func (m *NodesBackEnd) Put(k uint64, v utreexo.Leaf)

Put puts the given position and the leaf to the underlying map.

func (*NodesBackEnd) UsageStats added in v0.4.0

func (m *NodesBackEnd) UsageStats() (int64, int64)

UsageStats returns the currently cached elements and the total amount the cache can hold.

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: *btcutil.Block
  • NTBlockConnected: *btcutil.Block
  • NTBlockDisconnected: *btcutil.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 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 SpendableOut

type SpendableOut struct {
	PrevOut wire.OutPoint
	Amount  btcutil.Amount
}

SpendableOut represents a transaction output that is spendable along with additional metadata such as the block its in and how much it pays.

func AddBlock

func AddBlock(chain *BlockChain, prev *btcutil.Block, spends []*SpendableOut) (*btcutil.Block, []*SpendableOut, error)

AddBlock adds a block to the blockchain that succeeds prev. The blocks spends all the provided spendable outputs. The new block is returned, together with the new spendable outputs created in the block.

Panics on errors.

func MakeSpendableOutForTx

func MakeSpendableOutForTx(tx *wire.MsgTx, txOutIndex uint32) SpendableOut

MakeSpendableOutForTx returns a spendable output for the given transaction and transaction output index within the transaction.

func NewBlock

func NewBlock(chain *BlockChain, prev *btcutil.Block, spends []*SpendableOut) (*btcutil.Block, []*SpendableOut)

NewBlock creates a block to the blockchain that succeeds the prev block. The blocks spends all the provided spendable outputs. The new block is returned, together with the new spendable outputs created in the block.

Panics on errors.

type SpentTxOut

type SpentTxOut struct {
	// Amount is the amount of the output.
	Amount int64

	// PkScipt is the the public key script for the output.
	PkScript []byte

	// Height is the height of the the block containing the creating tx.
	Height int32

	// Denotes if the creating tx is a coinbase.
	IsCoinBase bool
}

SpentTxOut contains a spent transaction output and potentially additional contextual information such as whether or not it was contained in a coinbase transaction, the version of the transaction it was contained in, and which block height the containing transaction was included in. As described in the comments above, the additional contextual information will only be valid when this spent txout is spending the last unspent output of the containing transaction.

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.

type TipStatus

type TipStatus byte

TipStatus is the status of a chain tip.

const (
	// StatusUnknown indicates that the tip status isn't any of the defined
	// statuses.
	StatusUnknown TipStatus = iota

	// StatusActive indicates that the tip is considered active and is in
	// the best chain.
	StatusActive

	// StatusInvalid indicates that this tip or any of the ancestors of this
	// tip are invalid.
	StatusInvalid

	// StatusValidFork is given if:
	// 1: Not a part of the best chain.
	// 2: Is not invalid.
	// 3: Has the block data stored to disk.
	StatusValidFork
)

func (TipStatus) String

func (ts TipStatus) String() string

String returns the status flags as string.

type UtreexoViewpoint

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

UtreexoViewpoint is the compact state of the chainstate using the utreexo accumulator

func NewUtreexoViewpoint

func NewUtreexoViewpoint() *UtreexoViewpoint

NewUtreexoViewpoint returns an empty UtreexoViewpoint

func (*UtreexoViewpoint) AddProof

func (uview *UtreexoViewpoint) AddProof(delHashes []utreexo.Hash, accProof *utreexo.Proof) error

AddProof first checks that the utreexo proofs are valid. If it is valid, it readys the utreexo accumulator for additions/deletions by ingesting the proof.

func (*UtreexoViewpoint) CopyWithRoots

func (uview *UtreexoViewpoint) CopyWithRoots() *UtreexoViewpoint

CopyWithRoots returns a new utreexo viewpoint with just the roots copied.

func (*UtreexoViewpoint) Equal

func (uview *UtreexoViewpoint) Equal(compRoots []*chainhash.Hash) bool

Equal compares the UtreexoViewpoint with the roots that were passed in. returns true if they are equal.

This function is NOT safe for concurrent access. Equal should not be called when the UtreexoViewpoint is being modified.

func (*UtreexoViewpoint) GetProofInterval

func (uview *UtreexoViewpoint) GetProofInterval() int32

GetProofInterval returns the proof interval of the current utreexo viewpoint.

func (*UtreexoViewpoint) GetRoots

func (uview *UtreexoViewpoint) GetRoots() []*chainhash.Hash

GetRoots returns the utreexo roots of the current UtreexoViewpoint.

This function is NOT safe for concurrent access. GetRoots should not be called when the UtreexoViewpoint is being modified.

func (*UtreexoViewpoint) Modify

func (uview *UtreexoViewpoint) Modify(ud *wire.UData,
	adds []utreexo.Leaf, dels []utreexo.Hash) (*utreexo.UpdateData, error)

Modify modifies the utreexo state by adding and deleting elements from the utreexo state. The deletions are marked by the accumulator proof in the utreexo data and the additions are the leaves passed in.

This function is NOT safe for concurrent access.

func (*UtreexoViewpoint) NumLeaves

func (uview *UtreexoViewpoint) NumLeaves() uint64

NumLeaves returns the total number of elements (aka leaves) in the accumulator.

func (*UtreexoViewpoint) ProcessUData

func (uview *UtreexoViewpoint) ProcessUData(block *btcutil.Block,
	bestChain *chainView, ud *wire.UData) error

ProcessUData checks that the accumulator proof and the utxo data included in the UData passes consensus and then it updates the underlying accumulator.

func (*UtreexoViewpoint) PruneAll

func (uview *UtreexoViewpoint) PruneAll()

PruneAll deletes all the cached leaves in the utreexo viewpoint, leaving only the roots of the accumulator.

func (*UtreexoViewpoint) SetProofInterval

func (uview *UtreexoViewpoint) SetProofInterval(proofInterval int32)

SetProofInterval sets the interval of the utreexo proofs to be received by the node. Ex: interval of 10 means that you receive a utreexo proof every 10 blocks.

func (*UtreexoViewpoint) ToString

func (uview *UtreexoViewpoint) ToString() string

ToString outputs a string of the underlying accumulator.

func (*UtreexoViewpoint) VerifyAccProof

func (uview *UtreexoViewpoint) VerifyAccProof(toProve []utreexo.Hash,
	proof *utreexo.Proof) error

VerifyAccProof verifies the given accumulator proof. Returns an error if the verification failed.

type UtxoEntry

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

UtxoEntry houses details about an individual transaction output in a utxo view such as whether or not it was contained in a coinbase tx, the height of the block that contains the tx, whether or not it is spent, its public key script, and how much it pays.

func NewUtxoEntry

func NewUtxoEntry(
	txOut *wire.TxOut, blockHeight int32, isCoinbase bool) *UtxoEntry

NewUtxoEntry returns a new UtxoEntry built from the arguments.

func (*UtxoEntry) Amount

func (entry *UtxoEntry) Amount() int64

Amount returns the amount of the output.

func (*UtxoEntry) BlockHeight

func (entry *UtxoEntry) BlockHeight() int32

BlockHeight returns the height of the block containing the output.

func (*UtxoEntry) Clone

func (entry *UtxoEntry) Clone() *UtxoEntry

Clone returns a shallow copy of the utxo entry.

func (*UtxoEntry) IsCoinBase

func (entry *UtxoEntry) IsCoinBase() bool

IsCoinBase returns whether or not the output was contained in a coinbase transaction.

func (*UtxoEntry) IsSpent

func (entry *UtxoEntry) IsSpent() bool

IsSpent returns whether or not the output has been spent based upon the current state of the unspent transaction output view it was obtained from.

func (*UtxoEntry) PkScript

func (entry *UtxoEntry) PkScript() []byte

PkScript returns the public key script for the output.

func (*UtxoEntry) Spend

func (entry *UtxoEntry) Spend()

Spend marks the output as spent. Spending an output that is already spent has no effect.

type UtxoViewpoint

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

UtxoViewpoint represents a view into the set of unspent transaction outputs from a specific point of view in the chain. For example, it could be for the end of the main chain, some point in the history of the main chain, or down a side chain.

The unspent outputs are needed by other transactions for things such as script validation and double spend prevention.

func NewUtxoViewpoint

func NewUtxoViewpoint() *UtxoViewpoint

NewUtxoViewpoint returns a new empty unspent transaction output view.

func (*UtxoViewpoint) AddTxOut

func (view *UtxoViewpoint) AddTxOut(tx *btcutil.Tx, txOutIdx uint32, blockHeight int32)

AddTxOut adds the specified output of the passed transaction to the view if it exists and is not provably unspendable. When the view already has an entry for the output, it will be marked unspent. All fields will be updated for existing entries since it's possible it has changed during a reorg.

func (*UtxoViewpoint) AddTxOuts

func (view *UtxoViewpoint) AddTxOuts(tx *btcutil.Tx, blockHeight int32)

AddTxOuts adds all outputs in the passed transaction which are not provably unspendable to the view. When the view already has entries for any of the outputs, they are simply marked unspent. All fields will be updated for existing entries since it's possible it has changed during a reorg.

func (*UtxoViewpoint) BestHash

func (view *UtxoViewpoint) BestHash() *chainhash.Hash

BestHash returns the hash of the best block in the chain the view currently respresents.

func (*UtxoViewpoint) BlockToUtxoView

func (view *UtxoViewpoint) BlockToUtxoView(block *btcutil.Block) error

UBlockToUtxoView converts the UData from a block into a UtxoViewpoint. This function essentially mimics that of addInputUtxos as the UtxoViewpoint will include all the utxos necessary to validate the given bitcoin block.

NOTE: this function is only relevant when the utreexo accumulators are enabled.

func (*UtxoViewpoint) Entries

func (view *UtxoViewpoint) Entries() map[wire.OutPoint]*UtxoEntry

Entries returns the underlying map that stores of all the utxo entries.

func (*UtxoViewpoint) FetchPrevOutput

func (view *UtxoViewpoint) FetchPrevOutput(op wire.OutPoint) *wire.TxOut

FetchPrevOutput fetches the previous output referenced by the passed outpoint. This is identical to the LookupEntry method, but it returns a wire.TxOut instead.

NOTE: This is an implementation of the txscript.PrevOutputFetcher interface.

func (*UtxoViewpoint) LookupEntry

func (view *UtxoViewpoint) LookupEntry(outpoint wire.OutPoint) *UtxoEntry

LookupEntry returns information about a given transaction output according to the current state of the view. It will return nil if the passed output does not exist in the view or is otherwise not available such as when it has been disconnected during a reorg.

func (*UtxoViewpoint) RemoveEntry

func (view *UtxoViewpoint) RemoveEntry(outpoint wire.OutPoint)

RemoveEntry removes the given transaction output from the current state of the view. It will have no effect if the passed output does not exist in the view.

func (*UtxoViewpoint) SetBestHash

func (view *UtxoViewpoint) SetBestHash(hash *chainhash.Hash)

SetBestHash sets the hash of the best block in the chain the view currently respresents.

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

Jump to

Keyboard shortcuts

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