blockchain

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2021 License: ISC Imports: 25 Imported by: 0

Documentation

Overview

Copyright (c) 2020-2021 The bitcoinpay developers

Copyright (c) 2020-2021 The bitcoinpay developers

Index

Constants

View Source
const (

	// MaxTimeOffsetSeconds is the maximum number of seconds a block time
	// is allowed to be ahead of the current time.
	// 2 hours -> BTC settings (2 hours / 2016 block -> 2 weeks) = 0.6 %
	// 360 sec -> Bitcoinpay settings ( 30*2016*6/1000 )
	MaxTimeOffsetSeconds = 6 * 60 // 6 minutes

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

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

	// MaxOrphanTimeOffsetSeconds is the maximum number of seconds a orphan block time
	// is allowed to be ahead of the current time.  This is currently 10
	// minute.
	MaxOrphanTimeOffsetSeconds = 10 * 60
)
View Source
const (
	// The index of coinbase output for tax
	CoinbaseOutput_tax = 1

	// The index of coinbase output for custom data. (Can be used for future expansion)
	CoinbaseOutput_data = 2
)
View Source
const CheckpointConfirmations = 4096

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 (

	// maxOrphanBlocks is the maximum number of orphan blocks that can be
	// queued.
	MaxOrphanBlocks = 500
)
View Source
const (
	MaxOrphanStallDuration = 10 * time.Minute
)
View Source
const (
	// MaxSigOpsPerBlock is the maximum number of signature operations
	// allowed for a block.  This really should be based upon the max
	// allowed block size for a network and any votes that might change it,
	// however, since it was not updated to be based upon it before
	// release, it will require a hard fork and associated vote agenda to
	// change it.  The original max block size for the protocol was 1MiB,
	// so that is what this is based on.
	MaxSigOpsPerBlock = 1000000 / 200
)
View Source
const SpentTxOutTxInIndexSize = 4

The bytes of TxInIndex

View Source
const SpentTxOutTxIndexSize = 4

The bytes of TxIndex

Variables

This section is empty.

Functions

func CalcBlockTaxSubsidy

func CalcBlockTaxSubsidy(subsidyCache *SubsidyCache, blocks int64, params *params.Params) uint64

CalcBlockTaxSubsidy calculates the subsidy for the organization address in the coinbase.

func CalcBlockWorkSubsidy

func CalcBlockWorkSubsidy(subsidyCache *SubsidyCache, blocks int64, params *params.Params) uint64

CalcBlockWorkSubsidy calculates the proof of work subsidy for a block as a proportion of the total subsidy. (aka, the coinbase subsidy)

func CheckTransactionSanity

func CheckTransactionSanity(tx *types.Transaction, params *params.Params) error

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

func CountP2SHSigOps

