Bitcoin
|
#include <amount.h>
#include <coins.h>
#include <crypto/common.h>
#include <fs.h>
#include <policy/feerate.h>
#include <protocol.h>
#include <script/script_error.h>
#include <sync.h>
#include <txmempool.h>
#include <versionbits.h>
#include <algorithm>
#include <atomic>
#include <exception>
#include <map>
#include <memory>
#include <set>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
Go to the source code of this file.
Classes | |
struct | BlockHasher |
class | CScriptCheck |
class | CVerifyDB |
struct | CBlockIndexWorkComparator |
class | BlockManager |
class | CChainState |
Typedefs | |
typedef std::unordered_map< uint256, CBlockIndex *, BlockHasher > | BlockMap |
Enumerations | |
enum | DisconnectResult { DISCONNECT_OK, DISCONNECT_UNCLEAN, DISCONNECT_FAILED } |
enum | FlushStateMode { FlushStateMode::NONE, FlushStateMode::IF_NEEDED, FlushStateMode::PERIODIC, FlushStateMode::ALWAYS } |
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap |
enum DisconnectResult |
|
strong |
Enumerator | |
---|---|
NONE | |
IF_NEEDED | |
PERIODIC | |
ALWAYS |
bool AcceptToMemoryPool | ( | CTxMemPool & | pool, |
CValidationState & | state, | ||
const CTransactionRef & | tx, | ||
bool * | pfMissingInputs, | ||
std::list< CTransactionRef > * | plTxnReplaced, | ||
bool | bypass_limits, | ||
const CAmount | nAbsurdFee, | ||
bool | test_accept = false |
||
) |
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions replaced from mempool
bool ActivateBestChain | ( | CValidationState & | state, |
const CChainParams & | chainparams, | ||
std::shared_ptr< const CBlock > | pblock = std::shared_ptr< const CBlock >() |
||
) |
Find the best known block, and make it the tip of the block chain
May not be called with cs_main held. May not be called in a validationinterface callback.
BlockMap& BlockIndex | ( | ) |
uint64_t CalculateCurrentUsage | ( | ) |
Calculate the amount of disk space the block & undo files currently use
BLOCK PRUNING CODE
CChain& ChainActive | ( | ) |
CChainState& ChainstateActive | ( | ) |
bool CheckBlock | ( | const CBlock & | block, |
CValidationState & | state, | ||
const Consensus::Params & | consensusParams, | ||
bool | fCheckPOW = true , |
||
bool | fCheckMerkleRoot = true |
||
) |
Functions for validating blocks and updating the block tree Context-independent validity checks
bool CheckFinalTx | ( | const CTransaction & | tx, |
int | flags = -1 |
||
) |
Transaction validation functions Check if transaction will be final in the next block to be created.
Calls IsFinalTx() with current block height and appropriate block time.
See consensus/consensus.h for flag definitions.
bool CheckSequenceLocks | ( | const CTxMemPool & | pool, |
const CTransaction & | tx, | ||
int | flags, | ||
LockPoints * | lp = nullptr , |
||
bool | useExistingLockPoints = false |
||
) |
Check if transaction will be BIP 68 final in the next block to be created.
Simulates calling SequenceLocks() with data from the tip of the current active chain. Optionally stores in LockPoints the resulting height and time calculated and the hash of the block needed for calculation or skips the calculation and uses the LockPoints passed in for evaluation. The LockPoints should not be considered valid if CheckSequenceLocks returns false.
See consensus/consensus.h for flag definitions.
int32_t ComputeBlockVersion | ( | const CBlockIndex * | pindexPrev, |
const Consensus::Params & | params | ||
) |
Determine what nVersion a new block should use.
bool DumpMempool | ( | const CTxMemPool & | pool | ) |
Dump the mempool to disk.
CBlockIndex* FindForkInGlobalIndex | ( | const CChain & | chain, |
const CBlockLocator & | locator | ||
) |
Find the last common block between the parameter chain and a locator.
std::vector<unsigned char> GenerateCoinbaseCommitment | ( | CBlock & | block, |
const CBlockIndex * | pindexPrev, | ||
const Consensus::Params & | consensusParams | ||
) |
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks).
CBlockFileInfo* GetBlockFileInfo | ( | size_t | n | ) |
Get block file info entry for one block file
fs::path GetBlockPosFilename | ( | const FlatFilePos & | pos | ) |
Translation to a filesystem path
CAmount GetBlockSubsidy | ( | int | nHeight, |
const Consensus::Params & | consensusParams | ||
) |
int GetSpendHeight | ( | const CCoinsViewCache & | inputs | ) |
Return the spend height, which is one more than the inputs.GetBestBlock(). While checking, GetBestBlock() refers to the parent block. (protected by cs_main) This is also true for mempool checks.
bool GetTransaction | ( | const uint256 & | hash, |
CTransactionRef & | txOut, | ||
const Consensus::Params & | consensusParams, | ||
uint256 & | hashBlock, | ||
const CBlockIndex *const | block_index | ||
) |
Retrieve a transaction (from memory pool, or from disk, if possible)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock. If blockIndex is provided, the transaction is fetched from the corresponding block.
double GuessVerificationProgress | ( | const ChainTxData & | data, |
const CBlockIndex * | pindex | ||
) |
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
Guess how far we are in the verification process at the given block index require cs_main if pindex has not been validated yet (because nChainTx might be unset)
void InitScriptExecutionCache | ( | ) |
Initializes the script-execution cache
bool InvalidateBlock | ( | CValidationState & | state, |
const CChainParams & | chainparams, | ||
CBlockIndex * | pindex | ||
) |
Mark a block as invalid.
|
inline |
Check whether the block associated with this index entry is pruned or not.
bool IsNullDummyEnabled | ( | const CBlockIndex * | pindexPrev, |
const Consensus::Params & | params | ||
) |
Check whether NULLDUMMY (BIP 147) has activated.
bool IsWitnessEnabled | ( | const CBlockIndex * | pindexPrev, |
const Consensus::Params & | params | ||
) |
Check whether witness commitments are required for block.
bool LoadBlockIndex | ( | const CChainParams & | chainparams | ) |
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
bool LoadChainTip | ( | const CChainParams & | chainparams | ) |
Update the chain tip based on database information.
bool LoadExternalBlockFile | ( | const CChainParams & | chainparams, |
FILE * | fileIn, | ||
FlatFilePos * | dbp = nullptr |
||
) |
Import blocks from an external file
bool LoadGenesisBlock | ( | const CChainParams & | chainparams | ) |
Ensures we have a genesis block in the block tree, possibly writing one to disk.
bool LoadMempool | ( | CTxMemPool & | pool | ) |
Load the mempool from disk.
CBlockIndex* LookupBlockIndex | ( | const uint256 & | hash | ) |
FILE* OpenBlockFile | ( | const FlatFilePos & | pos, |
bool | fReadOnly = false |
||
) |
Open a block file (blk?????.dat)
bool PreciousBlock | ( | CValidationState & | state, |
const CChainParams & | params, | ||
CBlockIndex * | pindex | ||
) |
Mark a block as precious and reorganize.
May not be called in a validationinterface callback.
bool ProcessNewBlock | ( | const CChainParams & | chainparams, |
const std::shared_ptr< const CBlock > | pblock, | ||
bool | fForceProcessing, | ||
bool * | fNewBlock | ||
) |
Process an incoming block. This only returns after the best known valid block is made active. Note that it does not, however, guarantee that the specific block passed to it has been checked for validity!
If you want to possibly get feedback on whether pblock is valid, you must install a CValidationInterface (see validationinterface.h) - this will have its BlockChecked method called whenever any block completes validation.
Note that we guarantee that either the proof-of-work is valid on pblock, or (and possibly also) BlockChecked will have been called.
May not be called in a validationinterface callback.
[in] | pblock | The block we want to process. |
[in] | fForceProcessing | Process this block even if unrequested; used for non-network block sources and whitelisted peers. |
[out] | fNewBlock | A boolean which is set to indicate if the block was first received via this call |
bool ProcessNewBlockHeaders | ( | const std::vector< CBlockHeader > & | block, |
CValidationState & | state, | ||
const CChainParams & | chainparams, | ||
const CBlockIndex ** | ppindex = nullptr , |
||
CBlockHeader * | first_invalid = nullptr |
||
) |
Process incoming block headers.
May not be called in a validationinterface callback.
[in] | block | The block headers themselves |
[out] | state | This may be set to an Error state if any error occurred processing them |
[in] | chainparams | The params for the chain we want to connect to |
[out] | ppindex | If set, the pointer will be set to point to the last new block index object for the given headers |
[out] | first_invalid | First header that fails validation, if one exists |
void PruneBlockFilesManual | ( | int | nManualPruneHeight | ) |
Prune block files up to a given height
void PruneOneBlockFile | ( | const int | fileNumber | ) |
Mark one block file as pruned.
bool ReadBlockFromDisk | ( | CBlock & | block, |
const FlatFilePos & | pos, | ||
const Consensus::Params & | consensusParams | ||
) |
Functions for disk access for blocks
bool ReadBlockFromDisk | ( | CBlock & | block, |
const CBlockIndex * | pindex, | ||
const Consensus::Params & | consensusParams | ||
) |
bool ReadRawBlockFromDisk | ( | std::vector< uint8_t > & | block, |
const FlatFilePos & | pos, | ||
const CMessageHeader::MessageStartChars & | message_start | ||
) |
bool ReadRawBlockFromDisk | ( | std::vector< uint8_t > & | block, |
const CBlockIndex * | pindex, | ||
const CMessageHeader::MessageStartChars & | message_start | ||
) |
bool ReplayBlocks | ( | const CChainParams & | params, |
CCoinsView * | view | ||
) |
Replay blocks that aren't fully applied to the database.
void ResetBlockFailureFlags | ( | CBlockIndex * | pindex | ) |
Remove invalidity status from a block and its descendants.
bool RewindBlockIndex | ( | const CChainParams & | params | ) |
When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index
bool TestBlockValidity | ( | CValidationState & | state, |
const CChainParams & | chainparams, | ||
const CBlock & | block, | ||
CBlockIndex * | pindexPrev, | ||
bool | fCheckPOW = true , |
||
bool | fCheckMerkleRoot = true |
||
) |
Check a block is completely valid from start to finish (only works on top of our current best block)
bool TestLockPointValidity | ( | const LockPoints * | lp | ) |
Test whether the LockPoints height and time are still valid on the current chain
void ThreadScriptCheck | ( | int | worker_num | ) |
Run an instance of the script checking thread
bool UndoReadFromDisk | ( | CBlockUndo & | blockundo, |
const CBlockIndex * | pindex | ||
) |
void UnlinkPrunedFiles | ( | const std::set< int > & | setFilesToPrune | ) |
Actually unlink the specified files
void UnloadBlockIndex | ( | ) |
Unload database information
void UpdateCoins | ( | const CTransaction & | tx, |
CCoinsViewCache & | inputs, | ||
int | nHeight | ||
) |
Apply the effects of this transaction on the UTXO set represented by view
void UpdateUncommittedBlockStructures | ( | CBlock & | block, |
const CBlockIndex * | pindexPrev, | ||
const Consensus::Params & | consensusParams | ||
) |
Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks.
ThresholdState VersionBitsTipState | ( | const Consensus::Params & | params, |
Consensus::DeploymentPos | pos | ||
) |
Get the BIP9 state for a given deployment at the current tip.
int VersionBitsTipStateSinceHeight | ( | const Consensus::Params & | params, |
Consensus::DeploymentPos | pos | ||
) |
Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip.
BIP9Stats VersionBitsTipStatistics | ( | const Consensus::Params & | params, |
Consensus::DeploymentPos | pos | ||
) |
Get the numerical statistics for the BIP9 state for a given deployment at the current tip.
|
static |
Block download timeout base, expressed in millionths of the block interval (i.e. 10 min)
|
static |
Additional block download timeout per parallel downloading peer (i.e. 5 min)
|
static |
Size of the "block download window": how far ahead of our current height do we fetch? Larger windows tolerate larger download speed differences between peer, but increase the potential degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably want to make this a per-peer adaptive value at some point.
|
static |
Timeout in seconds during which a peer must stall block download progress before being disconnected.
|
static |
The pre-allocation chunk size for blk?????.dat files (since 0.8)
CScript COINBASE_FLAGS |
Constant stuff for coinbase transactions we create:
CCriticalSection cs_main |
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
This may also need to be locked when updating the transaction pool, e.g. on AcceptToMemoryPool. See CTxMemPool::cs comment for details.
The transaction pool has a separate lock to allow reading from it and the chainstate at the same time.
|
static |
Time to wait (in seconds) between flushing chainstate to disk.
|
static |
Time to wait (in seconds) between writing blocks/block index to disk.
|
static |
Default for -limitancestorcount, max number of in-mempool ancestors
|
static |
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
Default for -limitdescendantcount, max number of in-mempool descendants
|
static |
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants
|
static |
Default for using fee filter
|
static |
|
static |
Default for -mempoolexpiry, expiration time for mempool transactions in hours
|
static |
Default for -minrelaytxfee, minimum relay fee for transactions
|
static |
|
static |
Default for -persistmempool
|
static |
-par default (number of script-checking threads, 0 = auto)
|
static |
Default for -stopatheight
|
static |
|
static |
Default for -whitelistforcerelay.
|
static |
Default for -whitelistrelay.
bool fCheckBlockIndex |
bool fCheckpointsEnabled |
CBlockPolicyEstimator feeEstimator |
bool fHavePruned |
Pruning-related variables and constants True if any block files have ever been pruned.
std::atomic_bool fImporting |
bool fPruneMode |
True if we're running in -prune mode.
std::atomic_bool fReindex |
bool fRequireStandard |
uint256 g_best_block |
std::condition_variable g_best_block_cv |
Mutex g_best_block_mutex |
uint256 hashAssumeValid |
Block hash whose ancestors we will assume to have valid scripts without checking them.
|
static |
The maximum size of a blk?????.dat file (since 0.8)
|
static |
Number of blocks that can be requested at any given time from a single peer.
|
static |
Maximum number of headers to announce when relaying blocks with headers message.
|
static |
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
|
static |
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested. For older blocks, a regular BLOCK response will be sent.
|
static |
Maximum kilobytes for transactions to store for processing during reorg
|
static |
Maximum age of our tip in seconds for us to be considered current for fee estimation
|
static |
Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends less than this number, we reached its tip. Changing this value is a protocol upgrade.
|
static |
Maximum length of reject messages.
|
static |
Maximum number of script-checking threads allowed
|
static |
Maximum number of unconnecting headers announcements before DoS score
CTxMemPool mempool |
|
static |
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pruned.
|
static |
CFeeRate minRelayTxFee |
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
size_t nCoinCacheUsage |
int64_t nMaxTipAge |
If the tip is older than this (in seconds), the node is considered to be in initial block download.
arith_uint256 nMinimumChainWork |
Minimum work we will assume exists on some valid chain.
|
static |
Minimum blocks required to signal NODE_NETWORK_LIMITED
uint64_t nPruneTarget |
Number of MiB of block files that we're trying to stay below.
int nScriptCheckThreads |
std::unique_ptr<CBlockTreeDB> pblocktree |
Global variable that points to the active block tree (protected by cs_main)
std::unique_ptr<CCoinsViewDB> pcoinsdbview |
Global variable that points to the coins database (protected by cs_main)
std::unique_ptr<CCoinsViewCache> pcoinsTip |
Global variable that points to the active CCoinsView (protected by cs_main)
CBlockIndex* pindexBestHeader |
Best header we've seen so far (used for getheaders queries' starting points).
|
static |
Too high fee. Can not be triggered by P2P transactions
|
static |
Reject codes greater or equal to this can be returned by AcceptToMemPool for transactions, to signal internal conditions. They cannot and should not be sent over the P2P network.
|
static |
The pre-allocation chunk size for rev?????.dat files (since 0.8)
VersionBitsCache versionbitscache |