Skip to content

Payjoin-cli : add --consolidate mode - #1878

Open
AdamuAbba wants to merge 1 commit into
payjoin:masterfrom
AdamuAbba:feat-payjoin-cli
Open

AdamuAbba wants to merge 1 commit into
payjoin:masterfrom
AdamuAbba:feat-payjoin-cli

Conversation

@AdamuAbba

@AdamuAbba AdamuAbba commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR Adds the first of the two receiver capabilities from #1859 to Payjoin CLI. --cut-through has been split into its own PR, since it depends on #1949 exposing the fallback transaction on the receiver states that hold one.

Commits

5fb019b: --consolidate

Adds --consolidate [N] to receive, contributing up to N of the smallest available UTXOs on both the v1 and v2 receiver paths instead of the single privacy-preserving input.

For anyone reviewing this commit:

The cap exists because of the BIP77 message size limit. Padding leaves 7088 bytes for the receiver's reply (PADDED_PLAINTEXT_B_LENGTH); I hit 33,183 with a large UTXO set. It only fails when the receiver tries to post the proposal, so the session has to be cancelled in favour of the fallback. 10 seemed like a safe default; I haven't worked out where the real limit falls.

The setting is persisted per session. Config only reads the flags when the subcommand is Receive, so a resume run never sees them, and for v2 resume is the normal path, since that is usually the run reaching contribute_inputs. The choice is stored in the CLI's receive_sessions table as a serialised receive_options column, matching how receive_session_events.event_data already works. It reads as an application preference rather than protocol state.

This is the first schema migration in db/mod.rs. CREATE TABLE IF NOT EXISTS leaves an existing table untouched, so upgrading databases would not get the column. There is an explicit ALTER TABLE guarded by a pragma_table_info check.

Smallest UTXOs first, via a new select_receiver_utxos. list_unspent keeps its ordering so try_preserving_privacy is unchanged.

Testing: receiver_consolidates_utxos_v2 asserts the receiver's five UTXOs become one, and covers the persistence above since everything after the BIP21 runs through resume. The v1 path is covered by compilation only.

Follow-up

--cut-through is written and working on both receiver paths, with its own e2e test, but it currently keeps a copy of the original transaction and passes it alongside the session to reach WantsOutputs. Once #1949 is addressed I can drop that workaround, refactor the commit and open it for review.

Disclosure: co-authored by Claude Code

Pull Request Checklist

Please confirm the following before requesting review:

@coveralls

coveralls commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 38081510397

Coverage decreased (-0.03%) to 87.465%

Details

  • Coverage decreased (-0.03%) from the base build.
  • Patch coverage: 17 uncovered changes across 4 files (70 of 87 lines covered, 80.46%).
  • 1 coverage regression across 1 file.

Uncovered Changes

File Changed Covered %
payjoin-cli/src/app/v1.rs 28 15 53.57%
payjoin-cli/src/db/v2.rs 15 13 86.67%
payjoin-cli/src/app/v2/mod.rs 19 18 94.74%
payjoin-cli/src/db/mod.rs 6 5 83.33%
Total (6 files) 87 70 80.46%

Coverage Regressions

1 previously-covered line in 1 file lost coverage.

File Lines Losing Coverage Coverage
payjoin-cli/src/app/v1.rs 1 68.85%

Coverage Stats

Coverage Status
Relevant Lines: 17902
Covered Lines: 15658
Line Coverage: 87.47%
Coverage Strength: 325.83 hits per line

💛 - Coveralls

@AdamuAbba
AdamuAbba marked this pull request as ready for review September 23, 2026 18:29
@DanGould DanGould mentioned this pull request Sep 29, 2026
13 tasks
@DanGould DanGould added this to the payjoin-cli-1.1 milestone Sep 30, 2026
@xstoicunicornx

Copy link
Copy Markdown
Collaborator

To build the replacement outputs I need the receiver's own output, and WantsOutputs doesn't expose it.

Agree this is not very ergonomic to implement. I see three options:

  • expose the fallback_tx in the impl<S: HasFallbackTx> Receiver<S> block in the v2 receiver
  • expose new method on WantsOutputs for fetching outputs
  • expose new method on WantsOutputs for appending an output

Of the 3 I think the first would be the most useful and would also allow callers to access the fallback tx from any state that has a fallback tx, however I would like to hear other's thoughts on this since it involves exposing new things on the public API (@DanGould @spacebear21 ). Also interested in your opinion.

For the cut through script:amt I think it might be better to parse this at the command line and just pass around the parsed TxOut, was there a reason you decided against this approach? Also, I think for v1 I think maybe don't worry about replacing the

