Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
I would have expected rescanning to be I/O bound rather than CPU, in which case parallelization could make things worse (more random seeking). Have you benchmarked this on a non-SSD? |
Fast rescan checks block filters, which involves considerable hashing. This PR parallelises the checking of block filters, and my benchmarks show considerable improvements in rescan speeds with block filters. Slow rescan, which is I/O bound, remains the same. I expect the speedup to be transferable to non-SSD machines, but I haven't benchmarked this. |
|
#33689 has been merged; the cherry-picked Threadpool commit has been removed. |
furszy
left a comment
There was a problem hiding this comment.
I like the PR conceptually but I think it would be nice to first improve the current scanning code structure, then land the parallelization feature. The current code mixes a lot responsibilities.
Similar to what you did in 633531614f69de49733642fd19cc9eba830fbdea, but into a separate PR so we can first land some good building blocks for this to happen.
Some quick pseudo-code structuring how I imagine it, which is similar to yours:
Scan(wallet, start_block_hash, end_block_hash, fn_filter_block, fn_process_block, interrupt) {
it_current_hash = start_block_hash;
while (it_current_hash != end_block_hash || interrupt) {
// Skip block if needed (this function contains the BlockFilterIndex check if enabled)
if (fn_filter_block(it_current_hash)) continue;
// (this is more or less how we currently do it, we fetch the block and the next block hash at the same time)
block = chain.find_block(it_current_hash).next_block(it_current_hash);
// (inside this function the wallet will digest the block update the filter and save progress if needed)
fn_process_block(block);
}
}
|
Concept ACK |
I moved the test change into #34667 and the |
|
We replaced the previous implementation with a much simpler sliding-window implementation. New benchmark results are in #34400 (comment). |
There was a problem hiding this comment.
reviewed 15fa337
will review the other 4 commits tomorrow :)
| wallet->m_wallet_par += GetNumCores(); | ||
| } | ||
| // The calling thread counts towards -walletpar, as for -par. | ||
| wallet->m_wallet_par = std::clamp(wallet->m_wallet_par, 1, MAX_WALLETPAR + 1); |
There was a problem hiding this comment.
in 15fa337 wallet: add -walletpar option
Maybe we should just throw here if m_wallet_par is negative? I think we should require -walletpar to be bigger than -GetNumCores() and smaller than GetNumCores() + 1.
Also GetIntArg returns an int64 while m_wallet_par is a normal int you can overflow the integers and trick a bit the result. This obviously is weird and not critic, but I think is worth addressing as is easy to fix:
$ git diff
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index b1b9f52919..56e106afb5 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -2930,14 +2930,14 @@ bool CWallet::LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContex
wallet->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
wallet->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
- wallet->m_wallet_par = args.GetIntArg("-walletpar", DEFAULT_WALLETPAR);
- if (wallet->m_wallet_par <= 0) {
+ int64_t wallet_par = args.GetIntArg("-walletpar", DEFAULT_WALLETPAR);
+ if (wallet_par <= 0) {
// '0' means 'autodetect'
// '<0' means leave that many cores free
- wallet->m_wallet_par += GetNumCores();
+ wallet_par += GetNumCores();
}
// The calling thread counts towards -walletpar, as for -par.
- wallet->m_wallet_par = std::clamp(wallet->m_wallet_par, 1, MAX_WALLETPAR + 1);
+ wallet->m_wallet_par = static_cast<int>(std::clamp<int64_t>(wallet_par, 1, MAX_WALLETPAR + 1));
return true;
}
There was a problem hiding this comment.
I've fixed the overflow issue, but the code still doesn't throw. I'm not convinced we need to throw here. I think silently using the maximum or minimum number of threads is good enough, rather than forcing the user to enter the correct num cores.
polespinasa
left a comment
There was a problem hiding this comment.
reviewed db2d769
I've just reviewed code, I've skipped tests.
There are a few ralph comments that I would say they are worth addressing. Specially in commit 5441a57 where there are some edge cases that can make the rescan skip payments.
I couldn't personally find anything else wrong in the behavior of 5441a57, and my LLM scan found the same as Ralph.
|
CI failure seems unrelated. See #36913 |
polespinasa
left a comment
There was a problem hiding this comment.
I am close to acking it :)
reviewed cdbdfd8
There are some Ralph comments interesting to address.
For example the one regarding Reorg tests miss disconnection between lookup and transaction sync.
Maybe something like, the diff below would do the job. (The test is ai so may have some errors, but just to give an idea)
It fails in master and passes on top of commit1.
test diff
$ git diff
diff --git a/src/wallet/test/rescan_tests.cpp b/src/wallet/test/rescan_tests.cpp
index fc1b61c1e1..4df0214be0 100644
--- a/src/wallet/test/rescan_tests.cpp
+++ b/src/wallet/test/rescan_tests.cpp
@@ -6,6 +6,7 @@
#include <chain.h>
#include <index/blockfilterindex.h>
#include <interfaces/chain.h>
+#include <interfaces/handler.h>
#include <node/blockstorage.h>
#include <node/context.h>
#include <test/util/common.h>
@@ -261,6 +262,74 @@ BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorged_block, TestChain100
StopIndex(filter_index, m_node);
}
+BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorg_during_scan, TestChain100Setup)
+{
+ BlockFilterIndex& filter_index{*m_node.block_filter_indexes.emplace_back(
+ node::MakeIndex<BlockFilterIndex>(interfaces::MakeChain(m_node), BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true))};
+ BOOST_REQUIRE(filter_index.Init());
+ filter_index.Sync();
+ BOOST_REQUIRE(filter_index.BlockUntilSyncedToCurrentChain());
+
+ CBlockIndex* stale_block = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
+ BOOST_REQUIRE_EQUAL(stale_block->nHeight, 100);
+ const uint256 stale_hash{stale_block->GetBlockHash()};
+ const CBlockIndex* start_block{stale_block->pprev};
+ const auto& coinbase{m_coinbase_txns.back()};
+ auto wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
+ {
+ LOCK(wallet->cs_wallet);
+ wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
+ wallet->SetLastBlockProcessed(stale_block->nHeight, stale_hash);
+ }
+ AddKey(*wallet, coinbaseKey);
+ WalletRescanReserver reserver(*wallet);
+ BOOST_REQUIRE(reserver.reserve());
+ const ScanResult initial_result = wallet->Scanner().Scan(stale_hash, stale_block->nHeight,
+ /*max_height=*/stale_block->nHeight, reserver, /*save_progress=*/false);
+ BOOST_REQUIRE_EQUAL(initial_result.status, ScanResult::SUCCESS);
+ {
+ LOCK(wallet->cs_wallet);
+ BOOST_REQUIRE(wallet->mapWallet.at(coinbase->GetHash()).isConfirmed());
+ }
+ auto notifications = wallet->chain().handleNotifications(wallet);
+
+ // Scanning heights 99-100 emits its only intermediate progress update at
+ // height 100, after looking up its successor but before syncing its txs.
+ // Deliver the disconnect notification in that window: the earlier activity
+ // check must not allow the rescan to confirm the coinbase again afterwards.
+ bool disconnected{false};
+ auto progress_handler = wallet->ShowProgress.connect([&](const std::string&, int progress) {
+ if (progress == 0 || progress == 100 || disconnected) return;
+ disconnected = true;
+ BlockValidationState state;
+ BOOST_REQUIRE(m_node.chainman->ActiveChainstate().InvalidateBlock(state, stale_block));
+ wallet->chain().waitForNotifications();
+ LOCK(wallet->cs_wallet);
+ BOOST_REQUIRE_EQUAL(wallet->GetLastBlockHash(), start_block->GetBlockHash());
+ BOOST_REQUIRE(wallet->mapWallet.at(coinbase->GetHash()).isAbandoned());
+ });
+
+ const ScanResult result = wallet->Scanner().Scan(start_block->GetBlockHash(), start_block->nHeight,
+ /*max_height=*/stale_block->nHeight, reserver, /*save_progress=*/false);
+ progress_handler.disconnect();
+ notifications->disconnect();
+ wallet->chain().waitForNotifications();
+
+ BOOST_REQUIRE(disconnected);
+ BOOST_CHECK_EQUAL(result.status, ScanResult::FAILURE);
+ BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
+ BOOST_CHECK_EQUAL(result.last_scanned_block, start_block->GetBlockHash());
+ BOOST_REQUIRE(result.last_scanned_height);
+ BOOST_CHECK_EQUAL(*result.last_scanned_height, start_block->nHeight);
+ {
+ LOCK(wallet->cs_wallet);
+ BOOST_CHECK(!wallet->mapWallet.at(coinbase->GetHash()).isConfirmed());
+ BOOST_CHECK(wallet->mapWallet.at(coinbase->GetHash()).isAbandoned());
+ }
+
+ StopIndex(filter_index, m_node);
+}
+
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_abort, TestChain100Setup)
{
CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
Checking inActiveChain before reading the block left a window where the block could be disconnected and its blockDisconnected notification handled before its transactions were synced as confirmed. Checking with cs_wallet held closes it, since that notification needs cs_wallet.
Move the filtering in ShouldFetchBlock into NextBlocksSerial, which returns the blocks to scan, and keep per-scan state in a ScanContext. This prepares for parallel filter checks. No behaviour change, except that if the wallet's tip moves past the last processed block after the lookup of its successor found none, the successor is looked up again instead of ending the scan.
Number of threads for wallet operations, to be used by parallel fast rescan. As for -par, the calling thread counts towards it, 0 auto-detects, a negative value leaves that many cores free, and at most MAX_WALLETPAR (15) dedicated threads are used.
With -walletpar > 1, fast rescan checks block filters on a thread pool. Blocks are read in windows, checked in tasks of BLOCKS_PER_FILTER_TASK blocks queued ahead of delivery, and delivered in block order, so workers keep checking while the scan thread scans matched blocks. On a keypool top-up, in-flight checks are drained and undelivered NoMatch verdicts are re-checked against only the new scripts. Read-ahead is wasted work then, so the window shrinks on every top-up and grows while there are none.
Parallel filter checks would compete with block validation for cores.
Run the filter-dependent scan tests with -walletpar 1 and 4, and check that the wallet loading rescan takes the parallel path.
Parallel fast rescan is now the default, so pin the existing fast rescans to -walletpar=1 and add the same rescans with -walletpar=4.
|
Sorry for the noise.
The test you suggested works; I added it and fixed the following issues raised by Ralph:
and I added a release note for -walletpar |

This PR speeds up wallet fast-rescan by executing the filter checks in parallel while ensuring that the filters are updated properly so that no output scripts are missed. Benchmarks, outlined below, show considerable improvement that slows down around
8threads.Prerequisite PRs
CWallet::ScanForWalletTransactionsto prepare for the work in this PR.Benchmarks
Prepare
pyperf system tune.blockfilterindex=1in your bitcoin.conf file and sync your node to the tip.chain.isInitialBlockDownload()istrue. Ensure your node is synced before shutting down and running the mainnet benchmark commands.Using the following command on mainnet with a wallet with no scripts and hyperfine version
1.20.0:Table 1 was obtained on a machine with the following specifications
Table 1. Table of results of a mainnet benchmark of scanning 200,000 blocks on a wallet with no scripts. An empty wallet is not representative of a typical wallet; the next benchmark tries to simulate more "interesting" scenarios.
This Python script patch python script creates custom chains designed with payments at specified intervals to observe the performance of parallel fast rescan.
Fig 1 shown below was produced using this patch on a machine with the following specifications
Fig 1. Time to scan a 2000-block chain on Regtest with payments at varying intervals, comparing parallel Fast Rescan against serial Fast Rescan (baseline). These benchmarks use the -walletpar commit as a baseline instead of master, since master lacks the
-walletparconfig parameter. All materials for this custom benchmark are available here.