wallet: skip APS when no partial spend exists #34405

Open
8144225309 wants to merge 2 commits from aps-skip-no-partial-spend into master AGit
8144225309 commented 2026-01-26 04:36:55 +00:00 (Migrated from github.com)

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.

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 commented 2026-01-26 04:37:04 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/34405 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/34405.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/34405#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [polespinasa](https://github.com/bitcoin/bitcoin/pull/34405#pullrequestreview-5381354581) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36627](https://github.com/bitcoin/bitcoin/pull/36627) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36627.svg"></sub> (tracing: run USDT tests without BPF privileges by willcl-ark) * [#35302](https://github.com/bitcoin/bitcoin/pull/35302) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35302.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
achow101 (Migrated from github.com) reviewed 2026-02-02 21:36:09 +00:00
achow101 (Migrated from github.com) commented 2026-02-02 21:25:45 +00:00

This condition can be grouped with the others in the line above, there's no need to separate it with it's own return statement.

This condition can be grouped with the others in the line above, there's no need to separate it with it's own return statement.
achow101 (Migrated from github.com) commented 2026-02-02 21:36:06 +00:00

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

The default for `wallet_name` is essentially `self.default_wallet_name`, so set it to that instead of using `None`.
8144225309 (Migrated from github.com) reviewed 2026-02-03 02:54:52 +00:00
8144225309 (Migrated from github.com) commented 2026-02-03 02:54:52 +00:00

Done, combined.

Done, combined.
8144225309 (Migrated from github.com) reviewed 2026-02-03 02:55:15 +00:00
8144225309 (Migrated from github.com) commented 2026-02-03 02:55:15 +00:00

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()).

`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()`).
DrahtBot commented 2026-08-21 08:40:12 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
sedited commented 2026-09-22 07:55:16 +00:00 (Migrated from github.com)

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

@8144225309 this has been in need of a rebase for a while. Are you still interested in working on this change?
8144225309 commented 2026-09-22 19:07:34 +00:00 (Migrated from github.com)

Thank you for pinging me, resolving conflicts now.

Thank you for pinging me, resolving conflicts now.
8144225309 commented 2026-09-27 07:07:14 +00:00 (Migrated from github.com)

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
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. <details> <summary>range-diff</summary> ``` 1: b6319c62db ! 1: e382330b92 wallet: skip APS when no partial spend exists @@ ## Metadata ## -Author: 8144225309 <248271067+[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 ``` </details>
First-time contributor

🔵 Suggestion · Preset-only selections trigger a redundant APS retry

When preset inputs cover the target, the grouped pass selects the same inputs but still reports APS as used, leaving the partial spend unchanged; this behavior also exists on the base branch.

Location: src/wallet/spend.cpp:1255 (head).

🔵 Suggestion · Partial-spend counting adds overhead when the retry cannot use it

The wallet builds and discards a per-UTXO map on several paths where the APS retry is disabled; the resulting cost is unmeasured.

Location: src/wallet/spend.cpp:1255 (head).


Reviewed: 559cd158c296 · Full review report · Previous reports

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:6f232c871bca65facadc248ad7ecd634f87b0b5f6936bc30593af890589888f1:0cfbbc826fdd30e42f35c9a5b7d389c0902089c94f2400654bb32123e69823f6 --> <!-- ralph-base:6ed5aad06111177c39f9b9f07a52634476380ae1 --> <!-- ralph-head:559cd158c2960fe8d0b72eb52c070a4ceb89900b --> <!-- ralph-case:6ca8eacdcb8369a744bae525d93a0fe2e57914edca0c3a955eebf821464aa803 --> **🔵 Suggestion · Preset-only selections trigger a redundant APS retry** When preset inputs cover the target, the grouped pass selects the same inputs but still reports APS as used, leaving the partial spend unchanged; this behavior also exists on the base branch. Location: [`src/wallet/spend.cpp:1255`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/559cd158c2960fe8d0b72eb52c070a4ceb89900b/src/wallet/spend.cpp#L1255>) (head). **🔵 Suggestion · Partial-spend counting adds overhead when the retry cannot use it** The wallet builds and discards a per-UTXO map on several paths where the APS retry is disabled; the resulting cost is unmeasured. Location: [`src/wallet/spend.cpp:1255`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/559cd158c2960fe8d0b72eb52c070a4ceb89900b/src/wallet/spend.cpp#L1255>) (head). <!-- Review tier: sensitive --> --- Reviewed: [`559cd158c296`](<https://git.fish.foo/bitcoin/bitcoin/commit/559cd158c2960fe8d0b72eb52c070a4ceb89900b>) · [Full review report](<https://review.fish.foo/traces/34405-559cd158c2960fe8d0b72eb52c070a4ceb89900b-1736-4.html>) · [Previous reports](<https://review.fish.foo/traces/34405/>)
polespinasa (Migrated from github.com) reviewed 2026-10-01 15:23:16 +00:00
polespinasa (Migrated from github.com) left a comment

concept ACK 8a30292d59

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 :)

concept ACK 8a30292d59630653499d8d967508038b4ec2072d 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 :)
Lines 1263-1269
polespinasa (Migrated from github.com) commented 2026-10-01 15:14:43 +00:00

in e382330b92 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 :)

in e382330b925c33b29ade9a943aea8db8142b0d12 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: ```diff $ 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 :)
polespinasa (Migrated from github.com) commented 2026-10-01 15:18:56 +00:00

in 8a30292d59 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

in 8a30292d59630653499d8d967508038b4ec2072d 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
polespinasa (Migrated from github.com) commented 2026-10-01 15:21:39 +00:00

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.

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.
8144225309 commented 2026-10-03 16:41:11 +00:00 (Migrated from github.com)

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.

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.
8144225309 (Migrated from github.com) reviewed 2026-10-03 16:42:38 +00:00
Lines 1263-1269
8144225309 (Migrated from github.com) commented 2026-10-03 16:42:38 +00:00

Done, thanks. Used two loops.

Done, thanks. Used two loops.
8144225309 (Migrated from github.com) reviewed 2026-10-03 16:43:42 +00:00
8144225309 (Migrated from github.com) commented 2026-10-03 16:43:42 +00:00

Done.

Done.
8144225309 (Migrated from github.com) reviewed 2026-10-03 16:44:47 +00:00
8144225309 (Migrated from github.com) commented 2026-10-03 16:44:47 +00:00

Done.

Done.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!34405
No description provided.