Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions payjoin/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
fails: `cancel` yields a `Receiver<PendingFallback>` whose `fallback_tx`
is the transaction to broadcast.

### Bug Fixes

- Reject proposals whose outputs exceed their inputs. A receiver that raises
the total output value through `replace_receiver_outputs` without
contributing inputs covering the increase could otherwise produce a
proposal with a lower absolute fee than the original transaction, which
the sender would reject (#1939)

## 1.2.0

This release adds a non-blocking interface to the receiver state machine.
Expand Down
67 changes: 67 additions & 0 deletions payjoin/src/core/receive/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,20 @@ impl WantsFeeRange {
)
})?;
}
let original_fee = self
.original
.original_psbt
.fee()
.map_err(|_| InternalPayloadError::FeeCalculationOverflow)?;
let proposal_fee = match payjoin_psbt.fee() {
Ok(fee) => fee,
Err(bitcoin::psbt::Error::NegativeFee) =>
return Err(InternalPayloadError::AbsoluteFeeDecreased),
Err(_) => return Err(InternalPayloadError::FeeCalculationOverflow),
};
if proposal_fee < original_fee {
return Err(InternalPayloadError::AbsoluteFeeDecreased);
}

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.

Claude found issue with this strategy, if the witness-utxo and non-witness-utxo fields are missing from any inputs in the psbt this will error (and the error will be mislabeled as FeeCalculationOverflow). To avoid this we can instead check that receiver_inputs >= proposal_outputs - original_outputs. This should effectively be the same as checking proposal_fee >= original_fee and we should have all the utxo data for all receiver inputs.

Here is an untested code snippet from claude.

        let sum_outputs = |psbt: &Psbt| {
            psbt.unsigned_tx.output.iter().try_fold(Amount::ZERO, |acc, o| acc.checked_add(o.value))
        };
        let receiver_input_amount = self
            .proposal
            .receiver_inputs
            .iter()
            .try_fold(Amount::ZERO, |acc, input| acc.checked_add(input.previous_txout().value))
            .ok_or(InternalPayloadError::FeeCalculationOverflow)?;
        let original_output_amount = sum_outputs(&self.original.original_psbt)
            .ok_or(InternalPayloadError::FeeCalculationOverflow)?;
        let proposal_output_amount =
            sum_outputs(&payjoin_psbt).ok_or(InternalPayloadError::FeeCalculationOverflow)?;
        // The sender's inputs are identical in both transactions, so the absolute fee
        // does not decrease as long as receiver inputs cover any output increase.
        let output_increase =
            proposal_output_amount.checked_sub(original_output_amount).unwrap_or(Amount::ZERO);
        if receiver_input_amount < output_increase {
            return Err(InternalPayloadError::AbsoluteFeeDecreased);
        }

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.

Updated in 06d30e4 to check receiver_input_amount < output_increase using the existing checked_sum helper in common/mod.rs.

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.

Thank you for being so on top of it! Apparently claude was wrong and this path would actually get vetted for missing utxo data and so .fee() would be fine to use here. This current check would also introduce a new potential panic path with input.previous_txout() so the original strategy is preferable. Sigh. Apologies for the misdirection.

If you could revert this in your PR that would be much appreciated otherwise I'm happy to do as a follow up.

Ok(payjoin_psbt)
}

Expand Down Expand Up @@ -846,6 +860,59 @@ mod tests {
assert_eq!(wants_inputs.proposal.receiver_inputs[1], input_pair_2);
}

#[test]
fn receiver_rejects_proposal_with_outputs_exceeding_inputs() {
let original = original_from_test_vector();
let original_output = original.psbt.unsigned_tx.output[1].clone();
let wants_outputs = WantsOutputs::new(original, vec![1]);
let replacement_output = TxOut {
value: original_output.value + Amount::ONE_SAT,
script_pubkey: original_output.script_pubkey.clone(),
};

let wants_fee_range = wants_outputs
.replace_receiver_outputs(
[replacement_output],
original_output.script_pubkey.as_script(),
)
.expect("Output replacement should succeed")
.commit_outputs()
.commit_inputs();

let result = wants_fee_range.calculate_psbt_with_fee_range(None, None);
assert!(
matches!(result, Err(InternalPayloadError::AbsoluteFeeDecreased)),
"A proposal that increases output value without receiver inputs must be rejected"
);
}