func CountP2SHSigOps(tx *types.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 *types.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 DBFetchBlockByOrder

func DBFetchBlockByOrder(dbTx database.Tx, order uint64) (*types.SerializedBlock, error)

DBFetchBlockByOrder is the exported version of dbFetchBlockByOrder.

func ExtractCoinbaseHeight

func ExtractCoinbaseHeight(coinbaseTx *types.Transaction) (uint64, error)

func GetMaxLayerFromList

func GetMaxLayerFromList(list []*blockNode) uint

func IsExpired

func IsExpired(tx *types.Tx, blockHeight uint64) bool

IsExpired returns where or not the passed transaction is expired according to the given block height.

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

func IsExpiredTx

func IsExpiredTx(tx *types.Transaction, blockHeight uint64) bool

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

func IsFinalizedTransaction

func IsFinalizedTransaction(tx *types.Tx, blockHeight uint64, blockTime time.Time) bool

IsFinalizedTransaction determines whether or not a transaction is finalized.

func LockTimeToSequence

func LockTimeToSequence(isSeconds bool, lockTime uint32) (uint32, error)

LockTimeToSequence converts the passed relative lock time to a sequence number in accordance with DCP0003.

A sequence number is defined as follows:

  • bit 31 is the disable bit

  • the next 8 bits are reserved

  • bit 22 is the relative lock type (unset = block height, set = seconds)

  • the next 6 bites are reserved

  • the least significant 16 bits represent the value

  • value has a granularity of 512 when interpreted as seconds (bit 22 set)

    --------------------------------------------------- | Disable | Reserved | Type | Reserved | Value | --------------------------------------------------- | 1 bit | 8 bits | 1 bit | 6 bits | 16 bits | --------------------------------------------------- | [31] | [30-23] | [22] | [21-16] | [15-0] | ---------------------------------------------------

The above implies that the maximum relative block height that can be encoded is 65535 and the maximum relative number of seconds that can be encoded is 65535*512 = 33,553,920 seconds (~1.06 years). It also means that seconds are truncated to the nearest granularity towards 0 (e.g. 536 seconds will end up round tripping as 512 seconds and 1500 seconds will end up round tripping as 1024 seconds).

An error will be returned for values that are larger than can be represented.

func SequenceLockActive

func SequenceLockActive(lock *SequenceLock, blockHeight int64, medianTime time.Time) bool

SequenceLockActive determines if all of the inputs to a given transaction have achieved a relative age that surpasses the requirements specified by their respective sequence locks as calculated by CalcSequenceLock. A single sequence lock is sufficient because the calculated lock selects the minimum required time and block height from all of the non-disabled inputs after which the transaction can be included.

func UseLogger

func UseLogger(logger l.Logger)

UseLogger uses a specified Logger to output package logging info.

func ValidateTransactionScripts

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

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

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

	BFP2PAdd

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

type BestState

type BestState struct {
	Hash         hash.Hash            // The hash of the main chain tip.
	Bits         uint32               // The difficulty bits of the main chain tip.
	BlockSize    uint64               // The size of the main chain tip.
	NumTxns      uint64               // The number of txns in the main chain tip.
	MedianTime   time.Time            // Median time as per CalcPastMedianTime.
	TotalTxns    uint64               // The total number of txns in the chain.
	TotalSubsidy uint64               // The total subsidy for the chain.
	GraphState   *blockdag.GraphState // The graph state of dag
}

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 BlockAcceptedNotifyData

type BlockAcceptedNotifyData struct {
	// ForkLen is the length of the side chain the block extended or zero in the
	// case the block extended the main chain.
	//
	// This can be used in conjunction with the height of the accepted block to
	// determine the height at which the side chain the block created or
	// extended forked from the best chain.
	ForkLen int64

	// Block is the block that was accepted into the chain.
	Block *types.SerializedBlock

	Flags BehaviorFlags
}

BlockAcceptedNotifyData is the structure for data indicating information about an accepted block. Note that this does not necessarily mean the block that was accepted extended the best chain as it might have created or extended a side chain.

type BlockChain

type BlockChain struct {

	// block version
	BlockVersion uint32

	// Cache Invalid tx
	CacheInvalidTx bool
	// contains filtered or unexported fields
}

BlockChain provides functions such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, checkpoint handling, and best chain selection with reorganization.

func New

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

New returns a BlockChain instance using the provided configuration details.

func (*BlockChain) BestSnapshot

func (b *BlockChain) BestSnapshot() *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 *hash.Hash) (*types.SerializedBlock, error)

BlockByHash returns the block from the main chain with the given hash.

This function is safe for concurrent access.

func (*BlockChain) BlockByOrder

func (b *BlockChain) BlockByOrder(blockOrder uint64) (*types.SerializedBlock, error)

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

This function is safe for concurrent access.

func (*BlockChain) BlockDAG

func (b *BlockChain) BlockDAG() *blockdag.BlockDAG

Return the dag instance

func (*BlockChain) BlockHashByOrder

func (b *BlockChain) BlockHashByOrder(blockOrder uint64) (*hash.Hash, error)

BlockHashByOrder returns the hash of the block at the given order in the main chain.

This function is safe for concurrent access.

func (*BlockChain) BlockIndex

func (b *BlockChain) BlockIndex() *blockIndex

Return the blockindex instance

func (*BlockChain) BlockLocatorFromHash