What I've done instead is add an output next to the receiver's own and fund it from a contributed input

Can you expand on what you mean by "fund it from a contributed input"? At this point there should not be any contributed inputs yet. Or are you just saying you're not adjusting the original output's value and just forcing sufficient inputs to be added later? I think thats appropriate. That said, should we maybe ensure that the input selected has sufficient value to cover the cut through output? and if no sufficient utxos exist throw an error?

FEE_HEADROOM_VB = 250 is a guess rather than a calculation.

I don't think you have to account for this as WantsFeeRange state should adjust the fees accordingly. Or was there something that isn't getting accounted for appropriately there?

@DanGould

DanGould commented Oct 6, 2026

Copy link
Copy Markdown
Member

Rather than passing the mutable state around, I agree if the fallback_tx was exposed on the generic Receiver that HasFallback then The same sort of session driver match on sessions could be preserved and the API would be nicer in rust.

I think that means on FFI, this function would need to be added to every relevant struct, which could be done with a macro.

@DanGould

DanGould commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Indeed the point of the issue is to figure out if our API can accommodate these use cases ergonomically.

We need to look in Shepherd and SatSigner to figure out how they're using Cut-Through with our API and should have them listed here before deciding on an API change.

@spacebear21

Copy link
Copy Markdown
Collaborator

receiver_forwards_payment shrinks the receiver's output and hands the difference to the third party, which needs OutputSubstitution::Enabled and so is v1-only, since v2 URIs hardcode Disabled

This is mistaken: v2 URIs hardcode disabled strictly for backwards compatibility purposes, but v2 senders ignore this parameter, so a v2 receiver may still substitute outputs. IMO it's nice for the receiver to have the option to fund the cut-through with an input of their own, but I don't think that decision should be forced upon them (unless maybe the sender actually signals disabled output substitution).

@spacebear21

Copy link
Copy Markdown
Collaborator

Regarding exposing the fallback tx on every typestate: one limitation to that approach is that it refers only to the original transaction, not the working proposal. After one substitution the receiver output it shows no longer exists. The WantsOutputs typestate was designed to allow calling these methods multiple times, e.g. for an exchange service facilitating batch withdrawals.

It might be more correct to expose only WantsOutputs::receiver_outputs() returning the current receiver-owned outputs of the working PSBT, and maybe drain_output() alongside. This would also simplify the API change as no macros are needed for FFI, and it also supports V1 (the FallbackTx trait lives in receive/v2 only).

@DanGould

DanGould commented Oct 9, 2026

Copy link
Copy Markdown
Member

I think --consolidate's commit here could be reviewed and merged on its own, right? That seems to already be supported by the API, right?

@spacebear21

Copy link
Copy Markdown
Collaborator

Yes I think it's probably a good idea to split this PR in two independent ones

@DanGould

DanGould commented Oct 9, 2026

Copy link
Copy Markdown
Member

at risk of overcommunicating @AdamuAbba please save the 2nd commit to a draft pr and drop it from this PR so that we can review and merge that on its own and keep the ball moving. Thanks for keeping up here and for this PR.

@DanGould
DanGould removed their request for review October 9, 2026 15:57
@AdamuAbba

Copy link
Copy Markdown
Contributor Author

@xstoicunicornx to answer your question:

Can you expand on what you mean by "fund it from a contributed input"?

Your second reading is the right one, and sorry for the wording: nothing is contributed at WantsOutputs time. The sufficiency check already exists too. select_receiver_utxos tops up from the largest UTXOs and errors if the wallet can't cover it:

