Skip to content

wallet: skip APS when no partial spend exists - #34405

Open
8144225309 wants to merge 2 commits into
bitcoin:masterfrom
8144225309:aps-skip-no-partial-spend
Open

8144225309 wants to merge 2 commits into
bitcoin:masterfrom
8144225309:aps-skip-no-partial-spend

Conversation

@8144225309

@8144225309 8144225309 commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #25150

APS (Avoid Partial Spends) runs a second coin selection pass that spends many
(possibly all) or none of the UTXOs sharing a scriptPubKey. The second pass runs
even when the first selection left no partial spend for it to avoid, and
aps_create_tx_internal then reports APS as used whenever the grouped result is
taken, overreporting how often a partial spend was avoided.

Detect partial spends by comparing selected vs available UTXO counts per
scriptPubKey, reusing the coins already fetched for selection and counting
manually selected inputs towards their scriptPubKey. Skip APS if none found.

Functional tests cover APS being skipped and a manually selected input making
the spend partial.


Supersedes #34362.

@DrahtBot

DrahtBot commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK polespinasa

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36627 (tracing: run USDT tests without BPF privileges by willcl-ark)
  • #35302 (Silent Payments: Sending (take 2) by Eunovo)

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.

Comment thread src/wallet/spend.cpp Resolved
@@ -119,12 +119,14 @@ def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_running_under_valgrind()