func (b *BlockChain) BlockLocatorFromHash(hash *hash.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 DAG.

This function is safe for concurrent access.

func (*BlockChain) BlockOrderByHash

func (b *BlockChain) BlockOrderByHash(hash *hash.Hash) (uint64, error)

BlockOrderByHash returns the order of the block with the given hash in the chain.

This function is safe for concurrent access.

func (*BlockChain) CalcNextRequiredDiffFromNode

func (b *BlockChain) CalcNextRequiredDiffFromNode(hash *hash.Hash, timestamp time.Time, powType pow.PowType) (uint32, error)

CalcNextRequiredDiffFromNode calculates the required difficulty for the block given with the passed hash along with the given timestamp.

This function is NOT safe for concurrent access.

func (*BlockChain) CalcNextRequiredDifficulty

func (b *BlockChain) CalcNextRequiredDifficulty(timestamp time.Time, powType pow.PowType) (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 *types.Tx, view *UtxoViewpoint) (*SequenceLock, error)

CalcSequenceLock computes the minimum block order and time after which the passed transaction can be included into a block while satisfying the relative lock times of all of its input sequence numbers. The passed view is used to obtain the past median time and block heights of the blocks in which the referenced outputs of the inputs to the transaction were included. The generated sequence lock can be used in conjunction with a block height and median time to determine if all inputs to the transaction have reached the required maturity allowing it to be included in a block.

NOTE: This will calculate the sequence locks regardless of the state of the agenda which conditionally activates it. This is acceptable for standard transactions, however, callers which are intending to perform any type of consensus checking must check the status of the agenda first.

This function is safe for concurrent access.

func (*BlockChain) CalcWeight

func (b *BlockChain) CalcWeight(blocks int64, blockhash *hash.Hash, state byte) int64

func (*BlockChain) CalculateDAGDuplicateTxs

func (b *BlockChain) CalculateDAGDuplicateTxs(block *types.SerializedBlock)

func (*BlockChain) CalculateFees

func (b *BlockChain) CalculateFees(block *types.SerializedBlock) int64

func (*BlockChain) ChainLock

func (b *BlockChain) ChainLock()

func (*BlockChain) ChainRLock

func (b *BlockChain) ChainRLock()

func (*BlockChain) ChainRUnlock

func (b *BlockChain) ChainRUnlock()

func (*BlockChain) ChainUnlock

func (b *BlockChain) ChainUnlock()

func (*BlockChain) CheckCacheInvalidTxConfig

func (b *BlockChain) CheckCacheInvalidTxConfig() error

func (*BlockChain) CheckConnectBlockTemplate

func (b *BlockChain) CheckConnectBlockTemplate(block *types.SerializedBlock) error

CheckConnectBlockTemplate fully validates that connecting the passed block to either the tip of the main chain or its parent 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 or its parent.

This function is safe for concurrent access.

func (*BlockChain) CheckTransactionInputs

func (b *BlockChain) CheckTransactionInputs(tx *types.Tx, utxoView *UtxoViewpoint) (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 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 (*BlockChain) Checkpoints

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

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

This function is safe for concurrent access.

func (*BlockChain) DisableCheckpoints

func (b *BlockChain) DisableCheckpoints(disable bool)

DisableCheckpoints provides a mechanism to disable validation against checkpoints which you DO NOT want to do in production. It is provided only for debug purposes.

This function is safe for concurrent access.

func (*BlockChain) DumpBlockChain

func (b *BlockChain) DumpBlockChain(dumpFile string, params *params.Params, order uint64) error

dumpBlockChain dumps a map of the blockchain blocks as serialized bytes.

func (*BlockChain) FastAcceptBlock

func (b *BlockChain) FastAcceptBlock(block *types.SerializedBlock) error

func (*BlockChain) FetchBlockByHash

func (b *BlockChain) FetchBlockByHash(hash *hash.Hash) (*types.SerializedBlock, error)

FetchBlockByHash searches the internal chain block stores and the database in an attempt to find the requested block.

This function differs from BlockByHash in that this one also returns blocks that are not part of the main chain (if they are known).

This function is safe for concurrent access.

func (*BlockChain) FetchSpendJournal

func (b *BlockChain) FetchSpendJournal(targetBlock *types.SerializedBlock) ([]SpentTxOut, error)

FetchSpendJournal can return the set of outputs spent for the target block.

func (*BlockChain) FetchSubsidyCache

func (b *BlockChain) FetchSubsidyCache() *SubsidyCache

FetchSubsidyCache returns the current subsidy cache from the blockchain.

This function is safe for concurrent access.

func (*BlockChain) FetchUtxoEntry

func (b *BlockChain) FetchUtxoEntry(outpoint types.TxOutPoint) (*UtxoEntry, error)

FetchUtxoEntry loads and returns the unspent transaction output entry for the passed hash from the point of view of the end of the main chain.

NOTE: Requesting a hash 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 fully spent transactions. 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 *types.Tx) (*UtxoViewpoint, error)

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

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

func (*BlockChain) GetCurrentPowDiff

func (b *BlockChain) GetCurrentPowDiff(curNode blockNode, powType pow.PowType) *big.Int

find block node by pow type

func (*BlockChain) GetFees

func (b *BlockChain) GetFees(h *hash.Hash) int64

GetFees

func (*BlockChain) GetMiningTips

func (b *BlockChain) GetMiningTips() []*hash.Hash

func (*BlockChain) GetOrphan

func (b *BlockChain) GetOrphan(hash *hash.Hash) *types.SerializedBlock

func (*BlockChain) GetOrphansParents

func (b *BlockChain) GetOrphansParents() []*hash.Hash

GetOrphansParents returns the parents for the provided hash from the map of orphan blocks.

func (*BlockChain) GetOrphansTotal

func (b *BlockChain) GetOrphansTotal() int

Get the total of all orphans

func (*BlockChain) GetRecentOrphanParents

func (b *BlockChain) GetRecentOrphanParents(h *hash.Hash) []*hash.Hash

GetOrphansParents returns the parents for the provided hash from the map of orphan blocks.

func (*BlockChain) GetRecentOrphansParents

func (b *BlockChain) GetRecentOrphansParents() []*hash.Hash

func (*BlockChain) HasCheckpoints

func (b *BlockChain) HasCheckpoints() bool

func (*BlockChain) HaveBlock

func (b *BlockChain) HaveBlock(hash *hash.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 *hash.Hash) (types.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 chain and any side chains.

This function is safe for concurrent access.

func (*BlockChain) IsCheckpointCandidate

func (b *BlockChain) IsCheckpointCandidate(preBlock, block blockdag.IBlock) (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) IsDuplicateTx

func (b *BlockChain) IsDuplicateTx(txid *hash.Hash, blockHash *hash.Hash) bool

func (*BlockChain) IsInvalidOut

func (bc *BlockChain) IsInvalidOut(entry *UtxoEntry) bool

func (*BlockChain) IsOrphan

func (b *BlockChain) IsOrphan(hash *hash.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) IsOrphanOK

func (b *BlockChain) IsOrphanOK(serializedHeight uint64) bool

func (*BlockChain) IsUnconnectedOrphan

func (b *BlockChain) IsUnconnectedOrphan(hash *hash.Hash) bool

Whether it is connected by all parents

func (*BlockChain) LatestBlockLocator

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

LatestBlockLocator returns a block locator for the latest DAG state.

This function is safe for concurrent access.

func (*BlockChain) LatestCheckpoint

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

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

This function is safe for concurrent access.

func (*BlockChain) MainChainHasBlock

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

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

This function is safe for concurrent access.

func (*BlockChain) ProcessBlock

func (b *BlockChain) ProcessBlock(block *types.SerializedBlock, flags BehaviorFlags) (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 the length of the fork the block extended. In the case it either exteneded the best chain or is now the tip of the best chain due to causing a reorganize, the fork length will be 0. The second return value indicates whether or not the block is an orphan, in which case the fork length will also be zero as expected, because it, by definition, does not connect ot the best chain.

This function is safe for concurrent access.

func (*BlockChain) RefreshOrphans

func (b *BlockChain) RefreshOrphans() error

func (*BlockChain) RemoveOrphanBlock

func (b *BlockChain) RemoveOrphanBlock(orphan *orphanBlock)

removeOrphanBlock removes the passed orphan block from the orphan pool and previous orphan index.

func (*BlockChain) TimeSource

func (b *BlockChain) TimeSource() MedianTimeSource

Return median time source

func (*BlockChain) TipGeneration

func (b *BlockChain) TipGeneration() ([]hash.Hash, error)

TipGeneration returns the entire generation of blocks stemming from the parent of the current tip.

The function is safe for concurrent access.

type BlockLocator

type BlockLocator []*hash.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 BlockNodeList

type BlockNodeList []*blockNode

BlockNodeList is used to sort blockNode

func (BlockNodeList) Len

func (bn BlockNodeList) Len() int

func (BlockNodeList) Less

func (bn BlockNodeList) Less(i, j int) bool

func (BlockNodeList) Swap

func (bn BlockNodeList) Swap(i, j int)

type BlockStatus

type BlockStatus byte

BlockStatus is a bit field representing the validation state of the block.

func (BlockStatus) HaveData

func (status BlockStatus) HaveData() bool

HaveData returns whether the full block data is stored in the database. This will return false for a block node where only the header is downloaded or stored.

func (BlockStatus) KnownInvalid

func (status BlockStatus) KnownInvalid() bool

KnownInvalid returns whether the block is known to be invalid. This will return false for invalid blocks that have not been proven invalid yet.

func (BlockStatus) KnownValid

func (status BlockStatus) KnownValid() bool

KnownValid returns whether the block is known to be valid. This will return false for a valid block that has not been fully validated yet.

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

	// 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 *params.Params

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

	// Notifications defines a callback to which notifications will be sent
	// when various events take place.  See the documentation for
	// Notification and NotificationType for details on the types and
	// contents of notifications.
	//
	// This field can be nil if the caller is not interested in receiving
	// notifications.
	Notifications NotificationCallback

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

	// Setting different dag types will use different consensus
	DAGType string

	// block version
	BlockVersion uint32

	// Cache Invalid tx
	CacheInvalidTx bool
}

Config is a descriptor which specifies the blockchain instance configuration.

type DeploymentError

type DeploymentError string

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

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

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

	// ErrWrongBlockSize indicates that the block size from the header was
	// not the actual serialized size of the block.
	ErrWrongBlockSize

	// 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
	// ErrNoParents indicates the block does not have a least one
	// parent.
	ErrNoParents

	// ErrDuplicateParent indicates the block does not have a least one
	// parent.
	ErrDuplicateParent

	// ErrTooManyTransactions indicates the block has more transactions than
	// are allowed.
	ErrTooManyTransactions

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

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

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

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

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

	// ErrCoinbaseHeight indicates that the encoded height in the coinbase
	// is incorrect.
	ErrCoinbaseHeight

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

	// ErrIrregTxInRegularTree indicates irregular transaction was found in
	// the regular transaction tree.
	ErrIrregTxInRegularTree

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

	// ErrBadCoinbaseOutpoint indicates that the outpoint used by a coinbase
	// as input was non-null.
	ErrBadCoinbaseOutpoint

	// ErrBadCoinbaseFraudProof indicates that the fraud proof for a coinbase
	// input was non-null.
	ErrBadCoinbaseFraudProof

	// ErrBadCoinbaseAmountIn indicates that the AmountIn (=subsidy) for a
	// coinbase input was incorrect.
	ErrBadCoinbaseAmountIn

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

	// ErrInvalidRevNum indicates that the number of revocations from the
	// header was not the same as the number of SSRtx included in the block.
	ErrRevocationsMismatch

	// ErrTooManyRevocations indicates more revocations were found in a block
	// than were allowed.
	ErrTooManyRevocations

	// ErrInvalidFinalState indicates that the final state of the PRNG included
	// in the the block differed from the calculated final state.
	ErrInvalidFinalState

	// ErrPoolSize indicates an error in the ticket pool size for this block.
	ErrPoolSize

	// ErrForceReorgWrongChain indicates that a reroganization was attempted
	// to be forced, but the chain indicated was not mirrored by b.bestChain.
	ErrForceReorgWrongChain

	// ErrForceReorgMissingChild indicates that a reroganization was attempted
	// to be forced, but the child node to reorganize to could not be found.
	ErrForceReorgMissingChild

	// ErrBadBlockHeight indicates that a block header's embedded block height
	// was different from where it was actually embedded in the block chain.
	ErrBadBlockHeight

	// ErrBlockOneTx indicates that block height 1 failed to correct generate
	// the block one premine transaction.
	ErrBlockOneTx

	// ErrBlockOneTx indicates that block height 1 coinbase transaction in
	// zero was incorrect in some way.
	ErrBlockOneInputs

	// ErrBlockOneOutputs indicates that block height 1 failed to incorporate
	// the ledger addresses correctly into the transaction's outputs.
	ErrBlockOneOutputs

	// ErrExpiredTx indicates that the transaction is currently expired.
	ErrExpiredTx

	// ErrExpiryTxSpentEarly indicates that an output from a transaction
	// that included an expiry field was spent before coinbase maturity
	// many blocks had passed in the blockchain.
	ErrExpiryTxSpentEarly

	// ErrFraudAmountIn indicates the witness amount given was fraudulent.
	ErrFraudAmountIn

	// ErrFraudBlockHeight indicates the witness block height given was fraudulent.
	ErrFraudBlockHeight

	// ErrFraudBlockIndex indicates the witness block index given was fraudulent.
	ErrFraudBlockIndex

	// ErrZeroValueOutputSpend indicates that a transaction attempted to spend a
	// zero value output.
	ErrZeroValueOutputSpend

	// ErrInvalidEarlyFinalState indicates that a block before stake validation
	// height had a non-zero final state.
	ErrInvalidEarlyFinalState

	// ErrParentsBlockUnknown indicates that the parents block is not known.
	ErrParentsBlockUnknown

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

	// ErrInvalidTemplateParent indicates that a block template builds on a
	// block that is either not the current best chain tip or its parent.
	ErrInvalidTemplateParent

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

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

	// ErrMissingCoinbaseHeight
	ErrMissingCoinbaseHeight

	//ErrBadCuckooNonces
	ErrBadCuckooNonces

	// ErrInValidPowType
	ErrInValidPowType

	// ErrInValidPow
	ErrInvalidPow

	// ErrNoBlueCoinbase indicates a transaction is attempting to spend a
	// coinbase that is not in blue set
	ErrNoBlueCoinbase

	// ErrNoViewpoint
	ErrNoViewpoint
)

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 HashError

type HashError string

HashError identifies an error that indicates a hash was specified that does not exist.

func (HashError) Error

func (e HashError) Error() string

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

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.
	ConnectBlock(tx database.Tx, block *types.SerializedBlock, stxos []SpentTxOut) error

	// DisconnectBlock is invoked when a block has been disconnected from
	// the main chain.
	DisconnectBlock(tx database.Tx, block *types.SerializedBlock, stxos []SpentTxOut) error

	// IsDuplicateTx
	IsDuplicateTx(tx database.Tx, txid *hash.Hash, blockHash *hash.Hash) bool
}

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 Notification

