Skip to content

Fix fund loss and panics in receiver proposal construction - #2047

Open
caarloshenriq wants to merge 3 commits into
payjoin:masterfrom
caarloshenriq:fix/receiver-proposal
Open

caarloshenriq wants to merge 3 commits into
payjoin:masterfrom
caarloshenriq:fix/receiver-proposal

Conversation

@caarloshenriq

Copy link
Copy Markdown
Contributor

Three receiver-side bugs in v2 proposal construction can lose the receiver's funds or panic. One commit per fix, each with a regression test.

  • Credit every receiver contribution to change. contribute_inputs ignores inputs it already contributed, so splitting the receiver's inputs across calls sends the surplus to fees instead of change.
  • Resolve the drain output among receiver outputs. The change index could match a sender output sharing the script, misdirecting the receiver's change and panicking during construction. A drain script with no receiver output is now rejected with InvalidDrainScript.
  • Keep contributed inputs unsigned. A scriptSig or witness left on a contributed input could make the proposal fail to parse or stop matching the persisted session. Inputs now carry only outpoint and sequence.

Tests: every_contribution_is_credited_to_change, drain_script_resolves_to_a_receiver_output, contributed_inputs_leave_the_transaction_unsigned

Reviewer: @benalleng

Disclosure: co-authored by Claude

Pull Request Checklist

Please confirm the following before requesting review:

@coveralls

coveralls commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 43109752754

Coverage increased (+0.05%) to 87.871%

Details

  • Coverage increased (+0.05%) from the base build.
  • Patch coverage: 3 uncovered changes across 2 files (97 of 100 lines covered, 97.0%).
  • No coverage regressions found.

Uncovered Changes

File Changed Covered %
payjoin/src/core/receive/error.rs 2 0 0.0%
payjoin/src/core/receive/common/mod.rs 98 97 98.98%

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 18715
Covered Lines: 16445
Line Coverage: 87.87%
Coverage Strength: 312.51 hits per line

💛 - Coveralls

@benalleng

benalleng commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

I believe the first commit e28e4c5 relates to #1940 an #1998 I need to poke around to see if this is a better or worse fix

@benalleng benalleng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think that e28e4c5 is the right logix change as compared to #1998.

I think we need to get a little fancier with 2b3c1a2 as the addition of the boolean flags may not be enough though depending on the fix it may change some current behavior that I made a test that stated as "allowed behavior" but I'm not sure it should be.

Comment thread payjoin/src/core/receive/common/mod.rs Outdated
let mut outputs = vec![];
// Each output is tagged with whether it is the receiver's, so the drain
// output below cannot resolve to a sender output that shares its script.
let mut outputs: Vec<(TxOut, bool)> = vec![];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A bot review claims that this could be further hardened with a different form of logic instead of these tagged outputs.

        // Sender outputs are kept as is, so once the drain script is not a sender
        // script, only a receiver output can carry it.
        let pays_sender = |script: &Script| {
            self.original
                .original_psbt
                .unsigned_tx
                .output
                .iter()
                .enumerate()
                .any(|(i, txo)| !self.owned_vouts.contains(&i) && txo.script_pubkey == *script)
        };
        if pays_sender(drain_script) {
            return Err(InternalOutputSubstitutionError::InvalidDrainScript.into());
        }

A more restrictive version also rejects any replacement output that pays a sender script. That changes accepted behavior: fee_contribution_resolves_duplicate_script_to_sender_output currently allows a receiver output that reuses the sender's fee script, and would need to be rewritten. With that check in place, requiring the drain to be among the replacements is enough to resolve it to a receiver output:

