Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
validation.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Copyright (c) 2017-2020 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#ifndef BITCOIN_VALIDATION_H
8#define BITCOIN_VALIDATION_H
9
10#if defined(HAVE_CONFIG_H)
11#include <config/bitcoin-config.h>
12#endif
13
14#include <arith_uint256.h>
15#include <attributes.h>
16#include <blockfileinfo.h>
18#include <chain.h>
19#include <common/bloom.h>
20#include <config.h>
21#include <consensus/amount.h>
22#include <consensus/consensus.h>
23#include <deploymentstatus.h>
24#include <disconnectresult.h>
25#include <flatfile.h>
26#include <kernel/chainparams.h>
28#include <kernel/cs_main.h>
29#include <node/blockstorage.h>
30#include <policy/packages.h>
31#include <script/script_error.h>
33#include <shutdown.h>
34#include <sync.h>
35#include <txdb.h>
36#include <txmempool.h> // For CTxMemPool::cs
37#include <uint256.h>
38#include <util/check.h>
39#include <util/fs.h>
40#include <util/result.h>
41#include <util/translation.h>
42
43#include <atomic>
44#include <cstdint>
45#include <map>
46#include <memory>
47#include <optional>
48#include <set>
49#include <string>
50#include <thread>
51#include <type_traits>
52#include <utility>
53#include <vector>
54
56class CChainParams;
57class Chainstate;
59class CScriptCheck;
60class CTxMemPool;
61class CTxUndo;
63
64struct ChainTxData;
65struct FlatFilePos;
67struct LockPoints;
68struct AssumeutxoData;
69namespace node {
70class SnapshotMetadata;
71} // namespace node
72namespace Consensus {
73struct Params;
74} // namespace Consensus
75namespace avalanche {
76class Processor;
77} // namespace avalanche
78
79#define MIN_TRANSACTION_SIZE \
80 (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
81
83static const int MAX_SCRIPTCHECK_THREADS = 15;
85static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
86
87static const bool DEFAULT_PEERBLOOMFILTERS = true;
88
90static const int DEFAULT_STOPATHEIGHT = 0;
95static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
96static const signed int DEFAULT_CHECKBLOCKS = 6;
97static constexpr int DEFAULT_CHECKLEVEL{3};
111static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
112
115
117extern std::condition_variable g_best_block_cv;
119extern const CBlockIndex *g_best_block;
120
122extern const std::vector<std::string> CHECKLEVEL_DOC;
123
125private:
127 bool checkPoW : 1;
129
130public:
131 // Do full validation by default
132 explicit BlockValidationOptions(const Config &config);
138
142 return ret;
143 }
144
149 return ret;
150 }
151
152 bool shouldValidatePoW() const { return checkPoW; }
155};
156
161
166
168
169bool AbortNode(BlockValidationState &state, const std::string &strMessage,
171
176double GuessVerificationProgress(const ChainTxData &data,
177 const CBlockIndex *pindex);
178
182
183// clang-format off
206// clang-format on
209 enum class ResultType {
211 VALID,
213 INVALID,
216 };
219
222
227 const std::optional<int64_t> m_vsize;
229 const std::optional<Amount> m_base_fees;
237 const std::optional<CFeeRate> m_effective_feerate;
244 const std::optional<std::vector<TxId>> m_txids_fee_calculations;
245
247 return MempoolAcceptResult(state);
248 }
249
256
264
270 return MempoolAcceptResult(vsize, fees);
271 }
272
273 // Private constructors. Use static methods MempoolAcceptResult::Success,
274 // etc. to construct.
275private:
280 // Can be invalid or error
281 Assume(!state.IsValid());
282 }
283
286 ResultType result_type, int64_t vsize, Amount fees,
288 const std::vector<TxId> &txids_fee_calculations)
289 : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees),
292
300
302 explicit MempoolAcceptResult(int64_t vsize, Amount fees)
304 m_base_fees(fees) {}
305};
306
319 std::map<TxId, MempoolAcceptResult> m_tx_results;
320
323 std::map<TxId, MempoolAcceptResult> &&results)
324 : m_state{state}, m_tx_results(std::move(results)) {}
325
330 explicit PackageMempoolAcceptResult(const TxId &txid,
331 const MempoolAcceptResult &result)
332 : m_tx_results{{txid, result}} {}
333};
334
360 bool test_accept = false, unsigned int heightOverride = 0)
362
376 const Package &txns, bool test_accept)
378
384protected:
385 std::atomic<int64_t> remaining;
386
387public:
388 explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
389
391 auto newvalue = (remaining -= consumed);
392 return newvalue >= 0;
393 }
394
395 bool check() { return remaining >= 0; }
396};
397
399public:
401
402 // Let's make this bad boy copiable.
405
407 remaining = rhs.remaining.load();
408 return *this;
409 }
410
413 // Historically, there has not been a transaction with more than 20k sig
414 // checks on testnet or mainnet, so this effectively disable sigchecks.
415 txLimiter.remaining = 20000;
416 return txLimiter;
417 }
418};
419
450 const CCoinsViewCache &view, const uint32_t flags,
452 const PrecomputedTransactionData &txdata,
454 CheckInputsLimiter *pBlockLimitSigChecks,
455 std::vector<CScriptCheck> *pvChecks)
457
461static inline bool
472
477 int nHeight);
478
483 int nHeight);
484
503std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
504 const CCoinsView &coins_view,
505 const CTransaction &tx);
506
517
560
561// CScriptCheck is used a lot in std::vector, make sure that's efficient
562static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
563static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
564static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
565
574bool CheckBlock(const CBlock &block, BlockValidationState &state,
575 const Consensus::Params &params,
577
585 const CBlockIndex &active_chain_tip, const Consensus::Params &params,
586 const CTransaction &tx, TxValidationState &state)
588
594 BlockValidationState &state, const CChainParams &params,
596 const std::function<NodeClock::time_point()> &adjusted_time_callback,
598
602bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
604
606arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers);
607
615
621private:
623
624public:
626
627public:
628 explicit CVerifyDB(kernel::Notifications &notifications);
629 ~CVerifyDB();
630
633 int nCheckLevel, int nCheckDepth)
635};
636
639
676
679 CRITICAL = 2,
681 LARGE = 1,
682 OK = 0
683};
684
700protected:
706
712 std::atomic<int32_t> nBlockSequenceId{1};
714 int32_t nBlockReverseSequenceId = -1;
716 arith_uint256 nLastPreciousChainwork = 0;
717
724 mutable std::atomic<bool> m_cached_finished_ibd{false};
725
729
732 std::unique_ptr<CoinsViews> m_coins_views;
733
747
749
755 GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
756
763 CRollingBloomFilter m_filterParkingPoliciesApplied =
764 CRollingBloomFilter{1000, 0.000001};
765
766 CBlockIndex const *m_best_fork_tip = nullptr;
767 CBlockIndex const *m_best_fork_base = nullptr;
768
769public:
773
778
779 explicit Chainstate(
781 ChainstateManager &chainman,
782 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
783
790 void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
791 std::string leveldb_name = "chainstate");
792
797
803 return m_coins_views && m_coins_views->m_cacheview;
804 }
805
809
816 const std::optional<BlockHash> m_from_snapshot_blockhash{};
817
821 return m_from_snapshot_blockhash.has_value();
822 }
823
831 std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
832
836 Assert(m_coins_views);
837 return *Assert(m_coins_views->m_cacheview);
838 }
839
843 return Assert(m_coins_views)->m_dbview;
844 }
845
847 CTxMemPool *GetMempool() { return m_mempool; }
848
854 return Assert(m_coins_views)->m_catcherview;
855 }
856
858 void ResetCoinsViews() { m_coins_views.reset(); }
859
861 bool HasCoinsViews() const { return (bool)m_coins_views; }
862
864 size_t m_coinsdb_cache_size_bytes{0};
865
867 size_t m_coinstip_cache_size_bytes{0};
868
871 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
873
906 std::multimap<BlockHash, FlatFilePos>
908 avalanche::Processor *const avalanche = nullptr)
909 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
910 !cs_avalancheFinalizedBlockIndex);
911
923 bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
924 int nManualPruneHeight = 0);
925
927 void ForceFlushStateToDisk();
928
931 void PruneAndFlush();
932
959 bool ActivateBestChain(BlockValidationState &state,
960 std::shared_ptr<const CBlock> pblock = nullptr,
961 avalanche::Processor *const avalanche = nullptr,
963 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
964 !cs_avalancheFinalizedBlockIndex)
966
967 bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
968 BlockValidationState &state, bool fRequested,
969 const FlatFilePos *dbp, bool *fNewBlock,
971
972 // Block (dis)connection on a given view:
974 const CBlockIndex *pindex,
977 bool ConnectBlock(const CBlock &block, BlockValidationState &state,
980 Amount *blockFees = nullptr, bool fJustCheck = false)
982
983 // Apply the effects of a block disconnection on the UTXO set.
984 bool DisconnectTip(BlockValidationState &state,
987
988 // Manual block validity manipulation:
994 bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex,
995 avalanche::Processor *const avalanche = nullptr)
996 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
997 !cs_avalancheFinalizedBlockIndex)
1000 bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex)
1002 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
1003 !cs_avalancheFinalizedBlockIndex);
1005 bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
1007 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
1008 !cs_avalancheFinalizedBlockIndex);
1009
1013 bool AvalancheFinalizeBlock(CBlockIndex *pindex,
1014 avalanche::Processor &avalanche)
1015 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
1016
1020 void ClearAvalancheFinalizedBlock()
1021 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
1022
1026 bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
1027 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
1028
1030 void ResetBlockFailureFlags(CBlockIndex *pindex)
1033 bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
1036 void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
1039
1041 void UnparkBlockAndChildren(CBlockIndex *pindex)
1043
1045 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1046
1048 bool ReplayBlocks();
1049
1054 bool LoadGenesisBlock();
1055
1056 void PruneBlockIndexCandidates();
1057
1058 void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1059
1064 bool IsInitialBlockDownload() const;
1065
1067 const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
1069
1076 void CheckBlockIndex();
1077
1079 void
1080 LoadMempool(const fs::path &load_path,
1081 fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
1082
1085 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1086
1092
1097
1099
1102 RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1103 return m_mempool ? &m_mempool->cs : nullptr;
1104 }
1105
1106private:
1107 bool ActivateBestChainStep(
1109 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
1110 const avalanche::Processor *const avalanche = nullptr)
1112 !cs_avalancheFinalizedBlockIndex);
1113 bool ConnectTip(BlockValidationState &state,
1116 const std::shared_ptr<const CBlock> &pblock,
1118 const avalanche::Processor *const avalanche = nullptr)
1120 !cs_avalancheFinalizedBlockIndex);
1121 void InvalidBlockFound(CBlockIndex *pindex,
1122 const BlockValidationState &state)
1123 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1124 CBlockIndex *
1125 FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile,
1126 bool fAutoUnpark)
1127 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1128 void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1129 const FlatFilePos &pos)
1131
1132 bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1134
1135 void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1137
1138 bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1139 bool invalidate)
1140 EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1141 !cs_avalancheFinalizedBlockIndex);
1142
1143 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1144 void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1146 void InvalidChainFound(CBlockIndex *pindexNew)
1147 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1148
1149 const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1151
1155 void UpdateTip(const CBlockIndex *pindexNew)
1157
1158 std::chrono::microseconds m_last_write{0};
1159 std::chrono::microseconds m_last_flush{0};
1160
1167
1169};
1170
1172 SUCCESS,
1173 SKIPPED,
1174
1175 // Expected assumeutxo configuration data is not found for the height of the
1176 // base block.
1178
1179 // Failed to generate UTXO statistics (to check UTXO set hash) for the
1180 // background chainstate.
1182
1183 // The UTXO set hash of the background validation chainstate does not match
1184 // the one expected by assumeutxo chainparams.
1186
1187 // The blockhash of the current tip of the background validation chainstate
1188 // does not match the one expected by the snapshot chainstate.
1190};
1191
1220private:
1236 std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1237
1247 std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1248
1258 Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1259
1262
1264 [[nodiscard]] bool
1265 PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1276 bool AcceptBlockHeader(
1277 const CBlockHeader &block, BlockValidationState &state,
1279 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1282
1284 const CBlockIndex *GetSnapshotBaseBlock() const
1286
1289 std::optional<int> GetSnapshotBaseHeight() const
1291
1297 bool IsUsable(const Chainstate *const pchainstate) const
1299 return pchainstate && !pchainstate->m_disabled;
1300 }
1301
1304
1305public:
1307
1308 explicit ChainstateManager(Options options,
1310
1311 const Config &GetConfig() const { return m_options.config; }
1312
1313 const CChainParams &GetParams() const {
1314 return m_options.config.GetChainParams();
1315 }
1317 return m_options.config.GetChainParams().GetConsensus();
1318 }
1320 return *Assert(m_options.check_block_index);
1321 }
1323 return *Assert(m_options.minimum_chain_work);
1324 }
1326 return *Assert(m_options.assumed_valid_block);
1327 }
1329 return m_options.notifications;
1330 };
1331
1344 return ::cs_main;
1345 }
1346
1348 std::thread m_load_block;
1352
1372 std::set<CBlockIndex *> m_failed_blocks;
1373
1379
1382 int64_t m_total_coinstip_cache{0};
1383 //
1386 int64_t m_total_coinsdb_cache{0};
1387
1391 // constructor
1394
1396 std::vector<Chainstate *> GetAll();
1397
1411 [[nodiscard]] bool ActivateSnapshot(AutoFile &coins_file,
1413 bool in_memory);
1414
1423 std::function<void(bilingual_str)> shutdown_fnc =
1424 [](bilingual_str msg) { AbortNode(msg.original, msg); })
1426
1428 Chainstate &ActiveChainstate() const;
1430 return ActiveChainstate().m_chain;
1431 }
1432 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1433 return ActiveChain().Height();
1434 }
1436 return ActiveChain().Tip();
1437 }
1438
1441 return m_blockman.m_block_index;
1442 }
1443
1446 bool IsSnapshotActive() const;
1447
1448 std::optional<BlockHash> SnapshotBlockhash() const;
1449
1455
1483 bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1485 bool *new_block,
1486 avalanche::Processor *const avalanche = nullptr)
1488
1504 bool ProcessNewBlockHeaders(
1505 const std::vector<CBlockHeader> &block, bool min_pow_checked,
1506 BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1509
1519 ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1521
1524 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1525
1529
1536 void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1538
1543
1545
1551
1562
1564 bool DumpRecentHeadersTime(const fs::path &filePath) const
1565 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1567 bool LoadRecentHeadersTime(const fs::path &filePath)
1568 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1569};
1570
1574 const ChainstateManager &chainman, DEP dep) {
1575 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1576}
1577
1578template <typename DEP>
1580 const ChainstateManager &chainman, DEP dep) {
1581 return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1582}
1583
1591const AssumeutxoData *ExpectedAssumeutxo(const int height,
1592 const CChainParams &params);
1593
1594#endif // BITCOIN_VALIDATION_H
int flags
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition check.h:84
#define Assume(val)
Assume is the identity function.
Definition check.h:97
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:528
uint64_t getExcessiveBlockSize() const
Definition validation.h:154
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition validation.h:139
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition validation.h:133
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition validation.h:146
bool shouldValidatePoW() const
Definition validation.h:152
bool shouldValidateMerkleRoot() const
Definition validation.h:153
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition block.h:23
Definition block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition blockindex.h:25
An in-memory indexed chain of blocks.
Definition chain.h:134
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:80
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:221
CCoinsView backed by the coin database (chainstate/)
Definition txdb.h:65
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition coins.h:374
Abstract view on the open txout dataset.
Definition coins.h:163
Fee rate in satoshis per kilobyte: Amount / kB.
Definition feerate.h:21
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition bloom.h:115
Closure representing one script verification.
Definition validation.h:525
CScriptCheck & operator=(CScriptCheck &&)=default
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
Definition validation.h:539
ScriptError GetScriptError() const
Definition validation.h:556
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition validation.h:558
CScriptCheck(const CScriptCheck &)=delete
uint32_t nFlags
Definition validation.h:530
TxSigCheckLimiter * pTxLimitSigChecks
Definition validation.h:535
ScriptExecutionMetrics metrics
Definition validation.h:533
CTxOut m_tx_out
Definition validation.h:527
CScriptCheck(CScriptCheck &&)=default
ScriptError error
Definition validation.h:532
PrecomputedTransactionData txdata
Definition validation.h:534
const CTransaction * ptxTo
Definition validation.h:528
unsigned int nIn
Definition validation.h:529
CheckInputsLimiter * pBlockLimitSigChecks
Definition validation.h:536
CScriptCheck & operator=(const CScriptCheck &)=delete
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 ...
Definition txmempool.h:212
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition txmempool.h:307
An output of a transaction.
Restore the UTXO in a Coin at a given COutPoint.
Definition undo.h:62
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition validation.h:620
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition validation.h:622
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition validation.h:699
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition validation.h:831
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Definition validation.h:801
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition validation.h:705
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition validation.h:808
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition validation.h:861
CTxMemPool * GetMempool()
Definition validation.h:847
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition validation.h:851
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:834
Mutex cs_avalancheFinalizedBlockIndex
Definition validation.h:748
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition validation.h:728
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition validation.h:820
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition validation.h:746
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:841
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition validation.h:777
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition validation.h:732
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition validation.h:858
const CBlockIndex *m_avalancheFinalizedBlockIndex GUARDED_BY(cs_avalancheFinalizedBlockIndex)
The best block via avalanche voting.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition validation.h:772
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
const Config & GetConfig() const
kernel::Notifications & GetNotifications() const
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
bool ShouldCheckBlockIndex() const
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CChainParams & GetParams() const
const Consensus::Params & GetConsensus() const
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
const arith_uint256 & MinimumChainWork() const
const Options m_options
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
std::thread m_load_block
const BlockHash & AssumedValidBlock() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
std::set< CBlockIndex * > m_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition validation.h:383
bool consume_and_check(int consumed)
Definition validation.h:390
std::atomic< int64_t > remaining
Definition validation.h:385
CheckInputsLimiter(int64_t limit)
Definition validation.h:388
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition validation.h:649
std::unique_ptr< CCoinsViewCache > m_cacheview GUARDED_BY(cs_main)
This is the top layer of the cache hierarchy - it keeps as many coins in memory as can fit per the db...
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main)
This view wraps access to the leveldb instance and handles read errors gracefully.
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
Different type to mark Mutex at global scope.
Definition sync.h:144
static TxSigCheckLimiter getDisabled()
Definition validation.h:411
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition validation.h:406
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition validation.h:403
bool IsValid() const
Definition validation.h:119
256-bit unsigned big integer.
A base class defining functions for notifying about certain kernel events.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
Definition consensus.h:22
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:7
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
DisconnectResult
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
static void pool cs
Filesystem operations and types.
Definition fs.h:20
Bridge operations to C stdio.
Definition fs.cpp:28
Definition init.h:28
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition packages.h:40
std::shared_ptr< const CTransaction > CTransactionRef
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
ScriptError
static std::string ToString(const CService &ip)
Definition db.h:37
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
Definition shutdown.cpp:20
Holds configuration for use during UTXO snapshot load and validation.
Definition chainparams.h:46
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition block.h:105
Holds various statistics on transactions within a chain.
Definition chainparams.h:67
User-controlled performance and debug options.
Definition txdb.h:56
Parameters that influence chain consensus.
Definition params.h:34
Application-specific storage settings.
Definition dbwrapper.h:32
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition validation.h:207
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition validation.h:227
MempoolAcceptResult(ResultType result_type, int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Generic constructor for success cases.
Definition validation.h:285
const ResultType m_result_type
Result type.
Definition validation.h:218
const std::optional< std::vector< TxId > > m_txids_fee_calculations
Contains the txids of the transactions used for fee-related checks.
Definition validation.h:244
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition validation.h:277
const TxValidationState m_state
Contains information about why the transaction failed.
Definition validation.h:221
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for fee-related failure case.
Definition validation.h:294
ResultType
Used to indicate the results of mempool validation.
Definition validation.h:209
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition validation.h:246
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition validation.h:237
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition validation.h:251
static MempoolAcceptResult Success(int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for success case.
Definition validation.h:259
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition validation.h:269
MempoolAcceptResult(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition validation.h:302
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition validation.h:229
std::chrono::time_point< NodeClock > time_point
Definition time.h:19
Validation result for package mempool acceptance.
Definition validation.h:310
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition validation.h:330
PackageMempoolAcceptResult(PackageValidationState state, std::map< TxId, MempoolAcceptResult > &&results)
Definition validation.h:321
PackageValidationState m_state
Definition validation.h:311
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition validation.h:319
Precompute sighash midstate to avoid quadratic hashing.
Struct for holding cumulative results from executing a script or a sequence of scripts.
A TxId is the identifier of a transaction.
Definition txid.h:14
Bilingual messages:
Definition translation.h:17
std::string original
Definition translation.h:18
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
#define AssertLockHeld(cs)
Definition sync.h:146
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define LOCK_RETURNED(x)
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition time.h:31
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &chainparams)
Return the expected assumeutxo value for a given height, if one exists.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition validation.h:593
GlobalMutex g_best_block_mutex
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be cre...
static constexpr int DEFAULT_CHECKLEVEL
Definition validation.h:97
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition validation.h:111
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition validation.h:95
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
SnapshotCompletionResult
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition validation.h:83
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition validation.h:114
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition validation.h:85
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false, unsigned int heightOverride=0) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
VerifyDBResult
Definition validation.h:608
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CoinsCacheSizeState
Definition validation.h:677
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static const signed int DEFAULT_CHECKBLOCKS
Definition validation.h:96
FlushStateMode
Definition validation.h:638
static const bool DEFAULT_PEERBLOOMFILTERS
Definition validation.h:87
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition validation.h:90