6#include <bitcoin-build-config.h>
101 "level 0 reads the blocks from disk",
102 "level 1 verifies block validity",
103 "level 2 verifies undo data",
104 "level 3 checks disconnection of tip blocks",
105 "level 4 tries to reconnect the blocks",
106 "each level includes the checks of the previous levels",
118 static constexpr uint32_t flush_ratio{320};
136 if (
m_chain.Contains(pindex)) {
151 std::vector<CScriptCheck>* pvChecks =
nullptr)
164 const int nBlockHeight = active_chain_tip.nHeight + 1;
171 const int64_t nBlockTime{active_chain_tip.GetMedianTimePast()};
173 return IsFinalTx(tx, nBlockHeight, nBlockTime);
187std::optional<std::vector<int>> CalculatePrevHeights(
192 std::vector<int> prev_heights;
193 prev_heights.resize(tx.
vin.size());
194 for (
size_t i = 0; i < tx.
vin.size(); ++i) {
195 if (
auto coin{coins.
GetCoin(tx.
vin[i].prevout)}) {
200 LogInfo(
"ERROR: %s: Missing input %d in transaction \'%s\'\n", __func__, i, tx.
GetHash().
GetHex());
215 auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
216 if (!prev_heights.has_value())
return std::nullopt;
219 next_tip.
pprev = tip;
237 int max_input_height{0};
238 for (
const int height : prev_heights.value()) {
240 if (height != next_tip.
nHeight) {
241 max_input_height = std::max(max_input_height, height);
281 std::vector<COutPoint> vNoSpendsRemaining;
282 pool.TrimToSize(pool.m_opts.max_size_bytes, &vNoSpendsRemaining);
283 for (
const COutPoint& removed : vNoSpendsRemaining)
284 coins_cache.Uncache(removed);
290 if (active_chainstate.m_chainman.IsInitialBlockDownload()) {
295 if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
309 std::vector<Txid> vHashUpdate;
316 const auto queuedTx = disconnectpool.
take();
317 auto it = queuedTx.rbegin();
318 while (it != queuedTx.rend()) {
320 if (!fAddToMempool || (*it)->IsCoinBase() ||
322 true,
false).m_result_type !=
327 }
else if (
m_mempool->exists((*it)->GetHash())) {
328 vHashUpdate.push_back((*it)->GetHash());
339 m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
369 it->UpdateLockPoints(*new_lock_points);
376 if (it->GetSpendsCoinbase()) {
381 const auto mempool_spend_height{
m_chain.Tip()->nHeight + 1};
418 if (coin.
IsSpent())
return false;
445 explicit MemPoolAccept(CTxMemPool& mempool, Chainstate& active_chainstate) :
448 m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
449 m_active_chainstate(active_chainstate)
456 const CChainParams& m_chainparams;
457 const int64_t m_accept_time;
458 const bool m_bypass_limits;
466 std::vector<COutPoint>& m_coins_to_uncache;
468 const bool m_test_accept;
472 const bool m_allow_replacement;
474 const bool m_allow_sibling_eviction;
477 const bool m_package_submission;
481 const bool m_package_feerates;
486 const std::optional<CFeeRate> m_client_maxfeerate;
489 static ATMPArgs SingleAccept(
const CChainParams& chainparams, int64_t accept_time,
490 bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
492 return ATMPArgs{ chainparams,
506 static ATMPArgs PackageTestAccept(
const CChainParams& chainparams, int64_t accept_time,
507 std::vector<COutPoint>& coins_to_uncache) {
508 return ATMPArgs{ chainparams,
522 static ATMPArgs PackageChildWithParents(
const CChainParams& chainparams, int64_t accept_time,
523 std::vector<COutPoint>& coins_to_uncache,
const std::optional<CFeeRate>& client_maxfeerate) {
524 return ATMPArgs{ chainparams,
538 static ATMPArgs SingleInPackageAccept(
const ATMPArgs& package_args) {
539 return ATMPArgs{ package_args.m_chainparams,
540 package_args.m_accept_time,
542 package_args.m_coins_to_uncache,
543 package_args.m_test_accept,
548 package_args.m_client_maxfeerate,
555 ATMPArgs(
const CChainParams& chainparams,
558 std::vector<COutPoint>& coins_to_uncache,
560 bool allow_replacement,
561 bool allow_sibling_eviction,
562 bool package_submission,
563 bool package_feerates,
564 std::optional<CFeeRate> client_maxfeerate)
565 : m_chainparams{chainparams},
566 m_accept_time{accept_time},
567 m_bypass_limits{bypass_limits},
568 m_coins_to_uncache{coins_to_uncache},
569 m_test_accept{test_accept},
570 m_allow_replacement{allow_replacement},
571 m_allow_sibling_eviction{allow_sibling_eviction},
572 m_package_submission{package_submission},
573 m_package_feerates{package_feerates},
574 m_client_maxfeerate{client_maxfeerate}
578 if (m_package_feerates) {
579 Assume(m_package_submission);
580 Assume(!m_allow_sibling_eviction);
582 if (m_allow_sibling_eviction)
Assume(m_allow_replacement);
592 MempoolAcceptResult result = AcceptSingleTransactionInternal(ptx,
args);
593 ClearSubPackageState();
605 PackageMempoolAcceptResult result = AcceptMultipleTransactionsInternal(txns,
args);
606 ClearSubPackageState();
621 PackageMempoolAcceptResult AcceptSubPackage(
const std::vector<CTransactionRef>& subpackage, ATMPArgs&
args)
634 explicit Workspace(
const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
637 std::set<Txid> m_conflicts;
642 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
647 bool m_sibling_eviction{
false};
660 CFeeRate m_package_feerate{0};
665 TxValidationState m_state;
668 PrecomputedTransactionData m_precomputed_txdata;
680 bool PackageRBFChecks(
const std::vector<CTransactionRef>& txns,
681 std::vector<Workspace>& workspaces,
701 bool SubmitPackage(
const ATMPArgs&
args, std::vector<Workspace>& workspaces, PackageValidationState& package_state,
702 std::map<Wtxid, MempoolAcceptResult>& results)
710 CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
711 if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
715 if (package_fee < m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
717 strprintf(
"%d < %d", package_fee, m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
722 ValidationCache& GetValidationCache()
724 return m_active_chainstate.m_chainman.m_validation_cache;
741 CCoinsViewCache m_view;
746 CCoinsViewMemPool m_viewmempool;
752 Chainstate& m_active_chainstate;
756 struct SubPackageState {
758 CAmount m_total_modified_fees{0};
760 int64_t m_total_vsize{0};
767 std::list<CTransactionRef> m_replaced_transactions;
769 std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
774 size_t m_conflicting_size{0};
777 struct SubPackageState m_subpackage;
782 m_subpackage = SubPackageState{};
785 CleanupTemporaryCoins();
789bool MemPoolAccept::PreChecks(ATMPArgs&
args, Workspace& ws)
794 const CTransaction& tx = *ws.m_ptx;
795 const Txid& hash = ws.m_hash;
798 const int64_t nAcceptTime =
args.m_accept_time;
799 const bool bypass_limits =
args.m_bypass_limits;
800 std::vector<COutPoint>& coins_to_uncache =
args.m_coins_to_uncache;
803 TxValidationState& state = ws.m_state;
840 for (
const CTxIn &txin : tx.
vin)
843 if (ptxConflicting) {
844 if (!
args.m_allow_replacement) {
848 ws.m_conflicts.insert(ptxConflicting->
GetHash());
854 const CCoinsViewCache& coins_cache = m_active_chainstate.
CoinsTip();
856 for (
const CTxIn& txin : tx.
vin) {
858 coins_to_uncache.push_back(txin.
prevout);
866 for (
size_t out = 0;
out < tx.
vout.size();
out++) {
916 bool fSpendsCoinbase =
false;
917 for (
const CTxIn &txin : tx.
vin) {
920 fSpendsCoinbase =
true;
927 const uint64_t entry_sequence = bypass_limits ? 0 : m_pool.
GetSequence();
928 if (!m_subpackage.m_changeset) {
931 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());
934 ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
936 ws.m_vsize = ws.m_tx_handle->GetTxSize();
952 if (!bypass_limits && !
args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state))
return false;
954 ws.m_iters_conflicting = m_pool.
GetIterSet(ws.m_conflicts);
956 ws.m_parents = m_pool.
GetParents(*ws.m_tx_handle);
958 if (!
args.m_bypass_limits) {
960 if (
const auto err{
SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
962 if (
args.m_allow_sibling_eviction && err->second !=
nullptr) {
967 ws.m_conflicts.insert(err->second->GetHash());
971 ws.m_iters_conflicting.insert(m_pool.
GetIter(err->second->GetHash()).value());
972 ws.m_sibling_eviction =
true;
984 m_subpackage.m_rbf |= !ws.m_conflicts.empty();
988bool MemPoolAccept::ReplacementChecks(Workspace& ws)
993 const CTransaction& tx = *ws.m_ptx;
994 const Txid& hash = ws.m_hash;
995 TxValidationState& state = ws.m_state;
997 CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize);
1004 strprintf(
"too many potential replacements%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *err_string);
1010 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1011 m_subpackage.m_conflicting_size += it->GetTxSize();
1014 if (
const auto err_string{
PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
1018 strprintf(
"insufficient fee%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *err_string);
1022 for (
auto it : all_conflicts) {
1023 m_subpackage.m_changeset->StageRemoval(it);
1027 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1041bool MemPoolAccept::PackageRBFChecks(
const std::vector<CTransactionRef>& txns,
1042 std::vector<Workspace>& workspaces,
1043 const int64_t total_vsize,
1044 PackageValidationState& package_state)
1049 assert(std::all_of(txns.cbegin(), txns.cend(), [
this](
const auto& tx)
1050 { return !m_pool.exists(tx->GetHash());}));
1052 assert(txns.size() == workspaces.size());
1067 for (
const auto& ws : workspaces) {
1068 if (!ws.m_parents.empty()) {
1075 for (Workspace& ws : workspaces) {
1077 direct_conflict_iters.merge(ws.m_iters_conflicting);
1080 const auto& parent_ws = workspaces[0];
1081 const auto& child_ws = workspaces[1];
1089 "package RBF failed: too many potential replacements", *err_string);
1093 m_subpackage.m_changeset->StageRemoval(it);
1094 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1095 m_subpackage.m_conflicting_size += it->GetTxSize();
1099 const Txid& child_hash = child_ws.m_ptx->GetHash();
1100 if (
const auto err_string{
PaysForRBF(m_subpackage.m_conflicting_fees,
1101 m_subpackage.m_total_modified_fees,
1102 m_subpackage.m_total_vsize,
1105 "package RBF failed: insufficient anti-DoS fees", *err_string);
1110 const CFeeRate parent_feerate(parent_ws.m_modified_fees, parent_ws.m_vsize);
1111 const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1112 if (package_feerate <= parent_feerate) {
1114 "package RBF failed: package feerate is less than or equal to parent feerate",
1115 strprintf(
"package feerate %s <= parent feerate is %s", package_feerate.ToString(), parent_feerate.ToString()));
1119 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1127 "package RBF failed: " + err_tup.value().second,
"");
1130 LogDebug(
BCLog::TXPACKAGES,
"package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
1131 txns.front()->GetHash().ToString(), txns.front()->GetWitnessHash().ToString(),
1132 txns.back()->GetHash().ToString(), txns.back()->GetWitnessHash().ToString(),
1139bool MemPoolAccept::PolicyScriptChecks(
const ATMPArgs&
args, Workspace& ws)
1143 const CTransaction& tx = *ws.m_ptx;
1144 TxValidationState& state = ws.m_state;
1150 if (!
CheckInputScripts(tx, state, m_view, scriptVerifyFlags,
true,
false, ws.m_precomputed_txdata, GetValidationCache())) {
1162bool MemPoolAccept::ConsensusScriptChecks(
const ATMPArgs&
args, Workspace& ws)
1166 const CTransaction& tx = *ws.m_ptx;
1167 const Txid& hash = ws.m_hash;
1168 TxValidationState& state = ws.m_state;
1187 ws.m_precomputed_txdata, m_active_chainstate.
CoinsTip(), GetValidationCache())) {
1188 LogError(
"BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s", hash.
ToString(), state.
ToString());
1195void MemPoolAccept::FinalizeSubpackage(
const ATMPArgs&
args)
1200 if (!m_subpackage.m_changeset->GetRemovals().empty())
Assume(
args.m_allow_replacement);
1204 std::string log_string =
strprintf(
"replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1205 it->GetTx().GetHash().ToString(),
1206 it->GetTx().GetWitnessHash().ToString(),
1209 FeeFrac feerate{m_subpackage.m_total_modified_fees, int32_t(m_subpackage.m_total_vsize)};
1210 uint256 tx_or_package_hash{};
1211 const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
1212 if (replaced_with_tx) {
1213 const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1215 log_string +=
strprintf(
"New tx %s (wtxid=%s, fees=%s, vsize=%s)",
1221 tx_or_package_hash =
GetPackageHash(m_subpackage.m_changeset->GetAddedTxns());
1222 log_string +=
strprintf(
"New package %s with %lu txs, fees=%s, vsize=%s",
1224 m_subpackage.m_changeset->GetTxCount(),
1231 it->GetTx().GetHash().data(),
1234 std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1235 tx_or_package_hash.
data(),
1240 m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1242 m_subpackage.m_changeset->Apply();
1243 m_subpackage.m_changeset.reset();
1246bool MemPoolAccept::SubmitPackage(
const ATMPArgs&
args, std::vector<Workspace>& workspaces,
1247 PackageValidationState& package_state,
1248 std::map<Wtxid, MempoolAcceptResult>& results)
1254 assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [
this](
const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1256 bool all_submitted =
true;
1257 FinalizeSubpackage(
args);
1262 for (Workspace& ws : workspaces) {
1263 if (!ConsensusScriptChecks(
args, ws)) {
1267 all_submitted =
false;
1269 strprintf(
"BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1270 ws.m_ptx->GetHash().ToString()));
1272 if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.
GetChangeSet();
1273 m_subpackage.m_changeset->StageRemoval(m_pool.
GetIter(ws.m_ptx->GetHash()).value());
1276 if (!all_submitted) {
1277 Assume(m_subpackage.m_changeset);
1281 m_subpackage.m_changeset->Apply();
1282 m_subpackage.m_changeset.reset();
1286 std::vector<Wtxid> all_package_wtxids;
1287 all_package_wtxids.reserve(workspaces.size());
1288 std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1289 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1291 if (!m_subpackage.m_replaced_transactions.empty()) {
1292 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
1293 m_subpackage.m_replaced_transactions.size(), workspaces.size(),
1294 m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1295 m_subpackage.m_total_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1299 for (Workspace& ws : workspaces) {
1300 auto iter = m_pool.
GetIter(ws.m_ptx->GetHash());
1301 Assume(iter.has_value());
1302 const auto effective_feerate =
args.m_package_feerates ? ws.m_package_feerate :
1303 CFeeRate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1304 const auto effective_feerate_wtxids =
args.m_package_feerates ? all_package_wtxids :
1305 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1306 results.emplace(ws.m_ptx->GetWitnessHash(),
1308 ws.m_base_fees, effective_feerate, effective_feerate_wtxids));
1310 const CTransaction& tx = *ws.m_ptx;
1311 const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1312 ws.m_vsize, (*iter)->GetHeight(),
1313 args.m_bypass_limits,
args.m_package_submission,
1318 return all_submitted;
1321MempoolAcceptResult MemPoolAccept::AcceptSingleTransactionInternal(
const CTransactionRef& ptx, ATMPArgs&
args)
1327 const std::vector<Wtxid> single_wtxid{ws.m_ptx->GetWitnessHash()};
1329 if (!PreChecks(
args, ws)) {
1337 if (m_subpackage.m_rbf && !ReplacementChecks(ws)) {
1346 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1353 if (ws.m_conflicts.size()) {
1354 auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1368 m_subpackage.m_total_vsize = ws.m_vsize;
1369 m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1372 if (
args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1390 const CFeeRate effective_feerate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1392 if (
args.m_test_accept) {
1394 ws.m_base_fees, effective_feerate, single_wtxid);
1397 FinalizeSubpackage(
args);
1400 if (!
args.m_package_submission && !
args.m_bypass_limits) {
1404 CleanupTemporaryCoins();
1406 if (!m_pool.
exists(ws.m_hash)) {
1414 const CTransaction& tx = *ws.m_ptx;
1416 Assume(iter.has_value());
1417 const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1418 ws.m_vsize, (*iter)->GetHeight(),
1419 args.m_bypass_limits,
args.m_package_submission,
1425 if (!m_subpackage.m_replaced_transactions.empty()) {
1426 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
1427 m_subpackage.m_replaced_transactions.size(),
1428 ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1429 ws.m_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1433 effective_feerate, single_wtxid);
1436PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactionsInternal(
const std::vector<CTransactionRef>& txns, ATMPArgs&
args)
1442 PackageValidationState package_state;
1443 if (!
IsWellFormedPackage(txns, package_state))
return PackageMempoolAcceptResult(package_state, {});
1445 std::vector<Workspace> workspaces{};
1446 workspaces.reserve(txns.size());
1447 std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1448 [](
const auto& tx) { return Workspace(tx); });
1449 std::map<Wtxid, MempoolAcceptResult> results;
1452 for (Workspace& ws : workspaces) {
1453 if (!PreChecks(
args, ws)) {
1457 return PackageMempoolAcceptResult(package_state, std::move(results));
1462 if (
args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1468 return PackageMempoolAcceptResult(package_state, std::move(results));
1485 for (Workspace& ws : workspaces) {
1486 if (
auto err{
PackageTRUCChecks(m_pool, ws.m_ptx, ws.m_vsize, txns, ws.m_parents)}) {
1488 return PackageMempoolAcceptResult(package_state, {});
1501 m_subpackage.m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1502 [](int64_t
sum,
auto& ws) { return sum + ws.m_vsize; });
1503 m_subpackage.m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(),
CAmount{0},
1504 [](
CAmount sum,
auto& ws) { return sum + ws.m_modified_fees; });
1505 const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1506 std::vector<Wtxid> all_package_wtxids;
1507 all_package_wtxids.reserve(workspaces.size());
1508 std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1509 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1510 TxValidationState placeholder_state;
1511 if (
args.m_package_feerates &&
1512 !CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees, placeholder_state)) {
1514 return PackageMempoolAcceptResult(package_state, {{workspaces.back().m_ptx->GetWitnessHash(),
1519 if (m_subpackage.m_rbf && !PackageRBFChecks(txns, workspaces, m_subpackage.m_total_vsize, package_state)) {
1520 return PackageMempoolAcceptResult(package_state, std::move(results));
1524 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1526 return PackageMempoolAcceptResult(package_state, std::move(results));
1531 TxValidationState child_state;
1536 return PackageMempoolAcceptResult(package_state, std::move(results));
1540 for (Workspace& ws : workspaces) {
1541 ws.m_package_feerate = package_feerate;
1542 if (!PolicyScriptChecks(
args, ws)) {
1546 return PackageMempoolAcceptResult(package_state, std::move(results));
1548 if (
args.m_test_accept) {
1549 const auto effective_feerate =
args.m_package_feerates ? ws.m_package_feerate :
1550 CFeeRate{ws.m_modified_fees,
static_cast<int32_t
>(ws.m_vsize)};
1551 const auto effective_feerate_wtxids =
args.m_package_feerates ? all_package_wtxids :
1552 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1553 results.emplace(ws.m_ptx->GetWitnessHash(),
1555 ws.m_vsize, ws.m_base_fees, effective_feerate,
1556 effective_feerate_wtxids));
1560 if (
args.m_test_accept)
return PackageMempoolAcceptResult(package_state, std::move(results));
1562 if (!SubmitPackage(
args, workspaces, package_state, results)) {
1564 return PackageMempoolAcceptResult(package_state, std::move(results));
1567 return PackageMempoolAcceptResult(package_state, std::move(results));
1570void MemPoolAccept::CleanupTemporaryCoins()
1597 m_viewmempool.
Reset();
1600PackageMempoolAcceptResult MemPoolAccept::AcceptSubPackage(
const std::vector<CTransactionRef>& subpackage, ATMPArgs&
args)
1605 if (subpackage.size() > 1) {
1606 return AcceptMultipleTransactionsInternal(subpackage,
args);
1608 const auto& tx = subpackage.front();
1609 ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(
args);
1610 const auto single_res = AcceptSingleTransactionInternal(tx, single_args);
1611 PackageValidationState package_state_wrapped;
1615 return PackageMempoolAcceptResult(package_state_wrapped, {{tx->
GetWitnessHash(), single_res}});
1621 ClearSubPackageState();
1626PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(
const Package& package, ATMPArgs&
args)
1628 Assert(!package.empty());
1631 PackageValidationState package_state_quit_early;
1641 return PackageMempoolAcceptResult(package_state_quit_early, {});
1648 return PackageMempoolAcceptResult(package_state_quit_early, {});
1654 std::map<Wtxid, MempoolAcceptResult> results_final;
1658 std::map<Wtxid, MempoolAcceptResult> individual_results_nonfinal;
1660 bool quit_early{
false};
1661 std::vector<CTransactionRef> txns_package_eval;
1662 for (
const auto& tx : package) {
1664 const auto& txid = tx->
GetHash();
1668 if (m_pool.
exists(wtxid)) {
1680 }
else if (m_pool.
exists(txid)) {
1694 const auto single_package_res = AcceptSubPackage({tx},
args);
1695 const auto& single_res = single_package_res.m_tx_results.at(wtxid);
1700 results_final.emplace(wtxid, single_res);
1701 }
else if (package.size() == 1 ||
1715 individual_results_nonfinal.emplace(wtxid, single_res);
1717 individual_results_nonfinal.emplace(wtxid, single_res);
1718 txns_package_eval.push_back(tx);
1723 auto multi_submission_result = quit_early || txns_package_eval.empty() ? PackageMempoolAcceptResult(package_state_quit_early, {}) :
1724 AcceptSubPackage(txns_package_eval,
args);
1725 PackageValidationState& package_state_final = multi_submission_result.m_state;
1730 ClearSubPackageState();
1737 for (
const auto& tx : package) {
1739 if (multi_submission_result.m_tx_results.contains(wtxid)) {
1741 Assume(!results_final.contains(wtxid));
1744 const auto& txresult = multi_submission_result.m_tx_results.at(wtxid);
1747 TxValidationState mempool_full_state;
1751 results_final.emplace(wtxid, txresult);
1753 }
else if (
const auto it{results_final.find(wtxid)}; it != results_final.end()) {
1757 Assume(!individual_results_nonfinal.contains(wtxid));
1761 TxValidationState mempool_full_state;
1764 results_final.erase(wtxid);
1767 }
else if (
const auto it{individual_results_nonfinal.find(wtxid)}; it != individual_results_nonfinal.end()) {
1770 results_final.emplace(wtxid, it->second);
1773 Assume(results_final.size() == package.size());
1774 return PackageMempoolAcceptResult(package_state_final, std::move(results_final));
1780 int64_t accept_time,
bool bypass_limits,
bool test_accept)
1787 std::vector<COutPoint> coins_to_uncache;
1789 auto args = MemPoolAccept::ATMPArgs::SingleAccept(chainparams, accept_time, bypass_limits, coins_to_uncache, test_accept);
1790 MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransactionAndCleanup(tx,
args);
1798 for (
const COutPoint& hashTx : coins_to_uncache)
1801 tx->GetHash().data(),
1812 const Package& package,
bool test_accept,
const std::optional<CFeeRate>& client_maxfeerate)
1815 assert(!package.empty());
1816 assert(std::all_of(package.cbegin(), package.cend(), [](
const auto& tx){return tx != nullptr;}));
1818 std::vector<COutPoint> coins_to_uncache;
1823 auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(chainparams,
GetTime(), coins_to_uncache);
1824 return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactionsAndCleanup(package,
args);
1826 auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(chainparams,
GetTime(), coins_to_uncache, client_maxfeerate);
1827 return MemPoolAccept(pool, active_chainstate).AcceptPackage(package,
args);
1832 if (test_accept || result.m_state.IsInvalid()) {
1833 for (
const COutPoint& hashTx : coins_to_uncache) {
1852 nSubsidy >>= halvings;
1857 : m_dbview{
std::move(db_params),
std::move(options)},
1858 m_catcherview(&m_dbview) {}
1860void CoinsViews::InitCache()
1863 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1864 m_connect_block_view = std::make_unique<CoinsViewOverlay>(&*m_cacheview);
1871 std::optional<uint256> from_snapshot_blockhash)
1880 fs::path path{
m_chainman.m_options.datadir /
"chainstate"};
1887const CBlockIndex* Chainstate::SnapshotBase()
const
1891 return m_cached_snapshot_base;
1896 if (!m_target_blockhash)
return nullptr;
1897 if (!m_cached_target_block) m_cached_target_block =
Assert(
m_chainman.m_blockman.LookupBlockIndex(*m_target_blockhash));
1898 return m_cached_target_block;
1901void Chainstate::SetTargetBlock(
CBlockIndex* block)
1906 m_target_blockhash.reset();
1908 m_cached_target_block = block;
1911void Chainstate::SetTargetBlockHash(
uint256 block_hash)
1913 m_target_blockhash = block_hash;
1914 m_cached_target_block =
nullptr;
1918 size_t cache_size_bytes,
1925 .cache_bytes = cache_size_bytes,
1926 .memory_only = in_memory,
1927 .wipe_data = should_wipe,
1935void Chainstate::InitCoinsCache(
size_t cache_size_bytes)
1953 if (this->GetRole().historical) {
1958 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.");
1961 _(
"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."));
1974 SetBlockFailureFlags(pindexNew);
1979 LogInfo(
"%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
1984 LogInfo(
"%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
1997 m_blockman.m_dirty_blockindex.insert(pindex);
2022 if (
VerifyScript(scriptSig,
m_tx_out.scriptPubKey, witness,
m_flags,
CachingTransactionSignatureChecker(
ptxTo,
nIn,
m_tx_out.nValue,
cacheStore, *
m_signature_cache, *
txdata), &error)) {
2023 return std::nullopt;
2025 auto debug_str =
strprintf(
"input %i of %s (wtxid %s), spending %s:%i",
nIn,
ptxTo->GetHash().ToString(),
ptxTo->GetWitnessHash().ToString(),
ptxTo->vin[
nIn].prevout.hash.ToString(),
ptxTo->vin[
nIn].prevout.n);
2026 return std::make_pair(error, std::move(debug_str));
2042 LogInfo(
"Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2043 approx_size_bytes >> 20, script_execution_cache_bytes >> 20, num_elems);
2069 std::vector<CScriptCheck>* pvChecks)
2074 pvChecks->reserve(tx.
vin.size());
2091 std::vector<CTxOut> spent_outputs;
2092 spent_outputs.reserve(tx.
vin.size());
2094 for (
const auto& txin : tx.
vin) {
2098 spent_outputs.emplace_back(coin.
out);
2100 txdata.
Init(tx, std::move(spent_outputs));
2104 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
2115 pvChecks->emplace_back(std::move(check));
2116 }
else if (
auto result = check(); result.has_value()) {
2131 if (cacheFullScriptStore && !pvChecks) {
2157 if (view.
HaveCoin(out)) fClean =
false;
2159 if (undo.nHeight == 0) {
2165 undo.nHeight = alternate.
nHeight;
2176 view.
AddCoin(out, std::move(undo), !fClean);
2188 CBlockUndo blockUndo;
2189 if (!
m_blockman.ReadBlockUndo(blockUndo, *pindex)) {
2190 LogError(
"DisconnectBlock(): failure reading undo data\n");
2194 if (blockUndo.
vtxundo.size() + 1 != block.
vtx.size()) {
2195 LogError(
"DisconnectBlock(): block and undo data inconsistent\n");
2205 bool fEnforceBIP30 = !((pindex->
nHeight==91722 && pindex->
GetBlockHash() == uint256{
"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
2206 (pindex->
nHeight==91812 && pindex->
GetBlockHash() == uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2209 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
2210 const CTransaction &tx = *(block.
vtx[i]);
2213 bool is_bip30_exception = (is_coinbase && !fEnforceBIP30);
2217 for (
size_t o = 0; o < tx.
vout.size(); o++) {
2218 if (!tx.
vout[o].scriptPubKey.IsUnspendable()) {
2219 COutPoint
out(hash, o);
2221 bool is_spent = view.
SpendCoin(out, &coin);
2223 if (!is_bip30_exception) {
2232 CTxUndo &txundo = blockUndo.
vtxundo[i-1];
2234 LogError(
"DisconnectBlock(): transaction and undo data inconsistent\n");
2237 for (
unsigned int j = tx.
vin.size(); j > 0;) {
2239 const COutPoint&
out = tx.
vin[j].prevout;
2305 uint256 block_hash{block.
GetHash()};
2308 const auto time_start{SteadyClock::now()};
2309 const CChainParams& params{
m_chainman.GetParams()};
2329 return FatalError(
m_chainman.GetNotifications(), state,
_(
"Corrupt block found indicating potential hardware failure."));
2336 uint256 hashPrevBlock = pindex->
pprev ==
nullptr ? uint256() : pindex->pprev->GetBlockHash();
2349 const char* script_check_reason;
2350 if (
m_chainman.AssumedValidBlock().IsNull()) {
2351 script_check_reason =
"assumevalid=0 (always verify)";
2353 constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};
2361 script_check_reason =
"assumevalid hash not in headers";
2362 }
else if (it->second.GetAncestor(pindex->
nHeight) != pindex) {
2363 script_check_reason = (pindex->
nHeight > it->second.nHeight) ?
"block height above assumevalid height" :
"block not in assumevalid chain";
2365 script_check_reason =
"block not in best header chain";
2367 script_check_reason =
"best header chainwork below minimumchainwork";
2369 script_check_reason =
"block too recent relative to best header";
2385 script_check_reason =
nullptr;
2389 const auto time_1{SteadyClock::now()};
2390 m_chainman.time_check += time_1 - time_start;
2434 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2471 if (fEnforceBIP30 || pindex->
nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2472 for (
const auto& tx : block.
vtx) {
2473 for (
size_t o = 0; o < tx->
vout.size(); o++) {
2476 "tried to overwrite transaction");
2483 int nLockTimeFlags = 0;
2491 const auto time_2{SteadyClock::now()};
2498 const bool fScriptChecks{!!script_check_reason};
2499 const kernel::ChainstateRole role{GetRole()};
2500 if (script_check_reason != m_last_script_check_reason_logged && role.
validated && !role.
historical) {
2501 if (fScriptChecks) {
2502 LogInfo(
"Enabling script verification at block #%d (%s): %s.",
2505 LogInfo(
"Disabling script verification at block #%d (%s).",
2508 m_last_script_check_reason_logged = script_check_reason;
2511 CBlockUndo blockundo;
2518 std::vector<PrecomputedTransactionData> txsdata(block.
vtx.size());
2519 std::optional<CCheckQueueControl<CScriptCheck>> control;
2520 if (
auto& queue =
m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue);
2522 std::vector<int> prevheights;
2525 int64_t nSigOpsCost = 0;
2526 blockundo.
vtxundo.reserve(block.
vtx.size() - 1);
2527 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2530 const CTransaction &tx = *(block.
vtx[i]);
2532 nInputs += tx.
vin.size();
2537 TxValidationState tx_state;
2548 "accumulated fee in the block out of range");
2555 prevheights.resize(tx.
vin.size());
2556 for (
size_t j = 0; j < tx.
vin.size(); j++) {
2560 if (!
SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2579 bool fCacheResults = fJustCheck;
2581 TxValidationState tx_state;
2585 std::vector<CScriptCheck> vChecks;
2587 if (tx_ok) control->Add(std::move(vChecks));
2601 blockundo.
vtxundo.emplace_back();
2605 const auto time_3{SteadyClock::now()};
2607 LogDebug(
BCLog::BENCH,
" - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (
unsigned)block.
vtx.size(),
2614 if (block.
vtx[0]->GetValueOut() > blockReward && state.
IsValid()) {
2616 strprintf(
"coinbase pays too much (actual=%d vs limit=%d)", block.
vtx[0]->GetValueOut(), blockReward));
2619 auto parallel_result = control->Complete();
2620 if (parallel_result.has_value() && state.
IsValid()) {
2628 const auto time_4{SteadyClock::now()};
2630 LogDebug(
BCLog::BENCH,
" - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
2640 if (!
m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2644 const auto time_5{SteadyClock::now()};
2653 m_blockman.m_dirty_blockindex.insert(pindex);
2659 const auto time_6{SteadyClock::now()};
2681 return this->GetCoinsCacheSizeState(
2687 size_t max_coins_cache_size_bytes,
2688 size_t max_mempool_size_bytes)
2693 int64_t nTotalSpace =
2694 max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2696 if (cacheSize > nTotalSpace) {
2697 LogInfo(
"Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2708 int nManualPruneHeight)
2712 std::set<int> setFilesToPrune;
2713 bool full_flush_completed =
false;
2720 bool fFlushForPrune =
false;
2727 int last_prune{
m_chain.Height()};
2728 std::optional<std::string> limiting_lock;
2730 for (
const auto& prune_lock :
m_blockman.m_prune_locks) {
2731 if (prune_lock.second.height_first == std::numeric_limits<int>::max())
continue;
2734 last_prune = std::max(1, std::min(last_prune, lock_height));
2735 if (last_prune == lock_height) {
2736 limiting_lock = prune_lock.first;
2740 if (limiting_lock) {
2741 LogDebug(
BCLog::PRUNE,
"%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
2744 if (nManualPruneHeight > 0) {
2749 std::min(last_prune, nManualPruneHeight),
2757 if (!setFilesToPrune.empty()) {
2758 fFlushForPrune =
true;
2760 m_blockman.m_block_tree_db->WriteFlag(
"prunedblockfiles",
true);
2777 LogDebug(
BCLog::COINDB,
"Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
2778 FlushStateModeNames[
size_t(mode)], fFlushForPrune, fCacheLarge, fCacheCritical, fPeriodicWrite);
2791 LogWarning(
"%s: Failed to flush block file.\n", __func__);
2802 if (fFlushForPrune) {
2805 m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2808 if (!
CoinsTip().GetBestBlock().IsNull()) {
2819 full_flush_completed =
true;
2823 (uint64_t)coins_count,
2824 (uint64_t)coins_mem_usage,
2825 (bool)fFlushForPrune);
2829 if (should_write ||
m_next_write == NodeClock::time_point::max()) {
2834 if (full_flush_completed) {
2843 }
catch (
const std::exception& e) {
2844 LogWarning(
"Failed to start chainstate compaction (%s)", e.what());
2848 }
catch (
const std::runtime_error& e) {
2875 const std::string& func_name,
2876 const std::string&
prefix,
2888 chainman.GuessVerificationProgress(tip),
2891 !warning_messages.empty() ?
strprintf(
" warning='%s'", warning_messages) :
"");
2894void Chainstate::UpdateTip(
const CBlockIndex* pindexNew)
2897 const auto& coins_tip = this->
CoinsTip();
2901 if (
this != &
m_chainman.ActiveChainstate()) {
2903 constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2904 if (pindexNew->
nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2915 std::vector<bilingual_str> warning_messages;
2917 auto bits =
m_chainman.m_versionbitscache.CheckUnknownActivations(pindexNew,
m_chainman.GetParams());
2918 for (
auto [bit, active] : bits) {
2919 const bilingual_str warning =
strprintf(
_(
"Unknown new rules activated (versionbit %i)"), bit);
2923 warning_messages.push_back(warning);
2950 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2952 if (!
m_blockman.ReadBlock(block, *pindexDelete)) {
2953 LogError(
"DisconnectTip(): Failed to read block\n");
2957 const auto time_start{SteadyClock::now()};
2961 if (DisconnectBlock(block, pindexDelete, view) !=
DISCONNECT_OK) {
2972 const int max_height_first{pindexDelete->
nHeight - 1};
2973 for (
auto& prune_lock :
m_blockman.m_prune_locks) {
2974 if (prune_lock.second.height_first <= max_height_first)
continue;
2976 prune_lock.second.height_first = max_height_first;
2977 LogDebug(
BCLog::PRUNE,
"%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
2997 UpdateTip(pindexDelete->
pprev);
3001 m_chainman.m_options.signals->BlockDisconnected(pblock, pindexDelete);
3055 std::shared_ptr<const CBlock> block_to_connect,
3064 const auto time_1{SteadyClock::now()};
3065 if (!block_to_connect) {
3066 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3067 if (!
m_blockman.ReadBlock(*pblockNew, *pindexNew)) {
3070 block_to_connect = std::move(pblockNew);
3075 const auto time_2{SteadyClock::now()};
3076 SteadyClock::time_point time_3;
3084 bool rv =
ConnectBlock(*block_to_connect, state, pindexNew, view);
3086 m_chainman.m_options.signals->BlockChecked(block_to_connect, state);
3094 time_3 = SteadyClock::now();
3095 m_chainman.time_connect_total += time_3 - time_2;
3103 const auto time_4{SteadyClock::now()};
3113 const auto time_5{SteadyClock::now()};
3114 m_chainman.time_chainstate += time_5 - time_4;
3127 UpdateTip(pindexNew);
3129 const auto time_6{SteadyClock::now()};
3130 m_chainman.time_post_connect += time_6 - time_5;
3151 m_chainman.MaybeValidateSnapshot(*
this, current_cs);
3153 connectTrace.
BlockConnected(pindexNew, std::move(block_to_connect));
3178 bool fInvalidAncestor =
false;
3179 while (pindexTest && !
m_chain.Contains(pindexTest)) {
3188 if (fFailedChain || fMissingData) {
3195 while (pindexTest != pindexFailed) {
3198 m_blockman.m_dirty_blockindex.insert(pindexFailed);
3199 }
else if (fMissingData) {
3204 std::make_pair(pindexFailed->
pprev, pindexFailed));
3207 pindexFailed = pindexFailed->
pprev;
3210 fInvalidAncestor =
true;
3213 pindexTest = pindexTest->
pprev;
3215 if (!fInvalidAncestor)
3247 bool fBlocksDisconnected =
false;
3261 fBlocksDisconnected =
true;
3265 std::vector<CBlockIndex*> vpindexToConnect;
3266 bool fContinue =
true;
3271 int nTargetHeight = std::min(
nHeight + 32, pindexMostWork->
nHeight);
3272 vpindexToConnect.clear();
3273 vpindexToConnect.reserve(nTargetHeight -
nHeight);
3276 vpindexToConnect.push_back(pindexIter);
3277 pindexIter = pindexIter->
pprev;
3282 for (
CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
3283 if (!
ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
3290 fInvalidFound =
true;
3311 if (fBlocksDisconnected) {
3336 LogInfo(
"Leaving InitialBlockDownload (latching to false)");
3342 bool fNotify =
false;
3343 bool fInitialBlockDownload =
false;
3347 pindexHeader = m_best_header;
3349 if (pindexHeader != m_last_notified_header) {
3352 m_last_notified_header = pindexHeader;
3365 if (signals.CallbacksPending() > 10) {
3366 signals.SyncWithValidationInterfaceQueue();
3370bool Chainstate::ActivateBestChain(
BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3393 CBlockIndex *pindexMostWork =
nullptr;
3394 CBlockIndex *pindexNewTip =
nullptr;
3395 bool exited_ibd{
false};
3410 const bool was_in_ibd =
m_chainman.IsInitialBlockDownload();
3411 CBlockIndex* starting_tip =
m_chain.Tip();
3412 bool blocks_connected =
false;
3416 ConnectTrace connectTrace;
3418 if (pindexMostWork ==
nullptr) {
3423 if (pindexMostWork ==
nullptr || pindexMostWork ==
m_chain.Tip()) {
3427 bool fInvalidFound =
false;
3428 std::shared_ptr<const CBlock> nullBlockPtr;
3432 const ChainstateRole chainstate_role{this->GetRole()};
3433 if (!
ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->
GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
3437 blocks_connected =
true;
3439 if (fInvalidFound) {
3441 pindexMostWork =
nullptr;
3446 assert(trace.pblock && trace.pindex);
3448 m_chainman.m_options.signals->BlockConnected(chainstate_role, trace.pblock, trace.pindex);
3456 }
while (!
m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(
m_chain.Tip(), starting_tip)));
3457 if (!blocks_connected)
return true;
3459 const CBlockIndex* pindexFork =
m_chain.FindFork(starting_tip);
3460 bool still_in_ibd =
m_chainman.IsInitialBlockDownload();
3462 if (was_in_ibd && !still_in_ibd) {
3469 if (
this == &
m_chainman.ActiveChainstate() && pindexFork != pindexNewTip) {
3472 m_chainman.m_options.signals->UpdatedBlockTip(pindexNewTip, pindexFork, still_in_ibd);
3478 m_chainman.GuessVerificationProgress(pindexNewTip))))
3495 bool reached_target;
3512 if (reached_target) {
3520 if (
m_chainman.snapshot_download_completed) {
3531 }
while (pindexNewTip != pindexMostWork);
3555 if (
m_chainman.nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3566 return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3576 if (pindex->
nHeight == 0)
return false;
3590 std::multimap<const arith_uint256, CBlockIndex*> highpow_outofchain_headers;
3594 for (
auto& entry :
m_blockman.m_block_index) {
3595 CBlockIndex* candidate = &entry.second;
3601 if (!
m_chain.Contains(candidate) &&
3602 !CBlockIndexWorkComparator()(candidate, pindex->
pprev) &&
3604 highpow_outofchain_headers.insert({candidate->
nChainWork, candidate});
3609 CBlockIndex* to_mark_failed = pindex;
3610 bool pindex_was_in_chain =
false;
3611 int disconnected = 0;
3624 if (!
m_chain.Contains(pindex))
break;
3625 pindex_was_in_chain =
true;
3626 CBlockIndex* disconnected_tip{
m_chain.Tip()};
3638 if (!
ret)
return false;
3639 CBlockIndex* new_tip{
m_chain.Tip()};
3648 m_blockman.m_dirty_blockindex.insert(disconnected_tip);
3655 auto candidate_it = highpow_outofchain_headers.lower_bound(new_tip->
nChainWork);
3657 const bool best_header_needs_update{
m_chainman.m_best_header->GetAncestor(disconnected_tip->
nHeight) == disconnected_tip};
3658 if (best_header_needs_update) {
3663 while (candidate_it != highpow_outofchain_headers.end()) {
3664 CBlockIndex* candidate{candidate_it->second};
3668 m_blockman.m_dirty_blockindex.insert(candidate);
3671 candidate_it = highpow_outofchain_headers.erase(candidate_it);
3674 if (!CBlockIndexWorkComparator()(candidate, new_tip) &&
3681 if (best_header_needs_update &&
3689 to_mark_failed = disconnected_tip;
3696 if (
m_chain.Contains(to_mark_failed)) {
3704 m_blockman.m_dirty_blockindex.insert(pindex);
3715 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3725 if (pindex_was_in_chain) {
3733 (void)
m_chainman.GetNotifications().blockTip(
3735 *to_mark_failed->
pprev,
3747void Chainstate::SetBlockFailureFlags(
CBlockIndex* invalid_block)
3751 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3752 if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->
nHeight) == invalid_block) {
3754 m_blockman.m_dirty_blockindex.insert(&block_index);
3765 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
3767 block_index.nStatus &= ~BLOCK_FAILED_VALID;
3768 m_blockman.m_dirty_blockindex.insert(&block_index);
3772 if (&block_index ==
m_chainman.m_best_invalid) {
3799 if (!target_block) {
3816 pindexNew->
nTx = block.
vtx.size();
3822 auto prev_tx_sum = [](
CBlockIndex& block) {
return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3825 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",
3829 pindexNew->nFile = pos.
nFile;
3830 pindexNew->nDataPos = pos.
nPos;
3831 pindexNew->nUndoPos = 0;
3837 m_blockman.m_dirty_blockindex.insert(pindexNew);
3841 std::deque<CBlockIndex*> queue;
3842 queue.push_back(pindexNew);
3845 while (!queue.empty()) {
3853 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",
3858 for (
const auto& c : m_chainstates) {
3859 c->TryAddBlockIndexCandidate(pindex);
3861 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range =
m_blockman.m_blocks_unlinked.equal_range(pindex);
3862 while (range.first != range.second) {
3863 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3864 queue.push_back(it->second);
3871 m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->
pprev, pindexNew));
3895 "hashMerkleRoot mismatch");
3904 "bad-txns-duplicate",
3905 "duplicate transaction");
3920 if (expect_witness_commitment) {
3925 assert(!block.
vtx.empty() && !block.
vtx[0]->vin.empty());
3926 const auto& witness_stack{block.
vtx[0]->vin[0].scriptWitness.stack};
3928 if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
3931 "bad-witness-nonce-size",
3932 strprintf(
"%s : invalid witness reserved value size", __func__));
3941 if (memcmp(hash_witness.
begin(), &block.
vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3944 "bad-witness-merkle-match",
3945 strprintf(
"%s : witness merkle commitment mismatch", __func__));
3954 for (
const auto& tx : block.
vtx) {
3958 "unexpected-witness",
3959 strprintf(
"%s : unexpected witness data found", __func__));
3999 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase())
4001 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
4002 if (block.
vtx[i]->IsCoinBase())
4007 for (
const auto& tx : block.
vtx) {
4019 unsigned int nSigOps = 0;
4020 for (
const auto& tx : block.
vtx)
4027 if (fCheckPOW && fCheckMerkleRoot)
4036 static const std::vector<unsigned char>
nonce(32, 0x00);
4039 tx.
vin[0].scriptWitness.stack.resize(1);
4040 tx.
vin[0].scriptWitness.stack[0] =
nonce;
4048 std::vector<unsigned char>
ret(32, 0x00);
4056 out.scriptPubKey[1] = 0x24;
4057 out.scriptPubKey[2] = 0xaa;
4058 out.scriptPubKey[3] = 0x21;
4059 out.scriptPubKey[4] = 0xa9;
4060 out.scriptPubKey[5] = 0xed;
4061 memcpy(&out.scriptPubKey[6], witnessroot.
begin(), 32);
4063 tx.
vout.push_back(out);
4071 return std::ranges::all_of(headers,
4072 [&](
const auto& header) {
return CheckProofOfWork(header.GetHash(), header.nBits, consensusParams); });
4083 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase()) {
4090 return std::any_of(block.
vtx.begin(), block.
vtx.end(),
4091 [](
auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4131 assert(pindexPrev !=
nullptr);
4132 const int nHeight = pindexPrev->nHeight + 1;
4140 if (block.
GetBlockTime() <= pindexPrev->GetMedianTimePast())
4179 const int nHeight = pindexPrev ==
nullptr ? 0 : pindexPrev->
nHeight + 1;
4182 bool enforce_locktime_median_time_past{
false};
4184 assert(pindexPrev !=
nullptr);
4185 enforce_locktime_median_time_past =
true;
4188 const int64_t nLockTimeCutoff{enforce_locktime_median_time_past ?
4193 for (
const auto& tx : block.
vtx) {
4203 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
4204 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0]->vin[0].scriptSig.begin())) {
4240 BlockMap::iterator miSelf{
m_blockman.m_block_index.find(hash)};
4242 if (miSelf !=
m_blockman.m_block_index.end()) {
4267 pindexPrev = &((*mi).second);
4277 if (!min_pow_checked) {
4312 blocks_left = std::max<int64_t>(0, blocks_left);
4313 const double progress{100.0 * last_accepted.
nHeight / (last_accepted.
nHeight + blocks_left)};
4314 LogInfo(
"Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.
nHeight, progress);
4332 if (now < m_last_presync_update + std::chrono::milliseconds{250})
return;
4333 m_last_presync_update = now;
4337 if (initial_download) {
4339 blocks_left = std::max<int64_t>(0, blocks_left);
4340 const double progress{100.0 * height / (height + blocks_left)};
4341 LogInfo(
"Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4348 const CBlock& block = *pblock;
4350 if (fNewBlock) *fNewBlock =
false;
4354 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4356 bool accepted_header{
AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4359 if (!accepted_header)
4383 if (fAlreadyHave)
return true;
4385 if (pindex->
nTx != 0)
return true;
4386 if (!fHasMoreOrSameWork)
return true;
4387 if (fTooFarAhead)
return true;
4410 m_options.signals->NewPoWValidBlock(pindex, pblock);
4414 if (fNewBlock) *fNewBlock =
true;
4423 state.
Error(
strprintf(
"%s: Failed to find position to write new block to disk", __func__));
4428 }
catch (
const std::runtime_error& e) {
4452 if (new_block) *new_block =
false;
4467 ret =
AcceptBlock(block, state, &pindex, force_processing,
nullptr, new_block, min_pow_checked);
4471 m_options.signals->BlockChecked(block, state);
4482 LogError(
"%s: ActivateBestChain failed (%s)\n", __func__, state.
ToString());
4488 if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
4489 LogError(
"%s: [background] ActivateBestChain failed (%s)\n", __func__, bg_state.
ToString());
4514 const bool check_pow,
4515 const bool check_merkle_root)
4526 state.
Invalid({},
"inconclusive-not-best-prevblk");
4567 index_dummy.
pprev = tip;
4573 if(!chainstate.
ConnectBlock(block, state, &index_dummy, view_dummy,
true)) {
4617 assert(
cs->setBlockIndexCandidates.empty());
4625 target = target->pprev;
4628 LogInfo(
"Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
4635 if (!this->GetRole().historical) {
4637 (void)
m_chainman.GetNotifications().blockTip(
4663 int nCheckLevel,
int nCheckDepth)
4672 if (nCheckDepth <= 0 || nCheckDepth > chainstate.
m_chain.
Height()) {
4675 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4676 LogInfo(
"Verifying last %i blocks at level %i", nCheckDepth, nCheckLevel);
4680 int nGoodTransactions = 0;
4683 bool skipped_no_block_data{
false};
4684 bool skipped_l3_checks{
false};
4685 LogInfo(
"Verification progress: 0%%");
4690 const int percentageDone = std::max(1, std::min(99, (
int)(((
double)(chainstate.
m_chain.
Height() - pindex->
nHeight)) / (
double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4691 if (reportDone < percentageDone / 10) {
4693 LogInfo(
"Verification progress: %d%%", percentageDone);
4694 reportDone = percentageDone / 10;
4703 LogInfo(
"Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->
nHeight);
4704 skipped_no_block_data =
true;
4714 if (nCheckLevel >= 1 && !
CheckBlock(block, state, consensus_params)) {
4715 LogError(
"Verification error: found bad block at %d, hash=%s (%s)",
4720 if (nCheckLevel >= 2 && pindex) {
4732 if (nCheckLevel >= 3) {
4741 nGoodTransactions = 0;
4742 pindexFailure = pindex;
4744 nGoodTransactions += block.
vtx.size();
4747 skipped_l3_checks =
true;
4752 if (pindexFailure) {
4753 LogError(
"Verification error: coin database inconsistencies found (last %i blocks, %i good transactions before that)", chainstate.
m_chain.
Height() - pindexFailure->
nHeight + 1, nGoodTransactions);
4756 if (skipped_l3_checks) {
4757 LogWarning(
"Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4764 if (nCheckLevel >= 4 && !skipped_l3_checks) {
4766 const int percentageDone = std::max(1, std::min(99, 100 - (
int)(((
double)(chainstate.
m_chain.
Height() - pindex->
nHeight)) / (
double)nCheckDepth * 50)));
4767 if (reportDone < percentageDone / 10) {
4769 LogInfo(
"Verification progress: %d%%", percentageDone);
4770 reportDone = percentageDone / 10;
4779 if (!chainstate.
ConnectBlock(block, state, pindex, coins)) {
4787 LogInfo(
"Verification: No coin database inconsistencies in last %i blocks (%i transactions)", block_count, nGoodTransactions);
4789 if (skipped_l3_checks) {
4792 if (skipped_no_block_data) {
4810 if (!tx->IsCoinBase()) {
4811 for (
const CTxIn &txin : tx->vin) {
4829 if (hashHeads.empty())
return true;
4830 if (hashHeads.size() != 2) {
4831 LogError(
"ReplayBlocks(): unknown inconsistent state\n");
4835 m_chainman.GetNotifications().progress(
_(
"Replaying blocks…"), 0,
false);
4842 if (!
m_blockman.m_block_index.contains(hashHeads[0])) {
4843 LogError(
"ReplayBlocks(): reorganization to unknown block requested\n");
4846 pindexNew = &(
m_blockman.m_block_index[hashHeads[0]]);
4848 if (!hashHeads[1].IsNull()) {
4849 if (!
m_blockman.m_block_index.contains(hashHeads[1])) {
4850 LogError(
"ReplayBlocks(): reorganization from unknown block requested\n");
4853 pindexOld = &(
m_blockman.m_block_index[hashHeads[1]]);
4855 assert(pindexFork !=
nullptr);
4859 const int nForkHeight{pindexFork ? pindexFork->
nHeight : 0};
4860 if (pindexOld != pindexFork) {
4862 while (pindexOld != pindexFork) {
4865 if (!
m_blockman.ReadBlock(block, *pindexOld)) {
4869 if (pindexOld->
nHeight % 10'000 == 0) {
4882 pindexOld = pindexOld->
pprev;
4888 if (nForkHeight < pindexNew->
nHeight) {
4896 m_chainman.GetNotifications().progress(
_(
"Replaying blocks…"), (
int)((
nHeight - nForkHeight) * 100.0 / (pindexNew->
nHeight - nForkHeight)),
false);
4920 block = block->
pprev;
4926void Chainstate::ClearBlockIndexCandidates()
4932void Chainstate::PopulateBlockIndexCandidates()
4936 for (CBlockIndex* pindex :
m_blockman.GetAllBlockIndices()) {
4940 if (pindex == SnapshotBase() || pindex == TargetBlock() ||
4954 if (!
ret)
return false;
4956 m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
4958 std::vector<CBlockIndex*> vSortedByHeight{
m_blockman.GetAllBlockIndices()};
4959 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
4965 m_best_invalid = pindex;
4968 m_best_header = pindex;
4991 LogError(
"%s: writing genesis block to disk failed\n", __func__);
4995 m_chainman.ReceivedBlockTransactions(block, pindex, blockPos);
4996 }
catch (
const std::runtime_error& e) {
4997 LogError(
"%s: failed to write genesis block: %s\n", __func__, e.what());
5007 std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent)
5010 assert(!dbp == !blocks_with_unknown_parent);
5012 const auto start{SteadyClock::now()};
5020 uint64_t nRewind = blkdat.
GetPos();
5021 while (!blkdat.
eof()) {
5027 unsigned int nSize = 0;
5032 nRewind = blkdat.
GetPos() + 1;
5041 }
catch (
const std::exception&) {
5048 const uint64_t nBlockPos{blkdat.
GetPos()};
5050 dbp->
nPos = nBlockPos;
5051 blkdat.
SetLimit(nBlockPos + nSize);
5057 nRewind = nBlockPos + nSize;
5060 std::shared_ptr<CBlock> pblock{};
5068 if (dbp && blocks_with_unknown_parent) {
5069 blocks_with_unknown_parent->emplace(header.
hashPrevBlock, *dbp);
5078 blkdat.
SetPos(nBlockPos);
5079 pblock = std::make_shared<CBlock>();
5081 nRewind = blkdat.
GetPos();
5084 if (
AcceptBlock(pblock, state,
nullptr,
true, dbp,
nullptr,
true)) {
5117 if (
auto result{ActivateBestChains()}; !result) {
5125 if (!blocks_with_unknown_parent)
continue;
5128 std::deque<uint256> queue;
5129 queue.push_back(hash);
5130 while (!queue.empty()) {
5133 auto range = blocks_with_unknown_parent->equal_range(head);
5134 while (range.first != range.second) {
5135 std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5136 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5137 if (
m_blockman.ReadBlock(*pblockrecursive, it->second, {})) {
5138 const auto& block_hash{pblockrecursive->GetHash()};
5142 if (
AcceptBlock(pblockrecursive, dummy,
nullptr,
true, &it->second,
nullptr,
true)) {
5144 queue.push_back(block_hash);
5148 blocks_with_unknown_parent->erase(it);
5152 }
catch (
const std::exception& e) {
5164 LogDebug(
BCLog::REINDEX,
"%s: unexpected data at file offset 0x%x - %s. continuing\n", __func__, (nRewind - 1), e.what());
5167 }
catch (
const std::runtime_error& e) {
5205 best_hdr_chain.
SetTip(*m_best_header);
5207 std::multimap<const CBlockIndex*, const CBlockIndex*> forward;
5208 for (
auto& [
_, block_index] :
m_blockman.m_block_index) {
5210 if (!best_hdr_chain.
Contains(&block_index)) {
5212 assert(block_index.pprev);
5213 forward.emplace(block_index.pprev, &block_index);
5227 const CBlockIndex* pindexFirstNeverProcessed =
nullptr;
5228 const CBlockIndex* pindexFirstNotTreeValid =
nullptr;
5229 const CBlockIndex* pindexFirstNotTransactionsValid =
nullptr;
5230 const CBlockIndex* pindexFirstNotChainValid =
nullptr;
5231 const CBlockIndex* pindexFirstNotScriptsValid =
nullptr;
5238 const CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{}, *snap_first_nocv{}, *snap_first_nosv{};
5239 auto snap_update_firsts = [&] {
5240 if (pindex == snap_base) {
5241 std::swap(snap_first_missing, pindexFirstMissing);
5242 std::swap(snap_first_notx, pindexFirstNeverProcessed);
5243 std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
5244 std::swap(snap_first_nocv, pindexFirstNotChainValid);
5245 std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
5249 while (pindex !=
nullptr) {
5251 if (pindexFirstInvalid ==
nullptr && pindex->nStatus &
BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5252 if (pindexFirstMissing ==
nullptr && !(pindex->nStatus &
BLOCK_HAVE_DATA)) {
5253 pindexFirstMissing = pindex;
5255 if (pindexFirstNeverProcessed ==
nullptr && pindex->
nTx == 0) pindexFirstNeverProcessed = pindex;
5258 if (pindex->
pprev !=
nullptr) {
5259 if (pindexFirstNotTransactionsValid ==
nullptr &&
5261 pindexFirstNotTransactionsValid = pindex;
5264 if (pindexFirstNotChainValid ==
nullptr &&
5266 pindexFirstNotChainValid = pindex;
5269 if (pindexFirstNotScriptsValid ==
nullptr &&
5271 pindexFirstNotScriptsValid = pindex;
5276 if (pindex->
pprev ==
nullptr) {
5279 for (
const auto& c : m_chainstates) {
5280 if (c->m_chain.Genesis() !=
nullptr) {
5281 assert(pindex == c->m_chain.Genesis());
5293 assert(pindexFirstMissing == pindexFirstNeverProcessed);
5309 assert((pindexFirstNotTransactionsValid ==
nullptr || pindex == snap_base) == pindex->
HaveNumChainTxs());
5313 assert(pindexFirstNotTreeValid ==
nullptr);
5317 if (pindexFirstInvalid ==
nullptr) {
5324 if (!pindex->
pprev) {
5339 for (
const auto& c : m_chainstates) {
5340 if (c->m_chain.Tip() ==
nullptr)
continue;
5354 if (!
CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && (pindexFirstNeverProcessed ==
nullptr || pindex == snap_base)) {
5358 if (pindexFirstInvalid ==
nullptr) {
5377 if (pindexFirstMissing ==
nullptr || pindex == c->m_chain.Tip() || pindex == c->SnapshotBase()) {
5383 if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5384 assert(c->setBlockIndexCandidates.contains(pindex));
5392 assert(!c->setBlockIndexCandidates.contains(pindex));
5396 auto rangeUnlinked{
m_blockman.m_blocks_unlinked.equal_range(pindex->
pprev)};
5397 bool foundInUnlinked =
false;
5398 while (rangeUnlinked.first != rangeUnlinked.second) {
5399 assert(rangeUnlinked.first->first == pindex->
pprev);
5400 if (rangeUnlinked.first->second == pindex) {
5401 foundInUnlinked =
true;
5404 rangeUnlinked.first++;
5406 if (pindex->
pprev && (pindex->nStatus &
BLOCK_HAVE_DATA) && pindexFirstNeverProcessed !=
nullptr && pindexFirstInvalid ==
nullptr) {
5411 if (pindexFirstMissing ==
nullptr)
assert(!foundInUnlinked);
5412 if (pindex->
pprev && (pindex->nStatus &
BLOCK_HAVE_DATA) && pindexFirstNeverProcessed ==
nullptr && pindexFirstMissing !=
nullptr) {
5423 for (
const auto& c : m_chainstates) {
5425 if (pindexFirstInvalid ==
nullptr) {
5426 if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5438 snap_update_firsts();
5439 auto range{forward.equal_range(pindex)};
5440 if (range.first != range.second) {
5442 pindex = range.first->second;
5445 }
else if (best_hdr_chain.
Contains(pindex)) {
5448 pindex = best_hdr_chain[
nHeight];
5456 snap_update_firsts();
5458 if (pindex == pindexFirstInvalid) pindexFirstInvalid =
nullptr;
5459 if (pindex == pindexFirstMissing) pindexFirstMissing =
nullptr;
5460 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed =
nullptr;
5461 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid =
nullptr;
5462 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid =
nullptr;
5463 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid =
nullptr;
5464 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid =
nullptr;
5468 auto rangePar{forward.equal_range(pindexPar)};
5469 while (rangePar.first->second != pindex) {
5470 assert(rangePar.first != rangePar.second);
5475 if (rangePar.first != rangePar.second) {
5477 pindex = rangePar.first->second;
5479 }
else if (pindexPar == best_hdr_chain[
nHeight - 1]) {
5481 pindex = best_hdr_chain[
nHeight];
5483 assert((pindex ==
nullptr) == (pindexPar == best_hdr_chain.
Tip()));
5495 assert(nNodes == forward.size() + best_hdr_chain.
Height() + 1);
5498std::string Chainstate::ToString()
5502 return strprintf(
"Chainstate [%s] @ height %d (%s)",
5507bool Chainstate::ResizeCoinsCaches(
size_t coinstip_size,
size_t coinsdb_size)
5520 LogInfo(
"[%s] resized coinsdb cache to %.1f MiB",
5521 this->
ToString(), coinsdb_size * (1.0 / 1024 / 1024));
5522 LogInfo(
"[%s] resized coinstip cache to %.1f MiB",
5523 this->
ToString(), coinstip_size * (1.0 / 1024 / 1024));
5525 BlockValidationState state;
5528 if (coinstip_size > old_coinstip_size) {
5542 if (pindex ==
nullptr) {
5552 const auto block_time{
5567 fTxTotal = data.tx_count + (nNow - data.nTime) * data.dTxRate;
5578 assert(m_chainstates.empty());
5579 m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool,
m_blockman, *
this));
5580 return *m_chainstates.back();
5592 bool existed = fs::remove(base_blockhash_path);
5594 LogWarning(
"[snapshot] snapshot chainstate dir being removed lacks %s file",
5597 }
catch (
const fs::filesystem_error& e) {
5598 LogWarning(
"[snapshot] failed to remove file %s: %s\n",
5599 fs::PathToString(base_blockhash_path), e.code().message());
5603 std::string path_str = fs::PathToString(db_path);
5604 LogInfo(
"Removing leveldb dir at %s\n", path_str);
5608 const bool destroyed =
DestroyDB(path_str);
5611 LogError(
"leveldb DestroyDB call failed on %s", path_str);
5620 return destroyed && !fs::exists(db_path);
5630 CBlockIndex* snapshot_start_block{};
5636 return util::Error{
Untranslated(
"Can't activate a snapshot-based chainstate more than once")};
5638 if (!
GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
5640 std::string heights_formatted =
util::Join(available_heights,
", ", [&](
const auto& i) {
return util::ToString(i); });
5641 return util::Error{
Untranslated(
strprintf(
"assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5643 heights_formatted))};
5646 snapshot_start_block =
m_blockman.LookupBlockIndex(base_blockhash);
5647 if (!snapshot_start_block) {
5648 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",
5653 if (start_block_invalid) {
5657 if (!m_best_header || m_best_header->GetAncestor(snapshot_start_block->
nHeight) != snapshot_start_block) {
5658 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.")};
5662 if (mempool && mempool->
size() > 0) {
5663 return util::Error{
Untranslated(
"Can't activate a snapshot when mempool not empty")};
5667 int64_t current_coinsdb_cache_size{0};
5668 int64_t current_coinstip_cache_size{0};
5676 static constexpr double IBD_CACHE_PERC = 0.01;
5677 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
5695 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
5696 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
5700 return std::make_unique<Chainstate>(
5701 nullptr,
m_blockman, *
this, base_blockhash));
5705 snapshot_chainstate->InitCoinsDB(
5706 static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
5708 snapshot_chainstate->InitCoinsCache(
5709 static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
5713 this->MaybeRebalanceCaches();
5721 snapshot_chainstate.reset();
5725 "Manually remove it before restarting.\n"), fs::PathToString(*snapshot_datadir)));
5728 return util::Error{std::move(reason)};
5741 if (!CBlockIndexWorkComparator()(
ActiveTip(), snapshot_chainstate->m_chain.Tip())) {
5742 return cleanup_bad_snapshot(
Untranslated(
"work does not exceed active chainstate"));
5748 return cleanup_bad_snapshot(
Untranslated(
"could not write base blockhash"));
5752 Chainstate& chainstate{AddChainstate(std::move(snapshot_chainstate))};
5755 chainstate.PopulateBlockIndexCandidates();
5757 LogInfo(
"[snapshot] successfully activated snapshot %s", base_blockhash.
ToString());
5758 LogInfo(
"[snapshot] (%.2f MB)",
5761 this->MaybeRebalanceCaches();
5762 return snapshot_start_block;
5769 snapshot_loaded ?
"saving snapshot chainstate" :
"flushing coins cache",
5773 coins_cache.
Flush();
5778 const char*
what() const noexcept
override
5780 return "ComputeUTXOStats interrupted.";
5802 if (!snapshot_start_block) {
5809 int base_height = snapshot_start_block->
nHeight;
5812 if (!maybe_au_data) {
5814 "(%d) - refusing to load snapshot", base_height))};
5829 LogInfo(
"[snapshot] loading %d coins from snapshot %s", coins_left, base_blockhash.
ToString());
5830 int64_t coins_processed{0};
5832 while (coins_left > 0) {
5836 size_t coins_per_txid{0};
5839 if (coins_per_txid > coins_left) {
5843 for (
size_t i = 0; i < coins_per_txid; i++) {
5847 outpoint.
hash = txid;
5849 if (coin.
nHeight > base_height ||
5850 outpoint.
n >= std::numeric_limits<
decltype(outpoint.
n)>::max()
5853 coins_count - coins_left))};
5857 coins_count - coins_left))};
5864 if (coins_processed % 1000000 == 0) {
5865 LogInfo(
"[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5867 static_cast<float>(coins_processed) * 100 /
static_cast<float>(coins_count),
5875 if (coins_processed % 120000 == 0) {
5881 return snapshot_chainstate.GetCoinsCacheSizeState());
5894 }
catch (
const std::ios_base::failure&) {
5907 bool out_of_coins{
false};
5909 std::byte left_over_byte;
5910 coins_file >> left_over_byte;
5911 }
catch (
const std::ios_base::failure&) {
5913 out_of_coins =
true;
5915 if (!out_of_coins) {
5920 LogInfo(
"[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
5934 std::optional<CCoinsStats> maybe_stats;
5942 if (!maybe_stats.has_value()) {
5963 constexpr int AFTER_GENESIS_START{1};
5965 for (
int i = AFTER_GENESIS_START; i <= snapshot_chainstate.
m_chain.
Height(); ++i) {
5966 index = snapshot_chainstate.
m_chain[i];
5983 assert(index == snapshot_start_block);
5986 LogInfo(
"[snapshot] validated snapshot (%.2f MB)",
6013 !validated_cs.m_target_blockhash ||
6024 "%s failed to validate the -assumeutxo snapshot state. "
6025 "This indicates a hardware problem, or a bug in the software, or a "
6026 "bad software modification that allowed an invalid snapshot to be "
6027 "loaded. As a result of this, the node will shut down and stop using any "
6028 "state that was built on the snapshot, resetting the chain height "
6029 "from %d to %d. On the next "
6030 "restart, the node will resume syncing from %d "
6031 "without using any snapshot data. "
6032 "Please report this incident to %s, including how you obtained the snapshot. "
6033 "The invalid snapshot chainstate will be left on disk in case it is "
6034 "helpful in diagnosing the issue that caused this error."),
6040 LogError(
"[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6043 validated_cs.SetTargetBlock(
nullptr);
6047 auto rename_result = unvalidated_cs.InvalidateCoinsDBOnDisk();
6048 if (!rename_result) {
6055 CCoinsViewDB& validated_coins_db = validated_cs.
CoinsDB();
6059 if (!maybe_au_data) {
6060 LogWarning(
"[snapshot] assumeutxo data not found for height "
6061 "(%d) - refusing to validate snapshot", validated_cs.
m_chain.
Height());
6062 handle_invalid_snapshot();
6066 const AssumeutxoData& au_data = *maybe_au_data;
6067 std::optional<CCoinsStats> validated_cs_stats;
6068 LogInfo(
"[snapshot] computing UTXO stats for background chainstate to validate "
6069 "snapshot - this could take a few minutes");
6073 &validated_coins_db,
6076 }
catch (StopHashingException
const&) {
6081 if (!validated_cs_stats) {
6082 LogWarning(
"[snapshot] failed to generate stats for validation coins db");
6086 handle_invalid_snapshot();
6096 if (AssumeutxoHash{validated_cs_stats->hashSerialized} != au_data.
hash_serialized) {
6097 LogWarning(
"[snapshot] hash mismatch: actual=%s, expected=%s",
6098 validated_cs_stats->hashSerialized.ToString(),
6100 handle_invalid_snapshot();
6104 LogInfo(
"[snapshot] snapshot beginning at %s has been fully validated",
6108 validated_cs.m_target_utxohash = AssumeutxoHash{validated_cs_stats->hashSerialized};
6109 this->MaybeRebalanceCaches();
6120void ChainstateManager::MaybeRebalanceCaches()
6129 }
else if (!historical_cs) {
6131 LogInfo(
"[snapshot] allocating all cache to the snapshot chainstate");
6139 historical_cs->ResizeCoinsCaches(
6141 current_cs.ResizeCoinsCaches(
6144 current_cs.ResizeCoinsCaches(
6146 historical_cs->ResizeCoinsCaches(
6152void ChainstateManager::ResetChainstates()
6154 m_chainstates.clear();
6164 if (!opts.check_block_index.has_value()) opts.
check_block_index = opts.chainparams.DefaultConsistencyChecks();
6165 if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work =
UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6166 if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6167 return std::move(opts);
6186Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6194 if (!base_blockhash) {
6197 LogInfo(
"[snapshot] detected active snapshot chainstate (%s) - loading",
6198 fs::PathToString(*path));
6200 auto snapshot_chainstate{std::make_unique<Chainstate>(
nullptr,
m_blockman, *
this, base_blockhash)};
6201 LogInfo(
"[snapshot] switching active chainstate to %s", snapshot_chainstate->ToString());
6202 return &this->AddChainstate(std::move(snapshot_chainstate));
6205Chainstate& ChainstateManager::AddChainstate(std::unique_ptr<Chainstate> chainstate)
6210 assert(!prev_chainstate.m_target_blockhash);
6212 m_chainstates.push_back(std::move(chainstate));
6214 assert(&curr_chainstate == m_chainstates.back().get());
6221 return curr_chainstate;
6226 return (block_index.
nHeight==91842 && block_index.
GetBlockHash() ==
uint256{
"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6227 (block_index.
nHeight==91880 && block_index.
GetBlockHash() ==
uint256{
"00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"});
6232 return (block_height==91722 && block_hash ==
uint256{
"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
6233 (block_height==91812 && block_hash ==
uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6245 const fs::path invalid_path{db_path +
"_INVALID"};
6246 const std::string db_path_str{fs::PathToString(db_path)};
6247 const std::string invalid_path_str{fs::PathToString(invalid_path)};
6248 LogInfo(
"[snapshot] renaming snapshot datadir %s to %s", db_path_str, invalid_path_str);
6254 fs::rename(db_path, invalid_path);
6255 }
catch (
const fs::filesystem_error& e) {
6256 LogError(
"While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6257 db_path_str, invalid_path_str, e.what());
6259 "Rename of '%s' -> '%s' failed. "
6260 "You should resolve this by manually moving or deleting the invalid "
6261 "snapshot directory %s, otherwise you will encounter the same error again "
6262 "on the next startup."),
6263 db_path_str, invalid_path_str, db_path_str)};
6268bool ChainstateManager::DeleteChainstate(
Chainstate& chainstate)
6274 LogError(
"Deletion of %s failed. Please remove it manually to continue reindexing.",
6275 fs::PathToString(db_path));
6280 assert(prev_chainstate->m_mempool->size() == 0);
6282 std::swap(curr_chainstate.
m_mempool, prev_chainstate->m_mempool);
6288 return ChainstateRole{.validated = m_assumeutxo ==
Assumeutxo::VALIDATED, .historical =
bool{m_target_blockhash}};
6291void ChainstateManager::RecalculateBestHeader()
6295 for (
auto& entry :
m_blockman.m_block_index) {
6296 if (!(entry.second.nStatus &
BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
6297 m_best_header = &entry.second;
6302std::optional<int> ChainstateManager::BlocksAheadOfTip()
const
6305 const CBlockIndex* best_header{m_best_header};
6312 return std::nullopt;
6315bool ChainstateManager::ValidatedSnapshotCleanup(
Chainstate& validated_cs,
Chainstate& unvalidated_cs)
6323 const fs::path validated_path{validated_cs.
StoragePath()};
6324 const fs::path assumed_valid_path{unvalidated_cs.
StoragePath()};
6325 const fs::path delete_path{validated_path +
"_todelete"};
6333 this->ResetChainstates();
6334 assert(this->m_chainstates.size() == 0);
6336 LogInfo(
"[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6337 fs::PathToString(validated_path));
6339 auto rename_failed_abort = [
this](
6342 const fs::filesystem_error& err) {
6343 LogError(
"[snapshot] Error renaming path (%s) -> (%s): %s\n",
6344 fs::PathToString(p_old), fs::PathToString(p_new), err.what());
6346 "Rename of '%s' -> '%s' failed. "
6347 "Cannot clean up the background chainstate leveldb directory."),
6348 fs::PathToString(p_old), fs::PathToString(p_new)));
6352 fs::rename(validated_path, delete_path);
6353 }
catch (
const fs::filesystem_error& e) {
6354 rename_failed_abort(validated_path, delete_path, e);
6358 LogInfo(
"[snapshot] moving snapshot chainstate (%s) to "
6359 "default chainstate directory (%s)",
6360 fs::PathToString(assumed_valid_path), fs::PathToString(validated_path));
6363 fs::rename(assumed_valid_path, validated_path);
6364 }
catch (
const fs::filesystem_error& e) {
6365 rename_failed_abort(assumed_valid_path, validated_path, e);
6372 LogWarning(
"Deletion of %s failed. Please remove it manually, as the "
6373 "directory is now unnecessary.",
6374 fs::PathToString(delete_path));
6376 LogInfo(
"[snapshot] deleted background chainstate directory (%s)",
6377 fs::PathToString(validated_path));
6382std::pair<int, int> Chainstate::GetPruneRange(
int last_height_can_prune)
const
6393 prune_start =
Assert(SnapshotBase())->nHeight + 1;
6396 int max_prune = std::max<int>(
6405 int prune_end = std::min(last_height_can_prune, max_prune);
6407 return {prune_start, prune_end};
6410std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange()
const
6413 if (!chainstate)
return {};
6414 return std::make_pair(chainstate->
m_chain.
Tip(), chainstate->TargetBlock());
6423 std::vector<Chainstate*> chainstates;
6426 chainstates.reserve(m_chainstates.size());
6427 for (
const auto& chainstate : m_chainstates) {
6428 if (chainstate && chainstate->m_assumeutxo !=
Assumeutxo::INVALID && !chainstate->m_target_utxohash) {
6429 chainstates.push_back(chainstate.get());
6434 BlockValidationState state;
6435 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)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
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_MASK
All validity bits.
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ 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
static constexpr auto DATABASE_WRITE_INTERVAL_MAX
static constexpr auto DATABASE_WRITE_INTERVAL_MIN
#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 eof() const
check whether we're at the end of the source file
bool SetLimit(uint64_t nPos=std::numeric_limits< uint64_t >::max())
uint64_t GetPos() const
return the current reading position
void SkipTo(const uint64_t file_pos)
void FindByte(std::byte byte)
search for a given byte in the stream, and remain positioned on it
bool SetPos(uint64_t nPos)
rewind to a given reading position
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
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 ...
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(
CBlockIndex * pskip
pointer to the index of some further predecessor of 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.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
int Height() const
Return the maximal height in the chain.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const MessageStartChars & MessageStart() const
const CBlock & GenesisBlock() const
std::vector< int > GetAvailableSnapshotHeights() const
const ChainTxData & TxData() const
const Consensus::Params & GetConsensus() const
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
void SetBackend(CCoinsView &viewIn)
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs).
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
void SetBestBlock(const uint256 &hashBlock)
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
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/).
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dynamically alter the underlying leveldb cache size.
std::shared_future< void > CompactFull() EXCLUSIVE_LOCKS_REQUIRED(cs_main
Perform a full compaction of the underlying LevelDB on a one-shot background thread.
Abstract view on the open txout dataset.
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
virtual std::vector< uint256 > GetHeadBlocks() const
CCoinsView that brings transactions from a mempool into view.
void Reset()
Clear m_temp_added and m_non_base_coins.
const std::unordered_set< COutPoint, SaltedOutpointHasher > & GetNonBaseCoins() const
Get all coins in m_non_base_coins.
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
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 ...
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
bool HasNoInputsOf(const CTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
setEntries GetIterSet(const std::set< Txid > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
std::optional< txiter > GetIter(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CTransactionRef get(const Txid &hash) const
bool exists(const Txid &txid) const
std::set< txiter, CompareIteratorByHash > setEntries
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetParents(const CTxMemPoolEntry &entry) const
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
unsigned long size() const
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
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(
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
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)
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.
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, std::shared_ptr< const CBlock > block_to_connect, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe)
Initialize the CoinsViews UTXO set database management data structures.
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.
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,...
util::Result< void > InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(friend ChainstateManager
In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for iss...
ChainstateManager & m_chainman
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.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
node::BlockManager & m_blockman
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...
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Try to make some progress towards making pindexMostWork the active block.
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)
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.
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
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)
kernel::ChainstateManagerOpts Options
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
ValidationCache m_validation_cache
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate CurrentChainstate)() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return current chainstate targeting the most-work, network tip.
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
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.
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
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
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.
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 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)
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...
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
Update uncommitted block structures (currently: only the witness reserved value).
node::BlockManager m_blockman
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.
uint32_t nHeight
at which height this containing transaction was included in the active block chain
unsigned int fCoinBase
whether containing transaction was a coinbase
CoinsViews(DBParams db_params, CoinsViewOptions options)
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
std::vector< PerBlockConnectTrace > blocksConnected
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
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 TransactionAddedToMempool(const NewMempoolTransactionInfo &, uint64_t mempool_sequence)
std::string GetRejectReason() const
std::string GetDebugMessage() const
bool Error(const std::string &reject_reason)
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
std::string ToString() const
256-bit unsigned big integer.
constexpr bool IsNull() const
constexpr unsigned char * begin()
std::string ToString() const
constexpr const unsigned char * data() const
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)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
bool IsPruneMode() const
Whether running in -prune mode.
kernel::BlockManagerOpts Options
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)
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
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_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
@ 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...
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
#define LogPrintLevel_(category, level, should_ratelimit,...)
#define LogDebug(category,...)
@ REORG
Removed for reorganization.
std::array< uint8_t, 4 > MessageStartChars
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
bool IsInterrupted(const T &result)
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point, std::unique_ptr< CCoinsViewCursor > pcursor)
Calculate statistics about the unspent transaction output set.
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
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_vie SNAPSHOT_CHAINSTATE_SUFFIX)
std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir)
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.
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.
bool SpendsNonAnchorWitnessProg(const CTransaction &tx, const CCoinsViewCache &prevouts)
Check whether this transaction spends any witness program but P2A, including not-yet-defined ones.
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
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
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.
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 BIP34Height
Block height and hash at which BIP34 becomes active.
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.
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.
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.
std::shared_ptr< const CBlock > pblock
PerBlockConnectTrace()=default
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
std::optional< int32_t > check_block_index
Information about chainstate that notifications are sent from.
std::optional< unsigned > max_datacarrier_bytes
A data carrying output is an unspendable output containing data.
CFeeRate dust_relay_feerate
ValidationSignals * signals
CFeeRate incremental_relay_feerate
bool permit_bare_multisig
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
#define AssertLockHeld(cs)
#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,...)
#define TRACEPOINT_SEMAPHORE(context, event)
transaction_identifier< true > Wtxid
Wtxid commits to all transaction fields including the witness.
transaction_identifier< false > Txid
Txid commits to all transaction fields except the witness.
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.
static CTxMemPool::Options && Flatten(CTxMemPool::Options &&opts, bilingual_str &error)
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....
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) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
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 auto TicksSinceEpoch(Timepoint t)
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
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)
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 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) EXCLUSIVE_LOCKS_REQUIRED(
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
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 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.
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point, std::unique_ptr< CCoinsViewCursor > pcursor)
Calculate statistics about the unspent transaction output set.
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)
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)
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, const ChainstateManager &chainman, const CBlockIndex *pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
bool IsBIP30Unspendable(const uint256 &block_hash, int block_height)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30).
static void LimitValidationInterfaceQueue(ValidationSignals &signals) LOCKS_EXCLUDED(cs_main)
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(std::optional< LockPoints CalculateLockPointsAtTip)(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Check if transaction will be final in the next block to be created.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
bool FatalError(kernel::Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
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...
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
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
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Functions for validating blocks and updating the block tree.
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30).