type Notification struct {
	Type NotificationType
	Data interface{}
}

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 (
	// BlockAccepted 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.
	BlockAccepted NotificationType = iota

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

	// BlockDisconnected indicates the associated block was disconnected
	// from the main chain.
	BlockDisconnected

	// Reorganization indicates that a blockchain reorganization is in
	// progress.
	Reorganization
)

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 ReorganizationNotifyData

type ReorganizationNotifyData struct {
	OldHash   hash.Hash
	OldHeight uint64
	NewHash   hash.Hash
	NewHeight uint64
}

ReorganizationNotifyData is the structure for data indicating information about a reorganization.

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 {
	BlockHeight int64
	Time        int64
}

SequenceLock represents the minimum timestamp and minimum block height after which a transaction can be included into a block while satisfying the relative lock times of all of its input sequence numbers. It is calculated via the CalcSequenceLock function. Each field may be -1 if none of the input sequence numbers require a specific relative lock time for the respective type. Since all valid heights and times are larger than -1, this implies that it will not prevent a transaction from being included due to the sequence lock, which is the desired behavior.

type SpentTxOut

type SpentTxOut struct {
	Amount     uint64 // The total amount of the output.
	PkScript   []byte // The public key script for the output.
	BlockHash  hash.Hash
	IsCoinBase bool   // Whether creating tx is a coinbase.
	TxIndex    uint32 // The index of tx in block.
	TxInIndex  uint32 // The index of TxInput in the tx.
	OriAmount  uint64 // The original amount of the output.
}