pub fn select_receiver_utxos(
&self,
consolidate: Option<usize>,
min_total: Amount,
) -> Result<(Vec<InputPair>, usize)> {
let value_of =
|utxo: &ListUnspentItem| Amount::from_btc(utxo.amount.to_btc()).expect("Valid amount");
let mut unspent = self.list_unspent_raw()?;
unspent.sort_by_key(|utxo| value_of(utxo));
let available = unspent.len();
let mut selected = Vec::new();
let mut total = Amount::ZERO;
let smallest = consolidate.unwrap_or(0).min(available);
for utxo in unspent.drain(..smallest) {
total += value_of(&utxo);
selected.push(input_pair_from_corepc(utxo));
}
while total < min_total {
// Sorted ascending, so popping takes the largest remaining.
let Some(utxo) = unspent.pop() else {
return Err(anyhow!(
"wallet holds {total}, but this payjoin needs at least {min_total}"
));
};
total += value_of(&utxo);
selected.push(input_pair_from_corepc(utxo));
}

Thanks for pointing me in the right direction, guys. I really appreciate the help. I'm going to go ahead with the instructions to split up this PR.

Once #1949 is addressed, I can refactor the --cut-through commit and open it up for review.

@AdamuAbba AdamuAbba changed the title Payjoin-cli : add --consolidate and --cut-through modes Payjoin-cli : add --consolidate mode Oct 10, 2026
@AdamuAbba AdamuAbba mentioned this pull request Oct 10, 2026
1 of 3 tasks
The receiver API accepts a list of inputs, letting a receiver merge
their own UTXOs into the payjoin output rather than paying for a
separate consolidation transaction. Only the integration tests
demonstrated this; payjoin-cli always contributed a single
privacy-preserving input.

Add --consolidate [N] to `receive`, contributing up to N of the
smallest available UTXOs on both the v1 and v2 receiver paths.
Smallest first because every input costs the same to spend
regardless of value, so small UTXOs are the ones worth merging.

Store the choice per-session in the `receive_sessions` table. The
resume path never sees the original command line, and for v2 that
is the common case rather than an edge case: a receiver typically
publishes a BIP21, goes offline, and returns to `resume` after the
sender has posted, which is the run that reaches contribute_inputs.

N defaults to 10 because BIP77 pads every message to a fixed size,
capping the payjoin proposal at 7088 bytes. Contributing more than
fits fails when the proposal is posted, leaving the session to be
cancelled in favour of the fallback transaction.

Signed-off-by: shytypes <[email protected]>
@DanGould

DanGould commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

If this were mine to review I might look at how BitGo, Fortris etc think about interface they present to users for consolidation. IDK if it's by a certain number of coins n or if it's a target at a certain time. Would ask a clanker for a catalogue of some options.

Some people are already offering good consolidation & coin control as a savings benefit people are happy about. Leverage their work, because ultimately this is a reference for integrations with their systems.

@AdamuAbba

AdamuAbba commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @DanGould, really useful steer. Agreed the CLI should mirror what integrators already offer. I'll catalogue how BitGo, Fortris and others expose consolidation (coin count, target, fee-rate or time based) and post my findings here before settling the flag's shape.

P.S. I had to look up "clanker"... I should rewatch Star Wars 😅

@AdamuAbba

AdamuAbba commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @DanGould, sorry this took a while. I catalogued how BitGo, Fortris and others expose consolidation:

BitGo Fortris Others (Fireblocks, Core, Sparrow, Electrum, Casa) payjoin-cli
Coin cap per tx limit: server spends at most this many coins per tx. bulk splits larger jobs into 200-coin txs Not published Fireblocks: sends max balance to another vault, merging up to 250 coins, smallest first. Sparrow and Electrum: no cap, coins picked by hand Default 10, smallest first
Value ceiling maxValue: coins above it aren't selected Not published None found No
Dust floor v1 only: with a fee rate, skips coins worth less than their input fee Blog advice: freeze coins under a set value Sparrow: only labels coins of 1,000 sats or less on reused addresses as dust attacks. Electrum: auto-freezes unconfirmed coins under 5,000 sats from others No
Fee-rate gate Fee caps only: maxFeeRate limits the rate, maxFeePercentage the share spent on fees Not published Core: below 10 sat/vB, selection tends to merge inputs; above it, lowest fee No
Target coin count v1 only: merges batches of up to 200 coins until target coins remain (default 1). Not in v2 Not published None found No
Automatic EVM only: sweeps receive addresses into the main address "Manually and automatically", no details None found Runs when a payjoin arrives

BitGo's SDK is open source, but coin selection runs on its closed servers. I found no public Fortris code, so its column comes from its website and blog.

BTCPay and Bull Bitcoin always contribute one input as payjoin receivers, so an N-input cap appears to be new.

My proposal: keep --consolidate N as the coin cap and add two filters:

  • --consolidate-max-value <sats> keeps coins at or above this value out of the payjoin.
  • A dust floor skips coins worth less than the fee to spend them. At 10 sat/vB, a P2WPKH input costs about 680 sats, so a 500-sat coin would be skipped.

A fee-rate gate is possible too. I'd leave out a schedule, since a payjoin happens when a payment arrives. A target coin count could work as a stopping rule across payments, but BitGo's v2 API doesn't offer one and I found nobody else who does, so I'd skip it unless you see a use. What do you think of this direction?

Disclosure: I used Claude for the research and to help structure this comment.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants