6#include <bitcoin-build-config.h>
103 "level 0 reads the blocks from disk",
104 "level 1 verifies block validity",
105 "level 2 verifies undo data",
106 "level 3 checks disconnection of tip blocks",
107 "level 4 tries to reconnect the blocks",
108 "each level includes the checks of the previous levels",
120 static constexpr uint32_t flush_ratio{320};
153 std::vector<CScriptCheck>* pvChecks =
nullptr)
166 const int nBlockHeight = active_chain_tip.nHeight + 1;
173 const int64_t nBlockTime{active_chain_tip.GetMedianTimePast()};
175 return IsFinalTx(tx, nBlockHeight, nBlockTime);
189std::optional<std::vector<int>> CalculatePrevHeights(
194 std::vector<int> prev_heights;
195 prev_heights.resize(tx.
vin.size());
196 for (
size_t i = 0; i < tx.
vin.size(); ++i) {
197 if (
auto coin{coins.
GetCoin(tx.
vin[i].prevout)}) {
202 LogInfo(
"ERROR: %s: Missing input %d in transaction \'%s\'\n", __func__, i, tx.
GetHash().
GetHex());
217 auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
218 if (!prev_heights.has_value())
return std::nullopt;
221 next_tip.
pprev = tip;
239 int max_input_height{0};
240 for (
const int height : prev_heights.value()) {
242 if (height != next_tip.
nHeight) {
243 max_input_height = std::max(max_input_height, height);
278 int expired = pool.Expire(GetTime<std::chrono::seconds>() - pool.m_opts.expiry);
283 std::vector<COutPoint> vNoSpendsRemaining;
284 pool.TrimToSize(pool.m_opts.max_size_bytes, &vNoSpendsRemaining);
285 for (
const COutPoint& removed : vNoSpendsRemaining)
286 coins_cache.Uncache(removed);
292 if (active_chainstate.m_chainman.IsInitialBlockDownload()) {
297 if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
311 std::vector<Txid> vHashUpdate;
318 const auto queuedTx = disconnectpool.
take();
319 auto it = queuedTx.rbegin();
320 while (it != queuedTx.rend()) {
322 if (!fAddToMempool || (*it)->IsCoinBase() ||
324 true,
false).m_result_type !=
330 vHashUpdate.push_back((*it)->GetHash());
371 it->UpdateLockPoints(*new_lock_points);
378 if (it->GetSpendsCoinbase()) {
384 if (coin.IsCoinBase() && mempool_spend_height - coin.nHeight <
COINBASE_MATURITY) {
420 if (coin.
IsSpent())
return false;
450 m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
451 m_active_chainstate(active_chainstate)
459 const int64_t m_accept_time;
460 const bool m_bypass_limits;
468 std::vector<COutPoint>& m_coins_to_uncache;
470 const bool m_test_accept;
474 const bool m_allow_replacement;
476 const bool m_allow_sibling_eviction;
479 const bool m_package_submission;
483 const bool m_package_feerates;
488 const std::optional<CFeeRate> m_client_maxfeerate;
491 static ATMPArgs SingleAccept(
const CChainParams& chainparams, int64_t accept_time,
492 bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
494 return ATMPArgs{ chainparams,
508 static ATMPArgs PackageTestAccept(
const CChainParams& chainparams, int64_t accept_time,
509 std::vector<COutPoint>& coins_to_uncache) {
510 return ATMPArgs{ chainparams,
524 static ATMPArgs PackageChildWithParents(
const CChainParams& chainparams, int64_t accept_time,
525 std::vector<COutPoint>& coins_to_uncache,
const std::optional<CFeeRate>& client_maxfeerate) {
526 return ATMPArgs{ chainparams,
540 static ATMPArgs SingleInPackageAccept(
const ATMPArgs& package_args) {
541 return ATMPArgs{ package_args.m_chainparams,
542 package_args.m_accept_time,
544 package_args.m_coins_to_uncache,
545 package_args.m_test_accept,
550 package_args.m_client_maxfeerate,
560 std::vector<COutPoint>& coins_to_uncache,
562 bool allow_replacement,
563 bool allow_sibling_eviction,
564 bool package_submission,
565 bool package_feerates,
566 std::optional<CFeeRate> client_maxfeerate)
567 : m_chainparams{chainparams},
568 m_accept_time{accept_time},
569 m_bypass_limits{bypass_limits},
570 m_coins_to_uncache{coins_to_uncache},
571 m_test_accept{test_accept},
572 m_allow_replacement{allow_replacement},
573 m_allow_sibling_eviction{allow_sibling_eviction},
574 m_package_submission{package_submission},
575 m_package_feerates{package_feerates},
576 m_client_maxfeerate{client_maxfeerate}
580 if (m_package_feerates) {
581 Assume(m_package_submission);
582 Assume(!m_allow_sibling_eviction);
584 if (m_allow_sibling_eviction)
Assume(m_allow_replacement);
595 ClearSubPackageState();
608 ClearSubPackageState();
639 std::set<Txid> m_conflicts;
644 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
649 bool m_sibling_eviction{
false};
682 bool PackageRBFChecks(
const std::vector<CTransactionRef>& txns,
683 std::vector<Workspace>& workspaces,
704 std::map<Wtxid, MempoolAcceptResult>& results)
712 CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
713 if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
717 if (package_fee < m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
719 strprintf(
"%d < %d", package_fee, m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
726 return m_active_chainstate.m_chainman.m_validation_cache;
754 struct SubPackageState {
756 CAmount m_total_modified_fees{0};
758 int64_t m_total_vsize{0};
765 std::list<CTransactionRef> m_replaced_transactions;
767 std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
772 size_t m_conflicting_size{0};
775 struct SubPackageState m_subpackage;
780 m_subpackage = SubPackageState{};
783 CleanupTemporaryCoins();
787bool MemPoolAccept::PreChecks(ATMPArgs&
args, Workspace& ws)
793 const Txid& hash = ws.m_hash;
796 const int64_t nAcceptTime =
args.m_accept_time;
797 const bool bypass_limits =
args.m_bypass_limits;
798 std::vector<COutPoint>& coins_to_uncache =
args.m_coins_to_uncache;
813 if (m_pool.m_opts.require_standard && !
IsStandardTx(tx, m_pool.m_opts.max_datacarrier_bytes, m_pool.m_opts.permit_bare_multisig, m_pool.m_opts.dust_relay_feerate, reason)) {
831 }
else if (m_pool.exists(tx.
GetHash())) {
841 if (ptxConflicting) {
842 if (!
args.m_allow_replacement) {
846 ws.m_conflicts.insert(ptxConflicting->
GetHash());
850 m_view.SetBackend(m_viewmempool);
856 coins_to_uncache.push_back(txin.
prevout);
862 if (!m_view.HaveCoin(txin.
prevout)) {
877 (void)m_view.GetBestBlock();
884 assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
891 const std::optional<LockPoints> lock_points{
CalculateLockPointsAtTip(m_active_chainstate.m_chain.Tip(), m_view, tx)};
901 if (m_pool.m_opts.require_standard) {
917 bool fSpendsCoinbase =
false;
919 const Coin &coin = m_view.AccessCoin(txin.
prevout);
921 fSpendsCoinbase =
true;
928 const uint64_t entry_sequence = bypass_limits ? 0 : m_pool.GetSequence();
929 if (!m_subpackage.m_changeset) {
930 m_subpackage.m_changeset = m_pool.GetChangeSet();
932 ws.m_tx_handle = m_subpackage.m_changeset->StageAddition(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(), entry_sequence, fSpendsCoinbase, nSigOpsCost, lock_points.value());
935 ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
937 ws.m_vsize = ws.m_tx_handle->GetTxSize();
940 if (m_pool.m_opts.require_standard) {
941 if (!
PreCheckEphemeralTx(*ptx, m_pool.m_opts.dust_relay_feerate, ws.m_base_fees, ws.m_modified_fees, state)) {
953 if (!bypass_limits && !
args.m_package_feerates && !
CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state))
return false;
955 ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
957 ws.m_parents = m_pool.GetParents(*ws.m_tx_handle);
959 if (!
args.m_bypass_limits) {
961 if (
const auto err{
SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
963 if (
args.m_allow_sibling_eviction && err->second !=
nullptr) {
968 ws.m_conflicts.insert(err->second->GetHash());
972 ws.m_iters_conflicting.insert(m_pool.GetIter(err->second->GetHash()).value());
973 ws.m_sibling_eviction =
true;
985 m_subpackage.m_rbf |= !ws.m_conflicts.empty();
989bool MemPoolAccept::ReplacementChecks(Workspace& ws)
995 const Txid& hash = ws.m_hash;
998 CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize);
1005 strprintf(
"too many potential replacements%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *err_string);
1011 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1012 m_subpackage.m_conflicting_size += it->GetTxSize();
1015 if (
const auto err_string{
PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
1016 m_pool.m_opts.incremental_relay_feerate, hash)}) {
1019 strprintf(
"insufficient fee%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *err_string);
1023 for (
auto it : all_conflicts) {
1024 m_subpackage.m_changeset->StageRemoval(it);
1028 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1042bool MemPoolAccept::PackageRBFChecks(
const std::vector<CTransactionRef>& txns,
1043 std::vector<Workspace>& workspaces,
1044 const int64_t total_vsize,
1050 assert(std::all_of(txns.cbegin(), txns.cend(), [
this](
const auto& tx)
1051 { return !m_pool.exists(tx->GetHash());}));
1053 assert(txns.size() == workspaces.size());
1068 for (
const auto& ws : workspaces) {
1069 if (!ws.m_parents.empty()) {
1076 for (Workspace& ws : workspaces) {
1078 direct_conflict_iters.merge(ws.m_iters_conflicting);
1081 const auto& parent_ws = workspaces[0];
1082 const auto& child_ws = workspaces[1];
1090 "package RBF failed: too many potential replacements", *err_string);
1094 m_subpackage.m_changeset->StageRemoval(it);
1095 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1096 m_subpackage.m_conflicting_size += it->GetTxSize();
1100 const Txid& child_hash = child_ws.m_ptx->GetHash();
1101 if (
const auto err_string{
PaysForRBF(m_subpackage.m_conflicting_fees,
1102 m_subpackage.m_total_modified_fees,
1103 m_subpackage.m_total_vsize,
1104 m_pool.m_opts.incremental_relay_feerate, child_hash)}) {
1106 "package RBF failed: insufficient anti-DoS fees", *err_string);
1111 const CFeeRate parent_feerate(parent_ws.m_modified_fees, parent_ws.m_vsize);
1112 const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1113 if (package_feerate <= parent_feerate) {
1115 "package RBF failed: package feerate is less than or equal to parent feerate",
1116 strprintf(
"package feerate %s <= parent feerate is %s", package_feerate.ToString(), parent_feerate.ToString()));
1120 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1128 "package RBF failed: " + err_tup.value().second,
"");
1131 LogDebug(
BCLog::TXPACKAGES,
"package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
1132 txns.front()->GetHash().ToString(), txns.front()->GetWitnessHash().ToString(),
1133 txns.back()->GetHash().ToString(), txns.back()->GetWitnessHash().ToString(),
1140bool MemPoolAccept::PolicyScriptChecks(
const ATMPArgs&
args, Workspace& ws)
1151 if (!
CheckInputScripts(tx, state, m_view, scriptVerifyFlags,
true,
false, ws.m_precomputed_txdata, GetValidationCache())) {
1163bool MemPoolAccept::ConsensusScriptChecks(
const ATMPArgs&
args, Workspace& ws)
1168 const Txid& hash = ws.m_hash;
1188 ws.m_precomputed_txdata, m_active_chainstate.CoinsTip(), GetValidationCache())) {
1189 LogError(
"BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s", hash.
ToString(), state.
ToString());
1196void MemPoolAccept::FinalizeSubpackage(
const ATMPArgs&
args)
1201 if (!m_subpackage.m_changeset->GetRemovals().empty())
Assume(
args.m_allow_replacement);
1205 std::string log_string =
strprintf(
"replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1206 it->GetTx().GetHash().ToString(),
1207 it->GetTx().GetWitnessHash().ToString(),
1210 FeeFrac feerate{m_subpackage.m_total_modified_fees, int32_t(m_subpackage.m_total_vsize)};
1212 const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
1213 if (replaced_with_tx) {
1214 const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1216 log_string +=
strprintf(
"New tx %s (wtxid=%s, fees=%s, vsize=%s)",
1222 tx_or_package_hash =
GetPackageHash(m_subpackage.m_changeset->GetAddedTxns());
1223 log_string +=
strprintf(
"New package %s with %lu txs, fees=%s, vsize=%s",
1224 tx_or_package_hash.ToString(),
1225 m_subpackage.m_changeset->GetTxCount(),
1232 it->GetTx().GetHash().data(),
1235 std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1236 tx_or_package_hash.data(),
1241 m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1243 m_subpackage.m_changeset->Apply();
1244 m_subpackage.m_changeset.reset();
1247bool MemPoolAccept::SubmitPackage(
const ATMPArgs&
args, std::vector<Workspace>& workspaces,
1249 std::map<Wtxid, MempoolAcceptResult>& results)
1255 assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [
this](
const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1257 bool all_submitted =
true;
1258 FinalizeSubpackage(
args);
1263 for (Workspace& ws : workspaces) {
1264 if (!ConsensusScriptChecks(
args, ws)) {
1268 all_submitted =
false;
1270 strprintf(
"BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1271 ws.m_ptx->GetHash().ToString()));
1274 if (!all_submitted) {
1275 if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.GetChangeSet();
1276 m_subpackage.m_changeset->StageRemoval(m_pool.GetIter(ws.m_ptx->GetHash()).value());
1279 if (!all_submitted) {
1280 Assume(m_subpackage.m_changeset);
1284 m_subpackage.m_changeset->Apply();
1285 m_subpackage.m_changeset.reset();
1289 std::vector<Wtxid> all_package_wtxids;
1290 all_package_wtxids.reserve(workspaces.size());
1291 std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1292 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1294 if (!m_subpackage.m_replaced_transactions.empty()) {
1295 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
1296 m_subpackage.m_replaced_transactions.size(), workspaces.size(),
1297 m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1298 m_subpackage.m_total_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1302 for (Workspace& ws : workspaces) {
1303 auto iter = m_pool.GetIter(ws.m_ptx->GetHash());
1304 Assume(iter.has_value());
1305 const auto effective_feerate =
args.m_package_feerates ? ws.m_package_feerate :
1306 CFeeRate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1307 const auto effective_feerate_wtxids =
args.m_package_feerates ? all_package_wtxids :
1308 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1309 results.emplace(ws.m_ptx->GetWitnessHash(),
1311 ws.m_base_fees, effective_feerate, effective_feerate_wtxids));
1312 if (!m_pool.m_opts.signals)
continue;
1315 ws.m_vsize, (*iter)->GetHeight(),
1316 args.m_bypass_limits,
args.m_package_submission,
1318 m_pool.HasNoInputsOf(tx));
1319 m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1321 return all_submitted;
1330 const std::vector<Wtxid> single_wtxid{ws.m_ptx->GetWitnessHash()};
1332 if (!PreChecks(
args, ws)) {
1340 if (m_subpackage.m_rbf && !ReplacementChecks(ws)) {
1349 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1356 if (ws.m_conflicts.size()) {
1357 auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1371 m_subpackage.m_total_vsize = ws.m_vsize;
1372 m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1375 if (
args.m_client_maxfeerate &&
CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1380 if (!
args.m_bypass_limits && m_pool.m_opts.require_standard) {
1382 if (!
CheckEphemeralSpends({ptx}, m_pool.m_opts.dust_relay_feerate, m_pool, ws.m_state, dummy_wtxid)) {
1393 const CFeeRate effective_feerate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1395 if (
args.m_test_accept) {
1397 ws.m_base_fees, effective_feerate, single_wtxid);
1400 FinalizeSubpackage(
args);
1403 if (!
args.m_package_submission && !
args.m_bypass_limits) {
1407 CleanupTemporaryCoins();
1409 if (!m_pool.exists(ws.m_hash)) {
1416 if (m_pool.m_opts.signals) {
1418 auto iter = m_pool.GetIter(tx.
GetHash());
1419 Assume(iter.has_value());
1421 ws.m_vsize, (*iter)->GetHeight(),
1422 args.m_bypass_limits,
args.m_package_submission,
1424 m_pool.HasNoInputsOf(tx));
1425 m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1428 if (!m_subpackage.m_replaced_transactions.empty()) {
1429 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
1430 m_subpackage.m_replaced_transactions.size(),
1431 ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1432 ws.m_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1436 effective_feerate, single_wtxid);
1448 std::vector<Workspace> workspaces{};
1449 workspaces.reserve(txns.size());
1450 std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1451 [](
const auto& tx) { return Workspace(tx); });
1452 std::map<Wtxid, MempoolAcceptResult> results;
1455 for (Workspace& ws : workspaces) {
1456 if (!PreChecks(
args, ws)) {
1465 if (
args.m_client_maxfeerate &&
CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1483 m_viewmempool.PackageAddTransaction(ws.m_ptx);
1488 for (Workspace& ws : workspaces) {
1489 if (
auto err{
PackageTRUCChecks(m_pool, ws.m_ptx, ws.m_vsize, txns, ws.m_parents)}) {
1504 m_subpackage.m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1505 [](int64_t
sum,
auto& ws) { return sum + ws.m_vsize; });
1506 m_subpackage.m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(),
CAmount{0},
1507 [](
CAmount sum,
auto& ws) { return sum + ws.m_modified_fees; });
1508 const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1509 std::vector<Wtxid> all_package_wtxids;
1510 all_package_wtxids.reserve(workspaces.size());
1511 std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1512 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1514 if (
args.m_package_feerates &&
1515 !
CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees, placeholder_state)) {
1522 if (m_subpackage.m_rbf && !PackageRBFChecks(txns, workspaces, m_subpackage.m_total_vsize, package_state)) {
1527 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1533 if (m_pool.m_opts.require_standard) {
1536 if (!
CheckEphemeralSpends(txns, m_pool.m_opts.dust_relay_feerate, m_pool, child_state, child_wtxid)) {
1543 for (Workspace& ws : workspaces) {
1544 ws.m_package_feerate = package_feerate;
1545 if (!PolicyScriptChecks(
args, ws)) {
1551 if (
args.m_test_accept) {
1552 const auto effective_feerate =
args.m_package_feerates ? ws.m_package_feerate :
1553 CFeeRate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1554 const auto effective_feerate_wtxids =
args.m_package_feerates ? all_package_wtxids :
1555 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1556 results.emplace(ws.m_ptx->GetWitnessHash(),
1558 ws.m_vsize, ws.m_base_fees, effective_feerate,
1559 effective_feerate_wtxids));
1565 if (!SubmitPackage(
args, workspaces, package_state, results)) {
1573void MemPoolAccept::CleanupTemporaryCoins()
1594 for (
const auto& outpoint : m_viewmempool.GetNonBaseCoins()) {
1597 m_view.Uncache(outpoint);
1600 m_viewmempool.Reset();
1608 if (subpackage.size() > 1) {
1609 return AcceptMultipleTransactionsInternal(subpackage,
args);
1611 const auto& tx = subpackage.front();
1612 ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(
args);
1613 const auto single_res = AcceptSingleTransactionInternal(tx, single_args);
1624 ClearSubPackageState();
1631 Assert(!package.empty());
1657 std::map<Wtxid, MempoolAcceptResult> results_final;
1661 std::map<Wtxid, MempoolAcceptResult> individual_results_nonfinal;
1663 bool quit_early{
false};
1664 std::vector<CTransactionRef> txns_package_eval;
1665 for (
const auto& tx : package) {
1667 const auto& txid = tx->
GetHash();
1671 if (m_pool.exists(wtxid)) {
1681 const auto& entry{*
Assert(m_pool.GetEntry(txid))};
1683 }
else if (m_pool.exists(txid)) {
1691 const auto& entry{*
Assert(m_pool.GetEntry(txid))};
1697 const auto single_package_res = AcceptSubPackage({tx},
args);
1698 const auto& single_res = single_package_res.m_tx_results.at(wtxid);
1702 assert(m_pool.exists(wtxid));
1703 results_final.emplace(wtxid, single_res);
1704 }
else if (package.size() == 1 ||
1718 individual_results_nonfinal.emplace(wtxid, single_res);
1720 individual_results_nonfinal.emplace(wtxid, single_res);
1721 txns_package_eval.push_back(tx);
1726 auto multi_submission_result = quit_early || txns_package_eval.empty() ?
PackageMempoolAcceptResult(package_state_quit_early, {}) :
1727 AcceptSubPackage(txns_package_eval,
args);
1733 ClearSubPackageState();
1740 for (
const auto& tx : package) {
1742 if (multi_submission_result.m_tx_results.contains(wtxid)) {
1744 Assume(!results_final.contains(wtxid));
1747 const auto& txresult = multi_submission_result.m_tx_results.at(wtxid);
1754 results_final.emplace(wtxid, txresult);
1756 }
else if (
const auto it{results_final.find(wtxid)}; it != results_final.end()) {
1760 Assume(!individual_results_nonfinal.contains(wtxid));
1762 if (!m_pool.exists(tx->
GetHash())) {
1767 results_final.erase(wtxid);
1770 }
else if (
const auto it{individual_results_nonfinal.find(wtxid)}; it != individual_results_nonfinal.end()) {
1773 results_final.emplace(wtxid, it->second);
1776 Assume(results_final.size() == package.size());
1783 int64_t accept_time,
bool bypass_limits,
bool test_accept)
1790 std::vector<COutPoint> coins_to_uncache;
1792 auto args = MemPoolAccept::ATMPArgs::SingleAccept(chainparams, accept_time, bypass_limits, coins_to_uncache, test_accept);
1793 MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransactionAndCleanup(tx,
args);
1801 for (
const COutPoint& hashTx : coins_to_uncache)
1804 tx->GetHash().data(),
1815 const Package& package,
bool test_accept,
const std::optional<CFeeRate>& client_maxfeerate)
1818 assert(!package.empty());
1819 assert(std::all_of(package.cbegin(), package.cend(), [](
const auto& tx){return tx != nullptr;}));
1821 std::vector<COutPoint> coins_to_uncache;
1826 auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(chainparams,
GetTime(), coins_to_uncache);
1827 return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactionsAndCleanup(package,
args);
1829 auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(chainparams,
GetTime(), coins_to_uncache, client_maxfeerate);
1830 return MemPoolAccept(pool, active_chainstate).AcceptPackage(package,
args);
1835 if (test_accept || result.m_state.IsInvalid()) {
1836 for (
const COutPoint& hashTx : coins_to_uncache) {
1855 nSubsidy >>= halvings;
1860 : m_dbview{
std::move(db_params),
std::move(options)},
1861 m_catcherview(&m_dbview) {}
1863void CoinsViews::InitCache(int32_t prevoutfetch_threads)
1866 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1867 auto thread_pool{std::make_shared<ThreadPool>(
"prevout")};
1868 if (prevoutfetch_threads > 0) {
1869 thread_pool->Start(prevoutfetch_threads);
1870 LogInfo(
"Block input prevout fetching uses %d additional threads", prevoutfetch_threads);
1872 m_connect_block_view = std::make_unique<CoinsViewOverlay>(&*m_cacheview, std::move(thread_pool));
1879 std::optional<uint256> from_snapshot_blockhash)
1880 : m_mempool(mempool),
1881 m_blockman(blockman),
1882 m_chainman(chainman),
1884 m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1895const CBlockIndex* Chainstate::SnapshotBase()
const
1899 return m_cached_snapshot_base;
1904 if (!m_target_blockhash)
return nullptr;
1906 return m_cached_target_block;
1909void Chainstate::SetTargetBlock(
CBlockIndex* block)
1914 m_target_blockhash.reset();
1916 m_cached_target_block = block;
1919void Chainstate::SetTargetBlockHash(
uint256 block_hash)
1921 m_target_blockhash = block_hash;
1922 m_cached_target_block =
nullptr;
1926 size_t cache_size_bytes,
1933 .cache_bytes = cache_size_bytes,
1934 .memory_only = in_memory,
1935 .wipe_data = should_wipe,
1943void Chainstate::InitCoinsCache(
size_t cache_size_bytes)
1961 if (this->GetRole().historical) {
1966 LogWarning(
"Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers.");
1969 _(
"Warning: Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers."));
1982 SetBlockFailureFlags(pindexNew);
1987 LogInfo(
"%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
1992 LogInfo(
"%s: current best=%s height=%d log2_work=%f date=%s", __func__,
2030 if (
VerifyScript(scriptSig,
m_tx_out.
scriptPubKey, witness,
m_flags,
CachingTransactionSignatureChecker(
ptxTo,
nIn,
m_tx_out.
nValue,
cacheStore, *
m_signature_cache, *
txdata), &error)) {
2031 return std::nullopt;
2034 return std::make_pair(error, std::move(debug_str));
2039 : m_signature_cache{signature_cache_bytes}
2050 LogInfo(
"Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2051 approx_size_bytes >> 20, script_execution_cache_bytes >> 20, num_elems);
2077 std::vector<CScriptCheck>* pvChecks)
2082 pvChecks->reserve(tx.
vin.size());
2099 std::vector<CTxOut> spent_outputs;
2100 spent_outputs.reserve(tx.
vin.size());
2102 for (
const auto& txin : tx.
vin) {
2106 spent_outputs.emplace_back(coin.
out);
2108 txdata.
Init(tx, std::move(spent_outputs));
2112 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
2123 pvChecks->emplace_back(std::move(
check));
2124 }
else if (
auto result =
check(); result.has_value()) {
2139 if (cacheFullScriptStore && !pvChecks) {
2167 if (undo.nHeight == 0) {
2173 undo.nHeight = alternate.
nHeight;
2198 LogError(
"DisconnectBlock(): failure reading undo data\n");
2202 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size()) {
2203 LogError(
"DisconnectBlock(): block and undo data inconsistent\n");
2213 bool fEnforceBIP30 = !((pindex->
nHeight==91722 && pindex->
GetBlockHash() ==
uint256{
"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
2214 (pindex->
nHeight==91812 && pindex->
GetBlockHash() ==
uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2217 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
2221 bool is_bip30_exception = (is_coinbase && !fEnforceBIP30);
2225 for (
size_t o = 0; o < tx.
vout.size(); o++) {
2226 if (!tx.
vout[o].scriptPubKey.IsUnspendable()) {
2231 if (!is_bip30_exception) {
2242 LogError(
"DisconnectBlock(): transaction and undo data inconsistent\n");
2245 for (
unsigned int j = tx.
vin.size(); j > 0;) {
2316 const auto time_start{SteadyClock::now()};
2332 if (!
CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {
2344 uint256 hashPrevBlock = pindex->
pprev ==
nullptr ?
uint256() : pindex->pprev->GetBlockHash();
2351 if (block_hash == params.GetConsensus().hashGenesisBlock) {
2357 const char* script_check_reason;
2359 script_check_reason =
"assumevalid=0 (always verify)";
2361 constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};
2369 script_check_reason =
"assumevalid hash not in headers";
2370 }
else if (it->second.GetAncestor(pindex->
nHeight) != pindex) {
2371 script_check_reason = (pindex->
nHeight > it->second.nHeight) ?
"block height above assumevalid height" :
"block not in assumevalid chain";
2373 script_check_reason =
"block not in best header chain";
2375 script_check_reason =
"best header chainwork below minimumchainwork";
2377 script_check_reason =
"block too recent relative to best header";
2393 script_check_reason =
nullptr;
2397 const auto time_1{SteadyClock::now()};
2398 m_chainman.time_check += time_1 - time_start;
2400 Ticks<MillisecondsDouble>(time_1 - time_start),
2442 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2474 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->
GetBlockHash() == params.GetConsensus().BIP34Hash));
2479 if (fEnforceBIP30 || pindex->
nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2480 for (
const auto& tx : block.
vtx) {
2481 for (
size_t o = 0; o < tx->
vout.size(); o++) {
2484 "tried to overwrite transaction");
2491 int nLockTimeFlags = 0;
2499 const auto time_2{SteadyClock::now()};
2502 Ticks<MillisecondsDouble>(time_2 - time_1),
2506 const bool fScriptChecks{!!script_check_reason};
2508 if (script_check_reason != m_last_script_check_reason_logged && role.validated && !role.historical) {
2509 if (fScriptChecks) {
2510 LogInfo(
"Enabling script verification at block #%d (%s): %s.",
2511 pindex->
nHeight, block_hash.ToString(), script_check_reason);
2513 LogInfo(
"Disabling script verification at block #%d (%s).",
2514 pindex->
nHeight, block_hash.ToString());
2516 m_last_script_check_reason_logged = script_check_reason;
2526 std::vector<PrecomputedTransactionData> txsdata(block.
vtx.size());
2527 std::optional<CCheckQueueControl<CScriptCheck>> control;
2530 std::vector<int> prevheights;
2533 int64_t nSigOpsCost = 0;
2534 blockundo.
vtxundo.reserve(block.
vtx.size() - 1);
2535 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2540 nInputs += tx.
vin.size();
2556 "accumulated fee in the block out of range");
2563 prevheights.resize(tx.
vin.size());
2564 for (
size_t j = 0; j < tx.
vin.size(); j++) {
2568 if (!
SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2587 bool fCacheResults = fJustCheck;
2593 std::vector<CScriptCheck> vChecks;
2595 if (tx_ok) control->Add(std::move(vChecks));
2609 blockundo.
vtxundo.emplace_back();
2613 const auto time_3{SteadyClock::now()};
2615 LogDebug(
BCLog::BENCH,
" - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (
unsigned)block.
vtx.size(),
2616 Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.
vtx.size(),
2617 nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2618 Ticks<SecondsDouble>(
m_chainman.time_connect),
2622 if (block.
vtx[0]->GetValueOut() > blockReward && state.
IsValid()) {
2624 strprintf(
"coinbase pays too much (actual=%d vs limit=%d)", block.
vtx[0]->GetValueOut(), blockReward));
2627 auto parallel_result = control->Complete();
2628 if (parallel_result.has_value() && state.
IsValid()) {
2636 const auto time_4{SteadyClock::now()};
2638 LogDebug(
BCLog::BENCH,
" - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
2639 Ticks<MillisecondsDouble>(time_4 - time_2),
2640 nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2641 Ticks<SecondsDouble>(
m_chainman.time_verify),
2648 if (!
m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2652 const auto time_5{SteadyClock::now()};
2655 Ticks<MillisecondsDouble>(time_5 - time_4),
2667 const auto time_6{SteadyClock::now()};
2670 Ticks<MillisecondsDouble>(time_6 - time_5),
2680 Ticks<std::chrono::nanoseconds>(time_5 - time_start)
2689 return this->GetCoinsCacheSizeState(
2695 size_t max_coins_cache_size_bytes,
2696 size_t max_mempool_size_bytes)
2701 int64_t nTotalSpace =
2702 max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2704 if (cacheSize > nTotalSpace) {
2705 LogInfo(
"Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2716 int nManualPruneHeight)
2720 std::set<int> setFilesToPrune;
2721 bool full_flush_completed =
false;
2728 bool fFlushForPrune =
false;
2735 std::optional<std::string> limiting_lock;
2737 for (
const auto& prune_lock :
m_blockman.m_prune_locks) {
2738 if (prune_lock.second.height_first == std::numeric_limits<int>::max())
continue;
2741 last_prune = std::max(1, std::min(last_prune, lock_height));
2742 if (last_prune == lock_height) {
2743 limiting_lock = prune_lock.first;
2747 if (limiting_lock) {
2748 LogDebug(
BCLog::PRUNE,
"%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
2751 if (nManualPruneHeight > 0) {
2756 std::min(last_prune, nManualPruneHeight),
2764 if (!setFilesToPrune.empty()) {
2765 fFlushForPrune =
true;
2767 m_blockman.m_block_tree_db->WriteFlag(
"prunedblockfiles",
true);
2784 LogDebug(
BCLog::COINDB,
"Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
2785 FlushStateModeNames[
size_t(mode)], fFlushForPrune, fCacheLarge, fCacheCritical, fPeriodicWrite);
2798 LogWarning(
"%s: Failed to flush block file.\n", __func__);
2809 if (fFlushForPrune) {
2815 if (!
CoinsTip().GetBestBlock().IsNull()) {
2827 full_flush_completed =
true;
2829 int64_t{Ticks<std::chrono::microseconds>(
NodeClock::now() - nNow)},
2831 (uint64_t)coins_count,
2832 (uint64_t)coins_mem_usage,
2833 (
bool)fFlushForPrune);
2837 if (should_write ||
m_next_write == NodeClock::time_point::max()) {
2842 if (full_flush_completed) {
2850 }
catch (
const std::exception& e) {
2851 LogWarning(
"Failed to start chainstate compaction (%s)", e.what());
2855 }
catch (
const std::runtime_error& e) {
2882 const std::string& func_name,
2883 const std::string&
prefix,
2884 const std::string& warning_messages,
2896 background_validation ? chainman.GetBackgroundVerificationProgress(*tip) : chainman.GuessVerificationProgress(tip),
2899 !warning_messages.empty() ?
strprintf(
" warning='%s'", warning_messages) :
"");
2902void Chainstate::UpdateTip(
const CBlockIndex* pindexNew)
2905 const auto& coins_tip = this->
CoinsTip();
2911 constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2912 if (pindexNew->
nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2923 std::vector<bilingual_str> warning_messages;
2926 for (
auto [bit, active] : bits) {
2931 warning_messages.push_back(warning);
2958 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2961 LogError(
"DisconnectTip(): Failed to read block\n");
2965 const auto time_start{SteadyClock::now()};
2969 if (DisconnectBlock(block, pindexDelete, view) !=
DISCONNECT_OK) {
2976 Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
2980 const int max_height_first{pindexDelete->
nHeight - 1};
2981 for (
auto& prune_lock :
m_blockman.m_prune_locks) {
2982 if (prune_lock.second.height_first <= max_height_first)
continue;
2984 prune_lock.second.height_first = max_height_first;
2985 LogDebug(
BCLog::PRUNE,
"%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
3005 UpdateTip(pindexDelete->
pprev);
3028 std::shared_ptr<const CBlock> block_to_connect,
3029 std::vector<ConnectedBlock>& connected_blocks,
3037 const auto time_1{SteadyClock::now()};
3038 if (!block_to_connect) {
3039 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3043 block_to_connect = std::move(pblockNew);
3048 const auto time_2{SteadyClock::now()};
3049 SteadyClock::time_point time_3;
3053 Ticks<MillisecondsDouble>(time_2 - time_1));
3056 const auto reset_guard{view.StartFetching(*block_to_connect)};
3057 bool rv =
ConnectBlock(*block_to_connect, state, pindexNew, view);
3067 time_3 = SteadyClock::now();
3068 m_chainman.time_connect_total += time_3 - time_2;
3071 Ticks<MillisecondsDouble>(time_3 - time_2),
3072 Ticks<SecondsDouble>(
m_chainman.time_connect_total),
3076 const auto time_4{SteadyClock::now()};
3079 Ticks<MillisecondsDouble>(time_4 - time_3),
3086 const auto time_5{SteadyClock::now()};
3087 m_chainman.time_chainstate += time_5 - time_4;
3089 Ticks<MillisecondsDouble>(time_5 - time_4),
3090 Ticks<SecondsDouble>(
m_chainman.time_chainstate),
3100 UpdateTip(pindexNew);
3102 const auto time_6{SteadyClock::now()};
3103 m_chainman.time_post_connect += time_6 - time_5;
3106 Ticks<MillisecondsDouble>(time_6 - time_5),
3107 Ticks<SecondsDouble>(
m_chainman.time_post_connect),
3110 Ticks<MillisecondsDouble>(time_6 - time_1),
3124 m_chainman.MaybeValidateSnapshot(*
this, current_cs);
3126 connected_blocks.emplace_back(pindexNew, std::move(block_to_connect));
3150 bool fInvalidAncestor =
false;
3152 assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);
3160 if (fFailedChain || fMissingData) {
3166 for (
CBlockIndex *pindexFailed = pindexNew; pindexFailed != pindexTest; pindexFailed = pindexFailed->
pprev) {
3170 if (fMissingData && !fFailedChain) {
3180 fInvalidAncestor =
true;
3184 if (!fInvalidAncestor)
3216 bool fBlocksDisconnected =
false;
3230 fBlocksDisconnected =
true;
3234 std::vector<CBlockIndex*> vpindexToConnect;
3235 bool fContinue =
true;
3240 int nTargetHeight = std::min(
nHeight + 32, index_most_work.
nHeight);
3241 vpindexToConnect.clear();
3242 vpindexToConnect.reserve(nTargetHeight -
nHeight);
3245 vpindexToConnect.push_back(pindexIter);
3246 pindexIter = pindexIter->
pprev;
3251 for (
CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
3252 if (!
ConnectTip(state, pindexConnect, pindexConnect == &index_most_work ? pblock : std::shared_ptr<const CBlock>(), connected_blocks, disconnectpool)) {
3259 fInvalidFound =
true;
3280 if (fBlocksDisconnected) {
3305 LogInfo(
"Leaving InitialBlockDownload (latching to false)");
3311 bool fNotify =
false;
3312 bool fInitialBlockDownload =
false;
3316 pindexHeader = m_best_header;
3318 if (pindexHeader != m_last_notified_header) {
3321 m_last_notified_header = pindexHeader;
3334 if (signals.CallbacksPending() > 10) {
3335 signals.SyncWithValidationInterfaceQueue();
3339bool Chainstate::ActivateBestChain(
BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3364 bool exited_ibd{
false};
3381 bool blocks_connected =
false;
3385 std::vector<ConnectedBlock> connected_blocks;
3387 if (pindexMostWork ==
nullptr) {
3392 if (pindexMostWork ==
nullptr || pindexMostWork ==
m_chain.
Tip()) {
3396 bool fInvalidFound =
false;
3397 std::shared_ptr<const CBlock> nullBlockPtr;
3402 if (!
ActivateBestChainStep(state, *pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->
GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connected_blocks)) {
3406 blocks_connected =
true;
3408 if (fInvalidFound) {
3410 pindexMostWork =
nullptr;
3414 for (
auto& [index, block] : std::move(connected_blocks)) {
3425 if (!blocks_connected)
return true;
3430 if (was_in_ibd && !still_in_ibd) {
3463 bool reached_target;
3480 if (reached_target) {
3499 }
while (pindexNewTip != pindexMostWork);
3534 return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3544 if (pindex->
nHeight == 0)
return false;
3558 std::multimap<const arith_uint256, CBlockIndex*> highpow_outofchain_headers;
3562 for (
auto& entry :
m_blockman.m_block_index) {
3572 highpow_outofchain_headers.insert({candidate.
nChainWork, &candidate});
3578 bool pindex_was_in_chain =
false;
3579 int disconnected = 0;
3593 pindex_was_in_chain =
true;
3606 if (!
ret)
return false;
3608 assert(disconnected_tip->pprev == new_tip);
3623 auto candidate_it = highpow_outofchain_headers.lower_bound(new_tip->nChainWork);
3625 const bool best_header_needs_update{
m_chainman.m_best_header->GetAncestor(disconnected_tip->nHeight) == disconnected_tip};
3626 if (best_header_needs_update) {
3631 while (candidate_it != highpow_outofchain_headers.end()) {
3633 if (candidate->
GetAncestor(disconnected_tip->nHeight) == disconnected_tip) {
3639 candidate_it = highpow_outofchain_headers.erase(candidate_it);
3649 if (best_header_needs_update &&
3657 to_mark_failed = disconnected_tip;
3683 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3693 if (pindex_was_in_chain) {
3703 *to_mark_failed->
pprev,
3715void Chainstate::SetBlockFailureFlags(
CBlockIndex* invalid_block)
3719 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3720 if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->
nHeight) == invalid_block) {
3733 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3735 block_index.nStatus &= ~BLOCK_FAILED_VALID;
3740 if (&block_index ==
m_chainman.m_best_invalid) {
3767 if (!target_block) {
3774 if (target_block->GetAncestor(pindex->
nHeight) == pindex) {
3784 pindexNew->
nTx = block.
vtx.size();
3790 auto prev_tx_sum = [](
CBlockIndex& block) {
return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3793 LogWarning(
"Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3797 pindexNew->nFile = pos.
nFile;
3798 pindexNew->nDataPos = pos.
nPos;
3799 pindexNew->nUndoPos = 0;
3809 std::deque<CBlockIndex*> queue;
3810 queue.push_back(pindexNew);
3813 while (!queue.empty()) {
3821 LogWarning(
"Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3826 for (
const auto& c : m_chainstates) {
3827 c->TryAddBlockIndexCandidate(pindex);
3829 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range =
m_blockman.
m_blocks_unlinked.equal_range(pindex);
3830 while (range.first != range.second) {
3831 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3832 queue.push_back(it->second);
3863 "hashMerkleRoot mismatch");
3872 "bad-txns-duplicate",
3873 "duplicate transaction");
3888 if (expect_witness_commitment) {
3893 assert(!block.
vtx.empty() && !block.
vtx[0]->vin.empty());
3894 const auto& witness_stack{block.
vtx[0]->vin[0].scriptWitness.stack};
3896 if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
3899 "bad-witness-nonce-size",
3900 strprintf(
"%s : invalid witness reserved value size", __func__));
3909 if (memcmp(hash_witness.
begin(), &block.
vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3912 "bad-witness-merkle-match",
3913 strprintf(
"%s : witness merkle commitment mismatch", __func__));
3922 for (
const auto& tx : block.
vtx) {
3926 "unexpected-witness",
3927 strprintf(
"%s : unexpected witness data found", __func__));
3967 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase())
3969 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
3970 if (block.
vtx[i]->IsCoinBase())
3975 for (
const auto& tx : block.
vtx) {
3987 unsigned int nSigOps = 0;
3988 for (
const auto& tx : block.
vtx)
3995 if (fCheckPOW && fCheckMerkleRoot)
4004 static const std::vector<unsigned char>
nonce(32, 0x00);
4007 tx.
vin[0].scriptWitness.stack.resize(1);
4008 tx.
vin[0].scriptWitness.stack[0] =
nonce;
4016 std::vector<unsigned char>
ret(32, 0x00);
4024 out.scriptPubKey[1] = 0x24;
4025 out.scriptPubKey[2] = 0xaa;
4026 out.scriptPubKey[3] = 0x21;
4027 out.scriptPubKey[4] = 0xa9;
4028 out.scriptPubKey[5] = 0xed;
4029 memcpy(&
out.scriptPubKey[6], witnessroot.
begin(), 32);
4039 return std::ranges::all_of(
headers,
4040 [&](
const auto& header) {
return CheckProofOfWork(header.GetHash(), header.nBits, consensusParams); });
4051 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase()) {
4058 return std::any_of(block.
vtx.begin(), block.
vtx.end(),
4059 [](
auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4099 assert(pindexPrev !=
nullptr);
4100 const int nHeight = pindexPrev->nHeight + 1;
4108 if (block.
GetBlockTime() <= pindexPrev->GetMedianTimePast())
4147 const int nHeight = pindexPrev ==
nullptr ? 0 : pindexPrev->
nHeight + 1;
4150 bool enforce_locktime_median_time_past{
false};
4152 assert(pindexPrev !=
nullptr);
4153 enforce_locktime_median_time_past =
true;
4156 const int64_t nLockTimeCutoff{enforce_locktime_median_time_past ?
4161 for (
const auto& tx : block.
vtx) {
4171 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
4172 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0]->vin[0].scriptSig.begin())) {
4208 BlockMap::iterator miSelf{
m_blockman.m_block_index.find(hash)};
4210 if (miSelf !=
m_blockman.m_block_index.end()) {
4235 pindexPrev = &((*mi).second);
4245 if (!min_pow_checked) {
4280 blocks_left = std::max<int64_t>(0, blocks_left);
4281 const double progress{100.0 * last_accepted.nHeight / (last_accepted.nHeight + blocks_left)};
4282 LogInfo(
"Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.nHeight, progress);
4300 if (now < m_last_presync_update + std::chrono::milliseconds{250})
return;
4301 m_last_presync_update = now;
4305 if (initial_download) {
4307 blocks_left = std::max<int64_t>(0, blocks_left);
4308 const double progress{100.0 * height / (height + blocks_left)};
4309 LogInfo(
"Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4316 const CBlock& block = *pblock;
4318 if (fNewBlock) *fNewBlock =
false;
4322 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4324 bool accepted_header{
AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4327 if (!accepted_header)
4351 if (fAlreadyHave)
return true;
4353 if (pindex->
nTx != 0)
return true;
4354 if (!fHasMoreOrSameWork)
return true;
4355 if (fTooFarAhead)
return true;
4366 if (!
CheckBlock(block, state, params.GetConsensus()) ||
4382 if (fNewBlock) *fNewBlock =
true;
4390 if (blockPos.IsNull()) {
4391 state.
Error(
strprintf(
"%s: Failed to find position to write new block to disk", __func__));
4396 }
catch (
const std::runtime_error& e) {
4427 if (new_block) *new_block =
false;
4442 ret =
AcceptBlock(block, state, &pindex, force_processing,
nullptr, new_block, min_pow_checked);
4457 LogError(
"%s: ActivateBestChain failed (%s)\n", __func__, state.
ToString());
4463 if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
4464 LogError(
"%s: [background] ActivateBestChain failed (%s)\n", __func__, bg_state.
ToString());
4489 const bool check_pow,
4490 const bool check_merkle_root)
4501 state.
Invalid({},
"inconclusive-not-best-prevblk");
4542 index_dummy.pprev = tip;
4544 index_dummy.phashBlock = &block_hash;
4548 if(!chainstate.
ConnectBlock(block, state, &index_dummy, view_dummy,
true)) {
4587 m_last_flushed_block = pindex;
4593 assert(
cs->setBlockIndexCandidates.empty());
4601 target = target->pprev;
4604 LogInfo(
"Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
4611 if (!this->GetRole().historical) {
4639 int nCheckLevel,
int nCheckDepth)
4648 if (nCheckDepth <= 0 || nCheckDepth > chainstate.
m_chain.
Height()) {
4651 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4652 LogInfo(
"Verifying last %i blocks at level %i", nCheckDepth, nCheckLevel);
4656 int nGoodTransactions = 0;
4659 bool skipped_no_block_data{
false};
4660 bool skipped_l3_checks{
false};
4661 LogInfo(
"Verification progress: 0%%");
4666 const int percentageDone = std::max(1, std::min(99, (
int)(((
double)(chainstate.
m_chain.
Height() - pindex->
nHeight)) / (
double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4667 if (reportDone < percentageDone / 10) {
4669 LogInfo(
"Verification progress: %d%%", percentageDone);
4670 reportDone = percentageDone / 10;
4679 LogInfo(
"Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->
nHeight);
4680 skipped_no_block_data =
true;
4690 if (nCheckLevel >= 1 && !
CheckBlock(block, state, consensus_params)) {
4691 LogError(
"Verification error: found bad block at %d, hash=%s (%s)",
4696 if (nCheckLevel >= 2 && pindex) {
4708 if (nCheckLevel >= 3) {
4717 nGoodTransactions = 0;
4718 pindexFailure = pindex;
4720 nGoodTransactions += block.
vtx.size();
4723 skipped_l3_checks =
true;
4728 if (pindexFailure) {
4729 LogError(
"Verification error: coin database inconsistencies found (last %i blocks, %i good transactions before that)", chainstate.
m_chain.
Height() - pindexFailure->
nHeight + 1, nGoodTransactions);
4732 if (skipped_l3_checks) {
4733 LogWarning(
"Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4740 if (nCheckLevel >= 4 && !skipped_l3_checks) {
4742 const int percentageDone = std::max(1, std::min(99, 100 - (
int)(((
double)(chainstate.
m_chain.
Height() - pindex->
nHeight)) / (
double)nCheckDepth * 50)));
4743 if (reportDone < percentageDone / 10) {
4745 LogInfo(
"Verification progress: %d%%", percentageDone);
4746 reportDone = percentageDone / 10;
4755 if (!chainstate.
ConnectBlock(block, state, pindex, coins)) {
4763 LogInfo(
"Verification: checked last %i blocks at level %i", block_count, nCheckLevel);
4764 if (nCheckLevel >= 3 && !skipped_l3_checks) {
4765 LogInfo(
"Verification: no coin database inconsistencies (%i transactions)", nGoodTransactions);
4768 if (skipped_l3_checks) {
4771 if (skipped_no_block_data) {
4789 if (!tx->IsCoinBase()) {
4790 for (
const CTxIn &txin : tx->vin) {
4807 std::vector<uint256> hashHeads =
db.GetHeadBlocks();
4808 if (hashHeads.empty())
return true;
4809 if (hashHeads.size() != 2) {
4810 LogError(
"ReplayBlocks(): unknown inconsistent state\n");
4821 if (!
m_blockman.m_block_index.contains(hashHeads[0])) {
4822 LogError(
"ReplayBlocks(): reorganization to unknown block requested\n");
4825 pindexNew = &(
m_blockman.m_block_index[hashHeads[0]]);
4827 if (!hashHeads[1].IsNull()) {
4828 if (!
m_blockman.m_block_index.contains(hashHeads[1])) {
4829 LogError(
"ReplayBlocks(): reorganization from unknown block requested\n");
4832 pindexOld = &(
m_blockman.m_block_index[hashHeads[1]]);
4834 assert(pindexFork !=
nullptr);
4838 const int nForkHeight{pindexFork ? pindexFork->
nHeight : 0};
4839 if (pindexOld != pindexFork) {
4841 while (pindexOld != pindexFork) {
4848 if (pindexOld->
nHeight % 10'000 == 0) {
4861 pindexOld = pindexOld->
pprev;
4867 if (nForkHeight < pindexNew->
nHeight) {
4899 block = block->pprev;
4905void Chainstate::ClearBlockIndexCandidates()
4911void Chainstate::PopulateBlockIndexCandidates()
4919 if (pindex == SnapshotBase() ||
4933 if (!
ret)
return false;
4935 m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
4937 std::vector<CBlockIndex*> vSortedByHeight{
m_blockman.GetAllBlockIndices()};
4938 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
4944 m_best_invalid = pindex;
4947 m_best_header = pindex;
4963 if (
m_blockman.m_block_index.contains(genesis_block.GetHash())) {
4969 if (blockPos.IsNull()) {
4970 LogError(
"Writing genesis block to disk failed");
4975 }
catch (
const std::runtime_error& e) {
4976 LogError(
"Failed to write genesis block: %s", e.what());
4986 std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent)
4989 assert(!dbp == !blocks_with_unknown_parent);
4991 const auto start{SteadyClock::now()};
4999 uint64_t nRewind = blkdat.GetPos();
5000 while (!blkdat.eof()) {
5003 blkdat.SetPos(nRewind);
5006 unsigned int nSize = 0;
5010 blkdat.FindByte(std::byte(params.MessageStart()[0]));
5011 nRewind = blkdat.GetPos() + 1;
5013 if (buf != params.MessageStart()) {
5020 }
catch (
const std::exception&) {
5027 const uint64_t nBlockPos{blkdat.GetPos()};
5029 dbp->
nPos = nBlockPos;
5030 blkdat.SetLimit(nBlockPos + nSize);
5036 nRewind = nBlockPos + nSize;
5037 blkdat.SkipTo(nRewind);
5039 std::shared_ptr<CBlock> pblock{};
5047 if (dbp && blocks_with_unknown_parent) {
5048 blocks_with_unknown_parent->emplace(header.
hashPrevBlock, *dbp);
5057 blkdat.SetPos(nBlockPos);
5058 pblock = std::make_shared<CBlock>();
5060 nRewind = blkdat.GetPos();
5063 if (
AcceptBlock(pblock, state,
nullptr,
true, dbp,
nullptr,
true)) {
5069 }
else if (hash != params.GetConsensus().hashGenesisBlock && pindex->
nHeight % 1000 == 0) {
5096 if (
auto result{ActivateBestChains()}; !result) {
5104 if (!blocks_with_unknown_parent)
continue;
5107 std::deque<uint256> queue;
5108 queue.push_back(hash);
5109 while (!queue.empty()) {
5112 auto range = blocks_with_unknown_parent->equal_range(head);
5113 while (range.first != range.second) {
5114 std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5115 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5117 const auto& block_hash{pblockrecursive->GetHash()};
5121 if (
AcceptBlock(pblockrecursive, dummy,
nullptr,
true, &it->second,
nullptr,
true)) {
5123 queue.push_back(block_hash);
5127 blocks_with_unknown_parent->erase(it);
5131 }
catch (
const std::exception& e) {
5143 LogDebug(
BCLog::REINDEX,
"%s: unexpected data at file offset 0x%x - %s. continuing\n", __func__, (nRewind - 1), e.what());
5146 }
catch (
const std::runtime_error& e) {
5149 LogInfo(
"Loaded %i blocks from external file in %dms", nLoaded, Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
5184 best_hdr_chain.
SetTip(*m_best_header);
5186 std::multimap<const CBlockIndex*, const CBlockIndex*> forward;
5187 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
5189 if (!best_hdr_chain.
Contains(block_index)) {
5191 assert(block_index.pprev);
5192 forward.emplace(block_index.pprev, &block_index);
5206 const CBlockIndex* pindexFirstNeverProcessed =
nullptr;
5207 const CBlockIndex* pindexFirstNotTreeValid =
nullptr;
5208 const CBlockIndex* pindexFirstNotTransactionsValid =
nullptr;
5209 const CBlockIndex* pindexFirstNotChainValid =
nullptr;
5210 const CBlockIndex* pindexFirstNotScriptsValid =
nullptr;
5217 const CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{}, *snap_first_nocv{}, *snap_first_nosv{};
5218 auto snap_update_firsts = [&] {
5219 if (pindex == snap_base) {
5220 std::swap(snap_first_missing, pindexFirstMissing);
5221 std::swap(snap_first_notx, pindexFirstNeverProcessed);
5222 std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
5223 std::swap(snap_first_nocv, pindexFirstNotChainValid);
5224 std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
5228 while (pindex !=
nullptr) {
5230 if (pindexFirstInvalid ==
nullptr && pindex->nStatus &
BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5231 if (pindexFirstMissing ==
nullptr && !(pindex->nStatus &
BLOCK_HAVE_DATA)) {
5232 pindexFirstMissing = pindex;
5234 if (pindexFirstNeverProcessed ==
nullptr && pindex->
nTx == 0) pindexFirstNeverProcessed = pindex;
5237 if (pindex->
pprev !=
nullptr) {
5238 if (pindexFirstNotTransactionsValid ==
nullptr &&
5240 pindexFirstNotTransactionsValid = pindex;
5243 if (pindexFirstNotChainValid ==
nullptr &&
5245 pindexFirstNotChainValid = pindex;
5248 if (pindexFirstNotScriptsValid ==
nullptr &&
5250 pindexFirstNotScriptsValid = pindex;
5255 if (pindex->
pprev ==
nullptr) {
5258 for (
const auto& c : m_chainstates) {
5259 if (c->m_chain.Genesis() !=
nullptr) {
5260 assert(pindex == c->m_chain.Genesis());
5272 assert(pindexFirstMissing == pindexFirstNeverProcessed);
5278 if (snap_base && snap_base->GetAncestor(pindex->
nHeight) == pindex) {
5288 assert((pindexFirstNotTransactionsValid ==
nullptr || pindex == snap_base) == pindex->
HaveNumChainTxs());
5292 assert(pindexFirstNotTreeValid ==
nullptr);
5296 if (pindexFirstInvalid ==
nullptr) {
5303 if (!pindex->
pprev) {
5318 for (
const auto& c : m_chainstates) {
5319 if (c->m_chain.Tip() ==
nullptr)
continue;
5333 if (!
CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && (pindexFirstNeverProcessed ==
nullptr || pindex == snap_base)) {
5337 if (pindexFirstInvalid ==
nullptr) {
5356 if (pindexFirstMissing ==
nullptr || pindex == c->m_chain.Tip() || pindex == c->SnapshotBase()) {
5362 if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5363 assert(c->setBlockIndexCandidates.contains(pindex));
5371 assert(!c->setBlockIndexCandidates.contains(pindex));
5376 bool foundInUnlinked =
false;
5377 for (
auto it = rangeUnlinked.first; it != rangeUnlinked.second; ++it) {
5379 if (it->second == pindex) {
5380 assert(!foundInUnlinked);
5381 foundInUnlinked =
true;
5384 if (pindex->
pprev && (pindex->nStatus &
BLOCK_HAVE_DATA) && pindexFirstNeverProcessed !=
nullptr && pindexFirstInvalid ==
nullptr) {
5389 if (pindexFirstMissing ==
nullptr)
assert(!foundInUnlinked);
5390 if (pindex->
pprev && (pindex->nStatus &
BLOCK_HAVE_DATA) && pindexFirstNeverProcessed ==
nullptr && pindexFirstMissing !=
nullptr) {
5401 for (
const auto& c : m_chainstates) {
5403 if (pindexFirstInvalid ==
nullptr) {
5404 if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5416 snap_update_firsts();
5417 auto range{forward.equal_range(pindex)};
5418 if (range.first != range.second) {
5420 pindex = range.first->second;
5423 }
else if (best_hdr_chain.
Contains(*pindex)) {
5426 pindex = best_hdr_chain[
nHeight];
5434 snap_update_firsts();
5436 if (pindex == pindexFirstInvalid) pindexFirstInvalid =
nullptr;
5437 if (pindex == pindexFirstMissing) pindexFirstMissing =
nullptr;
5438 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed =
nullptr;
5439 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid =
nullptr;
5440 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid =
nullptr;
5441 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid =
nullptr;
5442 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid =
nullptr;
5446 auto rangePar{forward.equal_range(pindexPar)};
5447 while (rangePar.first->second != pindex) {
5448 assert(rangePar.first != rangePar.second);
5453 if (rangePar.first != rangePar.second) {
5455 pindex = rangePar.first->second;
5457 }
else if (pindexPar == best_hdr_chain[
nHeight - 1]) {
5459 pindex = best_hdr_chain[
nHeight];
5461 assert((pindex ==
nullptr) == (pindexPar == best_hdr_chain.
Tip()));
5473 assert(nNodes == forward.size() + best_hdr_chain.
Height() + 1);
5480 return strprintf(
"Chainstate [%s] @ height %d (%s)",
5485bool Chainstate::ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
5498 LogInfo(
"[%s] resized coinsdb cache to %.1f MiB",
5499 this->
ToString(), coinsdb_size /
double(1_MiB));
5500 LogInfo(
"[%s] resized coinstip cache to %.1f MiB",
5501 this->
ToString(), coinstip_size /
double(1_MiB));
5506 if (coinstip_size > old_coinstip_size) {
5520 if (pindex ==
nullptr) {
5529 const int64_t nNow{TicksSinceEpoch<std::chrono::seconds>(
NodeClock::now())};
5530 const auto block_time{
5531 (
Assume(m_best_header) && std::abs(nNow - pindex->
GetBlockTime()) <= Ticks<std::chrono::seconds>(2h) &&
5545 fTxTotal =
data.tx_count + (nNow -
data.nTime) *
data.dTxRate;
5563 return static_cast<double>(pindex.
m_chain_tx_count) /
static_cast<double>(target_block->m_chain_tx_count);
5569 assert(m_chainstates.empty());
5570 m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool,
m_blockman, *
this));
5571 return *m_chainstates.back();
5583 bool existed = fs::remove(base_blockhash_path);
5585 LogWarning(
"[snapshot] snapshot chainstate dir being removed lacks %s file",
5588 }
catch (
const fs::filesystem_error& e) {
5589 LogWarning(
"[snapshot] failed to remove file %s: %s\n",
5595 LogInfo(
"Removing leveldb dir at %s\n", path_str);
5599 const bool destroyed =
DestroyDB(path_str);
5602 LogError(
"leveldb DestroyDB call failed on %s", path_str);
5629 if (!
GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
5631 std::string heights_formatted =
util::Join(available_heights,
", ", [&](
const auto& i) {
return util::ToString(i); });
5632 return util::Error{
Untranslated(
strprintf(
"assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5634 heights_formatted))};
5638 if (!snapshot_start_block) {
5639 return util::Error{
Untranslated(
strprintf(
"The base block header (%s) must appear in the headers chain. Make sure all headers are syncing, and call loadtxoutset again",
5644 if (start_block_invalid) {
5648 if (!m_best_header || m_best_header->GetAncestor(snapshot_start_block->nHeight) != snapshot_start_block) {
5649 return util::Error{
Untranslated(
"A forked headers-chain with more work than the chain with the snapshot base block header exists. Please proceed to sync without AssumeUtxo.")};
5653 if (mempool && mempool->
size() > 0) {
5658 int64_t current_coinsdb_cache_size{0};
5659 int64_t current_coinstip_cache_size{0};
5667 static constexpr double IBD_CACHE_PERC = 0.01;
5668 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
5686 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
5687 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
5691 return std::make_unique<Chainstate>(
5692 nullptr,
m_blockman, *
this, base_blockhash));
5696 snapshot_chainstate->InitCoinsDB(
5697 static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
5699 snapshot_chainstate->InitCoinsCache(
5700 static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
5704 this->MaybeRebalanceCaches();
5712 snapshot_chainstate.reset();
5716 "Manually remove it before restarting.\n"), fs::PathToString(*snapshot_datadir)));
5733 return cleanup_bad_snapshot(
Untranslated(
"work does not exceed active chainstate"));
5739 return cleanup_bad_snapshot(
Untranslated(
"could not write base blockhash"));
5743 Chainstate& chainstate{AddChainstate(std::move(snapshot_chainstate))};
5746 chainstate.PopulateBlockIndexCandidates();
5748 LogInfo(
"[snapshot] successfully activated snapshot %s", base_blockhash.
ToString());
5749 LogInfo(
"[snapshot] (%.2f MB)",
5750 chainstate.CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
5752 this->MaybeRebalanceCaches();
5753 return snapshot_start_block;
5760 snapshot_loaded ?
"saving snapshot chainstate" :
"flushing coins cache",
5764 coins_cache.
Flush();
5769 const char*
what() const noexcept
override
5771 return "ComputeUTXOStats interrupted.";
5793 if (!snapshot_start_block) {
5800 int base_height = snapshot_start_block->
nHeight;
5803 if (!maybe_au_data) {
5805 "(%d) - refusing to load snapshot", base_height))};
5820 LogInfo(
"[snapshot] loading %d coins from snapshot %s", coins_left, base_blockhash.
ToString());
5821 int64_t coins_processed{0};
5823 while (coins_left > 0) {
5827 size_t coins_per_txid{0};
5830 if (coins_per_txid > coins_left) {
5834 for (
size_t i = 0; i < coins_per_txid; i++) {
5838 outpoint.
hash = txid;
5840 if (coin.
nHeight > base_height ||
5841 outpoint.
n >= std::numeric_limits<
decltype(outpoint.
n)>::max()
5844 coins_count - coins_left))};
5848 coins_count - coins_left))};
5855 if (coins_processed % 1000000 == 0) {
5856 LogInfo(
"[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5858 static_cast<float>(coins_processed) * 100 /
static_cast<float>(coins_count),
5866 if (coins_processed % 120000 == 0) {
5872 return snapshot_chainstate.GetCoinsCacheSizeState());
5885 }
catch (
const std::ios_base::failure&) {
5898 bool out_of_coins{
false};
5900 std::byte left_over_byte;
5901 coins_file >> left_over_byte;
5902 }
catch (
const std::ios_base::failure&) {
5904 out_of_coins =
true;
5906 if (!out_of_coins) {
5911 LogInfo(
"[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
5925 std::optional<CCoinsStats> maybe_stats;
5933 if (!maybe_stats.has_value()) {
5954 constexpr int AFTER_GENESIS_START{1};
5956 for (
int i = AFTER_GENESIS_START; i <= snapshot_chainstate.
m_chain.
Height(); ++i) {
5957 index = snapshot_chainstate.
m_chain[i];
5974 assert(index == snapshot_start_block);
5977 LogInfo(
"[snapshot] validated snapshot (%.2f MB)",
6004 !validated_cs.m_target_blockhash ||
6015 "%s failed to validate the -assumeutxo snapshot state. "
6016 "This indicates a hardware problem, or a bug in the software, or a "
6017 "bad software modification that allowed an invalid snapshot to be "
6018 "loaded. As a result of this, the node will shut down and stop using any "
6019 "state that was built on the snapshot, resetting the chain height "
6020 "from %d to %d. On the next "
6021 "restart, the node will resume syncing from %d "
6022 "without using any snapshot data. "
6023 "Please report this incident to %s, including how you obtained the snapshot. "
6024 "The invalid snapshot chainstate will be left on disk in case it is "
6025 "helpful in diagnosing the issue that caused this error."),
6031 LogError(
"[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6034 validated_cs.SetTargetBlock(
nullptr);
6038 auto rename_result = unvalidated_cs.InvalidateCoinsDBOnDisk();
6039 if (!rename_result) {
6050 if (!maybe_au_data) {
6051 LogWarning(
"[snapshot] assumeutxo data not found for height "
6052 "(%d) - refusing to validate snapshot", validated_cs.
m_chain.
Height());
6053 handle_invalid_snapshot();
6058 std::optional<CCoinsStats> validated_cs_stats;
6059 LogInfo(
"[snapshot] computing UTXO stats for background chainstate to validate "
6060 "snapshot - this could take a few minutes");
6063 CoinStatsHashType::HASH_SERIALIZED,
6072 if (!validated_cs_stats) {
6073 LogWarning(
"[snapshot] failed to generate stats for validation coins db");
6077 handle_invalid_snapshot();
6088 LogWarning(
"[snapshot] hash mismatch: actual=%s, expected=%s",
6089 validated_cs_stats->hashSerialized.ToString(),
6091 handle_invalid_snapshot();
6095 LogInfo(
"[snapshot] snapshot beginning at %s has been fully validated",
6099 validated_cs.m_target_utxohash =
AssumeutxoHash{validated_cs_stats->hashSerialized};
6100 this->MaybeRebalanceCaches();
6111void ChainstateManager::MaybeRebalanceCaches()
6116 if (!historical_cs && !current_cs.m_from_snapshot_blockhash) {
6120 }
else if (!historical_cs) {
6122 LogInfo(
"[snapshot] allocating all cache to the snapshot chainstate");
6130 historical_cs->ResizeCoinsCaches(
6132 current_cs.ResizeCoinsCaches(
6135 current_cs.ResizeCoinsCaches(
6137 historical_cs->ResizeCoinsCaches(
6143void ChainstateManager::ResetChainstates()
6145 m_chainstates.clear();
6155 if (!opts.check_block_index.has_value()) opts.
check_block_index = opts.chainparams.DefaultConsistencyChecks();
6156 if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work =
UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6157 if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6158 return std::move(opts);
6163 m_interrupt{interrupt},
6165 m_blockman{interrupt,
std::move(blockman_options)},
6166 m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
6177Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6185 if (!base_blockhash) {
6188 LogInfo(
"[snapshot] detected active snapshot chainstate (%s) - loading",
6189 fs::PathToString(*path));
6191 auto snapshot_chainstate{std::make_unique<Chainstate>(
nullptr,
m_blockman, *
this, base_blockhash)};
6192 LogInfo(
"[snapshot] switching active chainstate to %s", snapshot_chainstate->ToString());
6193 return &this->AddChainstate(std::move(snapshot_chainstate));
6196Chainstate& ChainstateManager::AddChainstate(std::unique_ptr<Chainstate> chainstate)
6201 assert(!prev_chainstate.m_target_blockhash);
6202 prev_chainstate.m_target_blockhash = chainstate->m_from_snapshot_blockhash;
6203 m_chainstates.push_back(std::move(chainstate));
6205 assert(&curr_chainstate == m_chainstates.back().get());
6209 assert(!prev_chainstate.m_mempool || prev_chainstate.m_mempool->size() == 0);
6210 assert(!curr_chainstate.m_mempool);
6211 std::swap(curr_chainstate.m_mempool, prev_chainstate.m_mempool);
6212 return curr_chainstate;
6217 return (block_index.
nHeight==91842 && block_index.
GetBlockHash() ==
uint256{
"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6218 (block_index.
nHeight==91880 && block_index.
GetBlockHash() ==
uint256{
"00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"});
6223 return (block_height==91722 && block_hash ==
uint256{
"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
6224 (block_height==91812 && block_hash ==
uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6236 const fs::path invalid_path{db_path +
"_INVALID"};
6239 LogInfo(
"[snapshot] renaming snapshot datadir %s to %s", db_path_str, invalid_path_str);
6245 fs::rename(db_path, invalid_path);
6246 }
catch (
const fs::filesystem_error& e) {
6247 LogError(
"While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6248 db_path_str, invalid_path_str, e.what());
6250 "Rename of '%s' -> '%s' failed. "
6251 "You should resolve this by manually moving or deleting the invalid "
6252 "snapshot directory %s, otherwise you will encounter the same error again "
6253 "on the next startup."),
6254 db_path_str, invalid_path_str, db_path_str)};
6259bool ChainstateManager::DeleteChainstate(
Chainstate& chainstate)
6265 LogError(
"Deletion of %s failed. Please remove it manually to continue reindexing.",
6266 fs::PathToString(db_path));
6271 assert(prev_chainstate->m_mempool->size() == 0);
6272 assert(!curr_chainstate.m_mempool);
6273 std::swap(curr_chainstate.m_mempool, prev_chainstate->m_mempool);
6282void ChainstateManager::RecalculateBestHeader()
6286 for (
auto& entry :
m_blockman.m_block_index) {
6287 if (!(entry.second.nStatus &
BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
6288 m_best_header = &entry.second;
6293std::optional<int> ChainstateManager::BlocksAheadOfTip()
const
6299 if (best_header && tip && best_header->nChainWork > tip->
nChainWork &&
6300 best_header->GetAncestor(tip->
nHeight) == tip) {
6303 return std::nullopt;
6306bool ChainstateManager::ValidatedSnapshotCleanup(
Chainstate& validated_cs,
Chainstate& unvalidated_cs)
6314 const fs::path validated_path{validated_cs.
StoragePath()};
6315 const fs::path assumed_valid_path{unvalidated_cs.
StoragePath()};
6316 const fs::path delete_path{validated_path +
"_todelete"};
6324 this->ResetChainstates();
6325 assert(this->m_chainstates.size() == 0);
6327 LogInfo(
"[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6328 fs::PathToString(validated_path));
6330 auto rename_failed_abort = [
this](
6333 const fs::filesystem_error& err) {
6334 LogError(
"[snapshot] Error renaming path (%s) -> (%s): %s\n",
6335 fs::PathToString(p_old), fs::PathToString(p_new), err.what());
6337 "Rename of '%s' -> '%s' failed. "
6338 "Cannot clean up the background chainstate leveldb directory."),
6339 fs::PathToString(p_old), fs::PathToString(p_new)));
6343 fs::rename(validated_path, delete_path);
6344 }
catch (
const fs::filesystem_error& e) {
6345 rename_failed_abort(validated_path, delete_path, e);
6349 LogInfo(
"[snapshot] moving snapshot chainstate (%s) to "
6350 "default chainstate directory (%s)",
6351 fs::PathToString(assumed_valid_path), fs::PathToString(validated_path));
6354 fs::rename(assumed_valid_path, validated_path);
6355 }
catch (
const fs::filesystem_error& e) {
6356 rename_failed_abort(assumed_valid_path, validated_path, e);
6363 LogWarning(
"Deletion of %s failed. Please remove it manually, as the "
6364 "directory is now unnecessary.",
6365 fs::PathToString(delete_path));
6367 LogInfo(
"[snapshot] deleted background chainstate directory (%s)",
6368 fs::PathToString(validated_path));
6373std::pair<int, int> Chainstate::GetPruneRange(
int last_height_can_prune)
const
6384 prune_start =
Assert(SnapshotBase())->nHeight + 1;
6387 int max_prune = std::max<int>(
6396 int prune_end = std::min(last_height_can_prune, max_prune);
6398 return {prune_start, prune_end};
6401std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange()
const
6404 if (!chainstate)
return {};
6405 return std::make_pair(chainstate->
m_chain.
Tip(), chainstate->TargetBlock());
6414 std::vector<Chainstate*> chainstates;
6417 chainstates.reserve(m_chainstates.size());
6418 for (
const auto& chainstate : m_chainstates) {
6419 if (chainstate && chainstate->m_assumeutxo !=
Assumeutxo::INVALID && !chainstate->m_target_utxohash) {
6420 chainstates.push_back(chainstate.get());
6426 if (!chainstate->ActivateBestChain(state,
nullptr)) {
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
arith_uint256 UintToArith256(const uint256 &a)
void InvalidateBlock(ChainstateManager &chainman, const uint256 block_hash)
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
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.
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ BLOCK_VALID_MASK
All validity bits.
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
@ BLOCK_FAILED_VALID
stage after last reached validness failed
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
static constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK
Init values for CBlockIndex nSequenceId when loaded from disk.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Compute how much work a block index entry corresponds to.
static constexpr int32_t SEQ_ID_INIT_FROM_DISK
#define NONFATAL_UNREACHABLE()
NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code.
#define Assert(val)
Identity function.
#define STR_INTERNAL_BUG(msg)
#define Assume(val)
Assume is the identity function.
Non-refcounted RAII wrapper for FILE*.
std::string ToString() const
Wrapper around an AutoFile& that implements a ring buffer to deserialize from.
bool m_checked_merkle_root
std::vector< CTransactionRef > vtx
bool m_checked_witness_commitment
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
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.
uint256 GetBlockHash() const
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
unsigned int nTx
Number of transactions in this block.
int32_t nVersion
block header
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
const CBlockIndex * FindFork(const CBlockIndex &index) const
Find the last common block between this chain and a block index entry.
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
CBlockIndex * Next(const CBlockIndex &index) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
std::vector< int > GetAvailableSnapshotHeights() const
const ChainTxData & TxData() const
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
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 (...
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
virtual void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
void SetBestBlock(const uint256 &block_hash)
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs)
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
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.
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::shared_future< void > CompactFullAsync() EXCLUSIVE_LOCKS_REQUIRED(cs_main
Perform a full compaction of the underlying LevelDB on a one-shot background thread.
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dynamically alter the underlying leveldb cache size.
Pure abstract view on the open txout dataset.
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const =0
Retrieve the Coin (unspent transaction output) for a given outpoint.
CCoinsView that brings transactions from a mempool into view.
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
void Finalize(std::span< unsigned char > output)
CHash256 & Write(std::span< const unsigned char > input)
An outpoint - a combination of a transaction hash and an index n into its vout.
A hasher class for SHA-256.
void Finalize(unsigned char hash[OUTPUT_SIZE])
CSHA256 & Write(const unsigned char *data, size_t len)
Closure representing one script verification Note that this stores references to the spending transac...
SignatureCache * m_signature_cache
PrecomputedTransactionData * txdata
script_verify_flags m_flags
std::optional< std::pair< ScriptError, std::string > > operator()()
const CTransaction * ptxTo
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
const Txid & GetHash() const LIFETIMEBOUND
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPool::txiter TxHandle
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
void UpdateTransactionsFromBlock(const std::vector< Txid > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
void AddTransactionsUpdated(unsigned int n)
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
size_t DynamicMemoryUsage() const
void removeForReorg(CChain &chain, std::function< bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs
After reorg, filter the entries that would no longer be valid in the next block, and update the entri...
bool exists(const Txid &txid) const
std::set< txiter, CompareIteratorByHash > setEntries
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
unsigned long size() const
An output of a transaction.
Undo information for a CTransaction.
std::vector< Coin > vprevout
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
CVerifyDB(kernel::Notifications ¬ifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
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...
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
CChain m_chain
The current chain of blockheaders we consult and build on.
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.
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.
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.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, std::shared_ptr< const CBlock > block_to_connect, std::vector< ConnectedBlock > &connected_blocks, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
const CBlockIndex *SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(boo ReachedTarget)() const EXCLUSIVE_LOCKS_REQUIRED(
The base of the snapshot this chainstate was created from.
kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe)
Return the current role of the chainstate.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex &index_most_work, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, std::vector< ConnectedBlock > &connected_blocks) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the [start, end] (inclusive) of block heights we can prune.
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.
CBlockIndex * FindMostWorkChain() 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...
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more,...
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.
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.
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Add a block to the candidate set if it has as much work as the current tip.
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.
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices.
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
fs::path StoragePath() const
Return path to chainstate leveldb directory.
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
util::Result< void > PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
const uint256 & AssumedValidBlock() const
ValidationCache m_validation_cache
double GetBackgroundVerificationProgress(const CBlockIndex &pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess background verification progress in case assume-utxo was used (as a fraction between 0....
double GuessVerificationProgress(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
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.
std::unique_ptr< Chainstate > RemoveChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Remove a chainstate.
kernel::Notifications & GetNotifications() const
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
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
void CheckBlockIndex() const
Make various assertions about the state of the block index.
const util::SignalInterrupt & m_interrupt
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< uint256, FlatFilePos > *blocks_with_unknown_parent=nullptr)
Import blocks from an external file.
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
VersionBitsCache m_versionbitscache
Track versionbit status.
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
void GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
bool ProcessNewBlockHeaders(std::span< const CBlockHeader > headers, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) 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 UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update and possibly latch the IBD status.
bool LoadGenesisBlock()
Ensures a genesis block is in the block tree, possibly writing one to disk.
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndex * ActivateSnapshot)(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Instantiate a new chainstate.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
void ReportHeadersPresync(int64_t height, int64_t timestamp)
This is used by net_processing to report pre-synchronization progress of headers, as headers are not ...
std::atomic_bool m_cached_is_ibd
Whether initial block download (IBD) is ongoing.
bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex())
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev) const
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
Chainstate *LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &AddChainstate(std::unique_ptr< Chainstate > chainstate) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(std::optional< std::pair< const CBlockIndex *, const CBlockIndex * > > GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(util::Result< void > ActivateBestChains() LOCKS_EXCLUDED(void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > BlocksAheadOfTip() const LOCKS_EXCLUDED(CCheckQueue< CScriptCheck > & GetCheckQueue()
When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process...
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...
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, 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).
CTxOut out
unspent transaction output
bool IsSpent() const
Either this coin never existed (see e.g.
bool fCoinBase
whether containing transaction was a coinbase
uint32_t nHeight
at which height this containing transaction was included in the active block chain
static CoinsViewEmpty & Get()
CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during Con...
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
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...
void insert(Element e)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
bool contains(const Element &e, const bool erase) const
contains iterates through the hash locations for a given element and checks to see if it is present.
DisconnectedBlockTransactions.
std::list< CTransactionRef > take()
Clear all data structures and return the list of transactions.
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Remove any entries that are in this block.
std::vector< CTransactionRef > AddTransactionsFromBlock(const std::vector< CTransactionRef > &vtx)
Add transactions from the block, iterating through vtx in reverse order.
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range) noexcept
Return the time point advanced by a uniform random duration.
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Convenience class for initializing and passing the script execution cache and signature cache.
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
CuckooCache::cache< uint256, SignatureCacheHasher > m_script_execution_cache
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 BlockConnected(const kernel::ChainstateRole &, std::shared_ptr< const CBlock >, const CBlockIndex *pindex)
void BlockChecked(const std::shared_ptr< const CBlock > &, const BlockValidationState &)
void ChainStateFlushed(const kernel::ChainstateRole &, const CBlockLocator &)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void ActiveTipChange(const CBlockIndex &, bool)
void BlockDisconnected(std::shared_ptr< const CBlock >, const CBlockIndex *pindex)
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
std::vector< std::pair< int, bool > > CheckUnknownActivations(const CBlockIndex *pindex, const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check for unknown activations Returns a vector containing the bit number used for signalling and a bo...
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
256-bit unsigned big integer.
constexpr bool IsNull() const
std::string ToString() const
constexpr unsigned char * begin()
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 bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warningSet(Warning id, const bilingual_str &message)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual InterruptResult blockTip(SynchronizationState state, const CBlockIndex &index, double verification_progress)
virtual void warningUnset(Warning id)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
const kernel::BlockManagerOpts m_opts
void FindFilesToPrune(std::set< int > &setFilesToPrune, int last_prune, const Chainstate &chain, ChainstateManager &chainman)
Prune block and undo files (blk???.dat and rev???.dat) so that the disk space used is less than a use...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockFileInfo *GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight) EXCLUSIVE_LOCKS_REQUIRED(void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(bool IsPruneMode() const
Get block file info entry for one block file.
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
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.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
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< uint256 > &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.
void AddUnlinkedBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain)
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
uint64_t CalculateCurrentUsage() EXCLUSIVE_LOCKS_REQUIRED(bool CheckBlockDataAvailability(const CBlockIndex &upper_block, const CBlockIndex &lower_block, BlockStatus block_status=BLOCK_HAVE_DATA) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex &GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block LIFETIMEBOUND=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Calculate the amount of disk space the block & undo files currently use.
std::string ToString() const
constexpr const std::byte * begin() const
const uint256 & ToUint256() const LIFETIMEBOUND
std::string GetHex() const
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
std::string FormatFullVersion()
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.
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
auto flush
Flush changes in top cache to the one below.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
uint256 BlockWitnessMerkleRoot(const CBlock &block)
static constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction.
static constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
static int64_t GetBlockWeight(const CBlock &block)
@ 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)
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
static constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
static const int WITNESS_SCALE_FACTOR
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool DestroyDB(const std::string &path_str)
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for this block.
static const unsigned int MAX_DISCONNECTED_TX_POOL_BYTES
Maximum bytes for transactions to store for processing during reorg.
bool CheckEphemeralSpends(const Package &package, CFeeRate dust_relay_rate, const CTxMemPool &tx_pool, TxValidationState &out_child_state, Wtxid &out_child_wtxid)
Called for each transaction(package) if any dust is in the package.
bool PreCheckEphemeralTx(const CTransaction &tx, CFeeRate dust_relay_rate, CAmount base_fee, CAmount mod_fee, TxValidationState &state)
These utility functions ensure that ephemeral dust is safely created and spent without unduly risking...
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ SCRIPT_VERIFY_NULLDUMMY
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
is a home for simple enum and struct type definitions that can be used internally by functions in the...
#define LogDebug(category,...)
@ REORG
Removed for reorganization.
std::array< uint8_t, 4 > MessageStartChars
BlockValidationState m_state
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
std::function< FILE *(const fs::path &, const char *)> FopenFn
static std::optional< CCoinsStats > ComputeUTXOStats(T hash_obj, const CCoinsViewDB &view, node::BlockManager &blockman, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
bool IsInterrupted(const T &result)
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
The file in the snapshot chainstate dir which stores the base blockhash.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate)
std::optional< fs::path > FindAssumeutxoChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate) EXCLUSIVE_LOCKS_REQUIRED(std::optional< uint256 > ReadSnapshotBaseBlockhash(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::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir)
constexpr NoRateLimitTag NO_RATE_LIMIT
bilingual_str ErrorString(const Result< T > &result)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
static feebumper::Result CheckFeeRate(const CWallet &wallet, const CMutableTransaction &mtx, const CFeeRate &newFeerate, const int64_t maxTxSize, CAmount old_fee, std::vector< bilingual_str > &errors)
Check if the user provided a valid feeRate.
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 IsWellFormedPackage(const Package &txns, PackageValidationState &state)
Context-free package policy checks:
uint256 GetPackageHash(const std::vector< CTransactionRef > &transactions)
Get the hash of the concatenated wtxids of transactions, with wtxids treated as a little-endian numbe...
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.
std::optional< std::pair< DiagramCheckError, std::string > > ImprovesFeerateDiagram(CTxMemPool::ChangeSet &changeset)
The replacement transaction must improve the feerate diagram of the mempool.
std::optional< std::string > PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const Txid &txid)
The replacement transaction must pay more fees than the original transactions.
std::optional< std::string > EntriesAndTxidsDisjoint(const CTxMemPool::setEntries &ancestors, const std::set< Txid > &direct_conflicts, const Txid &txid)
Check the intersection between two sets of transactions (a set of mempool entries and a set of txids)...
std::optional< std::string > GetEntriesForConflicts(const CTransaction &tx, CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting, CTxMemPool::setEntries &all_conflicts)
Get all descendants of iters_conflicting.
@ FAILURE
New diagram wasn't strictly superior
TxValidationState ValidateInputsStandardness(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
bool SpendsNonAnchorWitnessProg(const CTransaction &tx, const CCoinsViewCache &prevouts)
Check whether this transaction spends any witness program but P2A, including not-yet-defined ones.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
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 script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
static constexpr unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
static constexpr unsigned int MAX_STANDARD_TX_SIGOPS_COST
The maximum number of sigops we're willing to relay/mine in a single tx.
static constexpr unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE
The minimum non-witness size for transactions we're willing to relay/mine: one larger than 64
static constexpr script_verify_flags STANDARD_NOT_MANDATORY_VERIFY_FLAGS
For convenience, standard but not mandatory verify flags.
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
static constexpr TransactionSerParams TX_NO_WITNESS
static constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
uint256 GetRandHash() noexcept
Generate a random uint256.
std::string ScriptErrorString(const ScriptError serror)
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
uint64_t GetSerializeSize(const T &t)
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
unsigned char * UCharCast(char *c)
Holds configuration for use during UTXO snapshot load and validation.
AssumeutxoHash hash_serialized
The expected hash of the deserialized UTXO set.
uint64_t m_chain_tx_count
Used to populate the m_chain_tx_count value, which is used during BlockManager::LoadBlockIndex().
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< uint256 > vHave
A mutable version of CTransaction.
std::vector< CTxOut > vout
Holds various statistics on transactions within a chain.
User-controlled performance and debug options.
std::shared_ptr< const CBlock > pblock
const CBlockIndex * pindex
Parameters that influence chain consensus.
bool enforce_BIP94
Enforce BIP94 timewarp attack mitigation.
int64_t DifficultyAdjustmentInterval() const
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
int nSubsidyHalvingInterval
std::map< uint256, script_verify_flags > script_flag_exceptions
Hashes of blocks that.
int64_t nPowTargetSpacing
std::chrono::seconds PowTargetSpacing() const
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
Data structure storing a fee and size.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
const ResultType m_result_type
Result type.
const TxValidationState m_state
Contains information about why the transaction failed.
@ INVALID
‍Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
static MempoolAcceptResult MempoolTxDifferentWitness(const Wtxid &other_wtxid)
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
static time_point now() noexcept
Return current system time or mocked time, if set.
static time_point now() noexcept
Return current system time or mocked time, if set.
Validation result for package mempool acceptance.
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
std::vector< CTxOut > m_spent_outputs
const char * what() const noexcept override
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...
ValidationSignals * signals
std::optional< int32_t > check_block_index
std::chrono::seconds max_tip_age
If the tip is older than this, the node is considered to be in initial block download.
int32_t prevoutfetch_threads_num
Number of worker threads used for prefetching block input prevouts. Zero means no parallel fetching.
const CChainParams & chainparams
CoinsViewOptions coins_view
Information about chainstate that notifications are sent from.
bool validated
Whether this is a notification from a chainstate that's been fully validated starting from the genesi...
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
#define TRACEPOINT(context,...)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
std::optional< std::pair< std::string, CTransactionRef > > SingleTRUCChecks(const CTxMemPool &pool, const CTransactionRef &ptx, const std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &mempool_parents, const std::set< Txid > &direct_conflicts, int64_t vsize)
Must be called for every transaction, even if not TRUC.
std::optional< std::string > PackageTRUCChecks(const CTxMemPool &pool, const CTransactionRef &ptx, int64_t vsize, const Package &package, const std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &mempool_parents)
Must be called for every transaction that is submitted within a package, even if not TRUC.
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
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 IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp)
Test whether the LockPoints height and time are still valid on the current chain.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
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.
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate)
Validate (and maybe submit) a package to the mempool.
static void LimitMempoolSize(CTxMemPool &pool, CCoinsViewCache &coins_cache) EXCLUSIVE_LOCKS_REQUIRED(
bool IsBlockMutated(const CBlock &block, bool check_witness_root)
Check if a block has been mutated (with respect to its merkle root and witness commitments).
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, script_verify_flags flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData &txdata, ValidationCache &validation_cache, std::vector< CScriptCheck > *pvChecks=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept)
Try to add a transaction to the mempool.
bool HasValidProofOfWork(std::span< const CBlockHeader > headers, const Consensus::Params &consensusParams)
Check that the proof of work on each blockheader matches the value in nBits.
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
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 FatalError(Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
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 bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
static void UpdateTipLog(const ChainstateManager &chainman, const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const std::string &func_name, const std::string &prefix, const std::string &warning_messages, const bool background_validation) EXCLUSIVE_LOCKS_REQUIRED(
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, script_verify_flags flags, PrecomputedTransactionData &txdata, CCoinsViewCache &coins_tip, ValidationCache &validation_cache) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
static constexpr auto DATABASE_WRITE_INTERVAL_MAX
static bool CheckWitnessMalleation(const CBlock &block, bool expect_witness_commitment, BlockValidationState &state)
CheckWitnessMalleation performs checks for block malleation with regard to its witnesses.
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED(
static bool CheckMerkleRoot(const CBlock &block, BlockValidationState &state)
static constexpr int PRUNE_LOCK_BUFFER
The number of blocks to keep below the deepest prune lock.
arith_uint256 CalculateClaimedHeadersWork(std::span< const CBlockHeader > headers)
Return the sum of the claimed work on a given set of headers.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE
Maximum age of our tip for us to be considered current for fee estimation.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache, bool snapshot_loaded)
static bool IsCurrentForFeeEstimation(Chainstate &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr auto DATABASE_WRITE_INTERVAL_MIN
Time window to wait between writing blocks/block index and chainstate to disk.
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt &interrupt)
static bool ShouldCompactChainstate(bool in_ibd)
static SynchronizationState GetSynchronizationState(bool init, bool blockfiles_indexed)
bool IsBIP30Unspendable(const uint256 &block_hash, int block_height)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
TRACEPOINT_SEMAPHORE(validation, block_connected)
static void LimitValidationInterfaceQueue(ValidationSignals &signals) LOCKS_EXCLUDED(cs_main)
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
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...
Assumeutxo
Chainstate assumeutxo validity.
@ VALIDATED
Every block in the chain has been validated.
@ UNVALIDATED
Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validate...
@ INVALID
The assumeutxo snapshot failed validation.
SynchronizationState
Current sync state passed to tip changed callbacks.
constexpr std::array FlushStateModeNames
constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.