ralph

Outcomes

What happened to findings after review.

Addressed after review

Best-effort automated assessment of whether later PR updates addressed findings from previous reviews. This is not a causal claim or human validation.

73 assessed findings from 73 published findings across 10 source reviews.

StatusFindings
addressed10
partially_addressed8
still_present22
unclear33

Assessment jobs: 10

Assessment usage: 10 request records; 611,826 input tokens; 8,362 output tokens.

Finding assessments

PRFindingOutcomeEvidence
fork#45User-visible validation changes lack release notessrc/init.cppunclear
Assessment

The supplied diff covers help, documentation, and implementation changes but contains no release-note fragment or evidence identifying where combined release notes will land. The supplied excerpts are insufficient to determine whether such notes were added elsewhere.

path_diff: src/init.cpp; new_source: src/init.cpp

[
  {
    "evidence_id": "1d68156d6fd94d18a7970196702d6363",
    "finding_id": "finding:9",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/init.cpp",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/init.cpp b/src/init.cpp\nindex a657568572..941ca734a5 100644\n--- a/src/init.cpp\n+++ b/src/init.cpp\n@@ -541,7 +541,7 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)\n     argsman.AddArg(\"-par=<n>\", strprintf(\"Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d). Blocks validated in parallel during initial block download have their scripts verified on the connect pool threads (-prevoutfetchthreads), which this option does not bound.\",\n         MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-blockcache=<n>\", strprintf(\"Keep accepted blocks in memory until they are connected, up to <n> MiB, so that a block that arrived before its parent is connected from the object received rather than read from disk and deserialized again (0 disables, default: %d, or the size of the coins cache where that is smaller, at least 32).\", DEFAULT_BLOCK_CACHE_BYTES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n-    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which process the blocks received from peers and validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched, received blocks are processed by the message handler and the blocks of a -connectwindow are validated one after another; with one thread received blocks are processed by the message handler as well, so that a thread stays free for connecting; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n+    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched and the blocks of a -connectwindow are validated one after another; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-connectwindow=<n>\", strprintf(\"Set how many blocks are validated at the same time during initial block download, each on a connect pool thread, with the blocks confirmed in order (0 = twice as many as there are connect pool threads, 1 or -noconnectwindow = one at a time, up to %d, default: 0; the blocks in flight are further bounded, by an estimate of what they hold, to an eighth of the coins cache in memory, at least 32 MiB)\", MAX_CONNECT_WINDOW), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n     argsman.AddArg(\"-persistmempool\", strprintf(\"Whether to save the mempool on shutdown and load on restart (default: %u)\", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-pid=<file>\", strprintf(\"Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)\", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 572,
    "evidence_id": "bfc2cf0ee50d4c81982b1a65770ec72f",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 514,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/init.cpp",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "#endif\n    argsman.AddArg(\"-assumevalid=<hex>\", strprintf(\"If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet3: %s, testnet4: %s, signet: %s)\", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnet4ChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksdir=<dir>\", \"Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksxor\",\n                   strprintf(\"Whether an XOR-key applies to blocksdir *.dat files. \"\n                             \"The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is \"\n                             \"set, and random for a freshly initialized blocksdir. \"\n                             \"(default: %u)\",\n                             kernel::DEFAULT_XOR_BLOCKSDIR),\n                   ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-fastprune\", \"Use smaller block files and lower minimum prune height for testing purposes\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n#if HAVE_SYSTEM\n    argsman.AddArg(\"-blocknotify=<cmd>\", \"Execute command when the best block changes (%s in cmd is replaced by block hash). Not run for blocks connected during initial block download or reindexing.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#endif\n    argsman.AddArg(\"-blockreconstructionextratxn=<n>\", strprintf(\"Extra transactions to keep in memory for compact block reconstructions (default: %u)\", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksonly\", strprintf(\"Whether to reject transactions from network peers. Disables automatic broadcast and rebroadcast of transactions, unless the source peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)\", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-coinstatsindex\", strprintf(\"Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)\", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-conf=<file>\", strprintf(\"Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)\", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-datadir=<dir>\", \"Specify data directory\", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-dbbatchsize\", strprintf(\"Maximum database write batch size in bytes (default: %u)\", DEFAULT_DB_CACHE_BATCH), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-dbcache=<n>\", strprintf(\"Maximum database cache size <n> MiB (minimum %d, default: %d). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).\", MIN_DBCACHE_BYTES / 1_MiB, node::GetDefaultDBCache() / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-includeconf=<file>\", \"Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-allowignoredconf\", strprintf(\"For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.\", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-loadblock=<file>\", \"Imports blocks from an external file on startup. Obfuscated blocks are not supported.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-maxmempool=<n>\", strprintf(\"Keep the transaction memory pool below <n> megabytes (default: %u)\", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-mempoolexpiry=<n>\", strprintf(\"Do not keep transactions in the mempool longer than <n> hours (default: %u)\", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-minimumchainwork=<hex>\", strprintf(\"Minimum work assumed to exist on a valid chain in hex (default: %s, testnet3: %s, testnet4: %s, signet: %s)\", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnet4ChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-par=<n>\", strprintf(\"Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d). Blocks validated in parallel during initial block download have their scripts verified on the connect pool threads (-prevoutfetchthreads), which this option does not bound.\",\n        MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blockcache=<n>\", strprintf(\"Keep accepted blocks in memory until they are connected, up to <n> MiB, so that a block that arrived before its parent is connected from the object received rather than read from disk and deserialized again (0 disables, default: %d, or the size of the coins cache where that is smaller, at least 32).\", DEFAULT_BLOCK_CACHE_BYTES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched and the blocks of a -connectwindow are validated one after another; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-connectwindow=<n>\", strprintf(\"Set how many blocks are validated at the same time during initial block download, each on a connect pool thread, with the blocks confirmed in order (0 = twice as many as there are connect pool threads, 1 or -noconnectwindow = one at a time, up to %d, default: 0; the blocks in flight are further bounded, by an estimate of what they hold, to an eighth of the coins cache in memory, at least 32 MiB)\", MAX_CONNECT_WINDOW), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n    argsman.AddArg(\"-persistmempool\", strprintf(\"Whether to save the mempool on shutdown and load on restart (default: %u)\", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-pid=<file>\", strprintf(\"Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)\", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-prune=<n>\", strprintf(\"Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex. \"\n            \"Warning: Reverting this setting requires re-downloading the entire blockchain. Wallets and indexes should be loaded at startup and kept active while pruning is enabled so they stay synchronized before old block data is deleted; wallets or indexes that fall behind pruned data may require a reindex. \"\n            \"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)\", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-reindex\", \"If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-reindex-chainstate\", \"If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-settings=<file>\", strprintf(\"Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)\", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#if HAVE_SYSTEM\n    argsman.AddArg(\"-startupnotify=<cmd>\", \"Execute command on startup.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-shutdownnotify=<cmd>\", \"Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#endif\n    argsman.AddArg(\"-txindex\", strprintf(\"Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)\", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-txospenderindex\", strprintf(\"Maintain a transaction output spender index, used by the gettxspendingprevout rpc call (default: %u)\", DEFAULT_TXOSPENDERINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blockfilterindex=<type>\",\n                 strprintf(\"Maintain an index of compact filters by block (default: %s, values: %s).\", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +\n                 \" If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.\",\n                 ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n\n    argsman.AddArg(\"-addnode=<ip>\", strprintf(\"Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.\", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);\n    argsman.AddArg(\"-asmap=<file>\", strprintf(\"Specify asn mapping used for bucketing of the peers. Relative paths will be prefixed by the net-specific datadir location.%s\",\n                #ifdef ENABLE_EMBEDDED_ASMAP\n                    \" If a bool arg is given (-asmap or -asmap=1), the embedded mapping data in the binary will be used.\"\n                #else\n                    \"\"\n                #endif\n                ), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45IBD announcement tests do not ensure a block signal is pendingsrc/test/tip_snapshot_tests.cppaddressed
Assessment

The tests now enqueue a held effect before processing the block, keeping the undo write and `BlockConnected` behind it. They release the effect while holding `cs_main` as transaction submission or mempool loading begins, and assert the expected `{'b','t'}` ordering. This directly controls the pending-signal boundary identified in the finding.

path_diff: src/test/tip_snapshot_tests.cpp; new_source: src/test/tip_snapshot_tests.cpp

[
  {
    "evidence_id": "aeee0ea53b224438ad3b83e8f2af24b4",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/test/tip_snapshot_tests.cpp",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/test/tip_snapshot_tests.cpp b/src/test/tip_snapshot_tests.cpp\nindex 18b186d2ad..51c416617a 100644\n--- a/src/test/tip_snapshot_tests.cpp\n+++ b/src/test/tip_snapshot_tests.cpp\n@@ -4,6 +4,7 @@\n \n #include <chain.h>\n #include <consensus/validation.h>\n+#include <kernel/effects.h>\n #include <kernel/mempool_removal_reason.h>\n #include <node/block_facts.h>\n #include <node/mempool_persist.h>\n@@ -19,6 +20,8 @@\n \n #include <boost/test/unit_test.hpp>\n \n+#include <chrono>\n+#include <future>\n #include <vector>\n \n BOOST_FIXTURE_TEST_SUITE(tip_snapshot_tests, TestChain100Setup)\n@@ -155,6 +158,28 @@ BOOST_AUTO_TEST_CASE(tip_is_published_at_the_end_of_the_hold)\n     signals.UnregisterValidationInterface(&inside);\n }\n \n+// What the published value is for: a reader on another thread gets the tip while cs_main is held elsewhere and\n+// the tip is not moving, without waiting for the lock.\n+BOOST_AUTO_TEST_CASE(published_tip_is_read_without_cs_main)\n+{\n+    ChainstateManager& chainman{*Assert(m_node.chainman)};\n+    BOOST_REQUIRE(!chainman.TipUnpublished());\n+    const node::TipSnapshot before{chainman.PublishedTip()};\n+    std::future<node::TipSnapshot> read;\n+    std::future_status status;\n+    {\n+        LOCK(::cs_main);\n+        read = std::async(std::launch::async, [&chainman] { return chainman.PublishedTip(); });\n+        // Generous: it can only expire if the read waits for the lock this thread holds, which is released\n+        // before the future is waited for again, so a failure cannot hang.\n+        status = read.wait_for(std::chrono::seconds{60});\n+    }\n+    BOOST_REQUIRE(status == std::future_status::ready);\n+    const node::TipSnapshot seen{read.get()};\n+    BOOST_CHECK(seen.hash == before.hash);\n+    BOOST_CHECK_EQUAL(seen.sequence, before.sequence);\n+}\n+\n BOOST_AUTO_TEST_CASE(block_facts_are_one_copy)\n {\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n@@ -186,31 +211,62 @@ struct AnnouncementOrder final : public CValidationInterface {\n     }\n };\n \n+//! Holds the effects executor's queue behind an effect of its own until Release(), so that what is queued after\n+//! it, a block's undo write and with it the block's BlockConnected, waits. Released on destruction as well.\n+class HeldEffects\n+{\n+    std::promise<void> m_release;\n+\n+public:\n+    explicit HeldEffects(kernel::EffectsExecutor& effects)\n+    {\n+        effects.Enqueue([released = m_release.get_future().share()] { released.wait(); return true; }, [](bool) {});\n+    }\n+    ~HeldEffects() { Release(); }\n+    void Release()\n+    {\n+        try {\n+            m_release.set_value();\n+        } catch (const std::future_error&) {\n+        }\n+    }\n+};\n+\n //! In initial block download a block's BlockConnected waits for the block's undo write. A transaction\n-//! accepted after the block is still announced after it.\n+//! accepted after the block is still announced after it. The block's signal is held back until the\n+//! transaction is submitted, under cs_main, so that the executor's hook cannot hand it over first: only the\n+//! submission's own settling (SubmitToMemoryPool()) puts it ahead of the transaction.\n BOOST_AUTO_TEST_CASE(a_transaction_is_announced_after_the_block_in_ibd)\n {\n     auto& chainman{static_cast<TestChainstateManager&>(*Assert(m_node.chainman))};\n     ValidationSignals& signals{*Assert(m_node.validation_signals)};\n \n-    // A block that is two days old when it arrives leaves the node in initial block download.\n+    // A block that is two days old when it arrives leaves the node in initial block download. The chainstate\n+    // is written first, so that the block's connection makes no periodic write, which would wait for the\n+    // held queue.\n     const CBlock block{CreateBlock({}, CScript{} << OP_TRUE)};\n     m_clock += std::chrono::hours{48};\n     chainman.ResetIbd();\n+    chainman.ActiveChainstate().ForceFlushStateToDisk();\n     signals.SyncWithValidationInterfaceQueue();\n+    const CMutableTransaction tx{CreateValidMempoolTransaction(m_coinbase_txns[0], /*input_vout=*/0, /*input_height=*/1, coinbaseKey,\n+                                                               CScript{} << OP_0 << std::vector<uint8_t>(20, 1), CAmount{1 * COIN}, /*submit=*/false)};\n \n     AnnouncementOrder order;\n     signals.RegisterValidationInterface(&order);\n \n+    HeldEffects held{chainman.m_blockman.m_effects};\n     bool new_block{false};\n     BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(block), /*force_processing=*/true, /*min_pow_checked=*/true, &new_block));\n     BOOST_REQUIRE(new_block);\n     BOOST_REQUIRE(chainman.IsInitialBlockDownload());\n     BOOST_REQUIRE(WITH_LOCK(::cs_main, return chainman.ActiveTip()->GetBlockHash()) == block.GetHash());\n \n-    const CMutableTransaction tx{CreateValidMempoolTransaction(m_coinbase_txns[0], /*input_vout=*/0, /*input_height=*/1, coinbaseKey,\n-                                                               CScript{} << OP_0 << std::vector<uint8_t>(20, 1), CAmount{1 * COIN}, /*submit=*/false)};\n-    const MempoolAcceptResult result{WITH_LOCK(::cs_main, return chainman.ProcessTransaction(MakeTransactionRef(tx)))};\n+    const MempoolAcceptResult result{[&] {\n+        LOCK(::cs_main);\n+        held.Release();\n+        return chainman.ProcessTransaction(MakeTransactionRef(tx));\n+    }()};\n     BOOST_REQUIRE(result.m_result_type == MempoolAcceptResult::ResultType::VALID);\n     signals.SyncWithValidationInterfaceQueue();\n     signals.UnregisterValidationInterface(&order);\n@@ -220,12 +276,8 @@ BOOST_AUTO_TEST_CASE(a_transaction_is_announced_after_the_block_in_ibd)\n }\n \n //! The same for a transaction the node loads from its mempool file: in initial block download\n-//! LoadMempool() hands the signals of the blocks connected so far over before each transaction.\n-//!\n-//! Nothing here can see whether the block's signal still waited when the file was loaded, and a round in\n-//! which it had left already passes whatever LoadMempool() does. So the round is run several times, each\n-//! with a block of its own: a LoadMempool() that does not settle the signals has to be missed by all of\n-//! them.\n+//! LoadMempool() hands the signals of the blocks connected so far over before each transaction. As above,\n+//! the block's signal is held back until the file is loaded, under cs_main.\n BOOST_AUTO_TEST_CASE(a_loaded_transaction_is_announced_after_the_block_in_ibd)\n {\n     auto& chainman{static_cast<TestChainstateManager&>(*Assert(m_node.chainman))};\n@@ -244,32 +296,34 @@ BOOST_AUTO_TEST_CASE(a_loaded_transaction_is_announced_after_the_block_in_ibd)\n     }};\n     remove_transaction();\n \n-    for (int round{0}; round < 3; ++round) {\n-        // A block that is two days old when it arrives leaves the node in initial block download.\n-        const CBlock block{CreateBlock({}, CScript{} << OP_TRUE)};\n-        m_clock += std::chrono::hours{48};\n-        chainman.ResetIbd();\n-        signals.SyncWithValidationInterfaceQueue();\n+    // A block that is two days old when it arrives leaves the node in initial block download; the chainstate is\n+    // written first, as above.\n+    const CBlock block{CreateBlock({}, CScript{} << OP_TRUE)};\n+    m_clock += std::chrono::hours{48};\n+    chainman.ResetIbd();\n+    chainman.ActiveChainstate().ForceFlushStateToDisk();\n+    signals.SyncWithValidationInterfaceQueue();\n \n-        AnnouncementOrder order;\n-        signals.RegisterValidationInterface(&order);\n+    AnnouncementOrder order;\n+    signals.RegisterValidationInterface(&order);\n \n-        bool new_block{false};\n-        BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(block), /*force_processing=*/true, /*min_pow_checked=*/true, &new_block));\n-        BOOST_REQUIRE(new_block);\n-        BOOST_REQUIRE(chainman.IsInitialBlockDownload());\n+    HeldEffects held{chainman.m_blockman.m_effects};\n+    bool new_block{false};\n+    BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(block), /*force_processing=*/true, /*min_pow_checked=*/true, &new_block));\n+    BOOST_REQUIRE(new_block);\n+    BOOST_REQUIRE(chainman.IsInitialBlockDownload());\n \n+    {\n+        LOCK(::cs_main);\n+        held.Release();\n         BOOST_REQUIRE(node::LoadMempool(pool, path, chainman.ActiveChainstate(), {}));\n-        BOOST_REQUIRE_EQUAL(WITH_LOCK(pool.cs, return pool.size()), 1U);\n-        signals.SyncWithValidationInterfaceQueue();\n-        signals.UnregisterValidationInterface(&order);\n-\n-        const std::vector<char> expected{'b', 't'};\n-        BOOST_CHECK_EQUAL_COLLECTIONS(order.m_order.begin(), order.m_order.end(), expected.begin(), expected.end());\n-\n-        // The next round loads the file again.\n-        remove_transaction();\n     }\n+    BOOST_REQUIRE_EQUAL(WITH_LOCK(pool.cs, return pool.size()), 1U);\n+    signals.SyncWithValidationInterfaceQueue();\n+    signals.UnregisterValidationInterface(&order);\n+\n+    const std::vector<char> expected{'b', 't'};\n+    BOOST_CHECK_EQUAL_COLLECTIONS(order.m_order.begin(), order.m_order.end(), expected.begin(), expected.end());\n }\n \n BOOST_AUTO_TEST_SUITE_END()\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 329,
    "evidence_id": "1686ca23cdee477784c3ca6540f1d0ab",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 195,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/test/tip_snapshot_tests.cpp",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "    BOOST_CHECK_EQUAL(facts->status, tip->nStatus);\n    BOOST_CHECK_EQUAL(facts->tx_count, tip->nTx);\n    BOOST_CHECK(facts->HaveData());\n    BOOST_CHECK(facts->data_pos == tip->GetBlockPos());\n}\n\n//! Records the order of a block's and a transaction's announcement.\nstruct AnnouncementOrder final : public CValidationInterface {\n    std::vector<char> m_order;\n    void BlockConnected(const kernel::ChainstateRole&, const std::shared_ptr<const CBlock>&, const CBlockIndex*) override\n    {\n        m_order.push_back('b');\n    }\n    void TransactionAddedToMempool(const NewMempoolTransactionInfo&, uint64_t) override\n    {\n        m_order.push_back('t');\n    }\n};\n\n//! Holds the effects executor's queue behind an effect of its own until Release(), so that what is queued after\n//! it, a block's undo write and with it the block's BlockConnected, waits. Released on destruction as well.\nclass HeldEffects\n{\n    std::promise<void> m_release;\n\npublic:\n    explicit HeldEffects(kernel::EffectsExecutor& effects)\n    {\n        effects.Enqueue([released = m_release.get_future().share()] { released.wait(); return true; }, [](bool) {});\n    }\n    ~HeldEffects() { Release(); }\n    void Release()\n    {\n        try {\n            m_release.set_value();\n        } catch (const std::future_error&) {\n        }\n    }\n};\n\n//! In initial block download a block's BlockConnected waits for the block's undo write. A transaction\n//! accepted after the block is still announced after it. The block's signal is held back until the\n//! transaction is submitted, under cs_main, so that the executor's hook cannot hand it over first: only the\n//! submission's own settling (SubmitToMemoryPool()) puts it ahead of the transaction.\nBOOST_AUTO_TEST_CASE(a_transaction_is_announced_after_the_block_in_ibd)\n{\n    auto& chainman{static_cast<TestChainstateManager&>(*Assert(m_node.chainman))};\n    ValidationSignals& signals{*Assert(m_node.validation_signals)};\n\n    // A block that is two days old when it arrives leaves the node in initial block download. The chainstate\n    // is written first, so that the block's connection makes no periodic write, which would wait for the\n    // held queue.\n    const CBlock block{CreateBlock({}, CScript{} << OP_TRUE)};\n    m_clock += std::chrono::hours{48};\n    chainman.ResetIbd();\n    chainman.ActiveChainstate().ForceFlushStateToDisk();\n    signals.SyncWithValidationInterfaceQueue();\n    const CMutableTransaction tx{CreateValidMempoolTransaction(m_coinbase_txns[0], /*input_vout=*/0, /*input_height=*/1, coinbaseKey,\n                                                               CScript{} << OP_0 << std::vector<uint8_t>(20, 1), CAmount{1 * COIN}, /*submit=*/false)};\n\n    AnnouncementOrder order;\n    signals.RegisterValidationInterface(&order);\n\n    HeldEffects held{chainman.m_blockman.m_effects};\n    bool new_block{false};\n    BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(block), /*force_processing=*/true, /*min_pow_checked=*/true, &new_block));\n    BOOST_REQUIRE(new_block);\n    BOOST_REQUIRE(chainman.IsInitialBlockDownload());\n    BOOST_REQUIRE(WITH_LOCK(::cs_main, return chainman.ActiveTip()->GetBlockHash()) == block.GetHash());\n\n    const MempoolAcceptResult result{[&] {\n        LOCK(::cs_main);\n        held.Release();\n        return chainman.ProcessTransaction(MakeTransactionRef(tx));\n    }()};\n    BOOST_REQUIRE(result.m_result_type == MempoolAcceptResult::ResultType::VALID);\n    signals.SyncWithValidationInterfaceQueue();\n    signals.UnregisterValidationInterface(&order);\n\n    const std::vector<char> expected{'b', 't'};\n    BOOST_CHECK_EQUAL_COLLECTIONS(order.m_order.begin(), order.m_order.end(), expected.begin(), expected.end());\n}\n\n//! The same for a transaction the node loads from its mempool file: in initial block download\n//! LoadMempool() hands the signals of the blocks connected so far over before each transaction. As above,\n//! the block's signal is held back until the file is loaded, under cs_main.\nBOOST_AUTO_TEST_CASE(a_loaded_transaction_is_announced_after_the_block_in_ibd)\n{\n    auto& chainman{static_cast<TestChainstateManager&>(*Assert(m_node.chainman))};\n    ValidationSignals& signals{*Assert(m_node.validation_signals)};\n    CTxMemPool& pool{*Assert(m_node.mempool)};\n\n    // A mempool file with one transaction, which the pool then no longer holds.\n    const CMutableTransaction tx{CreateValidMempoolTransaction(m_coinbase_txns[0], /*input_vout=*/0, /*input_height=*/1, coinbaseKey,\n                                                               CScript{} << OP_0 << std::vector<uint8_t>(20, 1), CAmount{1 * COIN}, /*submit=*/true)};\n    const fs::path path{m_args.GetDataDirNet() / \"mempool_one_transaction.dat\"};\n    BOOST_REQUIRE(node::DumpMempool(pool, path));\n    const auto remove_transaction{[&] {\n        LOCK2(::cs_main, pool.cs);\n        pool.removeRecursive(CTransaction{tx}, MemPoolRemovalReason::REPLACED);\n        BOOST_REQUIRE_EQUAL(pool.size(), 0U);\n    }};\n    remove_transaction();\n\n    // A block that is two days old when it arrives leaves the node in initial block download; the chainstate is\n    // written first, as above.\n    const CBlock block{CreateBlock({}, CScript{} << OP_TRUE)};\n    m_clock += std::chrono::hours{48};\n    chainman.ResetIbd();\n    chainman.ActiveChainstate().ForceFlushStateToDisk();\n    signals.SyncWithValidationInterfaceQueue();\n\n    AnnouncementOrder order;\n    signals.RegisterValidationInterface(&order);\n\n    HeldEffects held{chainman.m_blockman.m_effects};\n    bool new_block{false};\n    BOOST_REQUIRE(chainman.ProcessNewBlock(std::make_shared<const CBlock>(block), /*force_processing=*/true, /*min_pow_checked=*/true, &new_block));\n    BOOST_REQUIRE(new_block);\n    BOOST_REQUIRE(chainman.IsInitialBlockDownload());\n\n    {\n        LOCK(::cs_main);\n        held.Release();\n        BOOST_REQUIRE(node::LoadMempool(pool, path, chainman.ActiveChainstate(), {}));\n    }\n    BOOST_REQUIRE_EQUAL(WITH_LOCK(pool.cs, return pool.size()), 1U);\n    signals.SyncWithValidationInterfaceQueue();\n    signals.UnregisterValidationInterface(&order);\n\n    const std::vector<char> expected{'b', 't'};\n    BOOST_CHECK_EQUAL_COLLECTIONS(order.m_order.begin(), order.m_order.end(), expected.begin(), expected.end());\n}\n\nBOOST_AUTO_TEST_SUITE_END()",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45Receive-path documentation describes code absent from this revisionsrc/validation.haddressed
Assessment

The new O1 description removes peer receive-task waits and limits the stated wait API to `WaitForPendingBlocks()`. The `-prevoutfetchthreads` help and pool documentation also describe window validation and tip prefetch rather than peer receive processing.

path_diff: src/validation.h; new_source: src/validation.h

[
  {
    "evidence_id": "e18fb3aa5bce48c9ad94b6c28371c7a9",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/validation.h",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/validation.h b/src/validation.h\nindex 3bf0ad0828..706b6c9812 100644\n--- a/src/validation.h\n+++ b/src/validation.h\n@@ -539,17 +539,9 @@ struct DeploymentFlags {\n  *      yet activated\", and calling ActivateBestChain() closes it.\n  *      ProcessNewBlock() opens it; ProcessGetBlockData() and the GETBLOCKS\n  *      handler in net_processing close it before they answer.\n- *      In flight: a block handed to the connector is in that state until\n- *      the connector has activated it. Wait: WaitForPendingBlocks(), and\n- *      before it the wait for the receive tasks left from initial block\n- *      download (PeerManagerImpl::WaitForPendingBlocks()), made by the\n- *      handlers of the messages that are judged against the tip\n- *      (GETHEADERS, TX, CMPCTBLOCK, BLOCKTXN and BLOCK), and before an\n- *      orphan is considered again. The wait is not made in initial\n- *      block download, where no transaction is accepted and blocks are\n- *      stored beside each other on purpose. Outside it the two handlers\n- *      activate as before; in it the connector does and they answer from\n- *      what is connected.\n+ *      In flight: a block handed to the connector (ProcessNewBlock() with\n+ *      activate_async) is in that state until the connector has activated\n+ *      it. Wait: WaitForPendingBlocks().\n  *  O2  When AcceptBlock() returns for a new block, its data, its position\n  *      and BLOCK_VALID_TRANSACTIONS are recorded together (asserted there),\n  *      in one hold of cs_main after the write (FinishAcceptBlock()). Until\n@@ -601,9 +593,12 @@ struct DeploymentFlags {\n  *  O9  Publication is strictly sequential: a block is published on top of\n  *      the tip (asserted in PublishConnectTip()), one ActivateBestChain()\n  *      at a time (m_chainstate_mutex).\n- *  O10 nSequenceId is assigned under cs_main in the order in which blocks\n- *      are recorded as stored (ReceivedBlockTransactions()), which may\n- *      differ from the order of arrival.\n+ *  O10 nSequenceId is assigned under cs_main when a block becomes linked\n+ *      (ReceivedBlockTransactions()): its data and every ancestor's\n+ *      transaction count are known. A block stored before its parent waits,\n+ *      and is numbered with the descendants the link reaches, parent first;\n+ *      so the order may differ from the order of arrival. Blocks loaded at\n+ *      startup and preciousblock assign it otherwise.\n  *  O11 A file position copied under cs_main stays readable afterwards, or\n  *      the reader handles the failed read (node::BlockFacts). A connected\n  *      block's undo position is null until its queued write has run. Wait:\n@@ -652,10 +647,9 @@ struct DeploymentFlags {\n  * ChainstateManager. The contextual header and block checks also take the\n  * previous block index entry, for the difficulty calculation.\n  *\n- * Every member is a copy, with two exceptions: params refers to the chain's\n- * constant parameters, and median_time_past_at is a function, because which\n- * ancestors a block's relative lock times refer to is known only once its\n- * inputs are looked up.\n+ * Every member is a copy, with two kinds of exception: params refers to the\n+ * chain's constant parameters, and median_time_past_at, help_point and\n+ * implicit_creates are functions.\n  */\n struct BlockValidationContext {\n     const Consensus::Params& params;\n@@ -685,13 +679,12 @@ struct BlockValidationContext {\n      * may be called without cs_main for as long as the block index lives.\n      */\n     std::function<int64_t(int)> median_time_past_at;\n-    /**\n-     * Whether a transaction whose inputs are not all in the view is deferred rather than a consensus\n-     * failure. True only while blocks below this one are still being applied (the window is incomplete):\n-     * the transaction's outputs are created, its other checks wait for FinishDeferredTransactions() once\n-     * every lower block is in. With a complete window a missing input is \"bad-txns-inputs-missingorspent\".\n-     */\n-    bool defer_missing_inputs{false};\n+    //! Called every 64 transactions of the block, where a window worker helps a commit that runs.\n+    std::function<void()> help_point{};\n+    //! Set for a window block whose outputs are not added to the view: a later transaction of the block\n+    //! reads them where the blocks above do, in the window's outputs. Called with each transaction's position\n+    //! before the transaction is checked.\n+    std::function<void(uint32_t)> implicit_creates{};\n     //! Where the block is on disk, as the index recorded it when the block was planned, for a worker that\n     //! reads the block itself. Null where the block is not read from there.\n     FlatFilePos block_pos{};\n@@ -703,6 +696,8 @@ struct BlockValidationContext {\n /** Outputs of the pure ConnectBlock() besides the mutated coins view.\n  *  ConnectBlock() resets the object it is given before it fills it. */\n struct ConnectBlockResult {\n+    //! `undo` once FinishConnectBlock() queued its write, which moved it here.\n+    std::shared_ptr<const CBlockUndo> queued_undo;\n     //! Undo data for the connected block; of no meaning when connection failed.\n     CBlockUndo undo;\n     //! The serialized size of `undo`, when it was measured ahead of FinishConnectBlock() (a window block's\n@@ -712,12 +707,6 @@ struct ConnectBlockResult {\n     int64_t sigops_cost{0};\n     //! True when the block failed CheckBlock() before any UTXO work was done.\n     bool failed_in_check_block{false};\n-    //! Indices into block.vtx of the transactions deferred because an input was not in the view yet\n-    //! (BlockValidationContext::defer_missing_inputs); their undo slots are empty until\n-    //! FinishDeferredTransactions() fills them. The block is not valid until that has run.\n-    std::vector<uint32_t> deferred_txs;\n-    //! The fees of the transactions checked so far; completed by FinishDeferredTransactions().\n-    CAmount fees{0};\n     //! Phase boundaries, for the caller's bench logging.\n     SteadyClock::time_point time_start{};\n     SteadyClock::time_point time_checked{};\n@@ -729,12 +718,9 @@ struct ConnectBlockResult {\n /**\n  * Apply `block` to `view`, checking every consensus rule that needs the UTXO\n  * set. Pure apart from the view and from what it is handed to use: it reads\n- * node state only through the context's callbacks (median_time_past_at),\n- * reads and updates the script execution cache, erases the entries of the\n- * signature cache that its script checks hit (as on master: a block's\n- * signatures are not looked up twice), reads the steady clock for its\n- * timings, writes nothing to disk and logs nothing itself (CheckBlock() does,\n- * in a debug category, where a signet block's solution fails).\n+ * node state only through the context's callbacks, reads and updates the\n+ * script execution cache, erases the signature cache entries its script\n+ * checks hit, reads the steady clock and writes nothing to disk.\n  *\n  * Script checks run on `check_queue` when it is non-null and has worker\n  * threads, otherwise inline; they are skipped when `ctx.check_scripts` is\n@@ -742,10 +728,9 @@ struct ConnectBlockResult {\n  * the script execution cache takes the results of the checks that run inline,\n  * and the view's best block is left untouched.\n  *\n- * On failure `state` holds the reason and the view may be partially updated.\n- * With `ctx.defer_missing_inputs` true is returned with the checks of the\n- * deferred transactions and the block's totals outstanding, and the block is\n- * valid only once FinishDeferredTransactions() has returned true as well.\n+ * The view's coins are changed with `just_check` too, and on failure `state` holds the reason, the view may be\n+ * partially updated and `result.undo` is incomplete: a caller that keeps the view only on success passes one it\n+ * can discard.\n  *\n  * `block` may be shared with readers on other threads: the fields\n  * CheckBlock() records its results in are atomic (BlockCheckedFlag).\n@@ -755,18 +740,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n                   ValidationCache& validation_cache, bool just_check,\n                   BlockValidationState& state, ConnectBlockResult& result);\n \n-/**\n- * Finish a block that deferred transactions, once every lower block's first pass is applied. A lower\n- * block's own continuation may still be pending; what it changes meanwhile is a store conflict, settled by\n- * connecting the block again alone. Checks each deferred transaction in full (inputs present and unspent,\n- * amounts, maturity, BIP68, sigops, scripts), spends its inputs into its undo slot, completes the fee total\n- * and the sigop count and runs the coinbase amount check. Pure in the same sense as ConnectBlock(). On\n- * failure `state` holds the reason; the view may be partially updated.\n- */\n-bool FinishDeferredTransactions(const CBlock& block, const BlockValidationContext& ctx,\n-                                CCoinsViewCache& view, ValidationCache& validation_cache,\n-                                BlockValidationState& state, ConnectBlockResult& result);\n-\n struct ConnectStep;\n struct StagedConnect;\n struct WindowSync;\n@@ -830,13 +803,12 @@ public:\n     std::unique_ptr<CoinsStore> m_store GUARDED_BY(cs_main);\n \n     //! The views blocks are connected into, one per block in flight, each a BlockApplyView over m_store: a\n-    //! block's changes reach the store once it is validated, under the block's identity, and are confirmed\n-    //! or unwound by one status flip, so an invalid block never pollutes what readers see. The first is the\n-    //! tip's (prefetch on the connect pool, the check queue); the others are the window's, each applied by\n-    //! a connect pool worker.\n+    //! block's changes reach the store once it is valid, so an invalid block never pollutes what readers\n+    //! see. The first is the tip's (prefetch on the connect pool, the check queue); the others are the\n+    //! window's, each validated by a connect pool worker.\n     std::vector<std::unique_ptr<BlockApplyView>> m_apply_views GUARDED_BY(cs_main);\n     BlockApplyView& TipView() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return *m_apply_views.front(); }\n-    //! A view with no block open, or nullptr when every view is in use.\n+    //! A view that is not in use, or nullptr when every view is.\n     BlockApplyView* FreeApplyView() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);\n \n     //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it\n@@ -892,6 +864,17 @@ enum class Assumeutxo {\n  * whereas block information and metadata independent of the current tip is\n  * kept in `BlockManager`.\n  */\n+/**\n+ * A commit puts the changes of several blocks into the store and the connector publishes them one by one,\n+ * all in one hold of cs_main. `ahead` counts those committed and not yet published: between two of them\n+ * nothing writes the coins (FlushStateToDisk()), the publication of the last one does. `run_active`: a\n+ * write-out run is in flight.\n+ */\n+struct CommitGate {\n+    std::atomic<int> ahead{0};\n+    std::atomic<bool> run_active{false};\n+};\n+\n class Chainstate\n {\n protected:\n@@ -1139,6 +1122,10 @@ public:\n     //! Flush all changes to disk.\n     void ForceFlushStateToDisk(bool wipe_cache = true);\n \n+    //! After the coins were written: start a compaction of the coins database now and then\n+    //! (ShouldCompactChainstate()), where the disk has the room it needs; otherwise defer it with a warning.\n+    void MaybeCompactChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);\n+\n     //! Prune blockfiles from the disk if necessary and then flush chainstate changes\n     //! if we pruned.\n     void PruneAndFlush();\n@@ -1266,22 +1253,24 @@ protected:\n \n     /**\n      * Connecting a block happens in three parts:\n-     *  - StageConnectTip(), under cs_main: open the block in a view of the\n+     *  - StageConnectTip(), under cs_main: give the block a view of the\n      *    store and decide the node policy (BlockValidationContext). At the\n      *    tip the block is already read and the prefetch of the coins it\n-     *    spends is started; in the window the block takes a free view, defers\n-     *    the inputs lower blocks have not produced yet, and if it is on disk\n-     *    its bytes are read on a block I/O thread (ReadForConnectTask()),\n-     *    which hands them to its worker.\n+     *    spends is started; in the window the block takes a free view, and if\n+     *    it is on disk its bytes are read on a block I/O thread\n+     *    (ReadForConnectTask()), which hands them to its worker.\n      *  - RunStagedConnect() at the tip: the pure ConnectBlock() into the view\n-     *    with the check queue, under cs_main. RunConnectTask() in the window:\n-     *    the same on a connect pool worker with its scripts inline and no lock\n-     *    held; RunContinuation() finishes what the block deferred.\n+     *    with the check queue, under cs_main. In the window, on connect pool\n+     *    workers with no lock held: RunConnectTask() parses the block and\n+     *    enters its transactions in the window's outputs, and once every\n+     *    lower block's are there RunWindowValidation() runs the same\n+     *    ConnectBlock() with its scripts inline, read only against the store.\n      *  - PublishConnectTip(), under cs_main and the mempool lock: queue the\n-     *    undo write, confirm the block in the store, update mempool and tip,\n-     *    notify. Returns true unless a system error occurred, the block was\n-     *    invalid (state says which), or a window block is to be connected\n-     *    again alone (state valid).\n+     *    undo write, commit the block to the store (a window block is\n+     *    committed by the connector just before, with the blocks above it\n+     *    that are ready), update mempool and tip, notify. Returns true unless\n+     *    a system error occurred, the block was invalid (state says which),\n+     *    or a window block is to be connected again alone (state valid).\n      * What exists of the block at each part is a type of its own\n      * (connect_phase, in validation.cpp); only a Validated is published.\n      */\n@@ -1292,10 +1281,12 @@ protected:\n     //! Read the bytes of a window block that is on disk, then hand its connect task to the pool with them.\n     //! On a block I/O thread, so that no connect pool worker waits for the disk.\n     void ReadForConnectTask(StagedConnect& staged, std::shared_ptr<std::promise<void>> done) noexcept;\n-    //! A windowed block's worker has applied it: mark it so and run the continuations this makes possible.\n-    void OnWindowBlockApplied(StagedConnect& staged);\n-    //! Finish a window block's deferred transactions and apply the result; the block is marked finished.\n-    void RunContinuation(StagedConnect& s, WindowSync& sync) noexcept;\n+    //! A window block's worker has entered it in the window's outputs, or could not read it: mark it so and\n+    //! run the validations this makes possible.\n+    void OnWindowBlockIndexed(StagedConnect& staged);\n+    //! Validate a window block against the store and the window's outputs; the block is marked finished.\n+    void RunWindowValidation(StagedConnect& s, WindowSync& sync) noexcept;\n+    CommitGate m_commit_gate;\n     bool PublishConnectTip(\n         BlockValidationState& state,\n         StagedConnect& staged,\n@@ -1496,13 +1487,13 @@ public:\n     node::BlockCache m_block_cache;\n \n private:\n-    //! The window's: blocks validated on a connect pool worker, transactions deferred to their block's\n-    //! continuation because a lower block had not produced an input yet, the conflicts a store change met\n-    //! (a spend or create a lower block took, a create BIP30 refused, a miss), and the blocks that failed in\n-    //! the window and were connected again alone. Written by the connector thread and the pool's workers\n-    //! (deferred transactions are counted where a block is applied), read at shutdown.\n+    //! The window's: blocks validated on a connect pool worker, the commits that met a conflict (a spend of\n+    //! a coin a lower block spent, a create over a coin) and the blocks that failed in the window or were\n+    //! taken back, and were connected again alone. Written by the connector thread, read at shutdown.\n     std::atomic<uint64_t> m_window_blocks{0};\n-    std::atomic<uint64_t> m_window_deferred_txs{0};\n+    //! Steps that use the window and have not ended (ConnectStep::window_steps): while one runs, every block it\n+    //! publishes checks for pruning, and a block accepted meanwhile leaves that check to it (FinishAcceptBlock()).\n+    std::atomic<int> m_window_steps_running{0};\n     std::atomic<uint64_t> m_window_conflicts{0};\n     std::atomic<uint64_t> m_window_retries{0};\n \n@@ -1779,6 +1770,9 @@ public:\n     Chainstate& ActiveChainstate() const;\n     CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }\n     int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }\n+    //! The tips the block cache measures its blocks against: the active one, and with a snapshot whose\n+    //! historical chainstate still syncs, that one's for the blocks at or below the snapshot's base.\n+    node::BlockCache::Tips BlockCacheTips() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());\n     CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }\n     //! @}\n \n@@ -1885,9 +1879,9 @@ public:\n     //! A block between the steps of ProcessNewBlock().\n     struct NewBlockInProcess;\n     /**\n-     * ProcessNewBlock() in its three steps, for a caller that makes the block's write on another thread:\n-     * the receive task of the initial block download, which writes on a block I/O thread\n-     * (BlockManager::RunBlockIO()), so that no connect pool worker waits for the disk.\n+     * ProcessNewBlock() in its three steps, for a caller that makes the block's write on another thread,\n+     * such as a block I/O thread (BlockManager::RunBlockIO()), so that no connect pool worker waits for\n+     * the disk.\n      *\n      *  - AcceptNewBlock(): the block's checks, its header, and the claim of its place on disk. False if\n      *    the block failed, which is ProcessNewBlock()'s result then and has been reported; the other\n@@ -2115,19 +2109,9 @@ public:\n     std::optional<int> BlocksAheadOfTip() const LOCKS_EXCLUDED(::cs_main);\n \n     CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }\n-    //! The connect pool: block appliers of the window and the blocks received from peers during initial\n-    //! block download, input prefetchers at the tip (sized by -prevoutfetchthreads). Shared by every\n-    //! chainstate's views.\n+    //! The connect pool: the parses and validations of the window's blocks during initial block download,\n+    //! input prefetchers at the tip (sized by -prevoutfetchthreads). Shared by every chainstate's views.\n     const util::NotNullSharedPtr<ThreadPool> m_connect_pool;\n-    /**\n-     * The free worker. The connector waits for the connect pool's workers with cs_main held\n-     * (Chainstate::DrainWindow()). The work it waits for, a block's validation, takes no cs_main, but it\n-     * needs a worker, and the pool also runs tasks that wait for cs_main: the receive tasks of net\n-     * processing. Whoever gives the pool such a task keeps to\n-     * LockTaskLimit(), one fewer than the workers, so at least one worker is in no such task and the waits\n-     * end.\n-     */\n-    int LockTaskLimit() const;\n     //! The blocks each thread built in a task on the connect pool, back from their last holder (NewBlock()).\n     const std::unique_ptr<BlockBins> m_block_bins;\n     /**\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 664,
    "evidence_id": "03e1af7e08534d9b8e8f15645f6e32b7",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 515,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/validation.h",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": " * Which consensus deployments are active for a block. Evaluated by the node\n * from the header chain (ChainstateManager::MakeBlockValidationContext()), so\n * that the validation functions need neither the ChainstateManager nor the\n * version bits cache.\n */\nstruct DeploymentFlags {\n    bool heightincb{false}; //!< BIP34\n    bool dersig{false};     //!< BIP66\n    bool cltv{false};       //!< BIP65\n    bool csv{false};        //!< BIP68, BIP112, BIP113\n    bool segwit{false};     //!< BIP141, BIP143, BIP147\n};\n\n/**\n * Ordering preconditions.\n *\n * Guarantees the rest of the node relies on that no type or annotation\n * states. The code that relies on one names its number; where the condition\n * can be tested it is asserted (Assume). Each entry says what holds it: the\n * construction, a named call that waits until it holds, or a deferral. A\n * call site that relies on a condition calls the wait; none reads the state\n * it waits for by itself.\n *\n *  O1  The only half-processed state a block can be seen in is \"stored, not\n *      yet activated\", and calling ActivateBestChain() closes it.\n *      ProcessNewBlock() opens it; ProcessGetBlockData() and the GETBLOCKS\n *      handler in net_processing close it before they answer.\n *      In flight: a block handed to the connector (ProcessNewBlock() with\n *      activate_async) is in that state until the connector has activated\n *      it. Wait: WaitForPendingBlocks().\n *  O2  When AcceptBlock() returns for a new block, its data, its position\n *      and BLOCK_VALID_TRANSACTIONS are recorded together (asserted there),\n *      in one hold of cs_main after the write (FinishAcceptBlock()). Until\n *      then the block is being stored (IsBlockBeingStored()), which no\n *      reader of its data takes for stored; a second copy is dropped as a\n *      block already had (PrepareAcceptBlockHeader()), and submitblock\n *      answers \"duplicate\" for it.\n *  O3  BlockChecked is delivered under cs_main before the tip moves to the\n *      block (PublishConnectTip()).\n *  O4  NewPoWValidBlock is delivered under cs_main before the block is\n *      recorded as stored, and only for a block on top of the tip\n *      (AcceptBlock(), not asserted). Deferral: a peer's request for the\n *      announced block is asked again until the block is stored\n *      (ProcessGetBlockData()).\n *  O5  Message processing requests only blocks that are not stored. Not\n *      asserted: getblockfrompeer checks and requests in two holds of\n *      cs_main. A block is \"received, not stored\" inside the handling of\n *      the message that delivers it (O13) and while its task runs on the\n *      connect pool. Deferral: its request stays in flight until the block\n *      is stored, and a second copy from the same peer is dropped while the\n *      first one's task runs. A peer that goes takes its\n *      requests with it, and the block may be downloaded a second time.\n *  O6  The tip is the fully connected frontier: its coins are in the tip\n *      view and its transaction counts are known. Asserted in PublishTip(),\n *      where after a failed write-out the tip view's best block may be the\n *      tip's parent (DisconnectTip()) or the block that was being connected\n *      (PublishConnectTip()). Window blocks are connected ahead of the tip,\n *      each on a view of its own.\n *  O7  Signals are queued under cs_main in the order of connection, and\n *      what they name is stored and connected (checked in\n *      PublishConnectTip() and DisconnectTip()). BlockDisconnected is\n *      queued directly, BlockConnected behind the block's undo write, so\n *      the callers of DisconnectTip() settle the latter before the first\n *      disconnect (PlanConnectStep(), InvalidateBlock()). Wait:\n *      BlockManager::SettleUndoWrites() under cs_main: outside initial\n *      block download before the step that connected the block releases\n *      cs_main, in it before a transaction is submitted to the mempool\n *      (SubmitToMemoryPool(), ProcessNewPackage()).\n *  O8  A flush never sees a half-applied block (asserted in\n *      FlushStateToDisk()): the coins' best block is the tip, its parent\n *      (inside DisconnectTip(), which writes before the tip moves), or the\n *      one block on top of the tip that is being connected, or was when a\n *      write-out failed. The write is made before the block becomes the\n *      tip (PublishConnectTip()), and nothing can fail once it is; a step\n *      that disconnected blocks writes at its end (FinishConnectStep()),\n *      where a failure is the same fatal error. Wait:\n *      Chainstate::SettleWriteOut() before another write-out run starts, a\n *      flush goes on or the block index is written.\n *  O9  Publication is strictly sequential: a block is published on top of\n *      the tip (asserted in PublishConnectTip()), one ActivateBestChain()\n *      at a time (m_chainstate_mutex).\n *  O10 nSequenceId is assigned under cs_main when a block becomes linked\n *      (ReceivedBlockTransactions()): its data and every ancestor's\n *      transaction count are known. A block stored before its parent waits,\n *      and is numbered with the descendants the link reaches, parent first;\n *      so the order may differ from the order of arrival. Blocks loaded at\n *      startup and preciousblock assign it otherwise.\n *  O11 A file position copied under cs_main stays readable afterwards, or\n *      the reader handles the failed read (node::BlockFacts). A connected\n *      block's undo position is null until its queued write has run. Wait:\n *      BlockManager::SettleUndoWriteOf() for a reader of one block's undo\n *      data, SettleUndoWrites() before blocks are disconnected or verified.\n *  O12 The block index invariants hold whenever cs_main is free\n *      (CheckBlockIndex()).\n *  O13 Messages are processed on one thread, so a block request may be\n *      removed before the block is stored and no message asks for the\n *      block again in between. Asserted at the BLOCK message and in\n *      ProcessCompactBlockTxns(); for a block on the connect pool see O5.\n *  O14 InvalidateBlock() tolerates blocks arriving between its lock drops,\n *      by going over the block index again at its end.\n *  O15 The tip does not move while a block template or proposal is\n *      checked: TestBlockValidity() runs under cs_main, and the tip is\n *      published under cs_main only.\n *\n * File I/O.\n *\n * Block and undo file work is made between two states, not inside a\n * transition: with cs_main free, so that nothing waits for it but what it is\n * made for. A transition under cs_main only decides and records.\n *\n *  - A block's write is the work between \"being stored\" and stored (O2): on\n *    the caller's thread, where only that block waits. The write allocates\n *    the file space it needs; the claim of its position is arithmetic.\n *  - A window block that is not in memory is read on a block I/O thread\n *    (BlockManager::RunBlockIO()).\n *  - Undo writes, the trim and sync of a file that is finished, and the\n *    write-out runs with the syncs their block index batch owes, are the\n *    ordered effects executor's (BlockManager::m_effects).\n *  - Pruned files are removed on a block I/O thread once the block index no\n *    longer records them.\n *\n * Still made under cs_main, by a caller that waits for the result itself: the\n * syncs of a forced flush, the removal of files for pruneblockchain, the\n * reads of DisconnectTip(), the external block loader, and loading and\n * verifying at the start.\n */\n\n/**\n * Everything a block validation function needs from the node besides the\n * block itself and the coins view. The node builds one under cs_main from\n * configuration and the header chain; the validation functions read it and\n * touch no other node state, so they can be called and tested without a\n * ChainstateManager. The contextual header and block checks also take the\n * previous block index entry, for the difficulty calculation.\n *\n * Every member is a copy, with two kinds of exception: params refers to the\n * chain's constant parameters, and median_time_past_at, help_point and\n * implicit_creates are functions.\n */\nstruct BlockValidationContext {\n    const Consensus::Params& params;\n    //! Clock reading used for the future-timestamp check of the header.\n    NodeClock::time_point now;\n    DeploymentFlags deployments;\n    //! Script flags to enforce for this block, see GetBlockScriptFlags().\n    script_verify_flags script_flags;\n    //! Whether to verify input scripts at all. False only under -assumevalid.\n    bool check_scripts{true};\n    //! The block's hash.\n    uint256 block_hash;",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45Kernel memory documentation omits pinned-block backpressuresrc/kernel/bitcoinkernel.hpartially_addressed
Assessment

The header no longer describes notification-pinned blocks as byte-unbounded: it gives an estimated allowance and notes that more may be retained during reorganizations. However, the supplied wording does not state the reorganization exception to the normal backpressure threshold, so that material qualification remains missing.

path_diff: src/kernel/bitcoinkernel.h; new_source: src/kernel/bitcoinkernel.h

[
  {
    "evidence_id": "0ba21edf889840a8b03c0f3fbddb0f7d",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/kernel/bitcoinkernel.h",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h\nindex 06aa0bae85..632ca1c8ac 100644\n--- a/src/kernel/bitcoinkernel.h\n+++ b/src/kernel/bitcoinkernel.h\n@@ -540,7 +540,9 @@ typedef struct {\n     btck_NotifyProgress progress;           //!< Reports on current block synchronization progress.\n     btck_NotifyWarningSet warning_set;      //!< A warning issued by the kernel library during validation.\n     btck_NotifyWarningUnset warning_unset;  //!< A previous condition leading to the issuance of a warning is no longer given.\n-    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk.\n+    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk. No later write of the block\n+                                            //!< index and the chainstate succeeds in this run: the caller may still read,\n+                                            //!< but has to stop processing blocks and restart to write again.\n     btck_NotifyFatalError fatal_error;      //!< An unrecoverable system error encountered by the library.\n } btck_NotificationInterfaceCallbacks;\n \n@@ -1304,9 +1306,11 @@ BITCOINKERNEL_API void btck_chainstate_manager_options_set_worker_threads_num(\n  * called, the total cache defaults to 450 MiB. On top of it, whatever the\n  * total cache size: up to 128 MiB of accepted blocks kept in memory until they\n  * are connected, an eighth of the coins cache and 32 MiB at least for the\n- * blocks being connected, up to 64 MiB of undo data waiting to be written, and,\n- * with no limit in bytes, the blocks whose notifications wait for an undo\n- * write.\n+ * blocks being connected, up to 64 MiB of undo data waiting to be written, and\n+ * an eighth of the coins cache and 64 MiB at least for the blocks whose\n+ * notifications wait for an undo write (more while a reorganisation connects\n+ * its blocks). Further, 4 MiB for each chainstate that validated blocks beside\n+ * each other.\n  *\n  * @param[in] chainstate_manager_options Non-null, options to be set.\n  * @param[in] database_cache_bytes       The total database cache size in bytes. Values below 4 MiB are rejected.\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1427,
    "evidence_id": "38bc3f0eb0794ba7ab0417094bfc7405",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 1278,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/kernel/bitcoinkernel.h",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": " * @param[in] blocks_directory Path string of the directory containing the block data. If the directory\n *                             does not exist yet, it will be created.\n * @return                     The allocated chainstate manager options, or null on error (e.g. if a path is invalid).\n */\nBITCOINKERNEL_API btck_ChainstateManagerOptions* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_create(\n    const btck_Context* context,\n    const char* data_directory,\n    size_t data_directory_len,\n    const char* blocks_directory,\n    size_t blocks_directory_len) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Set the number of available worker threads used during validation.\n *\n * @param[in] chainstate_manager_options Non-null, options to be set.\n * @param[in] worker_threads             The number of worker threads that should be spawned in the thread pool\n *                                       used for validation. When set to 0 no parallel verification is done.\n *                                       The value range is clamped internally between 0 and 15.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_set_worker_threads_num(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int worker_threads) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Set the total database cache used by the chainstate manager.\n *\n * The total cache is split internally between the block tree database,\n * chainstate database, and in-memory coins cache. If this function is not\n * called, the total cache defaults to 450 MiB. On top of it, whatever the\n * total cache size: up to 128 MiB of accepted blocks kept in memory until they\n * are connected, an eighth of the coins cache and 32 MiB at least for the\n * blocks being connected, up to 64 MiB of undo data waiting to be written, and\n * an eighth of the coins cache and 64 MiB at least for the blocks whose\n * notifications wait for an undo write (more while a reorganisation connects\n * its blocks). Further, 4 MiB for each chainstate that validated blocks beside\n * each other.\n *\n * @param[in] chainstate_manager_options Non-null, options to be set.\n * @param[in] database_cache_bytes       The total database cache size in bytes. Values below 4 MiB are rejected.\n *                                       On 32-bit systems, values above 1 GiB are also rejected.\n * @return                               0 if the set was successful, non-zero if the set failed.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_set_database_cache_bytes(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    uint64_t database_cache_bytes) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets wipe db in the options. In combination with calling\n * @ref btck_chainstate_manager_import_blocks this triggers either a full reindex,\n * or a reindex of just the chainstate database.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] wipe_block_tree_db         Set wipe block tree db. Should only be 1 if wipe_chainstate_db is 1 too.\n * @param[in] wipe_chainstate_db         Set wipe chainstate db.\n * @return                               0 if the set was successful, non-zero if the set failed.\n * @note                                 When a wipe is set, the caller must invoke @ref btck_chainstate_manager_import_blocks\n *                                       on the resulting chainstate manager before using it for anything else.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_set_wipe_dbs(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int wipe_block_tree_db,\n    int wipe_chainstate_db) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets block tree db in memory in the options.\n *\n * @param[in] chainstate_manager_options   Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] block_tree_db_in_memory      Set block tree db in memory.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_update_block_tree_db_in_memory(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int block_tree_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets chainstate db in memory in the options.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] chainstate_db_in_memory    Set chainstate db in memory.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_update_chainstate_db_in_memory(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int chainstate_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * Destroy the chainstate manager options.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* chainstate_manager_options);\n\n///@}\n\n/** @name ChainstateManager\n * Functions for chainstate management.\n */\n///@{\n\n/**\n * @brief Create a chainstate manager. This is the main object for many\n * validation tasks as well as for retrieving data from the chain and\n * interacting with its chainstate and indexes.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @return                               The allocated chainstate manager, or null on error.\n */\nBITCOINKERNEL_API btck_ChainstateManager* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_create(\n    const btck_ChainstateManagerOptions* chainstate_manager_options) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Get the btck_BlockTreeEntry whose associated btck_BlockHeader has the most\n * known cumulative proof of work.\n *\n * @param[in] chainstate_manager Non-null.\n * @return                       The btck_BlockTreeEntry, or null if no block headers have been loaded.\n */\nBITCOINKERNEL_API const btck_BlockTreeEntry* btck_chainstate_manager_get_best_entry(\n    const btck_ChainstateManager* chainstate_manager) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Processes and validates the provided btck_BlockHeader.\n *\n * @param[in] chainstate_manager        Non-null.\n * @param[in] header                    Non-null btck_BlockHeader to be validated.\n * @return                              The btck_BlockValidationState containing validation result, or null on error.\n */\nBITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_process_block_header(\n    btck_ChainstateManager* chainstate_manager,\n    const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1, 2);\n\n/**\n * @brief Triggers the start of a reindex if the wipe options were previously\n * set for the chainstate manager. Can also import an array of existing block\n * files selected by the user.\n *\n * Do not call this while another btck_chainstate_manager_import_blocks call\n * on the same chainstate manager is in progress. The process aborts when this\n * is detected.\n *\n * @param[in] chainstate_manager        Non-null.\n * @param[in] block_file_paths_data     Nullable, array of block files described by their full filesystem paths.\n * @param[in] block_file_paths_lens     Nullable, array containing the lengths of each of the paths.\n * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_len arrays.\n * @return                              0 if the import blocks call was completed successfully, non-zero otherwise.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_import_blocks(\n    btck_ChainstateManager* chainstate_manager,\n    const char** block_file_paths_data, size_t* block_file_paths_lens,\n    size_t block_file_paths_data_len) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Process and validate the passed in block with the chainstate\n * manager. Processing first does checks on the block, and if these passed,",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45Window tests do not force successful out-of-order continuationsrc/test/validation_chainstate_tests.cppstill_present
Assessment

The supplied test diff removes the deferred-transaction scenario and adds a double-spend conflict/retry case. It does not add a controlled successful case where a higher block waits for an output created by a lower block, nor assertions for successful continuation/publication of that case.

path_diff: src/test/validation_chainstate_tests.cpp; new_source: src/test/validation_chainstate_tests.cpp

[
  {
    "evidence_id": "479dfdc55d244c76acab8b4778714e81",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/test/validation_chainstate_tests.cpp",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/test/validation_chainstate_tests.cpp b/src/test/validation_chainstate_tests.cpp\nindex 1194650f2d..c275a411fa 100644\n--- a/src/test/validation_chainstate_tests.cpp\n+++ b/src/test/validation_chainstate_tests.cpp\n@@ -445,16 +445,16 @@ BOOST_FIXTURE_TEST_CASE(failed_write_out_leaves_the_tip, WriteOutEveryBlockSetup\n //! Drives a step of the connect window one block at a time, with nothing added to the node: the connect\n //! pool's workers are held by tasks that wait (as threadpool_tests' BlockWorkers() does), ActivateBestChain()\n //! runs on a thread of its own, and the test thread runs the tasks the step queues, one per call\n-//! (ThreadPool::ProcessTask()). Between two calls the connector waits for a block no worker will apply, so\n+//! (ThreadPool::ProcessTask()). Between two calls the connector waits for a block no worker will validate, so\n //! what the test does there happens between two blocks of the window. Not more than that: WaitForStep()\n //! returns once the tip is published and the queue has its count, and where the window had nothing to\n //! refill the connector may still be at what follows a publication (a periodic write-out, the wait for the\n //! signal queue, the plan of the next blocks).\n //!\n //! What this reaches: blocks that complete in the order they were staged, which is the order of the queue.\n-//! A block that completes ahead of a lower one is out of its reach, and with it a deferred transaction\n-//! whose coin a lower block brings later. A block connected outside the window stalls under it, its input\n-//! fetch waits for tasks of the same pool: the workers are let go (Finish()) before a step comes to one.\n+//! A block that completes ahead of a lower one is out of its reach. A block connected outside the window\n+//! stalls under it, its input fetch waits for tasks of the same pool: the workers are let go (Finish())\n+//! before a step comes to one.\n //!\n //! In a step of the window the queue holds the blocks' tasks only: a block read by its task is not freed\n //! through the pool, and a write-out of a chain this small has one range, which its own thread writes.\n@@ -614,6 +614,27 @@ struct WindowStepSetup : TestChain100Setup {\n         }\n     }\n \n+    //! Store a copy of the block at `original` on top of `parent`, with `extra` as one transaction more.\n+    std::pair<CBlock, CBlockIndex*> StoreSibling(const CBlockIndex& original, const uint256& parent, const CTransactionRef& extra = nullptr)\n+    {\n+        ChainstateManager& chainman{*Assert(m_node.chainman)};\n+        CBlock block;\n+        BOOST_REQUIRE(chainman.m_blockman.ReadBlock(block, original));\n+        block.hashPrevBlock = parent;\n+        if (extra) {\n+            block.vtx.push_back(extra);\n+            node::RegenerateCommitments(block, chainman);\n+        }\n+        while (!CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus())) ++block.nNonce;\n+        LOCK(::cs_main);\n+        BlockValidationState state;\n+        CBlockIndex* index{nullptr};\n+        bool new_block{false};\n+        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(block), state, &index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n+        BOOST_REQUIRE(new_block && index);\n+        return {std::move(block), index};\n+    }\n+\n     //! The blocks in flight once the tip is at `height`.\n     size_t InFlightAt(int height) const\n     {\n@@ -673,12 +694,11 @@ struct WindowSummaryLog {\n     }\n \n     //! The counts the manager is to log: the test's blocks that came to their publication in the window,\n-    //! the transactions it deferred, the conflicts its blocks met in the store, and the blocks it gave up\n-    //! and connected alone.\n-    void ExpectWindowSummary(unsigned blocks, unsigned deferred, unsigned conflicts, unsigned retries)\n+    //! the commits that met a conflict in the store, and the blocks it gave up and connected alone.\n+    void ExpectWindowSummary(unsigned blocks, unsigned conflicts, unsigned retries)\n     {\n         m_expected_blocks = strprintf(\"Connect window: %u blocks validated on the connect pool (\", FIXTURE_BLOCKS + blocks);\n-        m_expected_counts = strprintf(\" wide), %u transactions deferred to their block's continuation, %u conflicts, %u blocks retried alone\", deferred, conflicts, retries);\n+        m_expected_counts = strprintf(\" wide), %u conflicts, %u blocks retried alone\", conflicts, retries);\n     }\n };\n \n@@ -690,7 +710,7 @@ struct WindowSummarySetup : WindowSummaryLog, WindowStepSetup {\n //! write-out under it meets no conflict, and no block of it is connected a second time.\n BOOST_FIXTURE_TEST_CASE(window_step_block_by_block, WindowSummarySetup)\n {\n-    ExpectWindowSummary(/*blocks=*/BLOCKS, /*deferred=*/0, /*conflicts=*/0, /*retries=*/0);\n+    ExpectWindowSummary(/*blocks=*/BLOCKS, /*conflicts=*/0, /*retries=*/0);\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n     Chainstate& chainstate{chainman.ActiveChainstate()};\n     CacheStepBlocks();\n@@ -757,7 +777,7 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n         // The first block is published: the write-out before the tip has nothing due, the periodic write\n         // is, and the run its hold starts fails.\n         stepper.RunLowestBlock();\n-        // The blocks above it are run by the workers, and taken back.\n+        // The blocks above it are run by the workers, and let go.\n         stepper.Finish();\n     }\n     m_node.validation_signals->SyncWithValidationInterfaceQueue();\n@@ -766,9 +786,8 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n     BOOST_CHECK(!activated);\n     BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE);\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height + 1);\n-    // The blocks above gave their places in the store back.\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n-    // And what they held in memory; the block cache alone keeps the blocks that were not connected.\n+    // The blocks above gave back what they held in memory; the block cache alone keeps the blocks that were\n+    // not connected.\n     for (const util::ByteAccountId id : {util::ByteAccountId::Window, util::ByteAccountId::UndoBacklog, util::ByteAccountId::PinnedBlocks}) {\n         BOOST_CHECK_EQUAL(chainman.m_bytes_in_flight[id].Bytes(), 0U);\n     }\n@@ -781,7 +800,7 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n }\n \n //! A window block whose file cannot be read. Its task ends without a verdict, and the step ends where the\n-//! block would be published: the window is drained, the blocks give their places in the store back, the\n+//! block would be published: the window is drained, the blocks give their views back, the\n //! node gets a fatal error and the pass fails with the tip where it was. Nothing is published or announced.\n BOOST_FIXTURE_TEST_CASE(unreadable_block_ends_a_window_step, WindowStepSetup)\n {\n@@ -815,61 +834,32 @@ BOOST_FIXTURE_TEST_CASE(unreadable_block_ends_a_window_step, WindowStepSetup)\n     BOOST_CHECK_EQUAL(state.GetRejectReason(), \"Failed to read block.\");\n     BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE);\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height);\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n     CheckAccountsEmpty();\n     const std::lock_guard lock{m_recorder->mutex};\n     BOOST_CHECK(m_recorder->connected.empty());\n     BOOST_CHECK(m_recorder->tips.empty());\n }\n \n-//! A block of the window with a transaction whose coin no block creates. The transaction is deferred, since\n-//! the block's parent was not the tip when it was staged, and its continuation finds no coin, which in the\n-//! window decides nothing: the step ends, the changes of the block above it are taken back and then its own,\n-//! and the block is connected alone, where the same transaction makes it invalid. The block below it stays\n-//! the tip.\n-BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n+//! A block of the window with a transaction whose coin no block creates. Its validation in the window finds\n+//! no coin, which decides nothing there: the step ends, and the block is connected alone, where the same\n+//! transaction makes it invalid. The block below it stays the tip.\n+BOOST_FIXTURE_TEST_CASE(invalid_window_block_is_judged_alone, WindowSummarySetup)\n {\n-    // Two blocks came to their publication in the window, the first and the sibling. The window deferred\n-    // the sibling's transaction (a block that judges it with the rest fails there and defers nothing), the\n-    // failed continuation is no conflict in the store, and the sibling is the one block connected again.\n-    ExpectWindowSummary(/*blocks=*/2, /*deferred=*/1, /*conflicts=*/0, /*retries=*/1);\n+    // Two blocks came to their publication in the window, the first and the sibling, which met no conflict\n+    // in the store and is the one block connected again.\n+    ExpectWindowSummary(/*blocks=*/2, /*conflicts=*/0, /*retries=*/1);\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n     Chainstate& chainstate{chainman.ActiveChainstate()};\n+    const CBlockIndex* const first{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 1))};\n     CBlockIndex* const second{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 2))};\n     const CBlockIndex* const third{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 3))};\n-    // A sibling of the setup's second block with one transaction more, which spends no coin.\n-    CBlock bad;\n-    BOOST_REQUIRE(chainman.m_blockman.ReadBlock(bad, *second));\n+    // A sibling of the setup's second block with one transaction more, which spends no coin, and the setup's\n+    // third on top of it: a block of the window is in flight above the one that fails.\n     CMutableTransaction spend;\n     spend.vin.emplace_back(COutPoint{Txid::FromUint256(m_rng.rand256()), 0});\n     spend.vout.emplace_back(CAmount{1}, CScript() << OP_TRUE);\n-    bad.vtx.push_back(MakeTransactionRef(std::move(spend)));\n-    node::RegenerateCommitments(bad, chainman);\n-    while (!CheckProofOfWork(bad.GetHash(), bad.nBits, chainman.GetConsensus())) ++bad.nNonce;\n-    CBlockIndex* bad_index{nullptr};\n-    {\n-        LOCK(::cs_main);\n-        BlockValidationState accept_state;\n-        bool new_block{false};\n-        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(bad), accept_state, &bad_index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n-        BOOST_REQUIRE(new_block && bad_index);\n-    }\n-    // And a block on top of it, the setup's third with the sibling as its parent: a block of the window is\n-    // in flight above the one that fails, and its changes are taken back first.\n-    CBlock above;\n-    const CBlockIndex* top{nullptr};\n-    BOOST_REQUIRE(chainman.m_blockman.ReadBlock(above, *third));\n-    above.hashPrevBlock = bad.GetHash();\n-    while (!CheckProofOfWork(above.GetHash(), above.nBits, chainman.GetConsensus())) ++above.nNonce;\n-    {\n-        LOCK(::cs_main);\n-        BlockValidationState accept_state;\n-        CBlockIndex* above_index{nullptr};\n-        bool new_block{false};\n-        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(above), accept_state, &above_index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n-        BOOST_REQUIRE(new_block && above_index);\n-        top = above_index;\n-    }\n+    const auto [bad, bad_index]{StoreSibling(*second, first->GetBlockHash(), MakeTransactionRef(std::move(spend)))};\n+    const auto [above, top]{StoreSibling(*third, bad.GetHash())};\n     CacheStepBlocks(top);\n     // The setup's blocks from the second on are set aside, so that the sibling is what the step heads for.\n     BlockValidationState invalidate_state;\n@@ -880,17 +870,16 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     bool activated{false};\n     {\n         // Only a block that is connected alone logs this line (a window block is read by its task): the\n-        // block was connected a second time, outside the window. That its transaction was deferred the\n-        // first time, and not judged with the rest of the block, is in the window's summary (above).\n+        // block was connected a second time, outside the window.\n         ASSERT_DEBUG_LOG(\"  - Load block from disk\");\n         WindowStepper stepper{chainman};\n         stepper.Start([&] { activated = chainstate.ActivateBestChain(state); });\n         stepper.WaitForStep(m_base_height, std::min<size_t>(3, chainman.ConnectWindow()));\n         stepper.RunLowestBlock();\n         stepper.WaitForStep(m_base_height + 1, 2);\n-        // The sibling's task defers the transaction and runs its continuation, here, with the block above\n-        // it still queued. The workers are let go for that block, which the step waits for before it takes\n-        // the two back, and for the sibling connected alone next, outside the window.\n+        // The sibling's task finds the transaction's coin missing, here, with the block above it still\n+        // queued. The workers are let go for that block, which the step waits for, and for the sibling\n+        // connected alone next, outside the window.\n         stepper.RunLowestBlock();\n         stepper.Finish();\n     }\n@@ -899,8 +888,6 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     // The verdict is that of the step that connected the block alone: the window gives none.\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height + 1);\n     BOOST_CHECK(WITH_LOCK(::cs_main, return (bad_index->nStatus & BLOCK_FAILED_VALID) != 0));\n-    // The block's place in the store was given back both times, and that of the block above it.\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n     BOOST_CHECK(!WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(COutPoint{bad.vtx.back()->GetHash(), 0})));\n     BOOST_CHECK(!WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(COutPoint{above.vtx[0]->GetHash(), 0})));\n     m_node.validation_signals->SyncWithValidationInterfaceQueue();\n@@ -911,6 +898,88 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     BOOST_CHECK_EQUAL_COLLECTIONS(m_recorder->connected.begin(), m_recorder->connected.end(), expected.begin(), expected.end());\n }\n \n+//! Two blocks of the window spend one coin. Each is validated against the published blocks, where the coin\n+//! is, so both are valid and come to one commit. There the upper block's spend finds the coin gone: it and\n+//! the block above it are taken out of the store again, the lower block is published, and the upper one is\n+//! connected alone, where the spend makes it invalid.\n+BOOST_FIXTURE_TEST_CASE(double_spend_in_the_window_is_taken_back, WindowSummarySetup)\n+{\n+    // The first block and the lower spender came to their publication in the window; the upper spender is\n+    // the one conflict and the one block connected again.\n+    ExpectWindowSummary(/*blocks=*/2, /*conflicts=*/1, /*retries=*/1);\n+    ChainstateManager& chainman{*Assert(m_node.chainman)};\n+    Chainstate& chainstate{chainman.ActiveChainstate()};\n+    BOOST_REQUIRE_GE(chainman.ConnectWindow(), 4);\n+    const CBlockIndex* const first{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 1))};\n+    CBlockIndex* const second{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 2))};\n+    const CBlockIndex* const third{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 3))};\n+    const CBlockIndex* const fourth{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 4))};\n+    // Two spends of the fixture's first coinbase output, which no block of the setup spends.\n+    const CTransactionRef funding{m_coinbase_txns[0]};\n+    const COutPoint coin{funding->GetHash(), 0};\n+    const auto spend_to{[&](CAmount amount) {\n+        return MakeTransactionRef(CreateValidMempoolTransaction(funding, /*input_vout=*/0, /*input_height=*/1, coinbaseKey, CScript() << OP_TRUE, amount, /*submit=*/false));\n+    }};\n+    const CTransactionRef lower_spend{spend_to(1 * COIN)};\n+    const CTransactionRef upper_spend{spend_to(2 * COIN)};\n+    BOOST_REQUIRE(lower_spend->GetHash() != upper_spend->GetHash());\n+    BOOST_REQUIRE(WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(coin)));\n+    const auto [lower, lower_index]{StoreSibling(*second, first->GetBlockHash(), lower_spend)};\n+    const auto [upper, upper_index]{StoreSibling(*third, lower.GetHash(), upper_spend)};\n+    const auto [above, top]{StoreSibling(*fourth, upper.GetHash())};\n+    CacheStepBlocks(top);\n+    BlockValidationState invalidate_state;\n+    BOOST_REQUIRE(chainstate.InvalidateBlock(invalidate_state, second));\n+    BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height);\n+    // A write sets the timer of the periodic one: none is due in the step, and the commit takes every\n+    // complete block.\n+    {\n+        BlockValidationState flush_state;\n+        BOOST_REQUIRE(chainstate.FlushStateToDisk(flush_state, FlushStateMode::FORCE_FLUSH));\n+    }\n+\n+    BlockValidationState state;\n+    bool activated{false};\n+    {\n+        ASSERT_DEBUG_LOG(strprintf(\"A conflict in a commit, first in the block at height %d: 2 blocks taken out of the store again\", m_base_height + 3));\n+        ASSERT_DEBUG_LOG(\"bad-txns-inputs-missingorspent\");\n+        WindowStepper stepper{chainman};\n+        stepper.Start([&] { activated = chainstate.ActivateBestChain(state); });\n+        stepper.WaitForStep(m_base_height, 4);\n+        stepper.RunLowestBlock();\n+        stepper.WaitForStep(m_base_height + 1, 3);\n+        {\n+            // The connector commits and publishes under cs_main. Held here, the three blocks are complete\n+            // before any of them is committed, and each was validated with the coin in the store.\n+            LOCK(::cs_main);\n+            for (int i{0}; i < 3; ++i) stepper.RunLowestBlock();\n+        }\n+        stepper.Finish();\n+    }\n+    BOOST_CHECK(activated);\n+    BOOST_CHECK(state.IsValid());\n+    BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_SUCCESS);\n+    {\n+        LOCK(::cs_main);\n+        BOOST_CHECK(chainstate.m_chain.Tip() == lower_index);\n+        BOOST_CHECK((upper_index->nStatus & BLOCK_FAILED_VALID) != 0);\n+        const CCoinsViewCache& coins{chainstate.CoinsTip()};\n+        // The lower block's changes are there, and nothing of the two blocks above it.\n+        BOOST_CHECK(!coins.HaveCoin(coin));\n+        BOOST_CHECK(coins.HaveCoin(COutPoint{lower_spend->GetHash(), 0}));\n+        BOOST_CHECK(coins.HaveCoin(COutPoint{lower.vtx[0]->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{upper_spend->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{upper.vtx[0]->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{above.vtx[0]->GetHash(), 0}));\n+    }\n+    m_node.validation_signals->SyncWithValidationInterfaceQueue();\n+    m_node.validation_signals->UnregisterSharedValidationInterface(m_recorder);\n+    CheckAccountsEmpty();\n+    const std::vector<int> expected{m_base_height + 1, m_base_height + 2};\n+    const std::lock_guard lock{m_recorder->mutex};\n+    BOOST_CHECK_EQUAL_COLLECTIONS(m_recorder->connected.begin(), m_recorder->connected.end(), expected.begin(), expected.end());\n+}\n+\n //! The window's account is the node's, and only a step that uses the window writes it: a block connected\n //! outside the window leaves its limit and its co\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 652,
    "evidence_id": "101a4f525388442fbeb89fe9e85efee2",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 503,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/test/validation_chainstate_tests.cpp",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "    {\n        ReleaseWorkers();\n        m_connector.join();\n    }\n\n    //! The tip's height, or nothing while another thread holds cs_main: the wait below is not to hang on a\n    //! connector that waits under the lock for a block no worker runs.\n    std::optional<int> TipHeight() const\n    {\n        TRY_LOCK(::cs_main, locked);\n        if (!locked) return std::nullopt;\n        return m_chainman.ActiveChain().Height();\n    }\n\n    //! Wait until the connector is at rest with `height` as the tip and `queued` blocks handed to the pool.\n    void WaitForStep(int height, size_t queued)\n    {\n        const auto deadline{SteadyClock::now() + 60s};\n        while (true) {\n            const std::optional<int> tip{TipHeight()};\n            const size_t in_queue{m_pool.WorkQueueSize()};\n            if (tip == height && in_queue == queued) return;\n            BOOST_REQUIRE_MESSAGE(SteadyClock::now() < deadline,\n                                  strprintf(\"the step did not reach height %d with %u blocks queued: height %s, %u queued\",\n                                            height, queued, tip ? util::ToString(*tip) : \"unknown (cs_main is held)\", in_queue));\n            UninterruptibleSleep(1ms);\n        }\n    }\n\n    //! Run the task of the lowest block in flight, here.\n    void RunLowestBlock() { BOOST_REQUIRE(m_pool.ProcessTask()); }\n};\n\n//! The signals of a window step, as a subscriber gets them.\nstruct WindowStepRecorder final : CValidationInterface {\n    std::mutex mutex;\n    std::vector<int> connected;\n    std::vector<std::pair<int, bool>> tips;\n    void BlockConnected(const kernel::ChainstateRole&, const std::shared_ptr<const CBlock>&, const CBlockIndex* index) override\n    {\n        const std::lock_guard lock{mutex};\n        connected.push_back(index->nHeight);\n    }\n    void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex*, bool initial_download) override\n    {\n        const std::lock_guard lock{mutex};\n        tips.emplace_back(index->nHeight, initial_download);\n    }\n};\n\n//! A chain of BLOCKS blocks above the fixture's, stored and never connected (their undo data is still to be\n//! written), with the node in initial block download and its tip too old to leave it: what the next\n//! ActivateBestChain() connects in the window.\nstruct WindowStepSetup : TestChain100Setup {\n    static constexpr int BLOCKS{6};\n    int m_base_height{0};\n    std::shared_ptr<WindowStepRecorder> m_recorder{std::make_shared<WindowStepRecorder>()};\n\n    WindowStepSetup()\n    {\n        ChainstateManager& chainman{*Assert(m_node.chainman)};\n        Chainstate& chainstate{chainman.ActiveChainstate()};\n        m_base_height = WITH_LOCK(::cs_main, return chainstate.m_chain.Height());\n        // The blocks are made by a chain that is connected and then set aside for good. A copy of each with\n        // another nonce, on top of the copy below it, is stored: a block that was never connected.\n        std::vector<CBlock> blocks;\n        for (int i{0}; i < BLOCKS; ++i) blocks.push_back(CreateAndProcessBlock({}, CScript() << OP_TRUE));\n        CBlockIndex* const first{WITH_LOCK(::cs_main, return chainstate.m_chain[m_base_height + 1])};\n        const int64_t tip_time{WITH_LOCK(::cs_main, return chainstate.m_chain.Tip()->GetBlockTime())};\n        BlockValidationState state;\n        BOOST_REQUIRE(chainstate.InvalidateBlock(state, first));\n        m_node.validation_signals->SyncWithValidationInterfaceQueue();\n        // The blocks' signals held them in the pinned account, and their disconnection found it empty.\n        CheckAccountsEmpty();\n        {\n            LOCK(::cs_main);\n            uint256 prev{first->pprev->GetBlockHash()};\n            for (CBlock& block : blocks) {\n                block.hashPrevBlock = prev;\n                ++block.nNonce;\n                while (!CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus())) ++block.nNonce;\n                BlockValidationState accept_state;\n                CBlockIndex* index{nullptr};\n                bool new_block{false};\n                BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(block), accept_state, &index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n                BOOST_REQUIRE(new_block && index && index->GetUndoPos().IsNull());\n                prev = block.GetHash();\n            }\n        }\n        m_clock.set(std::chrono::seconds{tip_time} + 48h);\n        static_cast<TestChainstateManager&>(chainman).ResetIbd();\n        BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height);\n        BOOST_REQUIRE_GT(chainman.ConnectWindow(), 1);\n        m_node.validation_signals->RegisterSharedValidationInterface(m_recorder);\n    }\n\n    int Top() const { return m_base_height + BLOCKS; }\n\n    //! Put the blocks from the base up to `top` (the best header if none is given) in the block cache, as\n    //! blocks that were just received are. No task reads a file then, and the tasks are queued in the\n    //! blocks' order, which WindowStepper relies on: a block on disk is read on a block I/O thread, which\n    //! queues the block's task when its read is done, in no order with the others.\n    void CacheStepBlocks(const CBlockIndex* top = nullptr)\n    {\n        ChainstateManager& chainman{*Assert(m_node.chainman)};\n        BOOST_REQUIRE_GT(chainman.m_block_cache.Budget(), 0U);\n        if (!top) top = WITH_LOCK(::cs_main, return chainman.m_best_header);\n        for (const CBlockIndex* index{top}; index->nHeight > m_base_height; index = index->pprev) {\n            const auto block{std::make_shared<CBlock>()};\n            BOOST_REQUIRE(chainman.m_blockman.ReadBlock(*block, *index));\n            chainman.m_block_cache.Insert(index->nHeight, block, m_base_height);\n        }\n    }\n\n    //! Store a copy of the block at `original` on top of `parent`, with `extra` as one transaction more.\n    std::pair<CBlock, CBlockIndex*> StoreSibling(const CBlockIndex& original, const uint256& parent, const CTransactionRef& extra = nullptr)\n    {\n        ChainstateManager& chainman{*Assert(m_node.chainman)};\n        CBlock block;\n        BOOST_REQUIRE(chainman.m_blockman.ReadBlock(block, original));\n        block.hashPrevBlock = parent;\n        if (extra) {\n            block.vtx.push_back(extra);\n            node::RegenerateCommitments(block, chainman);\n        }\n        while (!CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus())) ++block.nNonce;\n        LOCK(::cs_main);\n        BlockValidationState state;\n        CBlockIndex* index{nullptr};\n        bool new_block{false};\n        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(block), state, &index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n        BOOST_REQUIRE(new_block && index);\n        return {std::move(block), index};\n    }\n\n    //! The blocks in flight once the tip is at `height`.\n    size_t InFlightAt(int height) const\n    {\n        return static_cast<size_t>(std::min(Top() - height, Assert(m_node.chainman)->ConnectWindow()));\n    }\n\n    //! Every byte charged for a block in flight has been released.\n    void CheckAccountsEmpty() const\n    {\n        const ChainstateManager& chainman{*Assert(m_node.chainman)};\n        for (const util::ByteAccountId id : util::BYTE_ACCOUNTS) {\n            BOOST_CHECK_EQUAL(chainman.m_bytes_in_flight[id].Bytes(), 0U);\n        }\n    }\n",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45-par no longer limits window script verificationsrc/init.cppstill_present
Assessment

The new help continues to say that `-par` does not bound scripts verified on connect-pool threads, while `-prevoutfetchthreads` retains an independent default. The supplied change revises wording about received blocks but does not show either deriving the default pool from `-par` or a GUI control exposing the distinction.

path_diff: src/init.cpp; new_source: src/init.cpp

[
  {
    "evidence_id": "7a6b39da2c62453ca58a2f51f1e0b09f",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/init.cpp",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/init.cpp b/src/init.cpp\nindex a657568572..941ca734a5 100644\n--- a/src/init.cpp\n+++ b/src/init.cpp\n@@ -541,7 +541,7 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)\n     argsman.AddArg(\"-par=<n>\", strprintf(\"Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d). Blocks validated in parallel during initial block download have their scripts verified on the connect pool threads (-prevoutfetchthreads), which this option does not bound.\",\n         MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-blockcache=<n>\", strprintf(\"Keep accepted blocks in memory until they are connected, up to <n> MiB, so that a block that arrived before its parent is connected from the object received rather than read from disk and deserialized again (0 disables, default: %d, or the size of the coins cache where that is smaller, at least 32).\", DEFAULT_BLOCK_CACHE_BYTES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n-    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which process the blocks received from peers and validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched, received blocks are processed by the message handler and the blocks of a -connectwindow are validated one after another; with one thread received blocks are processed by the message handler as well, so that a thread stays free for connecting; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n+    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched and the blocks of a -connectwindow are validated one after another; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-connectwindow=<n>\", strprintf(\"Set how many blocks are validated at the same time during initial block download, each on a connect pool thread, with the blocks confirmed in order (0 = twice as many as there are connect pool threads, 1 or -noconnectwindow = one at a time, up to %d, default: 0; the blocks in flight are further bounded, by an estimate of what they hold, to an eighth of the coins cache in memory, at least 32 MiB)\", MAX_CONNECT_WINDOW), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n     argsman.AddArg(\"-persistmempool\", strprintf(\"Whether to save the mempool on shutdown and load on restart (default: %u)\", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n     argsman.AddArg(\"-pid=<file>\", strprintf(\"Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)\", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 567,
    "evidence_id": "0fab2e7cf9494fd9a30f795792c2e14e",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 511,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/init.cpp",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "    argsman.AddArg(\"-version\", \"Print version and exit\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#if HAVE_SYSTEM\n    argsman.AddArg(\"-alertnotify=<cmd>\", \"Execute command when an alert is raised (%s in cmd is replaced by message)\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#endif\n    argsman.AddArg(\"-assumevalid=<hex>\", strprintf(\"If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet3: %s, testnet4: %s, signet: %s)\", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnet4ChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksdir=<dir>\", \"Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksxor\",\n                   strprintf(\"Whether an XOR-key applies to blocksdir *.dat files. \"\n                             \"The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is \"\n                             \"set, and random for a freshly initialized blocksdir. \"\n                             \"(default: %u)\",\n                             kernel::DEFAULT_XOR_BLOCKSDIR),\n                   ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-fastprune\", \"Use smaller block files and lower minimum prune height for testing purposes\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n#if HAVE_SYSTEM\n    argsman.AddArg(\"-blocknotify=<cmd>\", \"Execute command when the best block changes (%s in cmd is replaced by block hash). Not run for blocks connected during initial block download or reindexing.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#endif\n    argsman.AddArg(\"-blockreconstructionextratxn=<n>\", strprintf(\"Extra transactions to keep in memory for compact block reconstructions (default: %u)\", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blocksonly\", strprintf(\"Whether to reject transactions from network peers. Disables automatic broadcast and rebroadcast of transactions, unless the source peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)\", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-coinstatsindex\", strprintf(\"Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)\", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-conf=<file>\", strprintf(\"Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)\", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-datadir=<dir>\", \"Specify data directory\", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-dbbatchsize\", strprintf(\"Maximum database write batch size in bytes (default: %u)\", DEFAULT_DB_CACHE_BATCH), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-dbcache=<n>\", strprintf(\"Maximum database cache size <n> MiB (minimum %d, default: %d). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).\", MIN_DBCACHE_BYTES / 1_MiB, node::GetDefaultDBCache() / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-includeconf=<file>\", \"Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-allowignoredconf\", strprintf(\"For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.\", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-loadblock=<file>\", \"Imports blocks from an external file on startup. Obfuscated blocks are not supported.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-maxmempool=<n>\", strprintf(\"Keep the transaction memory pool below <n> megabytes (default: %u)\", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-mempoolexpiry=<n>\", strprintf(\"Do not keep transactions in the mempool longer than <n> hours (default: %u)\", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-minimumchainwork=<hex>\", strprintf(\"Minimum work assumed to exist on a valid chain in hex (default: %s, testnet3: %s, testnet4: %s, signet: %s)\", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnet4ChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-par=<n>\", strprintf(\"Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d). Blocks validated in parallel during initial block download have their scripts verified on the connect pool threads (-prevoutfetchthreads), which this option does not bound.\",\n        MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blockcache=<n>\", strprintf(\"Keep accepted blocks in memory until they are connected, up to <n> MiB, so that a block that arrived before its parent is connected from the object received rather than read from disk and deserialized again (0 disables, default: %d, or the size of the coins cache where that is smaller, at least 32).\", DEFAULT_BLOCK_CACHE_BYTES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-prevoutfetchthreads=<n>\", strprintf(\"Set the number of connect pool threads, which validate blocks in parallel during initial block download, and prefetch block input prevouts from the chainstate database at the tip (0 = no pool threads: nothing is prefetched and the blocks of a -connectwindow are validated one after another; up to %d, default: the number of cores, at least %d). Negative values are rejected.\", MAX_PREVOUTFETCH_THREADS, MIN_DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-connectwindow=<n>\", strprintf(\"Set how many blocks are validated at the same time during initial block download, each on a connect pool thread, with the blocks confirmed in order (0 = twice as many as there are connect pool threads, 1 or -noconnectwindow = one at a time, up to %d, default: 0; the blocks in flight are further bounded, by an estimate of what they hold, to an eighth of the coins cache in memory, at least 32 MiB)\", MAX_CONNECT_WINDOW), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n    argsman.AddArg(\"-persistmempool\", strprintf(\"Whether to save the mempool on shutdown and load on restart (default: %u)\", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-pid=<file>\", strprintf(\"Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)\", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-prune=<n>\", strprintf(\"Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex. \"\n            \"Warning: Reverting this setting requires re-downloading the entire blockchain. Wallets and indexes should be loaded at startup and kept active while pruning is enabled so they stay synchronized before old block data is deleted; wallets or indexes that fall behind pruned data may require a reindex. \"\n            \"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)\", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-reindex\", \"If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-reindex-chainstate\", \"If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-settings=<file>\", strprintf(\"Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)\", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#if HAVE_SYSTEM\n    argsman.AddArg(\"-startupnotify=<cmd>\", \"Execute command on startup.\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-shutdownnotify=<cmd>\", \"Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n#endif\n    argsman.AddArg(\"-txindex\", strprintf(\"Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)\", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-txospenderindex\", strprintf(\"Maintain a transaction output spender index, used by the gettxspendingprevout rpc call (default: %u)\", DEFAULT_TXOSPENDERINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n    argsman.AddArg(\"-blockfilterindex=<type>\",\n                 strprintf(\"Maintain an index of compact filters by block (default: %s, values: %s).\", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +\n                 \" If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.\",\n                 ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n\n    argsman.AddArg(\"-addnode=<ip>\", strprintf(\"Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.\", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);\n    argsman.AddArg(\"-asmap=<file>\", strprintf(\"Specify asn mapping used for bucketing of the peers. Relative paths will be prefixed by the net-specific datadir location.%s\",\n                #ifdef ENABLE_EMBEDDED_ASMAP",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45The kernel callback reentrancy ban excludes safe undo readssrc/kernel/bitcoinkernel.hunclear
Assessment

The supplied new-head header excerpt changes flush-error documentation, but does not show the callback reentrancy prohibition or the spent-outputs read documentation. The evidence does not establish whether the blanket ban was narrowed or safe reads explicitly permitted.

path_diff: src/kernel/bitcoinkernel.h; new_source: src/kernel/bitcoinkernel.h

[
  {
    "evidence_id": "f637b09ebb9f43ef8fdae2ed7b08b0ec",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/kernel/bitcoinkernel.h",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h\nindex 06aa0bae85..632ca1c8ac 100644\n--- a/src/kernel/bitcoinkernel.h\n+++ b/src/kernel/bitcoinkernel.h\n@@ -540,7 +540,9 @@ typedef struct {\n     btck_NotifyProgress progress;           //!< Reports on current block synchronization progress.\n     btck_NotifyWarningSet warning_set;      //!< A warning issued by the kernel library during validation.\n     btck_NotifyWarningUnset warning_unset;  //!< A previous condition leading to the issuance of a warning is no longer given.\n-    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk.\n+    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk. No later write of the block\n+                                            //!< index and the chainstate succeeds in this run: the caller may still read,\n+                                            //!< but has to stop processing blocks and restart to write again.\n     btck_NotifyFatalError fatal_error;      //!< An unrecoverable system error encountered by the library.\n } btck_NotificationInterfaceCallbacks;\n \n@@ -1304,9 +1306,11 @@ BITCOINKERNEL_API void btck_chainstate_manager_options_set_worker_threads_num(\n  * called, the total cache defaults to 450 MiB. On top of it, whatever the\n  * total cache size: up to 128 MiB of accepted blocks kept in memory until they\n  * are connected, an eighth of the coins cache and 32 MiB at least for the\n- * blocks being connected, up to 64 MiB of undo data waiting to be written, and,\n- * with no limit in bytes, the blocks whose notifications wait for an undo\n- * write.\n+ * blocks being connected, up to 64 MiB of undo data waiting to be written, and\n+ * an eighth of the coins cache and 64 MiB at least for the blocks whose\n+ * notifications wait for an undo write (more while a reorganisation connects\n+ * its blocks). Further, 4 MiB for each chainstate that validated blocks beside\n+ * each other.\n  *\n  * @param[in] chainstate_manager_options Non-null, options to be set.\n  * @param[in] database_cache_bytes       The total database cache size in bytes. Values below 4 MiB are rejected.\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 623,
    "evidence_id": "21c4f196a2ba4a758b2c0b73d323e074",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 474,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/kernel/bitcoinkernel.h",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "#define btck_BlockValidationResult_MUTATED ((btck_BlockValidationResult)(4))         //!< the block's data didn't match the data committed to by the PoW\n#define btck_BlockValidationResult_MISSING_PREV ((btck_BlockValidationResult)(5))    //!< We don't have the previous block the checked one is built on\n#define btck_BlockValidationResult_INVALID_PREV ((btck_BlockValidationResult)(6))    //!< A block this one builds on is invalid\n#define btck_BlockValidationResult_TIME_FUTURE ((btck_BlockValidationResult)(7))     //!< block timestamp was > 2 hours in the future (or our clock is bad)\n#define btck_BlockValidationResult_HEADER_LOW_WORK ((btck_BlockValidationResult)(8)) //!< the block header may be on a too-little-work chain\n\n/**\n * Indicates the reason why a transaction failed validation. The subset of\n * values reachable depends on which validation function was used.\n */\ntypedef uint32_t btck_TxValidationResult;\n#define btck_TxValidationResult_UNSET               ((btck_TxValidationResult)(0))  //!< initial value. Tx has not yet been rejected\n#define btck_TxValidationResult_CONSENSUS           ((btck_TxValidationResult)(1))  //!< invalid by consensus rules\n#define btck_TxValidationResult_INPUTS_NOT_STANDARD ((btck_TxValidationResult)(2))  //!< inputs (covered by txid) failed policy rules\n#define btck_TxValidationResult_NOT_STANDARD        ((btck_TxValidationResult)(3))  //!< otherwise didn't meet local policy rules\n#define btck_TxValidationResult_MISSING_INPUTS      ((btck_TxValidationResult)(4))  //!< transaction was missing some of its inputs\n#define btck_TxValidationResult_PREMATURE_SPEND     ((btck_TxValidationResult)(5))  //!< transaction spends a coinbase too early, or violates locktime/sequence locks\n#define btck_TxValidationResult_WITNESS_MUTATED     ((btck_TxValidationResult)(6))  //!< witness may have been malleated or is prior to SegWit activation\n#define btck_TxValidationResult_WITNESS_STRIPPED    ((btck_TxValidationResult)(7))  //!< transaction is missing a witness\n#define btck_TxValidationResult_CONFLICT            ((btck_TxValidationResult)(8))  //!< tx already in mempool or conflicts with a tx in the chain\n#define btck_TxValidationResult_MEMPOOL_POLICY      ((btck_TxValidationResult)(9))  //!< violated mempool's fee/size/descendant/RBF/etc limits\n#define btck_TxValidationResult_NO_MEMPOOL          ((btck_TxValidationResult)(10)) //!< this node does not have a mempool so can't validate the transaction\n#define btck_TxValidationResult_RECONSIDERABLE      ((btck_TxValidationResult)(11)) //!< fails some policy, but might be acceptable if submitted in a (different) package\n#define btck_TxValidationResult_UNKNOWN             ((btck_TxValidationResult)(12)) //!< transaction was not validated because package failed\n\n/**\n * Holds the validation interface callbacks. The user data pointer may be used\n * to point to user-defined structures to make processing the validation\n * callbacks easier. Note that these callbacks block any further validation\n * execution when they are called. They may be called from an internal thread\n * and must not call back into the chainstate manager.\n */\ntypedef struct {\n    void* user_data;                                              //!< Holds a user-defined opaque structure that is passed to the validation\n                                                                  //!< interface callbacks. If user_data_destroy is also defined ownership of the\n                                                                  //!< user_data is passed to the created context options and subsequently context.\n    btck_DestroyCallback user_data_destroy;                       //!< Frees the provided user data structure.\n    btck_ValidationInterfaceBlockChecked block_checked;           //!< Called when a new block has been fully validated. Contains the\n                                                                  //!< result of its validation.\n    btck_ValidationInterfacePoWValidBlock pow_valid_block;        //!< Called when a new block extends the header chain and has a valid transaction\n                                                                  //!< and segwit merkle root.\n    btck_ValidationInterfaceBlockConnected block_connected;       //!< Called when a block is valid and has now been connected to the best chain.\n                                                                  //!< During initial block download it is called once the block's undo data\n                                                                  //!< is written, which may be after the block_tip notification of the block.\n    btck_ValidationInterfaceBlockDisconnected block_disconnected; //!< Called during a re-org when a block has been removed from the best chain.\n} btck_ValidationInterfaceCallbacks;\n\n/**\n * A struct for holding the kernel notification callbacks. The user data\n * pointer may be used to point to user-defined structures to make processing\n * the notifications easier.\n *\n * If user_data_destroy is provided, the kernel will automatically call this\n * callback to clean up user_data when the notification interface object is destroyed.\n * If user_data_destroy is NULL, it is the user's responsibility to ensure that\n * the user_data outlives the kernel objects. Notifications can\n * occur even as kernel objects are deleted, so care has to be taken to ensure\n * safe unwinding.\n */\ntypedef struct {\n    void* user_data;                        //!< Holds a user-defined opaque structure that is passed to the notification callbacks.\n                                            //!< If user_data_destroy is also defined ownership of the user_data is passed to the\n                                            //!< created context options and subsequently context.\n    btck_DestroyCallback user_data_destroy; //!< Frees the provided user data structure.\n    btck_NotifyBlockTip block_tip;          //!< The chain's tip was updated to the provided block entry.\n    btck_NotifyHeaderTip header_tip;        //!< A new best block header was added.\n    btck_NotifyProgress progress;           //!< Reports on current block synchronization progress.\n    btck_NotifyWarningSet warning_set;      //!< A warning issued by the kernel library during validation.\n    btck_NotifyWarningUnset warning_unset;  //!< A previous condition leading to the issuance of a warning is no longer given.\n    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk. No later write of the block\n                                            //!< index and the chainstate succeeds in this run: the caller may still read,\n                                            //!< but has to stop processing blocks and restart to write again.\n    btck_NotifyFatalError fatal_error;      //!< An unrecoverable system error encountered by the library.\n} btck_NotificationInterfaceCallbacks;\n\n/**\n * A collection of status codes that may be issued by the script verify function.\n */\ntypedef uint8_t btck_ScriptVerifyStatus;\n#define btck_ScriptVerifyStatus_OK ((btck_ScriptVerifyStatus)(0))\n#define btck_ScriptVerifyStatus_ERROR_INVALID_FLAGS_COMBINATION ((btck_ScriptVerifyStatus)(1)) //!< The flags were combined in an invalid way.\n#define btck_ScriptVerifyStatus_ERROR_SPENT_OUTPUTS_REQUIRED ((btck_ScriptVerifyStatus)(2))    //!< The taproot flag was set, so valid spent_outputs have to be provided.\n\n/**\n * Script verification flags that may be composed with each other.\n */\ntypedef uint32_t btck_ScriptVerificationFlags;\n#define btck_ScriptVerificationFlags_NONE ((btck_ScriptVerificationFlags)(0))\n#define btck_ScriptVerificationFlags_P2SH ((btck_ScriptVerificationFlags)(1U << 0))                 //!< evaluate P2SH (BIP16) subscripts\n#define btck_ScriptVerificationFlags_DERSIG ((btck_ScriptVerificationFlags)(1U << 2))               //!< enforce strict DER (BIP66) compliance\n#define btck_ScriptVerificationFlags_NULLDUMMY ((btck_ScriptVerificationFlags)(1U << 4))            //!< enforce NULLDUMMY (BIP147)\n#define btck_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY ((btck_ScriptVerificationFlags)(1U << 9))  //!< enable CHECKLOCKTIMEVERIFY (BIP65)\n#define btck_ScriptVerificationFlags_CHECKSEQUENCEVERIFY ((btck_ScriptVerificationFlags)(1U << 10)) //!< enable CHECKSEQUENCEVERIFY (BIP112)\n#define btck_ScriptVerificationFlags_WITNESS ((btck_ScriptVerificationFlags)(1U << 11))             //!< enable WITNESS (BIP141)\n#define btck_ScriptVerificationFlags_TAPROOT ((btck_ScriptVerificationFlags)(1U << 17))             //!< enable TAPROOT (BIPs 341 & 342)\n#define btck_ScriptVerificationFlags_ALL ((btck_ScriptVerificationFlags)(btck_ScriptVerificationFlags_P2SH |                \\\n                                                                         btck_ScriptVerificationFlags_DERSIG |              \\\n                                                                         btck_ScriptVerificationFlags_NULLDUMMY |           \\\n                                                                         btck_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY | \\\n                                                                         btck_ScriptVerificationFlags_CHECKSEQUENCEVERIFY | \\\n                                                                         btck_ScriptVerificationFlags_WITNESS |             \\\n                                                                         btck_ScriptVerificationFlags_TAPROOT))\n\ntypedef uint8_t btck_ChainType;\n#define btck_ChainType_MAINNET ((btck_ChainType)(0))\n#define btck_ChainType_TESTNET ((btck_ChainType)(1))\n#define btck_ChainType_TESTNET_4 ((btck_ChainType)(2))\n#define btck_ChainType_SIGNET ((btck_ChainType)(3))\n#define btck_ChainType_REGTEST ((btck_ChainType)(4))\n\n/** @name TxValidationState\n *  Introspection for transaction validation state.\n */\n///@{\n\n/**\n * Create a new btck_TxValidationState.\n */\nBITCOINKERNEL_API btck_TxValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT btck_tx_validation_state_create();\n\n/**\n * Returns the validation mode from an opaque btck_TxValidationState pointer.\n */\nBITCOINKERNEL_API btck_ValidationMode btck_tx_validation_state_get_validation_mode(\n    const btck_TxValidationState* state) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * Returns the validation result from an opaque btck_TxValidationState pointer.\n *\n * btck_transaction_check currently produces only btck_TxValidationResult_UNSET\n * for valid transactions and btck_TxValidationResult_CONSENSUS for invalid\n * ones. Other values remain exposed for forward compatibility with higher-level\n * validation entry points.\n */\nBITCOINKERNEL_API btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(\n    const btck_TxValidationState* state) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * Destroy the btck_TxValidationState.\n */\nBITCOINKERNEL_API void btck_tx_validation_state_destroy(btck_TxValidationState* state);\n\n///@}\n\n/** @name Transaction\n * Functions for working with transactions.\n */\n///@{\n\n/**",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45Write-out completion bypasses the compaction free-space guardsrc/validation.cppunclear
Assessment

The follow-up assessment was invalid: addressed findings require original comparison evidence.

invalid_assessment

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#45Snapshot invalidation destroys views still used by staged connectionssrc/validation.cppstill_present
Assessment

The new head still resets `m_coins_views` before renaming the snapshot directory, and the supplied diff/source shows no drain or cancellation of staged connections before destruction. The finding’s lifetime hazard therefore remains.

path_diff: src/validation.cpp; new_source: src/validation.cpp

[
  {
    "evidence_id": "a0ee6fa915384b0196261fae9a591777",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/validation.cpp",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex f5d4abfeee..cf73b5ac30 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -118,12 +118,11 @@ static void CheckBlockStoreTransition(std::optional<node::BlockStoreState> befor\n \n /**\n  * The tasks validation runs where no caller is on the stack to decide what a std::runtime_error means\n- * (util/worker_task.h): a block's validation and its continuation on a connect pool worker, and a coins\n+ * (util/worker_task.h): a block's parse and its validation on a connect pool worker, and a coins\n  * write-out run and a block's undo write on the effects executor. Each reads or writes the node's own data,\n  * so each stops the node; the name is what the log and the fatal error begin with.\n  */\n static constexpr util::WorkerTaskType CONNECT_TASK{\"ConnectBlock\"};\n-static constexpr util::WorkerTaskType CONTINUATION_TASK{\"FinishDeferredTransactions\"};\n static constexpr util::WorkerTaskType WRITE_OUT_TASK{\"Coins write-out run failed\"};\n static constexpr util::WorkerTaskType UNDO_WRITE_TASK{\"Block undo write failed\"};\n \n@@ -1915,7 +1914,7 @@ BlockApplyView* CoinsViews::FreeApplyView()\n {\n     AssertLockHeld(::cs_main);\n     for (auto& view : m_apply_views) {\n-        if (!view->HasBlock()) return view.get();\n+        if (!view->InUse()) return view.get();\n     }\n     return nullptr;\n }\n@@ -2018,6 +2017,15 @@ void Chainstate::ResetCoinsViews()\n     m_coins_views.reset();\n }\n \n+//! The block a ChainStateFlushed names for coins written at `written`. Where that is the block being published,\n+//! one above the tip (precondition O8), its BlockConnected leaves after the signal, and a synced index would find\n+//! the locator off its chain and skip its commit: the signal names the tip, which the index has seen, and the\n+//! index catches up from there. Decided when the write starts, before the block's signal is queued.\n+static const CBlockIndex* FlushedSignalBlock(const CBlockIndex* written, const CChain& chain)\n+{\n+    return written && written != chain.Tip() && written->pprev == chain.Tip() ? written->pprev : written;\n+}\n+\n void Chainstate::SettleWriteOut()\n {\n     AssertLockHeld(::cs_main);\n@@ -2074,8 +2082,17 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n         bool for_prune;\n     };\n     const FlushTrace trace{NodeClock::now(), store.GetCacheSize(), store.DynamicMemoryUsage(), mode, for_prune};\n+    // See CommitGate. A commit that started first holds the run back.\n+    m_commit_gate.run_active.store(true);\n+    if (m_commit_gate.ahead.load() > 0) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     std::shared_ptr<CoinsStore::WriteOutRun> run{store.BeginWriteOut(bound_height, head->nHeight, head->GetBlockHash(), final)};\n-    if (!run) return true;\n+    if (!run) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     LogDebug(BCLog::COINDB, \"Starting a coins write-out run: changes at or below height %d, head %d%s\",\n              bound_height, head->nHeight, run->final ? \", final\" : \"\");\n \n@@ -2087,6 +2104,7 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n     // one state of it. The head and its ancestors do not change in the block index, so the effect looks the\n     // settled head up there.\n     auto index_batch{std::make_shared<node::BlockManager::IndexBatch>(m_blockman.PrepareBlockIndexBatch())};\n+    const CBlockIndex* signal_at{FlushedSignalBlock(head, m_chain)};\n     node::BlockManager& blockman{m_blockman};\n     CCoinsViewDB& db{CoinsDB()};\n     m_blockman.m_effects.Enqueue(\n@@ -2113,17 +2131,19 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (failure) LogError(\"%s\", failure->what);\n             return written || fail();\n         },\n-        [this, run, evict_to, trace](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n+        [this, run, evict_to, trace, signal_at](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n             AssertLockHeld(::cs_main);\n             if (!m_coins_views || !m_coins_views->m_store) return;\n             CoinsStore& store{CoinsStoreTip()};\n             if (!ok) {\n+                // A failed run never ends, and the commits stay off: the node is stopping.\n                 store.AbandonWriteOut();\n                 ++m_write_out_runs_failed;\n                 m_chainman.GetNotifications().fatalError(_(\"System error while writing the chainstate to disk.\"));\n                 return;\n             }\n             store.CommitWriteOut(*run);\n+            m_commit_gate.run_active.store(false);\n             (void)trace;\n             TRACEPOINT(utxocache, flush,\n                 int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - trace.start)},\n@@ -2137,29 +2157,34 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (evict_to) store.EvictClean(*evict_to);\n             m_last_flushed_block = m_blockman.LookupBlockIndex(run->new_head);\n             if (m_chainman.m_options.signals) {\n-                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n-            }\n-            if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n-                try {\n-                    CoinsDB().CompactFullAsync();\n-                } catch (const std::system_error& e) { // what std::async throws when no thread can be started\n-                    LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n-                }\n+                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(signal_at));\n             }\n+            // As after a synchronous write, with its check of the room a compaction needs.\n+            MaybeCompactChainstate();\n         },\n         0);\n     return true;\n }\n \n+node::BlockCache::Tips ChainstateManager::BlockCacheTips() const\n+{\n+    AssertLockHeld(::cs_main);\n+    node::BlockCache::Tips tips{.active = ActiveHeight()};\n+    if (const Chainstate* historical{HistoricalChainstate()}) {\n+        if (const CBlockIndex* base{CurrentChainstate().SnapshotBase()}) {\n+            tips.historical = historical->m_chain.Height();\n+            tips.historical_end = base->nHeight;\n+        }\n+    }\n+    return tips;\n+}\n+\n int ChainstateManager::ConnectWindow() const\n {\n     // By default twice as wide as the pool. The blocks are confirmed in order, so a window as wide as the\n     // pool leaves a worker without a block whenever one behind the oldest finishes first. What the blocks\n     // in flight hold in memory is bounded separately, by bytes (WINDOW_BYTES_SHARE).\n     const int window{m_options.connect_window > 0 ? m_options.connect_window : 2 * static_cast<int>(m_connect_pool->WorkersCount())};\n-    // No block of a window spends the coinbase of another, which the coin store's write-out rests on\n-    // (CoinsStore::CollectRecords()).\n-    static_assert(MAX_CONNECT_WINDOW < COINBASE_MATURITY);\n     return std::clamp(window, 1, MAX_CONNECT_WINDOW);\n }\n \n@@ -2734,29 +2759,12 @@ BlockValidationContext ChainstateManager::MakeBlockValidationContext(const uint2\n         .enforce_bip30 = EnforceBIP30(block_hash, prev ? prev->nHeight + 1 : 0, prev, GetConsensus(), GetParams().Bip30Off()),\n         // Callable without cs_main, see BlockValidationContext::median_time_past_at.\n         .median_time_past_at = [prev](int height) { return Assert(Assert(prev)->GetAncestor(height))->GetMedianTimePast(); },\n-        .defer_missing_inputs = false,\n     };\n }\n \n \n-\n-//! Whether BIP30 is checked for the block or for one that can be open in the connect window below it.\n-//! Such a block's spends leave a marker in the store even of a coin never written, so that a lower block\n-//! that makes the outpoint again does not find it gone (CoinsStore::BeginBlock()). The check is on below\n-//! BIP34 and from the height where it is on again (EnforceBIP30()), so the block and the lowest that can\n-//! be open with it decide. The two blocks below BIP34 that are exempt from the check, 91842 and 91880\n-//! (IsBIP30Repeat()), do not change that: where one of them is the block, the lowest that can be open with\n-//! it is checked, and where one of them is the lowest, the block is checked.\n-//! A block connected alone has no block open below it, and needs no marker.\n-static bool OpenBlocksCheckBIP30(const CBlockIndex& pindex, const Consensus::Params& params, bool bip30_off)\n-{\n-    if (!pindex.pprev || ConnectBlockChecksBIP30(pindex, params, bip30_off)) return true; // the genesis block spends nothing\n-    const int lowest{std::max(1, pindex.nHeight - static_cast<int>(CoinsStore::MAX_WINDOW_SLOTS))};\n-    return ConnectBlockChecksBIP30(*Assert(pindex.GetAncestor(lowest)), params, bip30_off);\n-}\n-\n //! Add a transaction's signature operations to the block's and check the block's limit. One copy of the rule,\n-//! for a coinbase, a transaction checked in order and a deferred one.\n+//! for a coinbase and for any other transaction.\n static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view, script_verify_flags flags,\n                            int64_t& sigops_cost, BlockValidationState& state)\n {\n@@ -2771,36 +2779,19 @@ static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view,\n     return true;\n }\n \n-//! Check that the coinbase pays no more than the subsidy and the block's fees. One copy of the rule, for a\n-//! block whose fees ConnectBlock() totalled and one whose total FinishDeferredTransactions() completed.\n-static bool CheckCoinbaseAmount(const CBlock& block, const BlockValidationContext& ctx, CAmount fees, BlockValidationState& state)\n-{\n-    const CAmount block_reward{fees + GetBlockSubsidy(ctx.height, ctx.params)};\n-    if (block.vtx[0]->GetValueOut() > block_reward) {\n-        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-cb-amount\",\n-                             strprintf(\"coinbase pays too much (actual=%d vs limit=%d)\", block.vtx[0]->GetValueOut(), block_reward));\n-    }\n-    return true;\n-}\n-\n //! The consensus checks of one transaction that is not a coinbase against the coins in `view`, in their order:\n //! its inputs and fee, the block's accumulated fee, BIP68, the block's signature operations, and, if\n //! `check_scripts`, its scripts, run here or appended to `checks` for a check queue. The block's totals `fees`\n //! and `sigops_cost` grow by the transaction's. False, with `state` set, on a failure, which is the block's.\n-//! Shared by ConnectBlock() and FinishDeferredTransactions(). `inputs_found`: the caller has found every\n-//! input of the transaction in the view, unspent, and the view is unchanged since, so the walk that looks\n-//! for a missing input is skipped.\n static bool CheckBlockTransaction(const CTransaction& tx, const BlockValidationContext& ctx, const CCoinsViewCache& view,\n                                   script_verify_flags flags, int lock_time_flags, bool check_scripts, bool cache_results,\n                                   PrecomputedTransactionData& txdata, ValidationCache& validation_cache,\n                                   std::vector<CScriptCheck>* checks, std::vector<int>& prevheights,\n-                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state,\n-                                  bool inputs_found = false)\n+                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state)\n {\n     CAmount txfee = 0;\n     TxValidationState tx_state;\n-    if (!(inputs_found ? Consensus::CheckAvailableTxInputs(tx, tx_state, view, ctx.height, txfee)\n-                       : Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee))) {\n+    if (!Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee)) {\n         // Any transaction validation failure in ConnectBlock is a block consensus failure\n         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,\n                              tx_state.GetRejectReason(),\n@@ -2872,8 +2863,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -2888,15 +2881,9 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n \n     // BIP30: no transaction may overwrite one that is not completely spent. Whether the rule\n     // applies to this block was decided when the context was built, see EnforceBIP30().\n-    if (ctx.enforce_bip30) {\n-        for (const auto& tx : block.vtx) {\n-            for (size_t o = 0; o < tx->vout.size(); o++) {\n-                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n-                                  \"tried to overwrite transaction\");\n-                }\n-            }\n-        }\n+    if (ctx.enforce_bip30 && view.HaveAnyOutput(block.vtx)) {\n+        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n+                      \"tried to overwrite transaction\");\n     }\n \n     // Enforce BIP68 (sequence locks)\n@@ -2929,8 +2916,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     }\n \n     std::vector<int> prevheights;\n-    //! This block's transaction ids in sorted order, built when the first transaction is deferred.\n-    std::vector<Txid> block_txids;\n     CAmount nFees = 0;\n     int& nInputs{result.num_inputs};\n     int64_t& nSigOpsCost{result.sigops_cost};\n@@ -2938,70 +2923,18 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     for (unsigned int i = 0; i < block.vtx.size(); i++)\n     {\n         if (!state.IsValid()) break;\n+        if (ctx.help_point && (i & 63) == 63) ctx.help_point();\n+        if (ctx.implicit_creates) ctx.implicit_creates(i);\n         const CTransaction &tx = *(block.vtx[i]);\n \n         nInputs += tx.vin.size();\n \n-        // In a block that may defer, a lower block in flight can show the outputs of a transaction while its\n-        // spends are still to be applied. A transaction with an unspent coin of its own txid among the coins\n-        // the view holds (HaveCoinInCache()) repeats an earlier one, whose inputs it shares and which spent\n-        // them: no lower block can make it valid, and creating its outputs would overwrite that coin, which\n-        // the view refuses with an exception. A coin of the store the view did not fetch, or one this block\n-        // spent before the repeat, is met at the apply as a conflict (BlockApplyView::ApplyChanges()). The\n-        // block fails here, which in the window decides nothing: it is connected again alone, where BIP30 or\n-        // the spent inputs reject it.\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs) {\n-            for (uint32_t o{0}; o < tx.vout.size(); ++o) {\n-                if (view.HaveCoinInCache(COutPoint{tx.GetHash(), o})) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + tx.GetHash().ToString() + \" repeats one with an unspent output\");\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-        }\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs && !view.HaveInputs(tx)) {\n-            // A lower block that is still being applied may hold the missing input. Not so for an input\n-            // from one of this block's own transactions: it is missing because it is produced later in the\n-            // block (or is this transaction's own, or was spent earlier), which validating in order rejects\n-            // at this point, and so does this.\n-            if (block_txids.empty()) {\n-                block_txids.reserve(block.vtx.size());\n-                for (const auto& block_tx : block.vtx) block_txids.push_back(block_tx->GetHash());\n-                std::sort(block_txids.begin(), block_txids.end());\n-                // A transaction the block holds twice. No lower block can make that valid: the second\n-                // copy spends what the first spent. (The merkle root's check for mutation only catches\n-                // copies that are paired in the tree.) Its outputs must not be created a second time.\n-                if (const auto twice{std::adjacent_find(block_txids.begin(), block_txids.end())}; twice != block_txids.end()) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + twice->ToString() + \" is in the block twice\");\n-                    break;\n-                }\n-            }\n-            for (const CTxIn& txin : tx.vin) {\n-                if (std::binary_search(block_txids.begin(), block_txids.end(), txin.prevout.hash) && !view.HaveCoin(txin.prevout)) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"input from this block missing or spent in transaction \" + tx.GetHash().ToString());\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-            // The transaction's outputs are created now, so that later transactions of this block can spend\n-            // them; everything else about it waits for FinishDeferredTransactions(), as do the block's totals.\n-            result.deferred_txs.push_back(i);\n-            if (i > 0) blockundo.vtxundo.emplace_back();\n-            AddCoins(view, tx, ctx.height);\n-            continue;\n-        }\n-\n         if (!tx.IsCoinBase()) {\n             const bool fCacheResults = just_check; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */\n             std::vector<CScriptCheck> vChecks;\n             PrecomputedTransactionData own_txdata;\n-            // In a block that may defer, the test above found every input (or the transaction was deferred).\n             if (!CheckBlockTransaction(tx, ctx, view, flags, nLockTimeFlags, fScriptChecks, fCacheResults, control ? txsdata[i] : own_txdata, validation_cache,\n-                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state,\n-                                       /*inputs_found=*/ctx.defer_missing_inputs)) {\n+                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state)) {\n                 break;\n             }\n             if (control) control->Add(std::move(vChecks));\n@@ -3014,14 +2947,27 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         if (i > 0) {\n             blockundo.vtxundo.emplace_back();\n         }\n-        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), ctx.height);\n+        if (ctx.implicit_creates) {\n+            // The inputs are spent; the outputs are the window's (WindowOutputs), and never the view's.\n+            if (i > 0) {\n+                CTxUndo& txundo{blockundo.vtxundo.back()};\n+                txundo.vprevout.reserve(tx.vin.size());\n+                for (const CTxIn& txin : tx.vin) {\n+                    txundo.vprevout.emplace_back();\n+                    const bool is_spent{view.SpendCoin(txin.prevout, &txundo.vprevout.back())};\n+                    assert(is_spent);\n+                }\n+            }\n+        } else {\n+     \n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 8718,
    "evidence_id": "1f66fb0137744d00b85a913a34dd5ee5",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 8569,
    "new_head": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "old_head": "6593eaa05b0cfee2a3ba757ed4f363a76cde3870",
    "path": "src/validation.cpp",
    "revision": "981564bf75bec0e60b53a68bbaab64e7300856cb",
    "source_generation": 3,
    "source_job_id": 2998,
    "text": "                rangePar.first++;\n            }\n            // Proceed to the next one.\n            rangePar.first++;\n            if (rangePar.first != rangePar.second) {\n                // Move to a sibling not part of the best header chain.\n                pindex = rangePar.first->second;\n                break;\n            } else if (pindexPar == best_hdr_chain[nHeight - 1]) {\n                // Move to pindex's sibling on the best-chain, if it has one.\n                pindex = best_hdr_chain[nHeight];\n                // There will not be a next block if (and only if) parent block is the best header.\n                assert((pindex == nullptr) == (pindexPar == best_hdr_chain.Tip()));\n                break;\n            } else {\n                // Move up further.\n                pindex = pindexPar;\n                nHeight--;\n                continue;\n            }\n        }\n    }\n\n    // Check that we actually traversed the entire block index.\n    assert(nNodes == forward.size() + best_hdr_chain.Height() + 1);\n}\n\nstd::string Chainstate::ToString()\n{\n    AssertLockHeld(::cs_main);\n    CBlockIndex* tip = m_chain.Tip();\n    return strprintf(\"Chainstate [%s] @ height %d (%s)\",\n                     m_from_snapshot_blockhash ? \"snapshot\" : \"ibd\",\n                     tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : \"null\");\n}\n\nbool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)\n{\n    AssertLockHeld(::cs_main);\n    if (coinstip_size == m_coinstip_cache_size_bytes &&\n            coinsdb_size == m_coinsdb_cache_size_bytes) {\n        // Cache sizes are unchanged, no need to continue.\n        return true;\n    }\n    size_t old_coinstip_size = m_coinstip_cache_size_bytes;\n    m_coinstip_cache_size_bytes = coinstip_size;\n    // The share of the coins database's cache is recorded only: the database keeps the cache it was\n    // opened with (at most MAX_COINS_DB_CACHE), since reopening it would replace the LevelDB instance\n    // under the connect window's workers, which read it without cs_main.\n    m_coinsdb_cache_size_bytes = coinsdb_size;\n\n    LogInfo(\"[%s] resized coinstip cache to %.1f MiB\",\n        this->ToString(), coinstip_size / double(1_MiB));\n\n    BlockValidationState state;\n    bool ret;\n\n    if (coinstip_size > old_coinstip_size) {\n        // Likely no need to flush if cache sizes have grown.\n        ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);\n    } else {\n        // Otherwise, flush state to disk and deallocate the in-memory coins map.\n        ret = FlushStateToDisk(state, FlushStateMode::FORCE_FLUSH);\n    }\n    return ret;\n}\n\ndouble ChainstateManager::GuessVerificationProgress(const CBlockIndex* pindex) const\n{\n    AssertLockHeld(GetMutex());\n    const ChainTxData& data{GetParams().TxData()};\n    if (pindex == nullptr) {\n        return 0.0;\n    }\n\n    if (pindex->m_chain_tx_count == 0) {\n        LogDebug(BCLog::VALIDATION, \"Block %d has unset m_chain_tx_count. Unable to estimate verification progress.\\n\", pindex->nHeight);\n        return 0.0;\n    }\n\n    const int64_t nNow{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};\n    const auto block_time{\n        (Assume(m_best_header) && std::abs(nNow - pindex->GetBlockTime()) <= Ticks<std::chrono::seconds>(2h) &&\n         Assume(m_best_header->nHeight >= pindex->nHeight)) ?\n            // When the header is known to be recent, switch to a height-based\n            // approach. This ensures the returned value is quantized when\n            // close to \"1.0\", because some users expect it to be. This also\n            // avoids relying too much on the exact miner-set timestamp, which\n            // may be off.\n            nNow - (m_best_header->nHeight - pindex->nHeight) * GetConsensus().nPowTargetSpacing :\n            pindex->GetBlockTime(),\n    };\n\n    double fTxTotal;\n\n    if (pindex->m_chain_tx_count <= data.tx_count) {\n        fTxTotal = data.tx_count + (nNow - data.nTime) * data.dTxRate;\n    } else {\n        fTxTotal = pindex->m_chain_tx_count + (nNow - block_time) * data.dTxRate;\n    }\n\n    return std::min<double>(pindex->m_chain_tx_count / fTxTotal, 1.0);\n}\n\ndouble ChainstateManager::GetBackgroundVerificationProgress(const CBlockIndex& pindex) const\n{\n    AssertLockHeld(GetMutex());\n    Assert(HistoricalChainstate());\n    auto target_block = HistoricalChainstate()->TargetBlock();\n\n    if (pindex.m_chain_tx_count == 0 || target_block->m_chain_tx_count == 0) {\n        LogDebug(BCLog::VALIDATION, \"[background validation] Block %d has unset m_chain_tx_count. Unable to estimate verification progress.\", pindex.nHeight);\n        return 0.0;\n    }\n    return static_cast<double>(pindex.m_chain_tx_count) / static_cast<double>(target_block->m_chain_tx_count);\n}\n\nChainstate& ChainstateManager::InitializeChainstate(CTxMemPool* mempool)\n{\n    AssertLockHeld(::cs_main);\n    assert(m_chainstates.empty());\n    m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool, m_blockman, *this));\n    return *m_chainstates.back();\n}\n\n[[nodiscard]] static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot)\n    EXCLUSIVE_LOCKS_REQUIRED(::cs_main)\n{\n    AssertLockHeld(::cs_main);\n\n    if (is_snapshot) {\n        fs::path base_blockhash_path = db_path / node::SNAPSHOT_BLOCKHASH_FILENAME;\n\n        try {\n            bool existed = fs::remove(base_blockhash_path);\n            if (!existed) {\n                LogWarning(\"[snapshot] snapshot chainstate dir being removed lacks %s file\",\n                          fs::PathToString(node::SNAPSHOT_BLOCKHASH_FILENAME));\n            }\n        } catch (const fs::filesystem_error& e) {\n            LogWarning(\"[snapshot] failed to remove file %s: %s\\n\",\n                       fs::PathToString(base_blockhash_path), e.code().message());\n        }\n    }\n\n    std::string path_str = fs::PathToString(db_path);\n    LogInfo(\"Removing leveldb dir at %s\\n\", path_str);\n\n    // We have to destruct before this call leveldb::DB in order to release the db\n    // lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 6593eaa05b0c..981564bf75be

2026-11-24T23:03:55Z · gpt-6-luna

fork#44Busy-pool fallback and late flush helpers lack deterministic coveragesrc/coinsstore.cppunclear
Assessment

The follow-up assessment was invalid: unknown follow-up evidence ID.

invalid_assessment

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44CoinsStore crash-prefix coverage bypasses ReplayBlocks()src/test/coinsstore_tests.cppstill_present
Assessment

The new crash-prefix test still uses a cache over the DB to replay heights directly after a cut; the excerpt does not exercise marker-derived fork selection or Chainstate::ReplayBlocks() with a real branch change.

path_diff: src/test/coinsstore_tests.cpp; new_source: src/test/coinsstore_tests.cpp

[
  {
    "evidence_id": "2e84dcb300d8493da08bac9da908c6fe",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/test/coinsstore_tests.cpp",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/test/coinsstore_tests.cpp b/src/test/coinsstore_tests.cpp\nindex 887f124ae9..55973c6eaa 100644\n--- a/src/test/coinsstore_tests.cpp\n+++ b/src/test/coinsstore_tests.cpp\n@@ -5,19 +5,22 @@\n #include <coins.h>\n #include <coinsstore.h>\n #include <dbwrapper.h>\n+#include <primitives/block.h>\n #include <script/script.h>\n #include <test/util/coinsstore.h>\n #include <test/util/random.h>\n #include <test/util/setup_common.h>\n #include <txdb.h>\n+#include <undo.h>\n #include <util/threadpool.h>\n #include <util/byte_units.h>\n \n #include <boost/test/unit_test.hpp>\n \n #include <algorithm>\n-#include <array>\n #include <functional>\n+#include <atomic>\n+#include <future>\n #include <limits>\n #include <map>\n #include <memory>\n@@ -101,12 +104,20 @@ std::vector<COutPoint> Universe(uint32_t txids)\n     return out;\n }\n \n-//! Block `block` creates `outpoint`: a batch of the one change.\n-void Create(CoinsStore& store, CoinsStore::BlockId block, const COutPoint& outpoint, Coin coin, bool possible_overwrite)\n+//! The block at `height` creates `outpoint`: the one confirmed change. Returns the number of conflicts.\n+uint32_t Create(CoinsStore& store, int height, const COutPoint& outpoint, Coin coin, bool possible_overwrite)\n {\n     std::vector<OwnedChange> changes;\n     changes.push_back({.outpoint = outpoint, .coin = std::move(coin), .possible_overwrite = possible_overwrite});\n-    ApplyBatch(store, block, std::move(changes));\n+    return ApplyConfirmed(store, height, changes);\n+}\n+\n+//! The block at `height` spends `outpoint`, whichever coin is there. Returns the number of conflicts.\n+uint32_t Spend(CoinsStore& store, int height, const COutPoint& outpoint)\n+{\n+    std::vector<OwnedChange> changes;\n+    changes.push_back({.outpoint = outpoint, .coin = Coin{}});\n+    return ApplyConfirmed(store, height, changes);\n }\n \n //! A name for the block at `height`: any but the null hash.\n@@ -593,6 +604,9 @@ BOOST_AUTO_TEST_CASE(failed_run_ends_all_writes)\n     // A forced sync refuses as well: it would close the marker over what the failed run had collected.\n     BOOST_CHECK_THROW(store.Sync(), std::runtime_error);\n     BOOST_CHECK(!db.PeekCoin(outpoint));\n+    // And so does a run started directly.\n+    BOOST_CHECK_THROW(store.BeginWriteOut(/*bound_height=*/1, /*head_height=*/1, uint256::ONE, /*final=*/true), std::runtime_error);\n+    BOOST_CHECK(!store.RunInFlight());\n }\n \n //! Counts what is written through it: the runs, their changes, and what they come to as database batches.\n@@ -616,6 +630,49 @@ public:\n     }\n };\n \n+//! A flush whose helpers' pool is busy with tasks that wait (as the connect pool's receive tasks wait for\n+//! cs_main, which the flush's caller may hold) writes every range itself and returns; the helper tasks that come\n+//! up later find their ranges taken and return at once.\n+BOOST_AUTO_TEST_CASE(flush_with_a_busy_pool_writes_every_range_itself)\n+{\n+    if (std::thread::hardware_concurrency() < 2) return; // one core: the flush has one worker and no helpers\n+    static constexpr uint64_t BATCH{4000};\n+    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n+    CountingBase base{&db};\n+    auto pool{FlushHelpers()};\n+    std::promise<void> release;\n+    const std::shared_future<void> released{release.get_future().share()};\n+    std::atomic<int> waiting{0};\n+    for (size_t i{0}; i < pool->WorkersCount(); ++i) {\n+        BOOST_REQUIRE(pool->Submit([&waiting, released] { ++waiting; released.wait(); }));\n+    }\n+    while (waiting.load() < static_cast<int>(pool->WorkersCount())) std::this_thread::yield();\n+    {\n+        CoinsStore store{&base, 256, true};\n+        store.SetBaseWrites(BATCH, /*concurrent=*/true);\n+        store.SetFlushHelpers(pool);\n+        store.SetBestBlock(uint256::ONE, 1);\n+        std::map<COutPoint, Coin> expected;\n+        for (int i{0}; i < 2000; ++i) {\n+            const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), 0};\n+            Coin coin{RandomCoin(m_rng, 1)};\n+            expected.emplace(outpoint, coin);\n+            store.AddCoin(outpoint, std::move(coin), false);\n+        }\n+        store.Flush();\n+        BOOST_CHECK_EQUAL(store.GetCacheSize(), 0U);\n+        BOOST_CHECK(db.GetBestBlock() == uint256::ONE);\n+        for (const auto& [outpoint, coin] : expected) {\n+            const std::optional<Coin> found{db.PeekCoin(outpoint)};\n+            BOOST_REQUIRE(found);\n+            BOOST_CHECK(found->out == coin.out);\n+        }\n+        release.set_value();\n+        // The helper tasks queued behind the waiting ones run and return before the store goes.\n+        pool->Stop();\n+    }\n+}\n+\n //! A flush fills its batches across the shards up to the batch size, a batch not being a shard's worth of\n //! changes, with several workers writing; the database then holds every change and the tier is empty.\n BOOST_AUTO_TEST_CASE(flush_fills_batches_across_shards)\n@@ -883,8 +940,6 @@ BOOST_AUTO_TEST_CASE(streamed_run_in_chunks_of_one_change)\n     store_many.SanityCheck();\n }\n \n-//! Changes made under a block's identity are seen by appliers and not by readers until the block is\n-//! confirmed; unwinding makes them disappear; conflicts are told apart by height.\n //! A base whose n-th write fails, counted from one; no write fails while n is zero.\n class FailingAtBase final : public CCoinsViewBacked\n {\n@@ -993,148 +1048,10 @@ BOOST_AUTO_TEST_CASE(streamed_run_cut_at_any_write_is_completed_by_a_replay)\n     for (int fail_at{1}; fail_at <= writes; ++fail_at) BOOST_CHECK_EQUAL(run_cut_at(fail_at), fail_at);\n }\n \n-BOOST_AUTO_TEST_CASE(block_identity_visibility_and_conflicts)\n-{\n-    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n-    CoinsStore store{&db, 4, true};\n-    store.SetBestBlock(uint256::ONE, 1);\n-    const COutPoint old_coin{Txid::FromUint256(uint256{10}), 0};\n-    const COutPoint new_coin{Txid::FromUint256(uint256{11}), 0};\n-    store.AddCoin(old_coin, RandomCoin(m_rng, 1), false); // a confirmed coin...\n-    store.Sync();                                         // ...that is in the database, so spending it owes an erase\n-\n-    const auto b2{store.BeginBlock(2)};\n-    const auto b3{store.BeginBlock(3)};\n-    BOOST_CHECK_EQUAL(store.OpenBlocks(), 2U);\n-\n-    // Block 2 creates new_coin and spends old_coin.\n-    Create(store, b2, new_coin, RandomCoin(m_rng, 2), false);\n-    BOOST_CHECK(store.ApplySpend(b2, old_coin));\n-    // Readers: the create is invisible, the old coin still there.\n-    BOOST_CHECK(!store.HaveCoin(new_coin));\n-    BOOST_CHECK(store.HaveCoin(old_coin));\n-    // Appliers (block 3): the create is visible, the old coin spent.\n-    BOOST_CHECK(store.LookupFor(b3, new_coin).has_value());\n-    BOOST_CHECK(!store.LookupFor(b3, old_coin).has_value());\n-    // Block 3 spending old_coin too: block 2 is lower, block 3 is the offender.\n-    BOOST_CHECK(!store.ApplySpend(b3, old_coin));\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b3), 1U);\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b2), 0U);\n-    // Nothing of this is writable yet.\n-    BOOST_CHECK(!store.BeginWriteOut(1, 1, uint256::ONE, false));\n-    store.SanityCheck();\n-\n-    // Confirm block 2: readers now see the create and the spend; the entries are dirty and the run's to take.\n-    store.ConfirmBlock(b2);\n-    BOOST_CHECK(store.HaveCoin(new_coin));\n-    BOOST_CHECK(!store.HaveCoin(old_coin));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 2U); // new_coin to write, old_coin's erase\n-    auto run{WriteOut(store, 2, 2, uint256{2})};\n-    BOOST_CHECK_EQUAL(run->count, 2U);\n-    BOOST_CHECK(db.PeekCoin(new_coin).has_value());\n-    BOOST_CHECK(!db.PeekCoin(old_coin).has_value());\n-\n-    // Block 3 (the offender) is unwound: nothing of it remains. A fresh block 4 spends new_coin and is\n-    // then unwound: the coin is back for everyone.\n-    store.UnwindBlock(b3);\n-    const auto b4{store.BeginBlock(4)};\n-    BOOST_CHECK(store.ApplySpend(b4, new_coin));\n-    BOOST_CHECK(store.HaveCoin(new_coin));             // readers still see it\n-    BOOST_CHECK(!store.LookupFor(b4, new_coin));       // the applier does not\n-    store.UnwindBlock(b4);\n-    BOOST_CHECK(store.HaveCoin(new_coin));\n-    BOOST_CHECK_EQUAL(store.OpenBlocks(), 0U);\n-    store.SanityCheck();\n-\n-    // Displacement: a higher block spends first, a lower block then takes the coin; the higher block gets\n-    // the conflict.\n-    const auto b6{store.BeginBlock(6)};\n-    const auto b5{store.BeginBlock(5)};\n-    BOOST_CHECK(store.ApplySpend(b6, new_coin));\n-    BOOST_CHECK(store.ApplySpend(b5, new_coin));\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b6), 1U);\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b5), 0U);\n-    store.ConfirmBlock(b5);\n-    BOOST_CHECK(!store.HaveCoin(new_coin));\n-    store.UnwindBlock(b6);\n-    store.SanityCheck();\n-    // A coin created and spent inside the window leaves no trace once confirmed.\n-    const auto b7{store.BeginBlock(7)};\n-    const COutPoint ephemeral{Txid::FromUint256(uint256{12}), 0};\n-    Create(store, b7, ephemeral, RandomCoin(m_rng, 7), false);\n-    BOOST_CHECK(store.ApplySpend(b7, ephemeral));\n-    store.ConfirmBlock(b7);\n-    BOOST_CHECK(!store.HaveCoinInCache(ephemeral));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U); // only new_coin's erase from block 5\n-    store.SanityCheck();\n-}\n-\n-//! A confirmed coin that an open block spends is written by a run as the confirmed coin it still is, and the\n-//! settled height is not held down by it; the spend lands as an erase once the block confirms, and nothing\n-//! is owed if the block is unwound.\n-BOOST_AUTO_TEST_CASE(run_writes_a_confirmed_coin_an_open_block_spends)\n-{\n-    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n-    RunBase base{&db};\n-    CoinsStore store{&base, 4, true};\n-    store.SetBestBlock(uint256{1}, 1);\n-    const COutPoint a{Txid::FromUint256(uint256{10}), 0};\n-    const COutPoint b{Txid::FromUint256(uint256{11}), 0};\n-    store.AddCoin(a, RandomCoin(m_rng, 1), false); // confirmed, dirty, tagged 1\n-    store.AddCoin(b, RandomCoin(m_rng, 1), false);\n-\n-    const auto b2{store.BeginBlock(2)};\n-    BOOST_CHECK(store.ApplySpend(b2, a)); // a is held by block 2 now, still unspent for readers\n-    BOOST_CHECK(store.HaveCoin(a));\n-\n-    auto run{WriteOut(store, /*bound_height=*/1, /*head_height=*/1, uint256{1})};\n-    BOOST_CHECK_EQUAL(base.m_writes.size(), 2U); // a and b, both as coins\n-    for (const auto& w : base.m_writes) BOOST_CHECK(w.coin.has_value());\n-    BOOST_CHECK_EQUAL(run->settled_height, 1);\n-    BOOST_CHECK(db.HaveCoin(a));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n-\n-    // Block 2 confirms: the spend is a change the database does not have, so an erase is owed and written.\n-    store.ConfirmBlock(b2);\n-    store.SetBestBlock(uint256{2}, 2);\n-    BOOST_CHECK(!store.HaveCoin(a));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U);\n-    store.Sync();\n-    BOOST_CHECK(!db.HaveCoin(a));\n-    BOOST_CHECK(db.HaveCoin(b));\n-\n-    // The block confirming before the run lands: the spend changed the entry (spent now), so the run must\n-    // not settle it, and the erase stays owed.\n-    const COutPoint c{Txid::FromUint256(uint256{12}), 0};\n-    store.AddCoin(c, RandomCoin(m_rng, 2), false);\n-    const auto b3c{store.BeginBlock(3)};\n-    BOOST_CHECK(store.ApplySpend(b3c, c));\n-    base.m_in_flight = [&] {\n-        store.ConfirmBlock(b3c);\n-        store.SetBestBlock(uint256{3}, 3);\n-    };\n-    auto run_c{WriteOut(store, 2, 2, uint256{2})};\n-    BOOST_CHECK_EQUAL(run_c->count, 1U);\n-    BOOST_CHECK(db.HaveCoin(c));                   // the run wrote the coin\n-    BOOST_CHECK(!store.HaveCoin(c));               // spent in the tier\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U);  // the erase is still owed\n-    store.Sync();\n-    BOOST_CHECK(!db.HaveCoin(c));\n-\n-    // The same with the block unwound instead: the coin stays, clean, as the database has it.\n-    const auto b3{store.BeginBlock(3)};\n-    BOOST_CHECK(store.ApplySpend(b3, b));\n-    BOOST_CHECK(!store.BeginWriteOut(2, 2, uint256{2}, false)); // b was written already and is clean: nothing to carry\n-    store.UnwindBlock(b3);\n-    BOOST_CHECK(store.HaveCoin(b));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n-    store.SanityCheck();\n-}\n-\n //! A block that creates an outpoint over an erase the database is still owed keeps that erase on the books:\n-//! a run meanwhile writes it, the outpoint's confirmed value, so that the database a final run leaves is the\n-//! head's state; unwritten, it is owed still if the block is unwound and written over if the block confirms.\n-BOOST_AUTO_TEST_CASE(owed_erase_survives_a_create_and_its_unwind)\n+//! the entry stays filed at the height of the spend, under the coin, and the coin is written over the one\n+//! the database has.\n+BOOST_AUTO_TEST_CASE(owed_erase_survives_a_create)\n {\n     CCoinsViewDB db{MemoryDb(\"store\"), {}};\n     CoinsStore store{&db, 4, true};\n@@ -1146,53 +1063,25 @@ BOOST_AUTO_TEST_CASE(owed_erase_survives_a_create_and_its_unwind)\n     BOOST_CHECK(store.SpendCoin(x)); // spent, dirty: the erase is owed\n     BOOST_CHECK_EQUAL(*OldestDirty(store), 2);\n \n-    // An applied block re-creates x (a duplicate, as BIP30 allowed once), then is unwound.\n-    const auto b3{store.BeginBlock(3)};\n-    Create(store, b3, x, RandomCoin(m_rng, 3), false);\n-    BOOST_CHECK(!store.HaveCoin(x));          // readers: still spent\n-    BOOST_CHECK(store.LookupFor(b3, x).has_value());\n-    BOOST_CHECK_EQUAL(*OldestDirty(store), 2); // the owed erase keeps its tag\n-    store.UnwindBlock(b3);\n-    BOOST_CHECK(!store.HaveCoin(x));\n+    // Block 3 makes x again (a duplicate, as BIP30 allowed once).\n+    BOOST_CHECK_EQUAL(Create(store, 3, x, RandomCoin(m_rng, 3), false), 0U);\n+    store.SetBestBlock(uint256{3}, 3);\n+    BOOST_CHECK(store.HaveCoin(x));\n     BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U);\n-\n-    // Applied again, with a final run while the block is undecided: the erase lands, the block's coin stays\n-    // the block's, and nothing is owed when the block is unwound.\n-    const auto b3b{store.BeginBlock(3)};\n-    Create(store, b3b, x, RandomCoin(m_rng, 3), false);\n-    store.Sync();\n-    BOOST_CHECK(!db.HaveCoin(x));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n-    BOOST_CHECK(!store.HaveCoin(x));\n-    BOOST_CHECK(store.LookupFor(b3b, x).has_value());\n+    // The erase still owed keeps its tag, the spend at 2, under the coin made at 3.\n+    BOOST_CHECK_EQUAL(*OldestDirty(store), 2);\n     store.SanityCheck();\n-    store.UnwindBlock(b3b);\n-    BOOST_CHECK(!store.HaveCoinInCache(x));\n-    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n-\n-    // The same create confirming instead writes the new coin over the old.\n-    store.SetChangeHeight(4);\n-    store.AddCoin(x, RandomCoin(m_rng, 4), false);\n-    store.Sync();\n-    store.SetChangeHeight(5);\n-    BOOST_CHECK(store.SpendCoin(x));\n-    const auto b6{store.BeginBlock(6)};\n-    Create(store, b6, x, RandomCoin(m_rng, 6), false);\n-    store.ConfirmBlock(b6);\n-    store.SetBestBlock(uint256{6}, 6);\n-    BOOST_CHECK(store.HaveCoin(x));\n-    // The erase still owed keeps its tag, the spend at 5, under the coin made at 6.\n-    BOOST_CHECK_EQUAL(*OldestDirty(store), 5);\n     store.Sync();\n     const auto coin{db.PeekCoin(x)};\n     BOOST_REQUIRE(coin.has_value());\n-    BOOST_CHECK_EQUAL(coin->nHeight, 6U);\n+    BOOST_CHECK_EQUAL(coin->nHeight, 3U);\n+    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n     store.SanityCheck();\n }\n \n //! The tier's byte count stays exact for coins whose scripts are on the heap, through the two paths that\n-//! empty an entry and keep it: a spend with no taker for the coin, and the unwind of a create that went over\n-//! an erase still owed. (An emptied script gives its memory back, CScript::clear().)\n+//! empty an entry and keep it: a spend with no taker for the coin, and the spend of a coin made over an\n+//! erase still owed. (An emptied script gives its memory back, CScript::clear().)\n BOOST_AUTO_TEST_CASE(emptied_entries_count_no_script_bytes)\n {\n     CCoinsViewDB db{MemoryDb(\"store\"), {}};\n@@ -1205,9 +1094,9 @@ BOOST_AUTO_TEST_CASE(emptied_entries_count_no_script_bytes)\n     store.SetChangeHeight(2);\n     BOOST_CHECK(store.SpendCoin(x)); // no taker: the entry stays, spent and dirty\n     store.SanityCheck();\n-    const auto b3{store.BeginBlock(3)};\n-    Create(store, b3, x, big(3), false);\n-    store.UnwindBlock(b3); // the erase is owed still: the entry is emptied again\n+    Create(store, 3, x, big(3), false);\n+    store.SanityCheck();\n+    BOOST_CHECK_EQUAL(Spend(store, 4, x), 0U); // the erase is owed still: the entry is emptied again\n     BOOST_CHECK(!store.HaveCoin(x));\n     BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U);\n     store.SanityCheck();\n@@ -1238,10 +1127,8 @@ BOOST_AUTO_TEST_CASE(run_after_a_disconnect_below_the_written_head_is_final)\n     BOOST_CHECK(store.SpendCoin(x));\n     store.SetBestBlock(uint256{1});\n     store.SetTierHeight(1);\n-    // The same blocks are connected again, block 2 as a window block, and two more.\n-    const auto b2{store.BeginBlock(2)};\n-    Create(store, b2, x, RandomCoin(m_rng, 2), false);\n-    store.ConfirmBlock(b2);\n+    // The same blocks are connected again, and two more.\n+    Create(store, 2, x, RandomCoin(m_rng, 2), false);\n     for (uint8_t height{2}; height <= 5; ++height) store.SetBestBlock(uint256{height}, height);\n \n     // A run asked to stop at block 1 writes everything: the database keeps x.\n@@ -1266,200 +1153,36 @@ BOOST_AUTO_TEST_CASE(run_after_a_disconnect_below_the_written_head_is_final)\n     store.SanityCheck();\n }\n \n-//! A higher block that creates an outpoint before the lower block that creates it too (a duplicate the\n-//! higher block could not see, BIP30) is the one charged: the lower block takes the entry, the higher\n-//! block fails at its confirmation.\n-BOOST_AUTO_TEST_CASE(higher_block_creating_first_is_charged)\n-{\n-    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n-    CoinsStore store{&db, 4, true};\n-    store.SetBestBlock(uint256::ONE, 1);\n-    const COutPoint dup{Txid::FromUint256(uint256{10}), 0};\n-\n-    const auto b2{store.BeginBlock(2)};\n-    const auto b3{store.BeginBlock(3)};\n-    Create(store, b3, dup, RandomCoin(m_rng, 3), false); // block 3 first: nothing of block 2 is visible to it\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b3), 0U);\n-    Create(store, b2, dup, RandomCoin(m_rng, 2), false); // block 2 creates the same outpoint\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b3), 1U);\n-    BOOST_CHECK_EQUAL(store.ConflictCount(b2), 0U);\n-    BOOST_CHECK(store.LookupFor(b2, dup).has_value());\n-\n-    // Block 2 confirms; block 3 is unwound as a failed block, and the coin is block 2's.\n-    store.ConfirmBlock(b2);\n-    store.UnwindBlock(b3);\n-    const auto coin{store.PeekCoin(dup)};\n-    BOOST_REQUIRE(coin.has_value());\n-    BOOST_CHECK_EQUAL(coin->nHeight, 2U);\n-    store.SanityCheck();\n-}\n-\n-//! The block view: changes made through it land in the store under the block's identity, in-block\n-//! dependencies resolve through the view's own map, and confirm/unwind are the store's status flips.\n-//! The batch: a block's creates and spends applied in one pass per shard behave as the one-by-one calls do,\n-//! including the conflict with a lower block's spend and a spend whose entry left the tier meanwhile.\n-BOOST_AUTO_TEST_CASE(apply_batch_matches_one_by_one)\n-{\n-    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n-    CoinsStore store{&db, 4, true};\n-    store.SetBestBlock(uint256::ONE, 1);\n-    const COutPoint a{Txid::FromUint256(uint256{10}), 0};\n-    const COutPoint b{Txid::FromUint256(uint256{11}), 0};\n-    const COutPoint c{Txid::FromUint256(uint256{12}), 0};\n-    const COutPoint d{Txid::FromUint256(uint256{20}), 0};\n-    const COutPoint unknown{Txid::FromUint256(uint256{99}), 0};\n-    for (const auto& outpoint : {a, b, c}) store.AddCoin(outpoint, RandomCoin(m_rng, 1), false);\n-    store.Sync(); // the database has them too\n-\n-    // FetchFor: what the block sees among what the tier holds; b no longer, once a lower block spent it.\n-    const auto lower{store.Beg\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1094,
    "evidence_id": "a6de61b274294a2896ee33871a20616e",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 945,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/test/coinsstore_tests.cpp",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "{\npublic:\n    using CCoinsViewBacked::CCoinsViewBacked;\n    int m_calls{0};\n    int m_fail_at{0};\n    void WriteRun(const std::vector<CoinWrite>& writes, const uint256& new_head, const uint256& old_head, bool final) override\n    {\n        if (++m_calls == m_fail_at) throw std::runtime_error{\"the write failed\"};\n        CCoinsViewBacked::WriteRun(writes, new_head, old_head, final);\n    }\n};\n\n//! A streamed run that ends at any of its writes, as a node that stops there leaves it, leaves a database\n//! the replay completes: the marker names the run's head and the head before the run, and applying the\n//! blocks between the two again, as Chainstate::ReplayBlocks() does through a cache on the database, gives\n//! the database of a node that never stopped. Every write of a run of one change per chunk is tried.\nBOOST_AUTO_TEST_CASE(streamed_run_cut_at_any_write_is_completed_by_a_replay)\n{\n    const auto hash{[](int height) { return uint256{static_cast<uint8_t>(height)}; }};\n    static constexpr int HEIGHTS{6};\n    static constexpr int PER_HEIGHT{8};\n    static constexpr int WRITTEN{2}; //!< the height the database is at before the run\n    const auto outpoint{[](int height, int n) { return COutPoint{Txid::FromUint256(uint256{static_cast<uint8_t>(height * 16 + n)}), 0}; }};\n    std::vector<Coin> coins;\n    for (int height{1}; height <= HEIGHTS; ++height) {\n        for (int n{0}; n < PER_HEIGHT; ++n) coins.push_back(RandomCoin(m_rng, height));\n    }\n    const auto coin{[&](int height, int n) { return coins[(height - 1) * PER_HEIGHT + n]; }};\n    // The changes of a block: its coins, and at two heights spends of coins the database holds and of one\n    // it never held.\n    const auto block{[&](auto& view, int height, bool overwrite) {\n        for (int n{0}; n < PER_HEIGHT; ++n) view.AddCoin(outpoint(height, n), coin(height, n), overwrite);\n        if (height == 3) {\n            for (int n{0}; n < PER_HEIGHT / 2; ++n) view.SpendCoin(outpoint(1, n));\n        } else if (height == 5) {\n            view.SpendCoin(outpoint(2, 0));\n            view.SpendCoin(outpoint(4, 0));\n        }\n    }};\n\n    // The database of a node that never stopped.\n    CCoinsViewDB db_whole{MemoryDb(\"whole\"), {}};\n    {\n        CCoinsViewCache cache{&db_whole};\n        for (int height{1}; height <= HEIGHTS; ++height) block(cache, height, /*overwrite=*/false);\n        cache.SetBestBlock(hash(HEIGHTS));\n        cache.Flush();\n    }\n\n    // Returns the number of writes the run made, all of them if none failed.\n    const auto run_cut_at{[&](int fail_at) {\n        CCoinsViewDB db{MemoryDb(\"cut\"), {}};\n        FailingAtBase base{&db};\n        CoinsStore store{&base, 4, true};\n        for (int height{1}; height <= HEIGHTS; ++height) {\n            store.SetBestBlock(hash(height), height);\n            block(store, height, /*overwrite=*/false);\n            if (height == WRITTEN) store.Sync();\n        }\n        auto run{store.BeginWriteOut(/*bound_height=*/4, /*head_height=*/HEIGHTS, hash(HEIGHTS), /*final=*/false)};\n        BOOST_REQUIRE(run);\n        base.m_calls = 0;\n        base.m_fail_at = fail_at;\n        if (fail_at == 0) {\n            store.StreamWriteOut(*run, hash, /*batch_bytes=*/1);\n            store.CommitWriteOut(*run);\n            return base.m_calls;\n        }\n        BOOST_CHECK_THROW(store.StreamWriteOut(*run, hash, /*batch_bytes=*/1), std::runtime_error);\n        // The run is the caller's to abandon, as the write-out's thread does.\n        store.AbandonWriteOut();\n        BOOST_CHECK(!store.RunInFlight());\n        BOOST_CHECK(store.FlushFailed());\n        if (fail_at == 1) {\n            // Nothing of the run is in the database.\n            BOOST_CHECK(db.GetHeadBlocks().empty());\n            BOOST_CHECK(db.GetBestBlock() == hash(WRITTEN));\n        } else {\n            BOOST_CHECK((db.GetHeadBlocks() == std::vector<uint256>{hash(HEIGHTS), hash(WRITTEN)}));\n            BOOST_CHECK(db.GetBestBlock().IsNull());\n        }\n\n        // The replay: the blocks above the old head again, whatever the database holds of them.\n        {\n            CCoinsViewCache replay{&db};\n            for (int height{WRITTEN + 1}; height <= HEIGHTS; ++height) block(replay, height, /*overwrite=*/true);\n            replay.SetBestBlock(hash(HEIGHTS));\n            replay.Flush();\n        }\n        BOOST_CHECK(db.GetHeadBlocks().empty());\n        BOOST_CHECK(db.GetBestBlock() == hash(HEIGHTS));\n        for (int height{1}; height <= HEIGHTS; ++height) {\n            for (int n{0}; n < PER_HEIGHT; ++n) {\n                BOOST_CHECK_MESSAGE(Same(db.PeekCoin(outpoint(height, n)), db_whole.PeekCoin(outpoint(height, n))),\n                                    \"cut at write \" << fail_at << \": the database differs at coin \" << n << \" of height \" << height);\n            }\n        }\n        return base.m_calls;\n    }};\n\n    const int writes{run_cut_at(0)};\n    // A chunk for each change at or below the run's bound, and the write that closes the marker.\n    BOOST_REQUIRE_GT(writes, 2 * PER_HEIGHT);\n    for (int fail_at{1}; fail_at <= writes; ++fail_at) BOOST_CHECK_EQUAL(run_cut_at(fail_at), fail_at);\n}\n\n//! A block that creates an outpoint over an erase the database is still owed keeps that erase on the books:\n//! the entry stays filed at the height of the spend, under the coin, and the coin is written over the one\n//! the database has.\nBOOST_AUTO_TEST_CASE(owed_erase_survives_a_create)\n{\n    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n    CoinsStore store{&db, 4, true};\n    store.SetBestBlock(uint256{1}, 1);\n    const COutPoint x{Txid::FromUint256(uint256{10}), 0};\n    store.AddCoin(x, RandomCoin(m_rng, 1), false);\n    store.Sync(); // x is in the database\n    store.SetChangeHeight(2);\n    BOOST_CHECK(store.SpendCoin(x)); // spent, dirty: the erase is owed\n    BOOST_CHECK_EQUAL(*OldestDirty(store), 2);\n\n    // Block 3 makes x again (a duplicate, as BIP30 allowed once).\n    BOOST_CHECK_EQUAL(Create(store, 3, x, RandomCoin(m_rng, 3), false), 0U);\n    store.SetBestBlock(uint256{3}, 3);\n    BOOST_CHECK(store.HaveCoin(x));\n    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 1U);\n    // The erase still owed keeps its tag, the spend at 2, under the coin made at 3.\n    BOOST_CHECK_EQUAL(*OldestDirty(store), 2);\n    store.SanityCheck();\n    store.Sync();\n    const auto coin{db.PeekCoin(x)};\n    BOOST_REQUIRE(coin.has_value());\n    BOOST_CHECK_EQUAL(coin->nHeight, 3U);\n    BOOST_CHECK_EQUAL(store.GetDirtyCount(), 0U);\n    store.SanityCheck();\n}\n\n//! The tier's byte count stays exact for coins whose scripts are on the heap, through the two paths that\n//! empty an entry and keep it: a spend with no taker for the coin, and the spend of a coin made over an\n//! erase still owed. (An emptied script gives its memory back, CScript::clear().)\nBOOST_AUTO_TEST_CASE(emptied_entries_count_no_script_bytes)\n{\n    CCoinsViewDB db{MemoryDb(\"store\"), {}};\n    CoinsStore store{&db, 4, true};\n    store.SetBestBlock(uint256{1}, 1);\n    const auto big{[](int height) { return Coin{CTxOut{CAmount{1000}, CScript{} << std::vector<unsigned char>(100, 0x42)}, height, /*fCoinBaseIn=*/false}; }};\n    const COutPoint x{Txid::FromUint256(uint256{10}), 0};\n    store.AddCoin(x, big(1), false);\n    store.Sync(); // x is in the database\n    store.SetChangeHeight(2);",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44Sync() can discard an unhandled restored-coin payloadsrc/coinsstore.cppunclear
Assessment

The new-head source around the restored-payload handling is unavailable, and the supplied diff does not show the relevant documentation, assertions, or test coverage. The fix cannot be verified.

path_diff: src/coinsstore.cpp

[
  {
    "evidence_id": "5f79280c48b843468177e18a1aa0a2ca",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coinsstore.cpp",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/coinsstore.cpp b/src/coinsstore.cpp\nindex 3fff13f646..e845477668 100644\n--- a/src/coinsstore.cpp\n+++ b/src/coinsstore.cpp\n@@ -11,9 +11,10 @@\n \n \n #include <algorithm>\n-#include <array>\n+#include <condition_variable>\n #include <exception>\n #include <functional>\n+#include <unordered_map>\n #include <limits>\n #include <map>\n #include <stdexcept>\n@@ -215,152 +216,24 @@ void CoinsStore::EraseEntry(Shard& shard, Node& node) const\n     Resized(shard);\n }\n \n-bool CoinsStore::Pending(const Entry& entry) const\n-{\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    return entry.coin.IsSpent() ? entry.block_spend && entry.height > confirmed\n-                                : entry.block_create && static_cast<int>(entry.coin.nHeight) > confirmed;\n-}\n-\n-CoinsStore::Sight CoinsStore::See(const Entry& entry, int viewer_height) const\n-{\n-    // The entry's state says what there is to see, the heights say whether this viewer sees it.\n-    switch (coins_entry::ReadingOf(StateOf(entry))) {\n-    case coins_entry::Reading::NOTHING: return Sight::NOTHING;\n-    case coins_entry::Reading::COIN: return Sight::COIN;\n-    case coins_entry::Reading::BLOCK_RECORD:\n-        // The viewer's own spend, or a lower block's: spent.\n-        if (entry.height <= viewer_height) return Sight::NOTHING;\n-        return entry.height > m_confirmed_height.load(std::memory_order_relaxed) ? Sight::RECORD : Sight::NOTHING;\n-    case coins_entry::Reading::BLOCK_COIN: {\n-        const int created{static_cast<int>(entry.coin.nHeight)};\n-        if (created <= viewer_height) return Sight::COIN;\n-        return created > m_confirmed_height.load(std::memory_order_relaxed) ? Sight::NOTHING : Sight::COIN;\n-    }\n-    } // no default case, so the compiler can warn about missing cases\n-    assert(false);\n-}\n-\n-CoinsStore::BlockId CoinsStore::SlotAt(int height) const\n-{\n-    for (BlockId id{1}; id < m_window.size(); ++id) {\n-        const WindowBlock& slot{m_window[id]};\n-        // The status is published last by the writer; what it publishes (the height) is read after it.\n-        if (slot.status.load(std::memory_order_acquire) == BlockStatus::FREE) continue;\n-        if (slot.height.load(std::memory_order_relaxed) == height) return id;\n-    }\n-    return NO_BLOCK;\n-}\n-\n-void CoinsStore::ChargeDelta(int height, int64_t delta) const\n-{\n-    const BlockId id{SlotAt(height)};\n-    if (id == NO_BLOCK) return;\n-    const WindowBlock& slot{m_window[id]};\n-    if (slot.status.load(std::memory_order_acquire) == BlockStatus::APPLIED) slot.dirty_delta.fetch_add(delta, std::memory_order_relaxed);\n-}\n-\n-std::optional<Coin> CoinsStore::SeenCoin(Entry& entry, const COutPoint& outpoint, int viewer_height) const\n-{\n-    switch (See(entry, viewer_height)) {\n-    case Sight::COIN:\n-        Reference(entry);\n-        return entry.coin;\n-    case Sight::RECORD: return RecordCoin(entry.height, outpoint, viewer_height);\n-    case Sight::NOTHING: break;\n-    }\n-    return std::nullopt;\n-}\n-\n-//! The last spend of `outpoint` in a block's record that still stands, or nullptr; with the block's mutex\n-//! held.\n-template <typename Record>\n-static auto* LiveSpend(Record& record, const COutPoint& outpoint)\n-{\n-    const auto item{std::find_if(record.rbegin(), record.rend(), [&](const auto& u) { return u.spend && !u.dead && u.outpoint == outpoint; })};\n-    return item == record.rend() ? nullptr : &*item;\n-}\n-\n-std::optional<Coin> CoinsStore::RecordCoin(int spender_height, const COutPoint& outpoint, int viewer_height) const\n-{\n-    const BlockId id{SlotAt(spender_height)};\n-    if (id == NO_BLOCK) return std::nullopt;\n-    const WindowBlock& slot{m_window[id]};\n-    LOCK(slot.mutex);\n-    if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE || slot.height.load(std::memory_order_relaxed) != spender_height) return std::nullopt;\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    const auto* item{LiveSpend(slot.record, outpoint)};\n-    if (!item) return std::nullopt;\n-    // A coin an open block created, which is not there yet from where the viewer stands.\n-    const int created{static_cast<int>(item->coin.nHeight)};\n-    if (item->created && created > confirmed && created > viewer_height) return std::nullopt;\n-    return item->coin;\n-}\n-\n-std::optional<Coin> CoinsStore::RecordScan(const COutPoint& outpoint) const\n-{\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    for (BlockId id{1}; id < m_window.size(); ++id) {\n-        const WindowBlock& slot{m_window[id]};\n-        if (slot.status.load(std::memory_order_acquire) == BlockStatus::FREE) continue;\n-        LOCK(slot.mutex);\n-        if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE) continue;\n-        if (const auto* item{LiveSpend(slot.record, outpoint)}) {\n-            // A coin an open block created is no reader's.\n-            if (item->created && static_cast<int>(item->coin.nHeight) > confirmed) return std::nullopt;\n-            return item->coin;\n-        }\n-    }\n-    return std::nullopt;\n-}\n-\n-std::optional<Coin> CoinsStore::OwedValue(int creator_height, const COutPoint& outpoint) const\n-{\n-    const BlockId id{SlotAt(creator_height)};\n-    if (id == NO_BLOCK) return std::nullopt;\n-    const WindowBlock& slot{m_window[id]};\n-    LOCK(slot.mutex);\n-    if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE || slot.height.load(std::memory_order_relaxed) != creator_height) return std::nullopt;\n-    // A create is in the record for the coin it went over alone.\n-    for (auto it{slot.record.rbegin()}; it != slot.record.rend(); ++it) {\n-        if (!it->spend && !it->dead && it->outpoint == outpoint) return it->coin;\n-    }\n-    return std::nullopt;\n-}\n-\n-void CoinsStore::Record(WindowBlock& mine, std::vector<Undo>& undo, std::vector<COutPoint>* plain_creates, int64_t& delta)\n-{\n-    if (delta != 0) mine.dirty_delta.fetch_add(std::exchange(delta, 0), std::memory_order_relaxed);\n-    if (undo.empty() && (!plain_creates || plain_creates->empty())) return;\n-    LOCK(mine.mutex);\n-    for (const Undo& item : undo) {\n-        if (item.spend && item.owed) mine.owed_spends = true;\n-    }\n-    mine.record.insert(mine.record.end(), std::make_move_iterator(undo.begin()), std::make_move_iterator(undo.end()));\n-    undo.clear();\n-    if (plain_creates) {\n-        mine.plain_creates.insert(mine.plain_creates.end(), plain_creates->begin(), plain_creates->end());\n-        plain_creates->clear();\n-    }\n-}\n-\n // ---------------------------------------------------------------------------------------------------------\n // Lookups\n \n-std::optional<Coin> CoinsStore::Lookup(const COutPoint& outpoint) const\n+std::optional<Coin> CoinsStore::SeenCoin(Entry& entry)\n {\n-    return LookupFor(NO_BLOCK, outpoint);\n+    if (entry.coin.IsSpent()) return std::nullopt;\n+    Reference(entry);\n+    return entry.coin;\n }\n \n-std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpoint) const\n+std::optional<Coin> CoinsStore::Lookup(const COutPoint& outpoint) const\n {\n-    const int viewer_height{ViewerHeight(viewer)};\n     Shard& shard{ShardFor(outpoint)};\n     while (true) {\n         uint64_t settles;\n         {\n             LOCK(shard.mutex);\n-            if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n+            if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second);\n             settles = shard.settles;\n         }\n         // A miss: read the base with the shard unlocked, then re-take the shard and insert unless another\n@@ -371,14 +244,8 @@ std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpo\n         // erase and dropped from the tier since the miss, with the base read before the erase. Look again.\n         if (shard.settles != settles) continue;\n         auto it{shard.map.find(outpoint)};\n-        if (it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-        if (!coin) {\n-            // In neither place. A confirmed coin the database never held and an open block spent is in that\n-            // block's record alone, where a reader finds it. An applier does not look there: a lower block\n-            // spending what a higher one spent is a chain that fails, and is connected again in order.\n-            if (viewer == NO_BLOCK && m_open_slots.load(std::memory_order_relaxed) > 0) return RecordScan(outpoint);\n-            return std::nullopt;\n-        }\n+        if (it != shard.map.end()) return SeenCoin(it->second);\n+        if (!coin) return std::nullopt;\n         Assert(!coin->IsSpent());\n         it = shard.map.try_emplace(outpoint).first;\n         Resized(shard);\n@@ -390,22 +257,6 @@ std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpo\n     }\n }\n \n-std::optional<Coin> CoinsStore::PeekCoinFor(BlockId viewer, const COutPoint& outpoint) const\n-{\n-    const int viewer_height{ViewerHeight(viewer)};\n-    Shard& shard{ShardFor(outpoint)};\n-    {\n-        LOCK(shard.mutex);\n-        if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-    }\n-    std::optional<Coin> coin{base->PeekCoin(outpoint)};\n-    if (coin || viewer != NO_BLOCK || m_open_slots.load(std::memory_order_relaxed) == 0) return coin;\n-    // As LookupFor(): a reader's coin may be in an open block's record alone.\n-    LOCK(shard.mutex);\n-    if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-    return RecordScan(outpoint);\n-}\n-\n std::optional<Coin> CoinsStore::GetCoin(const COutPoint& outpoint) const\n {\n     return Lookup(outpoint);\n@@ -413,7 +264,12 @@ std::optional<Coin> CoinsStore::GetCoin(const COutPoint& outpoint) const\n \n std::optional<Coin> CoinsStore::PeekCoin(const COutPoint& outpoint) const\n {\n-    return PeekCoinFor(NO_BLOCK, outpoint);\n+    Shard& shard{ShardFor(outpoint)};\n+    {\n+        LOCK(shard.mutex);\n+        if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second);\n+    }\n+    return base->PeekCoin(outpoint);\n }\n \n bool CoinsStore::HaveCoin(const COutPoint& outpoint) const\n@@ -426,13 +282,7 @@ bool CoinsStore::HaveCoinInCache(const COutPoint& outpoint) const\n     Shard& shard{ShardFor(outpoint)};\n     LOCK(shard.mutex);\n     const auto it{shard.map.find(outpoint)};\n-    if (it == shard.map.end()) return false;\n-    switch (See(it->second, /*viewer_height=*/-1)) {\n-    case Sight::COIN: return true;\n-    case Sight::RECORD: return RecordCoin(it->second.height, outpoint, /*viewer_height=*/-1).has_value();\n-    case Sight::NOTHING: break;\n-    }\n-    return false;\n+    return it != shard.map.end() && !it->second.coin.IsSpent();\n }\n \n static const Coin STORE_EMPTY_COIN;\n@@ -476,16 +326,11 @@ void CoinsStore::KeepWritten(std::vector<CoinWrite> restored)\n     m_restored.insert(m_restored.end(), std::make_move_iterator(restored.begin()), std::make_move_iterator(restored.end()));\n }\n \n-// Confirmed changes without a block identity\n-//\n-// None is made while a block is open: such a change clears the block flags of an entry an open block\n-// created or spent (coins_entry_machine.h), and the block's unwind would then skip the entry. The callers\n-// keep to that (a block is disconnected, and a view written through, before any block is staged); each\n-// entry point checks it.\n+// ---------------------------------------------------------------------------------------------------------\n+// Changes\n \n void CoinsStore::AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n     assert(!coin.IsSpent());\n     if (coin.out.scriptPubKey.IsUnspendable()) return;\n     Shard& shard{ShardFor(outpoint)};\n@@ -516,7 +361,6 @@ void CoinsStore::AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_o\n \n void CoinsStore::EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coin)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n     Shard& shard{ShardFor(outpoint)};\n     LOCK(shard.mutex);\n     const size_t usage{coin.DynamicMemoryUsage()};\n@@ -530,6 +374,139 @@ void CoinsStore::EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coi\n     Attach(shard, *it);\n }\n \n+//! Whether `coin` is the one a block validated its spend against. Two coins of an outpoint are told\n+//! apart by where they were made: the outputs of a transaction made twice are the same.\n+template <typename AnyCoin>\n+static bool IsCoin(const AnyCoin& coin, const Coin& known)\n+{\n+    return coin.nHeight == known.nHeight && coin.fCoinBase == known.fCoinBase;\n+}\n+\n+void CoinsStore::SpendEntryAt(Shard& shard, Map::iterator it, int height)\n+{\n+    AssertLockHeld(shard.mutex);\n+    Entry& entry{it->second};\n+    const State from{StateOf(entry)};\n+    Detach(shard, *it);\n+    SubUsage(shard, entry.coin.DynamicMemoryUsage());\n+    if (entry.fresh) {\n+        EraseDetached(shard, it);\n+        return;\n+    }\n+    entry.coin.Clear();\n+    Transit(entry, from, Event::ConfirmedSpend, height);\n+    Attach(shard, *it);\n+}\n+\n+bool CoinsStore::CreateLocked(Shard& shard, const COutPoint& outpoint, uint64_t hash, Coin&& coin, const CScript* script, bool possible_overwrite, int height)\n+{\n+    AssertLockHeld(shard.mutex);\n+    auto [it, inserted]{shard.map.try_emplace(outpoint, hash)};\n+    Entry& entry{it->second};\n+    if (!inserted && !entry.coin.IsSpent() && !possible_overwrite) return false;\n+    if (inserted) Resized(shard);\n+    const State from{StateOf(entry)};\n+    // As AddCoin().\n+    const bool fresh{!possible_overwrite && !entry.dirty};\n+    // A dirty spent entry is an erase the database does not have yet (the output of a disconnected block\n+    // that the new branch makes again): it is owed under the create and the entry stays at its height, so\n+    // that a run bounded below the create writes the erase (CollectChunk()). Filed at the create's height\n+    // the erase would be lost if the create were taken back before a run carried it.\n+    const bool owes{!inserted && entry.dirty && entry.coin.IsSpent() && entry.height < height};\n+    // A coin made below `height` is one put back where a commit is taken back. As where a disconnect puts\n+    // one back (TagFor()): made above the settled height it is not in the database, and it is filed under\n+    // the height it was made at, so that no run bounded between the two settles the database without it.\n+    const int made{static_cast<int>(coin.nHeight)};\n+    const int settled{m_run_in_flight ? m_inflight_settled_height : m_written_height};\n+    const int filed{made < height && made > settled ? made : height};\n+    if (!inserted) {\n+        Detach(shard, *it);\n+        SubUsage(shard, entry.coin.DynamicMemoryUsage());\n+    }\n+    entry.coin = std::move(coin);\n+    if (script) entry.coin.out.scriptPubKey = *script;\n+    Transit(entry, from, owes ? Event::CoinOverErase : fresh ? Event::ConfirmedNew : Event::ConfirmedWrite, filed);\n+    AddUsage(shard, entry.coin.DynamicMemoryUsage());\n+    Attach(shard, *it);\n+    return true;\n+}\n+\n+uint32_t CoinsStore::ApplyConfirmed(std::vector<Change>&& changes, int height, ConfirmedReport* report, const std::function<const Coin*(const COutPoint&)>& base_coin)\n+{\n+    std::erase_if(changes, [](const Change& change) { return !change.coin->IsSpent() && (change.script ? *change.script : change.coin->out.scriptPubKey).IsUnspendable(); });\n+    if (changes.empty()) return 0;\n+    std::vector<uint32_t> shard_of;\n+    std::vector<uint64_t> hashes;\n+    shard_of.reserve(changes.size());\n+    hashes.reserve(changes.size());\n+    for (const Change& change : changes) {\n+        shard_of.push_back(ShardIndex(*change.outpoint));\n+        hashes.push_back(KeyHash(*change.outpoint));\n+    }\n+    uint32_t conflicts{0};\n+    std::vector<const Change*> misses;\n+    VisitShards(shard_of, [&](Shard& shard, std::span<const uint32_t> items) EXCLUSIVE_LOCKS_REQUIRED(shard.mutex) {\n+        shard.map.PrefetchAll(hashes, items);\n+        for (const uint32_t i : items) {\n+            const Change& change{changes[i]};\n+            const COutPoint& outpoint{*change.outpoint};\n+            if (change.coin->IsSpent()) {\n+                const auto it{shard.map.find(outpoint, hashes[i])};\n+                if (it == shard.map.end()) {\n+                    misses.push_back(&change);\n+                } else if (it->second.coin.IsSpent() || (change.known_coin && !IsCoin(it->second.coin, *change.coin))) {\n+                    ++conflicts;\n+                    if (report) report->conflicted.push_back(change.outpoint);\n+                } else {\n+                    SpendEntryAt(shard, it, height);\n+                }\n+                continue;\n+            }\n+            const auto old{shard.map.find(outpoint, hashes[i])};\n+            const bool over{old != shard.map.end() && !old->second.coin.IsSpent()};\n+            if (over && !change.possible_overwrite) {\n+                ++conflicts;\n+                if (report) report->conflicted.push_back(change.outpoint);\n+                continue;\n+            }\n+            if (over && report) report->overwritten.emplace_back(change.outpoint, old->second.coin);\n+            if (!CreateLocked(shard, outpoint, hashes[i], std::move(*change.coin), change.script, change.possible_overwrite, height)) {\n+                ++conflicts;\n+                if (report) report->conflicted.push_back(change.outpoint);\n+            }\n+        }\n+    });\n+    // Coins the tier no longer holds (evicted since the block read them): from the base, then spent.\n+    for (const Change* change : misses) {\n+        const Coin* const given{base_coin ? base_coin(*change->outpoint) : nullptr};\n+        const std::optional<Coin> coin{given ? std::optional<Coin>{*given} : Lookup(*change->outpoint)};\n+        if (!coin || (change->known_coin && !IsCoin(*coin, *change->coin))) {\n+            ++conflicts;\n+            if (report) report->conflicted.push_back(change->outpoint);\n+            continue;\n+        }\n+        Shard& shard{ShardFor(*change->outpoint)};\n+        LOCK(shard.mutex);\n+        // An eviction may have taken the entry again since the lookup brought it in (a run's completion evicts\n+        // clean entries): the database's coin is put back first, as the lookup did.\n+        auto [it, inserted]{shard.map.try_emplace(*change->outpoint)};\n+        if (inserted) {\n+            Resized(shard);\n+            it->second.coin = *coin;\n+            Transit(it->second, coins_entry::ABSENT, Event::BaseCopy, static_cast<int>(coin->nHeight));\n+            AddUsage(shard, it->second.coin.DynamicMemoryUsage());\n+            Attach(shard, *it);\n+        }\n+        if (it->second.coin.IsSpent()) {\n+            ++conflicts;\n+            if (report) report->conflicted.push_back(change->outpoint);\n+            continue;\n+        }\n+        SpendEntryAt(shard, it, height);\n+    }\n+    return conflicts;\n+}\n+\n void CoinsStore::SpendEntry(Shard& shard, Map::iterator it, Coin* moveto)\n {\n     AssertLockHeld(shard.mutex);\n@@ -546,14 +523,14 @@ void CoinsStore::SpendEntry(Shard& shard, Map::iterator it, Coin* moveto)\n         return;\n     }\n     entry.coin.Clear();\n-    // Under the change height, or where an earlier change is owed still (coins_entry::Height::Lower).\n+    // Under the change height, or where an earlier change the database does not have is filed lower\n+    // (coins_entry::Height::Oldest).\n     Transit(entry, from, Event::ConfirmedSpend, m_change_height);\n     Attach(shard, *it);\n }\n \n bool CoinsStore::SpendCoin(const COutPoint& outpoint, Coin* moveto)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44EffectsExecutor leaves its hook's locking restriction unstatedsrc/kernel/effects.haddressed
Assessment

The new effects.h documentation now explicitly says the completion hook only tries the requester's lock and never blocks on it, and that unapplied completions are handled later by ApplyCompletions().

path_diff: src/kernel/effects.h; new_source: src/kernel/effects.h

[
  {
    "evidence_id": "fc465d9029e8461b985e1806b14b75a3",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/kernel/effects.h",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/kernel/effects.h b/src/kernel/effects.h\nindex a0974e295a..b76ace2e84 100644\n--- a/src/kernel/effects.h\n+++ b/src/kernel/effects.h\n@@ -28,7 +28,10 @@ namespace kernel {\n  * itself, and WaitForIO() only waits for the I/O half, so a thread holding\n  * that lock may wait for the I/O to finish and then apply the completions\n  * itself. The worker calls the on_completion hook after each effect, which\n- * is where the requester normally applies completions (taking its lock).\n+ * is where the requester normally applies completions. The hook only tries\n+ * the requester's lock and never blocks on it: a thread holding that lock\n+ * may be waiting in WaitForIO() for this very worker. What it cannot apply\n+ * is left to ApplyCompletions().\n  *\n  * Enqueue order is preserved end to end: effects run in order and their\n  * completions are applied in that same order. The appliers keep the second\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 109,
    "evidence_id": "a2b158f677e64b2bac64e7bb2d1e63e9",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 1,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/kernel/effects.h",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "// Copyright (c) 2026-present The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#ifndef BITCOIN_KERNEL_EFFECTS_H\n#define BITCOIN_KERNEL_EFFECTS_H\n\n#include <sync.h>\n#include <util/byte_ledger.h>\n#include <util/lifecycle.h>\n\n#include <condition_variable>\n#include <cstddef>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <thread>\n#include <utility>\n\nnamespace kernel {\n\n/**\n * Runs effects (system interactions that validation requests, such as writing\n * undo data) on one worker thread, in the order they were enqueued, and hands\n * each effect's completion back to be applied under the requester's lock.\n *\n * The split matters for locking: the worker never takes the requester's lock\n * itself, and WaitForIO() only waits for the I/O half, so a thread holding\n * that lock may wait for the I/O to finish and then apply the completions\n * itself. The worker calls the on_completion hook after each effect, which\n * is where the requester normally applies completions. The hook only tries\n * the requester's lock and never blocks on it: a thread holding that lock\n * may be waiting in WaitForIO() for this very worker. What it cannot apply\n * is left to ApplyCompletions().\n *\n * Enqueue order is preserved end to end: effects run in order and their\n * completions are applied in that same order. The appliers keep the second\n * half: ApplyCompletions() runs each completion outside the executor's mutex,\n * so every thread that calls it holds one common lock, the requester's\n * (cs_main in the node).\n *\n * Whether it takes effects is one machine (util/lifecycle.h): Stopped until\n * Start(), Running until Stop(), Draining while Stop() waits for the I/O of\n * what was queued, then Stopped again. An effect queued while it is not\n * Running would never run, or run behind the stop that was to be the last\n * word: Enqueue() asserts.\n */\nclass EffectsExecutor\n{\npublic:\n    //! The I/O half, run on the worker with no lock held. Returns success. Nothing catches above it: an\n    //! exception that leaves an effect terminates the node.\n    using Effect = std::function<bool()>;\n    //! The completion half, run by ApplyCompletions() with the result of the I/O.\n    using Completion = std::function<void(bool ok)>;\n\n    //! `backlog` is the account the weight of the queued effects is kept in (util/byte_ledger.h).\n    explicit EffectsExecutor(util::ByteAccount& backlog, std::function<void()> on_completion = {});\n    ~EffectsExecutor() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\n    EffectsExecutor(const EffectsExecutor&) = delete;\n    EffectsExecutor& operator=(const EffectsExecutor&) = delete;\n\n    //! Start the worker. Nothing is queued before it (Enqueue()).\n    void Start() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n    //! Run every enqueued effect's I/O, then stop the worker. Completions stay queued for ApplyCompletions().\n    void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\n    //! Queue an effect; `bytes` is its weight for the backlog limit. The executor is Running.\n    void Enqueue(Effect effect, Completion completion, size_t bytes = 0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\n    //! Wait until the I/O of every enqueued effect has run. Safe with the requester's lock held.\n    void WaitForIO() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n    //! Wait until the weight of effects whose I/O has not run yet is at most `limit_bytes`. Safe with the requester's\n    //! lock held, as WaitForIO(); called without it where it can be, so that the lock is free while it waits.\n    void WaitForBacklogBelow(size_t limit_bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n    //! Apply the completions of finished effects, in order. The caller holds whatever lock the completions need.\n    void ApplyCompletions() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\n    size_t PendingBytes() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n    bool HasPendingCompletions() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n    //! Whether nothing is left: no effect queued or running, no completion to apply.\n    bool Idle() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\nprivate:\n    struct Item {\n        Effect effect;\n        Completion completion;\n        size_t bytes;\n    };\n\n    void Loop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);\n\n    mutable Mutex m_mutex;\n    std::condition_variable m_cv_work;\n    std::condition_variable m_cv_done;\n    std::deque<Item> m_queue GUARDED_BY(m_mutex);\n    std::deque<std::pair<Completion, bool>> m_done GUARDED_BY(m_mutex);\n    //! The weight of the effects whose I/O has not run: changed under m_mutex, read by anyone.\n    util::ByteAccount& m_backlog;\n    bool m_io_running GUARDED_BY(m_mutex){false};\n    util::Lifecycle m_life GUARDED_BY(m_mutex);\n    std::thread m_thread;\n    const std::function<void()> m_on_completion;\n};\n\n} // namespace kernel\n\n#endif // BITCOIN_KERNEL_EFFECTS_H",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44Open-block record writes bypass the one-chunk memory boundsrc/coinsstore.cppunclear
Assessment

The new-head source at the record collection location is unavailable, and the supplied diff is truncated before showing whether record candidates or coin payloads are chunked. The available material cannot establish whether the memory-bound issue was fixed.

path_diff: src/coinsstore.cpp

[
  {
    "evidence_id": "7851e89c826445f8a5ff26e3b0c4b902",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coinsstore.cpp",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/coinsstore.cpp b/src/coinsstore.cpp\nindex 3fff13f646..e845477668 100644\n--- a/src/coinsstore.cpp\n+++ b/src/coinsstore.cpp\n@@ -11,9 +11,10 @@\n \n \n #include <algorithm>\n-#include <array>\n+#include <condition_variable>\n #include <exception>\n #include <functional>\n+#include <unordered_map>\n #include <limits>\n #include <map>\n #include <stdexcept>\n@@ -215,152 +216,24 @@ void CoinsStore::EraseEntry(Shard& shard, Node& node) const\n     Resized(shard);\n }\n \n-bool CoinsStore::Pending(const Entry& entry) const\n-{\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    return entry.coin.IsSpent() ? entry.block_spend && entry.height > confirmed\n-                                : entry.block_create && static_cast<int>(entry.coin.nHeight) > confirmed;\n-}\n-\n-CoinsStore::Sight CoinsStore::See(const Entry& entry, int viewer_height) const\n-{\n-    // The entry's state says what there is to see, the heights say whether this viewer sees it.\n-    switch (coins_entry::ReadingOf(StateOf(entry))) {\n-    case coins_entry::Reading::NOTHING: return Sight::NOTHING;\n-    case coins_entry::Reading::COIN: return Sight::COIN;\n-    case coins_entry::Reading::BLOCK_RECORD:\n-        // The viewer's own spend, or a lower block's: spent.\n-        if (entry.height <= viewer_height) return Sight::NOTHING;\n-        return entry.height > m_confirmed_height.load(std::memory_order_relaxed) ? Sight::RECORD : Sight::NOTHING;\n-    case coins_entry::Reading::BLOCK_COIN: {\n-        const int created{static_cast<int>(entry.coin.nHeight)};\n-        if (created <= viewer_height) return Sight::COIN;\n-        return created > m_confirmed_height.load(std::memory_order_relaxed) ? Sight::NOTHING : Sight::COIN;\n-    }\n-    } // no default case, so the compiler can warn about missing cases\n-    assert(false);\n-}\n-\n-CoinsStore::BlockId CoinsStore::SlotAt(int height) const\n-{\n-    for (BlockId id{1}; id < m_window.size(); ++id) {\n-        const WindowBlock& slot{m_window[id]};\n-        // The status is published last by the writer; what it publishes (the height) is read after it.\n-        if (slot.status.load(std::memory_order_acquire) == BlockStatus::FREE) continue;\n-        if (slot.height.load(std::memory_order_relaxed) == height) return id;\n-    }\n-    return NO_BLOCK;\n-}\n-\n-void CoinsStore::ChargeDelta(int height, int64_t delta) const\n-{\n-    const BlockId id{SlotAt(height)};\n-    if (id == NO_BLOCK) return;\n-    const WindowBlock& slot{m_window[id]};\n-    if (slot.status.load(std::memory_order_acquire) == BlockStatus::APPLIED) slot.dirty_delta.fetch_add(delta, std::memory_order_relaxed);\n-}\n-\n-std::optional<Coin> CoinsStore::SeenCoin(Entry& entry, const COutPoint& outpoint, int viewer_height) const\n-{\n-    switch (See(entry, viewer_height)) {\n-    case Sight::COIN:\n-        Reference(entry);\n-        return entry.coin;\n-    case Sight::RECORD: return RecordCoin(entry.height, outpoint, viewer_height);\n-    case Sight::NOTHING: break;\n-    }\n-    return std::nullopt;\n-}\n-\n-//! The last spend of `outpoint` in a block's record that still stands, or nullptr; with the block's mutex\n-//! held.\n-template <typename Record>\n-static auto* LiveSpend(Record& record, const COutPoint& outpoint)\n-{\n-    const auto item{std::find_if(record.rbegin(), record.rend(), [&](const auto& u) { return u.spend && !u.dead && u.outpoint == outpoint; })};\n-    return item == record.rend() ? nullptr : &*item;\n-}\n-\n-std::optional<Coin> CoinsStore::RecordCoin(int spender_height, const COutPoint& outpoint, int viewer_height) const\n-{\n-    const BlockId id{SlotAt(spender_height)};\n-    if (id == NO_BLOCK) return std::nullopt;\n-    const WindowBlock& slot{m_window[id]};\n-    LOCK(slot.mutex);\n-    if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE || slot.height.load(std::memory_order_relaxed) != spender_height) return std::nullopt;\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    const auto* item{LiveSpend(slot.record, outpoint)};\n-    if (!item) return std::nullopt;\n-    // A coin an open block created, which is not there yet from where the viewer stands.\n-    const int created{static_cast<int>(item->coin.nHeight)};\n-    if (item->created && created > confirmed && created > viewer_height) return std::nullopt;\n-    return item->coin;\n-}\n-\n-std::optional<Coin> CoinsStore::RecordScan(const COutPoint& outpoint) const\n-{\n-    const int confirmed{m_confirmed_height.load(std::memory_order_relaxed)};\n-    for (BlockId id{1}; id < m_window.size(); ++id) {\n-        const WindowBlock& slot{m_window[id]};\n-        if (slot.status.load(std::memory_order_acquire) == BlockStatus::FREE) continue;\n-        LOCK(slot.mutex);\n-        if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE) continue;\n-        if (const auto* item{LiveSpend(slot.record, outpoint)}) {\n-            // A coin an open block created is no reader's.\n-            if (item->created && static_cast<int>(item->coin.nHeight) > confirmed) return std::nullopt;\n-            return item->coin;\n-        }\n-    }\n-    return std::nullopt;\n-}\n-\n-std::optional<Coin> CoinsStore::OwedValue(int creator_height, const COutPoint& outpoint) const\n-{\n-    const BlockId id{SlotAt(creator_height)};\n-    if (id == NO_BLOCK) return std::nullopt;\n-    const WindowBlock& slot{m_window[id]};\n-    LOCK(slot.mutex);\n-    if (slot.status.load(std::memory_order_relaxed) == BlockStatus::FREE || slot.height.load(std::memory_order_relaxed) != creator_height) return std::nullopt;\n-    // A create is in the record for the coin it went over alone.\n-    for (auto it{slot.record.rbegin()}; it != slot.record.rend(); ++it) {\n-        if (!it->spend && !it->dead && it->outpoint == outpoint) return it->coin;\n-    }\n-    return std::nullopt;\n-}\n-\n-void CoinsStore::Record(WindowBlock& mine, std::vector<Undo>& undo, std::vector<COutPoint>* plain_creates, int64_t& delta)\n-{\n-    if (delta != 0) mine.dirty_delta.fetch_add(std::exchange(delta, 0), std::memory_order_relaxed);\n-    if (undo.empty() && (!plain_creates || plain_creates->empty())) return;\n-    LOCK(mine.mutex);\n-    for (const Undo& item : undo) {\n-        if (item.spend && item.owed) mine.owed_spends = true;\n-    }\n-    mine.record.insert(mine.record.end(), std::make_move_iterator(undo.begin()), std::make_move_iterator(undo.end()));\n-    undo.clear();\n-    if (plain_creates) {\n-        mine.plain_creates.insert(mine.plain_creates.end(), plain_creates->begin(), plain_creates->end());\n-        plain_creates->clear();\n-    }\n-}\n-\n // ---------------------------------------------------------------------------------------------------------\n // Lookups\n \n-std::optional<Coin> CoinsStore::Lookup(const COutPoint& outpoint) const\n+std::optional<Coin> CoinsStore::SeenCoin(Entry& entry)\n {\n-    return LookupFor(NO_BLOCK, outpoint);\n+    if (entry.coin.IsSpent()) return std::nullopt;\n+    Reference(entry);\n+    return entry.coin;\n }\n \n-std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpoint) const\n+std::optional<Coin> CoinsStore::Lookup(const COutPoint& outpoint) const\n {\n-    const int viewer_height{ViewerHeight(viewer)};\n     Shard& shard{ShardFor(outpoint)};\n     while (true) {\n         uint64_t settles;\n         {\n             LOCK(shard.mutex);\n-            if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n+            if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second);\n             settles = shard.settles;\n         }\n         // A miss: read the base with the shard unlocked, then re-take the shard and insert unless another\n@@ -371,14 +244,8 @@ std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpo\n         // erase and dropped from the tier since the miss, with the base read before the erase. Look again.\n         if (shard.settles != settles) continue;\n         auto it{shard.map.find(outpoint)};\n-        if (it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-        if (!coin) {\n-            // In neither place. A confirmed coin the database never held and an open block spent is in that\n-            // block's record alone, where a reader finds it. An applier does not look there: a lower block\n-            // spending what a higher one spent is a chain that fails, and is connected again in order.\n-            if (viewer == NO_BLOCK && m_open_slots.load(std::memory_order_relaxed) > 0) return RecordScan(outpoint);\n-            return std::nullopt;\n-        }\n+        if (it != shard.map.end()) return SeenCoin(it->second);\n+        if (!coin) return std::nullopt;\n         Assert(!coin->IsSpent());\n         it = shard.map.try_emplace(outpoint).first;\n         Resized(shard);\n@@ -390,22 +257,6 @@ std::optional<Coin> CoinsStore::LookupFor(BlockId viewer, const COutPoint& outpo\n     }\n }\n \n-std::optional<Coin> CoinsStore::PeekCoinFor(BlockId viewer, const COutPoint& outpoint) const\n-{\n-    const int viewer_height{ViewerHeight(viewer)};\n-    Shard& shard{ShardFor(outpoint)};\n-    {\n-        LOCK(shard.mutex);\n-        if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-    }\n-    std::optional<Coin> coin{base->PeekCoin(outpoint)};\n-    if (coin || viewer != NO_BLOCK || m_open_slots.load(std::memory_order_relaxed) == 0) return coin;\n-    // As LookupFor(): a reader's coin may be in an open block's record alone.\n-    LOCK(shard.mutex);\n-    if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second, outpoint, viewer_height);\n-    return RecordScan(outpoint);\n-}\n-\n std::optional<Coin> CoinsStore::GetCoin(const COutPoint& outpoint) const\n {\n     return Lookup(outpoint);\n@@ -413,7 +264,12 @@ std::optional<Coin> CoinsStore::GetCoin(const COutPoint& outpoint) const\n \n std::optional<Coin> CoinsStore::PeekCoin(const COutPoint& outpoint) const\n {\n-    return PeekCoinFor(NO_BLOCK, outpoint);\n+    Shard& shard{ShardFor(outpoint)};\n+    {\n+        LOCK(shard.mutex);\n+        if (auto it{shard.map.find(outpoint)}; it != shard.map.end()) return SeenCoin(it->second);\n+    }\n+    return base->PeekCoin(outpoint);\n }\n \n bool CoinsStore::HaveCoin(const COutPoint& outpoint) const\n@@ -426,13 +282,7 @@ bool CoinsStore::HaveCoinInCache(const COutPoint& outpoint) const\n     Shard& shard{ShardFor(outpoint)};\n     LOCK(shard.mutex);\n     const auto it{shard.map.find(outpoint)};\n-    if (it == shard.map.end()) return false;\n-    switch (See(it->second, /*viewer_height=*/-1)) {\n-    case Sight::COIN: return true;\n-    case Sight::RECORD: return RecordCoin(it->second.height, outpoint, /*viewer_height=*/-1).has_value();\n-    case Sight::NOTHING: break;\n-    }\n-    return false;\n+    return it != shard.map.end() && !it->second.coin.IsSpent();\n }\n \n static const Coin STORE_EMPTY_COIN;\n@@ -476,16 +326,11 @@ void CoinsStore::KeepWritten(std::vector<CoinWrite> restored)\n     m_restored.insert(m_restored.end(), std::make_move_iterator(restored.begin()), std::make_move_iterator(restored.end()));\n }\n \n-// Confirmed changes without a block identity\n-//\n-// None is made while a block is open: such a change clears the block flags of an entry an open block\n-// created or spent (coins_entry_machine.h), and the block's unwind would then skip the entry. The callers\n-// keep to that (a block is disconnected, and a view written through, before any block is staged); each\n-// entry point checks it.\n+// ---------------------------------------------------------------------------------------------------------\n+// Changes\n \n void CoinsStore::AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n     assert(!coin.IsSpent());\n     if (coin.out.scriptPubKey.IsUnspendable()) return;\n     Shard& shard{ShardFor(outpoint)};\n@@ -516,7 +361,6 @@ void CoinsStore::AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_o\n \n void CoinsStore::EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coin)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n     Shard& shard{ShardFor(outpoint)};\n     LOCK(shard.mutex);\n     const size_t usage{coin.DynamicMemoryUsage()};\n@@ -530,6 +374,139 @@ void CoinsStore::EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coi\n     Attach(shard, *it);\n }\n \n+//! Whether `coin` is the one a block validated its spend against. Two coins of an outpoint are told\n+//! apart by where they were made: the outputs of a transaction made twice are the same.\n+template <typename AnyCoin>\n+static bool IsCoin(const AnyCoin& coin, const Coin& known)\n+{\n+    return coin.nHeight == known.nHeight && coin.fCoinBase == known.fCoinBase;\n+}\n+\n+void CoinsStore::SpendEntryAt(Shard& shard, Map::iterator it, int height)\n+{\n+    AssertLockHeld(shard.mutex);\n+    Entry& entry{it->second};\n+    const State from{StateOf(entry)};\n+    Detach(shard, *it);\n+    SubUsage(shard, entry.coin.DynamicMemoryUsage());\n+    if (entry.fresh) {\n+        EraseDetached(shard, it);\n+        return;\n+    }\n+    entry.coin.Clear();\n+    Transit(entry, from, Event::ConfirmedSpend, height);\n+    Attach(shard, *it);\n+}\n+\n+bool CoinsStore::CreateLocked(Shard& shard, const COutPoint& outpoint, uint64_t hash, Coin&& coin, const CScript* script, bool possible_overwrite, int height)\n+{\n+    AssertLockHeld(shard.mutex);\n+    auto [it, inserted]{shard.map.try_emplace(outpoint, hash)};\n+    Entry& entry{it->second};\n+    if (!inserted && !entry.coin.IsSpent() && !possible_overwrite) return false;\n+    if (inserted) Resized(shard);\n+    const State from{StateOf(entry)};\n+    // As AddCoin().\n+    const bool fresh{!possible_overwrite && !entry.dirty};\n+    // A dirty spent entry is an erase the database does not have yet (the output of a disconnected block\n+    // that the new branch makes again): it is owed under the create and the entry stays at its height, so\n+    // that a run bounded below the create writes the erase (CollectChunk()). Filed at the create's height\n+    // the erase would be lost if the create were taken back before a run carried it.\n+    const bool owes{!inserted && entry.dirty && entry.coin.IsSpent() && entry.height < height};\n+    // A coin made below `height` is one put back where a commit is taken back. As where a disconnect puts\n+    // one back (TagFor()): made above the settled height it is not in the database, and it is filed under\n+    // the height it was made at, so that no run bounded between the two settles the database without it.\n+    const int made{static_cast<int>(coin.nHeight)};\n+    const int settled{m_run_in_flight ? m_inflight_settled_height : m_written_height};\n+    const int filed{made < height && made > settled ? made : height};\n+    if (!inserted) {\n+        Detach(shard, *it);\n+        SubUsage(shard, entry.coin.DynamicMemoryUsage());\n+    }\n+    entry.coin = std::move(coin);\n+    if (script) entry.coin.out.scriptPubKey = *script;\n+    Transit(entry, from, owes ? Event::CoinOverErase : fresh ? Event::ConfirmedNew : Event::ConfirmedWrite, filed);\n+    AddUsage(shard, entry.coin.DynamicMemoryUsage());\n+    Attach(shard, *it);\n+    return true;\n+}\n+\n+uint32_t CoinsStore::ApplyConfirmed(std::vector<Change>&& changes, int height, ConfirmedReport* report, const std::function<const Coin*(const COutPoint&)>& base_coin)\n+{\n+    std::erase_if(changes, [](const Change& change) { return !change.coin->IsSpent() && (change.script ? *change.script : change.coin->out.scriptPubKey).IsUnspendable(); });\n+    if (changes.empty()) return 0;\n+    std::vector<uint32_t> shard_of;\n+    std::vector<uint64_t> hashes;\n+    shard_of.reserve(changes.size());\n+    hashes.reserve(changes.size());\n+    for (const Change& change : changes) {\n+        shard_of.push_back(ShardIndex(*change.outpoint));\n+        hashes.push_back(KeyHash(*change.outpoint));\n+    }\n+    uint32_t conflicts{0};\n+    std::vector<const Change*> misses;\n+    VisitShards(shard_of, [&](Shard& shard, std::span<const uint32_t> items) EXCLUSIVE_LOCKS_REQUIRED(shard.mutex) {\n+        shard.map.PrefetchAll(hashes, items);\n+        for (const uint32_t i : items) {\n+            const Change& change{changes[i]};\n+            const COutPoint& outpoint{*change.outpoint};\n+            if (change.coin->IsSpent()) {\n+                const auto it{shard.map.find(outpoint, hashes[i])};\n+                if (it == shard.map.end()) {\n+                    misses.push_back(&change);\n+                } else if (it->second.coin.IsSpent() || (change.known_coin && !IsCoin(it->second.coin, *change.coin))) {\n+                    ++conflicts;\n+                    if (report) report->conflicted.push_back(change.outpoint);\n+                } else {\n+                    SpendEntryAt(shard, it, height);\n+                }\n+                continue;\n+            }\n+            const auto old{shard.map.find(outpoint, hashes[i])};\n+            const bool over{old != shard.map.end() && !old->second.coin.IsSpent()};\n+            if (over && !change.possible_overwrite) {\n+                ++conflicts;\n+                if (report) report->conflicted.push_back(change.outpoint);\n+                continue;\n+            }\n+            if (over && report) report->overwritten.emplace_back(change.outpoint, old->second.coin);\n+            if (!CreateLocked(shard, outpoint, hashes[i], std::move(*change.coin), change.script, change.possible_overwrite, height)) {\n+                ++conflicts;\n+                if (report) report->conflicted.push_back(change.outpoint);\n+            }\n+        }\n+    });\n+    // Coins the tier no longer holds (evicted since the block read them): from the base, then spent.\n+    for (const Change* change : misses) {\n+        const Coin* const given{base_coin ? base_coin(*change->outpoint) : nullptr};\n+        const std::optional<Coin> coin{given ? std::optional<Coin>{*given} : Lookup(*change->outpoint)};\n+        if (!coin || (change->known_coin && !IsCoin(*coin, *change->coin))) {\n+            ++conflicts;\n+            if (report) report->conflicted.push_back(change->outpoint);\n+            continue;\n+        }\n+        Shard& shard{ShardFor(*change->outpoint)};\n+        LOCK(shard.mutex);\n+        // An eviction may have taken the entry again since the lookup brought it in (a run's completion evicts\n+        // clean entries): the database's coin is put back first, as the lookup did.\n+        auto [it, inserted]{shard.map.try_emplace(*change->outpoint)};\n+        if (inserted) {\n+            Resized(shard);\n+            it->second.coin = *coin;\n+            Transit(it->second, coins_entry::ABSENT, Event::BaseCopy, static_cast<int>(coin->nHeight));\n+            AddUsage(shard, it->second.coin.DynamicMemoryUsage());\n+            Attach(shard, *it);\n+        }\n+        if (it->second.coin.IsSpent()) {\n+            ++conflicts;\n+            if (report) report->conflicted.push_back(change->outpoint);\n+            continue;\n+        }\n+        SpendEntryAt(shard, it, height);\n+    }\n+    return conflicts;\n+}\n+\n void CoinsStore::SpendEntry(Shard& shard, Map::iterator it, Coin* moveto)\n {\n     AssertLockHeld(shard.mutex);\n@@ -546,14 +523,14 @@ void CoinsStore::SpendEntry(Shard& shard, Map::iterator it, Coin* moveto)\n         return;\n     }\n     entry.coin.Clear();\n-    // Under the change height, or where an earlier change is owed still (coins_entry::Height::Lower).\n+    // Under the change height, or where an earlier change the database does not have is filed lower\n+    // (coins_entry::Height::Oldest).\n     Transit(entry, from, Event::ConfirmedSpend, m_change_height);\n     Attach(shard, *it);\n }\n \n bool CoinsStore::SpendCoin(const COutPoint& outpoint, Coin* moveto)\n {\n-    Assert(m_open_slots.load(std::memory_order_relaxed) == 0); // see \"Confirmed changes without a block identity\"\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44The nullopt guard does not ensure a consistent stats cursorsrc/kernel/coinstats.cppstill_present
Assessment

The new coinstats excerpt retains the same view.Cursor() call and separately obtains the best block from that cursor; no change addresses the snapshot consistency concern or shows interleaving tests.

old_source: src/kernel/coinstats.cpp; new_source: src/kernel/coinstats.cpp

[
  {
    "bounded": true,
    "end_line": 191,
    "evidence_id": "e182bbac6933490d8df60dbb1c1b2e51",
    "finding_id": "finding:4",
    "kind": "old_source",
    "line": 94,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/kernel/coinstats.cpp",
    "revision": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "    }\n}\n\nstatic void ApplyStats(CCoinsStats& stats, const std::map<uint32_t, Coin>& outputs)\n{\n    assert(!outputs.empty());\n    stats.nTransactions++;\n    for (auto it = outputs.begin(); it != outputs.end(); ++it) {\n        stats.nTransactionOutputs++;\n        if (stats.total_amount.has_value()) {\n            stats.total_amount = CheckedAdd(*stats.total_amount, it->second.out.nValue);\n        }\n        stats.nBogoSize += GetBogoSize(it->second.out.scriptPubKey);\n    }\n}\n\n//! Calculate statistics about the unspent transaction output set\ntemplate <typename T>\nstatic std::optional<CCoinsStats> ComputeUTXOStats(T hash_obj, const CCoinsViewDB& view, node::BlockManager& blockman, const std::function<void()>& interruption_point)\n{\n    std::unique_ptr<CCoinsViewCursor> pcursor;\n    CBlockIndex* pindex;\n    {\n        LOCK(::cs_main);\n        pcursor = view.Cursor();\n        pindex = blockman.LookupBlockIndex(pcursor->GetBestBlock());\n    }\n    // A write-out run that is not the last of its write-out leaves the database without a best block\n    // until a later run closes it. One may have started since the caller wrote the cache out: there is\n    // no block the database's coins are the set of.\n    if (!pindex) return std::nullopt;\n    CCoinsStats stats{pindex->nHeight, pindex->GetBlockHash()};\n\n    Txid prevkey;\n    std::map<uint32_t, Coin> outputs;\n    while (pcursor->Valid()) {\n        if (interruption_point) interruption_point();\n        COutPoint key;\n        Coin coin;\n        if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {\n            if (!outputs.empty() && key.hash != prevkey) {\n                ApplyStats(stats, outputs);\n                ApplyHash(hash_obj, prevkey, outputs);\n                outputs.clear();\n            }\n            prevkey = key.hash;\n            outputs[key.n] = std::move(coin);\n            stats.coins_count++;\n        } else {\n            LogDebug(BCLog::COINDB, \"%s: unable to read value\", __func__);\n            return std::nullopt;\n        }\n        pcursor->Next();\n    }\n    if (!outputs.empty()) {\n        ApplyStats(stats, outputs);\n        ApplyHash(hash_obj, prevkey, outputs);\n    }\n\n    FinalizeHash(hash_obj, stats);\n\n    stats.nDiskSize = view.EstimateSize();\n    return stats;\n}\n\nstd::optional<CCoinsStats> ComputeUTXOStats(CoinStatsHashType hash_type, const CCoinsViewDB& view, node::BlockManager& blockman, const std::function<void()>& interruption_point)\n{\n    return [&]() -> std::optional<CCoinsStats> {\n        switch (hash_type) {\n        case(CoinStatsHashType::HASH_SERIALIZED): {\n            HashWriter ss{};\n            return ComputeUTXOStats(ss, view, blockman, interruption_point);\n        }\n        case(CoinStatsHashType::MUHASH): {\n            MuHash3072 muhash;\n            return ComputeUTXOStats(muhash, view, blockman, interruption_point);\n        }\n        case(CoinStatsHashType::NONE): {\n            return ComputeUTXOStats(nullptr, view, blockman, interruption_point);\n        }\n        } // no default case, so the compiler can warn about missing cases\n        AssertUnreachable();\n    }();\n}\n\nstatic void FinalizeHash(HashWriter& ss, CCoinsStats& stats)\n{\n    stats.hashSerialized = ss.GetHash();\n}\nstatic void FinalizeHash(MuHash3072& muhash, CCoinsStats& stats)\n{\n    uint256 out;\n    muhash.Finalize(out);\n    stats.hashSerialized = out;\n}\nstatic void FinalizeHash(std::nullptr_t, CCoinsStats& stats) {}\n\n} // namespace kernel",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 191,
    "evidence_id": "4eadad9e145a4e05845b247e35371506",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 94,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/kernel/coinstats.cpp",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "    }\n}\n\nstatic void ApplyStats(CCoinsStats& stats, const std::map<uint32_t, Coin>& outputs)\n{\n    assert(!outputs.empty());\n    stats.nTransactions++;\n    for (auto it = outputs.begin(); it != outputs.end(); ++it) {\n        stats.nTransactionOutputs++;\n        if (stats.total_amount.has_value()) {\n            stats.total_amount = CheckedAdd(*stats.total_amount, it->second.out.nValue);\n        }\n        stats.nBogoSize += GetBogoSize(it->second.out.scriptPubKey);\n    }\n}\n\n//! Calculate statistics about the unspent transaction output set\ntemplate <typename T>\nstatic std::optional<CCoinsStats> ComputeUTXOStats(T hash_obj, const CCoinsViewDB& view, node::BlockManager& blockman, const std::function<void()>& interruption_point)\n{\n    std::unique_ptr<CCoinsViewCursor> pcursor;\n    CBlockIndex* pindex;\n    {\n        LOCK(::cs_main);\n        pcursor = view.Cursor();\n        pindex = blockman.LookupBlockIndex(pcursor->GetBestBlock());\n    }\n    // A write-out run that is not the last of its write-out leaves the database without a best block\n    // until a later run closes it. One may have started since the caller wrote the cache out: there is\n    // no block the database's coins are the set of.\n    if (!pindex) return std::nullopt;\n    CCoinsStats stats{pindex->nHeight, pindex->GetBlockHash()};\n\n    Txid prevkey;\n    std::map<uint32_t, Coin> outputs;\n    while (pcursor->Valid()) {\n        if (interruption_point) interruption_point();\n        COutPoint key;\n        Coin coin;\n        if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {\n            if (!outputs.empty() && key.hash != prevkey) {\n                ApplyStats(stats, outputs);\n                ApplyHash(hash_obj, prevkey, outputs);\n                outputs.clear();\n            }\n            prevkey = key.hash;\n            outputs[key.n] = std::move(coin);\n            stats.coins_count++;\n        } else {\n            LogDebug(BCLog::COINDB, \"%s: unable to read value\", __func__);\n            return std::nullopt;\n        }\n        pcursor->Next();\n    }\n    if (!outputs.empty()) {\n        ApplyStats(stats, outputs);\n        ApplyHash(hash_obj, prevkey, outputs);\n    }\n\n    FinalizeHash(hash_obj, stats);\n\n    stats.nDiskSize = view.EstimateSize();\n    return stats;\n}\n\nstd::optional<CCoinsStats> ComputeUTXOStats(CoinStatsHashType hash_type, const CCoinsViewDB& view, node::BlockManager& blockman, const std::function<void()>& interruption_point)\n{\n    return [&]() -> std::optional<CCoinsStats> {\n        switch (hash_type) {\n        case(CoinStatsHashType::HASH_SERIALIZED): {\n            HashWriter ss{};\n            return ComputeUTXOStats(ss, view, blockman, interruption_point);\n        }\n        case(CoinStatsHashType::MUHASH): {\n            MuHash3072 muhash;\n            return ComputeUTXOStats(muhash, view, blockman, interruption_point);\n        }\n        case(CoinStatsHashType::NONE): {\n            return ComputeUTXOStats(nullptr, view, blockman, interruption_point);\n        }\n        } // no default case, so the compiler can warn about missing cases\n        AssertUnreachable();\n    }();\n}\n\nstatic void FinalizeHash(HashWriter& ss, CCoinsStats& stats)\n{\n    stats.hashSerialized = ss.GetHash();\n}\nstatic void FinalizeHash(MuHash3072& muhash, CCoinsStats& stats)\n{\n    uint256 out;\n    muhash.Finalize(out);\n    stats.hashSerialized = out;\n}\nstatic void FinalizeHash(std::nullptr_t, CCoinsStats& stats) {}\n\n} // namespace kernel",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44CoinsStore::Sync() does not dispatch through the cache interfacesrc/coinsstore.hstill_present
Assessment

The new header still declares CoinsStore::Sync() as a non-virtual member, with no override annotation. The supplied evidence does not show virtual dispatch added to the cache sync path.

path_diff: src/coinsstore.h; new_source: src/coinsstore.h

[
  {
    "evidence_id": "bdfbc0d946794e1cb9df2c44f1a26daa",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coinsstore.h",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/coinsstore.h b/src/coinsstore.h\nindex 51aef97af1..3acb696c37 100644\n--- a/src/coinsstore.h\n+++ b/src/coinsstore.h\n@@ -9,6 +9,7 @@\n #include <coins_entry_machine.h>\n #include <crypto/common.h>\n #include <kernel/caches.h>\n+#include <undo.h>\n #include <primitives/transaction.h>\n #include <sync.h>\n #include <uint256.h>\n@@ -23,7 +24,6 @@\n #include <functional>\n #include <limits>\n #include <memory>\n-#include <mutex>\n #include <new>\n #include <optional>\n #include <span>\n@@ -53,29 +53,15 @@\n  *    which coins created and spent since the bound are never written at all.\n  *  - Clean entries can be evicted on their own (EvictClean), so the budget\n  *    is met before any dirty entry has to be written.\n- *  - A change made while connecting a block is made under that block's\n- *    identity (BeginBlock, ApplyBatch) and is complete when it is made. A\n- *    created coin is dirty at once, on the list of the block's height (one\n- *    made over a change the database is still owed stays on the list of\n- *    that change), and reads as not there yet to whoever stands below that\n- *    height while the confirmed height is below it too. A spent coin leaves\n- *    its entry at once: the entry is erased when the database never held\n- *    the coin, and becomes a spent marker under the block's height when the\n- *    database is owed the erase, or when a lower open block may create the\n- *    outpoint again (BIP30, see BeginBlock); the coin goes to the block's\n- *    record, where readers find it until the block is confirmed, and from\n- *    where a lower block that spends it too takes it through the marker.\n- *    Two applied blocks spending one coin are told apart by height: the\n- *    lower spend stands and the higher block gets a conflict (ApplySpend).\n- *    Confirming a block is one store of the confirmed height (ConfirmBlock),\n- *    after which its creates and markers read as plain ones; a block that\n- *    fails is taken back from its record (UnwindBlock).\n+ *  - A block's changes are made once the block is valid, at its height\n+ *    (ApplyConfirmed), by several threads on disjoint shards. A change that\n+ *    does not find the coin it expects is not made and is reported, and the\n+ *    caller takes the block's other changes back.\n  *\n- * The owner serialises confirmations, unwinds and runs (under cs_main); the\n- * shard locks make lookups and applies from other threads safe meanwhile.\n- * AccessCoin() returns a reference to the calling thread's copy of the coin,\n- * valid until the thread's next call: no lock of the caller keeps an applier\n- * from spending the entry.\n+ * The owner serialises commits and runs (under cs_main); the shard locks make\n+ * lookups from other threads safe meanwhile. AccessCoin() returns a reference\n+ * to the calling thread's copy of the coin, valid until the thread's next\n+ * call: no lock of the caller keeps a commit from spending the entry.\n  */\n class CoinsStore : public CCoinsViewCache\n {\n@@ -85,13 +71,6 @@ class CoinsStore : public CCoinsViewCache\n     using Node = std::pair<const COutPoint, Entry>;\n \n public:\n-    //! The identity of a block being connected, from BeginBlock(); 0 is \"no block\" (a confirmed change).\n-    using BlockId = uint32_t;\n-    static constexpr BlockId NO_BLOCK{0};\n-    //! Enough slots for the widest window and the tip view, with room to spare. Open blocks are consecutive\n-    //! blocks of one chain, so no two of them are this many heights apart.\n-    static constexpr size_t MAX_WINDOW_SLOTS{128};\n-\n     //! A write-out run between BeginWriteOut() and CommitWriteOut().\n     struct WriteOutRun {\n         //! Coins a disconnect restored (KeepWritten()), handed to this run: written before anything else of\n@@ -127,7 +106,7 @@ public:\n         size_t bytes{0};\n     };\n \n-    //! The number of shards unless the caller names one: many against any number of appliers a machine\n+    //! The number of shards unless the caller names one: many against any number of threads a machine\n     //! runs, since a thread that finds a shard taken waits far longer than the hold it waits out. An\n     //! empty shard is a few hundred bytes.\n     static constexpr size_t DEFAULT_SHARDS{256};\n@@ -136,7 +115,7 @@ public:\n     explicit CoinsStore(CCoinsView* base_view, size_t shards = DEFAULT_SHARDS, bool deterministic = false);\n     ~CoinsStore() override;\n \n-    // CCoinsView: the confirmed state, as readers see it.\n+    // CCoinsView\n     std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;\n     std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override;\n     bool HaveCoin(const COutPoint& outpoint) const override;\n@@ -144,7 +123,7 @@ public:\n     //! A child cache's dirty entries become confirmed changes of this tier at the current change height.\n     void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override;\n \n-    // CCoinsViewCache: confirmed changes with no block identity (the disconnect path, snapshot loading, tests).\n+    // CCoinsViewCache: changes one by one (the disconnect path, snapshot loading, tests).\n     void SetBestBlock(const uint256& block_hash) override;\n     bool HaveCoinInCache(const COutPoint& outpoint) const override;\n     const Coin& AccessCoin(const COutPoint& outpoint) const override;\n@@ -152,9 +131,8 @@ public:\n     //! Insert a coin known to be absent from the tier and the base (snapshot loading). Marked dirty, not fresh.\n     void EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coin) override;\n     bool SpendCoin(const COutPoint& outpoint, Coin* moveto = nullptr) override;\n-    //! Write everything dirty synchronously through the base, as a final run, and drop every entry but the\n-    //! open blocks' own, which stay as they are. The coins disconnects restored are not among what it\n-    //! writes: the caller writes Restored() first.\n+    //! Write everything dirty synchronously through the base, as a final run, and drop every entry. The\n+    //! coins disconnects restored are not among what it writes: the caller writes Restored() first.\n     void Flush(bool reallocate_cache = true) override;\n     //! Write everything dirty synchronously through the base, as a final run, and keep the entries clean.\n     //! As Flush(), the caller writes Restored() first.\n@@ -193,7 +171,6 @@ public:\n     //! The height tagged onto the changes that follow. Set to the fork height before disconnecting blocks, so\n     //! that the inverse changes are the oldest and the next run carries them all.\n     void SetChangeHeight(int height) { m_change_height = height; }\n-    int GetChangeHeight() const { return m_change_height; }\n     //! The height of the tier's best block, for the paths that move it by hash alone (a disconnect's\n     //! flush); SetBestBlock(hash, height) sets it too. Distinct from the change height, which a reorg\n     //! holds at the fork while the best block moves.\n@@ -203,93 +180,50 @@ public:\n         // with the fork height, and no run may stop at a bound until a final one has carried it.\n         if (height < (m_run_in_flight ? std::max(m_written_height, m_inflight_settled_height) : m_written_height)) m_fell_below_written = true;\n         m_tier_height = height;\n-        m_confirmed_height.store(height, std::memory_order_release);\n-        // Nothing above the tier's block is in the database to be met (a disconnect lowers the height).\n-        if (m_dropped_through.load(std::memory_order_relaxed) > height) m_dropped_through.store(height, std::memory_order_relaxed);\n     }\n \n-    // Connecting a block: changes with the block's identity, invisible to readers until confirmation.\n-    //! Open a block of `height` in the window table. Serialised by the owner. The height is above the\n-    //! confirmed height (that of the block confirmed last, or given with the best block), which is what\n-    //! tells an open block's changes from confirmed ones; only a disconnect lowers the confirmed height.\n-    //! `mark_fresh_spends` is given when the block, or a block that can be open below it, is checked for\n-    //! outpoints made twice (BIP30): the block's spend of a coin the database never held then leaves a spent\n-    //! marker like any other spend instead of erasing the entry, so that a lower block that creates the\n-    //! outpoint again finds the coin (its check fails) or the marker (its create is a conflict). Without\n-    //! it the lower block would find nothing and overwrite a coin that is unspent at its height.\n-    BlockId BeginBlock(int height, bool mark_fresh_spends = false);\n-    //! The coin as block `block` sees it: created long ago, by a confirmed block, by an applied block below it\n-    //! or by itself, and spent by none of these. An applied block above it shows it nothing: not the coins it\n-    //! created, and those it spent as they were (from its record). Brings old coins in from the base, clean, so that the block's spend\n-    //! finds them in the tier (a window block's view, BlockApplyView::SetKeepBaseReads()).\n-    std::optional<Coin> LookupFor(BlockId block, const COutPoint& outpoint) const;\n-    //! The same without bringing anything in (a block at the tip and its prefetch workers).\n-    std::optional<Coin> PeekCoinFor(BlockId block, const COutPoint& outpoint) const;\n-    /**\n-     * Block `block` spends `outpoint`, which it saw (LookupFor) when it checked its inputs. Another applied\n-     * block may have spent it since: the lower height stands. If that block is lower, this block becomes\n-     * the offender (its conflict count rises, the spend is not recorded); if higher, this block displaces\n-     * it and the other block gets the conflict. A spend the block did not see is not recorded either and\n-     * counts as a conflict; that includes a coin the database never held and a higher block spent first,\n-     * which left the tier with that spend: the owner unwinds the higher blocks and connects this one again.\n-     * Returns whether the spend was recorded.\n-     */\n-    bool ApplySpend(BlockId block, const COutPoint& outpoint, const Coin* known = nullptr);\n-    //! One of a block's changes, for ApplyBatch(): an unspent coin is the outpoint's creation, a spent one\n+    //! One of a block's changes, for ApplyConfirmed(): an unspent coin is the outpoint's creation, a spent one\n     //! its spend. The outpoint and the coin stay where the caller has them, for the length of the call: a\n-    //! change is three words, not a copy of both.\n+    //! change is no copy of either.\n     struct Change {\n         const COutPoint* outpoint;\n         Coin* coin;\n         //! For a create: a live coin under it is a BIP30 overwrite, allowed only with this, as AddCoin().\n         bool possible_overwrite{false};\n-        //! The block was checked to create no outpoint that has a coin (BIP30): a coin met at the apply\n-        //! came after that check and is a conflict, also where `possible_overwrite` allows writing over one.\n-        bool must_be_new{false};\n         //! For a spend: `coin`, spent, has the height and the coinbase flag of the coin the block validated\n-        //! the spend against, and another coin met at the apply is a conflict (`known` of ApplySpend()).\n+        //! the spend against, and another coin met at the apply is a conflict.\n         bool known_coin{false};\n+        //! For a create: the coin's script, where `coin` holds all but it.\n+        const CScript* script{nullptr};\n     };\n-    /**\n-     * Block `block` makes `changes`, each as it would be made alone (a spend as ApplySpend()), but grouped by\n-     * shard so that each shard's lock is taken once for the block.\n-     */\n-    void ApplyBatch(BlockId block, std::vector<Change>&& changes);\n-    //! The coins among `outpoints` that block `viewer` sees and the tier holds, read with one hold of each\n-    //! shard's lock; what is missing, spent or invisible is left out (PeekCoinFor() one by one is the fallback).\n-    std::vector<std::pair<COutPoint, Coin>> FetchFor(BlockId viewer, std::vector<COutPoint>&& outpoints) const;\n-    //! The conflicts recorded against the block so far; nonzero means it must not confirm.\n-    uint32_t ConflictCount(BlockId block) const;\n-    //! The block's height, as given to BeginBlock().\n-    int BlockHeight(BlockId block) const;\n-    /**\n-     * The block becomes part of the confirmed state: the confirmed height becomes its height, which is what\n-     * its creates and its spent markers are told from plain ones by, and the identity is freed. No entry\n-     * is visited but two kinds from the block's record: the spends that owe the database an erase, which\n-     * are filed for the next run, and the markers of coins the database never held, which are freed, and\n-     * only for a block that was opened with such markers (BeginBlock()): one that a block opened without\n-     * them took over stays until a run or a flush meets it. Blocks are confirmed from the lowest up, which\n-     * is asserted; that a block is opened above the confirmed height is the caller's to keep.\n-     */\n-    void ConfirmBlock(BlockId block);\n-    //! The block's changes are taken back from its record, the last first: its creates disappear, the coins\n-    //! it spent are put back as they were. The identity is freed. Blocks are unwound from the highest down\n-    //! (a coin a lower block created and a higher one spent goes with the higher block's unwind), and not\n-    //! while a run collects (StreamWriteOut(), Flush()). The order is the caller's\n-    //! to keep: a block whose publication failed is unwound after the blocks above it\n-    //! (ActivateBestChain()). A higher block's spend of a coin whose creator is gone leaves no coin behind\n-    //! (UnwindItem()), which is right for a coin the creator made and loses one the creator had written\n-    //! over.\n-    void UnwindBlock(BlockId block);\n-    //! Blocks opened and neither confirmed nor unwound.\n-    size_t OpenBlocks() const;\n+    //! The shard of an outpoint: what a commit groups a block's changes by.\n+    size_t ShardIndexOf(const COutPoint& outpoint) const { return ShardIndex(outpoint); }\n+    //! What ApplyConfirmed() tells of a call, for the caller that takes its changes back.\n+    struct ConfirmedReport {\n+        //! The changes that were not made, by the address of their outpoint.\n+        std::vector<const COutPoint*> conflicted;\n+        //! The coins that creates wrote over (Change::possible_overwrite), by the address of the create's outpoint.\n+        std::vector<std::pair<const COutPoint*, Coin>> overwritten;\n+    };\n+    //! The changes of the block at `height`, which validated, by several threads on disjoint shards. Returns\n+    //! the conflicts: a spend whose coin is not there, or is another, and a create over a coin it may not\n+    //! overwrite. A change that is a conflict is not made, the others are; `report` names them, so that the\n+    //! caller can take the others back (with the inverse changes, as a disconnected block's).\n+    //! A spend of a coin the tier does not hold takes the coin from `base_coin` where it gives one: the coin\n+    //! the database holds under the outpoint, as the block read it, which nothing has changed since (a block\n+    //! connected alone, from its undo data); else from a read of the database.\n+    uint32_t ApplyConfirmed(std::vector<Change>&& changes, int height, ConfirmedReport* report = nullptr, const std::function<const Coin*(const COutPoint&)>& base_coin = {});\n+    size_t ShardCount() const { return m_shards.size(); }\n+    //! The coins among `outpoints` that the tier holds, read with one hold of each shard's lock; what is\n+    //! missing or spent is left out (PeekCoin() one by one is the fallback).\n+    std::vector<std::pair<COutPoint, Coin>> Fetch(std::vector<COutPoint>&& outpoints) const;\n \n     //! The lowest height bound whose write-out frees at least `bytes` of dirty entries, or the tip height if\n     //! all dirty entries together do not.\n     int BoundForBytes(size_t bytes, int tip_height) const;\n \n-    //! Drop clean entries (an open block holds only dirty ones) until the tier's usage is at most `target_bytes`,\n-    //! oldest first in each shard; an entry read since it was last passed over gets a second chance.\n+    //! Drop clean entries until the tier's usage is at most `target_bytes`, oldest first in each shard; an\n+    //! entry read since it was last passed over gets a second chance.\n     size_t EvictClean(size_t target_bytes);\n \n     /**\n@@ -297,8 +231,7 @@ public:\n      * marker (`new_head`, the settled head of the previous run); `head_height` is new_head's height.\n      * `final` carries everything regardless of the bound. A run with nothing to carry still\n      * moves the settled head when the bound is above it; nullptr if there is nothing to carry and no\n-     * head to move. An entry an open block holds is dirty only for a confirmed change and is carried at\n-     * its confirmed value; the block's own changes are no part of new_head's state.\n+     * head to move.\n      *\n      * What the marker promises: before the run the database holds the state at old_head; each write sets\n      * an outpoint to its value at new_head; so a crash anywhere inside the run is repaired by undoing\n@@ -312,7 +245,7 @@ public:\n      * owes the database an erase is written as that erase (CollectChunk()), also where it went over an\n      * unspent coin the database never had. The database then holds less than the state below the create,\n      * never a coin that state does not have, and the replay re-applies the create like every block above\n-     * old_head. (An open block's create is written as what it went over, the value at the run's head.)\n+     * old_head.\n      */\n     std::unique_ptr<WriteOutRun> BeginWriteOut(int bound_height, int head_height, const uint256& new_head, bool final);\n     /**\n@@ -321,20 +254,18 @@ public:\n      * dirty lists, each shard under its lock and the chunk filling across shards, write\n      * it with no shard locked, then settle the chunk's entries shard by shard through the node pointers\n      * kept (an entry changed since stays dirty and is collected again; a spent one is erased). Memory\n-     * beyond the tier is one chunk's coins, whatever the size of the run, and a run smaller than a chunk is one\n-     * write. A collected entry is no longer FRESH: its value is on its way to the database, and a spend\n-     * meanwhile must produce an erase. At most one chunk is outstanding, and a collected entry is never\n-     * erased before its chunk settles, which is what keeps the pointers good.\n+     * beyond the tier is one chunk's coins, whatever the size of the run; a run smaller than a chunk is one\n+     * write. A collected entry is not FRESH: its value is on its way to the database, and a spend meanwhile\n+     * must produce an erase. At most one chunk is outstanding, and a collected entry is never erased before\n+     * its chunk settles, which is what keeps the pointers good.\n      *\n      * The last write closes the marker: a final run replaces it by the best block; any other rewrites\n      * it to (new_head, settled head), the pair the next run starts from, so that the marker on disk\n      * never names an old head below what the tier counts as written. `block_at` names the block at a\n      * height on new_head's chain (not needed for a final run).\n      *\n-     * Takes shard locks, and the slot mutexes of open blocks' records (CollectRecords()), and touches nothing\n-     * else of the tier, so it may run on another thread than the owner's while the owner makes no confirmed\n-     * change. Throws what the base's WriteRun() throws;\n-     * the run is then abandoned (AbandonWriteOut()).\n+     * Takes shard locks and touches nothing else of the tier, so it may run on another thread than the\n+     * owner's. Throws what the base's WriteRun() throws; the run is then abandoned (AbandonWriteOut()).\n      */\n     void StreamWriteOut(WriteOutRun& run, const std::function<uint256(int\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 280,
    "evidence_id": "437b68d82cf8404394f47879e2476ee3",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 131,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coinsstore.h",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "    //! Insert a coin known to be absent from the tier and the base (snapshot loading). Marked dirty, not fresh.\n    void EmplaceCoinInternalDANGER(const COutPoint& outpoint, Coin&& coin) override;\n    bool SpendCoin(const COutPoint& outpoint, Coin* moveto = nullptr) override;\n    //! Write everything dirty synchronously through the base, as a final run, and drop every entry. The\n    //! coins disconnects restored are not among what it writes: the caller writes Restored() first.\n    void Flush(bool reallocate_cache = true) override;\n    //! Write everything dirty synchronously through the base, as a final run, and keep the entries clean.\n    //! As Flush(), the caller writes Restored() first.\n    void Sync();\n    /**\n     * How the base takes its writes: the size of a batch (the database's batch size), and whether several\n     * threads may call its WriteRun() at once (the database's may). Flush() and Sync() write batches of up\n     * to that size, each the changes of neighbouring shards in the order of their keys: a range of the\n     * database's keys that no other batch of the flush reaches into (ShardIndex()). A flush of more than\n     * a few batches to a base that allows it has up to four workers, a range of the shards each,\n     * collecting and serializing its next batch while the database is busy with another's: the calling\n     * thread and tasks of the pool given to SetFlushHelpers().\n     */\n    void SetBaseWrites(uint64_t batch_bytes, bool concurrent)\n    {\n        m_batch_bytes = batch_bytes;\n        m_base_concurrent = concurrent;\n    }\n    //! The pool a flush's further workers run on, as tasks (the node's connect pool). Without one, the\n    //! calling thread writes every range, one after the other.\n    void SetFlushHelpers(std::shared_ptr<ThreadPool> pool) { m_flush_helpers = std::move(pool); }\n    void Uncache(const COutPoint& outpoint) override;\n    unsigned int GetCacheSize() const override;\n    size_t GetDirtyCount() const noexcept override;\n    size_t DynamicMemoryUsage() const override;\n    //! The regions the nodes of every store are carved from, which are never given back: beyond the live\n    //! nodes, which DynamicMemoryUsage() counts, they hold the free ones, which nothing else counts.\n    static size_t NodeRegionBytes() { return s_node_region_bytes.load(std::memory_order_relaxed); }\n    void SanityCheck() const override;\n    //! Not meaningful for the tier.\n    void Reset() noexcept override;\n\n    // The tier's own interface.\n    //! Set the block and the height tagged onto the changes that follow.\n    void SetBestBlock(const uint256& block_hash, int height);\n    //! The height tagged onto the changes that follow. Set to the fork height before disconnecting blocks, so\n    //! that the inverse changes are the oldest and the next run carries them all.\n    void SetChangeHeight(int height) { m_change_height = height; }\n    //! The height of the tier's best block, for the paths that move it by hash alone (a disconnect's\n    //! flush); SetBestBlock(hash, height) sets it too. Distinct from the change height, which a reorg\n    //! holds at the fork while the best block moves.\n    void SetTierHeight(int height)\n    {\n        // Below the block the database holds, or is being brought to: what the disconnect changed is tagged\n        // with the fork height, and no run may stop at a bound until a final one has carried it.\n        if (height < (m_run_in_flight ? std::max(m_written_height, m_inflight_settled_height) : m_written_height)) m_fell_below_written = true;\n        m_tier_height = height;\n    }\n\n    //! One of a block's changes, for ApplyConfirmed(): an unspent coin is the outpoint's creation, a spent one\n    //! its spend. The outpoint and the coin stay where the caller has them, for the length of the call: a\n    //! change is no copy of either.\n    struct Change {\n        const COutPoint* outpoint;\n        Coin* coin;\n        //! For a create: a live coin under it is a BIP30 overwrite, allowed only with this, as AddCoin().\n        bool possible_overwrite{false};\n        //! For a spend: `coin`, spent, has the height and the coinbase flag of the coin the block validated\n        //! the spend against, and another coin met at the apply is a conflict.\n        bool known_coin{false};\n        //! For a create: the coin's script, where `coin` holds all but it.\n        const CScript* script{nullptr};\n    };\n    //! The shard of an outpoint: what a commit groups a block's changes by.\n    size_t ShardIndexOf(const COutPoint& outpoint) const { return ShardIndex(outpoint); }\n    //! What ApplyConfirmed() tells of a call, for the caller that takes its changes back.\n    struct ConfirmedReport {\n        //! The changes that were not made, by the address of their outpoint.\n        std::vector<const COutPoint*> conflicted;\n        //! The coins that creates wrote over (Change::possible_overwrite), by the address of the create's outpoint.\n        std::vector<std::pair<const COutPoint*, Coin>> overwritten;\n    };\n    //! The changes of the block at `height`, which validated, by several threads on disjoint shards. Returns\n    //! the conflicts: a spend whose coin is not there, or is another, and a create over a coin it may not\n    //! overwrite. A change that is a conflict is not made, the others are; `report` names them, so that the\n    //! caller can take the others back (with the inverse changes, as a disconnected block's).\n    //! A spend of a coin the tier does not hold takes the coin from `base_coin` where it gives one: the coin\n    //! the database holds under the outpoint, as the block read it, which nothing has changed since (a block\n    //! connected alone, from its undo data); else from a read of the database.\n    uint32_t ApplyConfirmed(std::vector<Change>&& changes, int height, ConfirmedReport* report = nullptr, const std::function<const Coin*(const COutPoint&)>& base_coin = {});\n    size_t ShardCount() const { return m_shards.size(); }\n    //! The coins among `outpoints` that the tier holds, read with one hold of each shard's lock; what is\n    //! missing or spent is left out (PeekCoin() one by one is the fallback).\n    std::vector<std::pair<COutPoint, Coin>> Fetch(std::vector<COutPoint>&& outpoints) const;\n\n    //! The lowest height bound whose write-out frees at least `bytes` of dirty entries, or the tip height if\n    //! all dirty entries together do not.\n    int BoundForBytes(size_t bytes, int tip_height) const;\n\n    //! Drop clean entries until the tier's usage is at most `target_bytes`, oldest first in each shard; an\n    //! entry read since it was last passed over gets a second chance.\n    size_t EvictClean(size_t target_bytes);\n\n    /**\n     * Open a run that carries every dirty entry changed at or below `bound_height`, under the\n     * marker (`new_head`, the settled head of the previous run); `head_height` is new_head's height.\n     * `final` carries everything regardless of the bound. A run with nothing to carry still\n     * moves the settled head when the bound is above it; nullptr if there is nothing to carry and no\n     * head to move.\n     *\n     * What the marker promises: before the run the database holds the state at old_head; each write sets\n     * an outpoint to its value at new_head; so a crash anywhere inside the run is repaired by undoing\n     * old_head down to its fork with new_head and re-applying up to new_head (ReplayBlocks), which\n     * rewrites every outpoint the two states can differ in. For the promise to hold at the next run, the\n     * settled head after this one must be a block whose state the database then holds, which is\n     * `settled_height` on new_head's chain: the bound names the oldest change carried, not that state\n     * (a reorg's inverse changes are tagged with the fork height and move the state to the tier's head).\n     *\n     * One kind of write is not the outpoint's value at new_head: a confirmed create above the bound that\n     * owes the database an erase is written as that erase (CollectChunk()), also where it went over an\n     * unspent coin the database never had. The database then holds less than the state below the create,\n     * never a coin that state does not have, and the replay re-applies the create like every block above\n     * old_head.\n     */\n    std::unique_ptr<WriteOutRun> BeginWriteOut(int bound_height, int head_height, const uint256& new_head, bool final);\n    /**\n     * Write the run through the base a chunk at a time, a chunk being one database batch of about\n     * `batch_bytes` (the database's batch size): collect a chunk of dirty entries from the shards'\n     * dirty lists, each shard under its lock and the chunk filling across shards, write\n     * it with no shard locked, then settle the chunk's entries shard by shard through the node pointers\n     * kept (an entry changed since stays dirty and is collected again; a spent one is erased). Memory\n     * beyond the tier is one chunk's coins, whatever the size of the run; a run smaller than a chunk is one\n     * write. A collected entry is not FRESH: its value is on its way to the database, and a spend meanwhile\n     * must produce an erase. At most one chunk is outstanding, and a collected entry is never erased before\n     * its chunk settles, which is what keeps the pointers good.\n     *\n     * The last write closes the marker: a final run replaces it by the best block; any other rewrites\n     * it to (new_head, settled head), the pair the next run starts from, so that the marker on disk\n     * never names an old head below what the tier counts as written. `block_at` names the block at a\n     * height on new_head's chain (not needed for a final run).\n     *\n     * Takes shard locks and touches nothing else of the tier, so it may run on another thread than the\n     * owner's. Throws what the base's WriteRun() throws; the run is then abandoned (AbandonWriteOut()).\n     */\n    void StreamWriteOut(WriteOutRun& run, const std::function<uint256(int)>& block_at, uint64_t batch_bytes = DEFAULT_DB_CACHE_BATCH);\n    //! Coins a disconnect restored that the database may never have held (see DisconnectTip()): the next\n    //! run writes them first, before its marker, and a forced flush before anything (TakeRestored()). The\n    //! database may hold them from now on, so none of them stays fresh: a later spend is written as an\n    //! erase rather than dropped.\n    void KeepWritten(std::vector<CoinWrite> restored);\n    //! The restored coins not yet handed to a run, for a caller that writes them itself (a forced flush).\n    std::vector<CoinWrite> TakeRestored() { return std::exchange(m_restored, {}); }\n    const std::vector<CoinWrite>& Restored() const { return m_restored; }\n    //! The run has landed: its settled head is the database's state from now on.\n    void CommitWriteOut(const WriteOutRun& run);",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44byte_ledger_tests shifts a 32-bit size_t by 40 bitssrc/test/byte_ledger_tests.cpppartially_addressed
Assessment

The shift was reduced from 40 to 30, which avoids the reported 32-bit shift-width problem, but the finding's requested representable size_t value and reuse were not implemented. The new source still uses size_t{1} << 30, which is also too wide on 16-bit size_t targets if those are in scope; the supplied evidence does not establish those targets are supported.

path_diff: src/test/byte_ledger_tests.cpp; new_source: src/test/byte_ledger_tests.cpp

[
  {
    "evidence_id": "9cb02c00abd649c28c8637870ca9b560",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/test/byte_ledger_tests.cpp",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "diff --git a/src/test/byte_ledger_tests.cpp b/src/test/byte_ledger_tests.cpp\nindex 5ce9c5e08a..cc420b4016 100644\n--- a/src/test/byte_ledger_tests.cpp\n+++ b/src/test/byte_ledger_tests.cpp\n@@ -44,9 +44,9 @@ BOOST_AUTO_TEST_CASE(an_account_without_a_limit_is_counted_and_admits_everything\n {\n     ByteAccount account;\n     BOOST_CHECK_EQUAL(account.Limit(), 0U);\n-    account.Add(size_t{1} << 40);\n-    BOOST_CHECK(account.Admits(size_t{1} << 40));\n-    BOOST_CHECK_EQUAL(account.Bytes(), size_t{1} << 40);\n+    account.Add(size_t{1} << 30);\n+    BOOST_CHECK(account.Admits(size_t{1} << 30));\n+    BOOST_CHECK_EQUAL(account.Bytes(), size_t{1} << 30);\n }\n \n BOOST_AUTO_TEST_SUITE_END()\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 52,
    "evidence_id": "a799a654eadc49abbb5ddb8cd4bd3a3b",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 17,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/test/byte_ledger_tests.cpp",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "using Id = util::ByteAccountId;\n\nBOOST_FIXTURE_TEST_SUITE(byte_ledger_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(an_account_admits_up_to_its_limit)\n{\n    ByteAccount account;\n    account.SetLimit(100);\n    BOOST_CHECK(account.Admits());\n    BOOST_CHECK(account.Admits(100));\n    BOOST_CHECK(!account.Admits(101));\n\n    account.Add(60);\n    BOOST_CHECK(account.Admits(40));\n    BOOST_CHECK(!account.Admits(41));\n\n    // A holder may go over (one block is always in flight, whatever it weighs): nothing more is admitted\n    // until it is back within the limit.\n    account.Add(60);\n    BOOST_CHECK_EQUAL(account.Bytes(), 120U);\n    BOOST_CHECK(!account.Admits());\n    account.Sub(20);\n    BOOST_CHECK(account.Admits());\n    BOOST_CHECK(!account.Admits(1));\n}\n\nBOOST_AUTO_TEST_CASE(an_account_without_a_limit_is_counted_and_admits_everything)\n{\n    ByteAccount account;\n    BOOST_CHECK_EQUAL(account.Limit(), 0U);\n    account.Add(size_t{1} << 30);\n    BOOST_CHECK(account.Admits(size_t{1} << 30));\n    BOOST_CHECK_EQUAL(account.Bytes(), size_t{1} << 30);\n}\n\nBOOST_AUTO_TEST_SUITE_END()",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44The CoinsStore commit mixes an independent live prefetch changesrc/coins.cppstill_present
Assessment

The old and new src/coins.cpp excerpts show the same LOOKUPS_PER_TASK task-count adjustment in StartFetching(); no evidence shows it was separated into its own commit. This finding concerns commit organization, not whether the final code behavior changed.

old_source: src/coins.cpp; new_source: src/coins.cpp

[
  {
    "bounded": true,
    "end_line": 479,
    "evidence_id": "acc7409a81e94180be850e96503368c8",
    "finding_id": "finding:11",
    "kind": "old_source",
    "line": 384,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coins.cpp",
    "revision": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "        // Count the number of entries actually in the list.\n        ++count_linked;\n    }\n    assert(count_dirty == count_linked && count_dirty == m_dirty_count);\n    assert(recomputed_usage == cachedCoinsUsage);\n}\n\nCCoinsViewCache::ResetGuard CoinsViewOverlay::StartFetching(const CBlock& block LIFETIMEBOUND) noexcept\n{\n    Assert(m_futures.empty());\n    Assert(m_inputs.empty());\n    Assert(m_input_head.load(std::memory_order_relaxed) == 0);\n    Assert(m_input_tail == 0);\n    if (const auto workers_count{m_thread_pool->WorkersCount()}; workers_count > 0 && block.vtx.size() > 1) {\n        // Loop through the block inputs and set their prevouts in the queue.\n        // Filter inputs that spend outputs created earlier in the same block. These outputs will be created\n        // directly in the cache from the tx that creates them, so they will not be requested from a base view.\n        std::unordered_set<Txid, SaltedCoinsCacheHasher> earlier_txids;\n        earlier_txids.reserve(block.vtx.size());\n        earlier_txids.emplace(block.vtx[0]->GetHash());\n        for (const auto& tx : block.vtx | std::views::drop(1)) {\n            for (const auto& input : tx->vin) {\n                if (!earlier_txids.contains(input.prevout.hash)) m_inputs.emplace_back(input.prevout);\n            }\n            earlier_txids.emplace(tx->GetHash());\n        }\n        // Only submit tasks if we have something to fetch. One task per worker, but no more tasks than there are\n        // lookups to share out in batches of a few: every task wakes a worker, and a block with a handful of\n        // inputs should not wake the whole pool.\n        constexpr size_t LOOKUPS_PER_TASK{8};\n        if (const auto task_count{std::min<size_t>(workers_count, (m_inputs.size() + LOOKUPS_PER_TASK - 1) / LOOKUPS_PER_TASK)}; task_count > 0) {\n            std::vector<std::function<void()>> tasks(task_count, [this] {\n                WAITED_FOR_UNDER_LOCK(\"a block's input prefetch\"); // the tip's connect waits with cs_main held\n                while (ProcessInput()) {}\n            });\n            if (auto futures{m_thread_pool->Submit(std::move(tasks))}) {\n                m_futures = std::move(*futures);\n            } else {\n                // Submit can fail if a shared owner of the thread pool outside of this class calls Stop() or\n                // Interrupt() on a different thread after we call WorkersCount() above. In that case parallel\n                // fetching will not make progress, so we clear the inputs to fall back to single threaded fetching.\n                LogWarning(\"Failed to submit prevout fetch tasks (%s); falling back to single-threaded fetching for this block.\", SubmitErrorString(futures.error()));\n                m_inputs.clear();\n                StopFetching(); // Assert nothing changed if we failed to start tasks.\n            }\n        }\n    }\n    return CreateResetGuard();\n}\n\nstatic const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())};\nstatic const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT};\n\nconst Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)\n{\n    COutPoint iter(txid, 0);\n    while (iter.n < MAX_OUTPUTS_PER_BLOCK) {\n        const Coin& alternate = view.AccessCoin(iter);\n        if (!alternate.IsSpent()) return alternate;\n        ++iter.n;\n    }\n    return coinEmpty;\n}\n\ntemplate <typename ReturnType, typename Func>\nstatic ReturnType ExecuteBackedWrapper(Func func, const std::vector<std::function<void()>>& err_callbacks)\n{\n    try {\n        return func();\n    } catch(const std::runtime_error& e) {\n        for (const auto& f : err_callbacks) {\n            f();\n        }\n        LogError(\"Error reading from database: %s\\n\", e.what());\n        // Starting the shutdown sequence and returning false to the caller would be\n        // interpreted as 'entry not found' (as opposed to unable to read data), and\n        // could lead to invalid interpretation. Just exit immediately, as we can't\n        // continue anyway, and all writes should be atomic.\n        std::abort();\n    }\n}\n\nstd::optional<Coin> CCoinsViewErrorCatcher::GetCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);\n}\n\nbool CCoinsViewErrorCatcher::HaveCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<bool>([&]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);\n}\n\nstd::optional<Coin> CCoinsViewErrorCatcher::PeekCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::PeekCoin(outpoint); }, m_err_callbacks);\n}",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 479,
    "evidence_id": "8bc39826a83f49f3bf2cafce00547a41",
    "finding_id": "finding:11",
    "kind": "new_source",
    "line": 384,
    "new_head": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "old_head": "944454ba2aa024f5b0f0a6a728432c5264ea0dcc",
    "path": "src/coins.cpp",
    "revision": "ee04444c1d2ba791f52d6f1d3be5d31f5a1e8c61",
    "source_generation": 3,
    "source_job_id": 2996,
    "text": "        // Count the number of entries actually in the list.\n        ++count_linked;\n    }\n    assert(count_dirty == count_linked && count_dirty == m_dirty_count);\n    assert(recomputed_usage == cachedCoinsUsage);\n}\n\nCCoinsViewCache::ResetGuard CoinsViewOverlay::StartFetching(const CBlock& block LIFETIMEBOUND) noexcept\n{\n    Assert(m_futures.empty());\n    Assert(m_inputs.empty());\n    Assert(m_input_head.load(std::memory_order_relaxed) == 0);\n    Assert(m_input_tail == 0);\n    if (const auto workers_count{m_thread_pool->WorkersCount()}; workers_count > 0 && block.vtx.size() > 1) {\n        // Loop through the block inputs and set their prevouts in the queue.\n        // Filter inputs that spend outputs created earlier in the same block. These outputs will be created\n        // directly in the cache from the tx that creates them, so they will not be requested from a base view.\n        std::unordered_set<Txid, SaltedCoinsCacheHasher> earlier_txids;\n        earlier_txids.reserve(block.vtx.size());\n        earlier_txids.emplace(block.vtx[0]->GetHash());\n        for (const auto& tx : block.vtx | std::views::drop(1)) {\n            for (const auto& input : tx->vin) {\n                if (!earlier_txids.contains(input.prevout.hash)) m_inputs.emplace_back(input.prevout);\n            }\n            earlier_txids.emplace(tx->GetHash());\n        }\n        // Only submit tasks if we have something to fetch. One task per worker, but no more tasks than there are\n        // lookups to share out in batches of a few: every task wakes a worker, and a block with a handful of\n        // inputs should not wake the whole pool.\n        constexpr size_t LOOKUPS_PER_TASK{8};\n        if (const auto task_count{std::min<size_t>(workers_count, (m_inputs.size() + LOOKUPS_PER_TASK - 1) / LOOKUPS_PER_TASK)}; task_count > 0) {\n            std::vector<std::function<void()>> tasks(task_count, [this] {\n                WAITED_FOR_UNDER_LOCK(\"a block's input prefetch\"); // the tip's connect waits with cs_main held\n                while (ProcessInput()) {}\n            });\n            if (auto futures{m_thread_pool->Submit(std::move(tasks))}) {\n                m_futures = std::move(*futures);\n            } else {\n                // Submit can fail if a shared owner of the thread pool outside of this class calls Stop() or\n                // Interrupt() on a different thread after we call WorkersCount() above. In that case parallel\n                // fetching will not make progress, so we clear the inputs to fall back to single threaded fetching.\n                LogWarning(\"Failed to submit prevout fetch tasks (%s); falling back to single-threaded fetching for this block.\", SubmitErrorString(futures.error()));\n                m_inputs.clear();\n                StopFetching(); // Assert nothing changed if we failed to start tasks.\n            }\n        }\n    }\n    return CreateResetGuard();\n}\n\nstatic const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())};\nstatic const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT};\n\nconst Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)\n{\n    COutPoint iter(txid, 0);\n    while (iter.n < MAX_OUTPUTS_PER_BLOCK) {\n        const Coin& alternate = view.AccessCoin(iter);\n        if (!alternate.IsSpent()) return alternate;\n        ++iter.n;\n    }\n    return coinEmpty;\n}\n\ntemplate <typename ReturnType, typename Func>\nstatic ReturnType ExecuteBackedWrapper(Func func, const std::vector<std::function<void()>>& err_callbacks)\n{\n    try {\n        return func();\n    } catch(const std::runtime_error& e) {\n        for (const auto& f : err_callbacks) {\n            f();\n        }\n        LogError(\"Error reading from database: %s\\n\", e.what());\n        // Starting the shutdown sequence and returning false to the caller would be\n        // interpreted as 'entry not found' (as opposed to unable to read data), and\n        // could lead to invalid interpretation. Just exit immediately, as we can't\n        // continue anyway, and all writes should be atomic.\n        std::abort();\n    }\n}\n\nstd::optional<Coin> CCoinsViewErrorCatcher::GetCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);\n}\n\nbool CCoinsViewErrorCatcher::HaveCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<bool>([&]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);\n}\n\nstd::optional<Coin> CCoinsViewErrorCatcher::PeekCoin(const COutPoint& outpoint) const\n{\n    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::PeekCoin(outpoint); }, m_err_callbacks);\n}",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#44BeginWriteOut() accepts another run after write-out failuresrc/coinsstore.cppunclear
Assessment

The follow-up assessment was invalid: follow-up evidence belongs to another finding or comparison.

invalid_assessment

Source report · 944454ba2aa0..ee04444c1d2b

2026-11-25T01:58:34Z · gpt-6-luna

fork#47CoinsStore's class contract now precedes StoredCoinDatasrc/coinsstore.hunclear
Assessment

The follow-up assessment was invalid: addressed findings require original comparison evidence.

invalid_assessment

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47The coinsahead commit also carries an independent API-doc correctionsrc/kernel/bitcoinkernel.hunclear
Assessment

The supplied old-to-new diff shows changes to other files but no change to src/kernel/bitcoinkernel.h, and the available new-head excerpt still includes both the pinned-block budget text and the prepared-region clause. It does not establish whether the documentation correction was separated into the requested earlier commit; the base metadata differs, and the evidence is insufficient to distinguish author changes from rebase effects.

path_diff: src/kernel/bitcoinkernel.h; new_source: src/kernel/bitcoinkernel.h

[
  {
    "evidence_id": "ab91038b83434e50bf676f02e4c2b00e",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "e9034cfaacaa914bf5e50efb611d3bc45252767a",
    "old_head": "61de59296936210b94cf37d64afec03ce48b756d",
    "path": "src/kernel/bitcoinkernel.h",
    "source_generation": 3,
    "source_job_id": 2985,
    "text": "diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h\nindex 7be2754093..015b43b5a3 100644\n--- a/src/kernel/bitcoinkernel.h\n+++ b/src/kernel/bitcoinkernel.h\n@@ -540,7 +540,9 @@ typedef struct {\n     btck_NotifyProgress progress;           //!< Reports on current block synchronization progress.\n     btck_NotifyWarningSet warning_set;      //!< A warning issued by the kernel library during validation.\n     btck_NotifyWarningUnset warning_unset;  //!< A previous condition leading to the issuance of a warning is no longer given.\n-    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk.\n+    btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk. No later write of the block\n+                                            //!< index and the chainstate succeeds in this run: the caller may still read,\n+                                            //!< but has to stop processing blocks and restart to write again.\n     btck_NotifyFatalError fatal_error;      //!< An unrecoverable system error encountered by the library.\n } btck_NotificationInterfaceCallbacks;\n \n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1427,
    "evidence_id": "59de0a6cde664106a226367765f65aa5",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 1278,
    "new_head": "e9034cfaacaa914bf5e50efb611d3bc45252767a",
    "old_head": "61de59296936210b94cf37d64afec03ce48b756d",
    "path": "src/kernel/bitcoinkernel.h",
    "revision": "e9034cfaacaa914bf5e50efb611d3bc45252767a",
    "source_generation": 3,
    "source_job_id": 2985,
    "text": " * @param[in] blocks_directory Path string of the directory containing the block data. If the directory\n *                             does not exist yet, it will be created.\n * @return                     The allocated chainstate manager options, or null on error (e.g. if a path is invalid).\n */\nBITCOINKERNEL_API btck_ChainstateManagerOptions* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_create(\n    const btck_Context* context,\n    const char* data_directory,\n    size_t data_directory_len,\n    const char* blocks_directory,\n    size_t blocks_directory_len) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Set the number of available worker threads used during validation.\n *\n * @param[in] chainstate_manager_options Non-null, options to be set.\n * @param[in] worker_threads             The number of worker threads that should be spawned in the thread pool\n *                                       used for validation. When set to 0 no parallel verification is done.\n *                                       The value range is clamped internally between 0 and 15.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_set_worker_threads_num(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int worker_threads) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Set the total database cache used by the chainstate manager.\n *\n * The total cache is split internally between the block tree database,\n * chainstate database, and in-memory coins cache. If this function is not\n * called, the total cache defaults to 450 MiB. On top of it, whatever the\n * total cache size: up to 128 MiB of accepted blocks kept in memory until they\n * are connected, an eighth of the coins cache and 32 MiB at least for the\n * blocks being connected, up to 64 MiB of undo data waiting to be written, and\n * an eighth of the coins cache and 64 MiB at least for the blocks whose\n * notifications wait for an undo write (more while a reorganisation connects\n * its blocks). Further, 4 MiB for each chainstate that validated blocks beside\n * each other, and 32 MiB kept ready for coins once those in memory fill 1 GiB.\n *\n * @param[in] chainstate_manager_options Non-null, options to be set.\n * @param[in] database_cache_bytes       The total database cache size in bytes. Values below 4 MiB are rejected.\n *                                       On 32-bit systems, values above 1 GiB are also rejected.\n * @return                               0 if the set was successful, non-zero if the set failed.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_set_database_cache_bytes(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    uint64_t database_cache_bytes) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets wipe db in the options. In combination with calling\n * @ref btck_chainstate_manager_import_blocks this triggers either a full reindex,\n * or a reindex of just the chainstate database.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] wipe_block_tree_db         Set wipe block tree db. Should only be 1 if wipe_chainstate_db is 1 too.\n * @param[in] wipe_chainstate_db         Set wipe chainstate db.\n * @return                               0 if the set was successful, non-zero if the set failed.\n * @note                                 When a wipe is set, the caller must invoke @ref btck_chainstate_manager_import_blocks\n *                                       on the resulting chainstate manager before using it for anything else.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_set_wipe_dbs(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int wipe_block_tree_db,\n    int wipe_chainstate_db) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets block tree db in memory in the options.\n *\n * @param[in] chainstate_manager_options   Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] block_tree_db_in_memory      Set block tree db in memory.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_update_block_tree_db_in_memory(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int block_tree_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Sets chainstate db in memory in the options.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @param[in] chainstate_db_in_memory    Set chainstate db in memory.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_update_chainstate_db_in_memory(\n    btck_ChainstateManagerOptions* chainstate_manager_options,\n    int chainstate_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * Destroy the chainstate manager options.\n */\nBITCOINKERNEL_API void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* chainstate_manager_options);\n\n///@}\n\n/** @name ChainstateManager\n * Functions for chainstate management.\n */\n///@{\n\n/**\n * @brief Create a chainstate manager. This is the main object for many\n * validation tasks as well as for retrieving data from the chain and\n * interacting with its chainstate and indexes.\n *\n * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.\n * @return                               The allocated chainstate manager, or null on error.\n */\nBITCOINKERNEL_API btck_ChainstateManager* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_create(\n    const btck_ChainstateManagerOptions* chainstate_manager_options) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Get the btck_BlockTreeEntry whose associated btck_BlockHeader has the most\n * known cumulative proof of work.\n *\n * @param[in] chainstate_manager Non-null.\n * @return                       The btck_BlockTreeEntry, or null if no block headers have been loaded.\n */\nBITCOINKERNEL_API const btck_BlockTreeEntry* btck_chainstate_manager_get_best_entry(\n    const btck_ChainstateManager* chainstate_manager) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Processes and validates the provided btck_BlockHeader.\n *\n * @param[in] chainstate_manager        Non-null.\n * @param[in] header                    Non-null btck_BlockHeader to be validated.\n * @return                              The btck_BlockValidationState containing validation result, or null on error.\n */\nBITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_process_block_header(\n    btck_ChainstateManager* chainstate_manager,\n    const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1, 2);\n\n/**\n * @brief Triggers the start of a reindex if the wipe options were previously\n * set for the chainstate manager. Can also import an array of existing block\n * files selected by the user.\n *\n * Do not call this while another btck_chainstate_manager_import_blocks call\n * on the same chainstate manager is in progress. The process aborts when this\n * is detected.\n *\n * @param[in] chainstate_manager        Non-null.\n * @param[in] block_file_paths_data     Nullable, array of block files described by their full filesystem paths.\n * @param[in] block_file_paths_lens     Nullable, array containing the lengths of each of the paths.\n * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_len arrays.\n * @return                              0 if the import blocks call was completed successfully, non-zero otherwise.\n */\nBITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_import_blocks(\n    btck_ChainstateManager* chainstate_manager,\n    const char** block_file_paths_data, size_t* block_file_paths_lens,\n    size_t block_file_paths_data_len) BITCOINKERNEL_ARG_NONNULL(1);\n\n/**\n * @brief Process and validate the passed in block with the chainstate\n * manager. Processing first does checks on the block, and if these passed,",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47CollectChunk() makes an unnecessary owning StoredCoin copysrc/coinsstore.hunclear
Assessment

The supplied new-head evidence does not include CollectChunk or the CoinWrite construction, so it cannot establish whether the intermediate StoredCoin copy was removed.

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47The coinsahead handoff and shutdown paths lack deterministic testssrc/coinsstore.cppunclear
Assessment

The supplied new-head diff and source excerpts do not show whether a deterministic activation seam, allocation barrier, or targeted handoff and shutdown tests were added. The excerpts concern unrelated implementation and documentation changes.

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47Synchronous node-region faults can hold the shared depot mutexsrc/coinsstore.hunclear
Assessment

The supplied new-head excerpt ends before Depot::Take, where the region allocation, region-number write, and depot lock ordering need to be checked. The excerpt therefore cannot establish whether synchronous refill now prefaults outside the mutex.

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47The undo shortcut leaves its isolation precondition uncheckedsrc/coinsstore.cppunclear
Assessment

The supplied new-head evidence does not show the current ApplyChanges implementation or whether it rejects undo data in the window-view mode. The diff is truncated before the relevant caller and API-boundary logic, and the evidence explicitly notes that new source at the finding location is unavailable.

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#47Sparse output indices defeat KeyHash() collision randomizationsrc/coinsstore.hunclear
Assessment

The follow-up assessment was invalid: follow-up evidence belongs to another finding or comparison.

invalid_assessment

Source report · 61de59296936..e9034cfaacaa

2026-11-24T21:14:57Z · gpt-6-luna

fork#48ReorgReads is missing from the memory ledgersrc/validation.cppunclear
Assessment

The supplied excerpts do not include `util/byte_ledger.h` or the new-head holder summary. Although the old excerpt shows the 16-per-side read-ahead bound, the evidence is insufficient to determine whether the ledger entry and rationale were added.

new_source: src/validation.cpp; path_diff: src/validation.cpp

[
  {
    "bounded": true,
    "end_line": 4678,
    "evidence_id": "908c2cf640c34cc8a36a359d5da29afd",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 4529,
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "revision": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "            if (tx_undo.vprevout[j].nHeight == own_height) {\n                own_spent.push_back(&tx.vin[j].prevout);\n                continue;\n            }\n            groups.push_back(group_of(tx.vin[j].prevout));\n        }\n    }\n    static constexpr uint64_t SPREAD{0x9E3779B97F4A7C15ULL};\n    static thread_local std::vector<const COutPoint*> own_table;\n    const size_t own_mask{std::bit_ceil(std::max<size_t>(16, 2 * own_spent.size())) - 1};\n    if (!own_spent.empty()) {\n        own_table.assign(own_mask + 1, nullptr);\n        for (const COutPoint* spent : own_spent) {\n            size_t slot{((ReadLE64(spent->hash.ToUint256().data() + 16) ^ (uint64_t{spent->n} * SPREAD)) >> 1) & own_mask};\n            while (own_table[slot]) slot = (slot + 1) & own_mask;\n            own_table[slot] = spent;\n        }\n    }\n    // A byte for every spendable output, SKIP for one the block spent itself.\n    for (size_t t{0}; t < block.vtx.size(); ++t) {\n        const CTransaction& tx{*block.vtx[t]};\n        const uint64_t id{own_spent.empty() ? 0 : ReadLE64(tx.GetHash().ToUint256().data() + 16)};\n        for (uint32_t n{0}; n < tx.vout.size(); ++n) {\n            if (tx.vout[n].scriptPubKey.IsUnspendable()) continue;\n            bool spent_here{false};\n            if (!own_spent.empty()) {\n                for (size_t slot{((id ^ (uint64_t{n} * SPREAD)) >> 1) & own_mask}; own_table[slot]; slot = (slot + 1) & own_mask) {\n                    if (own_table[slot]->n != n || own_table[slot]->hash != tx.GetHash()) continue;\n                    spent_here = true;\n                    break;\n                }\n            }\n            groups.push_back(spent_here ? SKIP : group_of(COutPoint{tx.GetHash(), n}));\n        }\n    }\n    for (size_t g{0}; g < COMMIT_GROUPS; ++g) s.group_starts[g + 1] += s.group_starts[g];\n    std::array<uint32_t, COMMIT_GROUPS> next;\n    std::copy(s.group_starts.begin(), s.group_starts.end() - 1, next.begin());\n    s.items.resize(s.group_starts[COMMIT_GROUPS]);\n    size_t k{0};\n    for (size_t t{1}; t < block.vtx.size(); ++t) {\n        const CTransaction& tx{*block.vtx[t]};\n        const CTxUndo& tx_undo{undo.vtxundo[t - 1]};\n        for (size_t j{0}; j < tx.vin.size(); ++j) {\n            const Coin& coin{tx_undo.vprevout[j]};\n            if (coin.nHeight == own_height) continue;\n            s.items[next[groups[k++]]++] = {.at = &tx.vin[j].prevout, .n = (uint32_t{coin.nHeight} << 1) | uint32_t{coin.fCoinBase}, .flags = static_cast<uint8_t>(Item::SPEND | Item::KNOWN)};\n        }\n    }\n    for (size_t t{0}; t < block.vtx.size(); ++t) {\n        const CTransaction& tx{*block.vtx[t]};\n        const uint8_t flags{t == 0 ? Item::OVERWRITE : Item::FRESH};\n        for (uint32_t n{0}; n < tx.vout.size(); ++n) {\n            if (tx.vout[n].scriptPubKey.IsUnspendable()) continue;\n            const uint8_t g{groups[k++]};\n            if (g == SKIP) continue;\n            s.items[next[g]++] = {.at = &tx, .n = n, .flags = flags};\n        }\n    }\n    Assert(k == groups.size());\n    // Nothing reads the view's coins any more: what the block holds from here on is itself, its undo data\n    // and the items.\n    s.view->ChangesCommitted();\n}\n\n//! One commit: the complete, valid blocks at the front of the window that were not committed, applied by the\n//! connector, which starts it, and by the workers that come by meanwhile.\nstruct CommitJob {\n    //! The changes of its blocks, counted before any thread takes a group.\n    size_t items{0};\n    std::vector<StagedConnect*> blocks;\n    std::vector<int> heights;\n    //! Per group: 0 free, 1 taken, 2 applied.\n    std::array<std::atomic<uint8_t>, COMMIT_GROUPS> group_state{};\n    std::atomic<size_t> groups_done{0};\n    //! The items of every block are let go; the job is finished once the jobs below are.\n    bool ready{false};\n    std::atomic<size_t> next_clean{0};\n    std::atomic<size_t> cleaned{0};\n    //! The lowest of `blocks` with a conflict among its changes: that block and those above it are\n    //! taken back (TakeBackCommit()).\n    static constexpr uint32_t NO_CONFLICT{std::numeric_limits<uint32_t>::max()};\n    std::atomic<uint32_t> first_conflict{NO_CONFLICT};\n    //! The coins that creates of the job wrote over (a coinbase made twice), by block and item.\n    struct Overwritten {\n        uint32_t b;\n        uint32_t i;\n        Coin coin;\n    };\n    Mutex overwritten_mutex;\n    std::vector<Overwritten> overwritten GUARDED_BY(overwritten_mutex);\n};\n\nnamespace {\n//! One group's changes of every block of the commit, in height order: first a create and a later spend of\n//! the same coin inside the commit are dropped together, then the rest are applied block by block, each\n//! change made of the block's item at the apply.\nvoid CommitGroup(CommitJob& job, size_t g)\n{\n    using Item = BlockApplyView::CommitItem;\n    const uint32_t count{static_cast<uint32_t>(job.blocks.size())};\n    if (count > 1) {\n        // A table of the commit's creates without a node each: a tag of the outpoint, and where its item is. A\n        // create met twice is never netted (its slot is dead), which is what a tag's rare false match becomes too.\n        struct Slot {\n            uint64_t tag;\n            uint32_t b;\n            uint32_t i;\n        };\n        static constexpr uint32_t DEAD{std::numeric_limits<uint32_t>::max()};\n        const auto tag_of{[](const COutPoint& o) { return (ReadLE64(o.hash.ToUint256().data() + 16) ^ (uint64_t{o.n} * 0x9E3779B97F4A7C15ULL)) | 1; }};\n        size_t fresh{0};\n        for (uint32_t b{0}; b < count; ++b) {\n            const StagedConnect& s{*job.blocks[b]};\n            for (uint32_t i{s.group_starts[g]}; i < s.group_starts[g + 1]; ++i) fresh += !s.items[i].Spend() && (s.items[i].flags & Item::FRESH);\n        }\n        static thread_local std::vector<Slot> table;\n        const size_t mask{std::bit_ceil(std::max<size_t>(16, 2 * fresh)) - 1};\n        table.assign(mask + 1, Slot{0, 0, 0});\n        for (uint32_t b{0}; b < count; ++b) {\n            StagedConnect& s{*job.blocks[b]};\n            for (uint32_t i{s.group_starts[g]}; i < s.group_starts[g + 1]; ++i) {\n                const Item& item{s.items[i]};\n                if (!item.Spend()) {\n                    if (!(item.flags & Item::FRESH)) continue;\n                    const uint64_t tag{tag_of(item.Outpoint())};\n                    size_t slot{(tag >> 1) & mask};\n                    while (table[slot].tag != 0 && table[slot].tag != tag) slot = (slot + 1) & mask;\n                    if (table[slot].tag == 0) {\n                        table[slot] = {tag, b, i};\n                    } else {\n                        table[slot].b = DEAD;\n                    }\n                } else if (item.flags & Item::KNOWN) {\n                    const COutPoint outpoint{item.Outpoint()};\n                    const uint64_t tag{tag_of(outpoint)};\n                    size_t slot{(tag >> 1) & mask};\n                    while (table[slot].tag != 0 && table[slot].tag != tag) slot = (slot + 1) & mask;\n                    if (table[slot].tag == 0 || table[slot].b == DEAD) continue;\n                    const uint32_t cb{table[slot].b}, ci{table[slot].i};\n                    if (job.heights[cb] != static_cast<int>(item.n >> 1)) continue;\n                    if (job.blocks[cb]->items[ci].Outpoint() != outpoint) continue;\n                    job.blocks[cb]->items[ci].flags |= Item::DROPPED;\n                    s.items[i].flags |= Item::DROPPED;\n                    table[slot].b = DEAD;\n                }\n            }\n        }\n    }\n    std::vector<COutPoint> outpoints;",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "evidence_id": "0e9dca5278ee4f4d8aeb368a73cf1c15",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex 3323476b87..68c1909e60 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -119,12 +119,11 @@ static void CheckBlockStoreTransition(std::optional<node::BlockStoreState> befor\n \n /**\n  * The tasks validation runs where no caller is on the stack to decide what a std::runtime_error means\n- * (util/worker_task.h): a block's validation and its continuation on a connect pool worker, and a coins\n+ * (util/worker_task.h): a block's parse and its validation on a connect pool worker, and a coins\n  * write-out run and a block's undo write on the effects executor. Each reads or writes the node's own data,\n  * so each stops the node; the name is what the log and the fatal error begin with.\n  */\n static constexpr util::WorkerTaskType CONNECT_TASK{\"ConnectBlock\"};\n-static constexpr util::WorkerTaskType CONTINUATION_TASK{\"FinishDeferredTransactions\"};\n static constexpr util::WorkerTaskType WRITE_OUT_TASK{\"Coins write-out run failed\"};\n static constexpr util::WorkerTaskType UNDO_WRITE_TASK{\"Block undo write failed\"};\n \n@@ -1916,7 +1915,7 @@ BlockApplyView* CoinsViews::FreeApplyView()\n {\n     AssertLockHeld(::cs_main);\n     for (auto& view : m_apply_views) {\n-        if (!view->HasBlock()) return view.get();\n+        if (!view->InUse()) return view.get();\n     }\n     return nullptr;\n }\n@@ -2019,6 +2018,15 @@ void Chainstate::ResetCoinsViews()\n     m_coins_views.reset();\n }\n \n+//! The block a ChainStateFlushed names for coins written at `written`. Where that is the block being published,\n+//! one above the tip (precondition O8), its BlockConnected leaves after the signal, and a synced index would find\n+//! the locator off its chain and skip its commit: the signal names the tip, which the index has seen, and the\n+//! index catches up from there. Decided when the write starts, before the block's signal is queued.\n+static const CBlockIndex* FlushedSignalBlock(const CBlockIndex* written, const CChain& chain)\n+{\n+    return written && written != chain.Tip() && written->pprev == chain.Tip() ? written->pprev : written;\n+}\n+\n void Chainstate::SettleWriteOut()\n {\n     AssertLockHeld(::cs_main);\n@@ -2075,8 +2083,17 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n         bool for_prune;\n     };\n     const FlushTrace trace{NodeClock::now(), store.GetCacheSize(), store.DynamicMemoryUsage(), mode, for_prune};\n+    // See CommitGate. A commit that started first holds the run back.\n+    m_commit_gate.run_active.store(true);\n+    if (m_commit_gate.ahead.load() > 0) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     std::shared_ptr<CoinsStore::WriteOutRun> run{store.BeginWriteOut(bound_height, head->nHeight, head->GetBlockHash(), final)};\n-    if (!run) return true;\n+    if (!run) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     LogDebug(BCLog::COINDB, \"Starting a coins write-out run: changes at or below height %d, head %d%s\",\n              bound_height, head->nHeight, run->final ? \", final\" : \"\");\n \n@@ -2088,6 +2105,7 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n     // one state of it. The head and its ancestors do not change in the block index, so the effect looks the\n     // settled head up there.\n     auto index_batch{std::make_shared<node::BlockManager::IndexBatch>(m_blockman.PrepareBlockIndexBatch())};\n+    const CBlockIndex* signal_at{FlushedSignalBlock(head, m_chain)};\n     node::BlockManager& blockman{m_blockman};\n     CCoinsViewDB& db{CoinsDB()};\n     m_blockman.m_effects.Enqueue(\n@@ -2114,17 +2132,19 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (failure) LogError(\"%s\", failure->what);\n             return written || fail();\n         },\n-        [this, run, evict_to, trace](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n+        [this, run, evict_to, trace, signal_at](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n             AssertLockHeld(::cs_main);\n             if (!m_coins_views || !m_coins_views->m_store) return;\n             CoinsStore& store{CoinsStoreTip()};\n             if (!ok) {\n+                // A failed run never ends, and the commits stay off: the node is stopping.\n                 store.AbandonWriteOut();\n                 ++m_write_out_runs_failed;\n                 m_chainman.GetNotifications().fatalError(_(\"System error while writing the chainstate to disk.\"));\n                 return;\n             }\n             store.CommitWriteOut(*run);\n+            m_commit_gate.run_active.store(false);\n             (void)trace;\n             TRACEPOINT(utxocache, flush,\n                 int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - trace.start)},\n@@ -2138,29 +2158,34 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (evict_to) store.EvictClean(*evict_to);\n             m_last_flushed_block = m_blockman.LookupBlockIndex(run->new_head);\n             if (m_chainman.m_options.signals) {\n-                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n-            }\n-            if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n-                try {\n-                    CoinsDB().CompactFullAsync();\n-                } catch (const std::system_error& e) { // what std::async throws when no thread can be started\n-                    LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n-                }\n+                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(signal_at));\n             }\n+            // As after a synchronous write, with its check of the room a compaction needs.\n+            MaybeCompactChainstate();\n         },\n         0);\n     return true;\n }\n \n+node::BlockCache::Tips ChainstateManager::BlockCacheTips() const\n+{\n+    AssertLockHeld(::cs_main);\n+    node::BlockCache::Tips tips{.active = ActiveHeight()};\n+    if (const Chainstate* historical{HistoricalChainstate()}) {\n+        if (const CBlockIndex* base{CurrentChainstate().SnapshotBase()}) {\n+            tips.historical = historical->m_chain.Height();\n+            tips.historical_end = base->nHeight;\n+        }\n+    }\n+    return tips;\n+}\n+\n int ChainstateManager::ConnectWindow() const\n {\n     // By default twice as wide as the pool. The blocks are confirmed in order, so a window as wide as the\n     // pool leaves a worker without a block whenever one behind the oldest finishes first. What the blocks\n     // in flight hold in memory is bounded separately, by bytes (WINDOW_BYTES_SHARE).\n     const int window{m_options.connect_window > 0 ? m_options.connect_window : 2 * static_cast<int>(m_connect_pool->WorkersCount())};\n-    // No block of a window spends the coinbase of another, which the coin store's write-out rests on\n-    // (CoinsStore::CollectRecords()).\n-    static_assert(MAX_CONNECT_WINDOW < COINBASE_MATURITY);\n     return std::clamp(window, 1, MAX_CONNECT_WINDOW);\n }\n \n@@ -2736,29 +2761,12 @@ BlockValidationContext ChainstateManager::MakeBlockValidationContext(const uint2\n         .enforce_bip30 = EnforceBIP30(block_hash, prev ? prev->nHeight + 1 : 0, prev, GetConsensus(), GetParams().Bip30Off()),\n         // Callable without cs_main, see BlockValidationContext::median_time_past_at.\n         .median_time_past_at = [prev](int height) { return Assert(Assert(prev)->GetAncestor(height))->GetMedianTimePast(); },\n-        .defer_missing_inputs = false,\n     };\n }\n \n \n-\n-//! Whether BIP30 is checked for the block or for one that can be open in the connect window below it.\n-//! Such a block's spends leave a marker in the store even of a coin never written, so that a lower block\n-//! that makes the outpoint again does not find it gone (CoinsStore::BeginBlock()). The check is on below\n-//! BIP34 and from the height where it is on again (EnforceBIP30()), so the block and the lowest that can\n-//! be open with it decide. The two blocks below BIP34 that are exempt from the check, 91842 and 91880\n-//! (IsBIP30Repeat()), do not change that: where one of them is the block, the lowest that can be open with\n-//! it is checked, and where one of them is the lowest, the block is checked.\n-//! A block connected alone has no block open below it, and needs no marker.\n-static bool OpenBlocksCheckBIP30(const CBlockIndex& pindex, const Consensus::Params& params, bool bip30_off)\n-{\n-    if (!pindex.pprev || ConnectBlockChecksBIP30(pindex, params, bip30_off)) return true; // the genesis block spends nothing\n-    const int lowest{std::max(1, pindex.nHeight - static_cast<int>(CoinsStore::MAX_WINDOW_SLOTS))};\n-    return ConnectBlockChecksBIP30(*Assert(pindex.GetAncestor(lowest)), params, bip30_off);\n-}\n-\n //! Add a transaction's signature operations to the block's and check the block's limit. One copy of the rule,\n-//! for a coinbase, a transaction checked in order and a deferred one.\n+//! for a coinbase and for any other transaction.\n static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view, script_verify_flags flags,\n                            int64_t& sigops_cost, BlockValidationState& state)\n {\n@@ -2773,36 +2781,19 @@ static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view,\n     return true;\n }\n \n-//! Check that the coinbase pays no more than the subsidy and the block's fees. One copy of the rule, for a\n-//! block whose fees ConnectBlock() totalled and one whose total FinishDeferredTransactions() completed.\n-static bool CheckCoinbaseAmount(const CBlock& block, const BlockValidationContext& ctx, CAmount fees, BlockValidationState& state)\n-{\n-    const CAmount block_reward{fees + GetBlockSubsidy(ctx.height, ctx.params)};\n-    if (block.vtx[0]->GetValueOut() > block_reward) {\n-        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-cb-amount\",\n-                             strprintf(\"coinbase pays too much (actual=%d vs limit=%d)\", block.vtx[0]->GetValueOut(), block_reward));\n-    }\n-    return true;\n-}\n-\n //! The consensus checks of one transaction that is not a coinbase against the coins in `view`, in their order:\n //! its inputs and fee, the block's accumulated fee, BIP68, the block's signature operations, and, if\n //! `check_scripts`, its scripts, run here or appended to `checks` for a check queue. The block's totals `fees`\n //! and `sigops_cost` grow by the transaction's. False, with `state` set, on a failure, which is the block's.\n-//! Shared by ConnectBlock() and FinishDeferredTransactions(). `inputs_found`: the caller has found every\n-//! input of the transaction in the view, unspent, and the view is unchanged since, so the walk that looks\n-//! for a missing input is skipped.\n static bool CheckBlockTransaction(const CTransaction& tx, const BlockValidationContext& ctx, const CCoinsViewCache& view,\n                                   script_verify_flags flags, int lock_time_flags, bool check_scripts, bool cache_results,\n                                   PrecomputedTransactionData& txdata, ValidationCache& validation_cache,\n                                   std::vector<CScriptCheck>* checks, std::vector<int>& prevheights,\n-                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state,\n-                                  bool inputs_found = false)\n+                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state)\n {\n     CAmount txfee = 0;\n     TxValidationState tx_state;\n-    if (!(inputs_found ? Consensus::CheckAvailableTxInputs(tx, tx_state, view, ctx.height, txfee)\n-                       : Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee))) {\n+    if (!Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee)) {\n         // Any transaction validation failure in ConnectBlock is a block consensus failure\n         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,\n                              tx_state.GetRejectReason(),\n@@ -2874,8 +2865,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -2890,15 +2883,9 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n \n     // BIP30: no transaction may overwrite one that is not completely spent. Whether the rule\n     // applies to this block was decided when the context was built, see EnforceBIP30().\n-    if (ctx.enforce_bip30) {\n-        for (const auto& tx : block.vtx) {\n-            for (size_t o = 0; o < tx->vout.size(); o++) {\n-                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n-                                  \"tried to overwrite transaction\");\n-                }\n-            }\n-        }\n+    if (ctx.enforce_bip30 && view.HaveAnyOutput(block.vtx)) {\n+        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n+                      \"tried to overwrite transaction\");\n     }\n \n     // Enforce BIP68 (sequence locks)\n@@ -2931,8 +2918,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     }\n \n     std::vector<int> prevheights;\n-    //! This block's transaction ids in sorted order, built when the first transaction is deferred.\n-    std::vector<Txid> block_txids;\n     CAmount nFees = 0;\n     int& nInputs{result.num_inputs};\n     int64_t& nSigOpsCost{result.sigops_cost};\n@@ -2940,70 +2925,18 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     for (unsigned int i = 0; i < block.vtx.size(); i++)\n     {\n         if (!state.IsValid()) break;\n+        if (ctx.help_point && (i & 63) == 63) ctx.help_point();\n+        if (ctx.implicit_creates) ctx.implicit_creates(i);\n         const CTransaction &tx = *(block.vtx[i]);\n \n         nInputs += tx.vin.size();\n \n-        // In a block that may defer, a lower block in flight can show the outputs of a transaction while its\n-        // spends are still to be applied. A transaction with an unspent coin of its own txid among the coins\n-        // the view holds (HaveCoinInCache()) repeats an earlier one, whose inputs it shares and which spent\n-        // them: no lower block can make it valid, and creating its outputs would overwrite that coin, which\n-        // the view refuses with an exception. A coin of the store the view did not fetch, or one this block\n-        // spent before the repeat, is met at the apply as a conflict (BlockApplyView::ApplyChanges()). The\n-        // block fails here, which in the window decides nothing: it is connected again alone, where BIP30 or\n-        // the spent inputs reject it.\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs) {\n-            for (uint32_t o{0}; o < tx.vout.size(); ++o) {\n-                if (view.HaveCoinInCache(COutPoint{tx.GetHash(), o})) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + tx.GetHash().ToString() + \" repeats one with an unspent output\");\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-        }\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs && !view.HaveInputs(tx)) {\n-            // A lower block that is still being applied may hold the missing input. Not so for an input\n-            // from one of this block's own transactions: it is missing because it is produced later in the\n-            // block (or is this transaction's own, or was spent earlier), which validating in order rejects\n-            // at this point, and so does this.\n-            if (block_txids.empty()) {\n-                block_txids.reserve(block.vtx.size());\n-                for (const auto& block_tx : block.vtx) block_txids.push_back(block_tx->GetHash());\n-                std::sort(block_txids.begin(), block_txids.end());\n-                // A transaction the block holds twice. No lower block can make that valid: the second\n-                // copy spends what the first spent. (The merkle root's check for mutation only catches\n-                // copies that are paired in the tree.) Its outputs must not be created a second time.\n-                if (const auto twice{std::adjacent_find(block_txids.begin(), block_txids.end())}; twice != block_txids.end()) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + twice->ToString() + \" is in the block twice\");\n-                    break;\n-                }\n-            }\n-            for (const CTxIn& txin : tx.vin) {\n-                if (std::binary_search(block_txids.begin(), block_txids.end(), txin.prevout.hash) && !view.HaveCoin(txin.prevout)) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"input from this block missing or spent in transaction \" + tx.GetHash().ToString());\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-            // The transaction's outputs are created now, so that later transactions of this block can spend\n-            // them; everything else about it waits for FinishDeferredTransactions(), as do the block's totals.\n-            result.deferred_txs.push_back(i);\n-            if (i > 0) blockundo.vtxundo.emplace_back();\n-            AddCoins(view, tx, ctx.height);\n-            continue;\n-        }\n-\n         if (!tx.IsCoinBase()) {\n             const bool fCacheResults = just_check; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */\n             std::vector<CScriptCheck> vChecks;\n             PrecomputedTransactionData own_txdata;\n-            // In a block that may defer, the test above found every input (or the transaction was deferred).\n             if (!CheckBlockTransaction(tx, ctx, view, flags, nLockTimeFlags, fScriptChecks, fCacheResults, control ? txsdata[i] : own_txdata, validation_cache,\n-                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state,\n-                                       /*inputs_found=*/ctx.defer_missing_inputs)) {\n+                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state)) {\n                 break;\n             }\n             if (control) control->Add(std::move(vChecks));\n@@ -3016,14 +2949,27 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         if (i > 0) {\n             blockundo.vtxundo.emplace_back();\n         }\n-        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), ctx.height);\n+        if (ctx.implicit_creates) {\n+            // The inputs are spent; the outputs are the window's (WindowOutputs), and never the view's.\n+            if (i > 0) {\n+                CTxUndo& txundo{blockundo.vtxundo.back()};\n+                txundo.vprevout.reserve(tx.vin.size());\n+                for (const CTxIn& txin : tx.vin) {\n+                    txundo.vprevout.emplace_back();\n+                    const bool is_spent{view.SpendCoin(txin.prevout, &txundo.vprevout.back())};\n+                    assert(is_spent);\n+                }\n+            }\n+        } else {\n+     \n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 141ff08765a3..26065d4b5dc6

2026-11-25T02:35:08Z · gpt-6-luna

fork#48Failed undo read-ahead lacks fallback coveragesrc/validation.cppunclear
Assessment

The new-head excerpt does not show the speculative undo-read path or a failure-injection regression test. It therefore cannot establish whether the fallback scenario was addressed.

new_source: src/validation.cpp; path_diff: src/validation.cpp

[
  {
    "bounded": true,
    "end_line": 3894,
    "evidence_id": "b85f55ba590145f2b9fd53301fb62a7c",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 3745,
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "revision": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "    LogDebug(BCLog::BENCH, \"- Disconnect block: %.2fms\\n\",\n             Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));\n\n    {\n        // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg\n        const int max_height_first{pindexDelete->nHeight - 1};\n        for (auto& prune_lock : m_blockman.m_prune_locks) {\n            if (prune_lock.second.height_first <= max_height_first) continue;\n\n            prune_lock.second.height_first = max_height_first;\n            LogDebug(BCLog::PRUNE, \"%s prune lock moved back to %d\\n\", prune_lock.first, max_height_first);\n        }\n    }\n\n    // Write the chain state to disk, if necessary.\n    if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {\n        return false;\n    }\n\n    if (disconnectpool && m_mempool) {\n        // Save transactions to re-add to mempool at end of reorg. If any entries are evicted for\n        // exceeding memory limits, remove them and their descendants from the mempool.\n        for (auto&& evicted_tx : disconnectpool->AddTransactionsFromBlock(block.vtx)) {\n            m_mempool->removeRecursive(*evicted_tx, MemPoolRemovalReason::REORG);\n        }\n    }\n\n    const auto store_before{BlockStoreStateOf(*pindexDelete, m_chain)};\n    // Before the tip and the initial block download latch change.\n    m_chainman.MarkTipChanged();\n    m_chain.SetTip(*pindexDelete->pprev);\n    CheckBlockStoreTransition(store_before, BlockStoreEvent::Disconnect, *pindexDelete, m_chain);\n    m_chainman.UpdateIBDStatus();\n\n    UpdateTip(pindexDelete->pprev);\n    // Let wallets know transactions went from 1-confirmed to\n    // 0-confirmed or conflicted:\n    if (m_chainman.m_options.signals) {\n        // Precondition O7: queued under cs_main, in the hold in which the block left the chain. True by\n        // the statement above; checked so that a reordering of this function keeps it.\n        Assume(!m_chain.Contains(*pindexDelete));\n        // And no signal still waits on the effects queue, which this one would overtake: the callers settle\n        // them before the first disconnect. A waiting BlockConnected holds its block in the ledger's\n        // account; the queue has nothing left for either.\n        Assume(m_chainman.m_bytes_in_flight[util::ByteAccountId::PinnedBlocks].Bytes() == 0);\n        Assume(m_blockman.m_effects.Idle());\n        m_chainman.m_options.signals->BlockDisconnected(std::move(pblock), pindexDelete);\n    }\n    return true;\n}\n\n/**\n * The blocks each thread built in a task on the connect pool, back from their last holder: see\n * ChainstateManager::NewBlock(). A bin outlives the manager for as long as a block of its thread is held.\n */\nclass BlockBins\n{\n    struct Bin {\n        Mutex mutex;\n        std::vector<CBlock*> blocks GUARDED_BY(mutex);\n        //! Whether a block may wait here: read without the mutex (EmptyMine()).\n        std::atomic<bool> any{false};\n        void Empty() EXCLUSIVE_LOCKS_REQUIRED(!mutex)\n        {\n            if (!any.exchange(false, std::memory_order_acq_rel)) return;\n            for (const CBlock* block : WITH_LOCK(mutex, return std::exchange(blocks, {}))) delete block;\n        }\n        ~Bin() { Empty(); }\n    };\n    Mutex m_mutex;\n    std::map<std::thread::id, std::shared_ptr<Bin>> m_bins GUARDED_BY(m_mutex);\n\npublic:\n    //! A block for the calling thread, which first frees the blocks that came back to it.\n    std::shared_ptr<CBlock> NewBlock() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)\n    {\n        std::shared_ptr<Bin> bin;\n        {\n            LOCK(m_mutex);\n            auto& mine{m_bins[std::this_thread::get_id()]};\n            if (!mine) mine = std::make_shared<Bin>();\n            bin = mine;\n        }\n        bin->Empty();\n        return {new CBlock, [bin](CBlock* block) {\n            WITH_LOCK(bin->mutex, bin->blocks.push_back(block));\n            bin->any.store(true, std::memory_order_release);\n        }};\n    }\n    //! Free the blocks that came back to the calling thread, which need not build one for it: a worker\n    //! that validates and commits for a while between two parses would keep them until the next. The thread\n    //! remembers its bin, so that nothing is locked where no block waits.\n    void EmptyMine() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)\n    {\n        static thread_local std::pair<const BlockBins*, std::shared_ptr<Bin>> mine;\n        if (mine.first != this) {\n            LOCK(m_mutex);\n            const auto it{m_bins.find(std::this_thread::get_id())};\n            if (it == m_bins.end()) return;\n            mine = {this, it->second};\n        }\n        mine.second->Empty();\n    }\n    //! Free the blocks that came back to every thread.\n    void Empty() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)\n    {\n        LOCK(m_mutex);\n        for (const auto& [id, bin] : m_bins) bin->Empty();\n    }\n};\n\nstruct StagedConnect;\nstruct CommitJob;\n\n/**\n * The window's outputs overlay. A window block's worker enters the block's transactions here after the\n * parse, and its validation starts only once every lower block in flight has\n * (Chainstate::OnWindowBlockIndexed()). An input the block's view does not hold is looked for here first: made\n * by a block between the last published one and its own, it is that transaction's output, which the store\n * does not have yet. Every other input is the store's to answer (BlockApplyView::ReadBase()).\n *\n * The overlay knows what the window's blocks make, not what they spend. A block that spends a coin a lower\n * block of the window spent as well is therefore validated with that coin; the double spend is met when the\n * block is committed, where its spend finds no coin (CoinsStore::ApplyConfirmed()). The other way round, a\n * block may be found invalid here that is not (the store still shows a coin a lower block spends, for the\n * BIP30 check); a block that fails in the window is connected alone again, which decides.\n *\n * All the window's blocks are in one table, in shards by the transaction id, each under its mutex: a read is\n * one probe, however many blocks the window holds, and a block's reads are made shard by shard. An item keeps\n * its block's height, and the block itself is found by the height (m_ring). A published block's items are\n * taken out by the workers, once they have entered a block (Sweep()), never by the publishing thread; a\n * block is let go once its items are out of every shard, and an item is read under its shard's mutex, so the\n * block of an item found is there.\n */\nclass WindowOutputs final : public WindowCoinSource\n{\npublic:\n    void SetPublished(int height) { m_published.store(height, std::memory_order_release); }\n    void Index(int height, std::shared_ptr<const CBlock> block) EXCLUSIVE_LOCKS_REQUIRED(!m_released_mutex)\n    {\n        Held& held{m_ring[height % RING]};\n        // The place's last block is published, and its items are still in the table or on their way out.\n        while (held.at.load(std::memory_order_acquire) != nullptr) {\n            if (!EraseOne()) std::this_thread::yield();\n        }\n        static thread_local std::vector<uint64_t> tags;\n        static thread_local std::vector<uint32_t> order;\n        std::array<uint32_t, SHARDS + 1> start;\n        Tags(*block, tags);\n        Group(tags, order, start);",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "evidence_id": "9fbcfcff7fb14f90a27162bdf6695fda",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex 3323476b87..68c1909e60 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -119,12 +119,11 @@ static void CheckBlockStoreTransition(std::optional<node::BlockStoreState> befor\n \n /**\n  * The tasks validation runs where no caller is on the stack to decide what a std::runtime_error means\n- * (util/worker_task.h): a block's validation and its continuation on a connect pool worker, and a coins\n+ * (util/worker_task.h): a block's parse and its validation on a connect pool worker, and a coins\n  * write-out run and a block's undo write on the effects executor. Each reads or writes the node's own data,\n  * so each stops the node; the name is what the log and the fatal error begin with.\n  */\n static constexpr util::WorkerTaskType CONNECT_TASK{\"ConnectBlock\"};\n-static constexpr util::WorkerTaskType CONTINUATION_TASK{\"FinishDeferredTransactions\"};\n static constexpr util::WorkerTaskType WRITE_OUT_TASK{\"Coins write-out run failed\"};\n static constexpr util::WorkerTaskType UNDO_WRITE_TASK{\"Block undo write failed\"};\n \n@@ -1916,7 +1915,7 @@ BlockApplyView* CoinsViews::FreeApplyView()\n {\n     AssertLockHeld(::cs_main);\n     for (auto& view : m_apply_views) {\n-        if (!view->HasBlock()) return view.get();\n+        if (!view->InUse()) return view.get();\n     }\n     return nullptr;\n }\n@@ -2019,6 +2018,15 @@ void Chainstate::ResetCoinsViews()\n     m_coins_views.reset();\n }\n \n+//! The block a ChainStateFlushed names for coins written at `written`. Where that is the block being published,\n+//! one above the tip (precondition O8), its BlockConnected leaves after the signal, and a synced index would find\n+//! the locator off its chain and skip its commit: the signal names the tip, which the index has seen, and the\n+//! index catches up from there. Decided when the write starts, before the block's signal is queued.\n+static const CBlockIndex* FlushedSignalBlock(const CBlockIndex* written, const CChain& chain)\n+{\n+    return written && written != chain.Tip() && written->pprev == chain.Tip() ? written->pprev : written;\n+}\n+\n void Chainstate::SettleWriteOut()\n {\n     AssertLockHeld(::cs_main);\n@@ -2075,8 +2083,17 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n         bool for_prune;\n     };\n     const FlushTrace trace{NodeClock::now(), store.GetCacheSize(), store.DynamicMemoryUsage(), mode, for_prune};\n+    // See CommitGate. A commit that started first holds the run back.\n+    m_commit_gate.run_active.store(true);\n+    if (m_commit_gate.ahead.load() > 0) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     std::shared_ptr<CoinsStore::WriteOutRun> run{store.BeginWriteOut(bound_height, head->nHeight, head->GetBlockHash(), final)};\n-    if (!run) return true;\n+    if (!run) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     LogDebug(BCLog::COINDB, \"Starting a coins write-out run: changes at or below height %d, head %d%s\",\n              bound_height, head->nHeight, run->final ? \", final\" : \"\");\n \n@@ -2088,6 +2105,7 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n     // one state of it. The head and its ancestors do not change in the block index, so the effect looks the\n     // settled head up there.\n     auto index_batch{std::make_shared<node::BlockManager::IndexBatch>(m_blockman.PrepareBlockIndexBatch())};\n+    const CBlockIndex* signal_at{FlushedSignalBlock(head, m_chain)};\n     node::BlockManager& blockman{m_blockman};\n     CCoinsViewDB& db{CoinsDB()};\n     m_blockman.m_effects.Enqueue(\n@@ -2114,17 +2132,19 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (failure) LogError(\"%s\", failure->what);\n             return written || fail();\n         },\n-        [this, run, evict_to, trace](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n+        [this, run, evict_to, trace, signal_at](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n             AssertLockHeld(::cs_main);\n             if (!m_coins_views || !m_coins_views->m_store) return;\n             CoinsStore& store{CoinsStoreTip()};\n             if (!ok) {\n+                // A failed run never ends, and the commits stay off: the node is stopping.\n                 store.AbandonWriteOut();\n                 ++m_write_out_runs_failed;\n                 m_chainman.GetNotifications().fatalError(_(\"System error while writing the chainstate to disk.\"));\n                 return;\n             }\n             store.CommitWriteOut(*run);\n+            m_commit_gate.run_active.store(false);\n             (void)trace;\n             TRACEPOINT(utxocache, flush,\n                 int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - trace.start)},\n@@ -2138,29 +2158,34 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (evict_to) store.EvictClean(*evict_to);\n             m_last_flushed_block = m_blockman.LookupBlockIndex(run->new_head);\n             if (m_chainman.m_options.signals) {\n-                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n-            }\n-            if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n-                try {\n-                    CoinsDB().CompactFullAsync();\n-                } catch (const std::system_error& e) { // what std::async throws when no thread can be started\n-                    LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n-                }\n+                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(signal_at));\n             }\n+            // As after a synchronous write, with its check of the room a compaction needs.\n+            MaybeCompactChainstate();\n         },\n         0);\n     return true;\n }\n \n+node::BlockCache::Tips ChainstateManager::BlockCacheTips() const\n+{\n+    AssertLockHeld(::cs_main);\n+    node::BlockCache::Tips tips{.active = ActiveHeight()};\n+    if (const Chainstate* historical{HistoricalChainstate()}) {\n+        if (const CBlockIndex* base{CurrentChainstate().SnapshotBase()}) {\n+            tips.historical = historical->m_chain.Height();\n+            tips.historical_end = base->nHeight;\n+        }\n+    }\n+    return tips;\n+}\n+\n int ChainstateManager::ConnectWindow() const\n {\n     // By default twice as wide as the pool. The blocks are confirmed in order, so a window as wide as the\n     // pool leaves a worker without a block whenever one behind the oldest finishes first. What the blocks\n     // in flight hold in memory is bounded separately, by bytes (WINDOW_BYTES_SHARE).\n     const int window{m_options.connect_window > 0 ? m_options.connect_window : 2 * static_cast<int>(m_connect_pool->WorkersCount())};\n-    // No block of a window spends the coinbase of another, which the coin store's write-out rests on\n-    // (CoinsStore::CollectRecords()).\n-    static_assert(MAX_CONNECT_WINDOW < COINBASE_MATURITY);\n     return std::clamp(window, 1, MAX_CONNECT_WINDOW);\n }\n \n@@ -2736,29 +2761,12 @@ BlockValidationContext ChainstateManager::MakeBlockValidationContext(const uint2\n         .enforce_bip30 = EnforceBIP30(block_hash, prev ? prev->nHeight + 1 : 0, prev, GetConsensus(), GetParams().Bip30Off()),\n         // Callable without cs_main, see BlockValidationContext::median_time_past_at.\n         .median_time_past_at = [prev](int height) { return Assert(Assert(prev)->GetAncestor(height))->GetMedianTimePast(); },\n-        .defer_missing_inputs = false,\n     };\n }\n \n \n-\n-//! Whether BIP30 is checked for the block or for one that can be open in the connect window below it.\n-//! Such a block's spends leave a marker in the store even of a coin never written, so that a lower block\n-//! that makes the outpoint again does not find it gone (CoinsStore::BeginBlock()). The check is on below\n-//! BIP34 and from the height where it is on again (EnforceBIP30()), so the block and the lowest that can\n-//! be open with it decide. The two blocks below BIP34 that are exempt from the check, 91842 and 91880\n-//! (IsBIP30Repeat()), do not change that: where one of them is the block, the lowest that can be open with\n-//! it is checked, and where one of them is the lowest, the block is checked.\n-//! A block connected alone has no block open below it, and needs no marker.\n-static bool OpenBlocksCheckBIP30(const CBlockIndex& pindex, const Consensus::Params& params, bool bip30_off)\n-{\n-    if (!pindex.pprev || ConnectBlockChecksBIP30(pindex, params, bip30_off)) return true; // the genesis block spends nothing\n-    const int lowest{std::max(1, pindex.nHeight - static_cast<int>(CoinsStore::MAX_WINDOW_SLOTS))};\n-    return ConnectBlockChecksBIP30(*Assert(pindex.GetAncestor(lowest)), params, bip30_off);\n-}\n-\n //! Add a transaction's signature operations to the block's and check the block's limit. One copy of the rule,\n-//! for a coinbase, a transaction checked in order and a deferred one.\n+//! for a coinbase and for any other transaction.\n static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view, script_verify_flags flags,\n                            int64_t& sigops_cost, BlockValidationState& state)\n {\n@@ -2773,36 +2781,19 @@ static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view,\n     return true;\n }\n \n-//! Check that the coinbase pays no more than the subsidy and the block's fees. One copy of the rule, for a\n-//! block whose fees ConnectBlock() totalled and one whose total FinishDeferredTransactions() completed.\n-static bool CheckCoinbaseAmount(const CBlock& block, const BlockValidationContext& ctx, CAmount fees, BlockValidationState& state)\n-{\n-    const CAmount block_reward{fees + GetBlockSubsidy(ctx.height, ctx.params)};\n-    if (block.vtx[0]->GetValueOut() > block_reward) {\n-        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-cb-amount\",\n-                             strprintf(\"coinbase pays too much (actual=%d vs limit=%d)\", block.vtx[0]->GetValueOut(), block_reward));\n-    }\n-    return true;\n-}\n-\n //! The consensus checks of one transaction that is not a coinbase against the coins in `view`, in their order:\n //! its inputs and fee, the block's accumulated fee, BIP68, the block's signature operations, and, if\n //! `check_scripts`, its scripts, run here or appended to `checks` for a check queue. The block's totals `fees`\n //! and `sigops_cost` grow by the transaction's. False, with `state` set, on a failure, which is the block's.\n-//! Shared by ConnectBlock() and FinishDeferredTransactions(). `inputs_found`: the caller has found every\n-//! input of the transaction in the view, unspent, and the view is unchanged since, so the walk that looks\n-//! for a missing input is skipped.\n static bool CheckBlockTransaction(const CTransaction& tx, const BlockValidationContext& ctx, const CCoinsViewCache& view,\n                                   script_verify_flags flags, int lock_time_flags, bool check_scripts, bool cache_results,\n                                   PrecomputedTransactionData& txdata, ValidationCache& validation_cache,\n                                   std::vector<CScriptCheck>* checks, std::vector<int>& prevheights,\n-                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state,\n-                                  bool inputs_found = false)\n+                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state)\n {\n     CAmount txfee = 0;\n     TxValidationState tx_state;\n-    if (!(inputs_found ? Consensus::CheckAvailableTxInputs(tx, tx_state, view, ctx.height, txfee)\n-                       : Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee))) {\n+    if (!Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee)) {\n         // Any transaction validation failure in ConnectBlock is a block consensus failure\n         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,\n                              tx_state.GetRejectReason(),\n@@ -2874,8 +2865,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -2890,15 +2883,9 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n \n     // BIP30: no transaction may overwrite one that is not completely spent. Whether the rule\n     // applies to this block was decided when the context was built, see EnforceBIP30().\n-    if (ctx.enforce_bip30) {\n-        for (const auto& tx : block.vtx) {\n-            for (size_t o = 0; o < tx->vout.size(); o++) {\n-                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n-                                  \"tried to overwrite transaction\");\n-                }\n-            }\n-        }\n+    if (ctx.enforce_bip30 && view.HaveAnyOutput(block.vtx)) {\n+        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n+                      \"tried to overwrite transaction\");\n     }\n \n     // Enforce BIP68 (sequence locks)\n@@ -2931,8 +2918,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     }\n \n     std::vector<int> prevheights;\n-    //! This block's transaction ids in sorted order, built when the first transaction is deferred.\n-    std::vector<Txid> block_txids;\n     CAmount nFees = 0;\n     int& nInputs{result.num_inputs};\n     int64_t& nSigOpsCost{result.sigops_cost};\n@@ -2940,70 +2925,18 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     for (unsigned int i = 0; i < block.vtx.size(); i++)\n     {\n         if (!state.IsValid()) break;\n+        if (ctx.help_point && (i & 63) == 63) ctx.help_point();\n+        if (ctx.implicit_creates) ctx.implicit_creates(i);\n         const CTransaction &tx = *(block.vtx[i]);\n \n         nInputs += tx.vin.size();\n \n-        // In a block that may defer, a lower block in flight can show the outputs of a transaction while its\n-        // spends are still to be applied. A transaction with an unspent coin of its own txid among the coins\n-        // the view holds (HaveCoinInCache()) repeats an earlier one, whose inputs it shares and which spent\n-        // them: no lower block can make it valid, and creating its outputs would overwrite that coin, which\n-        // the view refuses with an exception. A coin of the store the view did not fetch, or one this block\n-        // spent before the repeat, is met at the apply as a conflict (BlockApplyView::ApplyChanges()). The\n-        // block fails here, which in the window decides nothing: it is connected again alone, where BIP30 or\n-        // the spent inputs reject it.\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs) {\n-            for (uint32_t o{0}; o < tx.vout.size(); ++o) {\n-                if (view.HaveCoinInCache(COutPoint{tx.GetHash(), o})) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + tx.GetHash().ToString() + \" repeats one with an unspent output\");\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-        }\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs && !view.HaveInputs(tx)) {\n-            // A lower block that is still being applied may hold the missing input. Not so for an input\n-            // from one of this block's own transactions: it is missing because it is produced later in the\n-            // block (or is this transaction's own, or was spent earlier), which validating in order rejects\n-            // at this point, and so does this.\n-            if (block_txids.empty()) {\n-                block_txids.reserve(block.vtx.size());\n-                for (const auto& block_tx : block.vtx) block_txids.push_back(block_tx->GetHash());\n-                std::sort(block_txids.begin(), block_txids.end());\n-                // A transaction the block holds twice. No lower block can make that valid: the second\n-                // copy spends what the first spent. (The merkle root's check for mutation only catches\n-                // copies that are paired in the tree.) Its outputs must not be created a second time.\n-                if (const auto twice{std::adjacent_find(block_txids.begin(), block_txids.end())}; twice != block_txids.end()) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + twice->ToString() + \" is in the block twice\");\n-                    break;\n-                }\n-            }\n-            for (const CTxIn& txin : tx.vin) {\n-                if (std::binary_search(block_txids.begin(), block_txids.end(), txin.prevout.hash) && !view.HaveCoin(txin.prevout)) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"input from this block missing or spent in transaction \" + tx.GetHash().ToString());\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-            // The transaction's outputs are created now, so that later transactions of this block can spend\n-            // them; everything else about it waits for FinishDeferredTransactions(), as do the block's totals.\n-            result.deferred_txs.push_back(i);\n-            if (i > 0) blockundo.vtxundo.emplace_back();\n-            AddCoins(view, tx, ctx.height);\n-            continue;\n-        }\n-\n         if (!tx.IsCoinBase()) {\n             const bool fCacheResults = just_check; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */\n             std::vector<CScriptCheck> vChecks;\n             PrecomputedTransactionData own_txdata;\n-            // In a block that may defer, the test above found every input (or the transaction was deferred).\n             if (!CheckBlockTransaction(tx, ctx, view, flags, nLockTimeFlags, fScriptChecks, fCacheResults, control ? txsdata[i] : own_txdata, validation_cache,\n-                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state,\n-                                       /*inputs_found=*/ctx.defer_missing_inputs)) {\n+                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state)) {\n                 break;\n             }\n             if (control) control->Add(std::move(vChecks));\n@@ -3016,14 +2949,27 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         if (i > 0) {\n             blockundo.vtxundo.emplace_back();\n         }\n-        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), ctx.height);\n+        if (ctx.implicit_creates) {\n+            // The inputs are spent; the outputs are the window's (WindowOutputs), and never the view's.\n+            if (i > 0) {\n+                CTxUndo& txundo{blockundo.vtxundo.back()};\n+                txundo.vprevout.reserve(tx.vin.size());\n+                for (const CTxIn& txin : tx.vin) {\n+                    txundo.vprevout.emplace_back();\n+                    const bool is_spent{view.SpendCoin(txin.prevout, &txundo.vprevout.back())};\n+                    assert(is_spent);\n+                }\n+            }\n+        } else {\n+     \n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 141ff08765a3..26065d4b5dc6

2026-11-25T02:35:08Z · gpt-6-luna

fork#48The initial page-cache sweep precedes window-block validationsrc/validation.cppunclear
Assessment

The supplied new-head excerpt does not include `ReadForConnectTask()` or the `ReleaseBlockFilesBelow()` call site, and the diff is truncated before that area. The evidence does not establish whether the page-cache sweep was moved off the validation submission path.

new_source: src/validation.cpp; path_diff: src/validation.cpp

[
  {
    "bounded": true,
    "end_line": 4240,
    "evidence_id": "dc8e5b745baf4a059d09ec5f74f6d166",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 4091,
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "revision": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "            at = next;\n        }\n        shard.slots[at] = Slot{};\n        --shard.count;\n    }\n    //! Take the items of one published block out and let the block go. False: none is waiting.\n    bool EraseOne() EXCLUSIVE_LOCKS_REQUIRED(!m_released_mutex)\n    {\n        int height;\n        {\n            LOCK(m_released_mutex);\n            if (m_released.empty()) return false;\n            height = m_released.back();\n            m_released.pop_back();\n        }\n        // The height is this thread's alone from here on.\n        Held& held{m_ring[height % RING]};\n        const CBlock* const block{held.at.load(std::memory_order_acquire)};\n        // A block that was never entered has no items.\n        if (block == nullptr || held.height.load(std::memory_order_relaxed) != height) return true;\n        static thread_local std::vector<uint64_t> tags;\n        static thread_local std::vector<uint32_t> order;\n        std::array<uint32_t, SHARDS + 1> start;\n        Tags(*block, tags);\n        Group(tags, order, start);\n        for (size_t n{0}; n < SHARDS; ++n) {\n            if (start[n] == start[n + 1]) continue;\n            Shard& shard{m_shards[n]};\n            LOCK(shard.mutex);\n            for (uint32_t k{start[n]}; k < start[n + 1]; ++k) Take(shard, Slot{tags[order[k]], order[k], height});\n        }\n        // Freed here, with no mutex held, once the place is given up.\n        const std::shared_ptr<const CBlock> freed{std::move(held.block)};\n        held.at.store(nullptr, std::memory_order_release);\n        return true;\n    }\n    struct Found {\n        const CTransaction* maker{nullptr};\n        int height{-1};\n    };\n    //! The transaction that makes the outputs of `txid` for a block at `viewer`: one of the block's own first\n    //! `own_limit` transactions, or else that of the highest block above `published` and below the viewer.\n    Found Probe(const Shard& shard, uint64_t tag, const Txid& txid, int published, int viewer, uint32_t own_limit) const EXCLUSIVE_LOCKS_REQUIRED(shard.mutex)\n    {\n        Found found;\n        if (shard.count == 0) return found;\n        for (size_t at{(tag >> 1) & shard.mask}; shard.slots[at].tag != 0; at = (at + 1) & shard.mask) {\n            const Slot& slot{shard.slots[at]};\n            if (slot.tag != tag) continue;\n            if (slot.height == viewer) {\n                if (slot.pos >= own_limit) continue;\n            } else if (slot.height <= published || slot.height > viewer || slot.height < found.height) {\n                continue;\n            }\n            const CTransaction& tx{*m_ring[slot.height % RING].at.load(std::memory_order_relaxed)->vtx[slot.pos]};\n            if (tx.GetHash() != txid) continue;\n            found = {&tx, slot.height};\n            if (slot.height == viewer) break;\n        }\n        return found;\n    }\n    std::array<Shard, SHARDS> m_shards;\n    std::array<Held, RING> m_ring;\n    //! The highest published height: the blocks above it are read.\n    std::atomic<int> m_published{-1};\n    //! The published blocks whose items are still in the table.\n    Mutex m_released_mutex;\n    std::vector<int> m_released GUARDED_BY(m_released_mutex);\n};\n\n/**\n * What the window's workers share with the connector thread: the blocks in flight in height order, the\n * outputs they make and the commit that runs. A block is validated once it and every block below it are in\n * the outputs (Chainstate::OnWindowBlockIndexed()). Held by shared pointer by the step and by every task, so\n * it outlives whichever of them is last.\n */\nstruct WindowSync {\n    Mutex mutex;\n    std::condition_variable cv;\n    //! The blocks in flight, lowest unpublished first. An entry is removed by the connector thread before\n    //! the block is published and freed, so a pointer taken under the mutex is valid while it is held.\n    std::deque<StagedConnect*> slots GUARDED_BY(mutex);\n    //! What the blocks in flight make (see WindowOutputs).\n    WindowOutputs outputs;\n    //! The commit that runs (RunCommitWork()), one at most: the connector starts it for the blocks it\n    //! publishes next and waits for it.\n    std::deque<std::shared_ptr<CommitJob>> jobs GUARDED_BY(mutex);\n    //! No commit starts any more: the step stops or the window drains.\n    bool draining GUARDED_BY(mutex){false};\n    //! The commits that have work left to claim, read by the workers' help points without the mutex.\n    std::atomic<int> open_jobs{0};\n};\n\n/**\n * The phases of a block connection in flight, each a type that holds what exists in it. A phase is\n * made from the one before it, by the thread that has the block then, so that what a phase does not\n * have cannot be read through its type: a block is published from a Validated, and nothing else has an\n * outcome or undo data to give. The types say no more than that: the phase a block is in and its state\n * in the window (node/connect_machine.h) are kept by different hands and are not checked against each\n * other.\n */\nnamespace connect_phase {\n//! Staged, under cs_main: everything the validation reads besides the block's view.\nstruct Staged {\n    //! The node's decisions on the block. A worker reads these, and of the block index only what was\n    //! written once before the block was staged (the ancestors' times, for the median time past).\n    //! With the block's position on disk and its size, if known: a worker reads neither from the index.\n    BlockValidationContext ctx;\n    //! Null for a windowed block still on disk (ctx.block_pos).\n    std::shared_ptr<const CBlock> block;\n};\n\n//! The worker could not read the block from disk: a system error, fatal at publication.\nstruct ReadFailed {\n};\n\n//! Validated: the verdict, and with `ok` the block's undo data and totals, complete.\nstruct Validated {\n    std::shared_ptr<const CBlock> block;\n    bool ok;\n    BlockValidationState state;\n    ConnectBlockResult result;\n};\n\n//! Only a Validated has a result to read.\ntemplate <typename Phase>\nconcept HasResult = requires(Phase phase) { phase.result; };\nstatic_assert(HasResult<Validated> && !HasResult<Staged> && !HasResult<ReadFailed>);\n} // namespace connect_phase\n\n/**\n * A block connection in flight, through the three parts of connecting a block\n * (Chainstate::StageConnectTip() in validation.h). The activating thread is\n * whichever runs ActivateBestChain(): the connector thread for the blocks\n * handed to it, else an RPC thread, the import thread or the message handler.\n *\n * What is fixed at staging is here for every thread to read. What the validation\n * makes of the block is in `at`, one phase type at a time (connect_phase). `at`\n * belongs to one thread at a time: the activating thread until the block's task\n * is submitted, the task until it marks the block indexed, the block's\n * validation between its claim and its finish (node::WindowBlockState, under\n * the window's mutex), and the activating thread again once the block is\n * complete, or once DrainWindow() has taken the block out of the window: a\n * block that was not claimed by then is claimed by no walk afterwards.\n */\nstruct StagedConnect {\n    //! Resets the overlay, stopping its prefetch workers, when the staged connection ends, however it ends.\n    struct FetchGuard {\n        CCoinsViewCache::ResetGuard reset;\n        FetchGuard(BlockApplyView& view, const CBlock& block) : reset{view.StartFetching(block)} {}",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "evidence_id": "aa2d8f9232b84b32b850d0bb94e360bb",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex 3323476b87..68c1909e60 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -119,12 +119,11 @@ static void CheckBlockStoreTransition(std::optional<node::BlockStoreState> befor\n \n /**\n  * The tasks validation runs where no caller is on the stack to decide what a std::runtime_error means\n- * (util/worker_task.h): a block's validation and its continuation on a connect pool worker, and a coins\n+ * (util/worker_task.h): a block's parse and its validation on a connect pool worker, and a coins\n  * write-out run and a block's undo write on the effects executor. Each reads or writes the node's own data,\n  * so each stops the node; the name is what the log and the fatal error begin with.\n  */\n static constexpr util::WorkerTaskType CONNECT_TASK{\"ConnectBlock\"};\n-static constexpr util::WorkerTaskType CONTINUATION_TASK{\"FinishDeferredTransactions\"};\n static constexpr util::WorkerTaskType WRITE_OUT_TASK{\"Coins write-out run failed\"};\n static constexpr util::WorkerTaskType UNDO_WRITE_TASK{\"Block undo write failed\"};\n \n@@ -1916,7 +1915,7 @@ BlockApplyView* CoinsViews::FreeApplyView()\n {\n     AssertLockHeld(::cs_main);\n     for (auto& view : m_apply_views) {\n-        if (!view->HasBlock()) return view.get();\n+        if (!view->InUse()) return view.get();\n     }\n     return nullptr;\n }\n@@ -2019,6 +2018,15 @@ void Chainstate::ResetCoinsViews()\n     m_coins_views.reset();\n }\n \n+//! The block a ChainStateFlushed names for coins written at `written`. Where that is the block being published,\n+//! one above the tip (precondition O8), its BlockConnected leaves after the signal, and a synced index would find\n+//! the locator off its chain and skip its commit: the signal names the tip, which the index has seen, and the\n+//! index catches up from there. Decided when the write starts, before the block's signal is queued.\n+static const CBlockIndex* FlushedSignalBlock(const CBlockIndex* written, const CChain& chain)\n+{\n+    return written && written != chain.Tip() && written->pprev == chain.Tip() ? written->pprev : written;\n+}\n+\n void Chainstate::SettleWriteOut()\n {\n     AssertLockHeld(::cs_main);\n@@ -2075,8 +2083,17 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n         bool for_prune;\n     };\n     const FlushTrace trace{NodeClock::now(), store.GetCacheSize(), store.DynamicMemoryUsage(), mode, for_prune};\n+    // See CommitGate. A commit that started first holds the run back.\n+    m_commit_gate.run_active.store(true);\n+    if (m_commit_gate.ahead.load() > 0) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     std::shared_ptr<CoinsStore::WriteOutRun> run{store.BeginWriteOut(bound_height, head->nHeight, head->GetBlockHash(), final)};\n-    if (!run) return true;\n+    if (!run) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     LogDebug(BCLog::COINDB, \"Starting a coins write-out run: changes at or below height %d, head %d%s\",\n              bound_height, head->nHeight, run->final ? \", final\" : \"\");\n \n@@ -2088,6 +2105,7 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n     // one state of it. The head and its ancestors do not change in the block index, so the effect looks the\n     // settled head up there.\n     auto index_batch{std::make_shared<node::BlockManager::IndexBatch>(m_blockman.PrepareBlockIndexBatch())};\n+    const CBlockIndex* signal_at{FlushedSignalBlock(head, m_chain)};\n     node::BlockManager& blockman{m_blockman};\n     CCoinsViewDB& db{CoinsDB()};\n     m_blockman.m_effects.Enqueue(\n@@ -2114,17 +2132,19 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (failure) LogError(\"%s\", failure->what);\n             return written || fail();\n         },\n-        [this, run, evict_to, trace](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n+        [this, run, evict_to, trace, signal_at](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n             AssertLockHeld(::cs_main);\n             if (!m_coins_views || !m_coins_views->m_store) return;\n             CoinsStore& store{CoinsStoreTip()};\n             if (!ok) {\n+                // A failed run never ends, and the commits stay off: the node is stopping.\n                 store.AbandonWriteOut();\n                 ++m_write_out_runs_failed;\n                 m_chainman.GetNotifications().fatalError(_(\"System error while writing the chainstate to disk.\"));\n                 return;\n             }\n             store.CommitWriteOut(*run);\n+            m_commit_gate.run_active.store(false);\n             (void)trace;\n             TRACEPOINT(utxocache, flush,\n                 int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - trace.start)},\n@@ -2138,29 +2158,34 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (evict_to) store.EvictClean(*evict_to);\n             m_last_flushed_block = m_blockman.LookupBlockIndex(run->new_head);\n             if (m_chainman.m_options.signals) {\n-                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n-            }\n-            if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n-                try {\n-                    CoinsDB().CompactFullAsync();\n-                } catch (const std::system_error& e) { // what std::async throws when no thread can be started\n-                    LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n-                }\n+                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(signal_at));\n             }\n+            // As after a synchronous write, with its check of the room a compaction needs.\n+            MaybeCompactChainstate();\n         },\n         0);\n     return true;\n }\n \n+node::BlockCache::Tips ChainstateManager::BlockCacheTips() const\n+{\n+    AssertLockHeld(::cs_main);\n+    node::BlockCache::Tips tips{.active = ActiveHeight()};\n+    if (const Chainstate* historical{HistoricalChainstate()}) {\n+        if (const CBlockIndex* base{CurrentChainstate().SnapshotBase()}) {\n+            tips.historical = historical->m_chain.Height();\n+            tips.historical_end = base->nHeight;\n+        }\n+    }\n+    return tips;\n+}\n+\n int ChainstateManager::ConnectWindow() const\n {\n     // By default twice as wide as the pool. The blocks are confirmed in order, so a window as wide as the\n     // pool leaves a worker without a block whenever one behind the oldest finishes first. What the blocks\n     // in flight hold in memory is bounded separately, by bytes (WINDOW_BYTES_SHARE).\n     const int window{m_options.connect_window > 0 ? m_options.connect_window : 2 * static_cast<int>(m_connect_pool->WorkersCount())};\n-    // No block of a window spends the coinbase of another, which the coin store's write-out rests on\n-    // (CoinsStore::CollectRecords()).\n-    static_assert(MAX_CONNECT_WINDOW < COINBASE_MATURITY);\n     return std::clamp(window, 1, MAX_CONNECT_WINDOW);\n }\n \n@@ -2736,29 +2761,12 @@ BlockValidationContext ChainstateManager::MakeBlockValidationContext(const uint2\n         .enforce_bip30 = EnforceBIP30(block_hash, prev ? prev->nHeight + 1 : 0, prev, GetConsensus(), GetParams().Bip30Off()),\n         // Callable without cs_main, see BlockValidationContext::median_time_past_at.\n         .median_time_past_at = [prev](int height) { return Assert(Assert(prev)->GetAncestor(height))->GetMedianTimePast(); },\n-        .defer_missing_inputs = false,\n     };\n }\n \n \n-\n-//! Whether BIP30 is checked for the block or for one that can be open in the connect window below it.\n-//! Such a block's spends leave a marker in the store even of a coin never written, so that a lower block\n-//! that makes the outpoint again does not find it gone (CoinsStore::BeginBlock()). The check is on below\n-//! BIP34 and from the height where it is on again (EnforceBIP30()), so the block and the lowest that can\n-//! be open with it decide. The two blocks below BIP34 that are exempt from the check, 91842 and 91880\n-//! (IsBIP30Repeat()), do not change that: where one of them is the block, the lowest that can be open with\n-//! it is checked, and where one of them is the lowest, the block is checked.\n-//! A block connected alone has no block open below it, and needs no marker.\n-static bool OpenBlocksCheckBIP30(const CBlockIndex& pindex, const Consensus::Params& params, bool bip30_off)\n-{\n-    if (!pindex.pprev || ConnectBlockChecksBIP30(pindex, params, bip30_off)) return true; // the genesis block spends nothing\n-    const int lowest{std::max(1, pindex.nHeight - static_cast<int>(CoinsStore::MAX_WINDOW_SLOTS))};\n-    return ConnectBlockChecksBIP30(*Assert(pindex.GetAncestor(lowest)), params, bip30_off);\n-}\n-\n //! Add a transaction's signature operations to the block's and check the block's limit. One copy of the rule,\n-//! for a coinbase, a transaction checked in order and a deferred one.\n+//! for a coinbase and for any other transaction.\n static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view, script_verify_flags flags,\n                            int64_t& sigops_cost, BlockValidationState& state)\n {\n@@ -2773,36 +2781,19 @@ static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view,\n     return true;\n }\n \n-//! Check that the coinbase pays no more than the subsidy and the block's fees. One copy of the rule, for a\n-//! block whose fees ConnectBlock() totalled and one whose total FinishDeferredTransactions() completed.\n-static bool CheckCoinbaseAmount(const CBlock& block, const BlockValidationContext& ctx, CAmount fees, BlockValidationState& state)\n-{\n-    const CAmount block_reward{fees + GetBlockSubsidy(ctx.height, ctx.params)};\n-    if (block.vtx[0]->GetValueOut() > block_reward) {\n-        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-cb-amount\",\n-                             strprintf(\"coinbase pays too much (actual=%d vs limit=%d)\", block.vtx[0]->GetValueOut(), block_reward));\n-    }\n-    return true;\n-}\n-\n //! The consensus checks of one transaction that is not a coinbase against the coins in `view`, in their order:\n //! its inputs and fee, the block's accumulated fee, BIP68, the block's signature operations, and, if\n //! `check_scripts`, its scripts, run here or appended to `checks` for a check queue. The block's totals `fees`\n //! and `sigops_cost` grow by the transaction's. False, with `state` set, on a failure, which is the block's.\n-//! Shared by ConnectBlock() and FinishDeferredTransactions(). `inputs_found`: the caller has found every\n-//! input of the transaction in the view, unspent, and the view is unchanged since, so the walk that looks\n-//! for a missing input is skipped.\n static bool CheckBlockTransaction(const CTransaction& tx, const BlockValidationContext& ctx, const CCoinsViewCache& view,\n                                   script_verify_flags flags, int lock_time_flags, bool check_scripts, bool cache_results,\n                                   PrecomputedTransactionData& txdata, ValidationCache& validation_cache,\n                                   std::vector<CScriptCheck>* checks, std::vector<int>& prevheights,\n-                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state,\n-                                  bool inputs_found = false)\n+                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state)\n {\n     CAmount txfee = 0;\n     TxValidationState tx_state;\n-    if (!(inputs_found ? Consensus::CheckAvailableTxInputs(tx, tx_state, view, ctx.height, txfee)\n-                       : Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee))) {\n+    if (!Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee)) {\n         // Any transaction validation failure in ConnectBlock is a block consensus failure\n         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,\n                              tx_state.GetRejectReason(),\n@@ -2874,8 +2865,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -2890,15 +2883,9 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n \n     // BIP30: no transaction may overwrite one that is not completely spent. Whether the rule\n     // applies to this block was decided when the context was built, see EnforceBIP30().\n-    if (ctx.enforce_bip30) {\n-        for (const auto& tx : block.vtx) {\n-            for (size_t o = 0; o < tx->vout.size(); o++) {\n-                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n-                                  \"tried to overwrite transaction\");\n-                }\n-            }\n-        }\n+    if (ctx.enforce_bip30 && view.HaveAnyOutput(block.vtx)) {\n+        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n+                      \"tried to overwrite transaction\");\n     }\n \n     // Enforce BIP68 (sequence locks)\n@@ -2931,8 +2918,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     }\n \n     std::vector<int> prevheights;\n-    //! This block's transaction ids in sorted order, built when the first transaction is deferred.\n-    std::vector<Txid> block_txids;\n     CAmount nFees = 0;\n     int& nInputs{result.num_inputs};\n     int64_t& nSigOpsCost{result.sigops_cost};\n@@ -2940,70 +2925,18 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     for (unsigned int i = 0; i < block.vtx.size(); i++)\n     {\n         if (!state.IsValid()) break;\n+        if (ctx.help_point && (i & 63) == 63) ctx.help_point();\n+        if (ctx.implicit_creates) ctx.implicit_creates(i);\n         const CTransaction &tx = *(block.vtx[i]);\n \n         nInputs += tx.vin.size();\n \n-        // In a block that may defer, a lower block in flight can show the outputs of a transaction while its\n-        // spends are still to be applied. A transaction with an unspent coin of its own txid among the coins\n-        // the view holds (HaveCoinInCache()) repeats an earlier one, whose inputs it shares and which spent\n-        // them: no lower block can make it valid, and creating its outputs would overwrite that coin, which\n-        // the view refuses with an exception. A coin of the store the view did not fetch, or one this block\n-        // spent before the repeat, is met at the apply as a conflict (BlockApplyView::ApplyChanges()). The\n-        // block fails here, which in the window decides nothing: it is connected again alone, where BIP30 or\n-        // the spent inputs reject it.\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs) {\n-            for (uint32_t o{0}; o < tx.vout.size(); ++o) {\n-                if (view.HaveCoinInCache(COutPoint{tx.GetHash(), o})) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + tx.GetHash().ToString() + \" repeats one with an unspent output\");\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-        }\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs && !view.HaveInputs(tx)) {\n-            // A lower block that is still being applied may hold the missing input. Not so for an input\n-            // from one of this block's own transactions: it is missing because it is produced later in the\n-            // block (or is this transaction's own, or was spent earlier), which validating in order rejects\n-            // at this point, and so does this.\n-            if (block_txids.empty()) {\n-                block_txids.reserve(block.vtx.size());\n-                for (const auto& block_tx : block.vtx) block_txids.push_back(block_tx->GetHash());\n-                std::sort(block_txids.begin(), block_txids.end());\n-                // A transaction the block holds twice. No lower block can make that valid: the second\n-                // copy spends what the first spent. (The merkle root's check for mutation only catches\n-                // copies that are paired in the tree.) Its outputs must not be created a second time.\n-                if (const auto twice{std::adjacent_find(block_txids.begin(), block_txids.end())}; twice != block_txids.end()) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + twice->ToString() + \" is in the block twice\");\n-                    break;\n-                }\n-            }\n-            for (const CTxIn& txin : tx.vin) {\n-                if (std::binary_search(block_txids.begin(), block_txids.end(), txin.prevout.hash) && !view.HaveCoin(txin.prevout)) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"input from this block missing or spent in transaction \" + tx.GetHash().ToString());\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-            // The transaction's outputs are created now, so that later transactions of this block can spend\n-            // them; everything else about it waits for FinishDeferredTransactions(), as do the block's totals.\n-            result.deferred_txs.push_back(i);\n-            if (i > 0) blockundo.vtxundo.emplace_back();\n-            AddCoins(view, tx, ctx.height);\n-            continue;\n-        }\n-\n         if (!tx.IsCoinBase()) {\n             const bool fCacheResults = just_check; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */\n             std::vector<CScriptCheck> vChecks;\n             PrecomputedTransactionData own_txdata;\n-            // In a block that may defer, the test above found every input (or the transaction was deferred).\n             if (!CheckBlockTransaction(tx, ctx, view, flags, nLockTimeFlags, fScriptChecks, fCacheResults, control ? txsdata[i] : own_txdata, validation_cache,\n-                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state,\n-                                       /*inputs_found=*/ctx.defer_missing_inputs)) {\n+                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state)) {\n                 break;\n             }\n             if (control) control->Add(std::move(vChecks));\n@@ -3016,14 +2949,27 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         if (i > 0) {\n             blockundo.vtxundo.emplace_back();\n         }\n-        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), ctx.height);\n+        if (ctx.implicit_creates) {\n+            // The inputs are spent; the outputs are the window's (WindowOutputs), and never the view's.\n+            if (i > 0) {\n+                CTxUndo& txundo{blockundo.vtxundo.back()};\n+                txundo.vprevout.reserve(tx.vin.size());\n+                for (const CTxIn& txin : tx.vin) {\n+                    txundo.vprevout.emplace_back();\n+                    const bool is_spent{view.SpendCoin(txin.prevout, &txundo.vprevout.back())};\n+                    assert(is_spent);\n+                }\n+            }\n+        } else {\n+     \n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 141ff08765a3..26065d4b5dc6

2026-11-25T02:35:08Z · gpt-6-luna

fork#48Reorganisation tests miss target changes across the lock dropsrc/test/validation_chainstate_tests.cppstill_present
Assessment

The added reorganisation tests shown still build branches before activation and use synchronous activation; they do not insert a competing higher-work candidate during off-lock reads or assert the refreshed plan and consumption behavior.

path_diff: src/test/validation_chainstate_tests.cpp; new_source: src/test/validation_chainstate_tests.cpp

[
  {
    "evidence_id": "f8775b4f3c964e07b3f69911c3896934",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/test/validation_chainstate_tests.cpp",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "diff --git a/src/test/validation_chainstate_tests.cpp b/src/test/validation_chainstate_tests.cpp\nindex f78583b846..564fbb4d78 100644\n--- a/src/test/validation_chainstate_tests.cpp\n+++ b/src/test/validation_chainstate_tests.cpp\n@@ -525,16 +525,16 @@ BOOST_FIXTURE_TEST_CASE(failed_write_out_leaves_the_tip, WriteOutEveryBlockSetup\n //! Drives a step of the connect window one block at a time, with nothing added to the node: the connect\n //! pool's workers are held by tasks that wait (as threadpool_tests' BlockWorkers() does), ActivateBestChain()\n //! runs on a thread of its own, and the test thread runs the tasks the step queues, one per call\n-//! (ThreadPool::ProcessTask()). Between two calls the connector waits for a block no worker will apply, so\n+//! (ThreadPool::ProcessTask()). Between two calls the connector waits for a block no worker will validate, so\n //! what the test does there happens between two blocks of the window. Not more than that: WaitForStep()\n //! returns once the tip is published and the queue has its count, and where the window had nothing to\n //! refill the connector may still be at what follows a publication (a periodic write-out, the wait for the\n //! signal queue, the plan of the next blocks).\n //!\n //! What this reaches: blocks that complete in the order they were staged, which is the order of the queue.\n-//! A block that completes ahead of a lower one is out of its reach, and with it a deferred transaction\n-//! whose coin a lower block brings later. A block connected outside the window stalls under it, its input\n-//! fetch waits for tasks of the same pool: the workers are let go (Finish()) before a step comes to one.\n+//! A block that completes ahead of a lower one is out of its reach. A block connected outside the window\n+//! stalls under it, its input fetch waits for tasks of the same pool: the workers are let go (Finish())\n+//! before a step comes to one.\n //!\n //! In a step of the window the queue holds the blocks' tasks only: a block read by its task is not freed\n //! through the pool, and a write-out of a chain this small has one range, which its own thread writes.\n@@ -694,6 +694,27 @@ struct WindowStepSetup : TestChain100Setup {\n         }\n     }\n \n+    //! Store a copy of the block at `original` on top of `parent`, with `extra` as one transaction more.\n+    std::pair<CBlock, CBlockIndex*> StoreSibling(const CBlockIndex& original, const uint256& parent, const CTransactionRef& extra = nullptr)\n+    {\n+        ChainstateManager& chainman{*Assert(m_node.chainman)};\n+        CBlock block;\n+        BOOST_REQUIRE(chainman.m_blockman.ReadBlock(block, original));\n+        block.hashPrevBlock = parent;\n+        if (extra) {\n+            block.vtx.push_back(extra);\n+            node::RegenerateCommitments(block, chainman);\n+        }\n+        while (!CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus())) ++block.nNonce;\n+        LOCK(::cs_main);\n+        BlockValidationState state;\n+        CBlockIndex* index{nullptr};\n+        bool new_block{false};\n+        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(block), state, &index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n+        BOOST_REQUIRE(new_block && index);\n+        return {std::move(block), index};\n+    }\n+\n     //! The blocks in flight once the tip is at `height`.\n     size_t InFlightAt(int height) const\n     {\n@@ -753,12 +774,11 @@ struct WindowSummaryLog {\n     }\n \n     //! The counts the manager is to log: the test's blocks that came to their publication in the window,\n-    //! the transactions it deferred, the conflicts its blocks met in the store, and the blocks it gave up\n-    //! and connected alone.\n-    void ExpectWindowSummary(unsigned blocks, unsigned deferred, unsigned conflicts, unsigned retries)\n+    //! the commits that met a conflict in the store, and the blocks it gave up and connected alone.\n+    void ExpectWindowSummary(unsigned blocks, unsigned conflicts, unsigned retries)\n     {\n         m_expected_blocks = strprintf(\"Connect window: %u blocks validated on the connect pool (\", FIXTURE_BLOCKS + blocks);\n-        m_expected_counts = strprintf(\" wide), %u transactions deferred to their block's continuation, %u conflicts, %u blocks retried alone\", deferred, conflicts, retries);\n+        m_expected_counts = strprintf(\" wide), %u conflicts, %u blocks retried alone\", conflicts, retries);\n     }\n };\n \n@@ -770,7 +790,7 @@ struct WindowSummarySetup : WindowSummaryLog, WindowStepSetup {\n //! write-out under it meets no conflict, and no block of it is connected a second time.\n BOOST_FIXTURE_TEST_CASE(window_step_block_by_block, WindowSummarySetup)\n {\n-    ExpectWindowSummary(/*blocks=*/BLOCKS, /*deferred=*/0, /*conflicts=*/0, /*retries=*/0);\n+    ExpectWindowSummary(/*blocks=*/BLOCKS, /*conflicts=*/0, /*retries=*/0);\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n     Chainstate& chainstate{chainman.ActiveChainstate()};\n     CacheStepBlocks();\n@@ -837,7 +857,7 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n         // The first block is published: the write-out before the tip has nothing due, the periodic write\n         // is, and the run its hold starts fails.\n         stepper.RunLowestBlock();\n-        // The blocks above it are run by the workers, and taken back.\n+        // The blocks above it are run by the workers, and let go.\n         stepper.Finish();\n     }\n     m_node.validation_signals->SyncWithValidationInterfaceQueue();\n@@ -846,9 +866,8 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n     BOOST_CHECK(!activated);\n     BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE);\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height + 1);\n-    // The blocks above gave their places in the store back.\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n-    // And what they held in memory; the block cache alone keeps the blocks that were not connected.\n+    // The blocks above gave back what they held in memory; the block cache alone keeps the blocks that were\n+    // not connected.\n     for (const util::ByteAccountId id : {util::ByteAccountId::Window, util::ByteAccountId::UndoBacklog, util::ByteAccountId::PinnedBlocks}) {\n         BOOST_CHECK_EQUAL(chainman.m_bytes_in_flight[id].Bytes(), 0U);\n     }\n@@ -861,7 +880,7 @@ BOOST_FIXTURE_TEST_CASE(failed_periodic_write_out_ends_a_window_step, WindowStep\n }\n \n //! A window block whose file cannot be read. Its task ends without a verdict, and the step ends where the\n-//! block would be published: the window is drained, the blocks give their places in the store back, the\n+//! block would be published: the window is drained, the blocks give their views back, the\n //! node gets a fatal error and the pass fails with the tip where it was. Nothing is published or announced.\n BOOST_FIXTURE_TEST_CASE(unreadable_block_ends_a_window_step, WindowStepSetup)\n {\n@@ -895,61 +914,32 @@ BOOST_FIXTURE_TEST_CASE(unreadable_block_ends_a_window_step, WindowStepSetup)\n     BOOST_CHECK_EQUAL(state.GetRejectReason(), \"Failed to read block.\");\n     BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE);\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height);\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n     CheckAccountsEmpty();\n     const std::lock_guard lock{m_recorder->mutex};\n     BOOST_CHECK(m_recorder->connected.empty());\n     BOOST_CHECK(m_recorder->tips.empty());\n }\n \n-//! A block of the window with a transaction whose coin no block creates. The transaction is deferred, since\n-//! the block's parent was not the tip when it was staged, and its continuation finds no coin, which in the\n-//! window decides nothing: the step ends, the changes of the block above it are taken back and then its own,\n-//! and the block is connected alone, where the same transaction makes it invalid. The block below it stays\n-//! the tip.\n-BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n+//! A block of the window with a transaction whose coin no block creates. Its validation in the window finds\n+//! no coin, which decides nothing there: the step ends, and the block is connected alone, where the same\n+//! transaction makes it invalid. The block below it stays the tip.\n+BOOST_FIXTURE_TEST_CASE(invalid_window_block_is_judged_alone, WindowSummarySetup)\n {\n-    // Two blocks came to their publication in the window, the first and the sibling. The window deferred\n-    // the sibling's transaction (a block that judges it with the rest fails there and defers nothing), the\n-    // failed continuation is no conflict in the store, and the sibling is the one block connected again.\n-    ExpectWindowSummary(/*blocks=*/2, /*deferred=*/1, /*conflicts=*/0, /*retries=*/1);\n+    // Two blocks came to their publication in the window, the first and the sibling, which met no conflict\n+    // in the store and is the one block connected again.\n+    ExpectWindowSummary(/*blocks=*/2, /*conflicts=*/0, /*retries=*/1);\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n     Chainstate& chainstate{chainman.ActiveChainstate()};\n+    const CBlockIndex* const first{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 1))};\n     CBlockIndex* const second{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 2))};\n     const CBlockIndex* const third{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 3))};\n-    // A sibling of the setup's second block with one transaction more, which spends no coin.\n-    CBlock bad;\n-    BOOST_REQUIRE(chainman.m_blockman.ReadBlock(bad, *second));\n+    // A sibling of the setup's second block with one transaction more, which spends no coin, and the setup's\n+    // third on top of it: a block of the window is in flight above the one that fails.\n     CMutableTransaction spend;\n     spend.vin.emplace_back(COutPoint{Txid::FromUint256(m_rng.rand256()), 0});\n     spend.vout.emplace_back(CAmount{1}, CScript() << OP_TRUE);\n-    bad.vtx.push_back(MakeTransactionRef(std::move(spend)));\n-    node::RegenerateCommitments(bad, chainman);\n-    while (!CheckProofOfWork(bad.GetHash(), bad.nBits, chainman.GetConsensus())) ++bad.nNonce;\n-    CBlockIndex* bad_index{nullptr};\n-    {\n-        LOCK(::cs_main);\n-        BlockValidationState accept_state;\n-        bool new_block{false};\n-        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(bad), accept_state, &bad_index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n-        BOOST_REQUIRE(new_block && bad_index);\n-    }\n-    // And a block on top of it, the setup's third with the sibling as its parent: a block of the window is\n-    // in flight above the one that fails, and its changes are taken back first.\n-    CBlock above;\n-    const CBlockIndex* top{nullptr};\n-    BOOST_REQUIRE(chainman.m_blockman.ReadBlock(above, *third));\n-    above.hashPrevBlock = bad.GetHash();\n-    while (!CheckProofOfWork(above.GetHash(), above.nBits, chainman.GetConsensus())) ++above.nNonce;\n-    {\n-        LOCK(::cs_main);\n-        BlockValidationState accept_state;\n-        CBlockIndex* above_index{nullptr};\n-        bool new_block{false};\n-        BOOST_REQUIRE(chainman.AcceptBlock(std::make_shared<const CBlock>(above), accept_state, &above_index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true));\n-        BOOST_REQUIRE(new_block && above_index);\n-        top = above_index;\n-    }\n+    const auto [bad, bad_index]{StoreSibling(*second, first->GetBlockHash(), MakeTransactionRef(std::move(spend)))};\n+    const auto [above, top]{StoreSibling(*third, bad.GetHash())};\n     CacheStepBlocks(top);\n     // The setup's blocks from the second on are set aside, so that the sibling is what the step heads for.\n     BlockValidationState invalidate_state;\n@@ -960,17 +950,16 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     bool activated{false};\n     {\n         // Only a block that is connected alone logs this line (a window block is read by its task): the\n-        // block was connected a second time, outside the window. That its transaction was deferred the\n-        // first time, and not judged with the rest of the block, is in the window's summary (above).\n+        // block was connected a second time, outside the window.\n         ASSERT_DEBUG_LOG(\"  - Load block from disk\");\n         WindowStepper stepper{chainman};\n         stepper.Start([&] { activated = chainstate.ActivateBestChain(state); });\n         stepper.WaitForStep(m_base_height, std::min<size_t>(3, chainman.ConnectWindow()));\n         stepper.RunLowestBlock();\n         stepper.WaitForStep(m_base_height + 1, 2);\n-        // The sibling's task defers the transaction and runs its continuation, here, with the block above\n-        // it still queued. The workers are let go for that block, which the step waits for before it takes\n-        // the two back, and for the sibling connected alone next, outside the window.\n+        // The sibling's task finds the transaction's coin missing, here, with the block above it still\n+        // queued. The workers are let go for that block, which the step waits for, and for the sibling\n+        // connected alone next, outside the window.\n         stepper.RunLowestBlock();\n         stepper.Finish();\n     }\n@@ -979,8 +968,6 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     // The verdict is that of the step that connected the block alone: the window gives none.\n     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height + 1);\n     BOOST_CHECK(WITH_LOCK(::cs_main, return (bad_index->nStatus & BLOCK_FAILED_VALID) != 0));\n-    // The block's place in the store was given back both times, and that of the block above it.\n-    BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return chainstate.CoinsStoreTip().OpenBlocks()), 0U);\n     BOOST_CHECK(!WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(COutPoint{bad.vtx.back()->GetHash(), 0})));\n     BOOST_CHECK(!WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(COutPoint{above.vtx[0]->GetHash(), 0})));\n     m_node.validation_signals->SyncWithValidationInterfaceQueue();\n@@ -991,6 +978,88 @@ BOOST_FIXTURE_TEST_CASE(failing_deferral_ends_a_window_step, WindowSummarySetup)\n     BOOST_CHECK_EQUAL_COLLECTIONS(m_recorder->connected.begin(), m_recorder->connected.end(), expected.begin(), expected.end());\n }\n \n+//! Two blocks of the window spend one coin. Each is validated against the published blocks, where the coin\n+//! is, so both are valid and come to one commit. There the upper block's spend finds the coin gone: it and\n+//! the block above it are taken out of the store again, the lower block is published, and the upper one is\n+//! connected alone, where the spend makes it invalid.\n+BOOST_FIXTURE_TEST_CASE(double_spend_in_the_window_is_taken_back, WindowSummarySetup)\n+{\n+    // The first block and the lower spender came to their publication in the window; the upper spender is\n+    // the one conflict and the one block connected again.\n+    ExpectWindowSummary(/*blocks=*/2, /*conflicts=*/1, /*retries=*/1);\n+    ChainstateManager& chainman{*Assert(m_node.chainman)};\n+    Chainstate& chainstate{chainman.ActiveChainstate()};\n+    BOOST_REQUIRE_GE(chainman.ConnectWindow(), 4);\n+    const CBlockIndex* const first{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 1))};\n+    CBlockIndex* const second{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 2))};\n+    const CBlockIndex* const third{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 3))};\n+    const CBlockIndex* const fourth{WITH_LOCK(::cs_main, return chainman.m_best_header->GetAncestor(m_base_height + 4))};\n+    // Two spends of the fixture's first coinbase output, which no block of the setup spends.\n+    const CTransactionRef funding{m_coinbase_txns[0]};\n+    const COutPoint coin{funding->GetHash(), 0};\n+    const auto spend_to{[&](CAmount amount) {\n+        return MakeTransactionRef(CreateValidMempoolTransaction(funding, /*input_vout=*/0, /*input_height=*/1, coinbaseKey, CScript() << OP_TRUE, amount, /*submit=*/false));\n+    }};\n+    const CTransactionRef lower_spend{spend_to(1 * COIN)};\n+    const CTransactionRef upper_spend{spend_to(2 * COIN)};\n+    BOOST_REQUIRE(lower_spend->GetHash() != upper_spend->GetHash());\n+    BOOST_REQUIRE(WITH_LOCK(::cs_main, return chainstate.CoinsTip().HaveCoin(coin)));\n+    const auto [lower, lower_index]{StoreSibling(*second, first->GetBlockHash(), lower_spend)};\n+    const auto [upper, upper_index]{StoreSibling(*third, lower.GetHash(), upper_spend)};\n+    const auto [above, top]{StoreSibling(*fourth, upper.GetHash())};\n+    CacheStepBlocks(top);\n+    BlockValidationState invalidate_state;\n+    BOOST_REQUIRE(chainstate.InvalidateBlock(invalidate_state, second));\n+    BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), m_base_height);\n+    // A write sets the timer of the periodic one: none is due in the step, and the commit takes every\n+    // complete block.\n+    {\n+        BlockValidationState flush_state;\n+        BOOST_REQUIRE(chainstate.FlushStateToDisk(flush_state, FlushStateMode::FORCE_FLUSH));\n+    }\n+\n+    BlockValidationState state;\n+    bool activated{false};\n+    {\n+        ASSERT_DEBUG_LOG(strprintf(\"A conflict in a commit, first in the block at height %d: 2 blocks taken out of the store again\", m_base_height + 3));\n+        ASSERT_DEBUG_LOG(\"bad-txns-inputs-missingorspent\");\n+        WindowStepper stepper{chainman};\n+        stepper.Start([&] { activated = chainstate.ActivateBestChain(state); });\n+        stepper.WaitForStep(m_base_height, 4);\n+        stepper.RunLowestBlock();\n+        stepper.WaitForStep(m_base_height + 1, 3);\n+        {\n+            // The connector commits and publishes under cs_main. Held here, the three blocks are complete\n+            // before any of them is committed, and each was validated with the coin in the store.\n+            LOCK(::cs_main);\n+            for (int i{0}; i < 3; ++i) stepper.RunLowestBlock();\n+        }\n+        stepper.Finish();\n+    }\n+    BOOST_CHECK(activated);\n+    BOOST_CHECK(state.IsValid());\n+    BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_SUCCESS);\n+    {\n+        LOCK(::cs_main);\n+        BOOST_CHECK(chainstate.m_chain.Tip() == lower_index);\n+        BOOST_CHECK((upper_index->nStatus & BLOCK_FAILED_VALID) != 0);\n+        const CCoinsViewCache& coins{chainstate.CoinsTip()};\n+        // The lower block's changes are there, and nothing of the two blocks above it.\n+        BOOST_CHECK(!coins.HaveCoin(coin));\n+        BOOST_CHECK(coins.HaveCoin(COutPoint{lower_spend->GetHash(), 0}));\n+        BOOST_CHECK(coins.HaveCoin(COutPoint{lower.vtx[0]->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{upper_spend->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{upper.vtx[0]->GetHash(), 0}));\n+        BOOST_CHECK(!coins.HaveCoin(COutPoint{above.vtx[0]->GetHash(), 0}));\n+    }\n+    m_node.validation_signals->SyncWithValidationInterfaceQueue();\n+    m_node.validation_signals->UnregisterSharedValidationInterface(m_recorder);\n+    CheckAccountsEmpty();\n+    const std::vector<int> expected{m_base_height + 1, m_base_height + 2};\n+    const std::lock_guard lock{m_recorder->mutex};\n+    BOOST_CHECK_EQUAL_COLLECTIONS(m_recorder->connected.begin(), m_recorder->connected.end(), expected.begin(), expected.end());\n+}\n+\n //! The window's account is the node's, and only a step that uses the window writes it: a block connected\n //! outside the window leaves its limit and its co\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 524,
    "evidence_id": "2046f0e7bf454124a861a3e7f995705a",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 375,
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/test/validation_chainstate_tests.cpp",
    "revision": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "    m_node.validation_signals->RegisterSharedValidationInterface(recorder);\n    {\n        LOCK(::cs_main);\n        chainstate.ResetBlockFailureFlags(fork1_index);\n        chainman.RecalculateBestHeader();\n    }\n    // Past the interval of the periodic write-out: the first write-out check that asks for it finds it due.\n    if (periodic_due) setup.m_clock += std::chrono::hours{2};\n    // A limit of one byte, which a connected block whose signal has not left is over. A step that is not of\n    // a reorganisation sets the limit anew, so it is the reorganisation's step that meets this one.\n    util::ByteAccount& pinned{chainman.m_bytes_in_flight[util::ByteAccountId::PinnedBlocks]};\n    if (pinned_over_limit) pinned.SetLimit(1);\n    BOOST_REQUIRE(chainstate.ActivateBestChain(state));\n    // Both blocks were connected by that step: no other step ran and set the limit.\n    if (pinned_over_limit) BOOST_CHECK_EQUAL(pinned.Limit(), 1U);\n    m_node.validation_signals->SyncWithValidationInterfaceQueue();\n    m_node.validation_signals->UnregisterSharedValidationInterface(recorder);\n    BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Tip()->GetBlockHash()), fork2.GetHash());\n\n    const std::vector<std::string> expected{\"A \" + CTransaction{tx}.GetHash().ToString(), \"A \" + CTransaction{tx2}.GetHash().ToString(), \"C \" + fork1.GetHash().ToString(), \"C \" + fork2.GetHash().ToString()};\n    BOOST_CHECK_EQUAL_COLLECTIONS(recorder->events.begin(), recorder->events.end(), expected.begin(), expected.end());\n}\n\nBOOST_FIXTURE_TEST_CASE(reorg_announces_readded_transactions_before_connected_blocks, TestChain100Setup)\n{\n    CheckReorgAnnouncementOrder(*this);\n}\n\n//! A reorganisation from a branch of `depth` blocks to one of `depth + 1`: its blocks are read before its\n//! hold, up to `read_ahead` on each side, and it ends at the longer branch with that branch's coins.\nstatic void CheckReorgReadAhead(TestChain100Setup& setup, int depth, int read_ahead)\n{\n    ChainstateManager& chainman{*Assert(setup.m_node.chainman)};\n    Chainstate& chainstate{chainman.ActiveChainstate()};\n    const CScript long_script{CScript() << OP_TRUE};\n    const CScript short_script{CScript() << OP_2};\n    BlockValidationState state;\n\n    // The longer branch first, then set aside: each of its blocks is read before the hold that disconnects it.\n    std::vector<CBlock> long_branch;\n    for (int i{0}; i < depth + 1; ++i) long_branch.push_back(setup.CreateAndProcessBlock({}, long_script));\n    CBlockIndex* const long_first{WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(long_branch.front().GetHash()))};\n    BOOST_REQUIRE(chainstate.InvalidateBlock(state, long_first));\n    BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Height()), 100);\n    std::vector<CBlock> short_branch;\n    for (int i{0}; i < depth; ++i) short_branch.push_back(setup.CreateAndProcessBlock({}, short_script));\n    BOOST_REQUIRE_EQUAL(WITH_LOCK(::cs_main, return chainstate.m_chain.Tip()->GetBlockHash()), short_branch.back().GetHash());\n\n    // The longer branch back. The step ends with the block that gives the tip more work than it had, the\n    // branch's last, so all of the branch is its to connect.\n    {\n        LOCK(::cs_main);\n        chainstate.ResetBlockFailureFlags(long_first);\n        chainman.RecalculateBestHeader();\n    }\n    {\n        ASSERT_DEBUG_LOG(strprintf(\"Read %d blocks to disconnect and %d blocks to connect ahead of a reorganisation from %s to %s\",\n                                   std::min(depth, read_ahead), std::min(depth + 1, read_ahead),\n                                   short_branch.back().GetHash().ToString(), long_branch.back().GetHash().ToString()));\n        // A block read ahead is the one connected, not read again under the hold.\n        ASSERT_DEBUG_LOG(\"Using block read ahead of the reorganisation\");\n        BOOST_REQUIRE(chainstate.ActivateBestChain(state));\n    }\n    setup.m_node.validation_signals->SyncWithValidationInterfaceQueue();\n\n    LOCK(::cs_main);\n    BOOST_REQUIRE_EQUAL(chainstate.m_chain.Tip()->GetBlockHash(), long_branch.back().GetHash());\n    for (const CBlock& block : short_branch) BOOST_CHECK(!chainstate.CoinsTip().HaveCoin(COutPoint{block.vtx[0]->GetHash(), 0}));\n    for (const CBlock& block : long_branch) BOOST_CHECK(chainstate.CoinsTip().HaveCoin(COutPoint{block.vtx[0]->GetHash(), 0}));\n}\n\nBOOST_FIXTURE_TEST_CASE(reorg_reads_its_blocks_before_its_hold, TestChain100Setup)\n{\n    CheckReorgReadAhead(*this, /*depth=*/2, /*read_ahead=*/16);\n}\n\n//! Deeper than what is read ahead: the blocks past the first 16 on each side are read under the hold.\nBOOST_FIXTURE_TEST_CASE(deep_reorg_reads_the_rest_under_its_hold, TestChain100Setup)\n{\n    CheckReorgReadAhead(*this, /*depth=*/18, /*read_ahead=*/16);\n}\n\n//! Undo data read from a position copied under cs_main, with no lock taken, is what the index's read gives;\n//! the hash of another parent does not pass its checksum.\nBOOST_FIXTURE_TEST_CASE(undo_read_from_a_copied_position, TestChain100Setup)\n{\n    ChainstateManager& chainman{*Assert(m_node.chainman)};\n    node::BlockManager& blockman{chainman.m_blockman};\n    const CMutableTransaction tx{CreateValidMempoolTransaction(m_coinbase_txns[0], 0, 1, coinbaseKey, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), 49 * COIN)};\n    CreateAndProcessBlock({tx}, CScript() << OP_TRUE);\n    blockman.SettleUndoWrites();\n    const CBlockIndex* const tip{WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip())};\n    const FlatFilePos pos{WITH_LOCK(::cs_main, return tip->GetUndoPos())};\n    BOOST_REQUIRE(!pos.IsNull());\n\n    CBlockUndo by_index, by_pos, wrong_parent;\n    BOOST_REQUIRE(blockman.ReadBlockUndo(by_index, *tip));\n    BOOST_REQUIRE(blockman.ReadBlockUndo(by_pos, pos, tip->pprev->GetBlockHash()));\n    BOOST_REQUIRE_EQUAL(by_pos.vtxundo.size(), 1U);\n    BOOST_CHECK((HashWriter{} << by_pos).GetHash() == (HashWriter{} << by_index).GetHash());\n    BOOST_CHECK(!blockman.ReadBlockUndo(wrong_parent, pos, tip->GetBlockHash()));\n}\n\n//! The same with a write-out run started at every block, inside the reorganisation's step too: a run's settle\n//! of the effects queue must not hand on the connected blocks' signals before the re-added transactions'.\nstruct WriteOutEveryBlockSetup : TestChain100Setup {\n    WriteOutEveryBlockSetup() : TestChain100Setup{ChainType::REGTEST, {.extra_args = {\"-test=write_out_every_block\"}}} {}\n};\n\n//! A block whose write-out fails does not become the tip, and is not announced: the write is made before\n//! the tip moves, as it always was.\nBOOST_FIXTURE_TEST_CASE(failed_write_out_leaves_the_tip, WriteOutEveryBlockSetup)\n{\n    struct Recorder final : CValidationInterface {\n        std::atomic<int> connected{0};\n        std::atomic<int> tips{0};\n        void BlockConnected(const kernel::ChainstateRole&, const std::shared_ptr<const CBlock>&, const CBlockIndex*) override { ++connected; }\n        void UpdatedBlockTip(const CBlockIndex*, const CBlockIndex*, bool) override { ++tips; }\n    };\n    ChainstateManager& chainman{*Assert(m_node.chainman)};\n    Chainstate& chainstate{chainman.ActiveChainstate()};\n    BOOST_REQUIRE(chainman.m_options.test_write_out_every_block);\n    const CBlockIndex* const old_tip{WITH_LOCK(::cs_main, return chainstate.m_chain.Tip())};\n\n    // The block is stored, and not connected yet.\n    const auto block{std::make_shared<const CBlock>(CreateBlock({}, CScript() << OP_TRUE))};\n    BlockValidationState state;\n    CBlockIndex* index{nullptr};\n    bool new_block{false};\n    BOOST_REQUIRE(WITH_LOCK(::cs_main, return chainman.AcceptBlock(block, state, &index, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true)));\n    BOOST_REQUIRE(new_block && index);\n\n    // Its block file cannot be opened from here on: the run its connection starts fails where it syncs the\n    // file.\n    const fs::path file{WITH_LOCK(::cs_main, return chainman.m_blockman.GetBlockPosFilename(index->GetBlockPos()))};\n    BOOST_REQUIRE(fs::remove(file));\n    BOOST_REQUIRE(fs::create_directory(file));\n\n    const auto recorder{std::make_shared<Recorder>()};\n    m_node.validation_signals->RegisterSharedValidationInterface(recorder);\n    BOOST_CHECK(!chainstate.ActivateBestChain(state, block));\n    m_node.validation_signals->SyncWithValidationInterfaceQueue();\n    m_node.validation_signals->UnregisterSharedValidationInterface(recorder);\n\n    BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE);\n    BOOST_CHECK(WITH_LOCK(::cs_main, return chainstate.m_chain.Tip()) == old_tip);\n    BOOST_CHECK_EQUAL(recorder->connected.load(), 0);\n    BOOST_CHECK_EQUAL(recorder->tips.load(), 0);\n}\n",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 141ff08765a3..26065d4b5dc6

2026-11-25T02:35:08Z · gpt-6-luna

fork#48Target changes discard usable reorganisation read-aheadsrc/validation.cppstill_present
Assessment

The new-head excerpt retains the target-mismatch path that resets `reorg_reads` and replans, with no visible consecutive-round limit or fallback that consumes completed reads. The proposed unbounded preparatory delay therefore is not shown to be fixed.

new_source: src/validation.cpp

[
  {
    "bounded": true,
    "end_line": 5260,
    "evidence_id": "60fb9ee4d07e46869db248e814397495",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 5111,
    "new_head": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "old_head": "141ff08765a3ac124f9dbf5e7b9d878f124a9504",
    "path": "src/validation.cpp",
    "revision": "26065d4b5dc6b01df0aa89442290f11d62dc828a",
    "source_generation": 3,
    "source_job_id": 2984,
    "text": "    // Remove conflicting transactions from the mempool.\n    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;\n    if (m_mempool) {\n        txs_removed_for_block = m_mempool->removeForBlock(block_to_connect->vtx);\n        disconnectpool.removeForBlock(block_to_connect->vtx);\n    }\n    // Update m_chain & related variables.\n    const auto store_before{BlockStoreStateOf(*pindexNew, m_chain)};\n    // Before the tip and the initial block download latch change.\n    m_chainman.MarkTipChanged();\n    m_chain.SetTip(*pindexNew);\n    CheckBlockStoreTransition(store_before, BlockStoreEvent::Connect, *pindexNew, m_chain);\n    const bool was_in_ibd{m_chainman.IsInitialBlockDownload()};\n    m_chainman.UpdateIBDStatus();\n    // Not fired while IBD is active. removeForBlock() above still runs.\n    if (m_mempool && m_chainman.m_options.signals && !m_chainman.IsInitialBlockDownload()) {\n        // At the block that ends initial block download, the BlockConnected of earlier blocks may still wait\n        // on the effects queue: they leave first, so that this block's mempool removals follow them. Not in a\n        // step that disconnected blocks, whose signals leave after the re-added transactions (FinishConnectStep()).\n        if (was_in_ibd && !reorg) m_blockman.SettleUndoWrites();\n        m_chainman.m_options.signals->MempoolTransactionsRemovedForBlock(block_to_connect, std::move(txs_removed_for_block), pindexNew->nHeight);\n    }\n    UpdateTip(pindexNew);\n\n    const auto time_6{SteadyClock::now()};\n    m_chainman.time_post_connect += time_6 - time_5;\n    m_chainman.time_total += time_6 - time_1;\n    LogDebug(BCLog::BENCH, \"  - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\\n\",\n             Ticks<MillisecondsDouble>(time_6 - time_5),\n             Ticks<SecondsDouble>(m_chainman.time_post_connect),\n             Ticks<MillisecondsDouble>(m_chainman.time_post_connect) / m_chainman.num_blocks_total);\n    LogDebug(BCLog::BENCH, \"- Connect block: %.2fms [%.2fs (%.2fms/blk)]\\n\",\n             Ticks<MillisecondsDouble>(time_6 - time_1),\n             Ticks<SecondsDouble>(m_chainman.time_total),\n             Ticks<MillisecondsDouble>(m_chainman.time_total) / m_chainman.num_blocks_total);\n\n    // See if this chainstate has reached a target block and can be used to\n    // validate an assumeutxo snapshot. If it can, hashing the UTXO database\n    // will be slow, and cs_main could remain locked here for several minutes.\n    // If the snapshot is validated, the UTXO hash will be saved to\n    // this->m_target_utxohash, causing HistoricalChainstate() to return null\n    // and this chainstate to no longer be used. ActivateBestChain() will also\n    // stop connecting blocks to this chainstate because this->ReachedTarget()\n    // will be true and this->setBlockIndexCandidates will not have additional\n    // blocks.\n    Chainstate& current_cs{m_chainman.CurrentChainstate()};\n    m_chainman.MaybeValidateSnapshot(*this, current_cs);\n\n    // Precondition O7: the signal for this block names what is stored and connected. True by the\n    // statements above (the block store's Connect and SetTip()); checked so that a reordering of this\n    // function keeps it.\n    Assume((pindexNew->nStatus & BLOCK_HAVE_DATA) && m_chain.Tip() == pindexNew);\n    if (m_chainman.m_options.signals) {\n        // The signal joins the effects queue here: the queue hands its completions on in order, so the\n        // signals reach the validation interface in this order too.\n        // The signal keeps the block until the undo writes ahead of it have run: counted, from the block's\n        // counts, for as long.\n        util::ByteAccount& pinned{m_chainman.m_bytes_in_flight[util::ByteAccountId::PinnedBlocks]};\n        const size_t pinned_bytes{WindowBlockBytes(*block_to_connect, validated.result.num_inputs, /*block_bytes=*/0)};\n        pinned.Add(pinned_bytes);\n        m_blockman.m_effects.Enqueue(\n            /*effect=*/nullptr,\n            [signals = m_chainman.m_options.signals, role, block = std::move(block_to_connect), pindexNew, &blockman = m_blockman, &pinned, pinned_bytes](bool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n                AssertLockHeld(::cs_main);\n                pinned.Sub(pinned_bytes);\n                // Not for a block whose undo data was not written: the node is stopping on that error, and\n                // a listener would look for undo data that is not there.\n                if (blockman.m_undo_write_failed) return;\n                signals->BlockConnected(role, block, pindexNew);\n            });\n        // Outside initial block download the signal leaves under the lock hold that moved the tip, behind\n        // the block's undo write (precondition O7). In a step that disconnected blocks it leaves once the\n        // disconnected transactions are back in the mempool (FinishConnectStep()), under the same hold.\n        if (!m_chainman.IsInitialBlockDownload() && !reorg) m_blockman.SettleUndoWrites();\n    }\n    return true;\n}\n\n/**\n * Return the tip of the chain with the most work in it, that isn't\n * known to be invalid (it's however far from certain to be valid).\n */\nCBlockIndex* Chainstate::FindMostWorkChain()\n{\n    AssertLockHeld(::cs_main);\n    do {\n        CBlockIndex *pindexNew = nullptr;\n\n        // Find the best candidate header.\n        {\n            std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();\n            if (it == setBlockIndexCandidates.rend())\n                return nullptr;\n            pindexNew = *it;\n        }\n\n        // Check whether all blocks on the path between the currently active chain and the candidate are valid.\n        // Just going until the active chain is an optimization, as we know all blocks in it are valid already.\n        bool fInvalidAncestor = false;\n        for (CBlockIndex *pindexTest = pindexNew; pindexTest && !m_chain.Contains(*pindexTest); pindexTest = pindexTest->pprev) {\n            assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);\n\n            // Pruned nodes may have entries in setBlockIndexCandidates for\n            // which block files have been deleted.  Remove those as candidates\n            // for the most work chain if we come across them; we can't switch\n            // to a chain unless we have all the non-active-chain parent blocks.\n            bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_VALID;\n            bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);\n            if (fFailedChain || fMissingData) {\n                DropUnusableCandidateChain(pindexNew, pindexTest, fFailedChain, fMissingData);\n                fInvalidAncestor = true;\n                break;\n            }\n        }\n        if (!fInvalidAncestor)\n            return pindexNew;\n    } while(true);\n}\n\nvoid Chainstate::DropUnusableCandidateChain(CBlockIndex* top, CBlockIndex* unusable, bool failed, bool missing_data)\n{\n    AssertLockHeld(cs_main);\n    // Candidate chain is not usable (either invalid or missing data)\n    if (failed && (m_chainman.m_best_invalid == nullptr || top->nChainWork > m_chainman.m_best_invalid->nChainWork)) {\n        m_chainman.m_best_invalid = top;\n    }\n    // Remove the entire chain from the set.\n    for (CBlockIndex* pindexFailed = top; pindexFailed != unusable; pindexFailed = pindexFailed->pprev) {\n        // If we're missing data and not a descendant of an invalid block,\n        // then add back to m_blocks_unlinked, so that if the block arrives in the future\n        // we can try adding to setBlockIndexCandidates again.\n        if (missing_data && !failed) {\n            // Avoid duplicate entries in m_blocks_unlinked. If the same entry is\n            // processed twice in ReceivedBlockTransactions(), it may be re-added to\n            // setBlockIndexCandidates with a modified nSequenceId, breaking ordering\n            // guarantees and leading to undefined behavior.\n            m_blockman.AddUnlinkedBlock(pindexFailed);\n        }\n        setBlockIndexCandidates.erase(pindexFailed);\n    }\n    setBlockIndexCandidates.erase(unusable);\n}\n\n/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */\nvoid Chainstate::PruneBlockIndexCandidates() {\n    // Note that we can't delete the current block itself, as we may need to return to it later in case a\n    // reorganization to a better block fails.\n    std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();\n    while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {\n        setBlockIndexCandidates.erase(it++);",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 141ff08765a3..26065d4b5dc6

2026-11-25T02:35:08Z · gpt-6-luna

fork#46Mid-write GETDATA retry and source retention lack deterministic coveragesrc/net_processing.cpppartially_addressed
Assessment

The new head adds a waits-for-store flag when ProcessGetBlockData() cannot yet serve the block and changes ProcessMessages() so the queued request is not treated as immediate work, supporting a later retry rather than a busy loop. But the supplied evidence does not show the requested deterministic staged-write test covering queued GETDATA, duplicate-source retention, and valid/invalid completion outcomes.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "6e5634d08f5c48e18c4ded3ce563faec",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 2882,
    "evidence_id": "234088faa16949b8bbcb2e9faa29bd85",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 2733,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "    }\n}\n\nbool PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)\n{\n    // First perform the stateless checks:\n    // A filtered-block can only ever be requested if we offer NODE_BLOOM\n    if (inv.IsMsgFilteredBlk() && !(peer.m_our_services & NODE_BLOOM)) {\n        LogDebug(BCLog::NET, \"filtered block request received when NODE_BLOOM service disabled, %s\", pfrom.DisconnectMsg());\n        pfrom.fDisconnect = true;\n        return true;\n    }\n\n    std::shared_ptr<const CBlock> a_recent_block;\n    std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;\n    {\n        LOCK(m_most_recent_block_mutex);\n        a_recent_block = m_most_recent_block;\n        a_recent_compact_block = m_most_recent_compact_block;\n    }\n    // The block this node announced last (NewPoWValidBlock): it is announced before it is written, which\n    // happens with cs_main released, so a request may come while it is being stored. The request is then asked\n    // again on a later call, the peer's further messages waiting behind it: once stored, the block is activated\n    // below and served only as any other block is, never unvalidated in full to a peer that would punish this\n    // node if it failed.\n    const bool announced{a_recent_block && a_recent_block->GetHash() == inv.hash};\n\n    bool need_activate_chain = false;\n    {\n        LOCK(cs_main);\n        const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);\n        if (pindex) {\n            // A request that waits for a state: the announced block is no longer being stored\n            // (ChainstateManager::IsBlockBeingStored()). Read in the critical section that decides the activation:\n            // the block is marked before it is announced and stored when the mark goes, so from here on it\n            // is stored and activated below, or was not stored at all. Read after the activation was\n            // decided, a block stored in between would be found stored and not activated, and refused.\n            if (announced && m_chainman.IsBlockBeingStored(*pindex)) return false;\n            if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&\n                    pindex->IsValid(BLOCK_VALID_TREE)) {\n                // Precondition O1 (validation.h):\n                // If we have the block and all of its parents, but have not yet validated it,\n                // we might be in the middle of connecting it (ie in the unlock of cs_main\n                // before ActivateBestChain but after AcceptBlock).\n                // In this case, we need to run ActivateBestChain prior to checking the relay\n                // conditions below.\n                need_activate_chain = true;\n            }\n        }\n    } // release cs_main before calling ActivateBestChain\n    // In initial block download the connector thread activates the blocks stored ahead of the tip: run here, the\n    // activation would wait for the connector's pass and then run the next one on this thread, with every peer's\n    // messages waiting meanwhile. Such a block is refused below as one not stored is; this node announced none.\n    if (need_activate_chain && !m_chainman.IsInitialBlockDownload()) {\n        BlockValidationState state;\n        if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {\n            LogDebug(BCLog::NET, \"failed to activate chain (%s)\\n\", state.ToString());\n        }\n    }\n\n    const CBlockIndex* pindex{nullptr};\n    const CBlockIndex* tip{nullptr};\n    bool can_direct_fetch{false};\n    FlatFilePos block_pos{};\n    {\n        LOCK(cs_main);\n        pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);\n        if (!pindex) {\n            return true;\n        }\n        if (!BlockRequestAllowed(*pindex)) {\n            LogDebug(BCLog::NET, \"%s: ignoring request from peer=%i for old block that isn't in the main chain\\n\", __func__, pfrom.GetId());\n            return true;\n        }\n        // disconnect node in case we have reached the outbound limit for serving historical blocks\n        if (m_connman.OutboundTargetReached(true) &&\n            (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&\n            !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target\n        ) {\n            LogDebug(BCLog::NET, \"historical block serving limit reached, %s\", pfrom.DisconnectMsg());\n            pfrom.fDisconnect = true;\n            return true;\n        }\n        tip = m_chainman.ActiveChain().Tip();\n        // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold\n        if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && (\n                (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (tip->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )\n           )) {\n            LogDebug(BCLog::NET, \"Ignore block request below NODE_NETWORK_LIMITED threshold, %s\", pfrom.DisconnectMsg());\n            //disconnect node and prevent it from stalling (would otherwise wait for the missing block)\n            pfrom.fDisconnect = true;\n            return true;\n        }\n        // Pruned nodes may have deleted the block, so check whether\n        // it's available before trying to send.\n        if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {\n            return true;\n        }\n        can_direct_fetch = CanDirectFetch();\n        block_pos = pindex->GetBlockPos();\n    }\n\n    std::shared_ptr<const CBlock> pblock;\n    if (announced) {\n        pblock = a_recent_block;\n    } else if (inv.IsMsgWitnessBlk()) {\n        // Fast-path: in this case it is possible to serve the block directly from disk,\n        // as the network format matches the format on disk\n        if (const auto block_data{m_chainman.m_blockman.ReadRawBlock(block_pos)}) {\n            MakeAndPushMessage(pfrom, NetMsgType::BLOCK, std::span{*block_data});\n        } else {\n            if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {\n                LogDebug(BCLog::NET, \"Block was pruned before it could be read, %s\", pfrom.DisconnectMsg());\n            } else {\n                LogError(\"Cannot load block from disk, %s\", pfrom.DisconnectMsg());\n            }\n            pfrom.fDisconnect = true;\n            return true;\n        }\n        // Don't set pblock as we've sent the block\n    } else {\n        // Send block from disk\n        std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();\n        if (!m_chainman.m_blockman.ReadBlock(*pblockRead, block_pos, inv.hash)) {\n            if (WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.IsBlockPruned(*pindex))) {\n                LogDebug(BCLog::NET, \"Block was pruned before it could be read, %s\", pfrom.DisconnectMsg());\n            } else {\n                LogError(\"Cannot load block from disk, %s\", pfrom.DisconnectMsg());\n            }\n            pfrom.fDisconnect = true;\n            return true;\n        }\n        pblock = pblockRead;\n    }\n    if (pblock) {\n        if (inv.IsMsgBlk()) {\n            MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock));\n        } else if (inv.IsMsgWitnessBlk()) {\n            MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock));\n        } else if (inv.IsMsgFilteredBlk()) {\n            bool sendMerkleBlock = false;\n            CMerkleBlock merkleBlock;\n            if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {\n                LOCK(tx_relay->m_bloom_filter_mutex);\n                if (tx_relay->m_bloom_filter) {\n                    sendMerkleBlock = true;\n                    merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);\n                }\n            }\n            if (sendMerkleBlock) {",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46c662f0e2 bundles independently reviewable policies with the hand-offsrc/validation.cppstill_present
Assessment

The feedback asks for independent reviewable commits; the supplied old-to-new diff is a combined change set and includes broad related validation and coin-store changes. No evidence shows the requested separation into preparatory commits. Commit organization is not fixed by the code excerpts.

path_diff: src/validation.cpp

[
  {
    "evidence_id": "f110737971ec45a58ae8219d20f1fc4b",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/validation.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex 7bdb93f3aa..88d9c219a4 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -118,12 +118,11 @@ static void CheckBlockStoreTransition(std::optional<node::BlockStoreState> befor\n \n /**\n  * The tasks validation runs where no caller is on the stack to decide what a std::runtime_error means\n- * (util/worker_task.h): a block's validation and its continuation on a connect pool worker, and a coins\n+ * (util/worker_task.h): a block's parse and its validation on a connect pool worker, and a coins\n  * write-out run and a block's undo write on the effects executor. Each reads or writes the node's own data,\n  * so each stops the node; the name is what the log and the fatal error begin with.\n  */\n static constexpr util::WorkerTaskType CONNECT_TASK{\"ConnectBlock\"};\n-static constexpr util::WorkerTaskType CONTINUATION_TASK{\"FinishDeferredTransactions\"};\n static constexpr util::WorkerTaskType WRITE_OUT_TASK{\"Coins write-out run failed\"};\n static constexpr util::WorkerTaskType UNDO_WRITE_TASK{\"Block undo write failed\"};\n \n@@ -1915,7 +1914,7 @@ BlockApplyView* CoinsViews::FreeApplyView()\n {\n     AssertLockHeld(::cs_main);\n     for (auto& view : m_apply_views) {\n-        if (!view->HasBlock()) return view.get();\n+        if (!view->InUse()) return view.get();\n     }\n     return nullptr;\n }\n@@ -2018,6 +2017,15 @@ void Chainstate::ResetCoinsViews()\n     m_coins_views.reset();\n }\n \n+//! The block a ChainStateFlushed names for coins written at `written`. Where that is the block being published,\n+//! one above the tip (precondition O8), its BlockConnected leaves after the signal, and a synced index would find\n+//! the locator off its chain and skip its commit: the signal names the tip, which the index has seen, and the\n+//! index catches up from there. Decided when the write starts, before the block's signal is queued.\n+static const CBlockIndex* FlushedSignalBlock(const CBlockIndex* written, const CChain& chain)\n+{\n+    return written && written != chain.Tip() && written->pprev == chain.Tip() ? written->pprev : written;\n+}\n+\n void Chainstate::SettleWriteOut()\n {\n     AssertLockHeld(::cs_main);\n@@ -2074,8 +2082,17 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n         bool for_prune;\n     };\n     const FlushTrace trace{NodeClock::now(), store.GetCacheSize(), store.DynamicMemoryUsage(), mode, for_prune};\n+    // See CommitGate. A commit that started first holds the run back.\n+    m_commit_gate.run_active.store(true);\n+    if (m_commit_gate.ahead.load() > 0) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     std::shared_ptr<CoinsStore::WriteOutRun> run{store.BeginWriteOut(bound_height, head->nHeight, head->GetBlockHash(), final)};\n-    if (!run) return true;\n+    if (!run) {\n+        m_commit_gate.run_active.store(false);\n+        return true;\n+    }\n     LogDebug(BCLog::COINDB, \"Starting a coins write-out run: changes at or below height %d, head %d%s\",\n              bound_height, head->nHeight, run->final ? \", final\" : \"\");\n \n@@ -2087,6 +2104,7 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n     // one state of it. The head and its ancestors do not change in the block index, so the effect looks the\n     // settled head up there.\n     auto index_batch{std::make_shared<node::BlockManager::IndexBatch>(m_blockman.PrepareBlockIndexBatch())};\n+    const CBlockIndex* signal_at{FlushedSignalBlock(head, m_chain)};\n     node::BlockManager& blockman{m_blockman};\n     CCoinsViewDB& db{CoinsDB()};\n     m_blockman.m_effects.Enqueue(\n@@ -2113,17 +2131,19 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (failure) LogError(\"%s\", failure->what);\n             return written || fail();\n         },\n-        [this, run, evict_to, trace](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n+        [this, run, evict_to, trace, signal_at](bool ok) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n             AssertLockHeld(::cs_main);\n             if (!m_coins_views || !m_coins_views->m_store) return;\n             CoinsStore& store{CoinsStoreTip()};\n             if (!ok) {\n+                // A failed run never ends, and the commits stay off: the node is stopping.\n                 store.AbandonWriteOut();\n                 ++m_write_out_runs_failed;\n                 m_chainman.GetNotifications().fatalError(_(\"System error while writing the chainstate to disk.\"));\n                 return;\n             }\n             store.CommitWriteOut(*run);\n+            m_commit_gate.run_active.store(false);\n             (void)trace;\n             TRACEPOINT(utxocache, flush,\n                 int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - trace.start)},\n@@ -2137,29 +2157,34 @@ bool Chainstate::StartWriteOutRun(BlockValidationState& state, int bound_height,\n             if (evict_to) store.EvictClean(*evict_to);\n             m_last_flushed_block = m_blockman.LookupBlockIndex(run->new_head);\n             if (m_chainman.m_options.signals) {\n-                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n-            }\n-            if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n-                try {\n-                    CoinsDB().CompactFullAsync();\n-                } catch (const std::system_error& e) { // what std::async throws when no thread can be started\n-                    LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n-                }\n+                m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(signal_at));\n             }\n+            // As after a synchronous write, with its check of the room a compaction needs.\n+            MaybeCompactChainstate();\n         },\n         0);\n     return true;\n }\n \n+node::BlockCache::Tips ChainstateManager::BlockCacheTips() const\n+{\n+    AssertLockHeld(::cs_main);\n+    node::BlockCache::Tips tips{.active = ActiveHeight()};\n+    if (const Chainstate* historical{HistoricalChainstate()}) {\n+        if (const CBlockIndex* base{CurrentChainstate().SnapshotBase()}) {\n+            tips.historical = historical->m_chain.Height();\n+            tips.historical_end = base->nHeight;\n+        }\n+    }\n+    return tips;\n+}\n+\n int ChainstateManager::ConnectWindow() const\n {\n     // By default twice as wide as the pool. The blocks are confirmed in order, so a window as wide as the\n     // pool leaves a worker without a block whenever one behind the oldest finishes first. What the blocks\n     // in flight hold in memory is bounded separately, by bytes (WINDOW_BYTES_SHARE).\n     const int window{m_options.connect_window > 0 ? m_options.connect_window : 2 * static_cast<int>(m_connect_pool->WorkersCount())};\n-    // No block of a window spends the coinbase of another, which the coin store's write-out rests on\n-    // (CoinsStore::CollectRecords()).\n-    static_assert(MAX_CONNECT_WINDOW < COINBASE_MATURITY);\n     return std::clamp(window, 1, MAX_CONNECT_WINDOW);\n }\n \n@@ -2734,29 +2759,12 @@ BlockValidationContext ChainstateManager::MakeBlockValidationContext(const uint2\n         .enforce_bip30 = EnforceBIP30(block_hash, prev ? prev->nHeight + 1 : 0, prev, GetConsensus(), GetParams().Bip30Off()),\n         // Callable without cs_main, see BlockValidationContext::median_time_past_at.\n         .median_time_past_at = [prev](int height) { return Assert(Assert(prev)->GetAncestor(height))->GetMedianTimePast(); },\n-        .defer_missing_inputs = false,\n     };\n }\n \n \n-\n-//! Whether BIP30 is checked for the block or for one that can be open in the connect window below it.\n-//! Such a block's spends leave a marker in the store even of a coin never written, so that a lower block\n-//! that makes the outpoint again does not find it gone (CoinsStore::BeginBlock()). The check is on below\n-//! BIP34 and from the height where it is on again (EnforceBIP30()), so the block and the lowest that can\n-//! be open with it decide. The two blocks below BIP34 that are exempt from the check, 91842 and 91880\n-//! (IsBIP30Repeat()), do not change that: where one of them is the block, the lowest that can be open with\n-//! it is checked, and where one of them is the lowest, the block is checked.\n-//! A block connected alone has no block open below it, and needs no marker.\n-static bool OpenBlocksCheckBIP30(const CBlockIndex& pindex, const Consensus::Params& params, bool bip30_off)\n-{\n-    if (!pindex.pprev || ConnectBlockChecksBIP30(pindex, params, bip30_off)) return true; // the genesis block spends nothing\n-    const int lowest{std::max(1, pindex.nHeight - static_cast<int>(CoinsStore::MAX_WINDOW_SLOTS))};\n-    return ConnectBlockChecksBIP30(*Assert(pindex.GetAncestor(lowest)), params, bip30_off);\n-}\n-\n //! Add a transaction's signature operations to the block's and check the block's limit. One copy of the rule,\n-//! for a coinbase, a transaction checked in order and a deferred one.\n+//! for a coinbase and for any other transaction.\n static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view, script_verify_flags flags,\n                            int64_t& sigops_cost, BlockValidationState& state)\n {\n@@ -2771,36 +2779,19 @@ static bool AddBlockSigOps(const CTransaction& tx, const CCoinsViewCache& view,\n     return true;\n }\n \n-//! Check that the coinbase pays no more than the subsidy and the block's fees. One copy of the rule, for a\n-//! block whose fees ConnectBlock() totalled and one whose total FinishDeferredTransactions() completed.\n-static bool CheckCoinbaseAmount(const CBlock& block, const BlockValidationContext& ctx, CAmount fees, BlockValidationState& state)\n-{\n-    const CAmount block_reward{fees + GetBlockSubsidy(ctx.height, ctx.params)};\n-    if (block.vtx[0]->GetValueOut() > block_reward) {\n-        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-cb-amount\",\n-                             strprintf(\"coinbase pays too much (actual=%d vs limit=%d)\", block.vtx[0]->GetValueOut(), block_reward));\n-    }\n-    return true;\n-}\n-\n //! The consensus checks of one transaction that is not a coinbase against the coins in `view`, in their order:\n //! its inputs and fee, the block's accumulated fee, BIP68, the block's signature operations, and, if\n //! `check_scripts`, its scripts, run here or appended to `checks` for a check queue. The block's totals `fees`\n //! and `sigops_cost` grow by the transaction's. False, with `state` set, on a failure, which is the block's.\n-//! Shared by ConnectBlock() and FinishDeferredTransactions(). `inputs_found`: the caller has found every\n-//! input of the transaction in the view, unspent, and the view is unchanged since, so the walk that looks\n-//! for a missing input is skipped.\n static bool CheckBlockTransaction(const CTransaction& tx, const BlockValidationContext& ctx, const CCoinsViewCache& view,\n                                   script_verify_flags flags, int lock_time_flags, bool check_scripts, bool cache_results,\n                                   PrecomputedTransactionData& txdata, ValidationCache& validation_cache,\n                                   std::vector<CScriptCheck>* checks, std::vector<int>& prevheights,\n-                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state,\n-                                  bool inputs_found = false)\n+                                  CAmount& fees, int64_t& sigops_cost, BlockValidationState& state)\n {\n     CAmount txfee = 0;\n     TxValidationState tx_state;\n-    if (!(inputs_found ? Consensus::CheckAvailableTxInputs(tx, tx_state, view, ctx.height, txfee)\n-                       : Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee))) {\n+    if (!Consensus::CheckTxInputs(tx, tx_state, view, ctx.height, txfee)) {\n         // Any transaction validation failure in ConnectBlock is a block consensus failure\n         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,\n                              tx_state.GetRejectReason(),\n@@ -2872,8 +2863,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -2888,15 +2881,9 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n \n     // BIP30: no transaction may overwrite one that is not completely spent. Whether the rule\n     // applies to this block was decided when the context was built, see EnforceBIP30().\n-    if (ctx.enforce_bip30) {\n-        for (const auto& tx : block.vtx) {\n-            for (size_t o = 0; o < tx->vout.size(); o++) {\n-                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n-                                  \"tried to overwrite transaction\");\n-                }\n-            }\n-        }\n+    if (ctx.enforce_bip30 && view.HaveAnyOutput(block.vtx)) {\n+        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-BIP30\",\n+                      \"tried to overwrite transaction\");\n     }\n \n     // Enforce BIP68 (sequence locks)\n@@ -2929,8 +2916,6 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     }\n \n     std::vector<int> prevheights;\n-    //! This block's transaction ids in sorted order, built when the first transaction is deferred.\n-    std::vector<Txid> block_txids;\n     CAmount nFees = 0;\n     int& nInputs{result.num_inputs};\n     int64_t& nSigOpsCost{result.sigops_cost};\n@@ -2938,70 +2923,18 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n     for (unsigned int i = 0; i < block.vtx.size(); i++)\n     {\n         if (!state.IsValid()) break;\n+        if (ctx.help_point && (i & 63) == 63) ctx.help_point();\n+        if (ctx.implicit_creates) ctx.implicit_creates(i);\n         const CTransaction &tx = *(block.vtx[i]);\n \n         nInputs += tx.vin.size();\n \n-        // In a block that may defer, a lower block in flight can show the outputs of a transaction while its\n-        // spends are still to be applied. A transaction with an unspent coin of its own txid among the coins\n-        // the view holds (HaveCoinInCache()) repeats an earlier one, whose inputs it shares and which spent\n-        // them: no lower block can make it valid, and creating its outputs would overwrite that coin, which\n-        // the view refuses with an exception. A coin of the store the view did not fetch, or one this block\n-        // spent before the repeat, is met at the apply as a conflict (BlockApplyView::ApplyChanges()). The\n-        // block fails here, which in the window decides nothing: it is connected again alone, where BIP30 or\n-        // the spent inputs reject it.\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs) {\n-            for (uint32_t o{0}; o < tx.vout.size(); ++o) {\n-                if (view.HaveCoinInCache(COutPoint{tx.GetHash(), o})) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + tx.GetHash().ToString() + \" repeats one with an unspent output\");\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-        }\n-        if (!tx.IsCoinBase() && ctx.defer_missing_inputs && !view.HaveInputs(tx)) {\n-            // A lower block that is still being applied may hold the missing input. Not so for an input\n-            // from one of this block's own transactions: it is missing because it is produced later in the\n-            // block (or is this transaction's own, or was spent earlier), which validating in order rejects\n-            // at this point, and so does this.\n-            if (block_txids.empty()) {\n-                block_txids.reserve(block.vtx.size());\n-                for (const auto& block_tx : block.vtx) block_txids.push_back(block_tx->GetHash());\n-                std::sort(block_txids.begin(), block_txids.end());\n-                // A transaction the block holds twice. No lower block can make that valid: the second\n-                // copy spends what the first spent. (The merkle root's check for mutation only catches\n-                // copies that are paired in the tree.) Its outputs must not be created a second time.\n-                if (const auto twice{std::adjacent_find(block_txids.begin(), block_txids.end())}; twice != block_txids.end()) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"transaction \" + twice->ToString() + \" is in the block twice\");\n-                    break;\n-                }\n-            }\n-            for (const CTxIn& txin : tx.vin) {\n-                if (std::binary_search(block_txids.begin(), block_txids.end(), txin.prevout.hash) && !view.HaveCoin(txin.prevout)) {\n-                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, \"bad-txns-inputs-missingorspent\",\n-                                  \"input from this block missing or spent in transaction \" + tx.GetHash().ToString());\n-                    break;\n-                }\n-            }\n-            if (!state.IsValid()) break;\n-            // The transaction's outputs are created now, so that later transactions of this block can spend\n-            // them; everything else about it waits for FinishDeferredTransactions(), as do the block's totals.\n-            result.deferred_txs.push_back(i);\n-            if (i > 0) blockundo.vtxundo.emplace_back();\n-            AddCoins(view, tx, ctx.height);\n-            continue;\n-        }\n-\n         if (!tx.IsCoinBase()) {\n             const bool fCacheResults = just_check; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */\n             std::vector<CScriptCheck> vChecks;\n             PrecomputedTransactionData own_txdata;\n-            // In a block that may defer, the test above found every input (or the transaction was deferred).\n             if (!CheckBlockTransaction(tx, ctx, view, flags, nLockTimeFlags, fScriptChecks, fCacheResults, control ? txsdata[i] : own_txdata, validation_cache,\n-                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state,\n-                                       /*inputs_found=*/ctx.defer_missing_inputs)) {\n+                                       control ? &vChecks : nullptr, prevheights, nFees, nSigOpsCost, state)) {\n                 break;\n             }\n             if (control) control->Add(std::move(vChecks));\n@@ -3014,14 +2947,27 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         if (i > 0) {\n             blockundo.vtxundo.emplace_back();\n         }\n-        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), ctx.height);\n+        if (ctx.implicit_creates) {\n+            // The inputs are spent; the outputs are the window's (WindowOutputs), and never the view's.\n+            if (i > 0) {\n+                CTxUndo& txundo{blockundo.vtxundo.back()};\n+                txundo.vprevout.reserve(tx.vin.size());\n+                for (const CTxIn& txin : tx.vin) {\n+                    txundo.vprevout.emplace_back();\n+                    const bool is_spent{view.SpendCoin(txin.prevout, &txundo.vprevout.back())};\n+                    assert(is_spent);\n+                }\n+            }\n+        } else {\n+     \n[Path diff truncated]",
    "truncated": true,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46Receive-task tests do not force the critical executor boundariessrc/net_processing.cppunclear
Assessment

The supplied evidence does not include the relevant test changes or test excerpts, so it cannot establish whether deterministic asynchronous two-worker coverage for the executor boundaries was added.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "11bcd69f89a644538a224b5c514275ee",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 4029,
    "evidence_id": "049509a8693c49cb9963912a5f072d03",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 3880,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "              headers);\n}\n\nvoid PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)\n{\n    // The connector thread connects the blocks this thread accepts while this thread takes the next message\n    // (not where the tests keep blocks on the message handler, Options::blocks_on_message_handler).\n    const bool activate_async{!m_opts.blocks_on_message_handler};\n    if (ProcessBlock(block, force_processing, min_pow_checked, activate_async)) {\n        node.m_last_block_time = GetTime<std::chrono::seconds>();\n    }\n}\n\nbool PeerManagerImpl::ProcessBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool activate_async)\n{\n    bool new_block{false};\n    m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block, activate_async);\n    return BlockProcessed(block->GetHash(), new_block);\n}\n\nbool PeerManagerImpl::BlockProcessed(const uint256& hash, bool new_block)\n{\n    if (new_block) {\n        // In case this block came from a different peer than we requested\n        // from, we can erase the block request now anyway (as we just stored\n        // this block to disk).\n        LOCK(cs_main);\n        RemoveBlockRequest(hash, std::nullopt);\n    } else {\n        LOCK(cs_main);\n        // A copy of a block stored before, or being stored, whose connection is still to come: the first\n        // sender's record stays for that verdict, which erases it (BlockChecked()); this copy's sender was\n        // never recorded over it. Once the block is connected or failed, or when it was not stored at all,\n        // the record is this copy's and goes.\n        const CBlockIndex* pindex{m_chainman.m_blockman.LookupBlockIndex(hash)};\n        const bool verdict_pending{pindex && !(pindex->nStatus & BLOCK_FAILED_VALID) && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&\n                                   ((pindex->nStatus & BLOCK_HAVE_DATA) || m_chainman.IsBlockBeingStored(*pindex))};\n        if (!verdict_pending) mapBlockSource.erase(hash);\n    }\n    return new_block;\n}\n\nbool PeerManagerImpl::ProcessBlockInStages(NodeId id, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)\n{\n    auto in{std::make_shared<ChainstateManager::NewBlockInProcess>()};\n    const uint256 hash{block->GetHash()};\n    // What follows the last step made of the block.\n    const auto processed{[this, id, hash, in] {\n        if (BlockProcessed(hash, in->new_block)) {\n            m_connman.ForNode(id, [now = GetTime<std::chrono::seconds>()](CNode* connection) {\n                connection->m_last_block_time = now;\n                return true;\n            });\n        } else {\n            WITH_LOCK(cs_main, RemoveBlockRequest(hash, id));\n        }\n    }};\n    if (!m_chainman.AcceptNewBlock(*in, block, force_processing, min_pow_checked, /*activate_async=*/true)) {\n        processed();\n        return false;\n    }\n    if (!in->prepared.write) {\n        // Nothing to write: a copy of a block that is stored, or being stored.\n        m_chainman.FinishNewBlock(*in);\n        processed();\n        return false;\n    }\n    // An exception that leaves either lambda would be lost in a pool's unread future: they terminate on it,\n    // as the task does (RunBlockTask()).\n    m_chainman.m_blockman.RunBlockIO([this, id, hash, in, processed]() noexcept {\n        {\n            // A block I/O thread takes no listed lock: the connector may wait for a read queued behind this\n            // write while it holds cs_main.\n            WAITED_FOR_UNDER_LOCK(\"a block's write\");\n            m_chainman.WriteNewBlock(*in);\n        }\n        // The rest takes cs_main, so it is a worker's again: ahead of the tasks that have not started, as\n        // the block is nearly done.\n        const auto rest{[this, id, hash, in, processed]() noexcept {\n            m_chainman.FinishNewBlock(*in);\n            processed();\n            // The task's hold of the block ends before the task does, as on one thread.\n            in->block.reset();\n            EndBlockTask(id, hash);\n        }};\n        // A pool that stopped meanwhile: here, as the task would.\n        if (!m_chainman.m_connect_pool->Submit(rest, /*front=*/true)) rest();\n    });\n    return true;\n}\n\nbool PeerManagerImpl::ProcessBlockMessage(Peer& peer, CNode* node, std::span<const std::byte> bytes)\n{\n    std::shared_ptr<CBlock> pblock{m_chainman.NewBlock(/*on_pool=*/!node)};\n    SpanReader{bytes} >> TX_WITH_WITNESS(*pblock);\n\n    LogDebug(BCLog::NET, \"received block %s peer=%d\\n\", pblock->GetHash().ToString(), peer.m_id);\n\n    const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};\n\n    // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active\n    if (prev_block && IsBlockMutated(/*block=*/*pblock,\n                       /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) {\n        LogDebug(BCLog::NET, \"Received mutated block from peer=%d\\n\", peer.m_id);\n        Misbehaving(peer, \"mutated block\");\n        WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer.m_id));\n        return false;\n    }\n\n    bool forceProcessing = false;\n    const uint256 hash(pblock->GetHash());\n    bool min_pow_checked = false;\n    {\n        LOCK(cs_main);\n        // Always process the block if we requested it, since we may\n        // need it even when it's not a candidate for a new best tip.\n        forceProcessing = IsBlockRequested(hash);\n        // Precondition O13 (validation.h): on the message handler the request is removed before the block\n        // is stored. No message asks for it again in between, messages being processed on that one thread,\n        // and a second copy the getblockfrompeer RPC asked for arrives for a stored block, which\n        // AcceptBlock() handles. A block on the connect pool stays in flight until it is stored: the\n        // message handler is free meanwhile and would request it again.\n        if (node) {\n            // Checked when run only: the connect pool calls this function too, without the mutex.\n            []() NO_THREAD_SAFETY_ANALYSIS { AssertLockHeld(g_msgproc_mutex); }();\n            RemoveBlockRequest(hash, peer.m_id);\n        }\n        // mapBlockSource is only used for punishing peers and setting\n        // which peers send us compact blocks, so the race between here and\n        // cs_main in ProcessNewBlock is fine.\n        mapBlockSource.emplace(hash, std::make_pair(peer.m_id, true));\n\n        // Check claimed work on this block against our anti-dos thresholds.\n        if (prev_block && prev_block->nChainWork + GetBlockProof(*pblock) >= GetAntiDoSWorkThreshold()) {\n            min_pow_checked = true;\n        }\n    }\n    // Without a connection this is a receive task on the connect pool, and its block is activated by the\n    // connector.\n    if (node) {\n        ProcessBlock(*node, pblock, forceProcessing, min_pow_checked);\n        return false;\n    }\n    return ProcessBlockInStages(peer.m_id, pblock, forceProcessing, min_pow_checked);\n}\n\nbool PeerManagerImpl::HandOffBlock(Peer& peer, DataStream& recv, node::SyncMode mode)\n{\n    static constexpr size_t HEADER_BYTES{80};\n    if (mode != node::SyncMode::Download) return false;",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46Deferred relay cleanup can destroy the pool on its own workersrc/net_processing.cppunclear
Assessment

The supplied new-head excerpt still shows deferred relay-data cleanup submitted to the connect pool, and the diff does not show a controller-thread stop/drain or retained owning reference addressing the described final-owner-on-worker teardown. However, the excerpts do not establish whether shutdown elsewhere in the new head now prevents that lifetime scenario.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "5785f92e119f46ed8e1a68034f95fc1d",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 2542,
    "evidence_id": "8672f9bb9511486cb2231d2094ec4b23",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 2393,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)\n{\n    auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, FastRandomContext().rand64());\n\n    LOCK(cs_main);\n\n    if (pindex->nHeight <= m_highest_fast_announce)\n        return;\n    m_highest_fast_announce = pindex->nHeight;\n\n    if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return;\n\n    uint256 hashBlock(pblock->GetHash());\n    const std::shared_future<CSerializedNetMsg> lazy_ser{\n        std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })};\n\n    // The previous block's, replaced below. Its map often holds the last references to that block's\n    // transactions, out of the mempool since it was connected: freeing them takes milliseconds for a large\n    // block, which this block, under cs_main and before it is stored and connected, need not wait for.\n    std::shared_ptr<const CBlock> previous_block;\n    std::shared_ptr<const CBlockHeaderAndShortTxIDs> previous_compact_block;\n    std::shared_ptr<const std::map<GenTxid, CTransactionRef>> previous_block_txs;\n    {\n        auto most_recent_block_txs = std::make_unique<std::map<GenTxid, CTransactionRef>>();\n        for (const auto& tx : pblock->vtx) {\n            most_recent_block_txs->emplace(tx->GetHash(), tx);\n            most_recent_block_txs->emplace(tx->GetWitnessHash(), tx);\n        }\n\n        LOCK(m_most_recent_block_mutex);\n        m_most_recent_block_hash = hashBlock;\n        previous_block = std::exchange(m_most_recent_block, pblock);\n        previous_compact_block = std::exchange(m_most_recent_compact_block, pcmpctblock);\n        previous_block_txs = std::exchange(m_most_recent_block_txs, std::move(most_recent_block_txs));\n    }\n    // Freed on a worker of the connect pool, or here where the pool takes no task (the task is destroyed with\n    // what it holds).\n    (void)m_chainman.m_connect_pool->Submit([block = std::move(previous_block), compact_block = std::move(previous_compact_block),\n                                             block_txs = std::move(previous_block_txs)]() mutable {\n        block_txs.reset();\n        compact_block.reset();\n        block.reset();\n    });\n\n    m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {\n        AssertLockHeld(::cs_main);\n\n        if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)\n            return;\n        ProcessBlockAvailability(pnode->GetId());\n        CNodeState &state = *State(pnode->GetId());\n        // If the peer has, or we announced to them the previous block already,\n        // but we don't think they have this one, go ahead and announce it\n        if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {\n\n            LogDebug(BCLog::NET, \"%s sending header-and-ids %s to peer=%d\\n\", \"PeerManager::NewPoWValidBlock\",\n                    hashBlock.ToString(), pnode->GetId());\n\n            const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()};\n            PushMessage(*pnode, ser_cmpctblock.Copy());\n            state.pindexBestHeaderSent = pindex;\n        }\n    });\n}\n\n/**\n * Update our best height and announce any block hashes which weren't previously\n * in m_chainman.ActiveChain() to our peers.\n */\nvoid PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)\n{\n    SetBestBlock(pindexNew->nHeight, std::chrono::seconds{pindexNew->GetBlockTime()});\n\n    // Don't relay inventory during initial block download.\n    if (fInitialDownload) return;\n\n    // Find the hashes of all blocks that weren't previously in the best chain.\n    std::vector<uint256> vHashes;\n    const CBlockIndex *pindexToAnnounce = pindexNew;\n    while (pindexToAnnounce != pindexFork) {\n        vHashes.push_back(pindexToAnnounce->GetBlockHash());\n        pindexToAnnounce = pindexToAnnounce->pprev;\n        if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {\n            // Limit announcements in case of a huge reorganization.\n            // Rely on the peer's synchronization mechanism in that case.\n            break;\n        }\n    }\n\n    {\n        LOCK(m_peer_mutex);\n        for (auto& it : m_peer_map) {\n            Peer& peer = *it.second;\n            LOCK(peer.m_block_inv_mutex);\n            for (const uint256& hash : vHashes | std::views::reverse) {\n                peer.m_blocks_for_headers_relay.push_back(hash);\n            }\n        }\n    }\n\n    m_connman.WakeMessageHandler();\n}\n\n/**\n * Handle invalid block rejection and consequent peer discouragement, maintain which\n * peers announce compact blocks.\n */\nvoid PeerManagerImpl::BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state)\n{\n    LOCK(cs_main);\n\n    const uint256 hash(block->GetHash());\n    std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);\n\n    // If the block failed validation, we know where it came from and we're still connected\n    // to that peer, maybe punish.\n    if (state.IsInvalid() &&\n        it != mapBlockSource.end() &&\n        State(it->second.first)) {\n            MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);\n    }\n    // Check that:\n    // 1. The block is valid\n    // 2. We're not in initial block download\n    // 3. This is currently the best block we're aware of. We haven't updated\n    //    the tip yet so we have no way to check this directly here. Instead we\n    //    just check that there are currently no other blocks in flight.\n    else if (state.IsValid() &&\n             !m_chainman.IsInitialBlockDownload() &&\n             mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {\n        if (it != mapBlockSource.end()) {\n            MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);\n        }\n    }\n    if (it != mapBlockSource.end())\n        mapBlockSource.erase(it);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Messages\n//\n\nbool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)\n{\n    return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;\n}\n\nvoid PeerManagerImpl::SendPings()\n{",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46Compact-filter requests can disconnect peers awaiting block activationsrc/net_processing.cppunclear
Assessment

The supplied new-head excerpt and diff do not include the filter-request state table or PrepareBlockFilterRequest() logic, so they cannot establish whether the three filter-request rows were changed to PendingBlocksConnected or whether the regression test was added.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "3541ac3a2bff48328ea809ba44d53351",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 3994,
    "evidence_id": "68b94bf31ec243af914b8635f91fb95f",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 3845,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv)\n{\n    uint8_t filter_type_ser;\n    uint256 stop_hash;\n\n    vRecv >> filter_type_ser >> stop_hash;\n\n    const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);\n\n    const CBlockIndex* stop_index;\n    BlockFilterIndex* filter_index;\n    if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash,\n                                   /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),\n                                   stop_index, filter_index)) {\n        return;\n    }\n\n    std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);\n\n    // Populate headers.\n    const CBlockIndex* block_index = stop_index;\n    for (int i = int(headers.size()) - 1; i >= 0; i--) {\n        int height = (i + 1) * CFCHECKPT_INTERVAL;\n        block_index = block_index->GetAncestor(height);\n\n        if (!filter_index->LookupFilterHeader(block_index, headers[i])) {\n            LogDebug(BCLog::NET, \"Failed to find block filter header in index: filter_type=%s, block_hash=%s\\n\",\n                         BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());\n            return;\n        }\n    }\n\n    MakeAndPushMessage(node, NetMsgType::CFCHECKPT,\n              filter_type_ser,\n              stop_index->GetBlockHash(),\n              headers);\n}\n\nvoid PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)\n{\n    // The connector thread connects the blocks this thread accepts while this thread takes the next message\n    // (not where the tests keep blocks on the message handler, Options::blocks_on_message_handler).\n    const bool activate_async{!m_opts.blocks_on_message_handler};\n    if (ProcessBlock(block, force_processing, min_pow_checked, activate_async)) {\n        node.m_last_block_time = GetTime<std::chrono::seconds>();\n    }\n}\n\nbool PeerManagerImpl::ProcessBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool activate_async)\n{\n    bool new_block{false};\n    m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block, activate_async);\n    return BlockProcessed(block->GetHash(), new_block);\n}\n\nbool PeerManagerImpl::BlockProcessed(const uint256& hash, bool new_block)\n{\n    if (new_block) {\n        // In case this block came from a different peer than we requested\n        // from, we can erase the block request now anyway (as we just stored\n        // this block to disk).\n        LOCK(cs_main);\n        RemoveBlockRequest(hash, std::nullopt);\n    } else {\n        LOCK(cs_main);\n        // A copy of a block stored before, or being stored, whose connection is still to come: the first\n        // sender's record stays for that verdict, which erases it (BlockChecked()); this copy's sender was\n        // never recorded over it. Once the block is connected or failed, or when it was not stored at all,\n        // the record is this copy's and goes.\n        const CBlockIndex* pindex{m_chainman.m_blockman.LookupBlockIndex(hash)};\n        const bool verdict_pending{pindex && !(pindex->nStatus & BLOCK_FAILED_VALID) && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&\n                                   ((pindex->nStatus & BLOCK_HAVE_DATA) || m_chainman.IsBlockBeingStored(*pindex))};\n        if (!verdict_pending) mapBlockSource.erase(hash);\n    }\n    return new_block;\n}\n\nbool PeerManagerImpl::ProcessBlockInStages(NodeId id, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)\n{\n    auto in{std::make_shared<ChainstateManager::NewBlockInProcess>()};\n    const uint256 hash{block->GetHash()};\n    // What follows the last step made of the block.\n    const auto processed{[this, id, hash, in] {\n        if (BlockProcessed(hash, in->new_block)) {\n            m_connman.ForNode(id, [now = GetTime<std::chrono::seconds>()](CNode* connection) {\n                connection->m_last_block_time = now;\n                return true;\n            });\n        } else {\n            WITH_LOCK(cs_main, RemoveBlockRequest(hash, id));\n        }\n    }};\n    if (!m_chainman.AcceptNewBlock(*in, block, force_processing, min_pow_checked, /*activate_async=*/true)) {\n        processed();\n        return false;\n    }\n    if (!in->prepared.write) {\n        // Nothing to write: a copy of a block that is stored, or being stored.\n        m_chainman.FinishNewBlock(*in);\n        processed();\n        return false;\n    }\n    // An exception that leaves either lambda would be lost in a pool's unread future: they terminate on it,\n    // as the task does (RunBlockTask()).\n    m_chainman.m_blockman.RunBlockIO([this, id, hash, in, processed]() noexcept {\n        {\n            // A block I/O thread takes no listed lock: the connector may wait for a read queued behind this\n            // write while it holds cs_main.\n            WAITED_FOR_UNDER_LOCK(\"a block's write\");\n            m_chainman.WriteNewBlock(*in);\n        }\n        // The rest takes cs_main, so it is a worker's again: ahead of the tasks that have not started, as\n        // the block is nearly done.\n        const auto rest{[this, id, hash, in, processed]() noexcept {\n            m_chainman.FinishNewBlock(*in);\n            processed();\n            // The task's hold of the block ends before the task does, as on one thread.\n            in->block.reset();\n            EndBlockTask(id, hash);\n        }};\n        // A pool that stopped meanwhile: here, as the task would.\n        if (!m_chainman.m_connect_pool->Submit(rest, /*front=*/true)) rest();\n    });\n    return true;\n}\n\nbool PeerManagerImpl::ProcessBlockMessage(Peer& peer, CNode* node, std::span<const std::byte> bytes)\n{\n    std::shared_ptr<CBlock> pblock{m_chainman.NewBlock(/*on_pool=*/!node)};\n    SpanReader{bytes} >> TX_WITH_WITNESS(*pblock);\n\n    LogDebug(BCLog::NET, \"received block %s peer=%d\\n\", pblock->GetHash().ToString(), peer.m_id);\n\n    const CBlockIndex* prev_block{WITH_LOCK(m_chainman.GetMutex(), return m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};\n\n    // Check for possible mutation if it connects to something we know so we can check for DEPLOYMENT_SEGWIT being active\n    if (prev_block && IsBlockMutated(/*block=*/*pblock,\n                       /*check_witness_root=*/DeploymentActiveAfter(prev_block, m_chainman, Consensus::DEPLOYMENT_SEGWIT))) {\n        LogDebug(BCLog::NET, \"Received mutated block from peer=%d\\n\", peer.m_id);\n        Misbehaving(peer, \"mutated block\");\n        WITH_LOCK(cs_main, RemoveBlockRequest(pblock->GetHash(), peer.m_id));\n        return false;\n    }\n\n    bool forceProcessing = false;\n    const uint256 hash(pblock->GetHash());\n    bool min_pow_checked = false;\n    {\n        LOCK(cs_main);\n        // Always process the block if we requested it, since we may",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46IBD request sizing traps high-latency peers at one blocksrc/net_processing.cppstill_present
Assessment

The new-head excerpt retains the same request-time delivery sampling and BlocksToAskFor() formula as the reported issue: when measured delivery time remains above the queue-time threshold, the computed outstanding request count remains one. The supplied diff shows no correction to that policy.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "88cbca5d68c74c79b791c4394a997f69",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 616,
    "evidence_id": "e6ea16f759264df6b68c185ef9b19839",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 467,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "\nusing PeerRef = std::shared_ptr<Peer>;\n\n/**\n * Maintain validation-specific state about nodes, protected by cs_main, instead\n * by CNode's own locks. This simplifies asynchronous operation, where\n * processing of incoming data is done after the ProcessMessage call returns,\n * and we're no longer holding the node's locks.\n */\nstruct CNodeState {\n    //! The best known block we know this peer has announced.\n    const CBlockIndex* pindexBestKnownBlock{nullptr};\n    //! The hash of the last unknown block this peer has announced.\n    uint256 hashLastUnknownBlock{};\n    //! The last full block we both have.\n    const CBlockIndex* pindexLastCommonBlock{nullptr};\n    //! The best header we have sent our peer.\n    const CBlockIndex* pindexBestHeaderSent{nullptr};\n    //! Whether we've started headers synchronization with this peer.\n    bool fSyncStarted{false};\n    //! Since when we're stalling block download progress (in microseconds), or 0.\n    std::chrono::microseconds m_stalling_since{0us};\n    std::list<QueuedBlock> vBlocksInFlight;\n    //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.\n    std::chrono::microseconds m_downloading_since{0us};\n    //! How long the peer took for a block of late, smoothed, or 0 before its first block.\n    std::chrono::microseconds m_block_delivery_time{0us};\n    //! When the block the peer is sending started: the arrival of the block before it, or its request if the\n    //! peer had no block to send then.\n    std::chrono::microseconds m_block_delivery_since{0us};\n    //! The blocks to have outstanding with the peer at a time in initial block download.\n    int BlocksToAskFor() const\n    {\n        if (m_block_delivery_time == 0us) return 1;\n        return static_cast<int>(std::min<int64_t>(MAX_BLOCKS_IN_TRANSIT_PER_PEER, 1 + std::chrono::microseconds{BLOCK_DOWNLOAD_QUEUE_TIME} / m_block_delivery_time));\n    }\n    //! Time before which block requests should not be sent to this peer.\n    std::chrono::microseconds m_block_download_paused_until{0us};\n    //! Whether we consider this a preferred download peer.\n    bool fPreferredDownload{false};\n    /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */\n    bool m_requested_hb_cmpctblocks{false};\n    /** Whether this peer will send us cmpctblocks if we request them. */\n    bool m_provides_cmpctblocks{false};\n\n    /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic.\n      *\n      * Both are only in effect for outbound, non-manual, non-protected connections.\n      * Any peer protected (m_protect = true) is not chosen for eviction. A peer is\n      * marked as protected if all of these are true:\n      *   - its connection type is IsBlockOnlyConn() == false\n      *   - it gave us a valid connecting header\n      *   - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet\n      *   - its chain tip has at least as much work as ours\n      *\n      * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip,\n      * set a timeout CHAIN_SYNC_TIMEOUT in the future:\n      *   - If at timeout their best known block now has more work than our tip\n      *     when the timeout was set, then either reset the timeout or clear it\n      *     (after comparing against our current tip's work)\n      *   - If at timeout their best known block still has less work than our\n      *     tip did when the timeout was set, then send a getheaders message,\n      *     and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.\n      *     If their best known block is still behind when that new timeout is\n      *     reached, disconnect.\n      *\n      * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers,\n      * drop the outbound one that least recently announced us a new block.\n      */\n    struct ChainSyncTimeoutState {\n        //! A timeout used for checking whether our peer has sufficiently synced\n        std::chrono::seconds m_timeout{0s};\n        //! A header with the work we require on our peer's chain\n        const CBlockIndex* m_work_header{nullptr};\n        //! After timeout is reached, set to true after sending getheaders\n        bool m_sent_getheaders{false};\n        //! Whether this peer is protected from disconnection due to a bad/slow chain\n        bool m_protect{false};\n    };\n\n    ChainSyncTimeoutState m_chain_sync;\n\n    //! Time of last new block announcement\n    NodeClock::time_point m_last_block_announcement{NodeClock::epoch};\n};\n\nstruct InvToSendBucket {\n    const double count_floor{0};\n    std::vector<Wtxid> backlog;\n    util::TokenBucket<NodeClock> size_bucket;\n    util::TokenBucket<NodeClock> count_bucket;\n\n    /* Initialization rationale:\n     *\n     * Count bucket: Fills at rate*mult, total/initial capacity of 30s with mult=1\n     * Size bucket: Fills at 12MB every 600s, times mult so expected to be 6 times\n     *   the rate at which blocks can confirm transactions, but at least 3 times that in\n     *   the worst case. High limit to avoid triggering even with large spikes, but a\n     *   modest initial value to ensure that frequent node restarts don't raise the limit\n     *   too much.\n     * Count floor: In order to avoid sorting the global backlog too often, we ensure\n     *   that we always remove at least an average INV message's number of transactions\n     *   each time we do work. (Or 50kB if the size bucket is the limiting factor)\n     */\n\n    static constexpr double SIZE_INIT{12'000'000}; // 12 MB initially\n    static constexpr double SIZE_CAP{50'000'000}; // 50 MB maximum\n    static constexpr double SIZE_REFILL{20'000}; // 20kB/s = 12MB/600s\n\n    static constexpr double INBOUND_COUNT_SECONDS{30}; // cap/initial at 30s/mult worth of txs\n\n    InvToSendBucket(unsigned int rate, double mult)\n        : count_floor{-1.0 * rate * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL)},\n          size_bucket(/*rate=*/SIZE_REFILL * mult, /*value=*/SIZE_INIT, /*cap=*/SIZE_CAP),\n          count_bucket(/*rate=*/rate * mult, /*value=*/rate * INBOUND_COUNT_SECONDS, /*cap=*/rate * INBOUND_COUNT_SECONDS)\n    {\n    }\n\n    bool avail() const\n    {\n        return !backlog.empty() && size_bucket.value() > 0 && count_bucket.value() > 0;\n    }\n\n    void increment(NodeClock::time_point now)\n    {\n        size_bucket.increment(now);\n        count_bucket.increment(now);\n    }\n\n    std::vector<Wtxid> TakeForProcessing(CTxMemPool& mempool) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs);\n\n    bool decrement(double size)\n    {\n        bool size_ok = size_bucket.decrement(size, /*floor=*/-50e3);\n        bool count_ok = count_bucket.decrement(1, /*floor=*/count_floor);\n        return size_ok && count_ok;\n    }\n\n    PeerManagerInfo::InvBucketInfo info() const\n    {\n        return {\n            .backlog_count = backlog.size(),\n            .count_bucket = count_bucket.value(),\n            .size_bucket = size_bucket.value(),\n        };\n    }\n};\n\nclass PeerManagerImpl final : public PeerManager\n{",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#46Active-tip download cap can prevent a higher-work reorganizationsrc/net_processing.cppaddressed
Assessment

The download window now uses the active tip only when the last common block descends from that tip. On a divergent fork it uses pindexLastCommonBlock->nHeight, allowing the request window to advance with the fork frontier as recommended.

path_diff: src/net_processing.cpp; new_source: src/net_processing.cpp

[
  {
    "evidence_id": "93a3ccfa3be14518b0b2847d95802990",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "diff --git a/src/net_processing.cpp b/src/net_processing.cpp\nindex 78be8e636a..7670231c00 100644\n--- a/src/net_processing.cpp\n+++ b/src/net_processing.cpp\n@@ -425,6 +425,10 @@ struct Peer {\n     Mutex m_getdata_requests_mutex;\n     /** Work queue of items requested by this peer **/\n     std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);\n+    //! The request at the front waits for its block to be stored (ProcessGetBlockData()): nothing to do for the\n+    //! peer until then. A receive task that stores the block wakes the handler (EndBlockTask()); one stored by\n+    //! another thread (submitblock) is asked for again at the handler's next wake, within its 100 ms wait.\n+    bool m_getdata_waits_for_store GUARDED_BY(m_getdata_requests_mutex){false};\n \n     /** Time of the last getheaders message to this peer */\n     NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){};\n@@ -1678,11 +1682,14 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co\n     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n     // download that next block if the window were 1 larger.\n-    // The window is measured from the connected tip where that is lower: in initial block download the connector\n-    // thread connects accepted blocks after this thread has moved on, and blocks stored but not connected count\n-    // against the window, so that what is stored ahead of the tip stays bounded and a pruned node keeps within\n-    // its target.\n-    const int window_base{std::min(state->pindexLastCommonBlock->nHeight, m_chainman.ActiveChain().Height())};\n+    // The window is measured from the connected tip where that is lower and on the way: in initial block\n+    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n+    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n+    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n+    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n+    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n+    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n+    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n     int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n \n     FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n@@ -2951,6 +2958,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n \n     std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();\n     std::vector<CInv> vNotFound;\n+    peer.m_getdata_waits_for_store = false;\n \n     // Process as many TX items from the front of the getdata queue as\n     // possible, since they're common and it's efficient to batch process\n@@ -2984,7 +2992,11 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic\n     if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {\n         const CInv &inv = *it;\n         // A block being stored stays at the front, asked for again on the next call (ProcessGetBlockData()).\n-        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) ++it;\n+        if (!inv.IsGenBlkMsg() || ProcessGetBlockData(pfrom, peer, inv)) {\n+            ++it;\n+        } else {\n+            peer.m_getdata_waits_for_store = true;\n+        }\n         // else: If the first item on the queue is an unknown type, we erase it\n         // and continue processing the queue on the next call.\n         // NOTE: previously we wouldn't do so and the peer sending us a malformed GETDATA could\n@@ -5706,7 +5718,9 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string\n             // seconds to respond to each, the 5th ping the remote sends would appear to\n             // return very quickly.\n             //\n-            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and connected.\n+            // The answer waits in Peer::m_pending_pong until the peer's blocks are processed and the active\n+            // chainstate's activation that covers them has run (node/handoff_machine.h: at most the historical\n+            // chainstate's pass in progress is waited for, by the blocks handed over during it).\n             // The mark it waits for is the node's latest hand-off (ChainstateManager::LatestHandOff()), not\n             // the peer's own: the pong also waits for the blocks other peers handed over before it, and\n             // nothing else of this peer is processed meanwhile (ProcessMessages()).\n@@ -5941,9 +5955,10 @@ bool PeerManagerImpl::ProcessMessages(CNode& node, std::atomic<bool>& interruptM\n \n     // this maintains the order of responses\n     // and prevents m_getdata_requests to grow unbounded\n+    // A request waiting for its block to be stored is no more work: the handler would only ask again at once.\n     {\n         LOCK(peer.m_getdata_requests_mutex);\n-        if (!peer.m_getdata_requests.empty()) return true;\n+        if (!peer.m_getdata_requests.empty()) return !peer.m_getdata_waits_for_store;\n     }\n \n     // Don't bother if send buffer is too full to respond anyway\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1804,
    "evidence_id": "90907c0e7a9441768fe1ffb56f6eee26",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 1655,
    "new_head": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "old_head": "1dae81a054d2938298a64bd7e742ff825cc6c5f2",
    "path": "src/net_processing.cpp",
    "revision": "8366a1a37d5d006e7f3cd82e021698dda5b3840c",
    "source_generation": 2,
    "source_job_id": 2983,
    "text": "    }\n\n    // When syncing with AssumeUtxo and the snapshot has not yet been validated,\n    // abort downloading blocks from peers that don't have the snapshot block in their best chain.\n    // We can't reorg to this chain due to missing undo data until validation completes,\n    // so downloading blocks from it would be futile.\n    const CBlockIndex* snap_base{m_chainman.CurrentChainstate().SnapshotBase()};\n    if (snap_base && m_chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED &&\n        state->pindexBestKnownBlock->GetAncestor(snap_base->nHeight) != snap_base) {\n        LogDebug(BCLog::NET, \"Not downloading blocks from peer=%d, which doesn't have the snapshot block in its best chain.\\n\", peer.m_id);\n        return;\n    }\n\n    // Determine the forking point between the peer's chain and our chain:\n    // pindexLastCommonBlock is required to be an ancestor of pindexBestKnownBlock, and will be used as a starting point.\n    // It is being set to the fork point between the peer's best known block and the current tip, unless it is already set to\n    // an ancestor with more work than the fork point.\n    auto fork_point = LastCommonAncestor(state->pindexBestKnownBlock, m_chainman.ActiveTip());\n    if (state->pindexLastCommonBlock == nullptr ||\n        fork_point->nChainWork > state->pindexLastCommonBlock->nChainWork ||\n        state->pindexBestKnownBlock->GetAncestor(state->pindexLastCommonBlock->nHeight) != state->pindexLastCommonBlock) {\n        state->pindexLastCommonBlock = fork_point;\n    }\n    if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)\n        return;\n\n    const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;\n    // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last\n    // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to\n    // download that next block if the window were 1 larger.\n    // The window is measured from the connected tip where that is lower and on the way: in initial block\n    // download the connector thread connects accepted blocks after this thread has moved on, and blocks stored\n    // but not connected count against the window, so that what is stored ahead of the tip stays bounded and a\n    // pruned node keeps within its target. A fork is measured from its own last common block, as before: its\n    // blocks do not move the tip until the fork has more work, which may lie beyond the window.\n    const CBlockIndex* const active_tip{m_chainman.ActiveTip()};\n    const bool beyond_tip{active_tip && state->pindexLastCommonBlock->GetAncestor(active_tip->nHeight) == active_tip};\n    const int window_base{beyond_tip ? active_tip->nHeight : state->pindexLastCommonBlock->nHeight};\n    int nWindowEnd = window_base + BLOCK_DOWNLOAD_WINDOW;\n\n    FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller);\n}\n\nvoid PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block)\n{\n    Assert(from_tip);\n    Assert(target_block);\n\n    if (vBlocks.size() >= count) {\n        return;\n    }\n\n    vBlocks.reserve(count);\n    CNodeState *state = Assert(State(peer.m_id));\n\n    if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) {\n        // This peer can't provide us the complete series of blocks leading up to the\n        // assumeutxo snapshot base.\n        //\n        // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we\n        // will eventually crash when we try to reorg to it. Let other logic\n        // deal with whether we disconnect this peer.\n        //\n        // TODO at some point in the future, we might choose to request what blocks\n        // this peer does have from the historical chain, despite it not having a\n        // complete history beneath the snapshot base.\n        return;\n    }\n\n    FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight));\n}\n\nvoid PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller)\n{\n    std::vector<const CBlockIndex*> vToFetch;\n    int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);\n    bool is_limited_peer = IsLimitedPeer(peer);\n    NodeId waitingfor = -1;\n    while (pindexWalk->nHeight < nMaxHeight) {\n        // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards\n        // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive\n        // as iterating over ~100 CBlockIndex* entries anyway.\n        int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));\n        vToFetch.resize(nToFetch);\n        pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);\n        vToFetch[nToFetch - 1] = pindexWalk;\n        for (unsigned int i = nToFetch - 1; i > 0; i--) {\n            vToFetch[i - 1] = vToFetch[i]->pprev;\n        }\n\n        // Iterate over those blocks in vToFetch (in forward direction), adding the ones that\n        // are not yet downloaded and not in flight to vBlocks. In the meantime, update\n        // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's\n        // already part of our chain (and therefore don't need it even if pruned).\n        for (const CBlockIndex* pindex : vToFetch) {\n            if (!pindex->IsValid(BLOCK_VALID_TREE)) {\n                // We consider the chain that this peer is on invalid.\n                return;\n            }\n\n            if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {\n                // We wouldn't download this block or its descendants from this peer.\n                return;\n            }\n\n            if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(*pindex))) {\n                if (activeChain && pindex->HaveNumChainTxs()) {\n                    state->pindexLastCommonBlock = pindex;\n                }\n                continue;\n            }\n\n            // Is block in-flight?\n            if (IsBlockRequested(pindex->GetBlockHash())) {\n                if (waitingfor == -1) {\n                    // This is the first already-in-flight block.\n                    waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first;\n                }\n                continue;\n            }\n\n            // The block is not already downloaded, and not yet in flight.\n            if (pindex->nHeight > nWindowEnd) {\n                // We reached the end of the window.\n                if (vBlocks.size() == 0 && waitingfor != peer.m_id) {\n                    // We aren't able to fetch anything, but we would be if the download window was one larger.\n                    if (nodeStaller) *nodeStaller = waitingfor;\n                }\n                return;\n            }\n\n            // Don't request blocks that go further than what limited peers can provide\n            if (is_limited_peer && (state->pindexBestKnownBlock->nHeight - pindex->nHeight >= static_cast<int>(NODE_NETWORK_LIMITED_MIN_BLOCKS) - 2 /* two blocks buffer for possible races */)) {\n                continue;\n            }\n\n            vBlocks.push_back(pindex);\n            if (vBlocks.size() == count) {\n                return;\n            }\n        }\n    }\n}\n\n} // namespace\n\nvoid PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)\n{\n    uint64_t my_services;\n    int64_t my_time;",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 1dae81a054d2..8366a1a37d5d

2026-11-25T03:30:39Z · gpt-6-luna

fork#43FlushBlockFile() retains unused finalization modessrc/node/blockstorage.cppunclear
Assessment

The supplied changed-code excerpt does not include `FlushBlockFile()`'s declaration or implementation, so it does not show whether the unused finalization parameters and branches were removed. The bases also changed, and the evidence is insufficient to attribute any unseen difference to an author amendment rather than rebase effects.

path_diff: src/node/blockstorage.cpp; new_source: src/node/blockstorage.cpp

[
  {
    "evidence_id": "c32825dd0dcf4bdf94fc7a4f3d41f6cd",
    "finding_id": "finding:9",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/node/blockstorage.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp\nindex db2519cf0b..210dfeef4a 100644\n--- a/src/node/blockstorage.cpp\n+++ b/src/node/blockstorage.cpp\n@@ -333,11 +333,11 @@ void BlockManager::FindFilesToPruneManual(\n         }\n         // a block is being written to the file with cs_main released\n         if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-        // a write position is in the file: its number is claimed again, and the files of a prune\n-        // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-        if (IsCursorFile(fileNumber)) continue;\n \n         PruneOneBlockFile(fileNumber);\n+        // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+        // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+        LeaveCursorFile(fileNumber);\n         setFilesToPrune.insert(fileNumber);\n         count++;\n     }\n@@ -413,11 +413,11 @@ void BlockManager::FindFilesToPrune(\n             }\n             // a block is being written to the file with cs_main released\n             if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-            // a write position is in the file: its number is claimed again, and the files of a prune\n-            // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-            if (IsCursorFile(fileNumber)) continue;\n \n             PruneOneBlockFile(fileNumber);\n+            // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+            // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+            LeaveCursorFile(fileNumber);\n             // Queue up the files for removal\n             setFilesToPrune.insert(fileNumber);\n             nCurrentUsage -= nBytesToPrune;\n@@ -885,15 +885,25 @@ bool BlockManager::ClaimChunks(Preallocation& prealloc, const FlatFileSeq& seq,\n bool BlockManager::Preallocate(Preallocation& prealloc, const FlatFileSeq& seq, const FlatFilePos& pos, uint64_t size)\n {\n     const uint64_t need{seq.Chunks(pos.nPos + size)};\n-    LOCK(prealloc.mutex);\n-    const auto it{prealloc.chunks.find(pos.nFile)};\n-    if (it == prealloc.chunks.end() || it->second >= need) return true;\n+    // The allocated end of the file, or nothing to do. Entries are never removed.\n+    const auto allocated{[&]() -> std::optional<uint64_t> {\n+        LOCK(prealloc.mutex);\n+        const auto it{prealloc.chunks.find(pos.nFile)};\n+        if (it == prealloc.chunks.end() || it->second >= need) return std::nullopt;\n+        return it->second;\n+    }};\n+    if (!allocated()) return true;\n+    LOCK(prealloc.allocating);\n+    // Again: an allocation that finished meanwhile may cover these bytes.\n+    const std::optional<uint64_t> from{allocated()};\n+    if (!from) return true;\n     // From the end of what is allocated, which is past every byte written: each writer comes through here\n-    // before it writes.\n+    // before it writes, and one whose bytes lie past the recorded end waits for `allocating`.\n     bool out_of_space;\n-    seq.AllocateChunks(pos.nFile, it->second, need, out_of_space);\n+    seq.AllocateChunks(pos.nFile, *from, need, out_of_space);\n     if (out_of_space) return false;\n-    it->second = need;\n+    LOCK(prealloc.mutex);\n+    prealloc.chunks.at(pos.nFile) = need;\n     return true;\n }\n \n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1091,
    "evidence_id": "f51a573c08784c979adf5b1cef97a963",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 942,
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/node/blockstorage.cpp",
    "revision": "89352ce92ea11962389525854ca694fa0f39f640",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "void BlockManager::UnlinkPrunedFiles(const std::set<int>& setFilesToPrune) const\n{\n    std::error_code ec;\n    for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {\n        FlatFilePos pos(*it, 0);\n        const bool removed_blockfile{fs::remove(m_block_file_seq.FileName(pos), ec)};\n        const bool removed_undofile{fs::remove(m_undo_file_seq.FileName(pos), ec)};\n        if (removed_blockfile || removed_undofile) {\n            LogDebug(BCLog::BLOCKSTORAGE, \"Prune: %s deleted blk/rev (%05u)\\n\", __func__, *it);\n        }\n    }\n}\n\nAutoFile BlockManager::OpenBlockFile(const FlatFilePos& pos, bool fReadOnly) const\n{\n    return AutoFile{m_block_file_seq.Open(pos, fReadOnly), m_obfuscation};\n}\n\n/** Open an undo file (rev?????.dat) */\nAutoFile BlockManager::OpenUndoFile(const FlatFilePos& pos, bool fReadOnly) const\n{\n    return AutoFile{m_undo_file_seq.Open(pos, fReadOnly), m_obfuscation};\n}\n\nfs::path BlockManager::GetBlockPosFilename(const FlatFilePos& pos) const\n{\n    return m_block_file_seq.FileName(pos);\n}\n\nFlatFilePos BlockManager::FindNextBlockPos(uint64_t nAddSize, unsigned int nHeight, uint64_t nTime)\n{\n    AssertLockHeld(::cs_main);\n    const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);\n\n    if (!m_blockfile_cursors[chain_type]) {\n        // If a snapshot is loaded during runtime, we may not have initialized this cursor yet.\n        assert(chain_type == BlockfileType::ASSUMED);\n        const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};\n        m_blockfile_cursors[chain_type] = new_cursor;\n        LogDebug(BCLog::BLOCKSTORAGE, \"[%s] initializing blockfile cursor to %s\\n\", chain_type, new_cursor);\n    }\n    const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;\n\n    int nFile = last_blockfile;\n    if (static_cast<int>(m_blockfile_info.size()) <= nFile) {\n        m_blockfile_info.resize(nFile + 1);\n    }\n\n    bool finalize_undo = false;\n    uint64_t max_blockfile_size{MAX_BLOCKFILE_SIZE};\n    // Use smaller blockfiles in test-only -fastprune mode - but avoid\n    // the possibility of having a block not fit into the block file.\n    if (m_opts.fast_prune) {\n        max_blockfile_size = 0x10000; // 64kiB\n        if (nAddSize >= max_blockfile_size) {\n            // dynamically adjust the blockfile size to be larger than the added size\n            max_blockfile_size = nAddSize + 1;\n        }\n    }\n    assert(nAddSize < max_blockfile_size);\n\n    while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {\n        // when the undo file is keeping up with the block file, we want to flush it explicitly\n        // when it is lagging behind (more blocks arrive than are being connected), we let the\n        // undo block write case handle it\n        finalize_undo = (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==\n                         Assert(m_blockfile_cursors[chain_type])->undo_height);\n\n        // Try the next unclaimed blockfile number\n        nFile = this->MaxBlockfileNum() + 1;\n        // Set to increment MaxBlockfileNum() for next iteration\n        m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};\n\n        if (static_cast<int>(m_blockfile_info.size()) <= nFile) {\n            m_blockfile_info.resize(nFile + 1);\n        }\n    }\n    FlatFilePos pos;\n    pos.nFile = nFile;\n    pos.nPos = m_blockfile_info[nFile].nSize;\n\n    if (nFile != last_blockfile) {\n        LogDebug(BCLog::BLOCKSTORAGE, \"Leaving block file %i: %s (onto %i) (height %i)\\n\",\n                 last_blockfile, m_blockfile_info[last_blockfile].ToString(), nFile, nHeight);\n\n        // The file is trimmed, not synced. It stays marked unsynced (m_unsynced_block_files, its undo file in\n        // m_unsynced_undo_files), and whatever records its blocks in the block index syncs it first\n        // (SyncWrittenFiles()). A sync here would be made under cs_main, holding every block being stored behind\n        // it, for a durability nothing reads yet.\n        // The block file's trim waits until no write is in flight for it (UnpinBlockFile()).\n        if (finalize_undo) TrimUndoFile(last_blockfile);\n        if (m_blockfiles_being_written.contains(last_blockfile)) {\n            m_blockfiles_to_trim.insert(last_blockfile);\n        } else {\n            TrimBlockFile(last_blockfile);\n        }\n        // No undo data yet in the new file, so reset our undo-height tracking.\n        m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};\n    }\n\n    m_blockfile_info[nFile].AddBlock(nHeight, nTime);\n    m_blockfile_info[nFile].nSize += nAddSize;\n\n    // Arithmetic only: the chunk is allocated, and the disk's room for it checked, by the write\n    // (WriteBlockAt()), not here under cs_main.\n    const bool new_chunk{ClaimChunks(m_block_prealloc, m_block_file_seq, pos, nAddSize)};\n    // The position is claimed: the file holds bytes its last sync did not cover.\n    m_unsynced_block_files.insert(nFile);\n    if (new_chunk && IsPruneMode()) {\n        m_check_for_pruning = true;\n    }\n\n    m_dirty_fileinfo.insert(nFile);\n    return pos;\n}\n\nvoid BlockManager::UpdateBlockInfo(const CBlock& block, unsigned int nHeight, const FlatFilePos& pos)\n{\n    AssertLockHeld(::cs_main);\n    // Update the cursor so it points to the last file.\n    const BlockfileType chain_type{BlockfileTypeForHeight(nHeight)};\n    auto& cursor{m_blockfile_cursors[chain_type]};\n    if (!cursor || cursor->file_num < pos.nFile) {\n        m_blockfile_cursors[chain_type] = BlockfileCursor{pos.nFile};\n    }\n\n    // Update the file information with the current block.\n    const uint64_t added_size{::GetSerializeSize(TX_WITH_WITNESS(block))};\n    const int nFile = pos.nFile;\n    if (static_cast<int>(m_blockfile_info.size()) <= nFile) {\n        m_blockfile_info.resize(nFile + 1);\n    }\n    m_blockfile_info[nFile].AddBlock(nHeight, block.GetBlockTime());\n    m_blockfile_info[nFile].nSize = std::max(pos.nPos + added_size, m_blockfile_info[nFile].nSize);\n    m_dirty_fileinfo.insert(nFile);\n}\n\nFlatFilePos BlockManager::FindUndoPos(int nFile, uint64_t nAddSize)\n{\n    AssertLockHeld(::cs_main);\n    FlatFilePos pos;\n    pos.nFile = nFile;\n\n    pos.nPos = m_blockfile_info[nFile].nUndoSize;\n    m_blockfile_info[nFile].nUndoSize += nAddSize;\n    m_dirty_fileinfo.insert(nFile);\n\n    // Arithmetic only, as for a block's position: the write allocates (WriteBlockUndo()).\n    const bool new_chunk{ClaimChunks(m_undo_prealloc, m_undo_file_seq, pos, nAddSize)};\n    // The position is claimed: the file holds bytes its last sync did not cover.",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43Storage tests do not verify preallocation with reversed writessrc/node/blockstorage.cppunclear
Assessment

The follow-up assessment was invalid: unknown follow-up evidence ID.

invalid_assessment

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43The invalidation and second-copy results lack deterministic assertionssrc/validation.cppunclear
Assessment

The supplied new-head excerpt contains the staged block-processing implementation but no relevant test changes or assertions for invalidating a parent, duplicate copies, result state, or unclaimed positions. The provided diff does not establish whether the requested deterministic assertions were added elsewhere.

path_diff: src/validation.cpp; new_source: src/validation.cpp

[
  {
    "evidence_id": "507a0496e67c462f9880dceec7cc567c",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/validation.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/validation.cpp b/src/validation.cpp\nindex 48b7a0c447..c0a0039208 100644\n--- a/src/validation.cpp\n+++ b/src/validation.cpp\n@@ -2544,8 +2544,10 @@ bool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n         return false;\n     }\n \n-    // verify that the view's current state corresponds to the previous block\n+    // verify that the view's current state corresponds to the previous block, and that the context was made\n+    // for this block's parent (both are null for the genesis block)\n     assert(ctx.prev_block_hash == view.GetBestBlock());\n+    assert(block.hashPrevBlock == ctx.prev_block_hash);\n \n     // Special case for the genesis block, skipping connection of its transactions\n     // (its coinbase is unspendable)\n@@ -3027,6 +3029,10 @@ bool Chainstate::FlushStateToDisk(\n                 // twice (once in the log, and once in the tables). This is already\n                 // an overestimation, as most will delete an existing entry or\n                 // overwrite one. Still, use a conservative safety factor of 2.\n+                // Checked before the block files this call prunes are gone: their unlink is queued on a block\n+                // I/O thread, behind the block index that records them. On a nearly full disk that holds the\n+                // blocks too, the check may therefore fail where unlinking first (as master does) would have\n+                // made room; the next start unlinks them (ScanAndUnlinkAlreadyPrunedFiles()) and goes on.\n                 if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetDirtyCount())) {\n                     return FatalError(m_chainman.GetNotifications(), state, _(\"Disk space is too low!\"));\n                 }\n@@ -4151,7 +4157,7 @@ void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockInd\n                    pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);\n             }\n             pindex->m_chain_tx_count = prev_tx_sum(*pindex);\n-            // Precondition O10: arrival order, assigned under cs_main.\n+            // Precondition O10: numbered as the block becomes linked, under cs_main.\n             pindex->nSequenceId = nBlockSequenceId++;\n             for (const auto& c : m_chainstates) {\n                 c->TryAddBlockIndexCandidate(pindex);\n@@ -6535,7 +6541,14 @@ SnapshotCompletionResult ChainstateManager::MaybeValidateSnapshot(Chainstate& va\n     };\n \n     CCoinsViewDB& validated_coins_db = validated_cs.CoinsDB();\n-    validated_cs.ForceFlushStateToDisk();\n+    // The hash is taken of the coins on disk: were they not all written, a valid snapshot would be judged\n+    // against an older set and discarded. A write that failed (now, or a sync that failed earlier and keeps every\n+    // later write from landing) is no verdict on the snapshot.\n+    if (BlockValidationState flush_state; !validated_cs.FlushStateToDisk(flush_state, FlushStateMode::FORCE_FLUSH)) {\n+        LogWarning(\"[snapshot] the validated chainstate could not be written (%s); the snapshot is not judged\",\n+                   flush_state.ToString());\n+        return SnapshotCompletionResult::STATS_FAILED;\n+    }\n \n     const auto& maybe_au_data = m_options.chainparams.AssumeutxoForHeight(validated_cs.m_chain.Height());\n     if (!maybe_au_data) {\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 4913,
    "evidence_id": "e421081c0fa948d08072455132bb0feb",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 4764,
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/validation.cpp",
    "revision": "89352ce92ea11962389525854ca694fa0f39f640",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "        } else {\n            prepared.pos = m_blockman.AllocateBlockPos(block, pindex->nHeight);\n            prepared.write = true;\n            m_blocks_being_stored.insert(pindex);\n            m_blockman.PinBlockFile(prepared.pos.nFile);\n        }\n    } catch (const std::runtime_error& e) {\n        prepared.store = false;\n        return FatalError(GetNotifications(), state, strprintf(_(\"System error while saving block to disk: %s\"), e.what()));\n    }\n\n    // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW\n    // (but if it does not build on our best tip, let the SendMessages loop relay it),\n    // before the write (precondition O4).\n    if (!IsInitialBlockDownload() && ActiveTip() == pindex->pprev && m_options.signals) {\n        m_options.signals->NewPoWValidBlock(pindex, pblock);\n    }\n    return true;\n}\n\nbool ChainstateManager::FinishAcceptBlock(const CBlock& block, BlockValidationState& state, PreparedBlock& prepared, bool written)\n{\n    AssertLockHeld(cs_main);\n    Assert(prepared.store);\n    prepared.store = false;\n    CBlockIndex* pindex{Assert(prepared.pindex)};\n    if (prepared.write) {\n        m_blocks_being_stored.erase(pindex);\n        m_blockman.UnpinBlockFile(prepared.pos.nFile);\n    }\n    if (!written) {\n        // WriteBlockAt() reported the fatal error already; the claimed space stays unused.\n        return state.Error(strprintf(\"%s: Failed to write block to disk\", __func__));\n    }\n    // The block is on disk; its index entry records nothing of it, as after a write the node never\n    // finished, which is also what is left behind when the same block is refused at its header.\n    if (FailedMeanwhile(*pindex, state)) return false;\n    try {\n        ReceivedBlockTransactions(block, pindex, prepared.pos);\n        // Precondition O2: stored means all of this, recorded in one hold of cs_main. This is\n        // what ReceivedBlockTransactions() just did; checked so that a split of that step keeps it.\n        Assume((pindex->nStatus & BLOCK_HAVE_DATA) && pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && !pindex->GetBlockPos().IsNull());\n    } catch (const std::runtime_error& e) {\n        return FatalError(GetNotifications(), state, strprintf(_(\"System error while saving block to disk: %s\"), e.what()));\n    }\n\n    // TODO: FlushStateToDisk() handles flushing of both block and chainstate\n    // data, so we should move this to ChainstateManager so that we can be more\n    // intelligent about how we flush.\n    // For now, since FlushStateMode::NONE is used, all that can happen is that\n    // the block files may be pruned, so we can just call this on one\n    // chainstate (particularly if we haven't implemented pruning with\n    // background validation yet).\n    //\n    // Flush errors (e.g. low disk space during pruning) are ignored, so that\n    // callers can't mistreat a flush failure as a block validation failure.\n    // The fatal error notification inside FlushStateToDisk still fires,\n    // so the node will shut down on unrecoverable flush errors regardless.\n    // For state a dummy value is used, and the return value is ignored.\n    BlockValidationState flush_state_ignore;\n    (void)ActiveChainstate().FlushStateToDisk(flush_state_ignore, FlushStateMode::NONE);\n\n    CheckBlockIndex();\n\n    return true;\n}\n\nbool ChainstateManager::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked)\n{\n    AssertLockHeld(cs_main);\n    PreparedBlock prepared;\n    if (!PrepareAcceptBlockHeader(*pblock, state, ppindex, fRequested, fNewBlock, min_pow_checked, prepared)) return false;\n    if (!prepared.check) return true;\n    const bool checks_ok{CheckAcceptBlock(*pblock, state, prepared)};\n    if (!PrepareAcceptBlockStorage(pblock, state, checks_ok, /*invalidate_on_check_block_failure=*/true, dbp, fNewBlock, prepared)) return false;\n    if (!prepared.store) return true;\n    bool written{true};\n    if (prepared.write) {\n        try {\n            written = m_blockman.WriteBlockAt(*pblock, prepared.pos);\n        } catch (const std::runtime_error& e) {\n            m_blocks_being_stored.erase(prepared.pindex);\n            m_blockman.UnpinBlockFile(prepared.pos.nFile);\n            return FatalError(GetNotifications(), state, strprintf(_(\"System error while saving block to disk: %s\"), e.what()));\n        }\n    }\n    return FinishAcceptBlock(*pblock, state, prepared, written);\n}\n\nbool ChainstateManager::ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block)\n{\n    AssertLockNotHeld(cs_main);\n    // The three steps in a row on this thread.\n    NewBlockInProcess in;\n    bool ret{false};\n    if (AcceptNewBlock(in, block, force_processing, min_pow_checked)) {\n        WriteNewBlock(in);\n        ret = FinishNewBlock(in);\n    }\n    if (new_block) *new_block = in.new_block;\n    return ret;\n}\n\nbool ChainstateManager::NewBlockFailed(NewBlockInProcess& in)\n{\n    AssertLockHeld(cs_main);\n    if (m_options.signals) {\n        m_options.signals->BlockChecked(in.block, in.state);\n    }\n    LogError(\"ProcessNewBlock: AcceptBlock FAILED (%s)\\n\", in.state.ToString());\n    return false;\n}\n\nbool ChainstateManager::AcceptNewBlock(NewBlockInProcess& in, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked)\n{\n    AssertLockNotHeld(cs_main);\n    in.block = block;\n    CBlockIndex *pindex = nullptr;\n\n    // The block's own checks come first, before anything of the header is accepted: their verdict is\n    // the block's, whatever its header, and they need only the consensus parameters, so they run\n    // without the lock. (Two calls may be given one block object: the flags the checks memoise in,\n    // CBlock::fChecked and its two siblings, are atomic.)\n    if (!CheckBlock(*block, in.state, GetConsensus())) {\n        LOCK(cs_main);\n        return NewBlockFailed(in);\n    }\n    {\n        LOCK(cs_main);\n        // Accept the header and decide whether the block is wanted; the contextual checks run below,\n        // without the lock, against the context built here.\n        if (!PrepareAcceptBlockHeader(*block, in.state, &pindex, force_processing, &in.new_block, min_pow_checked, in.prepared)) return NewBlockFailed(in);\n    }\n    if (in.prepared.check) {\n        // Not marking a block invalid when CheckBlock() fails is protective against consensus failure if\n        // there are any unknown forms of block malleability that cause CheckBlock() to fail; see e.g.\n        // CVE-2012-2459 and https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html.\n        // Because CheckBlock() is not very expensive, the anti-DoS benefits of caching failure (of a\n        // definitely-invalid block) are not substantial.\n        const bool checks_ok{CheckAcceptBlock(*block, in.state, in.prepared)};\n        LOCK(cs_main);\n        if (!PrepareAcceptBlockStorage(block, in.state, checks_ok, /*invalidate_on_check_block_failure=*/false, nullptr, &in.new_block, in.prepared)) return NewBlockFailed(in);\n    }\n    return true;\n}\n\nvoid ChainstateManager::WriteNewBlock(NewBlockInProcess& in)\n{\n    // No lock held, and none taken.\n    if (!in.prepared.store || !in.prepared.write) return;",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43Pin, cursor and deferred-trim guards lack targeted unit coveragesrc/node/blockstorage.cpppartially_addressed
Assessment

The changes make cursor files eligible for pruning by moving cursor positions to a fresh file number after pruning, addressing the cursor exclusion. But the supplied diff does not show a pin guard in either prune finder, nor the requested deterministic tests for pinned deferred trimming and pinned-file pruning; the finding's coverage gaps therefore remain materially unresolved.

path_diff: src/node/blockstorage.cpp

[
  {
    "evidence_id": "7b259687f4714e7b8a6b65f824f0a703",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/node/blockstorage.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp\nindex db2519cf0b..210dfeef4a 100644\n--- a/src/node/blockstorage.cpp\n+++ b/src/node/blockstorage.cpp\n@@ -333,11 +333,11 @@ void BlockManager::FindFilesToPruneManual(\n         }\n         // a block is being written to the file with cs_main released\n         if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-        // a write position is in the file: its number is claimed again, and the files of a prune\n-        // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-        if (IsCursorFile(fileNumber)) continue;\n \n         PruneOneBlockFile(fileNumber);\n+        // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+        // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+        LeaveCursorFile(fileNumber);\n         setFilesToPrune.insert(fileNumber);\n         count++;\n     }\n@@ -413,11 +413,11 @@ void BlockManager::FindFilesToPrune(\n             }\n             // a block is being written to the file with cs_main released\n             if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-            // a write position is in the file: its number is claimed again, and the files of a prune\n-            // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-            if (IsCursorFile(fileNumber)) continue;\n \n             PruneOneBlockFile(fileNumber);\n+            // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+            // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+            LeaveCursorFile(fileNumber);\n             // Queue up the files for removal\n             setFilesToPrune.insert(fileNumber);\n             nCurrentUsage -= nBytesToPrune;\n@@ -885,15 +885,25 @@ bool BlockManager::ClaimChunks(Preallocation& prealloc, const FlatFileSeq& seq,\n bool BlockManager::Preallocate(Preallocation& prealloc, const FlatFileSeq& seq, const FlatFilePos& pos, uint64_t size)\n {\n     const uint64_t need{seq.Chunks(pos.nPos + size)};\n-    LOCK(prealloc.mutex);\n-    const auto it{prealloc.chunks.find(pos.nFile)};\n-    if (it == prealloc.chunks.end() || it->second >= need) return true;\n+    // The allocated end of the file, or nothing to do. Entries are never removed.\n+    const auto allocated{[&]() -> std::optional<uint64_t> {\n+        LOCK(prealloc.mutex);\n+        const auto it{prealloc.chunks.find(pos.nFile)};\n+        if (it == prealloc.chunks.end() || it->second >= need) return std::nullopt;\n+        return it->second;\n+    }};\n+    if (!allocated()) return true;\n+    LOCK(prealloc.allocating);\n+    // Again: an allocation that finished meanwhile may cover these bytes.\n+    const std::optional<uint64_t> from{allocated()};\n+    if (!from) return true;\n     // From the end of what is allocated, which is past every byte written: each writer comes through here\n-    // before it writes.\n+    // before it writes, and one whose bytes lie past the recorded end waits for `allocating`.\n     bool out_of_space;\n-    seq.AllocateChunks(pos.nFile, it->second, need, out_of_space);\n+    seq.AllocateChunks(pos.nFile, *from, need, out_of_space);\n     if (out_of_space) return false;\n-    it->second = need;\n+    LOCK(prealloc.mutex);\n+    prealloc.chunks.at(pos.nFile) = need;\n     return true;\n }\n \n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43Position claims still wait on allocation I/O under cs_mainsrc/node/blockstorage.cppaddressed
Assessment

`Preallocate()` now holds the allocation-only `prealloc.allocating` lock during allocation, while its map mutex is acquired only briefly to read or update the high-water mark. `ClaimChunks()` takes only the map mutex, so it no longer waits on the allocation I/O lock while holding `cs_main`.

path_diff: src/node/blockstorage.cpp

[
  {
    "evidence_id": "4bb8d2f57fd14eea84cedb289ca31236",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/node/blockstorage.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp\nindex db2519cf0b..210dfeef4a 100644\n--- a/src/node/blockstorage.cpp\n+++ b/src/node/blockstorage.cpp\n@@ -333,11 +333,11 @@ void BlockManager::FindFilesToPruneManual(\n         }\n         // a block is being written to the file with cs_main released\n         if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-        // a write position is in the file: its number is claimed again, and the files of a prune\n-        // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-        if (IsCursorFile(fileNumber)) continue;\n \n         PruneOneBlockFile(fileNumber);\n+        // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+        // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+        LeaveCursorFile(fileNumber);\n         setFilesToPrune.insert(fileNumber);\n         count++;\n     }\n@@ -413,11 +413,11 @@ void BlockManager::FindFilesToPrune(\n             }\n             // a block is being written to the file with cs_main released\n             if (m_blockfiles_being_written.contains(fileNumber)) continue;\n-            // a write position is in the file: its number is claimed again, and the files of a prune\n-            // are removed later (UnlinkPrunedFiles() on a block I/O thread)\n-            if (IsCursorFile(fileNumber)) continue;\n \n             PruneOneBlockFile(fileNumber);\n+            // a write position in the file moves to an unclaimed number (m_blockfile_info may grow): the files\n+            // of a prune are removed later (UnlinkPrunedFiles() on a block I/O thread)\n+            LeaveCursorFile(fileNumber);\n             // Queue up the files for removal\n             setFilesToPrune.insert(fileNumber);\n             nCurrentUsage -= nBytesToPrune;\n@@ -885,15 +885,25 @@ bool BlockManager::ClaimChunks(Preallocation& prealloc, const FlatFileSeq& seq,\n bool BlockManager::Preallocate(Preallocation& prealloc, const FlatFileSeq& seq, const FlatFilePos& pos, uint64_t size)\n {\n     const uint64_t need{seq.Chunks(pos.nPos + size)};\n-    LOCK(prealloc.mutex);\n-    const auto it{prealloc.chunks.find(pos.nFile)};\n-    if (it == prealloc.chunks.end() || it->second >= need) return true;\n+    // The allocated end of the file, or nothing to do. Entries are never removed.\n+    const auto allocated{[&]() -> std::optional<uint64_t> {\n+        LOCK(prealloc.mutex);\n+        const auto it{prealloc.chunks.find(pos.nFile)};\n+        if (it == prealloc.chunks.end() || it->second >= need) return std::nullopt;\n+        return it->second;\n+    }};\n+    if (!allocated()) return true;\n+    LOCK(prealloc.allocating);\n+    // Again: an allocation that finished meanwhile may cover these bytes.\n+    const std::optional<uint64_t> from{allocated()};\n+    if (!from) return true;\n     // From the end of what is allocated, which is past every byte written: each writer comes through here\n-    // before it writes.\n+    // before it writes, and one whose bytes lie past the recorded end waits for `allocating`.\n     bool out_of_space;\n-    seq.AllocateChunks(pos.nFile, it->second, need, out_of_space);\n+    seq.AllocateChunks(pos.nFile, *from, need, out_of_space);\n     if (out_of_space) return false;\n-    it->second = need;\n+    LOCK(prealloc.mutex);\n+    prealloc.chunks.at(pos.nFile) = need;\n     return true;\n }\n \n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43AllocateChunks() narrows 64-bit undo offsets to 32 bitssrc/flatfile.cppaddressed
Assessment

`AllocateChunks()` now constructs the position from `from * m_chunk_size` without narrowing it to `unsigned int`, preserving the full-width offset and preventing the 4 GiB wrap described in the finding.

path_diff: src/flatfile.cpp

[
  {
    "evidence_id": "fa2147de6acf491bb93c50d831c930ac",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/flatfile.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/flatfile.cpp b/src/flatfile.cpp\nindex 9c72c7ce09..e9c94ade7e 100644\n--- a/src/flatfile.cpp\n+++ b/src/flatfile.cpp\n@@ -10,6 +10,7 @@\n #include <util/log.h>\n #include <util/overflow.h>\n \n+#include <cerrno>\n #include <stdexcept>\n \n FlatFileSeq::FlatFileSeq(fs::path dir, const char* prefix, uint64_t chunk_size)\n@@ -40,8 +41,12 @@ FILE* FlatFileSeq::Open(const FlatFilePos& pos, bool read_only) const\n     fs::path path = FileName(pos);\n     fs::create_directories(path.parent_path());\n     FILE* file = fsbridge::fopen(path, read_only ? \"rb\": \"rb+\");\n-    if (!file && !read_only)\n-        file = fsbridge::fopen(path, \"wb+\");\n+    if (!file && !read_only) {\n+        // Created only if it does not exist, never truncated: files are written and synced on several threads,\n+        // and another one may create the file and write to it between the two calls.\n+        file = fsbridge::fopen(path, \"wb+x\");\n+        if (!file && errno == EEXIST) file = fsbridge::fopen(path, \"rb+\");\n+    }\n     if (!file) {\n         LogError(\"Unable to open file %s\", fs::PathToString(path));\n         return nullptr;\n@@ -94,7 +99,7 @@ uint64_t FlatFileSeq::AllocateChunks(int file, uint64_t from, uint64_t to, bool&\n {\n     out_of_space = false;\n     if (to <= from) return 0;\n-    const FlatFilePos pos(file, static_cast<unsigned int>(from * m_chunk_size));\n+    const FlatFilePos pos(file, from * m_chunk_size);\n     const uint64_t new_size{to * m_chunk_size};\n     const uint64_t inc_size{new_size - pos.nPos};\n     if (!CheckDiskSpace(m_dir, inc_size)) {\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43Deferred automatic unlinking can cause a premature disk-space shutdownsrc/validation.cppstill_present
Assessment

The new-head excerpt explicitly documents that automatic unlinking is queued on the block I/O thread and that the dirty-coins disk-space check still occurs before those pruned files are gone. The premature low-disk failure described by the finding remains possible.

new_source: src/validation.cpp

[
  {
    "bounded": true,
    "end_line": 3139,
    "evidence_id": "32608b4f231d4a8d8bfe8e9a9aa8daf1",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 2990,
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/validation.cpp",
    "revision": "89352ce92ea11962389525854ca694fa0f39f640",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "                return FatalError(m_chainman.GetNotifications(), state, _(\"Disk space is too low!\"));\n            }\n            {\n                LOG_TIME_MILLIS_WITH_CATEGORY(\"write block and undo data to disk\", BCLog::BENCH);\n\n                // First make sure all block and undo data is flushed to disk: the file this\n                // chainstate writes to, then every other file written to since its last sync\n                // (an undo file whose block file was left behind, the other chainstate's file).\n                step(node::FlushStep::SyncFiles);\n                if (!m_blockman.FlushChainstateBlockFile(m_chain.Height()) || !m_blockman.SyncWrittenFiles()) {\n                    // The specific error was already reported through flushError()\n                    return state.Error(\"Failed to flush block or undo file\");\n                }\n            }\n\n            // Then update all block file information (which may refer to block and undo files).\n            {\n                LOG_TIME_MILLIS_WITH_CATEGORY(\"write block index to disk\", BCLog::BENCH);\n\n                step(node::FlushStep::WriteIndex);\n                m_blockman.WriteBlockIndexDB();\n            }\n            // Finally remove any pruned files\n            if (fFlushForPrune) {\n                LOG_TIME_MILLIS_WITH_CATEGORY(\"unlink pruned files\", BCLog::BENCH);\n\n                step(node::FlushStep::Unlink);\n                if (nManualPruneHeight > 0) {\n                    // A request (pruneblockchain) returns once its files are gone.\n                    m_blockman.UnlinkPrunedFiles(setFilesToPrune);\n                } else {\n                    // Nothing waits for the files to go: removed on a block I/O thread, not under cs_main.\n                    m_blockman.RunBlockIO([&blockman = m_blockman, files = std::move(setFilesToPrune)] { blockman.UnlinkPrunedFiles(files); });\n                }\n            }\n\n            if (!CoinsTip().GetBestBlock().IsNull()) {\n                // Typical Coin structures on disk are around 48 bytes in size.\n                // Pushing a new one to the database can cause it to be written\n                // twice (once in the log, and once in the tables). This is already\n                // an overestimation, as most will delete an existing entry or\n                // overwrite one. Still, use a conservative safety factor of 2.\n                // Checked before the block files this call prunes are gone: their unlink is queued on a block\n                // I/O thread, behind the block index that records them. On a nearly full disk that holds the\n                // blocks too, the check may therefore fail where unlinking first (as master does) would have\n                // made room; the next start unlinks them (ScanAndUnlinkAlreadyPrunedFiles()) and goes on.\n                if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetDirtyCount())) {\n                    return FatalError(m_chainman.GetNotifications(), state, _(\"Disk space is too low!\"));\n                }\n                // Flush the chainstate (which may refer to block index entries).\n                step(node::FlushStep::WriteCoins);\n                empty_cache ? CoinsTip().Flush() : CoinsTip().Sync();\n                m_last_flushed_block = m_blockman.LookupBlockIndex(CoinsTip().GetBestBlock());\n                full_flush_completed = true;\n                TRACEPOINT(utxocache, flush,\n                    int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - nNow)},\n                    (uint32_t)mode,\n                    (uint64_t)coins_count,\n                    (uint64_t)coins_mem_usage,\n                    (bool)fFlushForPrune);\n            }\n        }\n\n        if (should_write || m_next_write == NodeClock::time_point::max()) {\n            constexpr auto range{DATABASE_WRITE_INTERVAL_MAX - DATABASE_WRITE_INTERVAL_MIN};\n            m_next_write = FastRandomContext().rand_uniform_delay(NodeClock::now() + DATABASE_WRITE_INTERVAL_MIN, range);\n        }\n    }\n    if (full_flush_completed) {\n        if (m_chainman.m_options.signals) {\n            m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));\n        }\n\n        if (!m_chainman.m_interrupt && !CoinsDB().IsMemoryOnly() && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {\n            try {\n                const fs::path path{StoragePath()};\n                const uint64_t min_free_space{m_chainman.GetParams().AssumedChainStateSize() * 1_GiB};\n                if (CheckDiskSpace(path, min_free_space)) {\n                    CoinsDB().CompactFullAsync();\n                } else {\n                    LogWarning(\"Deferring chainstate compaction of %s: %.2f GiB free, %u GiB needed. Free up some space so compaction can run.\",\n                               fs::PathToString(path), fs::space(path).available / double{1_GiB}, CeilDiv(min_free_space, 1_GiB));\n                }\n            } catch (const std::exception& e) {\n                LogWarning(\"Failed to start chainstate compaction (%s)\", e.what());\n            }\n        }\n    }\n    } catch (const std::runtime_error& e) {\n        return FatalError(m_chainman.GetNotifications(), state, strprintf(_(\"System error while flushing: %s\"), e.what()));\n    }\n    return true;\n}\n\nvoid Chainstate::ForceFlushStateToDisk(bool wipe_cache)\n{\n    BlockValidationState state;\n    if (!this->FlushStateToDisk(state, wipe_cache ? FlushStateMode::FORCE_FLUSH : FlushStateMode::FORCE_SYNC)) {\n        LogWarning(\"Failed to force flush state (%s)\", state.ToString());\n    }\n}\n\nvoid Chainstate::PruneAndFlush()\n{\n    BlockValidationState state;\n    m_blockman.m_check_for_pruning = true;\n    if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {\n        LogWarning(\"Failed to flush state (%s)\", state.ToString());\n    }\n}\n\nstatic void UpdateTipLog(\n    const ChainstateManager& chainman,\n    const CCoinsViewCache& coins_tip,\n    const CBlockIndex* tip,\n    const std::string& func_name,\n    const std::string& prefix,\n    const std::string& warning_messages,\n    const bool background_validation) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)\n{\n\n    AssertLockHeld(::cs_main);\n\n    // Disable rate limiting as this may log frequently during IBD.\n    LogInfo(util::log::NO_RATE_LIMIT, \"%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\\n\",\n                   prefix, func_name,\n                   tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,\n                   log(tip->nChainWork.getdouble()) / log(2.0), tip->m_chain_tx_count,\n                   FormatISO8601DateTime(tip->GetBlockTime()),\n                   background_validation ? chainman.GetBackgroundVerificationProgress(*tip) : chainman.GuessVerificationProgress(tip),\n                   coins_tip.DynamicMemoryUsage() / double(1_MiB),\n                   coins_tip.GetCacheSize(),\n                   !warning_messages.empty() ? strprintf(\" warning='%s'\", warning_messages) : \"\");\n}\n\nvoid Chainstate::UpdateTip(const CBlockIndex* pindexNew)\n{\n    AssertLockHeld(::cs_main);\n    const auto& coins_tip = this->CoinsTip();\n\n    // The remainder of the function isn't relevant if we are not acting on\n    // the active chainstate, so return if need be.\n    if (this != &m_chainman.ActiveChainstate()) {\n        // Only log every so often so that we don't bury log messages at the tip.\n        constexpr int BACKGROUND_LOG_INTERVAL = 2000;\n        if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {\n            UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, \"[background validation] \", \"\", /*background_validation=*/true);\n        }\n        return;\n    }",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#43A concurrent flush can truncate a newly written block filesrc/flatfile.cppaddressed
Assessment

Writable open-or-create now uses exclusive `wb+x` creation and, on `EEXIST`, reopens with `rb+`; neither path truncates an existing file. This removes the described flush/write race in the reported code path.

path_diff: src/flatfile.cpp

[
  {
    "evidence_id": "4d7b42dea33b4d6788fb4d9277a1cf2b",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "89352ce92ea11962389525854ca694fa0f39f640",
    "old_head": "9a23fcf79ba8c892317dd741583975ff890a8287",
    "path": "src/flatfile.cpp",
    "source_generation": 2,
    "source_job_id": 2980,
    "text": "diff --git a/src/flatfile.cpp b/src/flatfile.cpp\nindex 9c72c7ce09..e9c94ade7e 100644\n--- a/src/flatfile.cpp\n+++ b/src/flatfile.cpp\n@@ -10,6 +10,7 @@\n #include <util/log.h>\n #include <util/overflow.h>\n \n+#include <cerrno>\n #include <stdexcept>\n \n FlatFileSeq::FlatFileSeq(fs::path dir, const char* prefix, uint64_t chunk_size)\n@@ -40,8 +41,12 @@ FILE* FlatFileSeq::Open(const FlatFilePos& pos, bool read_only) const\n     fs::path path = FileName(pos);\n     fs::create_directories(path.parent_path());\n     FILE* file = fsbridge::fopen(path, read_only ? \"rb\": \"rb+\");\n-    if (!file && !read_only)\n-        file = fsbridge::fopen(path, \"wb+\");\n+    if (!file && !read_only) {\n+        // Created only if it does not exist, never truncated: files are written and synced on several threads,\n+        // and another one may create the file and write to it between the two calls.\n+        file = fsbridge::fopen(path, \"wb+x\");\n+        if (!file && errno == EEXIST) file = fsbridge::fopen(path, \"rb+\");\n+    }\n     if (!file) {\n         LogError(\"Unable to open file %s\", fs::PathToString(path));\n         return nullptr;\n@@ -94,7 +99,7 @@ uint64_t FlatFileSeq::AllocateChunks(int file, uint64_t from, uint64_t to, bool&\n {\n     out_of_space = false;\n     if (to <= from) return 0;\n-    const FlatFilePos pos(file, static_cast<unsigned int>(from * m_chunk_size));\n+    const FlatFilePos pos(file, from * m_chunk_size);\n     const uint64_t new_size{to * m_chunk_size};\n     const uint64_t inc_size{new_size - pos.nPos};\n     if (!CheckDiskSpace(m_dir, inc_size)) {\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · 9a23fcf79ba8..89352ce92ea1

2026-11-25T00:05:40Z · gpt-6-luna

fork#42O10 describes receipt order instead of nSequenceId linking ordersrc/validation.hunclear
Assessment

The follow-up assessment was invalid: addressed findings require original comparison evidence.

invalid_assessment

Source report · d1213c8cc37b..65380388ffcc

2026-11-24T20:43:45Z · gpt-6-luna

fork#42The tip snapshot tests do not exercise independent readerssrc/test/tip_snapshot_tests.cpppartially_addressed
Assessment

A new test launches a separate reader while the test thread holds `cs_main` and checks that the published-tip read completes, addressing the independent-reader gap for the unchanged-tip case. The supplied new-head test excerpt does not add the requested coordinated multi-block reorganization case in which an outside reader waits for final publication.

path_diff: src/test/tip_snapshot_tests.cpp; new_source: src/test/tip_snapshot_tests.cpp

[
  {
    "evidence_id": "20cc4fa6af3440e9a40994a902ed368f",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "65380388ffcc175520da5aef26a031e6019b5444",
    "old_head": "d1213c8cc37b4fbe929e3ffdb15d9b40a2378e23",
    "path": "src/test/tip_snapshot_tests.cpp",
    "source_generation": 2,
    "source_job_id": 2979,
    "text": "diff --git a/src/test/tip_snapshot_tests.cpp b/src/test/tip_snapshot_tests.cpp\nindex 34013c98af..65d9d3da1c 100644\n--- a/src/test/tip_snapshot_tests.cpp\n+++ b/src/test/tip_snapshot_tests.cpp\n@@ -14,6 +14,8 @@\n \n #include <boost/test/unit_test.hpp>\n \n+#include <chrono>\n+#include <future>\n #include <vector>\n \n BOOST_FIXTURE_TEST_SUITE(tip_snapshot_tests, TestChain100Setup)\n@@ -150,6 +152,28 @@ BOOST_AUTO_TEST_CASE(tip_is_published_at_the_end_of_the_hold)\n     signals.UnregisterValidationInterface(&inside);\n }\n \n+// What the published value is for: a reader on another thread gets the tip while cs_main is held elsewhere and\n+// the tip is not moving, without waiting for the lock.\n+BOOST_AUTO_TEST_CASE(published_tip_is_read_without_cs_main)\n+{\n+    ChainstateManager& chainman{*Assert(m_node.chainman)};\n+    BOOST_REQUIRE(!chainman.TipUnpublished());\n+    const node::TipSnapshot before{chainman.PublishedTip()};\n+    std::future<node::TipSnapshot> read;\n+    std::future_status status;\n+    {\n+        LOCK(::cs_main);\n+        read = std::async(std::launch::async, [&chainman] { return chainman.PublishedTip(); });\n+        // Generous: it can only expire if the read waits for the lock this thread holds, which is released\n+        // before the future is waited for again, so a failure cannot hang.\n+        status = read.wait_for(std::chrono::seconds{60});\n+    }\n+    BOOST_REQUIRE(status == std::future_status::ready);\n+    const node::TipSnapshot seen{read.get()};\n+    BOOST_CHECK(seen.hash == before.hash);\n+    BOOST_CHECK_EQUAL(seen.sequence, before.sequence);\n+}\n+\n BOOST_AUTO_TEST_CASE(block_facts_are_one_copy)\n {\n     ChainstateManager& chainman{*Assert(m_node.chainman)};\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 195,
    "evidence_id": "36de0b214b8c42db84450c74b60c9250",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 89,
    "new_head": "65380388ffcc175520da5aef26a031e6019b5444",
    "old_head": "d1213c8cc37b4fbe929e3ffdb15d9b40a2378e23",
    "path": "src/test/tip_snapshot_tests.cpp",
    "revision": "65380388ffcc175520da5aef26a031e6019b5444",
    "source_generation": 2,
    "source_job_id": 2979,
    "text": "\nBOOST_AUTO_TEST_CASE(published_tip_follows_a_block_that_ends_ibd)\n{\n    auto& chainman{static_cast<TestChainstateManager&>(*Assert(m_node.chainman))};\n    if (!chainman.IsInitialBlockDownload()) chainman.ResetIbd();\n    const node::TipSnapshot during{chainman.PublishedTip()};\n    BOOST_REQUIRE(during.initial_block_download);\n\n    // A recent block ends initial block download in the hold that connects\n    // it: the published value has the new tip and the new answer.\n    CreateAndProcessBlock({}, CScript{} << OP_TRUE);\n    BOOST_REQUIRE(!chainman.IsInitialBlockDownload());\n    const node::TipSnapshot after{chainman.PublishedTip()};\n    BOOST_CHECK(!after.initial_block_download);\n    BOOST_CHECK_EQUAL(after.height, during.height + 1);\n    BOOST_CHECK_GT(after.sequence, during.sequence);\n    CheckMatchesChain(chainman);\n}\n\n//! Reads the tip from inside the cs_main hold that moved it.\nstruct InsideTheHold final : public CValidationInterface {\n    ChainstateManager& m_chainman;\n    std::vector<bool> m_unpublished;\n    std::vector<int> m_heights;\n    explicit InsideTheHold(ChainstateManager& chainman) : m_chainman{chainman} {}\n    void ActiveTipChange(const CBlockIndex&, bool) override\n    {\n        m_unpublished.push_back(m_chainman.TipUnpublished());\n        m_heights.push_back(m_chainman.PublishedTip().height);\n    }\n};\n\nBOOST_AUTO_TEST_CASE(tip_is_published_at_the_end_of_the_hold)\n{\n    ChainstateManager& chainman{*Assert(m_node.chainman)};\n    ValidationSignals& signals{*Assert(m_node.validation_signals)};\n    InsideTheHold inside{chainman};\n    signals.RegisterValidationInterface(&inside);\n\n    const node::TipSnapshot before{chainman.PublishedTip()};\n    CreateAndProcessBlock({}, CScript{} << OP_TRUE);\n\n    // While the hold was open nothing was published, and a reader holding\n    // cs_main saw the tip of that moment, as it would reading the chain.\n    BOOST_REQUIRE_EQUAL(inside.m_unpublished.size(), 1U);\n    BOOST_CHECK(inside.m_unpublished[0]);\n    BOOST_CHECK_EQUAL(inside.m_heights[0], before.height + 1);\n    // The hold published before it released cs_main.\n    CheckMatchesChain(chainman);\n    BOOST_CHECK_EQUAL(chainman.PublishedTip().sequence, before.sequence + 1);\n\n    // A tip moved outside the holds that publish leaves readers on\n    // cs_main until the next publication.\n    {\n        LOCK(::cs_main);\n        chainman.MarkTipChanged();\n        BOOST_CHECK(chainman.TipUnpublished());\n        BOOST_CHECK(chainman.PublishedTip().hash == chainman.ActiveTip()->GetBlockHash());\n        chainman.PublishTip();\n        BOOST_CHECK(!chainman.TipUnpublished());\n    }\n    BOOST_CHECK_EQUAL(chainman.PublishedTip().sequence, before.sequence + 2);\n\n    signals.UnregisterValidationInterface(&inside);\n}\n\n// What the published value is for: a reader on another thread gets the tip while cs_main is held elsewhere and\n// the tip is not moving, without waiting for the lock.\nBOOST_AUTO_TEST_CASE(published_tip_is_read_without_cs_main)\n{\n    ChainstateManager& chainman{*Assert(m_node.chainman)};\n    BOOST_REQUIRE(!chainman.TipUnpublished());\n    const node::TipSnapshot before{chainman.PublishedTip()};\n    std::future<node::TipSnapshot> read;\n    std::future_status status;\n    {\n        LOCK(::cs_main);\n        read = std::async(std::launch::async, [&chainman] { return chainman.PublishedTip(); });\n        // Generous: it can only expire if the read waits for the lock this thread holds, which is released\n        // before the future is waited for again, so a failure cannot hang.\n        status = read.wait_for(std::chrono::seconds{60});\n    }\n    BOOST_REQUIRE(status == std::future_status::ready);\n    const node::TipSnapshot seen{read.get()};\n    BOOST_CHECK(seen.hash == before.hash);\n    BOOST_CHECK_EQUAL(seen.sequence, before.sequence);\n}\n\nBOOST_AUTO_TEST_CASE(block_facts_are_one_copy)\n{\n    ChainstateManager& chainman{*Assert(m_node.chainman)};\n    LOCK(::cs_main);\n    const CBlockIndex* tip{chainman.ActiveTip()};\n    BOOST_REQUIRE(tip);\n\n    BOOST_CHECK(!chainman.m_blockman.LookupBlockFacts(uint256::ONE));\n\n    const auto facts{chainman.m_blockman.LookupBlockFacts(tip->GetBlockHash())};\n    BOOST_REQUIRE(facts);\n    BOOST_CHECK_EQUAL(facts->height, tip->nHeight);\n    BOOST_CHECK_EQUAL(facts->status, tip->nStatus);\n    BOOST_CHECK_EQUAL(facts->tx_count, tip->nTx);\n    BOOST_CHECK(facts->HaveData());\n    BOOST_CHECK(facts->data_pos == tip->GetBlockPos());\n}\n\nBOOST_AUTO_TEST_SUITE_END()",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · d1213c8cc37b..65380388ffcc

2026-11-24T20:43:45Z · gpt-6-luna

fork#42The mempool wait-rule registration lacks integration coveragesrc/txmempool.cppunclear
Assessment

The supplied new-head diff shows the lock registration is now named and provides an identifiable diagnostic, but it contains no new test excerpt demonstrating the requested `DEBUG_LOCKORDER` integration case holding `m_node.mempool->cs`.

path_diff: src/txmempool.cpp

[
  {
    "evidence_id": "3153289fe96e4086adb3f4107ad49ac4",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "65380388ffcc175520da5aef26a031e6019b5444",
    "old_head": "d1213c8cc37b4fbe929e3ffdb15d9b40a2378e23",
    "path": "src/txmempool.cpp",
    "source_generation": 2,
    "source_job_id": 2979,
    "text": "diff --git a/src/txmempool.cpp b/src/txmempool.cpp\nindex bf8768d72c..5fc7b27e17 100644\n--- a/src/txmempool.cpp\n+++ b/src/txmempool.cpp\n@@ -177,7 +177,7 @@ CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)\n     : m_opts{Flatten(std::move(opts), error)}\n {\n     // Signal callbacks take the mempool's lock, so nothing may wait for them while holding it.\n-    NO_WAIT_LOCK(cs);\n+    RegisterNoWaitLock(\"CTxMemPool::cs\", &cs);\n     m_txgraph = MakeTxGraph(\n         /*max_cluster_count=*/m_opts.limits.cluster_count,\n         /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · d1213c8cc37b..65380388ffcc

2026-11-24T20:43:45Z · gpt-6-luna

fork#42The O7 assertion documentation is unfinishedsrc/validation.hpartially_addressed
Assessment

O7 now names `ConnectTip()` and `DisconnectTip()` as the locations checking stored/connected block state, and the trailing fragment is gone. But it still does not name the senders’ `cs_main` assertions or clarify that these checks do not themselves assert queue order; the O7 reference remains attached to the queue-order statement without distinguishing those guarantees.

path_diff: src/validation.h; new_source: src/validation.h

[
  {
    "evidence_id": "87736e604a554efdb30b0a9e6f6e97b2",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "65380388ffcc175520da5aef26a031e6019b5444",
    "old_head": "d1213c8cc37b4fbe929e3ffdb15d9b40a2378e23",
    "path": "src/validation.h",
    "source_generation": 2,
    "source_job_id": 2979,
    "text": "diff --git a/src/validation.h b/src/validation.h\nindex 3b1ca20f27..d564e31759 100644\n--- a/src/validation.h\n+++ b/src/validation.h\n@@ -535,8 +535,9 @@ struct DeploymentFlags {\n  *      with O8's condition for the coins, which covers a write-out that\n  *      failed inside ConnectTip() or DisconnectTip().\n  *  O7  Signals are queued under cs_main in the order of connection, and\n- *      what they name is stored and connected. Asserted in part. That the\n- *      block is stored and is the tip, or has left the chain, is checked\n+ *      what they name is stored and connected. Asserted in part: that the\n+ *      block is stored and is the tip, or has left the chain, is checked in\n+ *      ConnectTip() and DisconnectTip().\n  *  O8  A flush never sees a half-applied block: the coins' best block is\n  *      the tip, its parent (inside DisconnectTip(), which writes before the\n  *      tip moves), or the one block on top of the tip that is being\n@@ -545,8 +546,12 @@ struct DeploymentFlags {\n  *  O9  Connection is strictly sequential: a block is connected on top of\n  *      the tip, one ActivateBestChain() at a time. ConnectTip() asserts\n  *      the first; the second is m_chainstate_mutex.\n- *  O10 nSequenceId is assigned in arrival order, in\n- *      ReceivedBlockTransactions() under cs_main.\n+ *  O10 nSequenceId is assigned under cs_main when a block becomes linked\n+ *      (ReceivedBlockTransactions()): its data and every ancestor's\n+ *      transaction count are known. A block stored before its parent waits,\n+ *      and is numbered with the descendants the link reaches, parent first;\n+ *      so the order may differ from the order of arrival. Blocks loaded at\n+ *      startup and preciousblock assign it otherwise.\n  *  O11 A file position copied under cs_main stays readable afterwards, or\n  *      the reader handles the failed read (node::BlockFacts).\n  *  O12 The block index invariants hold whenever cs_main is free.\n@@ -637,6 +642,9 @@ struct ConnectBlockResult {\n  * the script execution cache takes the results of the checks that run inline,\n  * and the view's best block is left untouched.\n  *\n+ * The view's coins are changed with `just_check` too, and on failure the view may be partially updated and\n+ * `result.undo` is incomplete: a caller that keeps the view only on success passes one it can discard.\n+ *\n  * The caller needs exclusive use of `block` for the call: CheckBlock() records\n  * its results in the block's mutable fields. The node's callers hold cs_main.\n  */\n",
    "truncated": false,
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 658,
    "evidence_id": "8592051bd27349379c445828351d9cff",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 509,
    "new_head": "65380388ffcc175520da5aef26a031e6019b5444",
    "old_head": "d1213c8cc37b4fbe929e3ffdb15d9b40a2378e23",
    "path": "src/validation.h",
    "revision": "65380388ffcc175520da5aef26a031e6019b5444",
    "source_generation": 2,
    "source_job_id": 2979,
    "text": " * Processing one block at a time under cs_main gives the rest of the node\n * guarantees that no type or annotation states. They are listed here, and\n * the code that relies on one says so with its number. Where the condition\n * can be tested it is asserted (Assume, so that a debug build stops and a\n * release build goes on as before).\n *\n *  O1  The only half-processed state a block can be seen in is \"stored, not\n *      yet activated\", and calling ActivateBestChain() closes it.\n *      ProcessNewBlock() opens it; ProcessGetBlockData() and the GETBLOCKS\n *      handler in net_processing close it before they answer.\n *  O2  When AcceptBlock() returns for a new block, its data, its position\n *      and BLOCK_VALID_TRANSACTIONS are recorded together. Asserted there,\n *      as the postcondition of ReceivedBlockTransactions().\n *  O3  BlockChecked is delivered under cs_main before the tip moves: the\n *      order of the statements in ConnectTip(), with O9's assertion above.\n *  O4  NewPoWValidBlock is delivered under cs_main before the block is\n *      written, and only for a block on top of the tip. Not asserted: both\n *      conditions are the control flow of AcceptBlock().\n *  O5  Message processing requests only blocks that are not stored, and\n *      a block is \"received, not stored\" only inside the handling of the\n *      one message that delivers it: BLOCK, or the BLOCKTXN or CMPCTBLOCK\n *      that completes a compact block (O13). Not asserted: the\n *      getblockfrompeer RPC checks and requests in two holds of cs_main\n *      and may request a stored block.\n *  O6  The tip is the fully connected frontier: its coins are in the tip\n *      view and its transaction counts are known. Asserted in PublishTip(),\n *      with O8's condition for the coins, which covers a write-out that\n *      failed inside ConnectTip() or DisconnectTip().\n *  O7  Signals are queued under cs_main in the order of connection, and\n *      what they name is stored and connected. Asserted in part: that the\n *      block is stored and is the tip, or has left the chain, is checked in\n *      ConnectTip() and DisconnectTip().\n *  O8  A flush never sees a half-applied block: the coins' best block is\n *      the tip, its parent (inside DisconnectTip(), which writes before the\n *      tip moves), or the one block on top of the tip that is being\n *      connected, or was when a write-out failed. Asserted in\n *      FlushStateToDisk().\n *  O9  Connection is strictly sequential: a block is connected on top of\n *      the tip, one ActivateBestChain() at a time. ConnectTip() asserts\n *      the first; the second is m_chainstate_mutex.\n *  O10 nSequenceId is assigned under cs_main when a block becomes linked\n *      (ReceivedBlockTransactions()): its data and every ancestor's\n *      transaction count are known. A block stored before its parent waits,\n *      and is numbered with the descendants the link reaches, parent first;\n *      so the order may differ from the order of arrival. Blocks loaded at\n *      startup and preciousblock assign it otherwise.\n *  O11 A file position copied under cs_main stays readable afterwards, or\n *      the reader handles the failed read (node::BlockFacts).\n *  O12 The block index invariants hold whenever cs_main is free.\n *      CheckBlockIndex() checks them.\n *  O13 Messages are processed on one thread, so a block request may be\n *      removed before the block is stored and no message asks for the\n *      block again in between. Asserted at the BLOCK message and in\n *      ProcessCompactBlockTxns().\n *  O14 InvalidateBlock() tolerates blocks arriving between its lock drops,\n *      by going over the block index again at its end.\n *  O15 The tip does not move while a block template or proposal is\n *      checked: TestBlockValidity() runs under cs_main.\n */\n\n/**\n * Everything a block validation function needs from the node besides the\n * block itself and the coins view. The node builds one under cs_main from\n * configuration and the header chain; the validation functions read it and\n * touch no other node state, so they can be called and tested without a\n * ChainstateManager. The contextual header and block checks also take the\n * previous block index entry, for the difficulty calculation.\n *\n * Every member is a copy, with two exceptions: params refers to the chain's\n * constant parameters, and median_time_past_at is a function, because which\n * ancestors a block's relative lock times refer to is known only once its\n * inputs are looked up.\n */\nstruct BlockValidationContext {\n    const Consensus::Params& params;\n    //! Clock reading used for the future-timestamp check of the header.\n    NodeClock::time_point now;\n    DeploymentFlags deployments;\n    //! Script flags to enforce for this block, see GetBlockScriptFlags().\n    script_verify_flags script_flags;\n    //! Whether to verify input scripts at all. False only under -assumevalid.\n    bool check_scripts{true};\n    //! The block's hash.\n    uint256 block_hash;\n    //! Hash of the previous block index entry; null for the genesis block. The\n    //! coins view must be at this block.\n    uint256 prev_block_hash;\n    //! The block's height.\n    int height{0};\n    //! Median time past of the previous block; 0 for the genesis block.\n    int64_t prev_median_time_past{0};\n    //! Whether the block is checked for BIP30, see EnforceBIP30().\n    bool enforce_bip30{true};\n    /**\n     * Median time past of the block's ancestor at a height below the block's\n     * own (BIP68 measures a time lock from the block before the spent coin's).\n     * The node's implementation reads only what the hold of cs_main that\n     * creates or loads an index entry writes and nothing writes after, so it\n     * may be called without cs_main for as long as the block index lives.\n     */\n    std::function<int64_t(int)> median_time_past_at;\n};\n\n/** Outputs of the pure ConnectBlock() besides the mutated coins view.\n *  ConnectBlock() resets the object it is given before it fills it. */\nstruct ConnectBlockResult {\n    //! Undo data for the connected block; partially filled when connection failed.\n    CBlockUndo undo;\n    int num_inputs{0};\n    int64_t sigops_cost{0};\n    //! True when the block failed CheckBlock() before any UTXO work was done.\n    bool failed_in_check_block{false};\n    //! Phase boundaries, for the caller's bench logging.\n    SteadyClock::time_point time_start{};\n    SteadyClock::time_point time_checked{};\n    SteadyClock::time_point time_forks{};\n    SteadyClock::time_point time_connected{};\n    SteadyClock::time_point time_verified{};\n};\n\n/**\n * Apply `block` to `view`, checking every consensus rule that needs the UTXO\n * set. Pure apart from the view and from what it is handed to use: it reads\n * node state only through the context's callbacks (median_time_past_at),\n * reads and updates the script execution cache, erases the entries of the\n * signature cache that its script checks hit (as on master: a block's\n * signatures are not looked up twice), reads the steady clock for its\n * timings, writes nothing to disk and logs nothing itself (CheckBlock() does,\n * in a debug category, where a signet block's solution fails).\n *\n * Script checks run on `check_queue` when it is non-null and has worker\n * threads, otherwise inline; they are skipped when `ctx.check_scripts` is\n * false. With `just_check` the block's PoW and merkle root are not rechecked,\n * the script execution cache takes the results of the checks that run inline,\n * and the view's best block is left untouched.\n *\n * The view's coins are changed with `just_check` too, and on failure the view may be partially updated and\n * `result.undo` is incomplete: a caller that keeps the view only on success passes one it can discard.\n *\n * The caller needs exclusive use of `block` for the call: CheckBlock() records\n * its results in the block's mutable fields. The node's callers hold cs_main.\n */\nbool ConnectBlock(const CBlock& block, const BlockValidationContext& ctx,\n                  CCoinsViewCache& view, CCheckQueue<CScriptCheck>* check_queue,\n                  ValidationCache& validation_cache, bool just_check,\n                  BlockValidationState& state, ConnectBlockResult& result);\n\nstruct ConnectedBlock;\n\n/**",
    "repository_id": "fork",
    "repository": "willcl-ark/bitcoin",
    "repository_url": "https://github.com/willcl-ark/bitcoin"
  }
]

Source report · d1213c8cc37b..65380388ffcc

2026-11-24T20:43:45Z · gpt-6-luna

Conceptual concerns

The archaeology pass can complete without publishing a concern. Published conceptual concerns are tracked separately from code findings.

22 saved reviews completed archaeology research; 1 saved and 1 published a conceptual concern.

StatusReviews
drop3
no_concern16
unresolved2
verified1

Median citations: 2.0; median alternatives: 0.0.