From 83976715a1a3c63273e421163962f2e2736a320c Mon Sep 17 00:00:00 2001 From: Carlos Santos Date: Tue, 3 Nov 2026 16:32:41 -0300 Subject: [PATCH 1/3] Credit every receiver contribution to change 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. --- payjoin/src/core/receive/common/mod.rs | 51 ++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/payjoin/src/core/receive/common/mod.rs b/payjoin/src/core/receive/common/mod.rs index 095deb888..ed517be19 100644 --- a/payjoin/src/core/receive/common/mod.rs +++ b/payjoin/src/core/receive/common/mod.rs @@ -425,13 +425,21 @@ impl WantsInputs { // Compute the minimum amount that the receiver must contribute to the transaction as input. // - // Output values are sender-supplied, so either sum can overflow. + // Output values are sender-supplied, so either sum can overflow. Earlier + // contributions were already credited to the change output, so they count + // toward the minimum rather than raising it. fn receiver_min_input_amount(&self) -> Result { let output_amount = checked_sum(self.proposal.payjoin_psbt.unsigned_tx.output.iter().map(|o| o.value))?; let original_output_amount = checked_sum(self.original.original_psbt.unsigned_tx.output.iter().map(|o| o.value))?; - Ok(output_amount.checked_sub(original_output_amount).unwrap_or(Amount::ZERO)) + let contributed_amount = checked_sum( + self.proposal.receiver_inputs.iter().map(|input| input.previous_txout().value), + )?; + Ok(output_amount + .checked_sub(original_output_amount) + .and_then(|deficit| deficit.checked_sub(contributed_amount)) + .unwrap_or(Amount::ZERO)) } /// Commits the inputs as final, and moves on to the next typestate. @@ -605,7 +613,7 @@ mod tests { use bitcoin::taproot::LeafVersion; use bitcoin::{ Amount, Network, OutPoint, PubkeyHash, ScriptBuf, Sequence, TapLeafHash, TapNodeHash, - Transaction, TxIn, TxOut, Weight, Witness, + Transaction, TxIn, TxOut, Txid, Weight, Witness, }; use payjoin_test_utils::{DUMMY20, RECEIVER_INPUT_CONTRIBUTION}; @@ -846,6 +854,43 @@ mod tests { assert_eq!(wants_inputs.proposal.receiver_inputs[1], input_pair_2); } + fn p2wpkh_input(vout: u32, value: Amount) -> InputPair { + let txout = TxOut { + value, + script_pubkey: ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array(DUMMY20)), + }; + let outpoint = OutPoint { txid: Txid::from_byte_array([1; 32]), vout }; + InputPair::new_p2wpkh(txout, outpoint).expect("valid p2wpkh input") + } + + fn output_sum(psbt: &Psbt) -> Amount { psbt.unsigned_tx.output.iter().map(|o| o.value).sum() } + + #[test] + fn every_contribution_is_credited_to_change() { + let original = original_from_test_vector(); + let original_sum = output_sum(&original.psbt); + let wants_inputs = WantsOutputs::new(original, vec![1]).commit_outputs(); + let value = Amount::from_sat(100_000); + + let one_call = wants_inputs + .clone() + .contribute_inputs([p2wpkh_input(0, value), p2wpkh_input(1, value)]) + .expect("contribution should succeed"); + let two_calls = wants_inputs + .contribute_inputs([p2wpkh_input(0, value)]) + .expect("first contribution should succeed") + .contribute_inputs([p2wpkh_input(1, value)]) + .expect("second contribution should succeed"); + + for proposal in [one_call.proposal, two_calls.proposal] { + assert_eq!( + output_sum(&proposal.payjoin_psbt), + original_sum + value + value, + "every contributed sat must reach the change output, not the miner" + ); + } + } + #[test] fn sender_specifies_excessive_fee_rate() { let original = original_from_test_vector(); From 326568f14b6ffb08751e7a7508956b25dc48916d Mon Sep 17 00:00:00 2001 From: Carlos Santos Date: Tue, 3 Nov 2026 16:35:24 -0300 Subject: [PATCH 2/3] Resolve the drain output among receiver outputs 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. --- payjoin/src/core/receive/common/mod.rs | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/payjoin/src/core/receive/common/mod.rs b/payjoin/src/core/receive/common/mod.rs index ed517be19..969fa7929 100644 --- a/payjoin/src/core/receive/common/mod.rs +++ b/payjoin/src/core/receive/common/mod.rs @@ -150,6 +150,20 @@ impl WantsOutputs { let mut payjoin_psbt = self.original.original_psbt.clone(); let mut outputs = vec![]; let mut replacement_outputs: Vec = replacement_outputs.into_iter().collect(); + // 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()); + } // Substitute the existing receiver outputs, keeping the sender/receiver output ordering for (i, original_output) in self.original.original_psbt.unsigned_tx.output.iter().enumerate() @@ -891,6 +905,34 @@ mod tests { } } + #[test] + fn drain_script_must_not_be_a_sender_script() { + let original = original_from_test_vector(); + let sender_output = original.psbt.unsigned_tx.output[0].clone(); + let wants_outputs = WantsOutputs::new(original, vec![1]); + let receiver_output = wants_outputs.payjoin_psbt.unsigned_tx.output[1].clone(); + + // Draining to the sender's script would credit the receiver's change to + // the sender, even when a receiver output also carries that script. + let err = wants_outputs + .clone() + .substitute_receiver_script(&sender_output.script_pubkey) + .expect_err("a sender script cannot be the drain"); + assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); + let err = wants_outputs + .clone() + .replace_receiver_outputs([receiver_output.clone()], &sender_output.script_pubkey) + .expect_err("a sender output cannot be the drain"); + assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); + + // A drain script no output carries names no receiver output either. + let unknown_script = ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array(DUMMY20)); + let err = wants_outputs + .replace_receiver_outputs([receiver_output], &unknown_script) + .expect_err("the drain must be a replacement output"); + assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); + } + #[test] fn sender_specifies_excessive_fee_rate() { let original = original_from_test_vector(); From 62dc59cc8bf929180d81992dea4238c9e76255a8 Mon Sep 17 00:00:00 2001 From: Carlos Santos Date: Tue, 3 Nov 2026 16:39:36 -0300 Subject: [PATCH 3/3] Keep contributed inputs unsigned in the proposal 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. --- payjoin/changelog.d/fix-receiver-proposal.md | 12 ++++ payjoin/src/core/receive/common/mod.rs | 65 +++++++++++++++----- payjoin/src/core/receive/error.rs | 5 ++ 3 files changed, 65 insertions(+), 17 deletions(-) create mode 100644 payjoin/changelog.d/fix-receiver-proposal.md diff --git a/payjoin/changelog.d/fix-receiver-proposal.md b/payjoin/changelog.d/fix-receiver-proposal.md new file mode 100644 index 000000000..66118aaf9 --- /dev/null +++ b/payjoin/changelog.d/fix-receiver-proposal.md @@ -0,0 +1,12 @@ +### Bug Fixes + +- Fix `Receiver::contribute_inputs` crediting a second + contribution to fees instead of the change output, so splitting the + receiver's inputs across calls lost funds to the miner and could + reject a smaller later batch as below the minimum. +- Reject a drain script that a sender output carries. It let the change + index resolve to that sender output, crediting the receiver's change to + the sender and then panicking in `apply_fee_range`. +- Keep inputs contributed through `contribute_inputs` unsigned in the + proposal. A `scriptSig` or witness left on the `TxIn` could make the + proposal fail to parse or stop matching the persisted session. diff --git a/payjoin/src/core/receive/common/mod.rs b/payjoin/src/core/receive/common/mod.rs index 969fa7929..f46c32484 100644 --- a/payjoin/src/core/receive/common/mod.rs +++ b/payjoin/src/core/receive/common/mod.rs @@ -152,17 +152,12 @@ impl WantsOutputs { let mut replacement_outputs: Vec = replacement_outputs.into_iter().collect(); // 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()); + 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::DrainScriptPaysSender.into()); } // Substitute the existing receiver outputs, keeping the sender/receiver output ordering for (i, original_output) in @@ -404,10 +399,14 @@ impl WantsInputs { for input_pair in inputs.clone() { let index = rng.gen_range(0..=self.proposal.payjoin_psbt.unsigned_tx.input.len()); payjoin_psbt.inputs.insert(index, input_pair.psbtin); - payjoin_psbt - .unsigned_tx - .input - .insert(index, TxIn { sequence: original_sequence, ..input_pair.txin }); + // A scriptSig or witness on the TxIn only informs the weight estimate. + // An unsigned transaction carries neither, or the PSBT stops parsing. + let txin = TxIn { + previous_output: input_pair.txin.previous_output, + sequence: original_sequence, + ..Default::default() + }; + payjoin_psbt.unsigned_tx.input.insert(index, txin); } // Add the receiver change amount to the receiver change output, if applicable @@ -918,12 +917,12 @@ mod tests { .clone() .substitute_receiver_script(&sender_output.script_pubkey) .expect_err("a sender script cannot be the drain"); - assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); + assert_eq!(err, InternalOutputSubstitutionError::DrainScriptPaysSender.into()); let err = wants_outputs .clone() .replace_receiver_outputs([receiver_output.clone()], &sender_output.script_pubkey) .expect_err("a sender output cannot be the drain"); - assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); + assert_eq!(err, InternalOutputSubstitutionError::DrainScriptPaysSender.into()); // A drain script no output carries names no receiver output either. let unknown_script = ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array(DUMMY20)); @@ -933,6 +932,38 @@ mod tests { assert_eq!(err, InternalOutputSubstitutionError::InvalidDrainScript.into()); } + #[test] + fn contributed_inputs_leave_the_transaction_unsigned() { + let original = original_from_test_vector(); + let wants_inputs = WantsOutputs::new(original, vec![1]).commit_outputs(); + let txout = TxOut { + value: Amount::from_sat(100_000), + script_pubkey: ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array(DUMMY20)), + }; + let txin = TxIn { + previous_output: OutPoint { txid: Txid::from_byte_array([1; 32]), vout: 0 }, + script_sig: ScriptBuf::from_bytes(vec![0x51]), + witness: Witness::from_slice(&[vec![0x30; 72], vec![0x02; 33]]), + ..Default::default() + }; + let input = InputPair::new( + txin, + bitcoin::psbt::Input { witness_utxo: Some(txout), ..Default::default() }, + None, + ) + .expect("the witness gives the input's weight"); + + let psbt = wants_inputs + .contribute_inputs([input]) + .expect("contribution should succeed") + .proposal + .payjoin_psbt; + for txin in &psbt.unsigned_tx.input { + assert!(txin.script_sig.is_empty() && txin.witness.is_empty(), "{txin:?} is signed"); + } + assert_eq!(Psbt::from_str(&psbt.to_string()).expect("the proposal parses"), psbt); + } + #[test] fn sender_specifies_excessive_fee_rate() { let original = original_from_test_vector(); diff --git a/payjoin/src/core/receive/error.rs b/payjoin/src/core/receive/error.rs index f6ec0b3b5..0322bfc99 100644 --- a/payjoin/src/core/receive/error.rs +++ b/payjoin/src/core/receive/error.rs @@ -322,6 +322,8 @@ pub(crate) enum InternalOutputSubstitutionError { NotEnoughOutputs, /// The provided drain script could not be identified in the provided replacement outputs InvalidDrainScript, + /// The drain script is the script of one of the sender's outputs + DrainScriptPaysSender, } impl fmt::Display for OutputSubstitutionError { @@ -335,6 +337,8 @@ impl fmt::Display for OutputSubstitutionError { ), InternalOutputSubstitutionError::InvalidDrainScript => write!(f, "The provided drain script could not be identified in the provided replacement outputs"), + InternalOutputSubstitutionError::DrainScriptPaysSender => + write!(f, "The drain script pays a script that one of the sender's outputs already uses"), } } } @@ -350,6 +354,7 @@ impl std::error::Error for OutputSubstitutionError { InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => None, InternalOutputSubstitutionError::NotEnoughOutputs => None, InternalOutputSubstitutionError::InvalidDrainScript => None, + InternalOutputSubstitutionError::DrainScriptPaysSender => None, } } }