SpentTxOut contains a spent transaction output and potentially additional contextual information such as whether or not it was contained in a coinbase transaction, the txVersion 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.

The struct is aligned for memory efficiency.

func GetStxo

func GetStxo(txIndex uint32, txInIndex uint32, stxos []SpentTxOut) *SpentTxOut

type SubsidyCache

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

SubsidyCache is a structure that caches calculated values of subsidy so that they're not constantly recalculated. The blockchain struct itself possesses a pointer to a preinitialized SubsidyCache.

func NewSubsidyCache

func NewSubsidyCache(blocks int64, params *params.Params) *SubsidyCache

NewSubsidyCache initializes a new subsidy cache for a given blocks. It precalculates the values of the subsidy that are most likely to be seen by the client when it connects to the network.

func (*SubsidyCache) CalcBlockSubsidy

func (s *SubsidyCache) CalcBlockSubsidy(blocks int64) int64

CalcBlockSubsidy returns the subsidy amount a block at the provided blocks 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.

Subsidy calculation for exponential reductions: 0 for i in range (0, height / SubsidyReductionInterval): 1 subsidy *= MulSubsidy 2 subsidy /= DivSubsidy

Safe for concurrent access.

type UtxoEntry

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

utxoOutput houses details about an individual unspent transaction output such as whether or not it is spent, its public key script, and how much it pays.