def get_tracepoints(self, expected_types):
def get_tracepoints(self, expected_types, wallet_name=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default for wallet_name is essentially self.default_wallet_name, so set it to that instead of using None.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self isn't available at function definition time in Python. The =None with internal check matches the pattern used elsewhere in the test framework (e.g., extra_args in add_nodes()).

@sedited

sedited commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

@8144225309 this has been in need of a rebase for a while. Are you still interested in working on this change?

@8144225309

Copy link
Copy Markdown
Contributor Author

Thank you for pinging me, resolving conflicts now.

@8144225309
8144225309 force-pushed the aps-skip-no-partial-spend branch from b6319c6 to fb4fc43 Compare September 27, 2026 07:04
@8144225309
8144225309 force-pushed the aps-skip-no-partial-spend branch from fb4fc43 to 8a30292 Compare September 27, 2026 07:05
@8144225309

Copy link
Copy Markdown
Contributor Author

Rebased onto master. The only conflict was CreatedTransactionResult moving from
FeeCalculation to FeeReason; no other code changed, and the rest of the src/ diff
is comments.

The new wallet_groups.py coverage is a separate commit; the tracepoint test changes
stay with the code commit. That test needs bcc and does not currently run in CI, so
both new scenarios assert on the debug log instead: APS skipped when nothing is
partially spent, and a manually selected input counted towards its scriptPubKey. The
tracepoint test also gains a case asserting use_aps with no change output.

range-diff
1:  b6319c62db ! 1:  e382330b92 wallet: skip APS when no partial spend exists
    @@
      ## Metadata ##
    -Author: 8144225309 <[email protected]>
    +Author: 8144225309 <[email protected]>
     
      ## Commit message ##
         wallet: skip APS when no partial spend exists
     
    -    APS runs a second coin selection to fully spend UTXOs sharing a
    -    scriptPubKey. Currently runs unconditionally, even when the first
    -    selection has no partial spend and APS cannot help.
    +    APS runs a second coin selection that spends many (possibly all) or none
    +    of the UTXOs sharing a scriptPubKey. It runs even when the first
    +    selection left no partial spend for it to avoid.
     
         Detect partial spends by comparing selected vs available UTXO counts
    -    per scriptPubKey inside CreateTransactionInternal, reusing available_coins.
    -    Add has_partial_spend to CreatedTransactionResult. Skip APS if false.
    -
    -    Update interface_usdt_coinselection test to create partial spend scenarios
    -    so tracepoints fire as expected.
    +    per scriptPubKey inside CreateTransactionInternal. The result is
    +    returned in CreatedTransactionResult as has_partial_spend, and APS
    +    now runs only when it is set.
     
         Fixes #25150
     
    @@ src/wallet/spend.cpp: static util::Result<CreatedTransactionResult> CreateTransa
                 result.GetWaste(),
                 result.GetSelectedValue());
      
    -+    // Check for partial spend: spending some but not all UTXOs from any scriptPubKey
    ++    // Check for partial spend: spending some but not all available UTXOs from any scriptPubKey
     +    bool has_partial_spend{false};
     +    if (coin_control.m_allow_other_inputs) {
     +        std::map<CScript, std::pair<size_t, size_t>> spk_counts; // {available, selected}
     +        for (const auto& coin : available_coins.All()) {
     +            spk_counts[coin.txout.scriptPubKey].first++;
     +        }
    -+        // Also count preset inputs as available (they're wallet UTXOs too)
    ++        // AvailableCoins skips manually selected coins, so count them here too.
     +        for (const auto& coin : preset_inputs.All()) {
     +            spk_counts[coin.txout.scriptPubKey].first++;
     +        }
    @@ src/wallet/spend.cpp: static util::Result<CreatedTransactionResult> CreateTransa
          txNew.vout.reserve(vecSend.size() + 1); // + 1 because of possible later insert
          for (const auto& recipient : vecSend)
     @@ src/wallet/spend.cpp: static util::Result<CreatedTransactionResult> CreateTransactionInternal(
    -               feeCalc.est.fail.start, feeCalc.est.fail.end,
    -               (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) > 0.0 ? 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) : 0.0,
    -               feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
    --    return CreatedTransactionResult(tx, current_fee, change_pos, feeCalc);
    -+    return CreatedTransactionResult(tx, current_fee, change_pos, feeCalc, has_partial_spend);
    +     wallet.WalletLogPrintf("Coin Selection: Algorithm:%s, Waste Metric Score:%d\n", GetAlgorithmName(result.GetAlgo()), result.GetWaste());
    +     wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u, Source: %s\n",
    +                            current_fee, nBytes, StringForFeeReason(min_fee_rate.fee_reason));
    +-    return CreatedTransactionResult(tx, current_fee, change_pos, min_fee_rate.fee_reason);
    ++    return CreatedTransactionResult(tx, current_fee, change_pos, min_fee_rate.fee_reason, has_partial_spend);
      }
      
      util::Result<CreatedTransactionResult> CreateTransaction(
    @@ src/wallet/spend.cpp: util::Result<CreatedTransactionResult> CreateTransaction(
      ## src/wallet/types.h ##
     @@ src/wallet/types.h: struct CreatedTransactionResult
          CAmount fee;
    -     FeeCalculation fee_calc;
    +     FeeReason fee_reason;
          std::optional<unsigned int> change_pos;
    -+    /** Whether the selection spends only some UTXOs from any scriptPubKey (relevant for APS) */
    ++    //! Whether the selection spends only some of the available UTXOs at any scriptPubKey (only populated if the wallet may add inputs)
     +    bool has_partial_spend{false};
      
    --    CreatedTransactionResult(CTransactionRef _tx, CAmount _fee, std::optional<unsigned int> _change_pos, const FeeCalculation& _fee_calc)
    --            : tx(_tx), fee(_fee), fee_calc(_fee_calc), change_pos(_change_pos) {}
    -+    CreatedTransactionResult(CTransactionRef _tx, CAmount _fee, std::optional<unsigned int> _change_pos, const FeeCalculation& _fee_calc, bool _has_partial_spend = false)
    -+            : tx(_tx), fee(_fee), fee_calc(_fee_calc), change_pos(_change_pos), has_partial_spend(_has_partial_spend) {}
    +-    CreatedTransactionResult(CTransactionRef _tx, CAmount _fee, std::optional<unsigned int> _change_pos, FeeReason _fee_reason)
    +-        : tx(_tx), fee(_fee), fee_reason(_fee_reason), change_pos(_change_pos) {}
    ++    CreatedTransactionResult(CTransactionRef _tx, CAmount _fee, std::optional<unsigned int> _change_pos, FeeReason _fee_reason, bool _has_partial_spend = false)
    ++        : tx(_tx), fee(_fee), fee_reason(_fee_reason), change_pos(_change_pos), has_partial_spend(_has_partial_spend) {}
      };
      
    - } // namespace wallet
    + //! Machine-readable wallet error codes.
     
      ## test/functional/interface_usdt_coinselection.py ##
     @@ test/functional/interface_usdt_coinselection.py: class CoinSelectionTracepointTest(BitcoinTestFramework):
    @@ test/functional/interface_usdt_coinselection.py: class CoinSelectionTracepointTe
      
     -        self.log.info("Sending a transaction should result in all tracepoints")
     +        self.log.info("Sending a transaction skips APS when no partial spend exists")
    -+        # Default wallet has UTXOs at different addresses (from mining), so no
    -+        # partial spend exists. APS is skipped. We should have 2 tracepoints:
    ++        # Only one coinbase is mature, so the wallet has a single available UTXO.
    ++        # We should have 2 tracepoints in the order:
     +        # 1. selected_coins (type 1)
     +        # 2. normal_create_tx_internal (type 2)
     +        wallet.sendtoaddress(wallet.getnewaddress(), 10)
    @@ test/functional/interface_usdt_coinselection.py: class CoinSelectionTracepointTe
     +        self.nodes[0].createwallet("aps_test")
     +        aps_wallet = self.nodes[0].get_wallet_rpc("aps_test")
     +        addr = aps_wallet.getnewaddress()
    -+        wallet.sendtoaddress(addr, 5)
    -+        self.get_tracepoints([1, 2])  # Consume tracepoints from funding tx
    -+        wallet.sendtoaddress(addr, 5)
    -+        self.get_tracepoints([1, 2])  # Consume tracepoints from funding tx
    ++        for _ in range(3):
    ++            wallet.sendtoaddress(addr, 5)
    ++            self.get_tracepoints([1, 2])  # Consume tracepoints from funding tx
     +        self.generate(self.nodes[0], 1)
    -+        # Spending less than the total creates a partial spend (using one of two
    -+        # UTXOs at the same address). APS should be attempted.
    ++        # The payment needs only one of the three UTXOs at addr, leaving a partial spend.
              # We should have 5 tracepoints in the order:
              # 1. selected_coins (type 1)
              # 2. normal_create_tx_internal (type 2)
    @@ test/functional/interface_usdt_coinselection.py: class CoinSelectionTracepointTe
              success, use_aps, _algo, _waste, change_pos = self.determine_selection_from_usdt(events)
              assert_equal(success, True)
              assert_greater_than(change_pos, -1)
    + 
    ++        self.log.info("Change position is -1 if no change is created with APS")
    ++        # The fee comes out of the output, so the preselected UTXO alone covers the
    ++        # target: both passes select just it, pay the same fee and create no change,
    ++        # so the APS result is used. The other UTXO left at addr is the partial spend.
    ++        # We should have 5 tracepoints in the order:
    ++        # 1. selected_coins (type 1)
    ++        # 2. normal_create_tx_internal (type 2)
    ++        # 3. attempting_aps_create_tx (type 3)
    ++        # 4. selected_coins (type 1)
    ++        # 5. aps_create_tx_internal (type 4)
    ++        preset = next(utxo for utxo in aps_wallet.listunspent() if utxo["address"] == addr)
    ++        raw_tx = aps_wallet.createrawtransaction(
    ++            [{"txid": preset["txid"], "vout": preset["vout"]}],
    ++            [{wallet.getnewaddress(): preset["amount"]}])
    ++        aps_wallet.fundrawtransaction(raw_tx, options={"add_inputs": True, "subtractFeeFromOutputs": [0]})
    ++        events = self.get_tracepoints([1, 2, 3, 1, 4], "aps_test")
    ++        success, use_aps, _algo, _waste, change_pos = self.determine_selection_from_usdt(events)
    ++        assert_equal(success, True)
    ++        assert_equal(use_aps, True)
    ++        assert_equal(change_pos, -1)
    ++
    +         self.log.info("Failing to fund results in 1 tracepoint")
    +         # We should have 1 tracepoints in the order
    +         # 1. normal_create_tx_internal (type 2)
     @@ test/functional/interface_usdt_coinselection.py: class CoinSelectionTracepointTest(BitcoinTestFramework):
              assert_equal(success, True)
              assert_equal(use_aps, None)
      
     -        self.log.info("Change position is -1 if no change is created with APS when APS was initially not used")
    --        # We should have 2 tracepoints in the order:
     +        self.log.info("Sending entire balance skips APS (no partial spend)")
    -+        # Sending entire balance spends all UTXOs, so no partial spend exists.
    -+        # APS is skipped. We should have 2 tracepoints:
    +         # We should have 2 tracepoints in the order:
              # 1. selected_coins (type 1)
              # 2. normal_create_tx_internal (type 2)
     -        # 3. attempting_aps_create_tx (type 3)
