From 45b14ab5590091556ce20292fb7fa71b3e75e953 Mon Sep 17 00:00:00 2001 From: chavic Date: Sun, 14 Jun 2026 15:41:53 +0200 Subject: [PATCH 1/3] Sign only the receiver's contributed inputs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The signer signed the whole proposal with SignAll over the store's derivation, which signs every wallet-owned input the receiver has keys for — including any the sender placed in the original PSBT — and then relied on cleanup to strip the signatures back off everything except the contributed inputs. Sign each contributed input individually instead, addressed by its outpoint and signed with the key derived from that coin's key path, so foreign and sender inputs are never signed in the first place. This mirrors BTCPayServer's core payjoin endpoint, which signs each selected UTXO individually. The post-signing normalization (finalize the contributed inputs, strip any sender-provided signatures, clear partial signatures and key paths) stays, now as a single NormalizeContributedProposalSignatures step. --- .../Services/PayjoinReceiverProposalSigner.cs | 41 +++++++++++++++---- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs index 12f31249..5ac2efc9 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs @@ -77,13 +77,25 @@ public async Task SignProposalAsync( } EnsureContributedInputsPresent(proposalPsbt, receiverCoins); - derivationScheme.RebaseKeyPaths(proposalPsbt); - proposalPsbt.RebaseKeyPaths(signingKeySettings.AccountKey, rootedKeyPath); - proposalPsbt.SignAll(derivationScheme.AccountDerivation, accountKey, rootedKeyPath); - FinalizeContributedInputs(proposalPsbt, receiverCoins); - ClearSenderInputFinalization(proposalPsbt, receiverCoins); - ClearPartialSignatures(proposalPsbt); - ClearHdKeyPaths(proposalPsbt); + + // Sign only the receiver's own contributed inputs, each addressed by its outpoint and signed with the + // key derived from that coin's key path. This replaces a SignAll over the whole derivation, which would + // sign every wallet-owned input the receiver has keys for — including any the sender placed in the + // original — and then rely on later cleanup to strip those signatures back out. Signing only the + // contributed inputs makes that guarantee structural; it mirrors BTCPayServer's core payjoin endpoint, + // which signs each selected UTXO individually. + foreach (var coin in receiverCoins) + { + var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint); + if (contributedInput is null) + { + continue; + } + + contributedInput.Sign(accountKey.Derive(coin.KeyPath).PrivateKey); + } + + NormalizeContributedProposalSignatures(proposalPsbt, receiverCoins); return proposalPsbt.ToBase64(); } @@ -103,9 +115,22 @@ public static void EnsureContributedInputsPresent(PSBT proposalPsbt, ReceivedCoi throw new InvalidOperationException($"Provisional proposal is missing contributed receiver inputs: {string.Join(", ", missingInputs)}"); } + // Enforces the invariant that the proposal returned to the sender carries signature material only on the + // receiver's own contributed inputs. SignAll may sign any wallet-owned input, so this finalizes the + // contributed inputs, strips finalized scriptSig/witness from every other input, and clears all partial + // signatures and key paths. After this runs, no signature survives on a sender (or any non-contributed) + // input. The individual steps are covered by ClearSenderInputFinalizationClearsOnlySenderInputs, + // ClearPartialSignaturesRemovesAllPartialSigs, and ClearHdKeyPathsRemovesAllInputAndOutputKeyPaths. + internal static void NormalizeContributedProposalSignatures(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) + { + FinalizeContributedInputs(proposalPsbt, receiverCoins); + ClearSenderInputFinalization(proposalPsbt, receiverCoins); + ClearPartialSignatures(proposalPsbt); + ClearHdKeyPaths(proposalPsbt); + } + private static void FinalizeContributedInputs(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) { - // TODO: Collapse the receiver-input finalization and sender-input cleanup steps into a single proposal-normalization pipeline if this PSBT policy grows further. foreach (var input in proposalPsbt.Inputs) { if (!IsContributedReceiverInput(input.PrevOut, receiverCoins)) From 592f9a41f9813caa4e9bbc87de553e2c0b2dcaec Mon Sep 17 00:00:00 2001 From: chavic Date: Thu, 18 Jun 2026 18:40:26 +0200 Subject: [PATCH 2/3] Sign inside the rust-payjoin finalize callback and drop manual stripping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The signer fetched the proposal PSBT through the public PsbtToSign() accessor, signed it externally, and handed it back through a pass-through finalize_proposal callback that ignored the PSBT the library supplied. That public accessor returns the raw payjoin PSBT with the sender's now-invalid signatures still attached, so the plugin had to strip those (plus partial signatures and key paths) by hand afterwards. Move signing into the finalize_proposal callback so it operates on the PSBT rust-payjoin hands the wallet — which already has the sender signatures cleared — and sign only the receiver's contributed inputs there. The library's prepare_psbt then drops partial signatures and key paths, so the manual stripping is removed entirely. The account key is resolved before finalize because the callback is synchronous. Because the signed PSBT now only exists after the callback runs, the expected settlement transaction is recorded from the resulting proposal after Save rather than from a pre-signed PSBT beforehand. --- .../PayjoinReceiverProposalFinalizerTests.cs | 41 +++++- .../PayjoinReceiverProposalSignerTests.cs | 61 --------- .../IPayjoinReceiverProposalSigner.cs | 6 +- .../PayjoinReceiverProposalFinalizer.cs | 53 ++++---- .../Services/PayjoinReceiverProposalSigner.cs | 127 +++++------------- 5 files changed, 102 insertions(+), 186 deletions(-) diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs index 0cbd9863..4b8c2abb 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs @@ -1,4 +1,6 @@ using BTCPayServer.Plugins.Payjoin.Services; +using BTCPayServer.Services.Wallets; +using NBitcoin; using Xunit; namespace BTCPayServer.Plugins.Payjoin.Tests.Services; @@ -6,12 +8,43 @@ namespace BTCPayServer.Plugins.Payjoin.Tests.Services; public class PayjoinReceiverProposalFinalizerTests { [Fact] - public void SigningProcessPsbtReturnsStoredPsbt() + public void ContributedInputSignerSignsOnlyContributedInputs() { - var processor = new PayjoinReceiverProposalFinalizer.SigningProcessPsbt("stored-psbt"); + // Arrange: a proposal PSBT with one receiver-contributed input and one sender input. + var network = Network.RegTest; + var accountKey = new ExtKey(); + var keyPath = new KeyPath("0/0"); + var contributedKey = accountKey.Derive(keyPath).PrivateKey; + var contributedScript = contributedKey.PubKey.WitHash.ScriptPubKey; - var result = processor.Callback("ignored"); + var contributedOutpoint = new OutPoint(uint256.Parse("1111111111111111111111111111111111111111111111111111111111111111"), 0); + var senderOutpoint = new OutPoint(uint256.Parse("2222222222222222222222222222222222222222222222222222222222222222"), 1); - Assert.Equal("stored-psbt", result); + using var sinkKey = new Key(); + var tx = network.CreateTransaction(); + tx.Inputs.Add(contributedOutpoint); + tx.Inputs.Add(senderOutpoint); + tx.Outputs.Add(Money.Coins(1.9m), sinkKey.PubKey.WitHash.ScriptPubKey); + var psbt = PSBT.FromTransaction(tx, network); + + var receivedCoin = new ReceivedCoin + { + OutPoint = contributedOutpoint, + ScriptPubKey = contributedScript, + KeyPath = keyPath, + Coin = new Coin(contributedOutpoint, new TxOut(Money.Coins(1m), contributedScript)) + }; + + var signer = new PayjoinReceiverProposalSigner.ContributedInputSigner(network, accountKey, new[] { receivedCoin }); + + // Act + var signed = PSBT.Parse(signer.Callback(psbt.ToBase64()), network); + + // Assert: the receiver's contributed input is signed and finalized; the sender input is left untouched. + var contributed = Assert.Single(signed.Inputs, i => i.PrevOut == contributedOutpoint); + var sender = Assert.Single(signed.Inputs, i => i.PrevOut == senderOutpoint); + Assert.NotNull(contributed.FinalScriptWitness); + Assert.Null(sender.FinalScriptWitness); + Assert.Null(sender.FinalScriptSig); } } diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs index 70cd9ecc..b7f1abd8 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs @@ -59,67 +59,6 @@ public void EnsureContributedInputsPresentThrowsWhenMultipleInputsMissing() Assert.Contains(missingOutPoint2.ToString(), exception.Message, StringComparison.Ordinal); } - [Fact] - public void ClearSenderInputFinalizationClearsOnlySenderInputs() - { - // Arrange - var receiverOutPoint = new OutPoint(uint256.Parse("4444444444444444444444444444444444444444444444444444444444444444"), 0); - var senderOutPoint = new OutPoint(uint256.Parse("5555555555555555555555555555555555555555555555555555555555555555"), 1); - var psbt = CreatePsbtWithInputs(receiverOutPoint, senderOutPoint); - psbt.Inputs[0].FinalScriptSig = Script.Empty; - psbt.Inputs[0].FinalScriptWitness = WitScript.Empty; - psbt.Inputs[1].FinalScriptSig = Script.Empty; - psbt.Inputs[1].FinalScriptWitness = WitScript.Empty; - var receivedCoins = new[] { CreateReceivedCoin(receiverOutPoint, Money.Satoshis(20_000), CreateScript(3)) }; - - // Act - PayjoinReceiverProposalSigner.ClearSenderInputFinalization(psbt, receivedCoins); - - // Assert - Assert.NotNull(psbt.Inputs[0].FinalScriptSig); - Assert.NotNull(psbt.Inputs[0].FinalScriptWitness); - Assert.Null(psbt.Inputs[1].FinalScriptSig); - Assert.Null(psbt.Inputs[1].FinalScriptWitness); - } - - [Fact] - public void ClearPartialSignaturesRemovesAllPartialSigs() - { - // Arrange - var psbt = CreatePsbtWithInputs( - new OutPoint(uint256.Parse("6666666666666666666666666666666666666666666666666666666666666666"), 0), - new OutPoint(uint256.Parse("7777777777777777777777777777777777777777777777777777777777777777"), 1)); - using var key1 = new Key(); - using var key2 = new Key(); - psbt.Inputs[0].PartialSigs.Add(key1.PubKey, new TransactionSignature(key1.Sign(uint256.One), SigHash.All)); - psbt.Inputs[1].PartialSigs.Add(key2.PubKey, new TransactionSignature(key2.Sign(uint256.One), SigHash.All)); - - // Act - PayjoinReceiverProposalSigner.ClearPartialSignatures(psbt); - - // Assert - Assert.Empty(psbt.Inputs[0].PartialSigs); - Assert.Empty(psbt.Inputs[1].PartialSigs); - } - - [Fact] - public void ClearHdKeyPathsRemovesAllInputAndOutputKeyPaths() - { - // Arrange - var psbt = CreatePsbtWithInputs(new OutPoint(uint256.Parse("8888888888888888888888888888888888888888888888888888888888888888"), 0)); - using var key = new Key(); - var fingerprint = new HDFingerprint(new byte[] { 1, 2, 3, 4 }); - psbt.Inputs[0].HDKeyPaths.Add(key.PubKey, new RootedKeyPath(fingerprint, new KeyPath("0/0"))); - psbt.Outputs[0].HDKeyPaths.Add(key.PubKey, new RootedKeyPath(fingerprint, new KeyPath("1/0"))); - - // Act - PayjoinReceiverProposalSigner.ClearHdKeyPaths(psbt); - - // Assert - Assert.Empty(psbt.Inputs[0].HDKeyPaths); - Assert.Empty(psbt.Outputs[0].HDKeyPaths); - } - private static PSBT CreatePsbtWithInputs(params OutPoint[] outPoints) { var network = Network.RegTest; diff --git a/BTCPayServer.Plugins.Payjoin/Services/IPayjoinReceiverProposalSigner.cs b/BTCPayServer.Plugins.Payjoin/Services/IPayjoinReceiverProposalSigner.cs index 6f6ecfc1..d800d8b4 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/IPayjoinReceiverProposalSigner.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/IPayjoinReceiverProposalSigner.cs @@ -7,8 +7,10 @@ namespace BTCPayServer.Plugins.Payjoin.Services; internal interface IPayjoinReceiverProposalSigner { - Task SignProposalAsync( - ProvisionalProposal proposal, + // Resolves the hot-wallet account key (async) and returns a synchronous signer for rust-payjoin's + // finalize_proposal callback, which signs only the receiver's contributed inputs on the library-supplied + // PSBT. The library handles sender-signature removal and field filtering, so no manual stripping is done. + Task CreateContributedInputSignerAsync( string storeId, ReceivedCoin[] receiverCoins, CancellationToken cancellationToken); diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs index 3395e2ac..ba635d29 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs @@ -48,25 +48,40 @@ public async Task FinalizeAsync( ReceivedCoin[] receiverCoins, CancellationToken cancellationToken) { - var signedPsbt = await _proposalSigner.SignProposalAsync(proposal, context.StoreId, receiverCoins, cancellationToken).ConfigureAwait(false); var btcPayNetwork = _networkProvider.GetNetwork(context.CryptoCode) ?? throw new InvalidOperationException($"Network '{context.CryptoCode}' is not available."); var network = btcPayNetwork.NBitcoinNetwork; - var finalTransaction = PSBT.Parse(signedPsbt, network).GetGlobalTransaction(); + + var signer = await _proposalSigner.CreateContributedInputSignerAsync(context.StoreId, receiverCoins, cancellationToken).ConfigureAwait(false); + using var transition = proposal.FinalizeProposal(signer); + using var payjoinProposal = transition.Save(context.Persister); + + await RecordExpectedFinalTransactionAsync(context, payjoinProposal, network, cancellationToken).ConfigureAwait(false); + await PostAsync(context, payjoinProposal, cancellationToken).ConfigureAwait(false); + } + + private async Task RecordExpectedFinalTransactionAsync( + PayjoinReceiverProposalFinalizationContext context, + PayjoinProposal payjoinProposal, + Network network, + CancellationToken cancellationToken) + { + // The signed PSBT only exists after finalize_proposal runs the signing callback, so the expected + // settlement transaction is recorded here (after Save) from the resulting proposal rather than before. var bridge = await _accountingBridgeService.TryGetByInvoiceIdAsync(context.InvoiceId, cancellationToken).ConfigureAwait(false); - if (bridge is not null) + if (bridge is null) { - var expectedFinalOutput = TryGetSettlementOutput(bridge, finalTransaction); - await _accountingBridgeService.SetExpectedFinalTransactionAsync( - context.InvoiceId, - finalTransaction.GetHash().ToString(), - expectedFinalOutput?.Index, - bridge.EffectiveInvoiceValueSats ?? expectedFinalOutput?.ValueSats ?? bridge.FallbackValueSats, - cancellationToken).ConfigureAwait(false); + return; } - using var transition = proposal.FinalizeProposal(new SigningProcessPsbt(signedPsbt)); - using var payjoinProposal = transition.Save(context.Persister); - await PostAsync(context, payjoinProposal, cancellationToken).ConfigureAwait(false); + + var finalTransaction = PSBT.Parse(payjoinProposal.Psbt(), network).GetGlobalTransaction(); + var expectedFinalOutput = TryGetSettlementOutput(bridge, finalTransaction); + await _accountingBridgeService.SetExpectedFinalTransactionAsync( + context.InvoiceId, + finalTransaction.GetHash().ToString(), + expectedFinalOutput?.Index, + bridge.EffectiveInvoiceValueSats ?? expectedFinalOutput?.ValueSats ?? bridge.FallbackValueSats, + cancellationToken).ConfigureAwait(false); } public async Task PostAsync( @@ -105,16 +120,4 @@ public async Task PostAsync( } private sealed record ExpectedFinalOutput(int Index, long ValueSats, Script ScriptPubKey); - - internal sealed class SigningProcessPsbt : ProcessPsbt - { - private readonly string _signedPsbt; - - public SigningProcessPsbt(string signedPsbt) - { - _signedPsbt = signedPsbt; - } - - public string Callback(string _psbt) => _signedPsbt; - } } diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs index 5ac2efc9..3e3b5e54 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs @@ -32,8 +32,7 @@ public PayjoinReceiverProposalSigner( _explorerClientProvider = explorerClientProvider; } - public async Task SignProposalAsync( - ProvisionalProposal proposal, + public async Task CreateContributedInputSignerAsync( string storeId, ReceivedCoin[] receiverCoins, CancellationToken cancellationToken) @@ -63,41 +62,8 @@ public async Task SignProposalAsync( var signingKeySettings = derivationScheme.GetAccountKeySettingsFromRoot(signingKey) ?? throw new InvalidOperationException("Wallet key settings not available"); var rootedKeyPath = signingKeySettings.GetRootedKeyPath() ?? throw new InvalidOperationException("Wallet key path mismatch"); var accountKey = signingKey.Derive(rootedKeyPath.KeyPath); - var psbtToSign = proposal.PsbtToSign(); - var proposalPsbt = PSBT.Parse(psbtToSign, network.NBitcoinNetwork); - var updated = await client.UpdatePSBTAsync(new NBXplorer.Models.UpdatePSBTRequest - { - PSBT = proposalPsbt, - DerivationScheme = derivationScheme.AccountDerivation - }, cancellationToken).ConfigureAwait(false); - if (updated?.PSBT is not null) - { - proposalPsbt = updated.PSBT; - } - - EnsureContributedInputsPresent(proposalPsbt, receiverCoins); - - // Sign only the receiver's own contributed inputs, each addressed by its outpoint and signed with the - // key derived from that coin's key path. This replaces a SignAll over the whole derivation, which would - // sign every wallet-owned input the receiver has keys for — including any the sender placed in the - // original — and then rely on later cleanup to strip those signatures back out. Signing only the - // contributed inputs makes that guarantee structural; it mirrors BTCPayServer's core payjoin endpoint, - // which signs each selected UTXO individually. - foreach (var coin in receiverCoins) - { - var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint); - if (contributedInput is null) - { - continue; - } - - contributedInput.Sign(accountKey.Derive(coin.KeyPath).PrivateKey); - } - - NormalizeContributedProposalSignatures(proposalPsbt, receiverCoins); - - return proposalPsbt.ToBase64(); + return new ContributedInputSigner(network.NBitcoinNetwork, accountKey, receiverCoins); } public static void EnsureContributedInputsPresent(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) @@ -115,73 +81,46 @@ public static void EnsureContributedInputsPresent(PSBT proposalPsbt, ReceivedCoi throw new InvalidOperationException($"Provisional proposal is missing contributed receiver inputs: {string.Join(", ", missingInputs)}"); } - // Enforces the invariant that the proposal returned to the sender carries signature material only on the - // receiver's own contributed inputs. SignAll may sign any wallet-owned input, so this finalizes the - // contributed inputs, strips finalized scriptSig/witness from every other input, and clears all partial - // signatures and key paths. After this runs, no signature survives on a sender (or any non-contributed) - // input. The individual steps are covered by ClearSenderInputFinalizationClearsOnlySenderInputs, - // ClearPartialSignaturesRemovesAllPartialSigs, and ClearHdKeyPathsRemovesAllInputAndOutputKeyPaths. - internal static void NormalizeContributedProposalSignatures(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) + // Signs only the receiver's contributed inputs on the PSBT that rust-payjoin hands to the wallet during + // finalize_proposal. That PSBT already has the sender's now-invalid signatures cleared by the library + // (psbt_to_sign), and the library's prepare_psbt drops partial signatures and key paths afterwards. So the + // receiver never signs a foreign input and no manual stripping is required. The account key is resolved + // ahead of time (CreateContributedInputSignerAsync) because this callback is synchronous. + internal sealed class ContributedInputSigner : ProcessPsbt { - FinalizeContributedInputs(proposalPsbt, receiverCoins); - ClearSenderInputFinalization(proposalPsbt, receiverCoins); - ClearPartialSignatures(proposalPsbt); - ClearHdKeyPaths(proposalPsbt); - } + private readonly Network _network; + private readonly ExtKey _accountKey; + private readonly ReceivedCoin[] _receiverCoins; - private static void FinalizeContributedInputs(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) - { - foreach (var input in proposalPsbt.Inputs) + public ContributedInputSigner(Network network, ExtKey accountKey, ReceivedCoin[] receiverCoins) { - if (!IsContributedReceiverInput(input.PrevOut, receiverCoins)) - { - continue; - } - - if (!input.TryFinalizeInput(out _)) - { - throw new InvalidOperationException($"Receiver input '{input.PrevOut}' could not be finalized."); - } + _network = network; + _accountKey = accountKey; + _receiverCoins = receiverCoins; } - } - public static void ClearSenderInputFinalization(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) - { - foreach (var input in proposalPsbt.Inputs) + public string Callback(string psbt) { - if (IsContributedReceiverInput(input.PrevOut, receiverCoins)) + var proposalPsbt = PSBT.Parse(psbt, _network); + EnsureContributedInputsPresent(proposalPsbt, _receiverCoins); + + foreach (var coin in _receiverCoins) { - continue; + var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint); + if (contributedInput is null) + { + continue; + } + + contributedInput.UpdateFromCoin(coin.Coin); + contributedInput.Sign(_accountKey.Derive(coin.KeyPath).PrivateKey); + if (!contributedInput.TryFinalizeInput(out _)) + { + throw new InvalidOperationException($"Receiver input '{coin.OutPoint}' could not be finalized."); + } } - input.FinalScriptSig = null; - input.FinalScriptWitness = null; - } - } - - private static bool IsContributedReceiverInput(NBitcoin.OutPoint prevOut, ReceivedCoin[] receiverCoins) - { - return receiverCoins.Any(receiverCoin => receiverCoin.OutPoint == prevOut); - } - - public static void ClearPartialSignatures(PSBT proposalPsbt) - { - foreach (var input in proposalPsbt.Inputs) - { - input.PartialSigs.Clear(); - } - } - - public static void ClearHdKeyPaths(PSBT proposalPsbt) - { - foreach (var input in proposalPsbt.Inputs) - { - input.HDKeyPaths.Clear(); - } - - foreach (var output in proposalPsbt.Outputs) - { - output.HDKeyPaths.Clear(); + return proposalPsbt.ToBase64(); } } } From 8314dcbb70770b0ab83662486c0384d957d99ba0 Mon Sep 17 00:00:00 2001 From: chavic Date: Wed, 24 Jun 2026 14:35:39 +0200 Subject: [PATCH 3/3] Address signer callback review feedback --- .../PayjoinReceiverProposalFinalizerTests.cs | 50 ------------- .../PayjoinReceiverProposalSignerTests.cs | 72 ++++++++++++++++++- .../Services/PayjoinReceiverProposalSigner.cs | 6 +- 3 files changed, 72 insertions(+), 56 deletions(-) delete mode 100644 BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs deleted file mode 100644 index 4b8c2abb..00000000 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -using BTCPayServer.Plugins.Payjoin.Services; -using BTCPayServer.Services.Wallets; -using NBitcoin; -using Xunit; - -namespace BTCPayServer.Plugins.Payjoin.Tests.Services; - -public class PayjoinReceiverProposalFinalizerTests -{ - [Fact] - public void ContributedInputSignerSignsOnlyContributedInputs() - { - // Arrange: a proposal PSBT with one receiver-contributed input and one sender input. - var network = Network.RegTest; - var accountKey = new ExtKey(); - var keyPath = new KeyPath("0/0"); - var contributedKey = accountKey.Derive(keyPath).PrivateKey; - var contributedScript = contributedKey.PubKey.WitHash.ScriptPubKey; - - var contributedOutpoint = new OutPoint(uint256.Parse("1111111111111111111111111111111111111111111111111111111111111111"), 0); - var senderOutpoint = new OutPoint(uint256.Parse("2222222222222222222222222222222222222222222222222222222222222222"), 1); - - using var sinkKey = new Key(); - var tx = network.CreateTransaction(); - tx.Inputs.Add(contributedOutpoint); - tx.Inputs.Add(senderOutpoint); - tx.Outputs.Add(Money.Coins(1.9m), sinkKey.PubKey.WitHash.ScriptPubKey); - var psbt = PSBT.FromTransaction(tx, network); - - var receivedCoin = new ReceivedCoin - { - OutPoint = contributedOutpoint, - ScriptPubKey = contributedScript, - KeyPath = keyPath, - Coin = new Coin(contributedOutpoint, new TxOut(Money.Coins(1m), contributedScript)) - }; - - var signer = new PayjoinReceiverProposalSigner.ContributedInputSigner(network, accountKey, new[] { receivedCoin }); - - // Act - var signed = PSBT.Parse(signer.Callback(psbt.ToBase64()), network); - - // Assert: the receiver's contributed input is signed and finalized; the sender input is left untouched. - var contributed = Assert.Single(signed.Inputs, i => i.PrevOut == contributedOutpoint); - var sender = Assert.Single(signed.Inputs, i => i.PrevOut == senderOutpoint); - Assert.NotNull(contributed.FinalScriptWitness); - Assert.Null(sender.FinalScriptWitness); - Assert.Null(sender.FinalScriptSig); - } -} diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs index b7f1abd8..290883a8 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs @@ -59,6 +59,75 @@ public void EnsureContributedInputsPresentThrowsWhenMultipleInputsMissing() Assert.Contains(missingOutPoint2.ToString(), exception.Message, StringComparison.Ordinal); } + [Fact] + public void ContributedInputSignerSignsOnlyContributedInputs() + { + // Arrange: a proposal PSBT with one receiver-contributed input and one sender input. + var network = Network.RegTest; + var accountKey = new ExtKey(); + var keyPath = new KeyPath("0/0"); + var contributedKey = accountKey.Derive(keyPath).PrivateKey; + var contributedScript = contributedKey.PubKey.WitHash.ScriptPubKey; + var contributedOutpoint = new OutPoint(uint256.Parse("1111111111111111111111111111111111111111111111111111111111111111"), 0); + var senderOutpoint = new OutPoint(uint256.Parse("2222222222222222222222222222222222222222222222222222222222222222"), 1); + var psbt = CreatePsbtWithInputs(contributedOutpoint, senderOutpoint); + var receivedCoin = CreateReceivedCoin(contributedOutpoint, Money.Coins(1m), contributedScript, keyPath); + var signer = new PayjoinReceiverProposalSigner.ContributedInputSigner(network, accountKey, new[] { receivedCoin }); + + // Act + var signed = PSBT.Parse(signer.Callback(psbt.ToBase64()), network); + + // Assert: the receiver's contributed input is signed and finalized; the sender input is left untouched. + var contributed = Assert.Single(signed.Inputs, i => i.PrevOut == contributedOutpoint); + var sender = Assert.Single(signed.Inputs, i => i.PrevOut == senderOutpoint); + Assert.NotNull(contributed.FinalScriptWitness); + Assert.Null(sender.FinalScriptWitness); + Assert.Null(sender.FinalScriptSig); + } + + [Fact] + public void ContributedInputSignerThrowsWhenContributedInputMissing() + { + // Arrange + var network = Network.RegTest; + var accountKey = new ExtKey(); + var keyPath = new KeyPath("0/0"); + var missingOutpoint = new OutPoint(uint256.Parse("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"), 0); + var proposalOutpoint = new OutPoint(uint256.Parse("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"), 1); + var script = accountKey.Derive(keyPath).PrivateKey.PubKey.WitHash.ScriptPubKey; + var psbt = CreatePsbtWithInputs(proposalOutpoint); + var receivedCoin = CreateReceivedCoin(missingOutpoint, Money.Satoshis(50_000), script, keyPath); + var signer = new PayjoinReceiverProposalSigner.ContributedInputSigner(network, accountKey, new[] { receivedCoin }); + + // Act + var exception = Assert.Throws(() => signer.Callback(psbt.ToBase64())); + + // Assert + Assert.Contains(missingOutpoint.ToString(), exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void ContributedInputSignerThrowsWhenContributedInputCannotFinalize() + { + // Arrange + var network = Network.RegTest; + var accountKey = new ExtKey(); + var keyPath = new KeyPath("0/0"); + var contributedOutpoint = new OutPoint(uint256.Parse("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), 0); + using var unrelatedKey = new Key(); + var unrelatedScript = unrelatedKey.PubKey.WitHash.ScriptPubKey; + var psbt = CreatePsbtWithInputs(contributedOutpoint); + var receivedCoin = CreateReceivedCoin(contributedOutpoint, Money.Satoshis(50_000), unrelatedScript, keyPath); + var signer = new PayjoinReceiverProposalSigner.ContributedInputSigner(network, accountKey, new[] { receivedCoin }); + + // Act + var exception = Assert.Throws(() => signer.Callback(psbt.ToBase64())); + + // Assert + Assert.Contains("could not be finalized", exception.Message, StringComparison.Ordinal); + Assert.Contains(contributedOutpoint.ToString(), exception.Message, StringComparison.Ordinal); + } + private static PSBT CreatePsbtWithInputs(params OutPoint[] outPoints) { var network = Network.RegTest; @@ -72,12 +141,13 @@ private static PSBT CreatePsbtWithInputs(params OutPoint[] outPoints) return PSBT.FromTransaction(transaction, network); } - private static ReceivedCoin CreateReceivedCoin(OutPoint outPoint, Money amount, Script scriptPubKey) + private static ReceivedCoin CreateReceivedCoin(OutPoint outPoint, Money amount, Script scriptPubKey, KeyPath? keyPath = null) { return new ReceivedCoin { OutPoint = outPoint, ScriptPubKey = scriptPubKey, + KeyPath = keyPath ?? KeyPath.Empty, Value = amount, Coin = new Coin(outPoint, new TxOut(amount, scriptPubKey)), Timestamp = DateTimeOffset.UtcNow, diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs index 3e3b5e54..e9868cd4 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalSigner.cs @@ -106,11 +106,7 @@ public string Callback(string psbt) foreach (var coin in _receiverCoins) { - var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint); - if (contributedInput is null) - { - continue; - } + var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint)!; contributedInput.UpdateFromCoin(coin.Coin); contributedInput.Sign(_accountKey.Derive(coin.KeyPath).PrivateKey);