Standard public key scripts are stored in the database using a compressed format. Since the vast majority of scripts are of the standard form, a fairly significant savings is achieved by discarding the portions of the standard scripts that can be reconstructed.

Also, since it is common for only a specific output in a given utxo entry to be referenced from a redeeming transaction, the script and amount for a given output is not uncompressed until the first time it is accessed. This provides a mechanism to avoid the overhead of needlessly uncompressing all outputs for a given utxo entry at the time of load.

The struct is aligned for memory efficiency.

func DeserializeUtxoEntry

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

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

func (*UtxoEntry) Amount

func (entry *UtxoEntry) Amount() uint64

Amount returns the amount of the output.

func (*UtxoEntry) BlockHash

func (entry *UtxoEntry) BlockHash() *hash.Hash

BlockHash returns the hash 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 *types.Tx, txOutIdx uint32, blockHash *hash.Hash)

func (*UtxoViewpoint) AddTxOuts

func (view *UtxoViewpoint) AddTxOuts(tx *types.Tx, blockHash *hash.Hash)

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

func (view *UtxoViewpoint) Clean()

func (*UtxoViewpoint) Entries

func (view *UtxoViewpoint) Entries() map[types.TxOutPoint]*UtxoEntry

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

func (*UtxoViewpoint) FetchInputUtxos

func (view *UtxoViewpoint) FetchInputUtxos(db database.DB, block *types.SerializedBlock, bc *BlockChain) error

func (*UtxoViewpoint) FilterInvalidOut

func (view *UtxoViewpoint) FilterInvalidOut(bc *BlockChain)

func (*UtxoViewpoint) LookupEntry

func (view *UtxoViewpoint) LookupEntry(outpoint types.TxOutPoint) *UtxoEntry

LookupEntry returns information about a given transaction according to the current state of the view. It will return nil if the passed transaction hash 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 types.TxOutPoint)

func (*UtxoViewpoint) SetViewpoints

func (view *UtxoViewpoint) SetViewpoints(views []*hash.Hash)

SetViewpoints sets the hash of the viewpoint block in the chain the view currently respresents.

func (*UtxoViewpoint) Viewpoints

func (view *UtxoViewpoint) Viewpoints() []*hash.Hash

Viewpoints returns the hash of the viewpoint block in the chain the view currently respresents.

Jump to

Keyboard shortcuts

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