diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs deleted file mode 100644 index 0cbd9863..00000000 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalFinalizerTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using BTCPayServer.Plugins.Payjoin.Services; -using Xunit; - -namespace BTCPayServer.Plugins.Payjoin.Tests.Services; - -public class PayjoinReceiverProposalFinalizerTests -{ - [Fact] - public void SigningProcessPsbtReturnsStoredPsbt() - { - var processor = new PayjoinReceiverProposalFinalizer.SigningProcessPsbt("stored-psbt"); - - var result = processor.Callback("ignored"); - - Assert.Equal("stored-psbt", result); - } -} diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs index 70cd9ecc..290883a8 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverProposalSignerTests.cs @@ -60,64 +60,72 @@ public void EnsureContributedInputsPresentThrowsWhenMultipleInputsMissing() } [Fact] - public void ClearSenderInputFinalizationClearsOnlySenderInputs() + public void ContributedInputSignerSignsOnlyContributedInputs() { - // 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)) }; + // 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 - 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); + 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 ClearPartialSignaturesRemovesAllPartialSigs() + public void ContributedInputSignerThrowsWhenContributedInputMissing() { // 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)); + 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 - PayjoinReceiverProposalSigner.ClearPartialSignatures(psbt); + var exception = Assert.Throws(() => signer.Callback(psbt.ToBase64())); // Assert - Assert.Empty(psbt.Inputs[0].PartialSigs); - Assert.Empty(psbt.Inputs[1].PartialSigs); + Assert.Contains(missingOutpoint.ToString(), exception.Message, StringComparison.Ordinal); } [Fact] - public void ClearHdKeyPathsRemovesAllInputAndOutputKeyPaths() + public void ContributedInputSignerThrowsWhenContributedInputCannotFinalize() { // 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"))); + 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 - PayjoinReceiverProposalSigner.ClearHdKeyPaths(psbt); + var exception = Assert.Throws(() => signer.Callback(psbt.ToBase64())); // Assert - Assert.Empty(psbt.Inputs[0].HDKeyPaths); - Assert.Empty(psbt.Outputs[0].HDKeyPaths); + 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) @@ -133,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/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 12f31249..e9868cd4 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,29 +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); - derivationScheme.RebaseKeyPaths(proposalPsbt); - proposalPsbt.RebaseKeyPaths(signingKeySettings.AccountKey, rootedKeyPath); - proposalPsbt.SignAll(derivationScheme.AccountDerivation, accountKey, rootedKeyPath); - FinalizeContributedInputs(proposalPsbt, receiverCoins); - ClearSenderInputFinalization(proposalPsbt, receiverCoins); - ClearPartialSignatures(proposalPsbt); - ClearHdKeyPaths(proposalPsbt); - - return proposalPsbt.ToBase64(); + return new ContributedInputSigner(network.NBitcoinNetwork, accountKey, receiverCoins); } public static void EnsureContributedInputsPresent(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) @@ -103,60 +81,42 @@ public static void EnsureContributedInputsPresent(PSBT proposalPsbt, ReceivedCoi throw new InvalidOperationException($"Provisional proposal is missing contributed receiver inputs: {string.Join(", ", missingInputs)}"); } - private static void FinalizeContributedInputs(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 { - // 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)) - { - continue; - } + private readonly Network _network; + private readonly ExtKey _accountKey; + private readonly ReceivedCoin[] _receiverCoins; - if (!input.TryFinalizeInput(out _)) - { - throw new InvalidOperationException($"Receiver input '{input.PrevOut}' could not be finalized."); - } - } - } - - public static void ClearSenderInputFinalization(PSBT proposalPsbt, ReceivedCoin[] receiverCoins) - { - foreach (var input in proposalPsbt.Inputs) + public ContributedInputSigner(Network network, ExtKey accountKey, ReceivedCoin[] receiverCoins) { - if (IsContributedReceiverInput(input.PrevOut, receiverCoins)) - { - continue; - } - - input.FinalScriptSig = null; - input.FinalScriptWitness = null; + _network = network; + _accountKey = accountKey; + _receiverCoins = receiverCoins; } - } - - 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) + public string Callback(string psbt) { - input.PartialSigs.Clear(); - } - } + var proposalPsbt = PSBT.Parse(psbt, _network); + EnsureContributedInputsPresent(proposalPsbt, _receiverCoins); - public static void ClearHdKeyPaths(PSBT proposalPsbt) - { - foreach (var input in proposalPsbt.Inputs) - { - input.HDKeyPaths.Clear(); - } + foreach (var coin in _receiverCoins) + { + var contributedInput = proposalPsbt.Inputs.FindIndexedInput(coin.OutPoint)!; + + 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."); + } + } - foreach (var output in proposalPsbt.Outputs) - { - output.HDKeyPaths.Clear(); + return proposalPsbt.ToBase64(); } } }