-:  ---------- > 2:  8a30292d59 test: add coverage for partial spend detection

@polespinasa polespinasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concept ACK 8a30292

I am not really familiar with this part of the wallet codebase but it looks pretty good to me.

Left a few suggestions before ACKing it :)

Comment thread src/wallet/spend.cpp Outdated
Comment on lines +1257 to +1263
for (const auto& coin : available_coins.All()) {
spk_counts[coin.txout.scriptPubKey].first++;
}
// AvailableCoins skips manually selected coins, so count them here too.
for (const auto& coin : preset_inputs.All()) {
spk_counts[coin.txout.scriptPubKey].first++;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in e382330 wallet: skip APS when no partial spend exists

By calling available_coins.All() and preset_inputs.All() (both are CoinsResult::All()) you are creating two new temporary vectors of COutput.

You can just iterate the original vectors, with something like:

$ git diff
diff --git a/src/wallet/spend.cpp b/src/wallet/spend.cpp
index 3dd562ba98..e09c741538 100644
--- a/src/wallet/spend.cpp
+++ b/src/wallet/spend.cpp
@@ -1254,13 +1254,16 @@ static util::Result<CreatedTransactionResult> CreateTransactionInternal(
     bool has_partial_spend{false};
     if (coin_control.m_allow_other_inputs) {
         std::map<CScript, std::pair<size_t, size_t>> spk_counts; // {available, selected}
-        for (const auto& coin : available_coins.All()) {
-            spk_counts[coin.txout.scriptPubKey].first++;
-        }
+        auto count_available_outputs = [&spk_counts](const CoinsResult& coins) {
+            for (const auto& [_, outputs] : coins.coins) {
+                for (const auto& coin : outputs) {
+                    spk_counts[coin.txout.scriptPubKey].first++;
+                }
+            }
+        };
+        count_available_outputs(available_coins);
         // AvailableCoins skips manually selected coins, so count them here too.
-        for (const auto& coin : preset_inputs.All()) {
-            spk_counts[coin.txout.scriptPubKey].first++;
-        }
+        count_available_outputs(preset_inputs);
         for (const auto& coin : result.GetInputSet()) {
             spk_counts[coin->txout.scriptPubKey].second++;
         }

You can ignore the lamda, it is just a personal preference, it is fine with me to have two loops :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks. Used two loops.

for _ in range(2):
self.nodes[0].sendtoaddress(no_partial.getnewaddress(), 1.0, fee_rate=self.fee_rate)
self.generate(self.nodes[0], 1)
with self.nodes[3].assert_debug_log(expected_msgs=[], unexpected_msgs=['Fee non-grouped']):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 8a30292 test: add coverage for partial spend detection

I would probably assert also here the len of vin similar to what you did in line 206

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread test/functional/wallet_groups.py Outdated
self.nodes[0].sendtoaddress(no_partial.getnewaddress(), 1.0, fee_rate=self.fee_rate)
self.generate(self.nodes[0], 1)
with self.nodes[3].assert_debug_log(expected_msgs=[], unexpected_msgs=['Fee non-grouped']):
no_partial.sendtoaddress(self.nodes[0].getnewaddress(), 0.5, fee_rate=self.fee_rate)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 8a30292 test: add coverage for partial spend detection

The test has a premise and is that the two UTXOs that the wallet has are owned by different scriptpubkey, maybe asserting it in the code would serve as documentation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

APS runs a second coin selection that spends many (possibly all) or none
of the UTXOs sharing a scriptPubKey. It runs even when the first
selection left no partial spend for it to avoid.

Detect partial spends by comparing selected vs available UTXO counts
per scriptPubKey inside CreateTransactionInternal. The result is
returned in CreatedTransactionResult as has_partial_spend, and APS
now runs only when it is set.

Fixes bitcoin#25150
APS now runs only when the first selection leaves a scriptPubKey
partially spent.

Cover the two cases that gate creates in wallet_groups.py: a wallet
whose scriptPubKeys hold one UTXO each never runs the second
selection, and a manually preselected input counts towards its
scriptPubKey, so the grouped selection still runs.
@8144225309
8144225309 force-pushed the aps-skip-no-partial-spend branch from 8a30292 to 559cd15 Compare October 3, 2026 16:33
@8144225309

Copy link
Copy Markdown
Contributor Author

Took @polespinasa's suggestions: the partial spend check now iterates CoinsResult::coins instead of copying through All(), and the no-partial-spend case asserts its premise and the input count. Also dropped the unused default on the new CreatedTransactionResult parameter, so callers must pass it. No rebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coin Selection tracepoint overreports use of APS

5 participants