6 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
9 #if defined(HAVE_CONFIG_H)
10 #include "config/bitcoin-config.h"
32 #include <boost/unordered_map.hpp>
33 #include <boost/filesystem/path.hpp>
51 static const bool DEFAULT_ALERTS =
true;
53 static const bool DEFAULT_WHITELISTRELAY =
true;
55 static const bool DEFAULT_WHITELISTFORCERELAY =
true;
57 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = COIN;
59 static const CAmount DEFAULT_TRANSACTION_MAXFEE = 400 * COIN;
61 static const CAmount HIGH_TX_FEE_PER_KB = 25 * COIN;
63 static const CAmount HIGH_MAX_TX_FEE = 10 * HIGH_TX_FEE_PER_KB;
65 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
67 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
69 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
71 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
73 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 24;
75 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000;
77 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000;
79 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000;
82 static const int MAX_SCRIPTCHECK_THREADS = 16;
84 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
86 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
88 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
91 static const unsigned int MAX_HEADERS_RESULTS = 2000;
94 static const int MAX_CMPCTBLOCK_DEPTH = 5;
96 static const int MAX_BLOCKTXN_DEPTH = 10;
101 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
103 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
105 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
107 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
109 static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 24 * 60;
111 static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
114 static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5;
117 static const unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_INTERVAL;
119 static const unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
121 static const unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
123 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 5000000;
125 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 2500000;
127 static const unsigned int DEFAULT_LIMITFREERELAY = 0;
128 static const bool DEFAULT_RELAYPRIORITY =
true;
129 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
131 static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
134 static const bool DEFAULT_PERMIT_BAREMULTISIG =
true;
135 static const bool DEFAULT_CHECKPOINTS_ENABLED =
true;
136 static const bool DEFAULT_TXINDEX =
false;
137 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
140 static const bool DEFAULT_ENABLE_REPLACEMENT =
true;
142 static const bool DEFAULT_FEEFILTER =
true;
145 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
148 static const int MAX_UNCONNECTING_HEADERS = 10;
150 static const bool DEFAULT_PEERBLOOMFILTERS =
true;
160 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher>
BlockMap;
193 static const uint64_t nMinDiskSpace = 52428800;
203 static const unsigned int MIN_BLOCKS_TO_KEEP = 1440;
205 static const signed int DEFAULT_CHECKBLOCKS = 6;
206 static const unsigned int DEFAULT_CHECKLEVEL = 3;
216 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 2200ULL * 1024 * 1024;
237 bool ProcessNewBlock(
const CChainParams& chainparams,
const std::shared_ptr<const CBlock> pblock,
bool fForceProcessing,
bool* fNewBlock);
278 std::string
GetWarnings(
const std::string& strFor);
306 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
330 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced = NULL,
331 bool fOverrideMempoolLimit=
false,
const CAmount nAbsurdFee=0);
335 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced = NULL,
336 bool fOverrideMempoolLimit=
false,
const CAmount nAbsurdFee=0);
466 std::swap(
nIn, check.
nIn);
499 const CChainParams& chainparams,
bool fJustCheck =
false);
569 static const unsigned int REJECT_INTERNAL = 0x100;
571 static const unsigned int REJECT_HIGHFEE = 0x100;
573 static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
575 static const unsigned int REJECT_CONFLICT = 0x102;
int64_t CAmount
Amount in satoshis (Can be negative)
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API.
The block chain is a tree shaped structure starting with the genesis block at the root,...
Access to the block database (blocks/index/)
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
An in-memory indexed chain of blocks.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Pruned version of CTransaction: only retains metadata and unspent transaction outputs.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Abstract view on the open txout dataset.
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Fee rate in satoshis per kilobyte: CAmount / kB.
Closure representing one script verification Note that this stores references to the spending transac...
ScriptError GetScriptError() const
PrecomputedTransactionData * txdata
void swap(CScriptCheck &check)
const CTransaction * ptxTo
CScriptCheck(const CCoins &txFromIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Capture information about block/transaction validation.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
void swap(prevector< N, T, Size, Diff > &other)
uint64_t GetCheapHash() const
A cheap hash function that just returns 64 bits from the result, it can be used when the contents are...
bool CheckTxInputs(const CChainParams ¶ms, const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
size_t operator()(const uint256 &hash) const
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Parameters that influence chain consensus.
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
std::shared_ptr< const CTransaction > CTransactionRef
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
bool PreciousBlock(CValidationState &state, const CChainParams ¶ms, CBlockIndex *pindex)
Mark a block as precious and reorganize.
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
bool GetTransaction(const uint256 &hash, CTransactionRef &tx, const Consensus::Params ¶ms, uint256 &hashBlock, bool fAllowSlow=false)
Retrieve a transaction (from memory pool, or from disk, if possible)
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
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,...
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks=NULL)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs,...
CCriticalSection cs_main
Global state.
bool WriteBlockToDisk(const CBlock &block, CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &messageStart)
Functions for disk access for blocks.
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams, bool fCheckPOW=true)
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp=NULL)
Import blocks from an external file.
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced=NULL, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
const std::string strMessageMagic
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain.
bool RewindBlockIndex(const CChainParams ¶ms)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
void DumpMempool()
Dump the mempool to disk.
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
VersionBitsCache versionbitscache
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
bool fHavePruned
Pruning-related variables and constants.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::atomic_bool fImporting
boost::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=NULL)
Process incoming block headers.
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, bool fCheckPOW=true)
Functions for validating blocks and updating the block tree.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
void PruneBlockFilesManual(int nPruneUpToHeight)
Prune block files up to a given height.
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
bool CheckFinalTx(const CTransaction &tx, int flags=-1)
Check if transaction will be final in the next block to be created.
bool CheckDiskSpace(uint64_t nAdditionalBytes=0)
Check whether enough disk space is available for an incoming block.
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.
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
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.
bool DisconnectBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean=NULL)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
void ThreadScriptCheck()
Run an instance of the script checking thread.
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
bool ReadBlockHeaderFromDisk(CBlockHeader &block, const CBlockIndex *pindex, const Consensus::Params &consensusParams, bool fCheckPOW=true)
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, const CChainParams &chainparams, bool fJustCheck=false)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs=true)
Transaction validation functions.
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
bool ContextualCheckBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindexPrev)
bool fPruneMode
True if we're running in -prune mode.
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk.
CWaitableCriticalSection csBestBlock
int VersionBitsTipStateSinceHeight(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
void UnloadBlockIndex()
Unload database information.
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for block.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
bool LoadMempool()
Load the mempool from disk.
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
bool AcceptToMemoryPoolWithTime(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced=NULL, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0)
(try to) add transaction to memory pool with a specified acceptance time
CConditionVariable cvBlockChange
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
uint64_t nLastBlockWeight
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp=NULL, bool useExistingLockPoints=false)
Check if transaction will be BIP 68 final in the next block to be created.
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
void PruneAndFlush()
Prune block files and flush state to disk.