99 "level 0 reads the blocks from disk",
100 "level 1 verifies block validity",
101 "level 2 verifies undo data",
102 "level 3 checks disconnection of tip blocks",
103 "level 4 tries to reconnect the blocks",
104 "each level includes the checks of the previous levels",
121 : excessiveBlockSize(config.GetMaxBlockSize()), checkPoW(
true),
122 checkMerkleRoot(
true) {}
164 for (
size_t i = 0; i < tx.
vin.size(); ++i) {
168 LogPrintf(
"ERROR: %s: Missing input %d in transaction \'%s\'\n",
292 : m_pool(mempool), m_view(&m_dummy),
301 const bool m_bypass_limits;
309 std::vector<COutPoint> &m_coins_to_uncache;
310 const bool m_test_accept;
311 const unsigned int m_heightOverride;
317 const bool m_package_submission;
323 const bool m_package_feerates;
467 std::unique_ptr<CTxMemPoolEntry> m_entry;
505 const uint32_t m_next_block_script_verify_flags;
506 int m_sig_checks_standard;
527 bool Finalize(
const ATMPArgs &args, Workspace &
ws)
537 std::map<TxId, MempoolAcceptResult> &
results)
552 return state.Invalid(
554 "mempool min fee not met",
561 return state.Invalid(
563 "min relay fee not met",
580bool MemPoolAccept::PreChecks(ATMPArgs &args, Workspace &
ws) {
585 const TxId &txid =
ws.m_ptx->GetId();
603 if (m_pool.m_require_standard &&
605 m_pool.m_permit_bare_multisig,
606 m_pool.m_dust_relay_feerate, reason)) {
615 *
Assert(m_active_chainstate.m_chain.Tip()),
616 args.m_config.GetChainParams().GetConsensus(), tx,
ctxState)) {
625 if (m_pool.exists(txid)) {
627 "txn-already-in-mempool");
635 "finalized-tx-conflict");
640 "txn-mempool-conflict");
644 m_view.SetBackend(m_viewmempool);
657 if (!m_view.HaveCoin(
txin.prevout)) {
659 for (
size_t out = 0; out < tx.
vout.size(); out++) {
664 "txn-already-known");
671 "bad-txns-inputs-missingorspent");
676 if (!m_view.HaveInputs(tx)) {
678 "bad-txns-inputs-spent");
682 m_view.GetBestBlock();
687 m_view.SetBackend(m_dummy);
689 assert(m_active_chainstate.m_blockman.LookupBlockIndex(
690 m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
699 m_active_chainstate.m_chain.Tip(), m_view, tx)};
710 m_active_chainstate.m_chain.Height() + 1,
717 if (m_pool.m_require_standard &&
720 "bad-txns-nonstandard-inputs");
724 ws.m_modified_fees =
ws.m_base_fees;
725 m_pool.ApplyDelta(txid,
ws.m_modified_fees);
734 ws.m_precomputed_txdata,
ws.m_sig_checks_standard)) {
739 ws.m_entry = std::make_unique<CTxMemPoolEntry>(
744 ws.m_vsize =
ws.m_entry->GetTxVirtualSize();
754 m_pool.m_min_relay_feerate.GetFee(
ws.m_ptx->GetTotalSize())) {
761 m_pool.m_min_relay_feerate.GetFee(nSize)));
774bool MemPoolAccept::ConsensusScriptChecks(
const ATMPArgs &args, Workspace &
ws) {
794 tx, state, m_view, m_pool,
ws.m_next_block_script_verify_flags,
796 m_active_chainstate.CoinsTip())) {
800 LogPrintf(
"BUG! PLEASE REPORT THIS! CheckInputScripts failed against "
801 "latest-block but not STANDARD flags %s, %s\n",
811 "%s: BUG! PLEASE REPORT THIS! SigChecks count differed between "
812 "standard and consensus flags in %s",
823 for (
const CTxIn &input :
ptx->vin) {
832bool MemPoolAccept::Finalize(
const ATMPArgs &args, Workspace &
ws) {
835 const TxId &txid =
ws.m_ptx->GetId();
842 m_pool.addUnchecked(entry);
846 std::make_shared<
const std::vector<Coin>>(
848 m_pool.GetAndIncrementSequence());
856 m_pool.LimitSize(m_active_chainstate.CoinsTip());
857 if (!m_pool.exists(txid)) {
867bool MemPoolAccept::SubmitPackage(
868 const ATMPArgs &args, std::vector<Workspace> &
workspaces,
870 std::map<TxId, MempoolAcceptResult> &
results) {
876 [
this](
const auto &
ws) { return !m_pool.exists(ws.m_ptx->GetId()); }));
893 strprintf(
"BUG! PolicyScriptChecks succeeded but "
894 "ConsensusScriptChecks failed: %s",
895 ws.m_ptx->GetId().ToString()));
905 if (!Finalize(args,
ws)) {
911 strprintf(
"BUG! Adding to mempool failed: %s",
912 ws.m_ptx->GetId().ToString()));
918 m_pool.LimitSize(m_active_chainstate.CoinsTip());
924 [](
const auto &
ws) { return ws.m_ptx->GetId(); });
930 args.m_package_feerates
931 ?
ws.m_package_feerate
936 : std::vector<TxId>({
ws.m_ptx->GetId()});
964 if (
ws.m_state.GetResult() ==
979 const TxId txid =
ptx->GetId();
989 if (
auto it = m_pool.mapNextTx.lower_bound(
COutPoint{txid, 0});
990 it != m_pool.mapNextTx.end() && it->first->GetTxId() == txid) {
991 LogPrintf(
"%s: BUG! PLEASE REPORT THIS! Attempt to add txid %s, but "
992 "its outputs are already spent in the "
996 "txn-child-before-parent");
1003 if (args.m_test_accept) {
1008 if (!Finalize(args,
ws)) {
1023 const std::vector<CTransactionRef> &
txns, ATMPArgs &args) {
1037 [
this](
const auto &tx) {
1039 tx, GetNextBlockScriptFlags(m_active_chainstate.m_chain.Tip(),
1040 m_active_chainstate.m_chainman));
1042 std::map<TxId, MempoolAcceptResult>
results;
1052 "transaction failed");
1062 m_viewmempool.PackageAddTransaction(
ws.m_ptx);
1080 [](
int64_t sum,
auto &
ws) { return sum + ws.m_ptx->GetTotalSize(); });
1083 [](
int64_t sum,
auto &
ws) { return sum + ws.m_vsize; });
1086 [](
Amount sum,
auto &
ws) { return sum + ws.m_modified_fees; });
1092 [](
const auto &
ws) { return ws.m_ptx->GetId(); });
1094 if (args.m_package_feerates &&
1098 "transaction failed");
1110 if (args.m_test_accept &&
1114 args.m_package_feerates
1115 ?
ws.m_package_feerate
1120 : std::vector<TxId>{
ws.m_ptx->GetId()};
1131 if (args.m_test_accept) {
1144MemPoolAccept::AcceptSubPackage(
const std::vector<CTransactionRef> &
subpackage,
1154 ATMPArgs
single_args = ATMPArgs::SingleInPackageAccept(args);
1160 "transaction failed");
1193 for (
const auto &outpoint : m_viewmempool.GetNonBaseCoins()) {
1197 m_view.Uncache(outpoint);
1200 m_viewmempool.Reset();
1225 "package-not-child-with-parents");
1238 [](
const auto &tx) { return tx->GetId(); });
1248 for (
const auto &input :
child->vin) {
1250 args.m_coins_to_uncache.push_back(input.prevout);
1257 m_view.SetBackend(m_active_chainstate.CoinsTip());
1259 const auto &input) {
1261 m_view.HaveCoin(input.prevout);
1263 if (!std::all_of(
child->vin.cbegin(),
child->vin.cend(),
1267 "package-not-child-with-unconfirmed-parents");
1273 m_view.SetBackend(m_dummy);
1287 for (
const auto &tx :
package) {
1288 const auto &txid = tx->
GetId();
1291 if (m_pool.exists(txid)) {
1305 auto iter = m_pool.GetIter(txid);
1308 (*
iter.value())->GetTxSize(),
1309 (*
iter.value())->GetFee()));
1320 assert(m_pool.exists(txid));
1359 m_pool.LimitSize(m_active_chainstate.CoinsTip());
1361 for (
const auto &tx :
package) {
1362 const auto &txid = tx->
GetId();
1374 !m_pool.exists(txid)) {
1376 "transaction failed");
1392 if (!m_pool.exists(tx->
GetId())) {
1394 "transaction failed");
1428 auto args = MemPoolAccept::ATMPArgs::SingleAccept(
1432 .AcceptSingleTransaction(tx, args);
1459 [](
const auto &tx) { return tx != nullptr; }));
1467 auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(
1470 .AcceptMultipleTransactions(
package, args);
1472 auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(
1475 .AcceptPackage(
package, args);
1509void CoinsViews::InitCache() {
1517 : m_mempool(mempool), m_blockman(
blockman), m_chainman(chainman),
1571 LogPrintf(
"Leaving InitialBlockDownload (latching to false)\n");
1598 std::string warning =
1599 std::string(
"'Warning: Large-work fork detected, forking after "
1606 LogPrintf(
"%s: Warning: Large fork found\n forking the "
1607 "chain at height %d (%s)\n lasting to height %d "
1608 "(%s).\nChain state database corruption likely.\n",
1615 LogPrintf(
"%s: Warning: Found invalid chain at least ~6 blocks "
1616 "longer than our best chain.\nChain state database "
1617 "corruption likely.\n",
1675 LogPrintf(
"%s: invalid block=%s height=%d log2_work=%f date=%s\n",
1682 LogPrintf(
"%s: current best=%s height=%d log2_work=%f date=%s\n",
1684 log(
tip->nChainWork.getdouble()) /
log(2.0),
1694 pindex->nStatus = pindex->nStatus.withFailed();
1710 txundo.vprevout.emplace_back();
1711 bool is_spent =
view.SpendCoin(
txin.prevout, &
txundo.vprevout.back());
1723 const CScript &scriptSig =
ptxTo->vin[
nIn].scriptSig;
1749 std::vector<CScriptCheck> *
pvChecks) {
1764 (pBlockLimitSigChecks &&
1767 "too-many-sigchecks");
1774 for (
size_t i = 0; i < tx.
vin.size(); i++) {
1791 pvChecks->push_back(std::move(check));
1814 strprintf(
"non-mandatory-script-verify-flag (%s)",
1818 scriptError =
check2.GetScriptError();
1830 strprintf(
"mandatory-script-verify-flag-failed (%s)",
1859 if (
view.HaveCoin(out)) {
1864 if (
undo.GetHeight() == 0) {
1902 error(
"DisconnectBlock(): failure reading undo data");
1914 if (
blockUndo.vtxundo.size() + 1 != block.
vtx.size()) {
1915 error(
"DisconnectBlock(): block and undo data inconsistent");
1920 for (
size_t i = 1; i < block.
vtx.size(); i++) {
1923 if (
txundo.vprevout.size() != tx.
vin.size()) {
1924 error(
"DisconnectBlock(): transaction and undo data inconsistent");
1928 for (
size_t j = 0;
j < tx.
vin.size();
j++) {
1941 for (
const auto &
ptx : block.
vtx) {
1948 for (
size_t o = 0;
o < tx.
vout.size();
o++) {
1949 if (tx.
vout[
o].scriptPubKey.IsUnspendable()) {
1955 bool is_spent =
view.SpendCoin(out, &coin);
2099 return AbortNode(state,
"Corrupt block found indicating potential "
2100 "hardware failure; shutting down");
2109 assert(hashPrevBlock ==
view.GetBestBlock());
2132 BlockMap::const_iterator it{
2135 if (it->second.GetAncestor(pindex->
nHeight) == pindex &&
2187 uint256S(
"0x00000000000a4d0a398161ffc163c503763"
2188 "b1f4360639393e0e4c8e300e0caec")) ||
2191 uint256S(
"0x00000000000743f190a18c5577a3c2d2a1f"
2192 "610ae9601ac046a38084ccb7cd721")));
2267 for (
const auto &tx : block.
vtx) {
2268 for (
size_t o = 0;
o < tx->
vout.size();
o++) {
2270 LogPrintf(
"ERROR: ConnectBlock(): tried to overwrite "
2317 for (
const auto &
ptx : block.
vtx) {
2320 }
catch (
const std::logic_error &
e) {
2329 LogPrintf(
"ERROR: ConnectBlock(): tried to overwrite transaction\n");
2338 for (
const auto &
ptx : block.
vtx) {
2355 return error(
"%s: Consensus::CheckTxInputs: %s, %s",
__func__,
2362 LogPrintf(
"ERROR: %s: accumulated fee in the block out of range.\n",
2365 "bad-txns-accumulated-fee-outofrange");
2377 for (
size_t j = 0;
j < tx.
vin.size();
j++) {
2382 LogPrintf(
"ERROR: %s: contains a non-BIP68-final transaction\n",
2385 "bad-txns-nonfinal");
2400 std::vector<CScriptCheck>
vChecks;
2413 "ConnectBlock(): CheckInputScripts on %s failed with %s",
2431 " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) "
2432 "[%.2fs (%.2fms/blk)]\n",
2441 LogPrintf(
"ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs "
2454 "blk-bad-inputs",
"parallel script check failed");
2461 " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n",
2558 std::numeric_limits<int>::max()) {
2596 "prunedblockfiles",
true);
2631 return AbortNode(state,
"Disk space is too low!",
2632 _(
"Disk space is too low!"));
2651 state,
"Failed to write to block index database");
2668 strprintf(
"write coins cache to disk (%d coins, %.2fkB)",
2679 48 * 2 * 2 *
CoinsTip().GetCacheSize())) {
2680 return AbortNode(state,
"Disk space is too low!",
2681 _(
"Disk space is too low!"));
2687 return AbortNode(state,
"Failed to write to coin database");
2703 }
catch (
const std::runtime_error &
e) {
2704 return AbortNode(state, std::string(
"System error while flushing: ") +
2730 const std::string &
prefix)
2733 LogPrintf(
"%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%ld "
2734 "date='%s' progress=%f cache=%.1fMiB(%utxo)\n",
2736 tip->nVersion,
log(
tip->nChainWork.getdouble()) /
log(2.0),
2737 tip->GetChainTxCount(),
2740 coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2758 "[background validation] ");
2801 std::shared_ptr<CBlock>
pblock = std::make_shared<CBlock>();
2804 return error(
"DisconnectTip(): Failed to read block");
2814 return error(
"DisconnectTip(): DisconnectBlock %s failed",
2853 "Disconnecting mempool due to rewind of upgrade block\n");
2887 const std::shared_ptr<const CBlock> &
pblock,
2902 std::shared_ptr<CBlock>
pblockNew = std::make_shared<CBlock>();
2904 return AbortNode(state,
"Failed to read block");
2981 std::make_unique<StakingRewardsPolicy>(
2987 std::make_unique<PreConsensusPolicy>(
2994 [&](
const auto &
policy) {
2995 bool ret = (*policy)(blockPolicyState);
2998 "Park block because it "
2999 "violated a block policy: %s\n",
3000 blockPolicyState.ToString());
3014 " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3035 " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3051 "Disconnecting mempool due to acceptance of upgrade block\n");
3064 " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3074 if (
this != &m_chainman.ActiveChainstate()) {
3078 m_chainman.MaybeCompleteSnapshotValidation();
3097 std::set<CBlockIndex *, CBlockIndexWorkComparator>::reverse_iterator
3111 LogPrintf(
"Park block %s because it forks prior to the "
3112 "avalanche finalized chaintip.\n",
3168 LogPrintf(
"Unpark chain up to block %s as it has "
3169 "accumulated enough PoW.\n",
3206 LogPrintf(
"Considered switching to better tip %s but that chain "
3207 "contains a%s%s%s block.\n",
3308 "Failed to disconnect block; see debug.log for details");
3339 : std::shared_ptr<const CBlock>(),
3387 "Updating mempool due to reorganization or "
3388 "rules upgrade/downgrade\n");
3396 if (fInvalidFound) {
3433 chainstate.m_chainman.GetNotifications().headerTip(
3449 std::shared_ptr<const CBlock>
pblock,
3471 LogPrintf(
"m_disabled is set - this chainstate should not be in "
3472 "operation. Please report this as a bug. %s\n",
3681template <
typename Func>
struct Defer {
3698 int disconnected = 0;
3718 for (
auto &entry :
m_blockman.m_block_index) {
3842 .withParkedParent());
3936template <
typename F>
3959template <
typename F,
typename C,
typename AC>
3995 return status.withClearedFailureFlags();
3998 return status.withClearedFailureFlags();
4001 return status.withFailedParent(false);
4011 return status.withClearedParkedFlags();
4014 return fClearChildren ? status.withClearedParkedFlags()
4015 : status.withParkedParent(false);
4018 return status.withParkedParent(false);
4038 "The block to mark finalized by avalanche is not on the "
4039 "active chain: %s\n",
4091 std::deque<CBlockIndex *> queue;
4096 while (!queue.empty()) {
4114 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
4115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
4118 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it =
4120 queue.push_back(it->second);
4148 "high-hash",
"proof of work failed");
4174 "bad-txnmrklroot",
"hashMerkleRoot mismatch");
4182 "bad-txns-duplicate",
"duplicate transaction");
4191 if (block.
vtx.empty()) {
4193 "bad-cb-missing",
"first tx is not coinbase");
4202 "bad-blk-length",
"size limits failed");
4208 "bad-blk-length",
"size limits failed");
4216 strprintf(
"Coinbase check failed (txid %s) %s",
4217 block.
vtx[0]->GetId().ToString(),
4223 for (
size_t i = 1; i < block.
vtx.size(); i++) {
4224 auto *tx = block.
vtx[i].get();
4229 strprintf(
"Transaction check failed (txid %s) %s",
4245 [&](
const auto &header) {
4246 return CheckProofOfWork(
4247 header.GetHash(), header.nBits, consensusParams);
4286 "bad-diffbits",
"incorrect proof of work");
4290 if (chainman.m_options.checkpoints_enabled) {
4298 "ERROR: %s: rejected by checkpoint lock-in at %d\n",
4301 "checkpoint mismatch");
4312 "ERROR: %s: forked chain older than last checkpoint "
4316 "bad-fork-prior-to-checkpoint");
4323 "time-too-old",
"block's timestamp is too early");
4327 if (block.
Time() > now + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4330 "block timestamp too far in the future");
4415 for (
const auto &
ptx : block.
vtx) {
4428 strprintf(
"Transaction order is invalid (%s < %s)",
4430 prevTx->GetId().ToString()));
4451 if (block.
vtx[0]->vin[0].scriptSig.size() <
expect.size() ||
4453 block.
vtx[0]->vin[0].scriptSig.begin())) {
4456 "block height mismatch in coinbase");
4487 if (pindex->nStatus.isInvalid()) {
4500 "%s: Consensus::CheckBlockHeader: %s, %s\n",
__func__,
4506 BlockMap::iterator
mi{
4510 "header %s has prev block not found: %s\n",
4513 "prev-blk-not-found");
4520 "header %s has prev block invalid: %s\n", hash.
ToString(),
4530 "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n",
4571 "header %s has prev block invalid: %s\n",
4582 "%s: not adding new block header %s, missing anti-dos "
4583 "proof-of-work validation\n",
4586 "too-little-chainwork");
4602 const auto msg =
strprintf(
"Saw new header hash=%s height=%d",
4648 LogPrintf(
"Synchronizing blockheaders, height: %d (~%.2f%%)\n",