Bitcoin ABC  0.26.3
P2P Digital Currency
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>
17 #include <blockindexcomparators.h>
18 #include <chain.h>
19 #include <consensus/amount.h>
20 #include <consensus/consensus.h>
21 #include <disconnectresult.h>
22 #include <flatfile.h>
23 #include <fs.h>
24 #include <node/blockstorage.h>
25 #include <policy/packages.h>
26 #include <script/script_error.h>
27 #include <script/script_metrics.h>
28 #include <sync.h>
29 #include <txdb.h>
30 #include <txmempool.h> // For CTxMemPool::cs
31 #include <uint256.h>
32 #include <util/check.h>
33 #include <util/translation.h>
34 
35 #include <atomic>
36 #include <cstdint>
37 #include <map>
38 #include <memory>
39 #include <optional>
40 #include <set>
41 #include <string>
42 #include <thread>
43 #include <utility>
44 #include <vector>
45 
46 class CChainParams;
47 class CChainState;
48 class ChainstateManager;
49 class Config;
50 class CScriptCheck;
51 class CTxMemPool;
52 class CTxUndo;
54 
55 struct ChainTxData;
56 struct FlatFilePos;
58 struct LockPoints;
59 struct AssumeutxoData;
60 namespace node {
61 class SnapshotMetadata;
62 } // namespace node
63 
64 namespace Consensus {
65 struct Params;
66 }
67 
68 #define MIN_TRANSACTION_SIZE \
69  (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
70 
79 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
81 static const int MAX_SCRIPTCHECK_THREADS = 15;
83 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
84 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
85 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
86 static const bool DEFAULT_TXINDEX = false;
87 static constexpr bool DEFAULT_COINSTATSINDEX{false};
88 static const char *const DEFAULT_BLOCKFILTERINDEX = "0";
89 
91 static const bool DEFAULT_PERSIST_MEMPOOL = true;
92 
93 static const bool DEFAULT_PEERBLOOMFILTERS = true;
94 
96 static const int DEFAULT_STOPATHEIGHT = 0;
101 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
102 static const signed int DEFAULT_CHECKBLOCKS = 6;
103 static const unsigned int DEFAULT_CHECKLEVEL = 3;
117 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
118 
121 
122 extern RecursiveMutex cs_main;
124 extern std::condition_variable g_best_block_cv;
126 extern uint256 g_best_block;
127 extern bool fRequireStandard;
128 extern bool fCheckBlockIndex;
129 extern bool fCheckpointsEnabled;
130 
135 extern CFeeRate minRelayTxFee;
140 extern int64_t nMaxTipAge;
141 
147 
152 
154 extern const std::vector<std::string> CHECKLEVEL_DOC;
155 
157 private:
159  bool checkPoW : 1;
160  bool checkMerkleRoot : 1;
161 
162 public:
163  // Do full validation by default
164  explicit BlockValidationOptions(const Config &config);
165  explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
166  bool _checkPow = true,
167  bool _checkMerkleRoot = true)
168  : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
169  checkMerkleRoot(_checkMerkleRoot) {}
170 
171  BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
172  BlockValidationOptions ret = *this;
173  ret.checkPoW = _checkPoW;
174  return ret;
175  }
176 
178  withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
179  BlockValidationOptions ret = *this;
180  ret.checkMerkleRoot = _checkMerkleRoot;
181  return ret;
182  }
183 
184  bool shouldValidatePoW() const { return checkPoW; }
185  bool shouldValidateMerkleRoot() const { return checkMerkleRoot; }
186  uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
187 };
188 
192 void StartScriptCheckWorkerThreads(int threads_num);
193 
198 
199 Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
200 
201 bool AbortNode(BlockValidationState &state, const std::string &strMessage,
202  const bilingual_str &userMessage = bilingual_str{});
203 
208 double GuessVerificationProgress(const ChainTxData &data,
209  const CBlockIndex *pindex);
210 
212 void PruneBlockFilesManual(CChainState &active_chainstate,
213  int nManualPruneHeight);
214 
220  enum class ResultType {
222  VALID,
224  INVALID,
227  };
230 
231  // The following fields are only present when m_result_type =
232  // ResultType::VALID or MEMPOOL_ENTRY
237  const std::optional<int64_t> m_vsize;
239  const std::optional<Amount> m_base_fees;
241  return MempoolAcceptResult(state);
242  }
243 
245  static MempoolAcceptResult Success(int64_t vsize, Amount fees) {
246  return MempoolAcceptResult(ResultType::VALID, vsize, fees);
247  }
248 
253  static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
254  return MempoolAcceptResult(ResultType::MEMPOOL_ENTRY, vsize, fees);
255  }
256 
257  // Private constructors. Use static methods MempoolAcceptResult::Success,
258  // etc. to construct.
259 private:
262  : m_result_type(ResultType::INVALID), m_state(state),
263  m_base_fees(std::nullopt) {
264  // Can be invalid or error
265  Assume(!state.IsValid());
266  }
267 
269  explicit MempoolAcceptResult(ResultType result_type, int64_t vsize,
270  Amount fees)
271  : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees) {}
272 };
273 
286  std::map<const TxId, const MempoolAcceptResult> m_tx_results;
287 
290  std::map<const TxId, const MempoolAcceptResult> &&results)
291  : m_state{state}, m_tx_results(std::move(results)) {}
292 
297  explicit PackageMempoolAcceptResult(const TxId &txid,
298  const MempoolAcceptResult &result)
299  : m_tx_results{{txid, result}} {}
300 };
301 
324 AcceptToMemoryPool(const Config &config, CChainState &active_chainstate,
325  const CTransactionRef &tx, int64_t accept_time,
326  bool bypass_limits, bool test_accept = false)
328 
341 ProcessNewPackage(const Config &config, CChainState &active_chainstate,
342  CTxMemPool &pool, const Package &txns, bool test_accept)
344 
350 protected:
351  std::atomic<int64_t> remaining;
352 
353 public:
354  explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
355 
356  bool consume_and_check(int consumed) {
357  auto newvalue = (remaining -= consumed);
358  return newvalue >= 0;
359  }
360 
361  bool check() { return remaining >= 0; }
362 };
363 
365 public:
367 
368  // Let's make this bad boy copiable.
370  : CheckInputsLimiter(rhs.remaining.load()) {}
371 
373  remaining = rhs.remaining.load();
374  return *this;
375  }
376 
378  TxSigCheckLimiter txLimiter;
379  // Historically, there has not been a transaction with more than 20k sig
380  // checks on testnet or mainnet, so this effectively disable sigchecks.
381  txLimiter.remaining = 20000;
382  return txLimiter;
383  }
384 };
385 
386 class ConnectTrace;
387 
417 bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
418  const CCoinsViewCache &view, const uint32_t flags,
419  bool sigCacheStore, bool scriptCacheStore,
420  const PrecomputedTransactionData &txdata,
421  int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks,
422  CheckInputsLimiter *pBlockLimitSigChecks,
423  std::vector<CScriptCheck> *pvChecks)
425 
429 static inline bool
431  const CCoinsViewCache &view, const uint32_t flags,
432  bool sigCacheStore, bool scriptCacheStore,
433  const PrecomputedTransactionData &txdata, int &nSigChecksOut)
435  TxSigCheckLimiter nSigChecksTxLimiter;
436  return CheckInputScripts(tx, state, view, flags, sigCacheStore,
437  scriptCacheStore, txdata, nSigChecksOut,
438  nSigChecksTxLimiter, nullptr, nullptr);
439 }
440 
444 void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
445  int nHeight);
446 
450 void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
451  int nHeight);
452 
471 bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view,
472  const CTransaction &tx, LockPoints *lp = nullptr,
473  bool useExistingLockPoints = false);
474 
483 private:
486  unsigned int nIn;
487  uint32_t nFlags;
494 
495 public:
497  : ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false),
499  pBlockLimitSigChecks(nullptr) {}
500 
501  CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
502  unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn,
503  const PrecomputedTransactionData &txdataIn,
504  TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
505  CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
506  : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
507  cacheStore(cacheIn), error(ScriptError::UNKNOWN), txdata(txdataIn),
508  pTxLimitSigChecks(pTxLimitSigChecksIn),
509  pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
510 
511  bool operator()();
512 
513  void swap(CScriptCheck &check) {
514  std::swap(ptxTo, check.ptxTo);
515  std::swap(m_tx_out, check.m_tx_out);
516  std::swap(nIn, check.nIn);
517  std::swap(nFlags, check.nFlags);
518  std::swap(cacheStore, check.cacheStore);
519  std::swap(error, check.error);
520  std::swap(metrics, check.metrics);
521  std::swap(txdata, check.txdata);
522  std::swap(pTxLimitSigChecks, check.pTxLimitSigChecks);
523  std::swap(pBlockLimitSigChecks, check.pBlockLimitSigChecks);
524  }
525 
526  ScriptError GetScriptError() const { return error; }
527 
529 };
530 
539 bool CheckBlock(const CBlock &block, BlockValidationState &state,
540  const Consensus::Params &params,
541  BlockValidationOptions validationOptions);
542 
550  const CBlockIndex *active_chain_tip, const Consensus::Params &params,
551  const CTransaction &tx, TxValidationState &state)
553 
559  CChainState &chainstate, const CBlock &block,
560  CBlockIndex *pindexPrev,
561  BlockValidationOptions validationOptions)
563 
568 class CVerifyDB {
569 public:
570  CVerifyDB();
571 
572  ~CVerifyDB();
573 
574  bool VerifyDB(CChainState &chainstate, const Config &config,
575  CCoinsView &coinsview, int nCheckLevel, int nCheckDepth)
577 };
578 
581 
591 class CoinsViews {
592 public:
596 
600 
603  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
604 
613  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory,
614  bool should_wipe);
615 
617  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
618 };
619 
622  CRITICAL = 2,
624  LARGE = 1,
625  OK = 0
626 };
627 
642 class CChainState {
643 private:
649 
655  std::atomic<int32_t> nBlockSequenceId{1};
657  int32_t nBlockReverseSequenceId = -1;
659  arith_uint256 nLastPreciousChainwork = 0;
660 
667  mutable std::atomic<bool> m_cached_finished_ibd{false};
668 
672 
675  std::unique_ptr<CoinsViews> m_coins_views;
676 
678 
683  const CBlockIndex *m_avalancheFinalizedBlockIndex
684  GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
685 
686  CBlockIndex const *m_best_fork_tip = nullptr;
687  CBlockIndex const *m_best_fork_base = nullptr;
688 
689 public:
693 
696 
701 
702  explicit CChainState(
703  CTxMemPool *mempool, node::BlockManager &blockman,
704  ChainstateManager &chainman,
705  std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
706 
713  void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
714  std::string leveldb_name = "chainstate");
715 
718  void InitCoinsCache(size_t cache_size_bytes)
720 
724  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
726  return m_coins_views && m_coins_views->m_cacheview;
727  }
728 
732 
739  const std::optional<BlockHash> m_from_snapshot_blockhash{};
740 
744  return m_from_snapshot_blockhash.has_value();
745  }
746 
754  std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
755 
759  assert(m_coins_views->m_cacheview);
760  return *m_coins_views->m_cacheview.get();
761  }
762 
766  return m_coins_views->m_dbview;
767  }
768 
770  CTxMemPool *GetMempool() { return m_mempool; }
771 
777  return m_coins_views->m_catcherview;
778  }
779 
781  void ResetCoinsViews() { m_coins_views.reset(); }
782 
784  size_t m_coinsdb_cache_size_bytes{0};
785 
787  size_t m_coinstip_cache_size_bytes{0};
788 
791  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
793 
795  void LoadExternalBlockFile(const Config &config, FILE *fileIn,
796  FlatFilePos *dbp = nullptr)
797  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex);
798 
810  bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
811  int nManualPruneHeight = 0);
812 
814  void ForceFlushStateToDisk();
815 
818  void PruneAndFlush();
819 
835  bool ActivateBestChain(const Config &config, BlockValidationState &state,
836  std::shared_ptr<const CBlock> pblock = nullptr)
837  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(cs_main);
838 
839  bool AcceptBlock(const Config &config,
840  const std::shared_ptr<const CBlock> &pblock,
841  BlockValidationState &state, bool fRequested,
842  const FlatFilePos *dbp, bool *fNewBlock)
844 
845  // Block (dis)connection on a given view:
846  DisconnectResult DisconnectBlock(const CBlock &block,
847  const CBlockIndex *pindex,
848  CCoinsViewCache &view)
850  bool ConnectBlock(const CBlock &block, BlockValidationState &state,
851  CBlockIndex *pindex, CCoinsViewCache &view,
852  BlockValidationOptions options, bool fJustCheck = false)
854 
855  // Apply the effects of a block disconnection on the UTXO set.
856  bool DisconnectTip(BlockValidationState &state,
857  DisconnectedBlockTransactions *disconnectpool)
859 
860  // Manual block validity manipulation:
866  bool PreciousBlock(const Config &config, BlockValidationState &state,
867  CBlockIndex *pindex)
868  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(cs_main);
870  bool InvalidateBlock(const Config &config, BlockValidationState &state,
872  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex);
874  bool ParkBlock(const Config &config, BlockValidationState &state,
876  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex);
877 
881  bool AvalancheFinalizeBlock(CBlockIndex *pindex);
882 
886  void ClearAvalancheFinalizedBlock();
887 
891  bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const;
892 
894  void ResetBlockFailureFlags(CBlockIndex *pindex)
896  template <typename F>
897  bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
899  template <typename F, typename C, typename AC>
900  void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
901  C fChild, AC fAncestorWasChanged)
903 
905  void UnparkBlockAndChildren(CBlockIndex *pindex)
907 
909  void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
910 
912  bool ReplayBlocks();
913 
918  bool LoadGenesisBlock();
919 
920  void PruneBlockIndexCandidates();
921 
922  void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
923 
928  bool IsInitialBlockDownload() const;
929 
931  const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
933 
940  void CheckBlockIndex();
941 
943  void LoadMempool(const Config &config, const ArgsManager &args);
944 
947  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
948 
952  CoinsCacheSizeState GetCoinsCacheSizeState()
954 
956  GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
957  size_t max_mempool_size_bytes)
959 
960  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
961 
962 private:
963  bool ActivateBestChainStep(const Config &config,
964  BlockValidationState &state,
965  CBlockIndex *pindexMostWork,
966  const std::shared_ptr<const CBlock> &pblock,
967  bool &fInvalidFound, ConnectTrace &connectTrace)
968  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
969  bool ConnectTip(const Config &config, BlockValidationState &state,
970  CBlockIndex *pindexNew,
971  const std::shared_ptr<const CBlock> &pblock,
972  ConnectTrace &connectTrace,
973  DisconnectedBlockTransactions &disconnectpool)
974  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
975  void InvalidBlockFound(CBlockIndex *pindex,
976  const BlockValidationState &state)
978  CBlockIndex *
979  FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile)
981  void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
982  const FlatFilePos &pos)
984 
985  bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
987 
988  void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
990 
991  bool UnwindBlock(const Config &config, BlockValidationState &state,
992  CBlockIndex *pindex, bool invalidate)
993  EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex);
994 
995  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
996  void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
998  void InvalidChainFound(CBlockIndex *pindexNew)
1000 
1001  const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1003 
1006  RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1007  return m_mempool ? &m_mempool->cs : nullptr;
1008  }
1009 
1013  void UpdateTip(const CBlockIndex *pindexNew)
1015 
1017 };
1018 
1047 private:
1063  std::unique_ptr<CChainState> m_ibd_chainstate GUARDED_BY(::cs_main);
1064 
1074  std::unique_ptr<CChainState> m_snapshot_chainstate GUARDED_BY(::cs_main);
1075 
1085  CChainState *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1086 
1089  bool m_snapshot_validated GUARDED_BY(::cs_main){false};
1090 
1091  CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1092  CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1093 
1095  [[nodiscard]] bool
1096  PopulateAndValidateSnapshot(CChainState &snapshot_chainstate,
1097  CAutoFile &coins_file,
1098  const node::SnapshotMetadata &metadata);
1104  bool AcceptBlockHeader(const Config &config, const CBlockHeader &block,
1105  BlockValidationState &state, CBlockIndex **ppindex)
1107  friend CChainState;
1108 
1109 public:
1110  std::thread m_load_block;
1114 
1134  std::set<CBlockIndex *> m_failed_blocks;
1135 
1140  CBlockIndex *m_best_header = nullptr;
1141 
1144  int64_t m_total_coinstip_cache{0};
1145  //
1148  int64_t m_total_coinsdb_cache{0};
1149 
1154  // constructor
1157  CChainState &
1158  InitializeChainstate(CTxMemPool *mempool,
1159  const std::optional<BlockHash> &snapshot_blockhash =
1160  std::nullopt) LIFETIMEBOUND
1162 
1164  std::vector<CChainState *> GetAll();
1165 
1179  [[nodiscard]] bool ActivateSnapshot(CAutoFile &coins_file,
1180  const node::SnapshotMetadata &metadata,
1181  bool in_memory);
1182 
1184  CChainState &ActiveChainstate() const;
1185  CChain &ActiveChain() const { return ActiveChainstate().m_chain; }
1186  int ActiveHeight() const { return ActiveChain().Height(); }
1187  CBlockIndex *ActiveTip() const { return ActiveChain().Tip(); }
1188 
1191  return m_blockman.m_block_index;
1192  }
1193 
1196  bool IsSnapshotActive() const;
1197 
1198  std::optional<BlockHash> SnapshotBlockhash() const;
1199 
1202  return m_snapshot_validated;
1203  }
1204 
1228  bool ProcessNewBlock(const Config &config,
1229  const std::shared_ptr<const CBlock> &block,
1230  bool force_processing, bool *new_block)
1232 
1247  bool ProcessNewBlockHeaders(const Config &config,
1248  const std::vector<CBlockHeader> &block,
1249  BlockValidationState &state,
1250  const CBlockIndex **ppindex = nullptr)
1252 
1261  [[nodiscard]] MempoolAcceptResult
1262  ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1264 
1267  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1268 
1271  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1272 };
1273 
1275 bool DumpMempool(const CTxMemPool &pool);
1276 
1278 bool LoadMempool(const Config &config, CTxMemPool &pool,
1279  CChainState &active_chainstate);
1280 
1288 const AssumeutxoData *ExpectedAssumeutxo(const int height,
1289  const CChainParams &params);
1290 
1291 #endif // BITCOIN_VALIDATION_H
static constexpr Amount SATOSHI
Definition: amount.h:153
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:537
@ UNKNOWN
Unused.
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
uint64_t getExcessiveBlockSize() const
Definition: validation.h:186
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:171
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:165
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:178
BlockValidationOptions(const Config &config)
Definition: validation.cpp:126
bool shouldValidatePoW() const
Definition: validation.h:184
uint64_t excessiveBlockSize
Definition: validation.h:158
bool shouldValidateMerkleRoot() const
Definition: validation.h:185
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:581
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
Definition: block.h:55
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
An in-memory indexed chain of blocks.
Definition: chain.h:141
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:642
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:648
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:754
const CChainParams & m_params
Chain parameters for this chainstate.
Definition: validation.h:695
CTxMemPool * GetMempool()
Definition: validation.h:770
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:700
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:757
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:671
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 CChainState instances.
Definition: validation.h:692
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:675
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:781
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:774
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:731
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:677
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:1013
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition: validation.h:743
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:764
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:203
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:54
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:339
Abstract view on the open txout dataset.
Definition: coins.h:147
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
Closure representing one script verification.
Definition: validation.h:482
bool operator()()
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:501
ScriptError GetScriptError() const
Definition: validation.h:526
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:528
uint32_t nFlags
Definition: validation.h:487
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:492
ScriptExecutionMetrics metrics
Definition: validation.h:490
void swap(CScriptCheck &check)
Definition: validation.h:513
CTxOut m_tx_out
Definition: validation.h:484
bool cacheStore
Definition: validation.h:488
ScriptError error
Definition: validation.h:489
PrecomputedTransactionData txdata
Definition: validation.h:491
const CTransaction * ptxTo
Definition: validation.h:485
unsigned int nIn
Definition: validation.h:486
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:493
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:438
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:521
An output of a transaction.
Definition: transaction.h:130
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:568
bool VerifyDB(CChainState &chainstate, const Config &config, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1046
std::unique_ptr< CChainState > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
int ActiveHeight() const
Definition: validation.h:1186
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:1085
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
Definition: validation.h:1092
bool m_snapshot_validated GUARDED_BY(::cs_main)
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
Definition: validation.h:1089
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< BlockHash > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:1164
std::unique_ptr< CChainState > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1189
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1201
CBlockIndex * ActiveTip() const
Definition: validation.h:1187
CChain & ActiveChain() const
Definition: validation.h:1185
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1091
std::thread m_load_block
Definition: validation.h:1110
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...
Definition: validation.h:1134
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1113
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:349
bool consume_and_check(int consumed)
Definition: validation.h:356
std::atomic< int64_t > remaining
Definition: validation.h:351
CheckInputsLimiter(int64_t limit)
Definition: validation.h:354
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:591
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.
CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Definition: config.h:17
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
static TxSigCheckLimiter getDisabled()
Definition: validation.h:377
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:372
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:369
bool IsValid() const
Definition: validation.h:120
256-bit unsigned big integer.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:67
Metadata describing a serialized version of a UTXO set from which an assumeutxo CChainState can be co...
Definition: utxo_snapshot.h:15
256-bit opaque blob.
Definition: uint256.h:127
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
Definition: consensus.h:22
DisconnectResult
unsigned int nHeight
LockPoints lp
static void pool cs
Definition: init.h:28
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:58
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:38
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
@ PERIODIC
Called by RandAddPeriodic()
ScriptError
Definition: script_error.h:11
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:77
Definition: amount.h:19
static constexpr Amount zero()
Definition: amount.h:42
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
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:100
Holds various statistics on transactions within a chain.
Definition: chainparams.h:61
Parameters that influence chain consensus.
Definition: params.h:76
Validation result for a single transaction mempool acceptance.
Definition: validation.h:218
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition: validation.h:237
const ResultType m_result_type
Definition: validation.h:228
static MempoolAcceptResult Success(int64_t vsize, Amount fees)
Constructor for success case.
Definition: validation.h:245
MempoolAcceptResult(ResultType result_type, int64_t vsize, Amount fees)
Generic constructor for success cases.
Definition: validation.h:269
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:261
const TxValidationState m_state
Definition: validation.h:229
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:220
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:240
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:253
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:239
Validation result for package mempool acceptance.
Definition: validation.h:277
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition: validation.h:297
std::map< const TxId, const MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:286
PackageMempoolAcceptResult(PackageValidationState state, std::map< const TxId, const MempoolAcceptResult > &&results)
Definition: validation.h:288
const PackageValidationState m_state
Definition: validation.h:278
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:329
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
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
#define LOCK_RETURNED(x)
Definition: threadsafety.h:54
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:122
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(boo TestBlockValidity)(BlockValidationState &state, const CChainParams &params, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: validation.h:558
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:85
PackageMempoolAcceptResult ProcessNewPackage(const Config &config, CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
MempoolAcceptResult AcceptToMemoryPool(const Config &config, CChainState &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
bool fCheckBlockIndex
Definition: validation.cpp:117
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
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:117
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
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 DEFAULT_CHECKLEVEL
Definition: validation.h:103
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:124
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:101
static const Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:81
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
Definition: validation.h:74
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:120
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:83
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:88
Mutex g_best_block_mutex
Definition: validation.cpp:113
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:79
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:87
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'.
Definition: validation.cpp:90
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:153
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:121
CoinsCacheSizeState
Definition: validation.h:620
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:111
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:84
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
bool fCheckpointsEnabled
Definition: validation.cpp:118
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:102
FlushStateMode
Definition: validation.h:580
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:115
bool LoadMempool(const Config &config, CTxMemPool &pool, CChainState &active_chainstate)
Load the mempool from disk.
bool fRequireStandard
Definition: validation.cpp:116
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:91
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:93
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:96
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:119
static const bool DEFAULT_TXINDEX
Definition: validation.h:86