#[test]
fn receiver_accepts_output_increase_covered_by_receiver_input() {
let original = original_from_test_vector();
let original_fee = original.psbt.fee().expect("Original PSBT should have a valid fee");
let original_output = original.psbt.unsigned_tx.output[1].clone();
let increase = original_fee + Amount::ONE_SAT;

let wants_outputs = WantsOutputs::new(original, vec![1]);
let replacement_output = TxOut {
value: original_output.value + increase,
script_pubkey: original_output.script_pubkey.clone(),
};
let wants_inputs = wants_outputs
.replace_receiver_outputs(
[replacement_output],
original_output.script_pubkey.as_script(),
)
.expect("Output replacement should succeed")
.commit_outputs()
.contribute_inputs([candidate_input_from_test_vector(increase)])
.expect("An input covering the output increase should be accepted")
.commit_inputs();

let result = wants_inputs.calculate_psbt_with_fee_range(None, None);
assert!(result.is_ok(), "An input covering the output increase must be accepted");
}

#[test]
fn sender_specifies_excessive_fee_rate() {
let original = original_from_test_vector();
Expand Down
8 changes: 8 additions & 0 deletions payjoin/src/core/receive/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ pub(crate) enum InternalPayloadError {
FeeTooHigh(bitcoin::FeeRate, bitcoin::FeeRate),
/// Fee calculation overflowed in arithmetic and was incomputeable
FeeCalculationOverflow,
AbsoluteFeeDecreased,
}

impl From<&PayloadError> for JsonReply {
Expand All @@ -238,6 +239,8 @@ impl From<&PayloadError> for JsonReply {

FeeTooHigh(_, _) => JsonReply::new(NotEnoughMoney, e),

AbsoluteFeeDecreased => JsonReply::new(Unavailable, "Receiver error"),

SenderParams(e) => match e {
super::optional_parameters::Error::UnknownVersion { supported_versions } => {
let supported_versions_json =
Expand Down Expand Up @@ -281,6 +284,10 @@ impl fmt::Display for InternalPayloadError {
"Effective receiver feerate exceeds maximum allowed feerate: {proposed_fee_rate} > {max_fee_rate}"
),
FeeCalculationOverflow => write!(f, "Fee arithmetic overflow."),
AbsoluteFeeDecreased => write!(
f,
"The proposal's absolute fee cannot decrease below the original fee."
),
}
}
}
Expand All @@ -297,6 +304,7 @@ impl std::error::Error for PayloadError {
PsbtBelowFeeRate(_, _) => None,
FeeTooHigh(_, _) => None,
FeeCalculationOverflow => None,
AbsoluteFeeDecreased => None,
MissingPayment => None,
OriginalPsbtNotBroadcastable => None,
InputOwned(_) => None,
Expand Down
38 changes: 38 additions & 0 deletions payjoin/src/core/receive/v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2717,6 +2717,44 @@ pub mod test {
Ok(())
}

#[test]
fn receiver_rejects_proposal_with_outputs_exceeding_inputs() {
let persister = InMemoryPersister::default();
let original =
OriginalPayload { psbt: PARSED_ORIGINAL_PSBT.clone(), params: Params::default() };
let original_output = original.psbt.unsigned_tx.output[0].clone();
let wants_outputs =
receiver(WantsOutputs { inner: common::WantsOutputs::new(original, vec![0]) });
let replacement_output = bitcoin::TxOut {
value: original_output.value + Amount::ONE_SAT,
script_pubkey: original_output.script_pubkey.clone(),
};

let wants_inputs = wants_outputs
.replace_receiver_outputs(
[replacement_output],
original_output.script_pubkey.as_script(),
)
.expect("Output replacement should succeed")
.commit_outputs()
.save(&persister)
.expect("Outputs should be committed");
let wants_fee_range =
wants_inputs.commit_inputs().save(&persister).expect("Inputs should be committed");
let err = wants_fee_range
.apply_fee_range(None, None)
.save(&persister)
.expect_err("A proposal whose outputs exceed its inputs must be rejected");

assert!(err.is_transient());
assert!(!err.is_fatal());
assert!(matches!(
err.api_error_ref(),
Some(ProtocolError::OriginalPayload(e))
if matches!(e.0, InternalPayloadError::AbsoluteFeeDecreased)
));
}

#[test]
fn default_max_fee_rate() {
let persister = InMemoryPersister::default();
Expand Down