6#include <bitcoin-build-config.h>
103 "level 0 reads the blocks from disk",
104 "level 1 verifies block validity",
105 "level 2 verifies undo data",
106 "level 3 checks disconnection of tip blocks",
107 "level 4 tries to reconnect the blocks",
108 "each level includes the checks of the previous levels",
189 for (
size_t i = 0; i < tx.
vin.size(); ++i) {
190 if (
auto coin{coins.
GetCoin(tx.
vin[i].prevout)}) {
312 auto it = queuedTx.rbegin();
313 while (it != queuedTx.rend()) {
317 true,
false).m_result_type !=
371 if (it->GetSpendsCoinbase()) {
413 if (coin.
IsSpent())
return false;
452 const bool m_bypass_limits;
460 std::vector<COutPoint>& m_coins_to_uncache;
462 const bool m_test_accept;
466 const bool m_allow_replacement;
468 const bool m_allow_sibling_eviction;
471 const bool m_package_submission;
475 const bool m_package_feerates;
480 const std::optional<CFeeRate> m_client_maxfeerate;
566 if (m_package_feerates) {
567 Assume(m_package_submission);
568 Assume(!m_allow_sibling_eviction);
570 if (m_allow_sibling_eviction)
Assume(m_allow_replacement);
625 std::set<Txid> m_conflicts;
630 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
635 bool m_sibling_eviction{
false};
689 std::map<Wtxid, MempoolAcceptResult>&
results)
711 return m_active_chainstate.m_chainman.m_validation_cache;
739 struct SubPackageState {
741 CAmount m_total_modified_fees{0};
750 std::list<CTransactionRef> m_replaced_transactions;
752 std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
757 size_t m_conflicting_size{0};
760 struct SubPackageState m_subpackage;
765 m_subpackage = SubPackageState{};
772bool MemPoolAccept::PreChecks(ATMPArgs&
args, Workspace& ws)
778 const Txid& hash = ws.m_hash;
798 if (m_pool.m_opts.require_standard && !
IsStandardTx(tx, m_pool.m_opts.max_datacarrier_bytes, m_pool.m_opts.permit_bare_multisig, m_pool.m_opts.dust_relay_feerate, reason)) {
816 }
else if (m_pool.exists(tx.
GetHash())) {
827 if (!
args.m_allow_replacement) {
835 m_view.SetBackend(m_viewmempool);
847 if (!m_view.HaveCoin(
txin.prevout)) {
849 for (
size_t out = 0;
out < tx.
vout.size();
out++) {
862 (
void)m_view.GetBestBlock();
869 assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
886 if (m_pool.m_opts.require_standard) {
904 const Coin &coin = m_view.AccessCoin(
txin.prevout);
914 if (!m_subpackage.m_changeset) {
915 m_subpackage.m_changeset = m_pool.GetChangeSet();
920 ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
922 ws.m_vsize = ws.m_tx_handle->GetTxSize();
925 if (m_pool.m_opts.require_standard) {
926 if (!
PreCheckEphemeralTx(*
ptx, m_pool.m_opts.dust_relay_feerate, ws.m_base_fees, ws.m_modified_fees, state)) {
938 if (!
bypass_limits && !
args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state))
return false;
940 ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
942 ws.m_parents = m_pool.GetParents(*ws.m_tx_handle);
944 if (!
args.m_bypass_limits) {
946 if (
const auto err{
SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
948 if (
args.m_allow_sibling_eviction && err->second !=
nullptr) {
953 ws.m_conflicts.insert(err->second->GetHash());
957 ws.m_iters_conflicting.insert(m_pool.GetIter(err->second->GetHash()).value());
958 ws.m_sibling_eviction =
true;
970 m_subpackage.m_rbf |= !ws.m_conflicts.empty();
974bool MemPoolAccept::ReplacementChecks(Workspace& ws)
980 const Txid& hash = ws.m_hash;
988 strprintf(
"too many potential replacements%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *
err_string);
994 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
995 m_subpackage.m_conflicting_size += it->GetTxSize();
998 if (
const auto err_string{
PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
999 m_pool.m_opts.incremental_relay_feerate, hash)}) {
1002 strprintf(
"insufficient fee%s", ws.m_sibling_eviction ?
" (including sibling eviction)" :
""), *
err_string);
1007 m_subpackage.m_changeset->StageRemoval(it);
1011 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1025bool MemPoolAccept::PackageRBFChecks(
const std::vector<CTransactionRef>&
txns,
1032 assert(std::all_of(
txns.cbegin(),
txns.cend(), [
this](
const auto& tx)
1033 { return !m_pool.exists(tx->GetHash());}));
1051 if (!ws.m_parents.empty()) {
1072 "package RBF failed: too many potential replacements", *
err_string);
1076 m_subpackage.m_changeset->StageRemoval(it);
1077 m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1078 m_subpackage.m_conflicting_size += it->GetTxSize();
1084 m_subpackage.m_total_modified_fees,
1085 m_subpackage.m_total_vsize,
1086 m_pool.m_opts.incremental_relay_feerate,
child_hash)}) {
1088 "package RBF failed: insufficient anti-DoS fees", *
err_string);
1097 "package RBF failed: package feerate is less than or equal to parent feerate",
1102 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1110 "package RBF failed: " +
err_tup.value().second,
"");
1113 LogDebug(
BCLog::TXPACKAGES,
"package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
1114 txns.front()->GetHash().ToString(),
txns.front()->GetWitnessHash().ToString(),
1115 txns.back()->GetHash().ToString(),
txns.back()->GetWitnessHash().ToString(),
1122bool MemPoolAccept::PolicyScriptChecks(Workspace& ws)
1145bool MemPoolAccept::ConsensusScriptChecks(Workspace& ws)
1150 const Txid& hash = ws.m_hash;
1172 LogError(
"BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not mempool flags %s, %s", hash.
ToString(), state.
ToString());
1179void MemPoolAccept::FinalizeSubpackage(
const ATMPArgs&
args)
1184 if (!m_subpackage.m_changeset->GetRemovals().empty())
Assume(
args.m_allow_replacement);
1188 std::string
log_string =
strprintf(
"replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1189 it->GetTx().GetHash().ToString(),
1190 it->GetTx().GetWitnessHash().ToString(),
1193 FeeFrac feerate{m_subpackage.m_total_modified_fees,
int32_t(m_subpackage.m_total_vsize)};
1197 const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1208 m_subpackage.m_changeset->GetTxCount(),
1215 it->GetTx().GetHash().data(),
1218 std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1224 m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1226 m_subpackage.m_changeset->Apply();
1227 m_subpackage.m_changeset.reset();
1230bool MemPoolAccept::SubmitPackage(
const ATMPArgs&
args, std::vector<Workspace>&
workspaces,
1232 std::map<Wtxid, MempoolAcceptResult>&
results)
1238 assert(std::all_of(
workspaces.cbegin(),
workspaces.cend(), [
this](
const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1253 strprintf(
"BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1254 ws.m_ptx->GetHash().ToString()));
1258 if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.GetChangeSet();
1259 m_subpackage.m_changeset->StageRemoval(m_pool.GetIter(ws.m_ptx->GetHash()).value());
1263 Assume(m_subpackage.m_changeset);
1267 m_subpackage.m_changeset->Apply();
1268 m_subpackage.m_changeset.reset();
1275 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1277 if (!m_subpackage.m_replaced_transactions.empty()) {
1278 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
1279 m_subpackage.m_replaced_transactions.size(),
workspaces.size(),
1280 m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1281 m_subpackage.m_total_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1286 auto iter = m_pool.GetIter(ws.m_ptx->GetHash());
1287 Assume(iter.has_value());
1291 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1292 results.emplace(ws.m_ptx->GetWitnessHash(),
1295 if (!m_pool.m_opts.signals)
continue;
1298 ws.m_vsize, (*iter)->GetHeight(),
1299 args.m_bypass_limits,
args.m_package_submission,
1301 m_pool.HasNoInputsOf(tx));
1302 m_pool.m_opts.signals->TransactionAddedToMempool(
tx_info, m_pool.GetAndIncrementSequence());
1313 const std::vector<Wtxid>
single_wtxid{ws.m_ptx->GetWitnessHash()};
1332 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1339 if (ws.m_conflicts.size()) {
1340 auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1354 m_subpackage.m_total_vsize = ws.m_vsize;
1355 m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1358 if (
args.m_client_maxfeerate &&
CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1363 if (!
args.m_bypass_limits && m_pool.m_opts.require_standard) {
1378 if (
args.m_test_accept) {
1386 if (!
args.m_package_submission && !
args.m_bypass_limits) {
1392 if (!m_pool.exists(ws.m_hash)) {
1399 if (m_pool.m_opts.signals) {
1401 auto iter = m_pool.GetIter(tx.
GetHash());
1402 Assume(iter.has_value());
1404 ws.m_vsize, (*iter)->GetHeight(),
1405 args.m_bypass_limits,
args.m_package_submission,
1407 m_pool.HasNoInputsOf(tx));
1408 m_pool.m_opts.signals->TransactionAddedToMempool(
tx_info, m_pool.GetAndIncrementSequence());
1411 if (!m_subpackage.m_replaced_transactions.empty()) {
1412 LogDebug(
BCLog::MEMPOOL,
"replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
1413 m_subpackage.m_replaced_transactions.size(),
1414 ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1415 ws.m_vsize -
static_cast<int>(m_subpackage.m_conflicting_size));
1434 [](
const auto& tx) { return Workspace(tx); });
1435 std::map<Wtxid, MempoolAcceptResult>
results;
1448 if (
args.m_client_maxfeerate &&
CFeeRate(ws.m_modified_fees, ws.m_vsize) >
args.m_client_maxfeerate.value()) {
1466 m_viewmempool.PackageAddTransaction(ws.m_ptx);
1488 [](
int64_t sum,
auto& ws) { return sum + ws.m_vsize; });
1490 [](
CAmount sum,
auto& ws) { return sum + ws.m_modified_fees; });
1495 [](
const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1497 if (
args.m_package_feerates &&
1498 !CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees,
placeholder_state)) {
1510 if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1516 if (m_pool.m_opts.require_standard) {
1534 if (
args.m_test_accept) {
1538 std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1539 results.emplace(ws.m_ptx->GetWitnessHash(),
1556void MemPoolAccept::CleanupTemporaryCoins()
1577 for (
const auto& outpoint : m_viewmempool.GetNonBaseCoins()) {
1580 m_view.Uncache(outpoint);
1583 m_viewmempool.Reset();
1648 for (
const auto& tx :
package) {
1650 const auto& txid = tx->
GetHash();
1654 if (m_pool.exists(
wtxid)) {
1664 const auto& entry{*
Assert(m_pool.GetEntry(txid))};
1666 }
else if (m_pool.exists(txid)) {
1674 const auto& entry{*
Assert(m_pool.GetEntry(txid))};
1687 }
else if (
package.size() == 1 ||
1723 for (
const auto& tx :
package) {
1745 if (!m_pool.exists(tx->
GetHash())) {
1786 tx->GetHash().data(),
1801 assert(std::all_of(
package.cbegin(),
package.cend(), [](
const auto& tx){return tx != nullptr;}));
1861 : m_mempool(mempool),
1863 m_chainman(chainman),
1876const CBlockIndex* Chainstate::SnapshotBase()
const
1890void Chainstate::SetTargetBlock(
CBlockIndex* block)
1900void Chainstate::SetTargetBlockHash(
uint256 block_hash)
1942 if (this->
GetRole().historical) {
1947 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.");
1950 _(
"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."));
1968 LogInfo(
"%s: invalid block=%s height=%d log2_work=%f date=%s",
__func__,
1973 LogInfo(
"%s: current best=%s height=%d log2_work=%f date=%s",
__func__,
1974 tip->GetBlockHash().ToString(),
m_chain.
Height(), log(
tip->nChainWork.getdouble())/log(2.0),
1998 txundo.vprevout.emplace_back();
2011 if (
VerifyScript(scriptSig,
m_tx_out.
scriptPubKey, witness,
m_flags,
CachingTransactionSignatureChecker(
ptxTo,
nIn,
m_tx_out.
nValue,
cacheStore, *
m_signature_cache, *
txdata), &error)) {
2012 return std::nullopt;
2015 return std::make_pair(error, std::move(
debug_str));
2020 : m_signature_cache{signature_cache_bytes}
2031 LogInfo(
"Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2054 std::vector<CScriptCheck>*
pvChecks)
2079 for (
const auto&
txin : tx.
vin) {
2089 for (
unsigned int i = 0; i < tx.
vin.size(); i++) {
2100 pvChecks->emplace_back(std::move(check));
2101 }
else if (
auto result = check(); result.has_value()) {
2146 if (
undo.nHeight == 0) {
2177 LogError(
"DisconnectBlock(): failure reading undo data\n");
2181 if (
blockUndo.vtxundo.size() + 1 != block.
vtx.size()) {
2182 LogError(
"DisconnectBlock(): block and undo data inconsistent\n");
2193 (pindex->
nHeight==91812 && pindex->
GetBlockHash() ==
uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2196 for (
int i = block.
vtx.size() - 1; i >= 0; i--) {
2204 for (
size_t o = 0;
o < tx.
vout.size();
o++) {
2205 if (!tx.
vout[
o].scriptPubKey.IsUnspendable()) {
2208 bool is_spent =
view.SpendCoin(out, &coin);
2220 if (
txundo.vprevout.size() != tx.
vin.size()) {
2221 LogError(
"DisconnectBlock(): transaction and undo data inconsistent\n");
2224 for (
unsigned int j = tx.
vin.size();
j > 0;) {
2261class ConsensusScriptVerifyFlags
2269 m_value =
flags.as_int();
2275 ConsensusScriptVerifyFlags&
operator|=(
const ConsensusScriptVerifyFlags&
flags)
2285 m_value &=
flags.as_int();
2295 value_type m_value{0};
2298template<script_verify_flag_name VFN>
2333 flags &= it->second;
2405 uint256 hashPrevBlock = pindex->
pprev ==
nullptr ?
uint256() : pindex->pprev->GetBlockHash();
2406 assert(hashPrevBlock ==
view.GetBestBlock());
2431 }
else if (it->second.GetAncestor(pindex->
nHeight) != pindex) {
2432 script_check_reason = (pindex->
nHeight > it->second.nHeight) ?
"block height above assumevalid height" :
"block not in assumevalid chain";
2458 const auto time_1{SteadyClock::now()};
2541 for (
const auto& tx : block.vtx) {
2542 for (
size_t o = 0;
o < tx->
vout.size();
o++) {
2545 "tried to overwrite transaction");
2560 const auto time_2{SteadyClock::now()};
2571 LogInfo(
"Enabling script verification at block #%d (%s): %s.",
2574 LogInfo(
"Disabling script verification at block #%d (%s).",
2575 pindex->
nHeight, block_hash.ToString());
2587 std::vector<PrecomputedTransactionData>
txsdata(block.
vtx.size());
2588 std::optional<CCheckQueueControl<CScriptCheck>>
control;
2596 for (
unsigned int i = 0; i < block.
vtx.size(); i++)
2617 "accumulated fee in the block out of range");
2625 for (
size_t j = 0;
j < tx.
vin.size();
j++) {
2654 std::vector<CScriptCheck>
vChecks;
2674 const auto time_3{SteadyClock::now()};
2676 LogDebug(
BCLog::BENCH,
" - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (
unsigned)block.
vtx.size(),
2697 const auto time_4{SteadyClock::now()};
2713 const auto time_5{SteadyClock::now()};
2728 const auto time_6{SteadyClock::now()};
2799 if (
prune_lock.second.height_first == std::numeric_limits<int>::max())
continue;
2828 m_blockman.m_block_tree_db->WriteFlag(
"prunedblockfiles",
true);
2845 LogDebug(
BCLog::COINDB,
"Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
2858 return state.
Error(
"Failed to flush block or undo file");
2875 if (!
CoinsTip().GetBestBlock().IsNull()) {
2910 }
catch (
const std::exception&
e) {
2911 LogWarning(
"Failed to start chainstate compaction (%s)",
e.what());
2915 }
catch (
const std::runtime_error&
e) {
2943 const std::string&
prefix,
2953 tip->GetBlockHash().ToString(),
tip->nHeight,
tip->nVersion,
2954 log(
tip->nChainWork.getdouble()) / log(2.0),
tip->m_chain_tx_count,
2986 for (
auto [bit, active] : bits) {
3018 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3021 LogError(
"DisconnectTip(): Failed to read block\n");
3030 LogError(
"DisconnectTip(): DisconnectBlock %s failed\n",
pindexDelete->GetBlockHash().ToString());
3097 const auto time_1{SteadyClock::now()};
3099 std::shared_ptr<CBlock>
pblockNew = std::make_shared<CBlock>();
3108 const auto time_2{SteadyClock::now()};
3109 SteadyClock::time_point
time_3;
3127 time_3 = SteadyClock::now();
3136 const auto time_4{SteadyClock::now()};
3146 const auto time_5{SteadyClock::now()};
3167 const auto time_6{SteadyClock::now()};
3370 LogInfo(
"Leaving InitialBlockDownload (latching to false)");
3399 if (signals.CallbacksPending() > 10) {
3400 signals.SyncWithValidationInterfaceQueue();
3404bool Chainstate::ActivateBestChain(
BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3609 if (pindex->
nHeight == 0)
return false;
3644 int disconnected = 0;
3671 if (!
ret)
return false;
3855 auto prev_tx_sum = [](
CBlockIndex& block) {
return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3858 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",
3874 std::deque<CBlockIndex*>
queue;
3878 while (!
queue.empty()) {
3886 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",
3892 c->TryAddBlockIndexCandidate(pindex);
3894 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range =
m_blockman.
m_blocks_unlinked.equal_range(pindex);
3895 while (range.first != range.second) {
3896 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3897 queue.push_back(it->second);
3928 "hashMerkleRoot mismatch");
3937 "bad-txns-duplicate",
3938 "duplicate transaction");
3958 assert(!block.
vtx.empty() && !block.
vtx[0]->vin.empty());
3964 "bad-witness-nonce-size",
3977 "bad-witness-merkle-match",
3987 for (
const auto& tx : block.
vtx) {
3991 "unexpected-witness",
4032 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase())
4034 for (
unsigned int i = 1; i < block.
vtx.size(); i++)
4035 if (block.
vtx[i]->IsCoinBase())
4040 for (
const auto& tx : block.
vtx) {
4053 for (
const auto& tx : block.
vtx)
4069 static const std::vector<unsigned char>
nonce(32, 0x00);
4072 tx.
vin[0].scriptWitness.stack.resize(1);
4073 tx.
vin[0].scriptWitness.stack[0] =
nonce;
4081 std::vector<unsigned char>
ret(32, 0x00);
4089 out.scriptPubKey[1] = 0x24;
4090 out.scriptPubKey[2] = 0xaa;
4091 out.scriptPubKey[3] = 0x21;
4092 out.scriptPubKey[4] = 0xa9;
4093 out.scriptPubKey[5] = 0xed;
4096 tx.
vout.push_back(out);
4104 return std::ranges::all_of(
headers,
4116 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase()) {
4123 return std::any_of(block.
vtx.begin(), block.
vtx.end(),
4124 [](
auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4226 for (
const auto& tx : block.
vtx) {
4236 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
4237 !std::equal(
expect.begin(),
expect.end(), block.
vtx[0]->vin[0].scriptSig.begin())) {
4347 LogInfo(
"Synchronizing blockheaders, height: %d (~%.2f%%)\n",
last_accepted.nHeight, progress);
4373 const double progress{100.0 * height / (height +
blocks_left)};
4374 LogInfo(
"Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4381 const CBlock& block = *pblock;
4418 if (pindex->
nTx != 0)
return true;
4431 if (!
CheckBlock(block, state, params.GetConsensus()) ||
4461 }
catch (
const std::runtime_error&
e) {
4554 const bool check_pow,
4555 const bool check_merkle_root)
4566 state.
Invalid({},
"inconclusive-not-best-prevblk");
4571 if (!
CheckBlock(block, state,
chainstate.m_chainman.GetConsensus(), check_pow, check_merkle_root)) {
4658 assert(
cs->setBlockIndexCandidates.empty());
4669 LogInfo(
"Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
4670 tip->GetBlockHash().ToString(),
4676 if (!this->
GetRole().historical) {
4726 LogInfo(
"Verification progress: 0%%");
4744 LogInfo(
"Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->
nHeight);
4750 if (!
chainstate.m_blockman.ReadBlock(block, *pindex)) {
4756 LogError(
"Verification error: found bad block at %d, hash=%s (%s)",
4798 LogWarning(
"Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4816 if (!
chainstate.m_blockman.ReadBlock(block, *pindex)) {
4820 if (!
chainstate.ConnectBlock(block, state, pindex, coins)) {
4872 std::vector<uint256>
hashHeads =
db.GetHeadBlocks();
4875 LogError(
"ReplayBlocks(): unknown inconsistent state\n");
4887 LogError(
"ReplayBlocks(): reorganization to unknown block requested\n");
4894 LogError(
"ReplayBlocks(): reorganization from unknown block requested\n");
4918 LogError(
"RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n",
pindexOld->nHeight,
pindexOld->GetBlockHash().ToString());
4964 block = block->pprev;
4970void Chainstate::ClearBlockIndexCandidates()
4976void Chainstate::PopulateBlockIndexCandidates()
4998 if (!
ret)
return false;
5000 m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
5035 LogError(
"Writing genesis block to disk failed");
5040 }
catch (
const std::runtime_error&
e) {
5041 LogError(
"Failed to write genesis block: %s",
e.what());
5056 const auto start{SteadyClock::now()};
5071 unsigned int nSize = 0;
5075 blkdat.FindByte(std::byte(params.MessageStart()[0]));
5076 nRewind =
blkdat.GetPos() + 1;
5078 if (buf != params.MessageStart()) {
5085 }
catch (
const std::exception&) {
5104 std::shared_ptr<CBlock> pblock{};
5123 pblock = std::make_shared<CBlock>();
5125 nRewind =
blkdat.GetPos();
5128 if (
AcceptBlock(pblock, state,
nullptr,
true,
dbp,
nullptr,
true)) {
5172 std::deque<uint256>
queue;
5173 queue.push_back(hash);
5174 while (!
queue.empty()) {
5178 while (range.first != range.second) {
5179 std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5188 queue.push_back(block_hash);
5196 }
catch (
const std::exception&
e) {
5211 }
catch (
const std::runtime_error&
e) {
5251 std::multimap<const CBlockIndex*, const CBlockIndex*>
forward;
5293 while (pindex !=
nullptr) {
5302 if (pindex->
pprev !=
nullptr) {
5320 if (pindex->
pprev ==
nullptr) {
5324 if (
c->m_chain.Genesis() !=
nullptr) {
5325 assert(pindex ==
c->m_chain.Genesis());
5368 if (!pindex->
pprev) {
5384 if (
c->m_chain.Tip() ==
nullptr)
continue;
5421 if (
pindexFirstMissing ==
nullptr || pindex ==
c->m_chain.Tip() || pindex ==
c->SnapshotBase()) {
5427 if (!
c->TargetBlock() ||
c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5428 assert(
c->setBlockIndexCandidates.contains(pindex));
5436 assert(!
c->setBlockIndexCandidates.contains(pindex));
5444 if (it->second == pindex) {
5469 if (!
c->TargetBlock() ||
c->TargetBlock()->GetAncestor(pindex->
nHeight) == pindex) {
5482 auto range{
forward.equal_range(pindex)};
5483 if (range.first != range.second) {
5485 pindex = range.first->second;
5512 while (
rangePar.first->second != pindex) {
5541std::string Chainstate::ToString()
5545 return strprintf(
"Chainstate [%s] @ height %d (%s)",
5563 LogInfo(
"[%s] resized coinsdb cache to %.1f MiB",
5565 LogInfo(
"[%s] resized coinstip cache to %.1f MiB",
5585 if (pindex ==
nullptr) {
5595 const auto block_time{
5650 LogWarning(
"[snapshot] snapshot chainstate dir being removed lacks %s file",
5653 }
catch (
const fs::filesystem_error&
e) {
5654 LogWarning(
"[snapshot] failed to remove file %s: %s\n",
5697 return util::Error{
Untranslated(
strprintf(
"assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5704 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",
5714 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.")};
5718 if (mempool && mempool->
size() > 0) {
5756 return std::make_unique<Chainstate>(
5781 "Manually remove it before restarting.\n"), fs::PathToString(*
snapshot_datadir)));
5814 LogInfo(
"[snapshot] (%.2f MB)",
5815 chainstate.CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
5825 snapshot_loaded ?
"saving snapshot chainstate" :
"flushing coins cache",
5826 coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
5834 const char*
what() const noexcept
override
5836 return "ComputeUTXOStats interrupted.";
5870 "(%d) - refusing to load snapshot",
base_height))};
5903 outpoint.
hash = txid;
5906 outpoint.
n >= std::numeric_limits<
decltype(outpoint.
n)>::max()
5915 coins_cache.EmplaceCoinInternalDANGER(outpoint, std::move(coin));
5921 LogInfo(
"[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5923 static_cast<float>(
coins_processed) * 100 /
static_cast<float>(coins_count),
5924 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5950 }
catch (
const std::ios_base::failure&) {
5967 }
catch (
const std::ios_base::failure&) {
5976 LogInfo(
"[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
6042 LogInfo(
"[snapshot] validated snapshot (%.2f MB)",
6043 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
6080 "%s failed to validate the -assumeutxo snapshot state. "
6081 "This indicates a hardware problem, or a bug in the software, or a "
6082 "bad software modification that allowed an invalid snapshot to be "
6083 "loaded. As a result of this, the node will shut down and stop using any "
6084 "state that was built on the snapshot, resetting the chain height "
6085 "from %d to %d. On the next "
6086 "restart, the node will resume syncing from %d "
6087 "without using any snapshot data. "
6088 "Please report this incident to %s, including how you obtained the snapshot. "
6089 "The invalid snapshot chainstate will be left on disk in case it is "
6090 "helpful in diagnosing the issue that caused this error."),
6096 LogError(
"[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6116 LogWarning(
"[snapshot] assumeutxo data not found for height "
6117 "(%d) - refusing to validate snapshot",
validated_cs.m_chain.Height());
6124 LogInfo(
"[snapshot] computing UTXO stats for background chainstate to validate "
6125 "snapshot - this could take a few minutes");
6128 CoinStatsHashType::HASH_SERIALIZED,
6138 LogWarning(
"[snapshot] failed to generate stats for validation coins db");
6153 LogWarning(
"[snapshot] hash mismatch: actual=%s, expected=%s",
6155 au_data.hash_serialized.ToString());
6160 LogInfo(
"[snapshot] snapshot beginning at %s has been fully validated",
6176void ChainstateManager::MaybeRebalanceCaches()
6187 LogInfo(
"[snapshot] allocating all cache to the snapshot chainstate");
6208void ChainstateManager::ResetChainstates()
6220 if (!opts.check_block_index.has_value()) opts.
check_block_index = opts.chainparams.DefaultConsistencyChecks();
6221 if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work =
UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6222 if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6223 return std::move(opts);
6228 m_interrupt{interrupt},
6231 m_all_consensus_script_flags{GetAllConsensusScriptFlags(m_options.chainparams.GetConsensus())},
6232 m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
6243Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6254 LogInfo(
"[snapshot] detected active snapshot chainstate (%s) - loading",
6255 fs::PathToString(*path));
6283 return (
block_index.nHeight==91842 &&
block_index.GetBlockHash() ==
uint256{
"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6289 return (block_height==91722 && block_hash ==
uint256{
"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
6290 (block_height==91812 && block_hash ==
uint256{
"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6312 }
catch (
const fs::filesystem_error&
e) {
6313 LogError(
"While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6316 "Rename of '%s' -> '%s' failed. "
6317 "You should resolve this by manually moving or deleting the invalid "
6318 "snapshot directory %s, otherwise you will encounter the same error again "
6319 "on the next startup."),
6331 LogError(
"Deletion of %s failed. Please remove it manually to continue reindexing.",
6348void ChainstateManager::RecalculateBestHeader()
6359std::optional<int> ChainstateManager::BlocksAheadOfTip()
const
6369 return std::nullopt;
6393 LogInfo(
"[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6399 const fs::filesystem_error& err) {
6400 LogError(
"[snapshot] Error renaming path (%s) -> (%s): %s\n",
6401 fs::PathToString(
p_old), fs::PathToString(
p_new), err.what());
6403 "Rename of '%s' -> '%s' failed. "
6404 "Cannot clean up the background chainstate leveldb directory."),
6405 fs::PathToString(
p_old), fs::PathToString(
p_new)));
6410 }
catch (
const fs::filesystem_error&
e) {
6415 LogInfo(
"[snapshot] moving snapshot chainstate (%s) to "
6416 "default chainstate directory (%s)",
6421 }
catch (
const fs::filesystem_error&
e) {
6429 LogWarning(
"Deletion of %s failed. Please remove it manually, as the "
6430 "directory is now unnecessary.",
6433 LogInfo(
"[snapshot] deleted background chainstate directory (%s)",
6467std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange()
const
6492 if (!
chainstate->ActivateBestChain(state,
nullptr)) {
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
constexpr CAmount COIN
The amount of satoshis in one BTC.
arith_uint256 UintToArith256(const uint256 &a)
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params ¶ms)
Return the time it would take to redo the work difference between from and to, assuming the current h...
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ BLOCK_VALID_MASK
All validity bits.
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
@ BLOCK_FAILED_VALID
stage after last reached validness failed
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
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.
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*.
Wrapper around an AutoFile& that implements a ring buffer to deserialize from.
uint64_t GetPos() const
return the current 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
(memory only) Number of transactions in the chain up to and including this block.
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
uint256 GetBlockHash() const
int64_t GetBlockTime() const
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
unsigned int nTx
Number of transactions in this block.
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.
An in-memory indexed chain of blocks.
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
const CBlockIndex * FindFork(const CBlockIndex &index) const
Find the last common block between this chain and a block index entry.
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
std::vector< int > GetAvailableSnapshotHeights() const
const ChainTxData & TxData() const
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
virtual void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
void SetBestBlock(const uint256 &block_hash)
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs)
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
CCoinsView backed by the coin database (chainstate/)
std::shared_future< void > CompactFullAsync() EXCLUSIVE_LOCKS_REQUIRED(cs_main
Perform a full compaction of the underlying LevelDB on a one-shot background thread.
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dynamically alter the underlying leveldb cache size.
Pure abstract view on the open txout dataset.
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const =0
Retrieve the Coin (unspent transaction output) for a given outpoint.
CCoinsView that brings transactions from a mempool into view.
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
void Finalize(std::span< unsigned char > output)
CHash256 & Write(std::span< const unsigned char > input)
An outpoint - a combination of a transaction hash and an index n into its vout.
A hasher class for SHA-256.
void Finalize(unsigned char hash[OUTPUT_SIZE])
CSHA256 & Write(const unsigned char *data, size_t len)
Closure representing one script verification Note that this stores references to the spending transac...
SignatureCache * m_signature_cache
PrecomputedTransactionData * txdata
script_verify_flags m_flags
std::optional< std::pair< ScriptError, std::string > > operator()()
const CTransaction * ptxTo
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
const Txid & GetHash() const LIFETIMEBOUND
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPool::txiter TxHandle
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
void UpdateTransactionsFromBlock(const std::vector< Txid > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
void AddTransactionsUpdated(unsigned int n)
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
size_t DynamicMemoryUsage() const
void removeForReorg(CChain &chain, std::function< bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs
After reorg, filter the entries that would no longer be valid in the next block, and update the entri...
bool exists(const Txid &txid) const
std::set< txiter, CompareIteratorByHash > setEntries
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
std::vector< RemovedMempoolTransactionInfo > removeForBlock(const std::vector< CTransactionRef > &vtx) EXCLUSIVE_LOCKS_REQUIRED(cs)
unsigned long size() const
An output of a transaction.
Undo information for a CTransaction.
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
CVerifyDB(kernel::Notifications ¬ifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
CChain m_chain
The current chain of blockheaders we consult and build on.
void SetTargetBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(boo ReachedTarget)() const EXCLUSIVE_LOCKS_REQUIRED(
Set target block for this chainstate.
CTxMemPool * GetMempool()
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(NodeClock::time_poin m_next_write)
Check warning conditions and do some notifications on new chain tip set.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, std::shared_ptr< const CBlock > block_to_connect, std::vector< ConnectedBlock > &connected_blocks, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe)
Return the current role of the chainstate.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex &index_most_work, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, std::vector< ConnectedBlock > &connected_blocks) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the [start, end] (inclusive) of block heights we can prune.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more,...
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Add a block to the candidate set if it has as much work as the current tip.
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Resize the CoinsViews caches dynamically and flush state to disk.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices.
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
fs::path StoragePath() const
Return path to chainstate leveldb directory.
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
util::Result< void > PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
const uint256 & AssumedValidBlock() const
ValidationCache m_validation_cache
double GetBackgroundVerificationProgress(const CBlockIndex &pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess background verification progress in case assume-utxo was used (as a fraction between 0....
double GuessVerificationProgress(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
const script_verify_flags m_all_consensus_script_flags
Store the potential consensus script flags for this manager's selected params.
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
std::unique_ptr< Chainstate > RemoveChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Remove a chainstate.
kernel::Notifications & GetNotifications() const
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
bool ShouldCheckBlockIndex() const
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
void CheckBlockIndex() const
Make various assertions about the state of the block index.
const util::SignalInterrupt & m_interrupt
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< uint256, FlatFilePos > *blocks_with_unknown_parent=nullptr)
Import blocks from an external file.
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
VersionBitsCache m_versionbitscache
Track versionbit status.
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
const CChainParams & GetParams() const
void GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
bool ProcessNewBlockHeaders(std::span< const CBlockHeader > headers, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
ChainstateManager(const util::SignalInterrupt &interrupt, Options options, node::BlockManager::Options blockman_options)
const arith_uint256 & MinimumChainWork() const
static script_verify_flags GetAllConsensusScriptFlags(const Consensus::Params ¶ms)
Determine the potential consensus script flags for blocks in a chain.
void UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update and possibly latch the IBD status.
bool LoadGenesisBlock()
Ensures a genesis block is in the block tree, possibly writing one to disk.
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndex * ActivateSnapshot)(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Instantiate a new chainstate.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
void ReportHeadersPresync(int64_t height, int64_t timestamp)
This is used by net_processing to report pre-synchronization progress of headers, as headers are not ...
std::atomic_bool m_cached_is_ibd
Whether initial block download (IBD) is ongoing.
bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex())
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev) const
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
Chainstate *LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &AddChainstate(std::unique_ptr< Chainstate > chainstate) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(std::optional< std::pair< const CBlockIndex *, const CBlockIndex * > > GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(util::Result< void > ActivateBestChains() LOCKS_EXCLUDED(void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > BlocksAheadOfTip() const LOCKS_EXCLUDED(CCheckQueue< CScriptCheck > & GetCheckQueue()
When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process...
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Sufficiently validate a block for disk storage (and store on disk).
CTxOut out
unspent transaction output
bool IsSpent() const
Either this coin never existed (see e.g.
uint32_t nHeight
at which height this containing transaction was included in the active block chain
static CoinsViewEmpty & Get()
CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during Con...
ResetGuard StartFetching(const CBlock &block LIFETIMEBOUND) noexcept
Start fetching inputs from block.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
std::pair< uint32_t, size_t > setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
DisconnectedBlockTransactions.
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 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
void BlockConnected(const kernel::ChainstateRole &, std::shared_ptr< const CBlock >, const CBlockIndex *pindex)
void BlockChecked(const std::shared_ptr< const CBlock > &, const BlockValidationState &)
void ChainStateFlushed(const kernel::ChainstateRole &, const CBlockLocator &)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void ActiveTipChange(const CBlockIndex &, bool)
void MempoolTransactionsRemovedForBlock(std::shared_ptr< const CBlock >, std::vector< RemovedMempoolTransactionInfo >, unsigned int block_height)
void BlockDisconnected(std::shared_ptr< const CBlock >, const CBlockIndex *pindex)
std::string GetRejectReason() const
std::string GetDebugMessage() const
bool Error(const std::string &reject_reason)
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
std::string ToString() const
std::vector< std::pair< int, bool > > CheckUnknownActivations(const CBlockIndex *pindex, const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check for unknown activations Returns a vector containing the bit number used for signalling and a bo...
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
256-bit unsigned big integer.
constexpr bool IsNull() const
std::string ToString() const
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warningSet(Warning id, const bilingual_str &message)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual InterruptResult blockTip(SynchronizationState state, const CBlockIndex &index, double verification_progress)
virtual void warningUnset(Warning id)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
const kernel::BlockManagerOpts m_opts
void FindFilesToPrune(std::set< int > &setFilesToPrune, int last_prune, const Chainstate &chain, ChainstateManager &chainman)
Prune block and undo files (blk???.dat and rev???.dat) so that the disk space used is less than a use...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockFileInfo *GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight) EXCLUSIVE_LOCKS_REQUIRED(void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(bool IsPruneMode() const
Get block file info entry for one block file.
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
std::vector< CBlockIndex * > GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
bool LoadingBlocks() const
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
void WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< uint256 > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(CBlockIndex * AddToBlockIndex(const CBlockHeader &block, CBlockIndex *&best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove any pruned block & undo files that are still on disk.
void AddUnlinkedBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain)
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
uint64_t CalculateCurrentUsage() EXCLUSIVE_LOCKS_REQUIRED(bool CheckBlockDataAvailability(const CBlockIndex &upper_block, const CBlockIndex &lower_block, BlockStatus block_status=BLOCK_HAVE_DATA) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex &GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block LIFETIMEBOUND=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Calculate the amount of disk space the block & undo files currently use.
static constexpr script_verify_flags from_int(value_type f)
std::string ToString() const
constexpr const std::byte * begin() const
const uint256 & ToUint256() const LIFETIMEBOUND
std::string GetHex() const
NotNull is intended to be used to denote that a smart pointer type can not hold a nullptr value.
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
std::string FormatFullVersion()
const Coin & AccessByTxid(const CCoinsViewCache &view, const Txid &txid)
Utility function to find any unspent output with a given txid.
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
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)
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
auto flush
Flush changes in top cache to the one below.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
uint256 BlockWitnessMerkleRoot(const CBlock &block)
constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction.
constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
static int64_t GetBlockWeight(const CBlock &block)
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
constexpr int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...
constexpr unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
constexpr int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
constexpr 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 DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for this block.
constexpr unsigned int MAX_DISCONNECTED_TX_POOL_BYTES
Maximum bytes for transactions to store for processing during reorg.
bool CheckEphemeralSpends(const Package &package, CFeeRate dust_relay_rate, const CTxMemPool &tx_pool, TxValidationState &out_child_state, Wtxid &out_child_wtxid)
Called for each transaction(package) if any dust is in the package.
bool PreCheckEphemeralTx(const CTransaction &tx, CFeeRate dust_relay_rate, CAmount base_fee, CAmount mod_fee, TxValidationState &state)
These utility functions ensure that ephemeral dust is safely created and spent without unduly risking...
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ SCRIPT_VERIFY_NULLDUMMY
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
constexpr script_verify_flags SCRIPT_VERIFY_NONE
Script verification flags.
is a home for simple enum and struct type definitions that can be used internally by functions in the...
#define LogDebug(category,...)
@ REORG
Removed for reorganization.
std::array< uint8_t, 4 > MessageStartChars
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...
constexpr T & operator&=(T &lhs, T rhs)
std::function< FILE *(const fs::path &, const char *)> FopenFn
std::optional< CCoinsStats > ComputeUTXOStats(CoinStatsHashType hash_type, const CCoinsViewDB &view, node::BlockManager &blockman, const std::function< void()> &interruption_point)
static std::optional< CCoinsStats > ComputeUTXOStats(T hash_obj, const CCoinsViewDB &view, node::BlockManager &blockman, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
bool IsInterrupted(const T &result)
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
The file in the snapshot chainstate dir which stores the base blockhash.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate)
std::optional< fs::path > FindAssumeutxoChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate) EXCLUSIVE_LOCKS_REQUIRED(std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir) EXCLUSIVE_LOCKS_REQUIRED(constexpr std::string_view SNAPSHOT_CHAINSTATE_SUFFIX
Write out the blockhash of the snapshot base block that was used to construct this chainstate.
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir)
constexpr NoRateLimitTag NO_RATE_LIMIT
bilingual_str ErrorString(const Result< T > &result)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
static ConnectionDirection & operator|=(ConnectionDirection &a, ConnectionDirection b)
std::shared_ptr< Chain::Notifications > m_notifications
bool IsChildWithParents(const Package &package)
Context-free check that a package is exactly one child and its parents; not all parents need to be pr...
bool IsWellFormedPackage(const Package &txns, PackageValidationState &state)
Context-free package policy checks:
uint256 GetPackageHash(const std::vector< CTransactionRef > &transactions)
Get the hash of the concatenated wtxids of transactions, with wtxids treated as a little-endian numbe...
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_MEMPOOL_ERROR
Mempool logic error.
@ PCKG_TX
At least one tx is invalid.
std::optional< std::pair< DiagramCheckError, std::string > > ImprovesFeerateDiagram(CTxMemPool::ChangeSet &changeset)
The replacement transaction must improve the feerate diagram of the mempool.
std::optional< std::string > PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const Txid &txid)
The replacement transaction must pay more fees than the original transactions.
std::optional< std::string > EntriesAndTxidsDisjoint(const CTxMemPool::setEntries &ancestors, const std::set< Txid > &direct_conflicts, const Txid &txid)
Check the intersection between two sets of transactions (a set of mempool entries and a set of txids)...
std::optional< std::string > GetEntriesForConflicts(const CTransaction &tx, CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting, CTxMemPool::setEntries &all_conflicts)
Get all descendants of iters_conflicting.
@ FAILURE
New diagram wasn't strictly superior
TxValidationState ValidateInputsStandardness(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
bool SpendsNonAnchorWitnessProg(const CTransaction &tx, const CCoinsViewCache &prevouts)
Check whether this transaction spends any witness program but P2A, including not-yet-defined ones.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
constexpr unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
constexpr script_verify_flags MANDATORY_SCRIPT_VERIFY_FLAGS
Mandatory script verification flags that all new transactions must comply with for them to be valid.
constexpr unsigned int MAX_STANDARD_TX_SIGOPS_COST
The maximum number of sigops we're willing to relay/mine in a single tx.
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
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.
constexpr TransactionSerParams TX_NO_WITNESS
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.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< uint256 > vHave
A mutable version of CTransaction.
std::vector< CTxOut > vout
Holds various statistics on transactions within a chain.
User-controlled performance and debug options.
std::shared_ptr< const CBlock > pblock
const CBlockIndex * pindex
Parameters that influence chain consensus.
int BIP34Height
Block height and hash at which BIP34 becomes active.
std::map< uint256, script_verify_flags > script_flag_exceptions
Hashes of blocks that.
int64_t nPowTargetSpacing
std::chrono::seconds PowTargetSpacing() const
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
Data structure storing a fee and size.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
const ResultType m_result_type
Result type.
const TxValidationState m_state
Contains information about why the transaction failed.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
static MempoolAcceptResult MempoolTxDifferentWitness(const Wtxid &other_wtxid)
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
static time_point now() noexcept
Return current system time or mocked time, if set.
static time_point now() noexcept
Return current system time or mocked time, if set.
Validation result for package mempool acceptance.
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
std::vector< CTxOut > m_spent_outputs
const char * what() const noexcept override
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
const fs::path blocks_dir
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
ValidationSignals * signals
std::optional< int32_t > check_block_index
std::chrono::seconds max_tip_age
If the tip is older than this, the node is considered to be in initial block download.
int32_t prevoutfetch_threads_num
Number of worker threads used for prefetching block input prevouts. Zero means no parallel fetching.
const CChainParams & chainparams
CoinsViewOptions coins_view
Information about chainstate that notifications are sent from.
bool validated
Whether this is a notification from a chainstate that's been fully validated starting from the genesi...
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define 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)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
std::optional< std::pair< std::string, CTransactionRef > > SingleTRUCChecks(const CTxMemPool &pool, const CTransactionRef &ptx, const std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &mempool_parents, const std::set< Txid > &direct_conflicts, int64_t vsize)
Must be called for every transaction, even if not TRUC.
std::optional< std::string > PackageTRUCChecks(const CTxMemPool &pool, const CTransactionRef &ptx, int64_t vsize, const Package &package, const std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &mempool_parents)
Must be called for every transaction that is submitted within a package, even if not TRUC.
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp)
Test whether the LockPoints height and time are still valid on the current chain.
constexpr uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
std::chrono::duration< double, std::chrono::seconds::period > SecondsDouble
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
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 CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept)
Try to add a transaction to the mempool.
bool HasValidProofOfWork(std::span< const CBlockHeader > headers, const Consensus::Params &consensusParams)
Check that the proof of work on each blockheader matches the value in nBits.
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
bool FatalError(Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
static void UpdateTipLog(const ChainstateManager &chainman, const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const std::string &func_name, const std::string &prefix, const std::string &warning_messages, const bool background_validation) EXCLUSIVE_LOCKS_REQUIRED(
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, script_verify_flags flags, PrecomputedTransactionData &txdata, CCoinsViewCache &coins_tip, ValidationCache &validation_cache) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
static constexpr auto DATABASE_WRITE_INTERVAL_MAX
static bool CheckWitnessMalleation(const CBlock &block, bool expect_witness_commitment, BlockValidationState &state)
CheckWitnessMalleation performs checks for block malleation with regard to its witnesses.
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED(
static bool CheckMerkleRoot(const CBlock &block, BlockValidationState &state)
static constexpr int PRUNE_LOCK_BUFFER
The number of blocks to keep below the deepest prune lock.
arith_uint256 CalculateClaimedHeadersWork(std::span< const CBlockHeader > headers)
Return the sum of the claimed work on a given set of headers.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE
Maximum age of our tip for us to be considered current for fee estimation.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache, bool snapshot_loaded)
static bool IsCurrentForFeeEstimation(Chainstate &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr auto DATABASE_WRITE_INTERVAL_MIN
Time window to wait between writing blocks/block index and chainstate to disk.
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.
return CheckInputScripts(tx, state, view, flags, CheckInputScriptsFor::Mempool, true, true, txdata, validation_cache)
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt &interrupt)
static bool ShouldCompactChainstate(bool in_ibd)
static SynchronizationState GetSynchronizationState(bool init, bool blockfiles_indexed)
bool IsBIP30Unspendable(const uint256 &block_hash, int block_height)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
static void LimitValidationInterfaceQueue(ValidationSignals &signals) LOCKS_EXCLUDED(cs_main)
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
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)
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
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.
constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
constexpr script_verify_flags CONSENSUS_SCRIPT_VERIFY_FLAGS
Set of script verify flags that may be enforced at the consensus level (for some combination of chain...
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.
CheckInputScriptsFor
The context CheckInputScripts is called in, which decides how a script failure is reported: as a cons...
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
constexpr unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
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)
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, script_verify_flags flags, CheckInputScriptsFor check_for, 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.