Here is a change that is more restrictive but breaks some unit tests that accept this behavior somewhat.

        // Ownership is per script, so an output paying a sender script pays the
        // sender, and the sender cannot tell it apart from its own outputs.
        let pays_sender = |script: &Script| {
            self.original
                .original_psbt
                .unsigned_tx
                .output
                .iter()
                .enumerate()
                .any(|(i, txo)| !self.owned_vouts.contains(&i) && txo.script_pubkey == *script)
        };
        if replacement_outputs.iter().any(|txo| pays_sender(&txo.script_pubkey)) {
            return Err(InternalOutputSubstitutionError::ReplacementPaysSender.into());
        }
        // With no replacement paying a sender script, a drain among the replacements
        // can only resolve to a receiver output.
        if !replacement_outputs.iter().any(|txo| txo.script_pubkey == *drain_script) {
            return Err(InternalOutputSubstitutionError::InvalidDrainScript.into());
        }

I am unsure if what we currently let pass through in fee_contribution_resolves_duplicate_script_to_sender_output is actually the appropriate behavior or not.

receiver_min_input_amount compared the proposal's outputs against the
original's without counting what an earlier contribute_inputs call had
already credited to the change output, so a second call paid for the
first one again. Contributing 100000 sat twice credited 100000 sat to
change and gave the other 100000 to the miner, and a second batch worth
less than the first was rejected as too low.

Subtract earlier contributions from the amount still owed.
replace_receiver_outputs took the first output whose script matched the
drain script as the change output, which can be a sender output.
Substituting the receiver script with the sender's change script made
the sender's output the change: contributed inputs were credited to it,
and apply_fee_range then panicked once the sender's fee output no
longer matched the original.

Only consider the receiver's outputs. A drain script that only a sender
output carries is now rejected as InvalidDrainScript.

@benalleng benalleng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually reading the error message for InternalOutputSubstitutionError::InvalidDrainScript I'm not sure it fits perfectly. perhaps using a new variant like DrainScriptPaysSender is best afterall.

Comment thread payjoin/src/core/receive/common/mod.rs Outdated
Comment on lines +155 to +166
let pays_sender = |script: &Script| {
self.original
.original_psbt
.unsigned_tx
.output
.iter()
.enumerate()
.any(|(i, txo)| !self.owned_vouts.contains(&i) && txo.script_pubkey == *script)
};
if pays_sender(drain_script) {
return Err(InternalOutputSubstitutionError::InvalidDrainScript.into());
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think we don't actually need a closure if it looks like this.

Suggested change
let pays_sender = |script: &Script| {
self.original
.original_psbt
.unsigned_tx
.output
.iter()
.enumerate()
.any(|(i, txo)| !self.owned_vouts.contains(&i) && txo.script_pubkey == *script)
};
if pays_sender(drain_script) {
return Err(InternalOutputSubstitutionError::InvalidDrainScript.into());
}
let drain_pays_sender =
self.original.original_psbt.unsigned_tx.output.iter().enumerate().any(|(i, txo)| {
!self.owned_vouts.contains(&i) && txo.script_pubkey == *drain_script
});
if drain_pays_sender {
return Err(InternalOutputSubstitutionError::InvalidDrainScript.into());
}

contribute_inputs copied the receiver's TxIn into the proposal as is.
InputPair::new accepts a scriptSig or witness on the TxIn, since a
witness is how it estimates the weight of some inputs, but a PSBT's
unsigned transaction carries neither. A scriptSig made the proposal
fail to parse, and a witness was dropped on serialization, so
psbt_to_sign no longer matched the persisted state.

Insert only the outpoint and sequence. The weight is computed when the
InputPair is built, and signatures belong in the PSBT input.
@caarloshenriq

Copy link
Copy Markdown
Contributor Author

Done, both. Dropped the closure for the inline drain_pays_sender, and added a DrainScriptPaysSender variant instead of reusing InvalidDrainScript. Kept InvalidDrainScript for the case where the drain script matches no output at all

@xstoicunicornx xstoicunicornx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

utACK 62dc59c

I agree the fix for #1940 implemented here is better than what I proposed in #1998 . The other two fixes makes sense and successfully close the gap on panics in straightforward and simple manner.

Nit: fixup seems to have been squashed in with last commit.

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.

4 participants