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 ConflictsNo conflicts as of last run. |
|
@w0xlt can you rebase this? |
There was a problem hiding this comment.
I might have gone a bit overboard again, I left comments documenting my review journey, please see the individual explanations - feel free to pick and choose between them.
For convenience here's my local patch against your rebased branch:
Local pending changes
diff --git a/src/bench/wallet_balance.cpp b/src/bench/wallet_balance.cpp
index ee8244501a..7ce15529d6 100644
--- a/src/bench/wallet_balance.cpp
+++ b/src/bench/wallet_balance.cpp
@@ -18,6 +18,7 @@
#include <wallet/wallet.h>
#include <cassert>
+#include <cstddef>
#include <memory>
#include <optional>
#include <string>
@@ -72,15 +73,26 @@ BENCHMARK(WalletBalanceWatch);
static void WalletBalanceManySpent(benchmark::Bench& bench)
{
+ constexpr int NUM_BLOCKS{500};
+ constexpr int OUTPUTS_PER_BLOCK{100};
+ constexpr CAmount OUTPUT_VALUE{50 * COIN / OUTPUTS_PER_BLOCK};
+ constexpr size_t TOTAL_WALLET_OUTPUTS{NUM_BLOCKS * OUTPUTS_PER_BLOCK};
+ constexpr size_t KEEP_UNSPENT{50};
+ constexpr size_t BATCH_SIZE{100};
+ constexpr CAmount FEE{1000};
+ constexpr size_t TXS_PER_BLOCK{10};
+ constexpr int FILLER_OUTPUTS{1};
+ constexpr CAmount FILLER_VALUE{50 * COIN};
+
// Benchmark GetBalance with many spent TXOs and few unspent TXOs.
// This scenario benefits from optimizations that separate definitely-spent
// outputs from potentially-spendable ones (such as m_unusable_txos).
//
- // Target: ~50,000 spent TXOs, ~50 unspent TXOs
+ // Target: many spent TXOs, few unspent TXOs
const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
const auto& params = test_setup->m_node.chainman->GetParams();
- SetMockTime(params.GenesisBlock().nTime);
+ NodeClockContext clock_ctx{params.GenesisBlock().Time()};
CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockableWalletDatabase()};
{
LOCK(wallet.cs_wallet);
@@ -91,55 +103,51 @@ static void WalletBalanceManySpent(benchmark::Bench& bench)
const auto dest = getNewDestination(wallet, OutputType::BECH32);
const CScript wallet_script = GetScriptForDestination(dest);
- // Burn script for outputs we don't want in the wallet
+ // OP_TRUE keeps the output spendable without adding it to the wallet
const CScript burn_script{CScript() << OP_TRUE};
- // Phase 1: Create many UTXOs (100 outputs per block * 500 blocks = 50,000 TXOs)
- constexpr int NUM_BLOCKS = 500;
- constexpr int OUTPUTS_PER_BLOCK = 100;
- constexpr CAmount OUTPUT_VALUE = 50 * COIN / OUTPUTS_PER_BLOCK;
-
+ // Phase 1: Create the configured wallet-owned output history
for (int i = 0; i < NUM_BLOCKS; ++i) {
GenerateFakeBlock(params, test_setup->m_node, wallet, wallet_script, OUTPUTS_PER_BLOCK);
}
// Phase 2: Add COINBASE_MATURITY blocks to mature all coinbase outputs
- // This ensures all 50,000 TXOs are spendable
for (int i = 0; i < COINBASE_MATURITY; ++i) {
- GenerateFakeBlock(params, test_setup->m_node, wallet, burn_script, 1);
+ GenerateFakeBlock(params, test_setup->m_node, wallet, burn_script, FILLER_OUTPUTS);
}
// Phase 3: Spend most UTXOs by creating spending transactions
// Get all available coins and spend them in batches
std::vector<COutPoint> outputs_to_spend;
+ outputs_to_spend.reserve(TOTAL_WALLET_OUTPUTS);
{
LOCK(wallet.cs_wallet);
- auto available = AvailableCoins(wallet);
- for (const auto& coin : available.All()) {
- outputs_to_spend.push_back(coin.outpoint);
+ for (const auto& [_, coins] : AvailableCoins(wallet).coins) {
+ for (const auto& coin : coins) {
+ outputs_to_spend.push_back(coin.outpoint);
+ }
}
}
- // Keep ~50 outputs unspent, spend the rest
- constexpr int KEEP_UNSPENT = 50;
- int num_to_spend = std::max(0, static_cast<int>(outputs_to_spend.size()) - KEEP_UNSPENT);
+ // Keep the configured small remainder unspent, and spend the rest
+ assert(outputs_to_spend.size() == TOTAL_WALLET_OUTPUTS);
+ const size_t num_to_spend{outputs_to_spend.size() - KEEP_UNSPENT};
- // Create spending transactions in batches of 100 inputs each
- constexpr int BATCH_SIZE = 100;
- constexpr CAmount BENCHMARK_FEE = 1000;
+ // Create spending transactions in configured-size batches
std::vector<CTransactionRef> spending_txs;
- for (int i = 0; i < num_to_spend; i += BATCH_SIZE) {
+ for (size_t i{0}; i < num_to_spend; i += BATCH_SIZE) {
CMutableTransaction spend_tx;
- int batch_end = std::min(i + BATCH_SIZE, num_to_spend);
+ const size_t batch_end{std::min(i + BATCH_SIZE, num_to_spend)};
- for (int j = i; j < batch_end; ++j) {
+ CAmount total_value{0};
+ for (size_t j{i}; j < batch_end; ++j) {
spend_tx.vin.emplace_back(outputs_to_spend[j]);
+ total_value += OUTPUT_VALUE;
}
// Send to burn script so consolidation outputs don't add to wallet TXOs
- CAmount total_value = (batch_end - i) * OUTPUT_VALUE;
- spend_tx.vout.emplace_back(total_value - BENCHMARK_FEE, burn_script);
+ spend_tx.vout.emplace_back(total_value - FEE, burn_script);
spending_txs.push_back(MakeTransactionRef(std::move(spend_tx)));
}
@@ -147,22 +155,33 @@ static void WalletBalanceManySpent(benchmark::Bench& bench)
// Phase 4: Confirm all spending transactions in new blocks
// Include multiple spending txs per block for efficiency
// Coinbase outputs go to burn script to avoid adding wallet TXOs
- constexpr int TXS_PER_BLOCK = 10;
- for (size_t i = 0; i < spending_txs.size(); i += TXS_PER_BLOCK) {
- std::vector<CTransactionRef> block_txs;
- for (size_t j = i; j < std::min(i + TXS_PER_BLOCK, spending_txs.size()); ++j) {
- block_txs.push_back(spending_txs[j]);
+ for (size_t i{0}; i < spending_txs.size(); i += TXS_PER_BLOCK) {
+ const size_t batch_end{std::min(i + TXS_PER_BLOCK, spending_txs.size())};
+ std::vector<CTransactionRef> block_txs{spending_txs.begin() + i, spending_txs.begin() + batch_end};
+ GenerateFakeBlock(params, test_setup->m_node, wallet, burn_script, FILLER_OUTPUTS, FILLER_VALUE, block_txs);
+ }
+
+ // Balance alone does not prove that spent wallet outputs remain in history.
+ size_t owned_outputs{0}, spent_outputs{0};
+ {
+ LOCK(wallet.cs_wallet);
+ for (const auto& [outpoint, _] : wallet.GetTXOs()) {
+ ++owned_outputs;
+ spent_outputs += wallet.IsSpent(outpoint);
}
- GenerateFakeBlock(params, test_setup->m_node, wallet, burn_script, 1, 50 * COIN, block_txs);
}
+ assert(owned_outputs == TOTAL_WALLET_OUTPUTS);
+ assert(spent_outputs == TOTAL_WALLET_OUTPUTS - KEEP_UNSPENT);
- // Phase 5: Run the benchmark
- auto bal = GetBalance(wallet); // Cache
+ CAmount expected_balance{0};
+ for (size_t i{0}; i < KEEP_UNSPENT; ++i) {
+ expected_balance += OUTPUT_VALUE;
+ }
- bench.run([&] {
- wallet.MarkDirty();
- bal = GetBalance(wallet);
- assert(bal.m_mine_trusted > 0);
+ bench.minEpochIterations(10).run([&] {
+ const auto bal{GetBalance(wallet)};
+ assert(bal.m_mine_trusted == expected_balance);
+ assert(bal.m_mine_immature == 0);
});
}
diff --git a/src/bench/wallet_bench_util.h b/src/bench/wallet_bench_util.h
index 7c7ebbb1d5..edc1bc15e3 100644
--- a/src/bench/wallet_bench_util.h
+++ b/src/bench/wallet_bench_util.h
@@ -19,20 +19,26 @@
#include <versionbits.h>
#include <wallet/wallet.h>
+#include <vector>
+
namespace wallet {
struct TipBlock
{
- uint256 prev_block_hash;
- int64_t prev_block_time;
- int tip_height;
+ uint256 prev_block_hash{};
+ int64_t prev_block_time{0};
+ int tip_height{0};
};
inline TipBlock GetTip(const CChainParams& params, const node::NodeContext& context)
{
- auto tip = WITH_LOCK(::cs_main, return context.chainman->ActiveTip());
- return (tip) ? TipBlock{tip->GetBlockHash(), tip->GetBlockTime(), tip->nHeight} :
- TipBlock{params.GenesisBlock().GetHash(), params.GenesisBlock().GetBlockTime(), 0};
+ {
+ LOCK(::cs_main);
+ if (const auto* tip{context.chainman->ActiveTip()}) {
+ return {tip->GetBlockHash(), tip->GetBlockTime(), tip->nHeight};
+ }
+ }
+ return {params.GenesisBlock().GetHash(), params.GenesisBlock().GetBlockTime(), 0};
}
/**
@@ -42,9 +48,7 @@ inline TipBlock GetTip(const CChainParams& params, const node::NodeContext& cont
inline void GenerateFakeBlock(const CChainParams& params,
const node::NodeContext& context,
CWallet& wallet,
- const CScript& coinbase_script,
- int num_coinbase_outputs,
- CAmount total_coinbase_value = 50 * COIN,
+ const std::vector<CTxOut>& coinbase_outputs,
const std::vector<CTransactionRef>& extra_txs = {})
{
TipBlock tip{GetTip(params, context)};
@@ -54,19 +58,11 @@ inline void GenerateFakeBlock(const CChainParams& params,
coinbase_tx.vin.resize(1);
coinbase_tx.vin[0].prevout.SetNull();
coinbase_tx.vin[0].scriptSig = CScript() << ++tip.tip_height << OP_0;
-
- // Create coinbase outputs
- CAmount per_output = total_coinbase_value / num_coinbase_outputs;
- for (int i = 0; i < num_coinbase_outputs; ++i) {
- coinbase_tx.vout.emplace_back(per_output, coinbase_script);
- }
+ coinbase_tx.vout = coinbase_outputs;
block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
- // Add any extra transactions
- for (const auto& tx : extra_txs) {
- block.vtx.push_back(tx);
- }
+ block.vtx.insert(block.vtx.end(), extra_txs.begin(), extra_txs.end());
block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;
block.hashPrevBlock = tip.prev_block_hash;
@@ -75,16 +71,33 @@ inline void GenerateFakeBlock(const CChainParams& params,
block.nBits = params.GenesisBlock().nBits;
block.nNonce = 0;
+ CBlockIndex* pindex{nullptr};
{
LOCK(::cs_main);
- CBlockIndex* pindex{context.chainman->m_blockman.AddToBlockIndex(block, context.chainman->m_best_header)};
+ pindex = context.chainman->m_blockman.AddToBlockIndex(block, context.chainman->m_best_header);
context.chainman->ActiveChain().SetTip(*pindex);
}
- const auto* pindex = WITH_LOCK(::cs_main, return context.chainman->ActiveChain().Tip());
wallet.blockConnected(kernel::ChainstateRole{}, kernel::MakeBlockInfo(pindex, &block));
}
+inline void GenerateFakeBlock(const CChainParams& params,
+ const node::NodeContext& context,
+ CWallet& wallet,
+ const CScript& coinbase_script,
+ int num_coinbase_outputs,
+ CAmount total_coinbase_value = 50 * COIN,
+ const std::vector<CTransactionRef>& extra_txs = {})
+{
+ std::vector<CTxOut> coinbase_outputs;
+ coinbase_outputs.reserve(num_coinbase_outputs);
+ const CAmount per_output{total_coinbase_value / num_coinbase_outputs};
+ for (int i{0}; i < num_coinbase_outputs; ++i) {
+ coinbase_outputs.emplace_back(per_output, coinbase_script);
+ }
+ GenerateFakeBlock(params, context, wallet, coinbase_outputs, extra_txs);
+}
+
} // namespace wallet
#endif // BITCOIN_BENCH_WALLET_BENCH_UTIL_H
diff --git a/src/bench/wallet_create_tx.cpp b/src/bench/wallet_create_tx.cpp
index 11125e26fe..309c950671 100644
--- a/src/bench/wallet_create_tx.cpp
+++ b/src/bench/wallet_create_tx.cpp
@@ -4,28 +4,20 @@
#include <addresstype.h>
#include <bench/bench.h>
-#include <chain.h>
+#include <bench/wallet_bench_util.h>
#include <chainparams.h>
#include <consensus/amount.h>
#include <consensus/consensus.h>
-#include <consensus/merkle.h>
#include <interfaces/chain.h>
-#include <kernel/chain.h>
-#include <kernel/types.h>
-#include <node/blockstorage.h>
#include <outputtype.h>
#include <policy/feerate.h>
-#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <sync.h>
#include <test/util/setup_common.h>
#include <test/util/time.h>
-#include <uint256.h>
#include <util/result.h>
#include <util/time.h>
-#include <validation.h>
-#include <versionbits.h>
#include <wallet/coincontrol.h>
#include <wallet/coinselection.h>
#include <wallet/spend.h>
@@ -41,70 +33,28 @@
#include <utility>
#include <vector>
-using kernel::ChainstateRole;
using wallet::CWallet;
using wallet::CreateMockableWalletDatabase;
using wallet::WALLET_FLAG_DESCRIPTORS;
-struct TipBlock
-{
- uint256 prev_block_hash;
- int64_t prev_block_time;
- int tip_height;
-};
-
-TipBlock getTip(const CChainParams& params, const node::NodeContext& context)
-{
- auto tip = WITH_LOCK(::cs_main, return context.chainman->ActiveTip());
- return (tip) ? TipBlock{tip->GetBlockHash(), tip->GetBlockTime(), tip->nHeight} :
- TipBlock{params.GenesisBlock().GetHash(), params.GenesisBlock().GetBlockTime(), 0};
-}
-
void generateFakeBlock(const CChainParams& params,
const node::NodeContext& context,
CWallet& wallet,
const CScript& coinbase_out_script)
{
- TipBlock tip{getTip(params, context)};
-
- // Create block
- CBlock block;
- CMutableTransaction coinbase_tx;
- coinbase_tx.vin.resize(1);
- coinbase_tx.vin[0].prevout.SetNull();
- coinbase_tx.vout.resize(2);
- coinbase_tx.vout[0].scriptPubKey = coinbase_out_script;
- coinbase_tx.vout[0].nValue = 48 * COIN;
- coinbase_tx.vin[0].scriptSig = CScript() << ++tip.tip_height << OP_0;
- coinbase_tx.vout[1].scriptPubKey = coinbase_out_script; // extra output
- coinbase_tx.vout[1].nValue = 1 * COIN;
+ constexpr int NON_WALLET_OUTPUTS{50};
+ std::vector<CTxOut> coinbase_outputs;
+ coinbase_outputs.reserve(2 + NON_WALLET_OUTPUTS);
+ coinbase_outputs.emplace_back(48 * COIN, coinbase_out_script);
+ coinbase_outputs.emplace_back(1 * COIN, coinbase_out_script);
// Fill the coinbase with outputs that don't belong to the wallet in order to benchmark
// AvailableCoins' behavior with unnecessary TXOs
- for (int i = 0; i < 50; ++i) {
- coinbase_tx.vout.emplace_back(1 * COIN / 50, CScript(OP_TRUE));
- }
-
- block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
-
- block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;
- block.hashPrevBlock = tip.prev_block_hash;
- block.hashMerkleRoot = BlockMerkleRoot(block);
- block.nTime = ++tip.prev_block_time;
- block.nBits = params.GenesisBlock().nBits;
- block.nNonce = 0;
-
- {
- LOCK(::cs_main);
- // Add it to the index
- CBlockIndex* pindex{context.chainman->m_blockman.AddToBlockIndex(block, context.chainman->m_best_header)};
- // add it to the chain
- context.chainman->ActiveChain().SetTip(*pindex);
+ for (int i{0}; i < NON_WALLET_OUTPUTS; ++i) {
+ coinbase_outputs.emplace_back(1 * COIN / NON_WALLET_OUTPUTS, CScript(OP_TRUE));
}
- // notify wallet
- const auto& pindex = WITH_LOCK(::cs_main, return context.chainman->ActiveChain().Tip());
- wallet.blockConnected(ChainstateRole{}, kernel::MakeBlockInfo(pindex, &block));
+ wallet::GenerateFakeBlock(params, context, wallet, coinbase_outputs);
}
struct PreSelectInputs {058e97c to
622265f
Compare
622265f to
5defb96
Compare
|
@l0rinc Thanks for the thorough review. I split the changes into two commits to make them easier to review, and added you as a co-author on both since many of the improvements came from your suggestions. |
|
I've re-run this benchmark to validate #27865, which changes how wallet TXOs are retained for balance calculation. Command used: build/bin/bench_bitcoin -filter=WalletBalanceManySpent -min-time=10000Results:
This is about a 2,981x speedup with #27865 for this workload. The benchmark's purpose is to model a wallet with many spent TXOs and only a few unspent TXOs, then measure With #27865, the balance path only sees the relevant unspent outputs, which is the performance improvement this benchmark is intended to demonstrate. |
| assert(owned_outputs == KEEP_UNSPENT); | ||
| assert(spent_outputs == 0); |
There was a problem hiding this comment.
nit: Is this meant to support running the benchmark on top of #27865?
On this PR’s current base the else branch should be dead code, so a short comment explaining the forward-compatibility case would help.
There was a problem hiding this comment.
I have changed my mind on this: since we don't know which direction follow-ups will take, could we rather simplify this to the assertions needed on the current base?
We can adapt them freely in a future PR if needed.
Related: Ralph's review also flags this branch. (cc: @maflcko / @willcl-ark how do we trigger @DrahtBot to update the reply?)
Simplify the output-state assertions
diff --git a/src/bench/wallet_balance.cpp b/src/bench/wallet_balance.cpp
index bfcddfc5b1..f1bed5d166 100644
--- a/src/bench/wallet_balance.cpp
+++ b/src/bench/wallet_balance.cpp
@@ -187,12 +187,8 @@ static void WalletBalanceManySpent(benchmark::Bench& bench)
spent_outputs += wallet.IsSpent(outpoint);
}
}
- if (owned_outputs == TOTAL_WALLET_OUTPUTS) {
- assert(spent_outputs == TOTAL_WALLET_OUTPUTS - KEEP_UNSPENT);
- } else {
- assert(owned_outputs == KEEP_UNSPENT);
- assert(spent_outputs == 0);
- }
+ assert(owned_outputs == TOTAL_WALLET_OUTPUTS);
+ assert(spent_outputs == TOTAL_WALLET_OUTPUTS - KEEP_UNSPENT);
CAmount expected_balance{0};
for (size_t i{0}; i < KEEP_UNSPENT; ++i) {There was a problem hiding this comment.
Related: Ralph's review also flags this branch. (cc: @maflcko / @willcl-ark how do we trigger @DrahtBot to update the reply?)
The summary is only updated when a comment is added or edited, see https://github.com/maflcko/DrahtBot/blob/7c658efafe394b4b7629053b582bc13df92b10aa/webhook_features/src/features/summary_comment.rs#L28-L32
Maybe there can be a manual one-time trigger for all pull requests, if you think an updated comment is important?
There was a problem hiding this comment.
Wasn't there an option before to add a thumbs down emoji when we need an update?
There was a problem hiding this comment.
Wasn't there an option before to add a thumbs down emoji when we need an update?
No, there was only an option to react on the summary comment to have it act on the next update (maflcko/DrahtBot@207fb31). I think it is enough to have the update path on comment creation or edits, but I can re-trigger it manually globally, if needed.
|
ACK 5defb96 Thanks for taking the suggestions. I see you've made it forward-compatible - I'm usually more strict about adding dead code, but in this case I personally don't mind. If you touch this again, either remove it and let the other PR extend the benchmark (it likely needs other changes anyway) or add a comment explaining it. I'm also fine with just adding a note to the PR's description. |
|
Ping @w0xlt for a rebase. |
5defb96 to
7971f41
Compare
|
Rebased. Thanks @sedited |
|
🚧 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. |
|
Could turn into draft while CI is red? |
7971f41 to
3a1a980
Compare
|
Rebased. |
Co-authored-by: Lőrinc <[email protected]>
Co-authored-by: Lőrinc <[email protected]>
3a1a980 to
bc9a71b
Compare
| assert(owned_outputs == KEEP_UNSPENT); | ||
| assert(spent_outputs == 0); |
There was a problem hiding this comment.
I have changed my mind on this: since we don't know which direction follow-ups will take, could we rather simplify this to the assertions needed on the current base?
We can adapt them freely in a future PR if needed.
Related: Ralph's review also flags this branch. (cc: @maflcko / @willcl-ark how do we trigger @DrahtBot to update the reply?)
Simplify the output-state assertions
diff --git a/src/bench/wallet_balance.cpp b/src/bench/wallet_balance.cpp
index bfcddfc5b1..f1bed5d166 100644
--- a/src/bench/wallet_balance.cpp
+++ b/src/bench/wallet_balance.cpp
@@ -187,12 +187,8 @@ static void WalletBalanceManySpent(benchmark::Bench& bench)
spent_outputs += wallet.IsSpent(outpoint);
}
}
- if (owned_outputs == TOTAL_WALLET_OUTPUTS) {
- assert(spent_outputs == TOTAL_WALLET_OUTPUTS - KEEP_UNSPENT);
- } else {
- assert(owned_outputs == KEEP_UNSPENT);
- assert(spent_outputs == 0);
- }
+ assert(owned_outputs == TOTAL_WALLET_OUTPUTS);
+ assert(spent_outputs == TOTAL_WALLET_OUTPUTS - KEEP_UNSPENT);
CAmount expected_balance{0};
for (size_t i{0}; i < KEEP_UNSPENT; ++i) {
This PR introduces a new benchmark that measures
GetBalance()performance on wallets with extensive transaction history where the majority of outputs have already been spent.It was created to test #27865, which separates spent TXOs from spendable ones.
This pattern mirrors real-world usage in high-activity wallets such as Lightning nodes, exchanges, hot wallets, and payment processors.
Setup:
To keep the setup time reasonable, the benchmark uses the fast “fake block” approach, similar to
wallet_create_tx.cpp.