96 "level 0 reads the blocks from disk",
97 "level 1 verifies block validity",
98 "level 2 verifies undo data",
99 "level 3 checks disconnection of tip blocks",
100 "level 4 tries to reconnect the blocks",
101 "each level includes the checks of the previous levels",
118 : excessiveBlockSize(config.GetMaxBlockSize()), checkPoW(true),
119 checkMerkleRoot(true) {}
156std::optional<std::vector<int>> CalculatePrevHeights(
const CBlockIndex &tip,
158 const CTransaction &tx) {
159 std::vector<int> prev_heights;
160 prev_heights.resize(tx.vin.size());
161 for (
size_t i = 0; i < tx.vin.size(); ++i) {
162 if (
auto coin{coins.
GetCoin(tx.vin[i].prevout)}) {
168 LogPrintf(
"ERROR: %s: Missing input %d in transaction \'%s\'\n",
169 __func__, i, tx.GetHash().GetHex());
179 const CTransaction &tx) {
182 auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
183 if (!prev_heights.has_value()) {
188 next_tip.
pprev = tip;
223 const std::optional<int64_t> activation_time) {
224 if (pindexPrev ==
nullptr) {
247 for (
const CTxIn &txin : tx.vin) {
263 assert(txFrom->GetId() == txin.prevout.GetTxId());
264 assert(txFrom->vout.size() > txin.prevout.GetN());
277 validation_cache, nSigChecksOut);
285 : m_pool(mempool), m_view(&m_dummy),
286 m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
287 m_active_chainstate(active_chainstate) {}
293 const int64_t m_accept_time;
294 const bool m_bypass_limits;
302 std::vector<COutPoint> &m_coins_to_uncache;
303 const bool m_test_accept;
304 const unsigned int m_heightOverride;
310 const bool m_package_submission;
316 const bool m_package_feerates;
319 static ATMPArgs SingleAccept(
const Config &config, int64_t accept_time,
321 std::vector<COutPoint> &coins_to_uncache,
323 unsigned int heightOverride) {
341 PackageTestAccept(
const Config &config, int64_t accept_time,
342 std::vector<COutPoint> &coins_to_uncache) {
358 PackageChildWithParents(
const Config &config, int64_t accept_time,
359 std::vector<COutPoint> &coins_to_uncache) {
373 static ATMPArgs SingleInPackageAccept(
const ATMPArgs &package_args) {
375 package_args.m_config,
376 package_args.m_accept_time,
378 package_args.m_coins_to_uncache,
379 package_args.m_test_accept,
380 package_args.m_heightOverride,
392 ATMPArgs(
const Config &config, int64_t accept_time,
bool bypass_limits,
393 std::vector<COutPoint> &coins_to_uncache,
bool test_accept,
394 unsigned int height_override,
bool package_submission,
395 bool package_feerates)
396 : m_config{config}, m_accept_time{accept_time},
397 m_bypass_limits{bypass_limits},
398 m_coins_to_uncache{coins_to_uncache}, m_test_accept{test_accept},
399 m_heightOverride{height_override},
400 m_package_submission{package_submission},
401 m_package_feerates(package_feerates) {}
416 AcceptMultipleTransactions(
const std::vector<CTransactionRef> &txns,
433 AcceptSubPackage(
const std::vector<CTransactionRef> &subpackage,
451 const uint32_t next_block_script_verify_flags)
453 m_next_block_script_verify_flags(next_block_script_verify_flags) {
460 std::unique_ptr<CTxMemPoolEntry> m_entry;
498 const uint32_t m_next_block_script_verify_flags;
499 int m_sig_checks_standard;
507 bool PreChecks(ATMPArgs &args, Workspace &ws)
514 bool ConsensusScriptChecks(
const ATMPArgs &args, Workspace &ws)
520 bool Finalize(
const ATMPArgs &args, Workspace &ws)
528 bool SubmitPackage(
const ATMPArgs &args, std::vector<Workspace> &workspaces,
530 std::map<TxId, MempoolAcceptResult> &results)
534 bool CheckFeeRate(
size_t package_size,
size_t package_vsize,
540 const Amount mempoolRejectFee =
541 m_pool.GetMinFee().GetFee(package_vsize);
544 package_fee < mempoolRejectFee) {
547 "mempool min fee not met",
548 strprintf(
"%d < %d", package_fee, mempoolRejectFee));
554 m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
557 "min relay fee not met",
559 "%d < %d", package_fee,
560 m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
567 return m_active_chainstate.m_chainman.m_validation_cache;
579bool MemPoolAccept::PreChecks(ATMPArgs &args, Workspace &ws) {
583 const CTransaction &tx = *ws.m_ptx;
584 const TxId &txid = ws.m_ptx->GetId();
587 const int64_t nAcceptTime = args.m_accept_time;
588 const bool bypass_limits = args.m_bypass_limits;
589 std::vector<COutPoint> &coins_to_uncache = args.m_coins_to_uncache;
590 const unsigned int heightOverride = args.m_heightOverride;
602 if (m_pool.m_opts.require_standard &&
604 m_pool.m_opts.permit_bare_multisig,
605 m_pool.m_opts.dust_relay_feerate, reason)) {
614 *
Assert(m_active_chainstate.m_chain.Tip()),
615 args.m_config.GetChainParams().GetConsensus(), tx, ctxState)) {
624 if (m_pool.exists(txid)) {
626 "txn-already-in-mempool");
630 for (
const CTxIn &txin : tx.vin) {
631 if (
const auto ptxConflicting = m_pool.GetConflictTx(txin.prevout)) {
632 if (m_pool.isAvalancheFinalizedPreConsensus(
633 ptxConflicting->GetId())) {
635 "finalized-tx-conflict");
640 "txn-mempool-conflict");
644 m_view.SetBackend(m_viewmempool);
648 for (
const CTxIn &txin : tx.vin) {
650 coins_to_uncache.push_back(txin.prevout);
657 if (!m_view.HaveCoin(txin.prevout)) {
659 for (
size_t out = 0;
out < tx.vout.size();
out++) {
664 "txn-already-known");
671 "bad-txns-inputs-missingorspent");
676 if (!m_view.HaveInputs(tx)) {
678 "bad-txns-inputs-spent");
682 m_view.GetBestBlock();
687 m_view.SetBackend(m_dummy);
689 assert(m_active_chainstate.m_blockman.LookupBlockIndex(
690 m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
699 m_active_chainstate.m_chain.Tip(), m_view, tx)};
700 if (!lock_points.has_value() ||
710 m_active_chainstate.m_chain.Height() + 1,
717 if (m_pool.m_opts.require_standard &&
720 "bad-txns-nonstandard-inputs");
724 ws.m_modified_fees = ws.m_base_fees;
725 m_pool.ApplyDelta(txid, ws.m_modified_fees);
727 unsigned int nSize = tx.GetTotalSize();
730 const uint32_t scriptVerifyFlags =
734 ws.m_precomputed_txdata, GetValidationCache(),
735 ws.m_sig_checks_standard)) {
740 ws.m_entry = std::make_unique<CTxMemPoolEntry>(
741 ptx, ws.m_base_fees, nAcceptTime,
742 heightOverride ? heightOverride : m_active_chainstate.m_chain.Height(),
743 ws.m_sig_checks_standard, lock_points.value());
745 ws.m_vsize = ws.m_entry->GetTxVirtualSize();
753 if (!bypass_limits &&
755 m_pool.m_opts.min_relay_feerate.GetFee(ws.m_ptx->GetTotalSize())) {
762 m_pool.m_opts.min_relay_feerate.GetFee(nSize)));
767 if (!bypass_limits && !args.m_package_feerates &&
768 !CheckFeeRate(nSize, ws.m_vsize, ws.m_modified_fees, state)) {
775bool MemPoolAccept::ConsensusScriptChecks(
const ATMPArgs &args, Workspace &ws) {
778 const CTransaction &tx = *ws.m_ptx;
779 const TxId &txid = tx.GetId();
793 int nSigChecksConsensus;
795 tx, state, m_view, m_pool, ws.m_next_block_script_verify_flags,
796 ws.m_precomputed_txdata, GetValidationCache(), nSigChecksConsensus,
797 m_active_chainstate.CoinsTip())) {
801 LogPrintf(
"BUG! PLEASE REPORT THIS! CheckInputScripts failed against "
802 "latest-block but not STANDARD flags %s, %s\n",
807 if (ws.m_sig_checks_standard != nSigChecksConsensus) {
812 "%s: BUG! PLEASE REPORT THIS! SigChecks count differed between "
813 "standard and consensus flags in %s\n",
820bool MemPoolAccept::Finalize(
const ATMPArgs &args, Workspace &ws) {
823 const TxId &txid = ws.m_ptx->GetId();
825 const bool bypass_limits = args.m_bypass_limits;
830 m_pool.addUnchecked(entry);
833 Assume(spentCoins.has_value());
835 if (m_pool.m_opts.signals) {
836 m_pool.m_opts.signals->TransactionAddedToMempool(
839 spentCoins.has_value() ? std::make_shared<
const std::vector<Coin>>(
840 std::move(*spentCoins))
842 m_pool.GetAndIncrementSequence());
850 if (!args.m_package_submission && !bypass_limits) {
851 m_pool.LimitSize(m_active_chainstate.CoinsTip());
852 if (!m_pool.exists(txid)) {
862bool MemPoolAccept::SubmitPackage(
863 const ATMPArgs &args, std::vector<Workspace> &workspaces,
865 std::map<TxId, MempoolAcceptResult> &results) {
870 workspaces.cbegin(), workspaces.cend(),
871 [
this](
const auto &ws) { return !m_pool.exists(ws.m_ptx->GetId()); }));
873 bool all_submitted =
true;
880 for (Workspace &ws : workspaces) {
881 if (!ConsensusScriptChecks(args, ws)) {
882 results.emplace(ws.m_ptx->GetId(),
885 all_submitted =
false;
888 strprintf(
"BUG! PolicyScriptChecks succeeded but "
889 "ConsensusScriptChecks failed: %s",
890 ws.m_ptx->GetId().ToString()));
900 if (!Finalize(args, ws)) {
901 results.emplace(ws.m_ptx->GetId(),
904 all_submitted =
false;
906 strprintf(
"BUG! Adding to mempool failed: %s",
907 ws.m_ptx->GetId().ToString()));
913 m_pool.LimitSize(m_active_chainstate.CoinsTip());
915 std::vector<TxId> all_package_txids;
916 all_package_txids.reserve(workspaces.size());
917 std::transform(workspaces.cbegin(), workspaces.cend(),
918 std::back_inserter(all_package_txids),
919 [](
const auto &ws) { return ws.m_ptx->GetId(); });
923 for (Workspace &ws : workspaces) {
924 const auto effective_feerate =
925 args.m_package_feerates
926 ? ws.m_package_feerate
928 static_cast<uint32_t
>(ws.m_vsize)};
929 const auto effective_feerate_txids =
930 args.m_package_feerates ? all_package_txids
931 : std::vector<TxId>({ws.m_ptx->GetId()});
932 results.emplace(ws.m_ptx->GetId(),
935 effective_feerate_txids));
937 return all_submitted;
948 const CBlockIndex *tip = m_active_chainstate.m_chain.Tip();
953 const std::vector<TxId> single_txid{ws.m_ptx->GetId()};
958 if (!PreChecks(args, ws)) {
959 if (ws.m_state.GetResult() ==
964 ws.m_state,
CFeeRate(ws.m_modified_fees, ws.m_vsize),
970 if (!ConsensusScriptChecks(args, ws)) {
974 const TxId txid = ptx->GetId();
984 if (
auto it = m_pool.mapNextTx.lower_bound(COutPoint{txid, 0});
985 it != m_pool.mapNextTx.end() && it->first->GetTxId() == txid) {
986 LogPrintf(
"%s: BUG! PLEASE REPORT THIS! Attempt to add txid %s, but "
987 "its outputs are already spent in the "
991 "txn-child-before-parent");
995 const CFeeRate effective_feerate{ws.m_modified_fees,
996 static_cast<uint32_t
>(ws.m_vsize)};
998 if (args.m_test_accept) {
1000 effective_feerate, single_txid);
1003 if (!Finalize(args, ws)) {
1007 Assume(ws.m_state.GetResult() ==
1010 ws.m_state,
CFeeRate(ws.m_modified_fees, ws.m_vsize), single_txid);
1014 effective_feerate, single_txid);
1018 const std::vector<CTransactionRef> &txns, ATMPArgs &args) {
1028 std::vector<Workspace> workspaces{};
1029 workspaces.reserve(txns.size());
1031 txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1032 [
this](
const auto &tx) {
1034 tx, GetNextBlockScriptFlags(m_active_chainstate.m_chain.Tip(),
1035 m_active_chainstate.m_chainman));
1037 std::map<TxId, MempoolAcceptResult> results;
1043 std::vector<TxId> valid_txids;
1044 for (Workspace &ws : workspaces) {
1045 if (!PreChecks(args, ws)) {
1047 "transaction failed");
1050 results.emplace(ws.m_ptx->GetId(),
1053 std::move(results));
1057 m_viewmempool.PackageAddTransaction(ws.m_ptx);
1058 valid_txids.push_back(ws.m_ptx->GetId());
1073 const auto m_total_size = std::accumulate(
1074 workspaces.cbegin(), workspaces.cend(), int64_t{0},
1075 [](int64_t
sum,
auto &ws) { return sum + ws.m_ptx->GetTotalSize(); });
1076 const auto m_total_vsize =
1077 std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1078 [](int64_t
sum,
auto &ws) { return sum + ws.m_vsize; });
1079 const auto m_total_modified_fees = std::accumulate(
1080 workspaces.cbegin(), workspaces.cend(),
Amount::zero(),
1081 [](
Amount sum,
auto &ws) { return sum + ws.m_modified_fees; });
1082 const CFeeRate package_feerate(m_total_modified_fees, m_total_vsize);
1083 std::vector<TxId> all_package_txids;
1084 all_package_txids.reserve(workspaces.size());
1085 std::transform(workspaces.cbegin(), workspaces.cend(),
1086 std::back_inserter(all_package_txids),
1087 [](
const auto &ws) { return ws.m_ptx->GetId(); });
1089 if (args.m_package_feerates &&
1090 !CheckFeeRate(m_total_size, m_total_vsize, m_total_modified_fees,
1091 placeholder_state)) {
1093 "transaction failed");
1095 package_state, {{workspaces.back().m_ptx->GetId(),
1098 CFeeRate(m_total_modified_fees, m_total_vsize),
1099 all_package_txids)}});
1102 for (Workspace &ws : workspaces) {
1103 ws.m_package_feerate = package_feerate;
1104 const TxId &ws_txid = ws.m_ptx->GetId();
1105 if (args.m_test_accept &&
1106 std::find(valid_txids.begin(), valid_txids.end(), ws_txid) !=
1107 valid_txids.end()) {
1108 const auto effective_feerate =
1109 args.m_package_feerates
1110 ? ws.m_package_feerate
1112 static_cast<uint32_t
>(ws.m_vsize)};
1113 const auto effective_feerate_txids =
1114 args.m_package_feerates ? all_package_txids
1115 : std::vector<TxId>{ws.m_ptx->GetId()};
1119 results.emplace(ws_txid,
1121 ws.m_vsize, ws.m_base_fees, effective_feerate,
1122 effective_feerate_txids));
1126 if (args.m_test_accept) {
1130 if (!SubmitPackage(args, workspaces, package_state, results)) {
1139MemPoolAccept::AcceptSubPackage(
const std::vector<CTransactionRef> &subpackage,
1145 if (subpackage.size() > 1) {
1146 return AcceptMultipleTransactions(subpackage, args);
1148 const auto &tx = subpackage.front();
1149 ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1150 const auto single_res = AcceptSingleTransaction(tx, single_args);
1152 if (single_res.m_result_type !=
1155 "transaction failed");
1158 {{tx->GetId(), single_res}});
1188 for (
const auto &outpoint : m_viewmempool.GetNonBaseCoins()) {
1192 m_view.Uncache(outpoint);
1195 m_viewmempool.Reset();
1211 if (!
CheckPackage(package, package_state_quit_early)) {
1220 "package-not-child-with-parents");
1225 assert(package.size() > 1);
1228 const auto &child = package.back();
1229 std::unordered_set<TxId, SaltedTxIdHasher> unconfirmed_parent_txids;
1231 package.cbegin(), package.cend() - 1,
1232 std::inserter(unconfirmed_parent_txids, unconfirmed_parent_txids.end()),
1233 [](
const auto &tx) { return tx->GetId(); });
1242 const CCoinsViewCache &coins_tip_cache = m_active_chainstate.CoinsTip();
1243 for (
const auto &input : child->vin) {
1245 args.m_coins_to_uncache.push_back(input.prevout);
1252 m_view.
SetBackend(m_active_chainstate.CoinsTip());
1253 const auto package_or_confirmed = [
this, &unconfirmed_parent_txids](
1254 const auto &input) {
1255 return unconfirmed_parent_txids.count(input.prevout.GetTxId()) > 0 ||
1256 m_view.HaveCoin(input.prevout);
1258 if (!std::all_of(child->vin.cbegin(), child->vin.cend(),
1259 package_or_confirmed)) {
1260 package_state_quit_early.
Invalid(
1262 "package-not-child-with-unconfirmed-parents");
1268 m_view.SetBackend(m_dummy);
1274 std::map<TxId, MempoolAcceptResult> results_final;
1279 std::map<TxId, MempoolAcceptResult> individual_results_nonfinal;
1280 bool quit_early{
false};
1281 std::vector<CTransactionRef> txns_package_eval;
1282 for (
const auto &tx : package) {
1283 const auto &txid = tx->GetId();
1286 if (m_pool.exists(txid)) {
1300 auto iter = m_pool.GetIter(txid);
1301 assert(iter != std::nullopt);
1303 (*iter.value())->GetTxSize(),
1304 (*iter.value())->GetFee()));
1308 const auto single_package_res = AcceptSubPackage({tx}, args);
1309 const auto &single_res = single_package_res.m_tx_results.at(txid);
1310 if (single_res.m_result_type ==
1315 assert(m_pool.exists(txid));
1316 results_final.emplace(txid, single_res);
1317 }
else if (single_res.m_state.GetResult() !=
1319 single_res.m_state.GetResult() !=
1334 package_state_quit_early.
Invalid(
1336 individual_results_nonfinal.emplace(txid, single_res);
1338 individual_results_nonfinal.emplace(txid, single_res);
1339 txns_package_eval.push_back(tx);
1344 auto multi_submission_result =
1345 quit_early || txns_package_eval.empty()
1347 : AcceptSubPackage(txns_package_eval, args);
1349 multi_submission_result.m_state;
1354 m_pool.LimitSize(m_active_chainstate.CoinsTip());
1356 for (
const auto &tx : package) {
1357 const auto &txid = tx->GetId();
1358 if (multi_submission_result.m_tx_results.count(txid) > 0) {
1361 Assume(results_final.count(txid) == 0);
1365 const auto &txresult =
1366 multi_submission_result.m_tx_results.at(txid);
1367 if (txresult.m_result_type ==
1369 !m_pool.exists(txid)) {
1371 "transaction failed");
1375 results_final.emplace(
1378 results_final.emplace(txid, txresult);
1380 }
else if (
const auto final_it{results_final.find(txid)};
1381 final_it != results_final.end()) {
1384 Assume(final_it->second.m_result_type !=
1386 Assume(individual_results_nonfinal.count(txid) == 0);
1387 if (!m_pool.exists(tx->GetId())) {
1389 "transaction failed");
1394 results_final.erase(txid);
1395 results_final.emplace(
1398 }
else if (
const auto non_final_it{
1399 individual_results_nonfinal.find(txid)};
1400 non_final_it != individual_results_nonfinal.end()) {
1401 Assume(non_final_it->second.m_result_type ==
1404 results_final.emplace(txid, non_final_it->second);
1407 Assume(results_final.size() == package.size());
1409 std::move(results_final));
1415 int64_t accept_time,
bool bypass_limits,
1417 unsigned int heightOverride) {
1422 std::vector<COutPoint> coins_to_uncache;
1423 auto args = MemPoolAccept::ATMPArgs::SingleAccept(
1425 coins_to_uncache, test_accept, heightOverride);
1427 .AcceptSingleTransaction(tx, args);
1435 for (
const COutPoint &outpoint : coins_to_uncache) {
1452 assert(!package.empty());
1453 assert(std::all_of(package.cbegin(), package.cend(),
1454 [](
const auto &tx) { return tx != nullptr; }));
1458 std::vector<COutPoint> coins_to_uncache;
1462 auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(
1463 config,
GetTime(), coins_to_uncache);
1464 return MemPoolAccept(pool, active_chainstate)
1465 .AcceptMultipleTransactions(package, args);
1467 auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(
1468 config,
GetTime(), coins_to_uncache);
1469 return MemPoolAccept(pool, active_chainstate)
1470 .AcceptPackage(package, args);
1476 if (test_accept || result.m_state.IsInvalid()) {
1477 for (
const COutPoint &hashTx : coins_to_uncache) {
1490 if (halvings >= 64) {
1501 : m_dbview{
std::move(db_params),
std::move(options)},
1502 m_catcherview(&m_dbview) {}
1504void CoinsViews::InitCache() {
1506 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1507 m_connect_block_view = std::make_unique<CCoinsViewCache>(&*m_cacheview);
1512 std::optional<BlockHash> from_snapshot_blockhash)
1513 : m_mempool(mempool), m_blockman(blockman), m_chainman(chainman),
1514 m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1520 if (!m_cached_snapshot_base) {
1521 m_cached_snapshot_base =
Assert(
1524 return m_cached_snapshot_base;
1528 bool should_wipe, std::string leveldb_name) {
1535 .cache_bytes = cache_size_bytes,
1536 .memory_only = in_memory,
1537 .wipe_data = should_wipe,
1543void Chainstate::InitCoinsCache(
size_t cache_size_bytes) {
1569 if (chain.Tip() ==
nullptr) {
1578 LogPrintf(
"Leaving InitialBlockDownload (latching to false)\n");
1605 std::string warning =
1606 std::string(
"'Warning: Large-work fork detected, forking after "
1613 LogPrintf(
"%s: Warning: Large fork found\n forking the "
1614 "chain at height %d (%s)\n lasting to height %d "
1615 "(%s).\nChain state database corruption likely.\n",
1622 LogPrintf(
"%s: Warning: Found invalid chain at least ~6 blocks "
1623 "longer than our best chain.\nChain state database "
1624 "corruption likely.\n",
1669 SetBlockFailureFlags(pindexNew);
1680 m_avalancheFinalizedBlockIndex = pindexNew->
pprev;
1683 LogPrintf(
"%s: invalid block=%s height=%d log2_work=%f date=%s\n",
1690 LogPrintf(
"%s: current best=%s height=%d log2_work=%f date=%s\n",
1702 pindex->nStatus = pindex->nStatus.withFailed();
1712 if (tx.IsCoinBase()) {
1716 txundo.
vprevout.reserve(tx.vin.size());
1717 for (
const CTxIn &txin : tx.vin) {
1730std::optional<std::vector<Coin>>
1732 std::vector<Coin> spent_coins;
1733 spent_coins.reserve(ptx->vin.size());
1734 for (
const CTxIn &input : ptx->vin) {
1735 auto coin{coins_view.
GetCoin(input.prevout)};
1736 if (!coin.has_value()) {
1737 return std::nullopt;
1739 spent_coins.push_back(std::move(*coin));
1745 const CScript &scriptSig =
ptxTo->vin[
nIn].scriptSig;
1747 auto debug_str =
strprintf(
"input %i of %s, spending %s:%i",
nIn,
1748 ptxTo->GetId().ToString(),
1749 ptxTo->vin[
nIn].prevout.GetTxId().ToString(),
1756 return std::make_pair(error, std::move(debug_str));
1766 std::move(debug_str));
1768 return std::nullopt;
1772 const size_t signature_cache_bytes)
1773 : m_signature_cache{signature_cache_bytes} {
1782 const auto [num_elems, approx_size_bytes] =
1784 LogPrintf(
"Using %zu MiB out of %zu MiB requested for script execution "
1785 "cache, able to store %zu elements\n",
1786 approx_size_bytes >> 20, script_execution_cache_bytes >> 20,
1792 bool sigCacheStore,
bool scriptCacheStore,
1797 std::vector<CScriptCheck> *pvChecks) {
1799 assert(!tx.IsCoinBase());
1802 pvChecks->reserve(tx.vin.size());
1813 elem, !scriptCacheStore);
1815 if (found_in_cache) {
1817 (pBlockLimitSigChecks &&
1820 "too-many-sigchecks");
1825 int nSigChecksTotal = 0;
1827 for (
size_t i = 0; i < tx.vin.size(); i++) {
1828 const COutPoint &prevout = tx.vin[i].prevout;
1841 sigCacheStore, txdata, &txLimitSigChecks, pBlockLimitSigChecks);
1845 pvChecks->push_back(std::move(check));
1849 if (
auto result = check(); result.has_value()) {
1854 uint32_t mandatoryFlags =
1855 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS;
1856 if (
flags != mandatoryFlags) {
1864 mandatoryFlags, sigCacheStore, txdata);
1865 auto mandatory_result = check2();
1866 if (!mandatory_result.has_value()) {
1869 strprintf(
"non-mandatory-script-verify-flag (%s)",
1880 result = mandatory_result;
1892 strprintf(
"mandatory-script-verify-flag-failed (%s)",
1900 nSigChecksOut = nSigChecksTotal;
1902 if (scriptCacheStore && !pvChecks) {
1913 const std::string &strMessage,
1915 notifications.
fatalError(strMessage, userMessage);
1916 return state.
Error(strMessage);
1921 const COutPoint &
out) {
1929 if (undo.GetHeight() == 0) {
1967 LogError(
"DisconnectBlock(): failure reading undo data\n");
1971 return ApplyBlockUndo(std::move(blockUndo), block, pindex, view);
1979 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size()) {
1980 LogError(
"DisconnectBlock(): block and undo data inconsistent\n");
1985 for (
size_t i = 1; i < block.
vtx.size(); i++) {
1986 const CTransaction &tx = *(block.
vtx[i]);
1988 if (txundo.
vprevout.size() != tx.vin.size()) {
1990 "DisconnectBlock(): transaction and undo data inconsistent\n");
1994 for (
size_t j = 0; j < tx.vin.size(); j++) {
1995 const COutPoint &
out = tx.vin[j].prevout;
2007 for (
const auto &ptx : block.
vtx) {
2008 const CTransaction &tx = *ptx;
2009 const TxId &txid = tx.GetId();
2010 const bool is_coinbase = tx.IsCoinBase();
2014 for (
size_t o = 0; o < tx.vout.size(); o++) {
2015 if (tx.vout[o].scriptPubKey.IsUnspendable()) {
2019 COutPoint
out(txid, o);
2022 if (!is_spent || tx.vout[o] != coin.
GetTxOut() ||
2101 consensusparams, pindex,
2133 const auto time_start{SteadyClock::now()};
2150 if (!
CheckBlock(block, state, consensusParams,
2158 "Corrupt block found indicating potential "
2159 "hardware failure; shutting down");
2182 bool fScriptChecks =
true;
2191 BlockMap::const_iterator it{
2194 if (it->second.GetAncestor(pindex->
nHeight) == pindex &&
2222 consensusParams) <= 60 * 60 * 24 * 7 * 2);
2227 const auto time_1{SteadyClock::now()};
2230 Ticks<MillisecondsDouble>(time_1 - time_start),
2245 bool fEnforceBIP30 = !((pindex->
nHeight == 91842 &&
2247 uint256S(
"0x00000000000a4d0a398161ffc163c503763"
2248 "b1f4360639393e0e4c8e300e0caec")) ||
2251 uint256S(
"0x00000000000743f190a18c5577a3c2d2a1f"
2252 "610ae9601ac046a38084ccb7cd721")));
2283 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2320 (!pindexBIP34height ||
2326 if (fEnforceBIP30 || pindex->
nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2327 for (
const auto &tx : block.
vtx) {
2328 for (
size_t o = 0; o < tx->vout.size(); o++) {
2329 if (view.
HaveCoin(COutPoint(tx->GetId(), o))) {
2332 "tried to overwrite transaction");
2339 int nLockTimeFlags = 0;
2347 const auto time_2{SteadyClock::now()};
2350 Ticks<MillisecondsDouble>(time_2 - time_1),
2354 std::vector<int> prevheights;
2366 std::vector<TxSigCheckLimiter> nSigChecksTxLimiters;
2367 nSigChecksTxLimiters.resize(block.
vtx.size() - 1);
2370 blockundo.
vtxundo.resize(block.
vtx.size() - 1);
2377 for (
const auto &ptx : block.
vtx) {
2380 }
catch (
const std::logic_error &e) {
2390 "tx-duplicate",
"tried to overwrite transaction");
2397 for (
const auto &ptx : block.
vtx) {
2398 const CTransaction &tx = *ptx;
2399 const bool isCoinBase = tx.IsCoinBase();
2400 nInputs += tx.vin.size();
2413 tx.GetId().ToString());
2421 "bad-txns-accumulated-fee-outofrange",
2422 "accumulated fee in the block out of range");
2434 prevheights.resize(tx.vin.size());
2435 for (
size_t j = 0; j < tx.vin.size(); j++) {
2439 if (!
SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2441 "bad-txns-nonfinal",
2442 "contains a non-BIP68-final transaction " +
2443 tx.GetHash().ToString());
2449 bool fCacheResults = fJustCheck;
2452 if (!fEnforceSigCheck) {
2459 std::vector<CScriptCheck> vChecks;
2461 if (fScriptChecks &&
2465 nSigChecksTxLimiters[txIndex],
2466 &nSigChecksBlockLimiter, &vChecks)) {
2475 control.
Add(std::move(vChecks));
2485 const auto time_3{SteadyClock::now()};
2488 " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) "
2489 "[%.2fs (%.2fms/blk)]\n",
2490 (
unsigned)block.
vtx.size(),
2491 Ticks<MillisecondsDouble>(time_3 - time_2),
2492 Ticks<MillisecondsDouble>(time_3 - time_2) / block.
vtx.size(),
2495 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2499 const Amount blockReward =
2501 if (block.
vtx[0]->GetValueOut() > blockReward && state.
IsValid()) {
2504 strprintf(
"coinbase pays too much (actual=%d vs limit=%d)",
2505 block.
vtx[0]->GetValueOut(), blockReward));
2512 auto parallel_result = control.
Complete();
2513 if (parallel_result.has_value() && state.
IsValid()) {
2515 strprintf(
"mandatory-script-verify-flag-failed (%s)",
2517 parallel_result->second);
2523 const auto time_4{SteadyClock::now()};
2527 " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n",
2528 nInputs - 1, Ticks<MillisecondsDouble>(time_4 - time_2),
2531 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2539 if (!
m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2551 const auto time_5{SteadyClock::now()};
2554 Ticks<MillisecondsDouble>(time_5 - time_4),
2558 TRACE6(validation, block_connected, block_hash.data(), pindex->
nHeight,
2559 block.
vtx.size(), nInputs, nSigChecksRet,
2561 time_5 - time_start);
2568 return this->GetCoinsCacheSizeState(
2574Chainstate::GetCoinsCacheSizeState(
size_t max_coins_cache_size_bytes,
2575 size_t max_mempool_size_bytes) {
2579 int64_t nTotalSpace =
2580 max_coins_cache_size_bytes +
2581 std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2584 static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES =
2586 int64_t large_threshold = std::max(
2587 (9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2589 if (cacheSize > nTotalSpace) {
2590 LogPrintf(
"Cache size (%s) exceeds total space (%s)\n", cacheSize,
2593 }
else if (cacheSize > large_threshold) {
2603 std::set<int> setFilesToPrune;
2604 bool full_flush_completed =
false;
2607 [[maybe_unused]]
const size_t coins_mem_usage{
2612 bool fFlushForPrune =
false;
2624 std::optional<std::string> limiting_lock;
2626 for (
const auto &prune_lock :
m_blockman.m_prune_locks) {
2627 if (prune_lock.second.height_first ==
2628 std::numeric_limits<int>::max()) {
2633 const int lock_height{prune_lock.second.height_first -
2635 last_prune = std::max(1, std::min(last_prune, lock_height));
2636 if (last_prune == lock_height) {
2637 limiting_lock = prune_lock.first;
2641 if (limiting_lock) {
2643 limiting_lock.value(), last_prune);
2646 if (nManualPruneHeight > 0) {
2651 std::min(last_prune, nManualPruneHeight), *
this,
2660 if (!setFilesToPrune.empty()) {
2661 fFlushForPrune =
true;
2664 "prunedblockfiles",
true);
2680 bool fPeriodicWrite =
2684 fCacheLarge || fCacheCritical ||
2685 fPeriodicWrite || fFlushForPrune;
2691 "Disk space is too low!",
2692 _(
"Disk space is too low!"));
2706 "%s: Failed to flush block file.\n",
2720 if (fFlushForPrune) {
2727 if (!
CoinsTip().GetBestBlock().IsNull()) {
2738 "Disk space is too low!",
2739 _(
"Disk space is too low!"));
2745 fCacheLarge || fCacheCritical};
2747 full_flush_completed =
true;
2749 int64_t{Ticks<std::chrono::microseconds>(
2750 SteadyClock::now() - nNow)},
2751 uint32_t(mode), coins_count,
2752 uint64_t(coins_mem_usage), fFlushForPrune);
2756 if (should_write ||
m_next_write == NodeClock::time_point::max()) {
2769 }
catch (
const std::runtime_error &e) {
2771 std::string(
"System error while flushing: ") +
2780 LogPrintf(
"%s: failed to flush state (%s)\n", __func__,
2789 LogPrintf(
"%s: failed to flush state (%s)\n", __func__,
2796 const std::string &func_name,
2797 const std::string &
prefix)
2806 "%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%ld "
2807 "date='%s' progress=%f cache=%.1fMiB(%utxo)\n",
2816void Chainstate::UpdateTip(
const CBlockIndex *pindexNew) {
2818 const auto &coins_tip =
CoinsTip();
2827 constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2828 if (pindexNew->
nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2830 "[background validation] ");
2846 UpdateTipLog(coins_tip, pindexNew, params, __func__,
"");
2873 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2876 LogError(
"DisconnectTip(): Failed to read block\n");
2881 const auto time_start{SteadyClock::now()};
2885 if (DisconnectBlock(block, pindexDelete, view) !=
2887 LogError(
"DisconnectTip(): DisconnectBlock %s failed\n",
2896 Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
2901 const int max_height_first{pindexDelete->
nHeight - 1};
2902 for (
auto &prune_lock :
m_blockman.m_prune_locks) {
2903 if (prune_lock.second.height_first <= max_height_first) {
2907 prune_lock.second.height_first = max_height_first;
2909 prune_lock.first, max_height_first);
2922 if (pindexDelete->
pprev !=
nullptr &&
2926 "Disconnecting mempool due to rewind of upgrade block\n");
2927 if (disconnectpool) {
2933 if (disconnectpool) {
2940 UpdateTip(pindexDelete->
pprev);
2961 const std::shared_ptr<const CBlock> &pblock,
2974 const auto time_1{SteadyClock::now()};
2975 std::shared_ptr<const CBlock> pthisBlock;
2977 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2980 "Failed to read block");
2982 pthisBlock = pblockNew;
2984 pthisBlock = pblock;
2987 const CBlock &blockConnecting = *pthisBlock;
2990 const auto time_2{SteadyClock::now()};
2991 SteadyClock::time_point time_3;
2995 Ticks<MillisecondsDouble>(time_2 - time_1));
3000 bool rv =
ConnectBlock(blockConnecting, state, pindexNew, view,
3011 LogError(
"%s: ConnectBlock %s failed, %s\n", __func__,
3032 const Amount blockReward =
3036 std::vector<std::unique_ptr<ParkingPolicy>> parkingPolicies;
3037 parkingPolicies.emplace_back(std::make_unique<MinerFundPolicy>(
3038 consensusParams, *pindexNew, blockConnecting, blockReward));
3054 parkingPolicies.emplace_back(
3055 std::make_unique<RTTPolicy>(consensusParams,
3060 parkingPolicies.emplace_back(
3061 std::make_unique<StakingRewardsPolicy>(
3062 *
avalanche, consensusParams, *pindexNew,
3063 blockConnecting, blockReward));
3066 parkingPolicies.emplace_back(
3067 std::make_unique<PreConsensusPolicy>(
3074 if (std::find_if_not(parkingPolicies.begin(), parkingPolicies.end(),
3075 [&](
const auto &policy) {
3076 bool ret = (*policy)(blockPolicyState);
3079 "Park block because it "
3080 "violated a block policy: %s\n",
3081 blockPolicyState.ToString());
3084 }) != parkingPolicies.end()) {
3085 pindexNew->nStatus = pindexNew->nStatus.withParked();
3091 time_3 = SteadyClock::now();
3095 BCLog::BENCH,
" - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3096 Ticks<MillisecondsDouble>(time_3 - time_2),
3103 const auto time_4{SteadyClock::now()};
3106 Ticks<MillisecondsDouble>(time_4 - time_3),
3113 const auto time_5{SteadyClock::now()};
3116 " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3117 Ticks<MillisecondsDouble>(time_5 - time_4),
3122 disconnectpool.removeForBlock(blockConnecting.vtx, *m_mempool);
3127 if (pindexNew->
pprev !=
nullptr &&
3132 "Disconnecting mempool due to acceptance of upgrade block\n");
3133 disconnectpool.importMempool(*m_mempool);
3138 m_chain.SetTip(*pindexNew);
3139 UpdateTip(pindexNew);
3141 const auto time_6{SteadyClock::now()};
3145 " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3146 Ticks<MillisecondsDouble>(time_6 - time_5),
3150 Ticks<MillisecondsDouble>(time_6 - time_1),
3157 if (
this != &m_chainman.ActiveChainstate()) {
3161 m_chainman.MaybeCompleteSnapshotValidation();
3164 if (m_chainman.m_options.signals) {
3165 m_chainman.m_options.signals->BlockConnected(chainstate_role,
3166 pthisBlock, pindexNew);
3176 std::vector<const CBlockIndex *> &blocksToReconcile,
bool fAutoUnpark) {
3183 std::set<CBlockIndex *, CBlockIndexWorkComparator>::reverse_iterator
3195 if (m_avalancheFinalizedBlockIndex &&
3197 LogPrintf(
"Park block %s because it forks prior to the "
3198 "avalanche finalized chaintip.\n",
3200 pindexNew->nStatus = pindexNew->nStatus.withParked();
3211 bool hasValidAncestor =
true;
3212 while (hasValidAncestor && pindexTest && pindexTest != pindexFork) {
3217 bool fParkedChain = pindexTest->nStatus.isOnParkedChain();
3218 if (fAutoUnpark && fParkedChain) {
3224 if (!pindexTip || !pindexFork) {
3238 pindexExtraPow = pindexExtraPow->
pprev;
3243 requiredWork += (deltaWork >> 1);
3254 LogPrintf(
"Unpark chain up to block %s as it has "
3255 "accumulated enough PoW.\n",
3257 fParkedChain =
false;
3266 bool fInvalidChain = pindexTest->nStatus.isInvalid();
3267 bool fMissingData = !pindexTest->nStatus.hasData();
3268 if (!(fInvalidChain || fParkedChain || fMissingData)) {
3271 pindexTest = pindexTest->
pprev;
3277 hasValidAncestor =
false;
3280 if (fInvalidChain && (
m_chainman.m_best_invalid ==
nullptr ||
3286 if (fParkedChain && (
m_chainman.m_best_parked ==
nullptr ||
3292 LogPrintf(
"Considered switching to better tip %s but that chain "
3293 "contains a%s%s%s block.\n",
3295 fInvalidChain ?
"n invalid" :
"",
3296 fParkedChain ?
" parked" :
"",
3297 fMissingData ?
" missing-data" :
"");
3301 while (pindexTest != pindexFailed) {
3302 if (fInvalidChain || fParkedChain) {
3303 pindexFailed->nStatus =
3304 pindexFailed->nStatus.withFailedParent(fInvalidChain)
3305 .withParkedParent(fParkedChain);
3307 }
else if (fMissingData) {
3313 std::make_pair(pindexFailed->
pprev, pindexFailed));
3316 pindexFailed = pindexFailed->
pprev;
3319 if (fInvalidChain || fParkedChain) {
3326 blocksToReconcile.push_back(pindexNew);
3329 if (hasValidAncestor) {
3362 const std::shared_ptr<const CBlock> &pblock,
bool &fInvalidFound,
3374 bool fBlocksDisconnected =
false;
3377 if (
m_mempool && !fBlocksDisconnected) {
3396 "Failed to disconnect block; see debug.log for details");
3400 fBlocksDisconnected =
true;
3404 std::vector<CBlockIndex *> vpindexToConnect;
3405 bool fContinue =
true;
3410 int nTargetHeight = std::min(
nHeight + 32, pindexMostWork->
nHeight);
3411 vpindexToConnect.clear();
3412 vpindexToConnect.reserve(nTargetHeight -
nHeight);
3415 vpindexToConnect.push_back(pindexIter);
3416 pindexIter = pindexIter->
pprev;
3424 if (!
ConnectTip(state, blockPolicyState, pindexConnect,
3425 pindexConnect == pindexMostWork
3427 : std::shared_ptr<const CBlock>(),
3428 disconnectpool,
avalanche, chainstate_role)) {
3436 fInvalidFound =
true;
3443 CBlockIndex *pindexParkedDescendant = pindexMostWork;
3444 while (pindexParkedDescendant &&
3445 pindexParkedDescendant != pindexConnect) {
3446 pindexParkedDescendant->nStatus =
3447 pindexParkedDescendant->nStatus.withParkedParent();
3449 pindexParkedDescendant);
3451 pindexParkedDescendant = pindexParkedDescendant->
pprev;
3467 if (!pindexOldTip ||
3479 if (fBlocksDisconnected || !disconnectpool.
isEmpty()) {
3485 "Updating mempool due to reorganization or "
3486 "rules upgrade/downgrade\n");
3494 if (fInvalidFound) {
3516 bool fNotify =
false;
3517 bool fInitialBlockDownload =
false;
3522 pindexHeader = chainman.m_best_header;
3524 if (pindexHeader != pindexHeaderOld) {
3526 fInitialBlockDownload = chainman.IsInitialBlockDownload();
3527 pindexHeaderOld = pindexHeader;
3533 chainman.GetNotifications().headerTip(
3535 chainman.m_blockman.m_reindexing),
3545 if (signals.CallbacksPending() > 10) {
3546 signals.SyncWithValidationInterfaceQueue();
3551 std::shared_ptr<const CBlock> pblock,
3572 LogPrintf(
"m_disabled is set - this chainstate should not be in "
3573 "operation. Please report this as a bug. %s\n",
3580 bool exited_ibd{
false};
3592 std::vector<const CBlockIndex *> blocksToReconcile;
3593 bool blocks_connected =
false;
3607 if (pindexMostWork ==
nullptr) {
3614 if (pindexMostWork ==
nullptr ||
3619 bool fInvalidFound =
false;
3620 std::shared_ptr<const CBlock> nullBlockPtr;
3627 state, pindexMostWork,
3628 pblock && pblock->GetHash() ==
3632 fInvalidFound,
avalanche, chainstate_role)) {
3636 blocks_connected =
true;
3638 if (fInvalidFound ||
3640 pindexMostWork->nStatus.isOnParkedChain())) {
3642 pindexMostWork =
nullptr;
3667 if (blocks_connected) {
3671 if (was_in_ibd && !still_in_ibd) {
3680 pindexFork != pindexNewTip) {
3684 pindexNewTip, pindexFork, still_in_ibd);
3708 return m_avalancheFinalizedBlockIndex);
3709 for (
const CBlockIndex *pindex : blocksToReconcile) {
3715 if (blocks_connected) {
3717 while (pindexTest && pindexTest != pfinalized) {
3722 avalanche->computeStakingReward(pindexTest);
3723 pindexTest = pindexTest->
pprev;
3729 if (!blocks_connected) {
3766 }
while (pindexNewTip != pindexMostWork);
3797 std::numeric_limits<int32_t>::min()) {
3819template <
typename Func>
struct Defer {
3821 Defer(
Func &&f) : func(
std::move(f)) {}
3822 ~Defer() { func(); }
3835 bool pindex_was_in_chain =
false;
3836 int disconnected = 0;
3852 std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
3856 for (
auto &entry :
m_blockman.m_block_index) {
3867 candidate_blocks_by_work.insert(
3868 std::make_pair(candidate->
nChainWork, candidate));
3880 constexpr int maxDisconnectPoolBlocks = 10;
3932 pindex_was_in_chain =
true;
3941 if (optDisconnectPool && disconnected > maxDisconnectPoolBlocks) {
3946 optDisconnectPool =
nullptr;
3962 invalid_walk_tip->nStatus =
3963 invalidate ? invalid_walk_tip->nStatus.withFailed()
3964 : invalid_walk_tip->nStatus.withParked();
3969 if (invalid_walk_tip == to_mark_failed_or_parked->
pprev &&
3970 (invalidate ? to_mark_failed_or_parked->nStatus.hasFailed()
3971 : to_mark_failed_or_parked->nStatus.isParked())) {
3975 to_mark_failed_or_parked->nStatus =
3977 ? to_mark_failed_or_parked->nStatus.withFailed(
false)
3979 : to_mark_failed_or_parked->nStatus.withParked(
false)
3980 .withParkedParent());
3986 auto candidate_it = candidate_blocks_by_work.lower_bound(
3988 while (candidate_it != candidate_blocks_by_work.end()) {
3990 invalid_walk_tip->
pprev)) {
3992 candidate_it = candidate_blocks_by_work.erase(candidate_it);
4001 to_mark_failed_or_parked = invalid_walk_tip;
4017 to_mark_failed_or_parked->nStatus =
4018 invalidate ? to_mark_failed_or_parked->nStatus.withFailed()
4019 : to_mark_failed_or_parked->nStatus.withParked();
4032 for (
auto &[
_, block_index] :
m_blockman.m_block_index) {
4034 block_index.HaveNumChainTxs() &&
4047 if (pindex_was_in_chain) {
4058 *to_mark_failed_or_parked->
pprev);
4082template <
typename F>
4086 if (pindex->nStatus != newStatus &&
4089 pindex->nStatus = newStatus;
4105template <
typename F,
typename C,
typename AC>
4107 F f, C fChild, AC fAncestorWasChanged) {
4113 for (
auto pindexAncestor = pindex; pindexAncestor !=
nullptr;
4114 pindexAncestor = pindexAncestor->
pprev) {
4116 pindexDeepestChanged = pindexAncestor;
4122 pindexDeepestChanged) {
4124 pindexReset =
nullptr;
4128 for (
auto &[
_, block_index] :
m_blockman.m_block_index) {
4131 fAncestorWasChanged);
4135void Chainstate::SetBlockFailureFlags(
CBlockIndex *invalid_block) {
4138 for (
auto &[
_, block_index] :
m_blockman.m_block_index) {
4139 if (block_index.GetAncestor(invalid_block->
nHeight) == invalid_block &&
4140 !block_index.nStatus.isInvalid()) {
4141 block_index.nStatus = block_index.nStatus.withFailedParent();
4152 return status.withClearedFailureFlags();
4155 return status.withClearedFailureFlags();
4158 return status.withFailedParent(false);
4172 if (is_active_chainstate) {
4176 }
else if (!m_disabled) {
4182 if (snapshot_base->GetAncestor(pindex->
nHeight) == pindex) {
4194 return status.withClearedParkedFlags();
4197 return fClearChildren ? status.withClearedParkedFlags()
4198 : status.withParkedParent(false);
4201 return status.withParkedParent(false);
4213bool Chainstate::AvalancheFinalizeBlock(
CBlockIndex *pindex,
4224 "The block to mark finalized by avalanche is not on the "
4225 "active chain: %s\n",
4236 m_avalancheFinalizedBlockIndex = pindex;
4248 m_avalancheFinalizedBlockIndex =
nullptr;
4253 return pindex && m_avalancheFinalizedBlockIndex &&
4265 pindexNew->
nTx = block.
vtx.size();
4272 return block.nTx + (block.pprev ? block.pprev->nChainTx : 0);
4275 pindexNew->
nChainTx == prev_tx_sum(*pindexNew) ||
4276 pindexNew == GetSnapshotBaseBlock())) {
4277 LogPrintf(
"Internal bug detected: block %d has unexpected nChainTx %i "
4278 "that should be %i. Please report this issue here: %s\n",
4280 prev_tx_sum(*pindexNew), PACKAGE_BUGREPORT);
4284 pindexNew->nFile = pos.
nFile;
4285 pindexNew->nDataPos = pos.
nPos;
4286 pindexNew->nUndoPos = 0;
4287 pindexNew->nStatus = pindexNew->nStatus.withData();
4294 std::deque<CBlockIndex *> queue;
4295 queue.push_back(pindexNew);
4299 while (!queue.empty()) {
4307 pindex->
nChainTx == prev_tx_sum(*pindex))) {
4309 "Internal bug detected: block %d has unexpected nChainTx "
4310 "%i that should be %i. Please report this issue here: %s\n",
4314 pindex->
nChainTx = prev_tx_sum(*pindex);
4324 c->TryAddBlockIndexCandidate(pindex);
4327 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
4328 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
4330 while (range.first != range.second) {
4331 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it =
4333 queue.push_back(it->second);
4338 }
else if (pindexNew->
pprev &&
4341 std::make_pair(pindexNew->
pprev, pindexNew));
4361 "high-hash",
"proof of work failed");
4378 "hashMerkleRoot mismatch");
4387 "bad-txns-duplicate",
4388 "duplicate transaction");
4420 if (block.
vtx.empty()) {
4422 "bad-cb-missing",
"first tx is not coinbase");
4431 "bad-blk-length",
"size limits failed");
4435 if (currentBlockSize > nMaxBlockSize) {
4437 "bad-blk-length",
"size limits failed");
4445 strprintf(
"Coinbase check failed (txid %s) %s",
4446 block.
vtx[0]->GetId().ToString(),
4452 for (
size_t i = 1; i < block.
vtx.size(); i++) {
4453 auto *tx = block.
vtx[i].get();
4458 strprintf(
"Transaction check failed (txid %s) %s",
4473 return std::all_of(headers.cbegin(), headers.cend(),
4474 [&](
const auto &header) {
4475 return CheckProofOfWork(
4476 header.GetHash(), header.nBits, consensusParams);
4484 "Block mutated: %s\n", state.
ToString());
4488 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase()) {
4496 return std::any_of(block.
vtx.begin(), block.
vtx.end(),
4497 [](
auto &tx) { return GetSerializeSize(tx) == 64; });
4531 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
4534 assert(pindexPrev !=
nullptr);
4535 const int nHeight = pindexPrev->nHeight + 1;
4541 LogPrintf(
"bad bits after height: %d\n", pindexPrev->nHeight);
4543 "bad-diffbits",
"incorrect proof of work");
4547 if (chainman.m_options.checkpoints_enabled) {
4549 test_checkpoints ? test_checkpoints.value() : params.
Checkpoints();
4555 "ERROR: %s: rejected by checkpoint lock-in at %d\n",
4558 "checkpoint mismatch");
4566 blockman.GetLastCheckpoint(checkpoints);
4567 if (pcheckpoint && nHeight < pcheckpoint->
nHeight) {
4569 "ERROR: %s: forked chain older than last checkpoint "
4573 "bad-fork-prior-to-checkpoint");
4578 if (block.
GetBlockTime() <= pindexPrev->GetMedianTimePast()) {
4580 "time-too-old",
"block's timestamp is too early");
4584 if (block.
Time() > now + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4587 "block timestamp too far in the future");
4620 const int nHeight = pindexPrev ==
nullptr ? 0 : pindexPrev->
nHeight + 1;
4623 bool enforce_locktime_median_time_past{
false};
4626 assert(pindexPrev !=
nullptr);
4627 enforce_locktime_median_time_past =
true;
4630 const int64_t nMedianTimePast =
4633 const int64_t nLockTimeCutoff{enforce_locktime_median_time_past
4638 const bool fIsMagneticAnomalyEnabled =
4645 const CTransaction *prevTx =
nullptr;
4646 for (
const auto &ptx : block.
vtx) {
4647 const CTransaction &tx = *ptx;
4648 if (fIsMagneticAnomalyEnabled) {
4649 if (prevTx && (tx.GetId() <= prevTx->GetId())) {
4650 if (tx.GetId() == prevTx->GetId()) {
4654 tx.GetId().ToString()));
4659 strprintf(
"Transaction order is invalid (%s < %s)",
4660 tx.GetId().ToString(),
4661 prevTx->GetId().ToString()));
4664 if (prevTx || !tx.IsCoinBase()) {
4682 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
4684 block.
vtx[0]->vin[0].scriptSig.begin())) {
4687 "block height mismatch in coinbase");
4702 const std::optional<CCheckpointData> &test_checkpoints) {
4709 BlockMap::iterator miSelf{
m_blockman.m_block_index.find(hash)};
4711 if (miSelf !=
m_blockman.m_block_index.end()) {
4718 if (pindex->nStatus.isInvalid()) {
4731 "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__,
4737 BlockMap::iterator mi{
4741 "header %s has prev block not found: %s\n",
4744 "prev-blk-not-found");
4749 if (pindexPrev->nStatus.isInvalid()) {
4751 "header %s has prev block invalid: %s\n", hash.
ToString(),
4761 "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n",
4792 if (pindexPrev->
GetAncestor(failedit->nHeight) == failedit) {
4793 assert(failedit->nStatus.hasFailed());
4795 while (invalid_walk != failedit) {
4796 invalid_walk->nStatus =
4797 invalid_walk->nStatus.withFailedParent();
4799 invalid_walk = invalid_walk->
pprev;
4802 "header %s has prev block invalid: %s\n",
4811 if (!min_pow_checked) {
4813 "%s: not adding new block header %s, missing anti-dos "
4814 "proof-of-work validation\n",
4817 "too-little-chainwork");
4833 const auto msg =
strprintf(
"Saw new header hash=%s height=%d",
4847 const std::vector<CBlockHeader> &headers,
bool min_pow_checked,
4849 const std::optional<CCheckpointData> &test_checkpoints) {
4857 header, state, &pindex, min_pow_checked, test_checkpoints);
4875 blocks_left = std::max<int64_t>(0, blocks_left);
4876 const double progress{100.0 * last_accepted.nHeight /
4877 (last_accepted.nHeight + blocks_left)};
4878 LogInfo(
"Synchronizing blockheaders, height: %d (~%.2f%%)\n",
4879 last_accepted.nHeight, progress);
4887 int64_t timestamp) {
4896 if (m_best_header->nChainWork >=
4902 auto now = Now<SteadyMilliseconds>();
4903 if (now < m_last_presync_update + 250ms) {
4906 m_last_presync_update = now;
4911 height, timestamp,
true);
4912 if (initial_download) {
4913 int64_t blocks_left{
4916 blocks_left = std::max<int64_t>(0, blocks_left);
4917 const double progress{100.0 * height / (height + blocks_left)};
4918 LogInfo(
"Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n",
4926 bool *fNewBlock,
bool min_pow_checked) {
4929 const CBlock &block = *pblock;
4936 bool accepted_header{
4940 if (!accepted_header) {
4948 bool fAlreadyHave = pindex->nStatus.hasData();
4960 int64_t chainTipTimeDiff =
4966 LogPrintf(
"Chain tip timestamp-to-received-time difference: hash=%s, "
4969 LogPrintf(
"New block timestamp-to-received-time difference: hash=%s, "
4974 bool fHasMoreOrSameWork =
4982 bool fTooFarAhead{pindex->
nHeight >
4995 if (pindex->
nTx != 0) {
5000 if (!fHasMoreOrSameWork) {
5024 pindex->nStatus = pindex->nStatus.withFailed();
5043 std::optional<int> snapshot_base_height = GetSnapshotBaseHeight();
5044 const bool is_background_block =
5046 pindex->
nHeight <= snapshot_base_height;
5048 if (!is_background_block && pindexFork &&
5050 LogPrintf(
"Park block %s as it would cause a deep reorg.\n",
5052 pindex->nStatus = pindex->nStatus.withParked();
5076 if (blockPos.IsNull()) {
5078 "%s: Failed to find position to write new block to disk",
5084 }
catch (
const std::runtime_error &e) {
5086 std::string(
"System error: ") + e.what());
5104 const std::shared_ptr<const CBlock> &block,
bool force_processing,
5105 bool min_pow_checked,
bool *new_block,
5134 ret =
AcceptBlock(block, state, force_processing,
nullptr,
5135 new_block, min_pow_checked);
5142 LogError(
"%s: AcceptBlock FAILED (%s)\n", __func__,
5153 LogError(
"%s: ActivateBestChain failed (%s)\n", __func__,
5159 ? m_ibd_chainstate.get()
5162 if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
5163 LogError(
"%s: [background] ActivateBestChain failed (%s)\n", __func__,
5182 false, test_accept);
5198 indexDummy.
pprev = pindexPrev;
5205 adjusted_time_callback())) {
5206 LogError(
"%s: Consensus::ContextualCheckBlockHeader: %s\n", __func__,
5218 LogError(
"%s: Consensus::ContextualCheckBlock: %s\n", __func__,
5223 if (!chainstate.
ConnectBlock(block, state, &indexDummy, viewNew,
5224 validationOptions,
nullptr,
true)) {
5234 int nManualPruneHeight) {
5237 nManualPruneHeight)) {
5238 LogPrintf(
"%s: failed to flush state (%s)\n", __func__,
5265 "Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
5296 if (nCheckDepth <= 0 || nCheckDepth > chainstate.
m_chain.
Height()) {
5300 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
5301 LogPrintf(
"Verifying last %i blocks at level %i\n", nCheckDepth,
5307 int nGoodTransactions = 0;
5310 bool skipped_no_block_data{
false};
5311 bool skipped_l3_checks{
false};
5312 LogPrintf(
"Verification progress: 0%%\n");
5317 pindex = pindex->
pprev) {
5318 const int percentageDone = std::max(
5319 1, std::min(99, (
int)(((
double)(chainstate.
m_chain.
Height() -
5321 (
double)nCheckDepth *
5322 (nCheckLevel >= 4 ? 50 : 100))));
5323 if (reportDone < percentageDone / 10) {
5325 LogPrintf(
"Verification progress: %d%%\n", percentageDone);
5326 reportDone = percentageDone / 10;
5335 !pindex->nStatus.hasData()) {
5338 LogPrintf(
"VerifyDB(): block verification stopping at height %d "
5339 "(no data). This could be due to pruning or use of an "
5340 "assumeutxo snapshot.\n",
5342 skipped_no_block_data =
true;
5350 LogPrintf(
"Verification error: ReadBlock failed at %d, hash=%s\n",
5356 if (nCheckLevel >= 1 && !
CheckBlock(block, state, consensusParams,
5359 "Verification error: found bad block at %d, hash=%s (%s)\n",
5366 if (nCheckLevel >= 2 && pindex) {
5370 LogPrintf(
"Verification error: found bad undo data at %d, "
5383 if (nCheckLevel >= 3) {
5387 chainstate.DisconnectBlock(block, pindex, coins);
5389 LogPrintf(
"Verification error: irrecoverable inconsistency "
5390 "in block data at %d, hash=%s\n",
5396 nGoodTransactions = 0;
5397 pindexFailure = pindex;
5399 nGoodTransactions += block.
vtx.size();
5402 skipped_l3_checks =
true;
5411 if (pindexFailure) {
5412 LogPrintf(
"Verification error: coin database inconsistencies found "
5413 "(last %i blocks, %i good transactions before that)\n",
5418 if (skipped_l3_checks) {
5419 LogPrintf(
"Skipped verification of level >=3 (insufficient database "
5420 "cache size). Consider increasing -dbcache.\n");
5427 if (nCheckLevel >= 4 && !skipped_l3_checks) {
5429 const int percentageDone = std::max(
5430 1, std::min(99, 100 -
int(
double(chainstate.
m_chain.
Height() -
5432 double(nCheckDepth) * 50)));
5433 if (reportDone < percentageDone / 10) {
5435 LogPrintf(
"Verification progress: %d%%\n", percentageDone);
5436 reportDone = percentageDone / 10;
5443 LogPrintf(
"Verification error: ReadBlock failed at %d, "
5448 if (!chainstate.
ConnectBlock(block, state, pindex, coins,
5450 LogPrintf(
"Verification error: found unconnectable block at "
5451 "%d, hash=%s (%s)\n",
5462 LogPrintf(
"Verification: No coin database inconsistencies in last %i "
5463 "blocks (%i transactions)\n",
5464 block_count, nGoodTransactions);
5466 if (skipped_l3_checks) {
5469 if (skipped_no_block_data) {
5485 LogError(
"ReplayBlock(): ReadBlock failed at %d, hash=%s\n",
5496 if (tx->IsCoinBase()) {
5500 for (
const CTxIn &txin : tx->vin) {
5514 std::vector<BlockHash> hashHeads =
db.GetHeadBlocks();
5515 if (hashHeads.empty()) {
5519 if (hashHeads.size() != 2) {
5520 LogError(
"ReplayBlocks(): unknown inconsistent state\n");
5534 if (
m_blockman.m_block_index.count(hashHeads[0]) == 0) {
5535 LogError(
"ReplayBlocks(): reorganization to unknown block requested\n");
5539 pindexNew = &(
m_blockman.m_block_index[hashHeads[0]]);
5541 if (!hashHeads[1].IsNull()) {
5543 if (
m_blockman.m_block_index.count(hashHeads[1]) == 0) {
5544 LogError(
"ReplayBlocks(): reorganization from unknown block "
5549 pindexOld = &(
m_blockman.m_block_index[hashHeads[1]]);
5551 assert(pindexFork !=
nullptr);
5555 while (pindexOld != pindexFork) {
5560 LogError(
"RollbackBlock(): ReadBlock() failed at "
5572 "RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n",
5585 pindexOld = pindexOld->
pprev;
5589 int nForkHeight = pindexFork ? pindexFork->
nHeight : 0;
5596 _(
"Replaying blocks…"),
5597 (
int)((
nHeight - nForkHeight) * 100.0 /
5598 (pindexNew->
nHeight - nForkHeight)),
5614void Chainstate::ClearBlockIndexCandidates() {
5630 const uint64_t numHeaders{20};
5633 const fs::path filePathTmp = filePath +
".new";
5644 bool missingIndex{
false};
5645 for (uint64_t i = 0; i < numHeaders; i++) {
5647 LogPrintf(
"Missing block index, stopping the headers time "
5648 "dumping after %d blocks.\n",
5650 missingIndex =
true;
5657 index = index->
pprev;
5661 throw std::runtime_error(
strprintf(
"Failed to commit to file %s",
5667 fs::remove(filePathTmp);
5672 throw std::runtime_error(
strprintf(
"Rename failed from %s to %s",
5676 }
catch (
const std::exception &e) {
5677 LogPrintf(
"Failed to dump the headers time: %s.\n", e.what());
5681 LogPrintf(
"Successfully dumped the last %d headers time to %s.\n",
5696 if (file.IsNull()) {
5697 LogPrintf(
"Failed to open header times from disk, skipping.\n");
5706 LogPrintf(
"Unsupported header times file version, skipping.\n");
5713 for (uint64_t i = 0; i < numBlocks; i++) {
5715 int64_t receiveTime;
5718 file >> receiveTime;
5722 LogPrintf(
"Missing index for block %s, stopping the headers "
5723 "time loading after %d blocks.\n",
5730 }
catch (
const std::exception &e) {
5731 LogPrintf(
"Failed to read the headers time file data on disk: %s.\n",
5749 m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
5751 std::vector<CBlockIndex *> vSortedByHeight{
5753 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
5765 if (pindex == GetSnapshotBaseBlock() ||
5773 if (pindex->nStatus.isInvalid() &&
5775 pindex->
nChainWork > m_best_invalid->nChainWork)) {
5776 m_best_invalid = pindex;
5779 if (pindex->nStatus.isOnParkedChain() &&
5781 pindex->
nChainWork > m_best_parked->nChainWork)) {
5782 m_best_parked = pindex;
5786 (m_best_header ==
nullptr ||
5788 m_best_header = pindex;
5792 needs_init =
m_blockman.m_block_index.empty();
5802 LogPrintf(
"Initializing databases...\n");
5823 if (blockPos.IsNull()) {
5824 LogError(
"%s: writing genesis block to disk failed\n", __func__);
5830 }
catch (
const std::runtime_error &e) {
5831 LogError(
"%s: failed to write genesis block: %s\n", __func__, e.what());
5840 std::multimap<BlockHash, FlatFilePos> *blocks_with_unknown_parent,
5843 assert(!dbp == !blocks_with_unknown_parent);
5855 uint64_t nRewind = blkdat.GetPos();
5856 while (!blkdat.eof()) {
5861 blkdat.SetPos(nRewind);
5866 unsigned int nSize = 0;
5870 blkdat.FindByte(std::byte(params.
DiskMagic()[0]));
5871 nRewind = blkdat.GetPos() + 1;
5873 if (memcmp(buf, params.
DiskMagic().data(),
5883 }
catch (
const std::exception &) {
5891 const uint64_t nBlockPos{blkdat.GetPos()};
5893 dbp->
nPos = nBlockPos;
5895 blkdat.SetLimit(nBlockPos + nSize);
5903 nRewind = nBlockPos + nSize;
5904 blkdat.SkipTo(nRewind);
5908 std::shared_ptr<CBlock> pblock{};
5917 "%s: Out of order block %s, parent %s not known\n",
5918 __func__, hash.ToString(),
5920 if (dbp && blocks_with_unknown_parent) {
5921 blocks_with_unknown_parent->emplace(
5930 if (!pindex || !pindex->nStatus.hasData()) {
5933 blkdat.SetPos(nBlockPos);
5934 pblock = std::make_shared<CBlock>();
5936 nRewind = blkdat.GetPos();
5939 if (
AcceptBlock(pblock, state,
true, dbp,
nullptr,
5947 pindex->
nHeight % 1000 == 0) {
5950 "Block Import: already had block %s at height %d\n",
5951 hash.ToString(), pindex->
nHeight);
5958 bool genesis_activation_failure =
false;
5959 for (
auto c :
GetAll()) {
5961 if (!c->ActivateBestChain(state,
nullptr,
avalanche)) {
5962 genesis_activation_failure =
true;
5966 if (genesis_activation_failure) {
5981 bool activation_failure =
false;
5982 for (
auto c :
GetAll()) {
5984 if (!c->ActivateBestChain(state, pblock,
avalanche)) {
5986 "failed to activate chain (%s)\n",
5988 activation_failure =
true;
5992 if (activation_failure) {
5999 if (!blocks_with_unknown_parent) {
6005 std::deque<BlockHash> queue;
6006 queue.push_back(hash);
6007 while (!queue.empty()) {
6010 auto range = blocks_with_unknown_parent->equal_range(head);
6011 while (range.first != range.second) {
6012 std::multimap<BlockHash, FlatFilePos>::iterator it =
6014 std::shared_ptr<CBlock> pblockrecursive =
6015 std::make_shared<CBlock>();
6020 "%s: Processing out of order child %s of %s\n",
6021 __func__, pblockrecursive->GetHash().ToString(),
6026 &it->second,
nullptr,
true)) {
6028 queue.push_back(pblockrecursive->GetHash());
6032 blocks_with_unknown_parent->erase(it);
6036 }
catch (
const std::exception &e) {
6057 "%s: unexpected data at file offset 0x%x - %s. "
6059 __func__, (nRewind - 1), e.what());
6062 }
catch (
const std::runtime_error &e) {
6066 LogPrintf(
"Loaded %i blocks from external file in %dms\n", nLoaded,
6087 std::multimap<CBlockIndex *, CBlockIndex *> forward;
6088 for (
auto &[
_, block_index] :
m_blockman.m_block_index) {
6089 forward.emplace(block_index.pprev, &block_index);
6094 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6095 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6096 rangeGenesis = forward.equal_range(
nullptr);
6098 rangeGenesis.first++;
6100 assert(rangeGenesis.first == rangeGenesis.second);
6122 CBlockIndex *pindexFirstNotTransactionsValid =
nullptr;
6128 CBlockIndex *pindexFirstNotScriptsValid =
nullptr;
6134 const CBlockIndex *snap_base{GetSnapshotBaseBlock()};
6135 CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{},
6136 *snap_first_nocv{}, *snap_first_nosv{};
6137 auto snap_update_firsts = [&] {
6138 if (pindex == snap_base) {
6139 std::swap(snap_first_missing, pindexFirstMissing);
6140 std::swap(snap_first_notx, pindexFirstNeverProcessed);
6141 std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
6142 std::swap(snap_first_nocv, pindexFirstNotChainValid);
6143 std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
6147 while (pindex !=
nullptr) {
6149 if (pindexFirstInvalid ==
nullptr && pindex->nStatus.hasFailed()) {
6150 pindexFirstInvalid = pindex;
6152 if (pindexFirstParked ==
nullptr && pindex->nStatus.isParked()) {
6153 pindexFirstParked = pindex;
6155 if (pindexFirstMissing ==
nullptr && !pindex->nStatus.hasData()) {
6156 pindexFirstMissing = pindex;
6158 if (pindexFirstNeverProcessed ==
nullptr && pindex->
nTx == 0) {
6159 pindexFirstNeverProcessed = pindex;
6161 if (pindex->
pprev !=
nullptr && pindexFirstNotTreeValid ==
nullptr &&
6163 pindexFirstNotTreeValid = pindex;
6165 if (pindex->
pprev !=
nullptr) {
6166 if (pindexFirstNotTransactionsValid ==
nullptr &&
6168 pindexFirstNotTransactionsValid = pindex;
6170 if (pindexFirstNotChainValid ==
nullptr &&
6172 pindexFirstNotChainValid = pindex;
6174 if (pindexFirstNotScriptsValid ==
nullptr &&
6176 pindexFirstNotScriptsValid = pindex;
6181 if (pindex->
pprev ==
nullptr) {
6185 for (
auto c :
GetAll()) {
6186 if (c->m_chain.Genesis() !=
nullptr) {
6188 assert(pindex == c->m_chain.Genesis());
6203 assert(pindex->nStatus.hasData() == (pindex->
nTx > 0));
6204 assert(pindexFirstMissing == pindexFirstNeverProcessed);
6205 }
else if (pindex->nStatus.hasData()) {
6210 if (pindex->nStatus.hasUndo()) {
6211 assert(pindex->nStatus.hasData());
6213 if (snap_base && snap_base->GetAncestor(pindex->
nHeight) == pindex) {
6225 assert((pindexFirstNeverProcessed ==
nullptr || pindex == snap_base) ==
6227 assert((pindexFirstNotTransactionsValid ==
nullptr ||
6239 assert(pindexFirstNotTreeValid ==
nullptr);
6242 assert(pindexFirstNotTreeValid ==
nullptr);
6246 assert(pindexFirstNotChainValid ==
nullptr);
6250 assert(pindexFirstNotScriptsValid ==
nullptr);
6252 if (pindexFirstInvalid ==
nullptr) {
6255 assert(!pindex->nStatus.isInvalid());
6257 if (pindexFirstParked ==
nullptr) {
6261 assert(!pindex->nStatus.isOnParkedChain());
6264 if (!pindex->
pprev) {
6278 for (
auto c :
GetAll()) {
6279 if (c->m_chain.Tip() ==
nullptr) {
6296 (pindexFirstNeverProcessed ==
nullptr || pindex == snap_base)) {
6300 if (pindexFirstInvalid ==
nullptr) {
6307 GetSnapshotBaseBlock()->GetAncestor(pindex->
nHeight) ==
6321 if (pindexFirstMissing ==
nullptr) {
6322 assert(pindex->nStatus.isOnParkedChain() ||
6323 c->setBlockIndexCandidates.count(pindex));
6331 if (pindex == c->m_chain.Tip() ||
6332 pindex == c->SnapshotBase()) {
6333 assert(c->setBlockIndexCandidates.count(pindex));
6345 assert(c->setBlockIndexCandidates.count(pindex) == 0);
6349 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6350 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6353 bool foundInUnlinked =
false;
6354 while (rangeUnlinked.first != rangeUnlinked.second) {
6355 assert(rangeUnlinked.first->first == pindex->
pprev);
6356 if (rangeUnlinked.first->second == pindex) {
6357 foundInUnlinked =
true;
6360 rangeUnlinked.first++;
6362 if (pindex->
pprev && pindex->nStatus.hasData() &&
6363 pindexFirstNeverProcessed !=
nullptr &&
6364 pindexFirstInvalid ==
nullptr) {
6370 if (!pindex->nStatus.hasData()) {
6372 assert(!foundInUnlinked);
6374 if (pindexFirstMissing ==
nullptr) {
6377 assert(!foundInUnlinked);
6379 if (pindex->
pprev && pindex->nStatus.hasData() &&
6380 pindexFirstNeverProcessed ==
nullptr &&
6381 pindexFirstMissing !=
nullptr) {
6394 for (
auto c :
GetAll()) {
6397 c->setBlockIndexCandidates.count(pindex) == 0) {
6398 if (pindexFirstInvalid ==
nullptr) {
6400 snap_base->GetAncestor(pindex->
nHeight) == pindex) {
6412 snap_update_firsts();
6413 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6414 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6415 range = forward.equal_range(pindex);
6416 if (range.first != range.second) {
6418 pindex = range.first->second;
6426 snap_update_firsts();
6429 if (pindex == pindexFirstInvalid) {
6430 pindexFirstInvalid =
nullptr;
6432 if (pindex == pindexFirstParked) {
6433 pindexFirstParked =
nullptr;
6435 if (pindex == pindexFirstMissing) {
6436 pindexFirstMissing =
nullptr;
6438 if (pindex == pindexFirstNeverProcessed) {
6439 pindexFirstNeverProcessed =
nullptr;
6441 if (pindex == pindexFirstNotTreeValid) {
6442 pindexFirstNotTreeValid =
nullptr;
6444 if (pindex == pindexFirstNotTransactionsValid) {
6445 pindexFirstNotTransactionsValid =
nullptr;
6447 if (pindex == pindexFirstNotChainValid) {
6448 pindexFirstNotChainValid =
nullptr;
6450 if (pindex == pindexFirstNotScriptsValid) {
6451 pindexFirstNotScriptsValid =
nullptr;
6456 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6457 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6458 rangePar = forward.equal_range(pindexPar);
6459 while (rangePar.first->second != pindex) {
6462 assert(rangePar.first != rangePar.second);
6467 if (rangePar.first != rangePar.second) {
6469 pindex = rangePar.first->second;
6481 assert(nNodes == forward.size());
6487 return strprintf(
"Chainstate [%s] @ height %d (%s)",
6493bool Chainstate::ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size) {
6506 coinsdb_size * (1.0 / 1024 / 1024));
6508 coinstip_size * (1.0 / 1024 / 1024));
6513 if (coinstip_size > old_coinstip_size) {
6530 if (pindex ==
nullptr) {
6535 "Block %d has unset m_chain_tx_count. Unable to "
6536 "estimate verification progress.\n",
6541 int64_t nNow = time(
nullptr);
6556 if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
6558 return m_active_chainstate->m_from_snapshot_blockhash;
6560 return std::nullopt;
6565 std::vector<Chainstate *>
out;
6568 {m_ibd_chainstate.get(), m_snapshot_chainstate.get()}) {
6570 out.push_back(pchainstate);
6579 assert(!m_ibd_chainstate);
6580 assert(!m_active_chainstate);
6582 m_ibd_chainstate = std::make_unique<Chainstate>(mempool,
m_blockman, *
this);
6583 m_active_chainstate = m_ibd_chainstate.get();
6584 return *m_active_chainstate;
6597 const bool existed{fs::remove(base_blockhash_path)};
6599 LogPrintf(
"[snapshot] snapshot chainstate dir being removed "
6603 }
catch (
const fs::filesystem_error &e) {
6604 LogPrintf(
"[snapshot] failed to remove file %s: %s\n",
6611 LogPrintf(
"Removing leveldb dir at %s\n", path_str);
6615 const bool destroyed = dbwrapper::DestroyDB(path_str, {}).ok();
6618 LogPrintf(
"error: leveldb DestroyDB call failed on %s\n", path_str);
6636 "Can't activate a snapshot-based chainstate more than once")};
6644 if (!
GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
6646 std::string heights_formatted =
6650 Untranslated(
"assumeutxo block hash in snapshot metadata not "
6651 "recognized (hash: %s). The following "
6652 "snapshot heights are available: %s."),
6653 base_blockhash.
ToString(), heights_formatted)};
6657 if (!snapshot_start_block) {
6659 Untranslated(
"The base block header (%s) must appear in the "
6660 "headers chain. Make sure all headers are "
6661 "syncing, and call loadtxoutset again."),
6665 if (snapshot_start_block->nStatus.isInvalid()) {
6668 "The base block header (%s) is part of an invalid chain"),
6672 if (!m_best_header ||
6673 m_best_header->GetAncestor(snapshot_start_block->nHeight) !=
6674 snapshot_start_block) {
6676 "A forked headers-chain with more work than the chain with the "
6677 "snapshot base block header exists. Please proceed to sync "
6678 "without AssumeUtxo.")};
6681 if (
Assert(m_active_chainstate->GetMempool())->size() > 0) {
6683 "Can't activate a snapshot when mempool not empty.")};
6687 int64_t current_coinsdb_cache_size{0};
6688 int64_t current_coinstip_cache_size{0};
6697 static constexpr double IBD_CACHE_PERC = 0.01;
6698 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
6711 current_coinsdb_cache_size =
6713 current_coinstip_cache_size =
6719 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
6720 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
6723 auto snapshot_chainstate =
6730 snapshot_chainstate->InitCoinsDB(
6731 static_cast<size_t>(current_coinsdb_cache_size *
6732 SNAPSHOT_CACHE_PERC),
6733 in_memory,
false,
"chainstate");
6734 snapshot_chainstate->InitCoinsCache(
static_cast<size_t>(
6735 current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
6738 auto cleanup_bad_snapshot =
6740 this->MaybeRebalanceCaches();
6745 if (
auto snapshot_datadir =
6751 snapshot_chainstate.reset();
6756 "Failed to remove snapshot chainstate dir (%s). "
6757 "Manually remove it before restarting.\n",
6767 return cleanup_bad_snapshot(
Untranslated(
"population failed"));
6778 snapshot_chainstate->m_chain.Tip())) {
6779 return cleanup_bad_snapshot(
6780 Untranslated(
"work does not exceed active chainstate"));
6786 return cleanup_bad_snapshot(
6791 assert(!m_snapshot_chainstate);
6792 m_snapshot_chainstate.swap(snapshot_chainstate);
6793 const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
6798 Assert(m_active_chainstate->m_mempool->size() == 0);
6799 Assert(!m_snapshot_chainstate->m_mempool);
6800 m_snapshot_chainstate->m_mempool = m_active_chainstate->m_mempool;
6801 m_active_chainstate->m_mempool =
nullptr;
6802 m_active_chainstate = m_snapshot_chainstate.get();
6805 LogPrintf(
"[snapshot] successfully activated snapshot %s\n",
6808 m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() /
6811 this->MaybeRebalanceCaches();
6812 return snapshot_start_block;
6816 bool snapshot_loaded) {
6819 snapshot_loaded ?
"saving snapshot chainstate"
6820 :
"flushing coins cache",
6822 BCLog::LogFlags::ALL);
6824 coins_cache.
Flush();
6828 const char *
what() const noexcept
override {
6829 return "ComputeUTXOStats interrupted by shutdown.";
6853 if (!snapshot_start_block) {
6856 LogPrintf(
"[snapshot] Did not find snapshot start blockheader %s\n",
6861 int base_height = snapshot_start_block->
nHeight;
6864 if (!maybe_au_data) {
6865 LogPrintf(
"[snapshot] assumeutxo height in snapshot metadata not "
6866 "recognized (%d) - refusing to load snapshot\n",
6878 LogPrintf(
"[snapshot] activation failed - work does not exceed active "
6886 LogPrintf(
"[snapshot] loading %d coins from snapshot %s\n", coins_left,
6888 int64_t coins_processed{0};
6890 while (coins_left > 0) {
6894 size_t coins_per_txid{0};
6897 if (coins_per_txid > coins_left) {
6898 LogPrintf(
"[snapshot] mismatch in coins count in snapshot "
6899 "metadata and actual snapshot data\n");
6903 for (
size_t i = 0; i < coins_per_txid; i++) {
6909 if (coin.
GetHeight() > uint32_t(base_height) ||
6911 std::numeric_limits<
decltype(outpoint.GetN())>::max()) {
6912 LogPrintf(
"[snapshot] bad snapshot data after "
6913 "deserializing %d coins\n",
6914 coins_count - coins_left);
6918 LogPrintf(
"[snapshot] bad snapshot data after "
6919 "deserializing %d coins - bad tx out value\n",
6920 coins_count - coins_left);
6929 if (coins_processed % 1000000 == 0) {
6930 LogPrintf(
"[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
6932 static_cast<float>(coins_processed) * 100 /
6933 static_cast<float>(coins_count),
6941 if (coins_processed % 120000 == 0) {
6946 const auto snapshot_cache_state =
WITH_LOCK(
6948 return snapshot_chainstate.GetCoinsCacheSizeState());
6965 }
catch (
const std::ios_base::failure &) {
6966 LogPrintf(
"[snapshot] bad snapshot format or truncated snapshot "
6967 "after deserializing %d coins\n",
6980 bool out_of_coins{
false};
6984 }
catch (
const std::ios_base::failure &) {
6986 out_of_coins =
true;
6988 if (!out_of_coins) {
6989 LogPrintf(
"[snapshot] bad snapshot - coins left over after "
6990 "deserializing %d coins\n",
6995 LogPrintf(
"[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
7009 std::optional<CCoinsStats> maybe_stats;
7013 CoinStatsHashType::HASH_SERIALIZED, snapshot_coinsdb,
m_blockman,
7020 if (!maybe_stats.has_value()) {
7021 LogPrintf(
"[snapshot] failed to generate coins stats\n");
7029 LogPrintf(
"[snapshot] bad snapshot content hash: expected %s, got %s\n",
7031 maybe_stats->hashSerialized.ToString());
7047 constexpr int AFTER_GENESIS_START{1};
7049 for (
int i = AFTER_GENESIS_START; i <= snapshot_chainstate.
m_chain.
Height();
7051 index = snapshot_chainstate.
m_chain[i];
7062 assert(index == snapshot_start_block);
7066 LogPrintf(
"[snapshot] validated snapshot (%.2f MB)\n",
7088 if (m_ibd_chainstate.get() == &this->ActiveChainstate() ||
7089 !this->IsUsable(m_snapshot_chainstate.get()) ||
7090 !this->IsUsable(m_ibd_chainstate.get()) ||
7091 !m_ibd_chainstate->m_chain.Tip()) {
7097 const int snapshot_base_height = *
Assert(this->GetSnapshotBaseHeight());
7100 if (index_new.
nHeight < snapshot_base_height) {
7110 _(
"%s failed to validate the -assumeutxo snapshot state. "
7111 "This indicates a hardware problem, or a bug in the software, or "
7112 "a bad software modification that allowed an invalid snapshot to "
7113 "be loaded. As a result of this, the node will shut down and "
7114 "stop using any state that was built on the snapshot, resetting "
7115 "the chain height from %d to %d. On the next restart, the node "
7116 "will resume syncing from %d without using any snapshot data. "
7117 "Please report this incident to %s, including how you obtained "
7118 "the snapshot. The invalid snapshot chainstate will be left on "
7119 "disk in case it is helpful in diagnosing the issue that caused "
7121 PACKAGE_NAME, snapshot_tip_height, snapshot_base_height,
7122 snapshot_base_height, PACKAGE_BUGREPORT);
7125 LogPrintf(
"[snapshot] deleting snapshot, reverting to validated chain, "
7126 "and stopping node\n");
7128 m_active_chainstate = m_ibd_chainstate.get();
7129 m_snapshot_chainstate->m_disabled =
true;
7133 auto rename_result = m_snapshot_chainstate->InvalidateCoinsDBOnDisk();
7134 if (!rename_result) {
7144 "[snapshot] supposed base block %s does not match the "
7145 "snapshot base block %s (height %d). Snapshot is not valid.\n",
7147 snapshot_base_height);
7148 handle_invalid_snapshot();
7154 int curr_height = m_ibd_chainstate->m_chain.Height();
7156 assert(snapshot_base_height == curr_height);
7161 CCoinsViewDB &ibd_coins_db = m_ibd_chainstate->CoinsDB();
7162 m_ibd_chainstate->ForceFlushStateToDisk();
7164 const auto &maybe_au_data =
7166 if (!maybe_au_data) {
7167 LogPrintf(
"[snapshot] assumeutxo data not found for height "
7168 "(%d) - refusing to validate snapshot\n",
7170 handle_invalid_snapshot();
7175 std::optional<CCoinsStats> maybe_ibd_stats;
7177 "[snapshot] computing UTXO stats for background chainstate to validate "
7178 "snapshot - this could take a few minutes\n");
7189 if (!maybe_ibd_stats) {
7191 "[snapshot] failed to generate stats for validation coins db\n");
7195 handle_invalid_snapshot();
7198 const auto &ibd_stats = *maybe_ibd_stats;
7207 LogPrintf(
"[snapshot] hash mismatch: actual=%s, expected=%s\n",
7208 ibd_stats.hashSerialized.ToString(),
7210 handle_invalid_snapshot();
7214 LogPrintf(
"[snapshot] snapshot beginning at %s has been fully validated\n",
7217 m_ibd_chainstate->m_disabled =
true;
7218 this->MaybeRebalanceCaches();
7225 assert(m_active_chainstate);
7226 return *m_active_chainstate;
7231 LOCK(active_chainstate.cs_avalancheFinalizedBlockIndex);
7232 return active_chainstate.m_avalancheFinalizedBlockIndex;
7237 return m_snapshot_chainstate &&
7238 m_active_chainstate == m_snapshot_chainstate.get();
7240void ChainstateManager::MaybeRebalanceCaches() {
7242 bool ibd_usable = this->
IsUsable(m_ibd_chainstate.get());
7243 bool snapshot_usable = this->
IsUsable(m_snapshot_chainstate.get());
7244 assert(ibd_usable || snapshot_usable);
7246 if (ibd_usable && !snapshot_usable) {
7251 }
else if (snapshot_usable && !ibd_usable) {
7255 "[snapshot] allocating all cache to the snapshot chainstate\n");
7259 }
else if (ibd_usable && snapshot_usable) {
7268 m_snapshot_chainstate->ResizeCoinsCaches(
7271 m_snapshot_chainstate->ResizeCoinsCaches(
7279void ChainstateManager::ResetChainstates() {
7280 m_ibd_chainstate.reset();
7281 m_snapshot_chainstate.reset();
7282 m_active_chainstate =
nullptr;
7291 if (!opts.check_block_index.has_value()) {
7293 opts.config.GetChainParams().DefaultConsistencyChecks();
7296 if (!opts.minimum_chain_work.has_value()) {
7298 opts.config.GetChainParams().GetConsensus().nMinimumChainWork);
7300 if (!opts.assumed_valid_block.has_value()) {
7301 opts.assumed_valid_block =
7302 opts.config.GetChainParams().GetConsensus().defaultAssumeValid;
7304 Assert(opts.adjusted_time_callback);
7305 return std::move(opts);
7311 : m_script_check_queue{128, options.worker_threads_num},
7312 m_interrupt{interrupt}, m_options{
Flatten(
std::move(options))},
7313 m_blockman{interrupt,
std::move(blockman_options)},
7314 m_validation_cache{m_options.script_execution_cache_bytes,
7315 m_options.signature_cache_bytes} {}
7317bool ChainstateManager::DetectSnapshotChainstate(
CTxMemPool *mempool) {
7318 assert(!m_snapshot_chainstate);
7319 std::optional<fs::path> path =
7324 std::optional<BlockHash> base_blockhash =
7326 if (!base_blockhash) {
7329 LogPrintf(
"[snapshot] detected active snapshot chainstate (%s) - loading\n",
7332 this->ActivateExistingSnapshot(*base_blockhash);
7337ChainstateManager::ActivateExistingSnapshot(
BlockHash base_blockhash) {
7338 assert(!m_snapshot_chainstate);
7339 m_snapshot_chainstate = std::make_unique<Chainstate>(
nullptr,
m_blockman,
7340 *
this, base_blockhash);
7341 LogPrintf(
"[snapshot] switching active chainstate to %s\n",
7342 m_snapshot_chainstate->ToString());
7345 Assert(m_active_chainstate->m_mempool->size() == 0);
7346 Assert(!m_snapshot_chainstate->m_mempool);
7347 m_snapshot_chainstate->m_mempool = m_active_chainstate->m_mempool;
7348 m_active_chainstate->m_mempool =
nullptr;
7349 m_active_chainstate = m_snapshot_chainstate.get();
7350 return *m_snapshot_chainstate;
7357 assert(
cs.m_from_snapshot_blockhash);
7358 auto storage_path_maybe =
cs.CoinsDB().StoragePath();
7360 assert(storage_path_maybe);
7361 return *storage_path_maybe;
7370 auto invalid_path = snapshot_datadir +
"_INVALID";
7373 LogPrintf(
"[snapshot] renaming snapshot datadir %s to %s\n", dbpath,
7380 fs::rename(snapshot_datadir, invalid_path);
7381 }
catch (
const fs::filesystem_error &e) {
7385 LogPrintf(
"%s: error renaming file '%s' -> '%s': %s\n", __func__,
7386 src_str, dest_str, e.what());
7388 "You should resolve this by manually "
7389 "moving or deleting the invalid "
7390 "snapshot directory %s, otherwise you "
7391 "will encounter the same error again "
7392 "on the next startup."),
7393 src_str, dest_str, src_str)};
7398bool ChainstateManager::DeleteSnapshotChainstate() {
7400 Assert(m_snapshot_chainstate);
7401 Assert(m_ibd_chainstate);
7406 LogPrintf(
"Deletion of %s failed. Please remove it manually to "
7407 "continue reindexing.\n",
7411 m_active_chainstate = m_ibd_chainstate.get();
7412 m_active_chainstate->m_mempool = m_snapshot_chainstate->m_mempool;
7413 m_snapshot_chainstate.reset();
7425const CBlockIndex *ChainstateManager::GetSnapshotBaseBlock()
const {
7426 return m_active_chainstate ? m_active_chainstate->SnapshotBase() :
nullptr;
7429std::optional<int> ChainstateManager::GetSnapshotBaseHeight()
const {
7430 const CBlockIndex *base = this->GetSnapshotBaseBlock();
7431 return base ? std::make_optional(base->
nHeight) :
std::nullopt;
7434void ChainstateManager::RecalculateBestHeader() {
7437 for (
auto &entry :
m_blockman.m_block_index) {
7438 if (!(entry.second.nStatus.isInvalid()) &&
7439 m_best_header->nChainWork < entry.second.nChainWork) {
7440 m_best_header = &entry.second;
7445bool ChainstateManager::ValidatedSnapshotCleanup() {
7454 std::optional<fs::path> ibd_chainstate_path_maybe =
7455 get_storage_path(m_ibd_chainstate);
7456 std::optional<fs::path> snapshot_chainstate_path_maybe =
7457 get_storage_path(m_snapshot_chainstate);
7466 if (!ibd_chainstate_path_maybe || !snapshot_chainstate_path_maybe) {
7467 LogPrintf(
"[snapshot] snapshot chainstate cleanup cannot happen with "
7468 "in-memory chainstates. You are testing, right?\n");
7472 const auto &snapshot_chainstate_path = *snapshot_chainstate_path_maybe;
7473 const auto &ibd_chainstate_path = *ibd_chainstate_path_maybe;
7481 this->ResetChainstates();
7486 LogPrintf(
"[snapshot] deleting background chainstate directory (now "
7487 "unnecessary) (%s)\n",
7490 fs::path tmp_old{ibd_chainstate_path +
"_todelete"};
7493 const fs::filesystem_error &err) {
7494 LogPrintf(
"Error renaming path (%s) -> (%s): %s\n",
7497 "Rename of '%s' -> '%s' failed. "
7498 "Cannot clean up the background chainstate leveldb directory.",
7503 fs::rename(ibd_chainstate_path, tmp_old);
7504 }
catch (
const fs::filesystem_error &e) {
7505 rename_failed_abort(ibd_chainstate_path, tmp_old, e);
7509 LogPrintf(
"[snapshot] moving snapshot chainstate (%s) to "
7510 "default chainstate directory (%s)\n",
7515 fs::rename(snapshot_chainstate_path, ibd_chainstate_path);
7516 }
catch (
const fs::filesystem_error &e) {
7517 rename_failed_abort(snapshot_chainstate_path, ibd_chainstate_path, e);
7524 LogPrintf(
"Deletion of %s failed. Please remove it manually, as the "
7525 "directory is now unnecessary.\n",
7528 LogPrintf(
"[snapshot] deleted background chainstate directory (%s)\n",
7534Chainstate &ChainstateManager::GetChainstateForIndexing() {
7538 return (this->
GetAll().size() > 1) ? *m_ibd_chainstate
7539 : *m_active_chainstate;
7543ChainstateManager::GetPruneRange(
const Chainstate &chainstate,
7544 int last_height_can_prune) {
7550 if (this->
GetAll().size() > 1 &&
7551 m_snapshot_chainstate.get() == &chainstate) {
7554 prune_start = *
Assert(GetSnapshotBaseHeight()) + 1;
7557 int max_prune = std::max<int>(0, chainstate.
m_chain.
Height() -
7567 int prune_end = std::min(last_height_can_prune, max_prune);
7569 return {prune_start, prune_end};
bool IsDAAEnabled(const Consensus::Params ¶ms, int nHeight)
bool IsUAHFenabled(const Consensus::Params ¶ms, int nHeight)
static bool IsPhononEnabled(const Consensus::Params ¶ms, int32_t nHeight)
static bool IsGravitonEnabled(const Consensus::Params ¶ms, int32_t nHeight)
bool IsMagneticAnomalyEnabled(const Consensus::Params ¶ms, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
bool MoneyRange(const Amount nValue)
static constexpr Amount SATOSHI
static constexpr Amount COIN
arith_uint256 UintToArith256(const uint256 &a)
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
Return the time it would take to redo the work difference between from and to, assuming the current h...
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
bool AreOnTheSameFork(const CBlockIndex *pa, const CBlockIndex *pb)
Check if two block index are on the same fork.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
Non-refcounted RAII wrapper for FILE*.
std::string ToString() const
uint64_t getExcessiveBlockSize() const
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
BlockValidationOptions(const Config &config)
bool shouldValidatePoW() const
bool shouldValidateMerkleRoot() const
Wrapper around an AutoFile& that implements a ring buffer to deserialize from.
bool m_checked_merkle_root
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
std::string ToString() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
int64_t GetHeaderReceivedTime() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
const BlockHash * phashBlock
pointer to the hash of the block, if any.
int64_t GetChainTxCount() const
Get the number of transaction in the chain so far.
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
int64_t GetReceivedTimeDiff() const
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
unsigned int nTx
Number of transactions in this block.
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
int32_t nVersion
block header
int64_t nTimeReceived
(memory only) block header metadata
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
unsigned int nSize
Size of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip of this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
std::vector< int > GetAvailableSnapshotHeights() const
const CMessageHeader::MessageMagic & DiskMagic() const
const ChainTxData & TxData() const
const Consensus::Params & GetConsensus() const
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
const CCheckpointData & Checkpoints() const
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
std::optional< R > Complete()
void Add(std::vector< T > &&vChecks)
void SetBackend(CCoinsView &viewIn)
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
void SetBestBlock(const BlockHash &hashBlock)
void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs)
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
CCoinsView backed by the coin database (chainstate/)
std::optional< fs::path > StoragePath()
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
Abstract view on the open txout dataset.
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
CCoinsView that brings transactions from a mempool into view.
Fee rate in satoshis per kilobyte: Amount / kB.
void insert(Span< const uint8_t > vKey)
bool contains(Span< const uint8_t > vKey) const
CSHA256 & Write(const uint8_t *data, size_t len)
Closure representing one script verification.
SignatureCache * m_signature_cache
ScriptExecutionMetrics GetScriptExecutionMetrics() const
TxSigCheckLimiter * pTxLimitSigChecks
ScriptExecutionMetrics metrics
std::optional< std::pair< ScriptError, std::string > > operator()()
PrecomputedTransactionData txdata
const CTransaction * ptxTo
CheckInputsLimiter * pBlockLimitSigChecks
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
void AddTransactionsUpdated(unsigned int n)
size_t DynamicMemoryUsage() const
CTransactionRef get(const TxId &txid) const
void clear(bool include_finalized_txs=false)
Restore the UTXO in a Coin at a given COutPoint.
std::vector< Coin > vprevout
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Chainstate stores and provides an API to update our local knowledge of the current best chain.
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Checks if a block is finalized by avalanche voting.
const std::optional< BlockHash > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
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...
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
Mutex m_chainstate_mutex
The ChainState Mutex.
bool ConnectTip(BlockValidationState &state, BlockPolicyValidationState &blockPolicyState, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, DisconnectedBlockTransactions &disconnectpool, const avalanche::Processor *const avalanche=nullptr, ChainstateRole chainstate_role=ChainstateRole::NORMAL) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f, C fChild, AC fAncestorWasChanged) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CChain m_chain
The current chain of blockheaders we consult and build on.
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(NodeClock::time_poin m_next_write)
Check warning conditions and do some notifications on new chain tip set.
CTxMemPool * GetMempool()
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Set invalidity status to all descendants of a block.
void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< BlockHash > from_snapshot_blockhash=std::nullopt)
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, const avalanche::Processor *const avalanche=nullptr, ChainstateRole=ChainstateRole::NORMAL) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Try to make some progress towards making pindexMostWork the active block.
Mutex cs_avalancheFinalizedBlockIndex
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex, bool invalidate) EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as invalid.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The base of the snapshot this chainstate was created from.
CRollingBloomFilter m_filterParkingPoliciesApplied
Filter to prevent parking a block due to block policies more than once.
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, BlockValidationOptions options, Amount *blockFees=nullptr, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
CBlockIndex const * m_best_fork_tip
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool AvalancheFinalizeBlock(CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(voi ClearAvalancheFinalizedBlock)() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Mark a block as finalized by avalanche.
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Resize the CoinsViews caches dynamically and flush state to disk.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Return the current role of the chainstate.
CBlockIndex const * m_best_fork_base
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main
void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as precious and reorganize.
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
CBlockIndex * FindMostWorkChain(std::vector< const CBlockIndex * > &blocksToReconcile, bool fAutoUnpark) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Park a block.
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Dictates whether we need to flush the cache to disk or not.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
ValidationCache m_validation_cache
std::atomic< int32_t > nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(bool DumpRecentHeadersTime(const fs::path &filePath) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
If, due to invalidation / reconsideration of blocks, the previous best header is no longer valid / gu...
bool DetectSnapshotChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(std::pair< int, int > GetPruneRange(const Chainstate &chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(CCheckQueue< CScriptCheck > GetCheckQueue)()
When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process...
const Config & GetConfig() const
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
kernel::Notifications & GetNotifications() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
bool ShouldCheckBlockIndex() const
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
bool LoadRecentHeadersTime(const fs::path &filePath) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Load the recent block headers reception time from a file.
std::optional< BlockHash > SnapshotBlockhash() const
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
bool IsUsable(const Chainstate *const pchainstate) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
std::atomic< bool > m_cached_finished_ibd
Whether initial block download has ended and IsInitialBlockDownload should return false from now on.
bool PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
const util::SignalInterrupt & m_interrupt
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool IsSnapshotActive() const
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Sufficiently validate a block for disk storage (and store on disk).
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
const CChainParams & GetParams() const
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
ChainstateManager(const util::SignalInterrupt &interrupt, Options options, node::BlockManager::Options blockman_options)
const arith_uint256 & MinimumChainWork() const
void CheckBlockIndex()
Make various assertions about the state of the block index.
const CBlockIndex * GetAvalancheFinalizedTip() const
util::Result< CBlockIndex * > ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void ReportHeadersPresync(const arith_uint256 &work, int64_t height, int64_t timestamp)
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
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...
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< BlockHash, FlatFilePos > *blocks_with_unknown_parent=nullptr, avalanche::Processor *const avalanche=nullptr)
Import blocks from an external file.
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
uint32_t GetHeight() const
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
virtual const CChainParams & GetChainParams() const =0
std::pair< uint32_t, size_t > setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
bool get(Element &e, const bool erase) const
get is almost identical to contains(), with the difference that it obtains the found element (for Ele...
void insert(Element e, bool replace=false)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
void updateMempoolForReorg(Chainstate &active_chainstate, bool fAddToMempool, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
void addForBlock(const std::vector< CTransactionRef > &vtx, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Different type to mark Mutex at global scope.
static RCUPtr acquire(T *&ptrIn)
Acquire ownership of some pointer.
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range) noexcept
Return the time point advanced by a uniform random duration.
The script cache is a map using a key/value element, that caches the success of executing a specific ...
static TxSigCheckLimiter getDisabled()
Convenience class for initializing and passing the script execution cache and signature cache.
CuckooCache::cache< ScriptCacheElement, ScriptCacheHasher > m_script_execution_cache
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
SignatureCache m_signature_cache
void BlockFinalized(const CBlockIndex *pindex)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void ChainStateFlushed(ChainstateRole, const CBlockLocator &)
void BlockChecked(const CBlock &, const BlockValidationState &)
std::string GetRejectReason() const
std::string GetDebugMessage() const
bool Error(const std::string &reject_reason)
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
std::string ToString() const
256-bit unsigned big integer.
std::string ToString() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warning(const std::string &warning)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual InterruptResult blockTip(SynchronizationState state, CBlockIndex &index)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
const kernel::BlockManagerOpts m_opts
RecursiveMutex cs_LastBlockFile
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
bool FlushChainstateBlockFile(int tip_height)
void FindFilesToPrune(std::set< int > &setFilesToPrune, int last_prune, const Chainstate &chain, ChainstateManager &chainman)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool LoadingBlocks() const
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
void WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(CBlockIndex * AddToBlockIndex(const CBlockHeader &block, CBlockIndex *&best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove any pruned block & undo files that are still on disk.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
std::atomic_bool m_reindexing
Tracks if a reindex is currently in progress.
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
bool IsPruneMode() const
Whether running in -prune mode.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight)
Store block on disk and update block file statistics.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
std::vector< CBlockIndex * > GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_CHILD_BEFORE_PARENT
This tx outputs are already spent in the mempool.
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/etc limits
@ TX_PACKAGE_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_DUPLICATE
Tx already in mempool or in the chain.
@ TX_INPUTS_NOT_STANDARD
inputs failed policy rules
@ TX_CONFLICT
Tx conflicts with a finalized tx, i.e.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_AVALANCHE_RECONSIDERABLE
fails some policy, but might be reconsidered by avalanche voting
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_CONSENSUS
invalid by consensus rules
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metricsOut, ScriptError *serror)
Execute an unlocking and locking script together.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
#define LogPrintLevel(category, level,...)
#define LogPrintLevel_(category, level, should_ratelimit,...)
#define LogPrint(category,...)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
bool CheckBlock(const CCheckpointData &data, int nHeight, const BlockHash &hash)
Returns true if block passes checkpoint checks.
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
FILE * fopen(const fs::path &p, const char *mode)
std::string get_filesystem_error_message(const fs::filesystem_error &e)
std::function< FILE *(const fs::path &, const char *)> FopenFn
bool IsInterrupted(const T &result)
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
The file in the snapshot chainstate dir which stores the base blockhash.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate)
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
std::optional< BlockHash > ReadSnapshotBaseBlockhash(const fs::path &chaindir)
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate) EXCLUSIVE_LOCKS_REQUIRED(std::optional< BlockHash > ReadSnapshotBaseBlockhash(const fs::path &chaindir) EXCLUSIVE_LOCKS_REQUIRED(constexpr std::string_view SNAPSHOT_CHAINSTATE_SUFFIX
Write out the blockhash of the snapshot base block that was used to construct this chainstate.
std::optional< fs::path > FindSnapshotChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
bilingual_str ErrorString(const Result< T > &result)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::shared_ptr< Chain::Notifications > m_notifications
bool IsChildWithParents(const Package &package)
Context-free check that a package is exactly one child and its parents; not all parents need to be pr...
bool CheckPackage(const Package &txns, PackageValidationState &state)
Context-free package policy checks:
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_MEMPOOL_ERROR
Mempool logic error.
@ PCKG_TX
At least one tx is invalid.
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, uint32_t flags)
Check transaction inputs to mitigate two potential denial-of-service attacks:
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
static constexpr uint32_t STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
std::shared_ptr< const CTransaction > CTransactionRef
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
reverse_range< T > reverse_iterate(T &x)
std::string ScriptErrorString(const ScriptError serror)
@ SIGCHECKS_LIMIT_EXCEEDED
@ SCRIPT_VERIFY_SIGPUSHONLY
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
@ SCRIPT_ENABLE_REPLAY_PROTECTION
@ SCRIPT_ENABLE_SCHNORR_MULTISIG
@ SCRIPT_VERIFY_STRICTENC
@ SCRIPT_ENFORCE_SIGCHECKS
@ SCRIPT_VERIFY_CLEANSTACK
@ SCRIPT_VERIFY_MINIMALDATA
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
@ SCRIPT_ENABLE_SIGHASH_FORKID
static std::string ToString(const CService &ip)
size_t GetSerializeSize(const T &t)
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
static constexpr Amount zero() noexcept
Holds configuration for use during UTXO snapshot load and validation.
AssumeutxoHash hash_serialized
The expected hash of the deserialized UTXO set.
unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
A BlockHash is a unqiue identifier for a block.
bool isValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< BlockHash > vHave
Holds various statistics on transactions within a chain.
User-controlled performance and debug options.
Parameters that influence chain consensus.
int BIP34Height
Block height and hash at which BIP34 becomes active.
int nSubsidyHalvingInterval
BlockHash hashGenesisBlock
int64_t nPowTargetSpacing
std::chrono::seconds PowTargetSpacing() const
int mengerActivationTime
Unix time used for MTP activation of 15 November 2026 12:00:00 UTC upgrade.
bool fPowAllowMinDifficultyBlocks
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
const ResultType m_result_type
Result type.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
static MempoolAcceptResult Success(int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for success case.
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
static time_point now() noexcept
Return current system time or mocked time, if set.
std::chrono::time_point< NodeClock > time_point
Validation result for package mempool acceptance.
Precompute sighash midstate to avoid quadratic hashing.
In future if many more values are added, it should be considered to expand the element size to 64 byt...
const char * what() const noexcept override
A TxId is the identifier of a transaction.
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
const fs::path blocks_dir
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const std::function< NodeClock::time_point()> adjusted_time_callback
std::optional< bool > check_block_index
ValidationSignals * signals
std::chrono::seconds max_tip_age
If the tip is older than this, the node is considered to be in initial block download.
bool store_recent_headers_time
If set, store and load the last few block headers reception time to speed up RTT bootstraping.
CoinsViewOptions coins_view
std::optional< int64_t > replay_protection_activation_time
If set, this overwrites the timestamp at which replay protection activates.
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define NO_THREAD_SAFETY_ANALYSIS
int64_t GetTimeMillis()
Returns the system time (not mockable)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
#define TRACE6(context, event, a, b, c, d, e, f)
#define TRACE5(context, event, a, b, c, d, e)
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
bool CheckRegularTransaction(const CTransaction &tx, TxValidationState &state)
Context-independent validity checks for coinbase and non-coinbase transactions.
bool CheckCoinbase(const CTransaction &tx, TxValidationState &state)
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state)
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
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.
bool ContextualCheckTransaction(const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
uint256 uint256S(const char *str)
uint256 from const char *.
static bool DeleteCoinsDBFromDisk(const fs::path &db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED(
static bool NotifyHeaderTip(ChainstateManager &chainman) LOCKS_EXCLUDED(cs_main)
static int64_t num_blocks_total
bool FatalError(Notifications ¬ifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage)
GlobalMutex g_best_block_mutex
static SteadyClock::duration time_connect_total
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...
return CheckInputScripts(tx, state, view, flags, true, true, txdata, validation_cache, nSigChecksOut)
DisconnectResult ApplyBlockUndo(CBlockUndo &&blockUndo, const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo a block from the block and the undoblock data.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept, unsigned int heightOverride)
Try to add a transaction to the mempool.
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params ¶ms, BlockValidationOptions validationOptions)
Return true if the provided block header is valid.
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
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.
static SteadyClock::duration time_post_connect
static SteadyClock::duration time_chainstate
static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex, const ChainstateManager &chainman)
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.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
static SteadyClock::duration time_forks
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
static constexpr auto DATABASE_WRITE_INTERVAL_MAX
static SteadyClock::duration time_verify
static bool CheckMerkleRoot(const CBlock &block, BlockValidationState &state)
static SynchronizationState GetSynchronizationState(bool init, bool reindexing)
static SteadyClock::duration time_check
static constexpr int PRUNE_LOCK_BUFFER
The number of blocks to keep below the deepest prune lock.
static SteadyClock::duration time_index
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 ¶ms, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
static SteadyClock::duration time_connect
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
DisconnectResult UndoCoinSpend(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
bool TestBlockValidity(BlockValidationState &state, const CChainParams ¶ms, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block)
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache, bool snapshot_loaded)
bool IsBlockMutated(const CBlock &block)
Check if a block has been mutated (with respect to its merkle root).
static constexpr auto DATABASE_WRITE_INTERVAL_MIN
Time window to wait between writing blocks/block index and chainstate to disk.
static SteadyClock::duration time_total
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags, PrecomputedTransactionData &txdata, ValidationCache &validation_cache, int &nSigChecksOut, CCoinsViewCache &coins_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
std::optional< std::vector< Coin > > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
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 bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, ChainstateManager &chainman, const CBlockIndex *pindexPrev, NodeClock::time_point now, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
static SteadyClock::duration time_flush
static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt &interrupt)
static constexpr uint64_t HEADERS_TIME_VERSION
static fs::path GetSnapshotCoinsDBPath(Chainstate &cs) EXCLUSIVE_LOCKS_REQUIRED(
static bool IsReplayProtectionEnabled(const Consensus::Params ¶ms, const CBlockIndex *pindexPrev, const std::optional< int64_t > activation_time)
static void UpdateTipLog(const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams ¶ms, const std::string &func_name, const std::string &prefix) EXCLUSIVE_LOCKS_REQUIRED(
static void LimitValidationInterfaceQueue(ValidationSignals &signals) LOCKS_EXCLUDED(cs_main)
#define MIN_TRANSACTION_SIZE
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...
@ BASE_BLOCKHASH_MISMATCH
SynchronizationState
Current sync state passed to tip changed callbacks.
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
void SetfLargeWorkInvalidChainFound(bool flag)
void SetfLargeWorkForkFound(bool flag)
bool GetfLargeWorkForkFound()