From ac970911b17ccecd66b21788ff0b7901e123916a Mon Sep 17 00:00:00 2001 From: chavic Date: Thu, 2 Jul 2026 15:39:00 +0200 Subject: [PATCH 1/5] Update rust-payjoin for the InputPair outpoint FFI Point the rust-payjoin submodule at upstream payjoin/rust-payjoin master commit f4a6008a, which includes the merged InputPair outpoint accessor (payjoin/rust-payjoin#1654). The previously tracked fork branch does not contain that change yet. Between the old pin and f4a6008a upstream upgraded uniffi to 0.31.2, which renamed the generated C# record accessors from camelCase fields to PascalCase properties, so the plugin call sites are renamed to match. --- .gitmodules | 4 ++-- .../TestUtils/PayjoinTestPayer.cs | 22 +++++++++---------- .../PayjoinReceiverOutputBuilderTests.cs | 8 +++---- .../PayjoinReceiverProposalFinalizer.cs | 8 +++---- .../PayjoinReceiverSessionProcessor.cs | 22 +++++++++---------- .../Services/PayjoinReceiverStateProcessor.cs | 22 +++++++++---------- .../Services/RunTestPaymentService.cs | 18 +++++++-------- rust-payjoin | 2 +- 8 files changed, 53 insertions(+), 53 deletions(-) diff --git a/.gitmodules b/.gitmodules index 7d89bd4f..6e761c88 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,5 +3,5 @@ url = https://github.com/ValeraFinebits/btcpayserver [submodule "rust-payjoin"] path = rust-payjoin - url = https://github.com/ValeraFinebits/rust-payjoin.git - branch = feat/csharp-ffi-bindings + url = https://github.com/payjoin/rust-payjoin.git + branch = master diff --git a/BTCPayServer.Plugins.Payjoin.IntegrationTests/TestUtils/PayjoinTestPayer.cs b/BTCPayServer.Plugins.Payjoin.IntegrationTests/TestUtils/PayjoinTestPayer.cs index 3142695a..3d6a3b50 100644 --- a/BTCPayServer.Plugins.Payjoin.IntegrationTests/TestUtils/PayjoinTestPayer.cs +++ b/BTCPayServer.Plugins.Payjoin.IntegrationTests/TestUtils/PayjoinTestPayer.cs @@ -193,8 +193,8 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh using var withReplyKey = initial.Save(senderPersister); using var postContext = withReplyKey.CreateV2PostRequest(ohttpRelayUrl.ToString()); - var postResponse = await SendRequestAsync(postContext.request, cancellationToken).ConfigureAwait(false); - using var withReplyTransition = withReplyKey.ProcessResponse(postResponse, postContext.ohttpCtx); + var postResponse = await SendRequestAsync(postContext.Request, cancellationToken).ConfigureAwait(false); + using var withReplyTransition = withReplyKey.ProcessResponse(postResponse, postContext.OhttpCtx); try { @@ -242,8 +242,8 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh for (var attempt = 0; attempt < MaxProposalPollAttempts; attempt++) { using var pollRequest = current.CreatePollRequest(ohttpRelayUrl.ToString()); - var pollResponse = await SendRequestAsync(pollRequest.request, cancellationToken).ConfigureAwait(false); - using var pollTransition = current.ProcessResponse(pollResponse, pollRequest.ohttpCtx); + var pollResponse = await SendRequestAsync(pollRequest.Request, cancellationToken).ConfigureAwait(false); + using var pollTransition = current.ProcessResponse(pollResponse, pollRequest.OhttpCtx); var outcome = pollTransition.Save(senderPersister); @@ -252,11 +252,11 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh switch (outcome) { case PollingForProposalTransitionOutcome.Progress progress: - proposalPsbtBase64 = progress.psbtBase64; + proposalPsbtBase64 = progress.PsbtBase64; break; case PollingForProposalTransitionOutcome.Stasis stasis: current.Dispose(); - current = stasis.inner; + current = stasis.Inner; outcome = null; break; } @@ -302,11 +302,11 @@ private static string FormatSenderResponseException(global::Payjoin.ResponseExce private async Task SendRequestAsync(Request request, CancellationToken cancellationToken) { - using var message = new HttpRequestMessage(HttpMethod.Post, request.url) + using var message = new HttpRequestMessage(HttpMethod.Post, request.Url) { - Content = new ByteArrayContent(request.body) + Content = new ByteArrayContent(request.Body) }; - message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.contentType); + message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.ContentType); var client = _httpClientFactory.CreateClient(nameof(PayjoinTestPayer)); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -321,7 +321,7 @@ private async Task SendRequestAsync(Request request, CancellationToken c } catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested) { - throw new InvalidOperationException($"Payjoin HTTP request timed out after {RelayRequestTimeout.TotalSeconds:0} seconds. RequestUrl='{request.url}', RequestContentType='{request.contentType}'.", ex); + throw new InvalidOperationException($"Payjoin HTTP request timed out after {RelayRequestTimeout.TotalSeconds:0} seconds. RequestUrl='{request.Url}', RequestContentType='{request.ContentType}'.", ex); } using (response) @@ -341,7 +341,7 @@ private static InvalidOperationException CreateHttpRequestFailure(Request reques var diagnosticBody = FormatResponseBody(responseBody, responseContentType); return new InvalidOperationException( - $"Payjoin HTTP request failed. RequestUrl='{request.url}', RequestContentType='{request.contentType}', ResponseStatusCode={(int)response.StatusCode} ({response.StatusCode}), ResponseContentType='{responseContentType}', ResponseBody='{diagnosticBody}'."); + $"Payjoin HTTP request failed. RequestUrl='{request.Url}', RequestContentType='{request.ContentType}', ResponseStatusCode={(int)response.StatusCode} ({response.StatusCode}), ResponseContentType='{responseContentType}', ResponseBody='{diagnosticBody}'."); } private static string FormatResponseBody(byte[] responseBody, string responseContentType) diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverOutputBuilderTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverOutputBuilderTests.cs index 44ec89c3..4b9cc308 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverOutputBuilderTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverOutputBuilderTests.cs @@ -17,8 +17,8 @@ public void CreateSettlementOutputsCreatesSingleSettlementOutput() // Assert Assert.Equal(settlementScript, result.SettlementScript); Assert.Single(result.ReplacementOutputs); - Assert.Equal(50_000UL, result.ReplacementOutputs[0].valueSat); - Assert.Equal(settlementScript, result.ReplacementOutputs[0].scriptPubkey); + Assert.Equal(50_000UL, result.ReplacementOutputs[0].ValueSat); + Assert.Equal(settlementScript, result.ReplacementOutputs[0].ScriptPubkey); } [Fact] @@ -30,7 +30,7 @@ public void CreateSettlementOutputsSupportsPreservingReceiverScript() Assert.Equal(receiverScript, result.SettlementScript); Assert.Single(result.ReplacementOutputs); - Assert.Equal(75_000UL, result.ReplacementOutputs[0].valueSat); - Assert.Equal(receiverScript, result.ReplacementOutputs[0].scriptPubkey); + Assert.Equal(75_000UL, result.ReplacementOutputs[0].ValueSat); + Assert.Equal(receiverScript, result.ReplacementOutputs[0].ScriptPubkey); } } diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs index ba635d29..912c82d8 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverProposalFinalizer.cs @@ -91,12 +91,12 @@ public async Task PostAsync( { using var requestResponse = proposal.CreatePostRequest(context.OhttpRelayUrl.ToString()); var responseBody = await _relayClient.SendAsync( - new SystemUri(requestResponse.request.url, UriKind.Absolute), - requestResponse.request.contentType, - requestResponse.request.body, + new SystemUri(requestResponse.Request.Url, UriKind.Absolute), + requestResponse.Request.ContentType, + requestResponse.Request.Body, cancellationToken).ConfigureAwait(false); - using var transition = proposal.ProcessResponse(responseBody, requestResponse.clientResponse); + using var transition = proposal.ProcessResponse(responseBody, requestResponse.ClientResponse); using var _ = transition.Save(context.Persister); } diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs index ce56e638..7f4cd9dc 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs @@ -158,7 +158,7 @@ private async Task ProcessSessionAsync(PayjoinReceiverSessionState session, Canc case ReceiveSession.Initialized initialized: try { - await _stateProcessor.ProcessInitializedAsync(stateContext, initialized.inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessInitializedAsync(stateContext, initialized.Inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); } catch (PayjoinReceiverRelayTimeoutException ex) { @@ -167,25 +167,25 @@ private async Task ProcessSessionAsync(PayjoinReceiverSessionState session, Canc break; case ReceiveSession.HasReplyableError hasReplyableError: - await _stateProcessor.ProcessReplyableErrorAsync(stateContext, hasReplyableError.inner, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessReplyableErrorAsync(stateContext, hasReplyableError.Inner, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.UncheckedOriginalPayload payload: - await _stateProcessor.ProcessUncheckedProposalAsync(stateContext, payload.inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessUncheckedProposalAsync(stateContext, payload.Inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.MaybeInputsOwned maybeInputsOwned: - await _stateProcessor.ProcessMaybeInputsOwnedAsync(stateContext, maybeInputsOwned.inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessMaybeInputsOwnedAsync(stateContext, maybeInputsOwned.Inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.MaybeInputsSeen maybeInputsSeen: - await _stateProcessor.ProcessMaybeInputsSeenAsync(stateContext, maybeInputsSeen.inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessMaybeInputsSeenAsync(stateContext, maybeInputsSeen.Inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.OutputsUnknown outputsUnknown: - await _stateProcessor.ProcessOutputsUnknownAsync(stateContext, outputsUnknown.inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); + await _stateProcessor.ProcessOutputsUnknownAsync(stateContext, outputsUnknown.Inner, ContinueWithOutputsAsync, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.WantsOutputs wantsOutputs: - await ContinueWithOutputsAsync(wantsOutputs.inner, stateContext, stoppingToken).ConfigureAwait(false); + await ContinueWithOutputsAsync(wantsOutputs.Inner, stateContext, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.WantsInputs wantsInputs: - await ProcessWantsInputsAsync(wantsInputs.inner, persister, receiverScript, session.OhttpRelayUrl!, session.StoreId, session.InvoiceId, GetReservationExpiresAt(session), stoppingToken).ConfigureAwait(false); + await ProcessWantsInputsAsync(wantsInputs.Inner, persister, receiverScript, session.OhttpRelayUrl!, session.StoreId, session.InvoiceId, GetReservationExpiresAt(session), stoppingToken).ConfigureAwait(false); break; case ReceiveSession.WantsFeeRange wantsFeeRange: { @@ -197,7 +197,7 @@ private async Task ProcessSessionAsync(PayjoinReceiverSessionState session, Canc await _proposalFinalizer.FinalizeAsync( new PayjoinReceiverProposalFinalizationContext(persister, session.OhttpRelayUrl!, session.StoreId, session.InvoiceId, PayjoinConstants.BitcoinCode), - wantsFeeRange.inner, + wantsFeeRange.Inner, contributedCoinsForFeeRange, stoppingToken).ConfigureAwait(false); break; @@ -212,7 +212,7 @@ await _proposalFinalizer.FinalizeAsync( await _proposalFinalizer.FinalizeAsync( new PayjoinReceiverProposalFinalizationContext(persister, session.OhttpRelayUrl!, session.StoreId, session.InvoiceId, PayjoinConstants.BitcoinCode), - provisionalProposal.inner, + provisionalProposal.Inner, contributedCoinsForProposal, stoppingToken).ConfigureAwait(false); break; @@ -220,7 +220,7 @@ await _proposalFinalizer.FinalizeAsync( case ReceiveSession.PayjoinProposal payjoinProposal: await _proposalFinalizer.PostAsync( new PayjoinReceiverProposalFinalizationContext(persister, session.OhttpRelayUrl!, session.StoreId, session.InvoiceId, PayjoinConstants.BitcoinCode), - payjoinProposal.inner, + payjoinProposal.Inner, stoppingToken).ConfigureAwait(false); break; case ReceiveSession.Monitor: diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverStateProcessor.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverStateProcessor.cs index 0f21bf5e..990ee379 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverStateProcessor.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverStateProcessor.cs @@ -40,17 +40,17 @@ public async Task ProcessInitializedAsync( using var requestResponse = initialized.CreatePollRequest(context.OhttpRelayUrl.ToString()); var responseBody = await _relayClient.SendAsync( - new SystemUri(requestResponse.request.url, UriKind.Absolute), - requestResponse.request.contentType, - requestResponse.request.body, + new SystemUri(requestResponse.Request.Url, UriKind.Absolute), + requestResponse.Request.ContentType, + requestResponse.Request.Body, cancellationToken).ConfigureAwait(false); - using var transition = initialized.ProcessResponse(responseBody, requestResponse.clientResponse); + using var transition = initialized.ProcessResponse(responseBody, requestResponse.ClientResponse); using var outcome = transition.Save(context.Persister); if (outcome is InitializedTransitionOutcome.Progress progress) { - await ProcessUncheckedProposalAsync(context, progress.inner, continueWithOutputsAsync, cancellationToken).ConfigureAwait(false); + await ProcessUncheckedProposalAsync(context, progress.Inner, continueWithOutputsAsync, cancellationToken).ConfigureAwait(false); } } @@ -61,11 +61,11 @@ public async Task ProcessReplyableErrorAsync( { using var requestResponse = replyableError.CreateErrorRequest(context.OhttpRelayUrl.ToString()); var responseBody = await _relayClient.SendAsync( - new SystemUri(requestResponse.request.url, UriKind.Absolute), - requestResponse.request.contentType, - requestResponse.request.body, + new SystemUri(requestResponse.Request.Url, UriKind.Absolute), + requestResponse.Request.ContentType, + requestResponse.Request.Body, cancellationToken).ConfigureAwait(false); - using var transition = replyableError.ProcessErrorResponse(responseBody, requestResponse.clientResponse); + using var transition = replyableError.ProcessErrorResponse(responseBody, requestResponse.ClientResponse); transition.Save(context.Persister); } @@ -213,7 +213,7 @@ private async Task TryPostPersistedReplyableErrorAsync( return false; } - await ProcessReplyableErrorAsync(context, hasReplyableError.inner, cancellationToken).ConfigureAwait(false); + await ProcessReplyableErrorAsync(context, hasReplyableError.Inner, cancellationToken).ConfigureAwait(false); return true; } @@ -244,7 +244,7 @@ public PersistentInputsSeenCallback(PayjoinSeenInputStore seenInputStore) } public bool Callback(OutPoint outpoint) => - _seenInputStore.MarkSeenAndWasPresent(outpoint.txid, checked((long)outpoint.vout)); + _seenInputStore.MarkSeenAndWasPresent(outpoint.Txid, checked((long)outpoint.Vout)); } internal sealed class CloseRequestedBroadcastGuard : CanBroadcast diff --git a/BTCPayServer.Plugins.Payjoin/Services/RunTestPaymentService.cs b/BTCPayServer.Plugins.Payjoin/Services/RunTestPaymentService.cs index 9c9fc93e..32bee243 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/RunTestPaymentService.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/RunTestPaymentService.cs @@ -205,8 +205,8 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh using var withReplyKey = initial.Save(senderPersister); using var postContext = withReplyKey.CreateV2PostRequest(ohttpRelayUrl.ToString()); - var postResponse = await SendRequestAsync(postContext.request, cancellationToken).ConfigureAwait(false); - using var withReplyTransition = withReplyKey.ProcessResponse(postResponse, postContext.ohttpCtx); + var postResponse = await SendRequestAsync(postContext.Request, cancellationToken).ConfigureAwait(false); + using var withReplyTransition = withReplyKey.ProcessResponse(postResponse, postContext.OhttpCtx); var current = withReplyTransition.Save(senderPersister); try @@ -214,8 +214,8 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh for (var attempt = 0; attempt < MaxProposalPollAttempts; attempt++) { using var pollRequest = current.CreatePollRequest(ohttpRelayUrl.ToString()); - var pollResponse = await SendRequestAsync(pollRequest.request, cancellationToken).ConfigureAwait(false); - using var pollTransition = current.ProcessResponse(pollResponse, pollRequest.ohttpCtx); + var pollResponse = await SendRequestAsync(pollRequest.Request, cancellationToken).ConfigureAwait(false); + using var pollTransition = current.ProcessResponse(pollResponse, pollRequest.OhttpCtx); var outcome = pollTransition.Save(senderPersister); try @@ -223,11 +223,11 @@ private async Task RequestProposalAsync(SystemUri paymentUrl, SystemUri oh switch (outcome) { case PollingForProposalTransitionOutcome.Progress progress: - proposalPsbtBase64 = progress.psbtBase64; + proposalPsbtBase64 = progress.PsbtBase64; break; case PollingForProposalTransitionOutcome.Stasis stasis: current.Dispose(); - current = stasis.inner; + current = stasis.Inner; outcome = null; break; } @@ -330,11 +330,11 @@ private async Task SignAndBroadcastAsync(RunTestPaymentContext runTestPa private async Task SendRequestAsync(Request request, CancellationToken cancellationToken) { - using var message = new HttpRequestMessage(HttpMethod.Post, request.url) + using var message = new HttpRequestMessage(HttpMethod.Post, request.Url) { - Content = new ByteArrayContent(request.body) + Content = new ByteArrayContent(request.Body) }; - message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.contentType); + message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.ContentType); var client = _httpClientFactory.CreateClient(nameof(RunTestPaymentService)); using var response = await client.SendAsync(message, cancellationToken).ConfigureAwait(false); diff --git a/rust-payjoin b/rust-payjoin index 7e0f21ec..f4a6008a 160000 --- a/rust-payjoin +++ b/rust-payjoin @@ -1 +1 @@ -Subproject commit 7e0f21ec7ca209dc4399e0f116330a235a04e6b7 +Subproject commit f4a6008a3a531530434bdd6911db864bcb42fc66 From 97f017c5c331656869c3cb9e1da1bdb425311596 Mon Sep 17 00:00:00 2001 From: chavic Date: Thu, 2 Jul 2026 15:39:26 +0200 Subject: [PATCH 2/5] Use rust-payjoin privacy-preserving receiver input selection Replace the deterministic smallest-first receiver coin choice with rust-payjoin's try_preserving_privacy, so UIH2 avoidance is decided by the library instead of plugin heuristics. A receiver wallet adapter maps wallet coins to FFI InputPairs and resolves the selected input back to its ReceivedCoin through the new InputPair outpoint accessor. When a privacy-selected coin loses its reservation race to another session, the candidate is removed and selection is retried over the remaining coins. --- .../PluginRegistrationTests.cs | 3 + .../PayjoinReceiverInputSelectorTests.cs | 48 +++++++--- BTCPayServer.Plugins.Payjoin/Plugin.cs | 1 + .../Services/PayjoinReceiverInputSelector.cs | 89 ++++++++--------- .../Services/PayjoinReceiverWalletAdapter.cs | 95 +++++++++++++++++++ 5 files changed, 169 insertions(+), 67 deletions(-) create mode 100644 BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs diff --git a/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs index 65c7a8fb..f6fd2840 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs @@ -42,6 +42,9 @@ public void PluginRegistersBitcoinCheckoutExtensions() Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPayjoinReceiverInputSelector) && descriptor.ImplementationType == typeof(PayjoinReceiverInputSelector)); + Assert.Contains(services, descriptor => + descriptor.ServiceType == typeof(IPayjoinReceiverWalletAdapter) && + descriptor.ImplementationType == typeof(PayjoinReceiverWalletAdapter)); } [Fact] diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs index 611a0f0a..17afa61d 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs @@ -1,13 +1,12 @@ using BTCPayServer.Abstractions.Models; using BTCPayServer.Client.Models; using BTCPayServer.Plugins.Payjoin.Services; +using BTCPayServer.Services.Wallets; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Options; using NBitcoin; -using NBXplorer; using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; -using NSubstitute; using Xunit; namespace BTCPayServer.Plugins.Payjoin.Tests.Services; @@ -69,10 +68,10 @@ public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenContributed } [Fact] - public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenNetworkUnavailable() + public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenCoinUnavailable() { using var context = new TestContext(); - var selector = CreateSelector(context.CreateStore(), CreateEmptyNetworkProvider()); + var selector = CreateSelector(context.CreateStore()); var outPoint = new OutPoint(uint256.Parse("8888888888888888888888888888888888888888888888888888888888888888"), 2); var session = CreateSession( contributedInputTransactionId: outPoint.Hash.ToString(), @@ -83,11 +82,12 @@ public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenNetworkUnav Assert.Null(result); } - private static PayjoinReceiverInputSelector CreateSelector(PayjoinReceiverSessionStore sessionStore, BTCPayNetworkProvider? networkProvider = null) + private static PayjoinReceiverInputSelector CreateSelector( + PayjoinReceiverSessionStore sessionStore, + IPayjoinReceiverWalletAdapter? walletAdapter = null) { return new PayjoinReceiverInputSelector( - networkProvider ?? CreateEmptyNetworkProvider(), - new PayjoinAvailabilityService(null!, null!, null!), + walletAdapter ?? new TestReceiverWalletAdapter(), sessionStore); } @@ -125,14 +125,6 @@ private static PayjoinReceiverSessionState CreateSession( events); } - private static BTCPayNetworkProvider CreateEmptyNetworkProvider() - { - return new BTCPayNetworkProvider( - Array.Empty(), - Substitute.For(ChainName.Regtest), - Substitute.For()); - } - private sealed class TestContext : IDisposable { private readonly TestPayjoinPluginDbContextFactory _dbContextFactory = new(); @@ -172,4 +164,30 @@ public override PayjoinPluginDbContext CreateContext(Action(); + + public Task> GetInputCandidatesAsync( + string storeId, + CancellationToken cancellationToken) + { + return Task.FromResult>(Array.Empty()); + } + + public PayjoinReceiverInputCandidate? ResolveSelectedCandidate( + IReadOnlyList candidates, + global::Payjoin.OutPoint selectedOutPoint) + { + return null; + } + + public Task GetConfirmedReceiverCoinsAsync( + string storeId, + CancellationToken cancellationToken) + { + return Task.FromResult(ConfirmedCoins); + } + } } diff --git a/BTCPayServer.Plugins.Payjoin/Plugin.cs b/BTCPayServer.Plugins.Payjoin/Plugin.cs index 53ccf34a..683fcc28 100644 --- a/BTCPayServer.Plugins.Payjoin/Plugin.cs +++ b/BTCPayServer.Plugins.Payjoin/Plugin.cs @@ -36,6 +36,7 @@ public override void Execute(IServiceCollection applicationBuilder) applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); + applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(provider => new PayjoinAccountingBridgeService( provider.GetRequiredService(), diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs index 467043a5..2c32d2ea 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs @@ -10,17 +10,14 @@ namespace BTCPayServer.Plugins.Payjoin.Services; internal sealed class PayjoinReceiverInputSelector : IPayjoinReceiverInputSelector { - private readonly BTCPayNetworkProvider _networkProvider; - private readonly PayjoinAvailabilityService _availabilityService; + private readonly IPayjoinReceiverWalletAdapter _walletAdapter; private readonly PayjoinReceiverSessionStore _sessionStore; public PayjoinReceiverInputSelector( - BTCPayNetworkProvider networkProvider, - PayjoinAvailabilityService availabilityService, + IPayjoinReceiverWalletAdapter walletAdapter, PayjoinReceiverSessionStore sessionStore) { - _networkProvider = networkProvider; - _availabilityService = availabilityService; + _walletAdapter = walletAdapter; _sessionStore = sessionStore; } @@ -31,35 +28,56 @@ public async Task TryContributeInputsAsync( DateTimeOffset reservationExpiresAt, CancellationToken cancellationToken) { - // TODO: Restore `proposal.TryPreservingPrivacy(receiverInputs)` only after rust-payjoin/payjoin-ffi lets us identify which `ReceivedCoin` was actually selected. - // TODO: Persist only the truly contributed coin(s) into `contributedCoins`; otherwise the signing step can treat unrelated wallet inputs as receiver-owned and produce an invalid proposal. - var (receiverInputs, receiverCoins) = await GetReceiverInputsAsync(storeId, cancellationToken).ConfigureAwait(false); + var candidates = (await _walletAdapter.GetInputCandidatesAsync(storeId, cancellationToken).ConfigureAwait(false)).ToList(); var contributionFailures = new List(); - var orderedCandidates = receiverCoins - .Select((coin, index) => new { coin, index }) - .OrderBy(x => x.coin.Coin.Amount.Satoshi) - .Select(x => x.index); + if (candidates.Count == 0) + { + return ReceiverInputContributionResult.Failure("no confirmed receiver coins available"); + } - foreach (var index in orderedCandidates) + while (candidates.Count > 0) { + PayjoinReceiverInputCandidate? selected = null; + try + { + using var selectedInput = proposal.TryPreservingPrivacy(candidates.Select(candidate => candidate.Input).ToArray()); + selected = _walletAdapter.ResolveSelectedCandidate(candidates, selectedInput.Outpoint()); + } + catch (CoinSelectionException ex) + { + contributionFailures.Add($"receiver input selection failed: {ex.Message}"); + break; + } + + if (selected is null) + { + contributionFailures.Add("selected receiver input could not be mapped back to a wallet coin"); + break; + } + + var selectedOutPoint = selected.Coin.OutPoint.ToString(); WantsInputs? withInputs = null; try { - withInputs = proposal.ContributeInputs(new[] { receiverInputs[index] }); - var contributedCoins = new[] { receiverCoins[index] }; + withInputs = proposal.ContributeInputs(new[] { selected.Input }); + var contributedCoins = new[] { selected.Coin }; if (_sessionStore.TryReserveContributedInput(storeId, invoiceId, contributedCoins[0].OutPoint, reservationExpiresAt)) { return ReceiverInputContributionResult.Success(withInputs, contributedCoins); } - contributionFailures.Add($"candidate '{receiverCoins[index].OutPoint}' reservation conflict"); + // Cross-session reservations can make the privacy-selected coin unavailable. Remove + // that candidate and ask rust-payjoin to choose again from the remaining wallet inputs. + contributionFailures.Add($"candidate '{selectedOutPoint}' reservation conflict"); + candidates.Remove(selected); withInputs.Dispose(); withInputs = null; } catch (InputContributionException ex) { - contributionFailures.Add($"candidate '{receiverCoins[index].OutPoint}' rejected: {ex.Message}"); + contributionFailures.Add($"candidate '{selectedOutPoint}' rejected: {ex.Message}"); + candidates.Remove(selected); } catch { @@ -86,43 +104,10 @@ public async Task TryContributeInputsAsync( return null; } - var (_, receiverCoins) = await GetReceiverInputsAsync(session.StoreId, cancellationToken).ConfigureAwait(false); + var receiverCoins = await _walletAdapter.GetConfirmedReceiverCoinsAsync(session.StoreId, cancellationToken).ConfigureAwait(false); var contributedCoins = receiverCoins .Where(coin => coin.OutPoint.Hash == contributedOutPoint.Hash && coin.OutPoint.N == contributedOutPoint.N) .ToArray(); return contributedCoins.Length > 0 ? contributedCoins : null; } - - private async Task<(InputPair[] Inputs, ReceivedCoin[] Coins)> GetReceiverInputsAsync( - string storeId, - CancellationToken cancellationToken) - { - var network = _networkProvider.GetNetwork(PayjoinConstants.BitcoinCode); - if (network is null) - { - return (Array.Empty(), Array.Empty()); - } - - var confirmed = await _availabilityService.GetConfirmedReceiverCoinsAsync(storeId, PayjoinConstants.BitcoinCode, network, cancellationToken).ConfigureAwait(false); - if (confirmed.Length == 0) - { - return (Array.Empty(), Array.Empty()); - } - - var inputs = confirmed - .Select(c => - { - var txin = new TxIn( - new OutPoint(c.OutPoint.Hash.ToString(), (uint)c.OutPoint.N), - Array.Empty(), - uint.MaxValue, - Array.Empty()); - var txout = new TxOut(checked((ulong)c.Coin.Amount.Satoshi), c.ScriptPubKey.ToBytes()); - var psbtIn = new PsbtInput(txout, null, null); - return new InputPair(txin, psbtIn, null); - }) - .ToArray(); - - return (inputs, confirmed); - } } diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs new file mode 100644 index 00000000..3036ba7f --- /dev/null +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs @@ -0,0 +1,95 @@ +using BTCPayServer.Services.Wallets; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using PayjoinInputPair = global::Payjoin.InputPair; +using PayjoinOutPoint = global::Payjoin.OutPoint; +using PayjoinPsbtInput = global::Payjoin.PsbtInput; +using PayjoinTxIn = global::Payjoin.TxIn; +using PayjoinTxOut = global::Payjoin.TxOut; + +namespace BTCPayServer.Plugins.Payjoin.Services; + +internal interface IPayjoinReceiverWalletAdapter +{ + Task> GetInputCandidatesAsync( + string storeId, + CancellationToken cancellationToken); + + PayjoinReceiverInputCandidate? ResolveSelectedCandidate( + IReadOnlyList candidates, + PayjoinOutPoint selectedOutPoint); + + Task GetConfirmedReceiverCoinsAsync( + string storeId, + CancellationToken cancellationToken); +} + +internal sealed class PayjoinReceiverWalletAdapter : IPayjoinReceiverWalletAdapter +{ + private readonly BTCPayNetworkProvider _networkProvider; + private readonly PayjoinAvailabilityService _availabilityService; + + public PayjoinReceiverWalletAdapter( + BTCPayNetworkProvider networkProvider, + PayjoinAvailabilityService availabilityService) + { + _networkProvider = networkProvider; + _availabilityService = availabilityService; + } + + public async Task> GetInputCandidatesAsync( + string storeId, + CancellationToken cancellationToken) + { + var confirmed = await GetConfirmedReceiverCoinsAsync(storeId, cancellationToken).ConfigureAwait(false); + return confirmed + .Select(coin => new PayjoinReceiverInputCandidate(CreateInputPair(coin), coin)) + .ToArray(); + } + + public PayjoinReceiverInputCandidate? ResolveSelectedCandidate( + IReadOnlyList candidates, + PayjoinOutPoint selectedOutPoint) + { + return candidates.SingleOrDefault(candidate => + string.Equals(candidate.Coin.OutPoint.Hash.ToString(), selectedOutPoint.Txid, StringComparison.OrdinalIgnoreCase) && + candidate.Coin.OutPoint.N == selectedOutPoint.Vout); + } + + public async Task GetConfirmedReceiverCoinsAsync( + string storeId, + CancellationToken cancellationToken) + { + var network = _networkProvider.GetNetwork(PayjoinConstants.BitcoinCode); + if (network is null) + { + return Array.Empty(); + } + + return await _availabilityService.GetConfirmedReceiverCoinsAsync( + storeId, + PayjoinConstants.BitcoinCode, + network, + cancellationToken).ConfigureAwait(false); + } + + private static PayjoinInputPair CreateInputPair(ReceivedCoin coin) + { + var txin = new PayjoinTxIn( + new PayjoinOutPoint(coin.OutPoint.Hash.ToString(), coin.OutPoint.N), + Array.Empty(), + uint.MaxValue, + Array.Empty()); + var txout = new PayjoinTxOut(checked((ulong)coin.Coin.Amount.Satoshi), coin.ScriptPubKey.ToBytes()); + var psbtIn = new PayjoinPsbtInput(txout, null, null); + return new PayjoinInputPair(txin, psbtIn, null); + } +} + +internal sealed record PayjoinReceiverInputCandidate(PayjoinInputPair Input, ReceivedCoin Coin) +{ + public NBitcoin.OutPoint OutPoint => Coin.OutPoint; +} From eee42df5658176312d874ee84a13252b8a54e17d Mon Sep 17 00:00:00 2001 From: chavic Date: Fri, 3 Jul 2026 14:24:56 +0200 Subject: [PATCH 3/5] Test the receiver input contribution flow Wrap the rust-payjoin proposal calls behind an injectable seam so the selection and retry logic stays free of FFI types, translating the library's selection and contribution errors into plugin exceptions at that boundary. Document the retry model where it lives: candidates are snapshotted once per attempt and failed entries removed locally, because the wallet view does not exclude coins reserved by concurrent sessions and rebuilding mid-attempt would re-offer the input that just failed; each poll tick re-enters with a fresh set. Adds focused tests for the contribution flow: successful selection, reservation conflict with reselection, exhaustion when every candidate is reserved, contribution rejection with reselection, unmappable selection, and library selection failure. --- .../PluginRegistrationTests.cs | 3 + .../PayjoinReceiverInputSelectorTests.cs | 196 +++++++++++++++++- BTCPayServer.Plugins.Payjoin/Plugin.cs | 1 + .../PayjoinReceiverInputProposalOperations.cs | 88 ++++++++ .../Services/PayjoinReceiverInputSelector.cs | 30 ++- 5 files changed, 305 insertions(+), 13 deletions(-) create mode 100644 BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputProposalOperations.cs diff --git a/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs index f6fd2840..2fe38359 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs @@ -45,6 +45,9 @@ public void PluginRegistersBitcoinCheckoutExtensions() Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPayjoinReceiverWalletAdapter) && descriptor.ImplementationType == typeof(PayjoinReceiverWalletAdapter)); + Assert.Contains(services, descriptor => + descriptor.ServiceType == typeof(IPayjoinReceiverInputProposalOperations) && + descriptor.ImplementationType == typeof(PayjoinReceiverInputProposalOperations)); } [Fact] diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs index 17afa61d..0700f4c3 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverInputSelectorTests.cs @@ -82,12 +82,159 @@ public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenCoinUnavail Assert.Null(result); } + [Fact] + public async Task TryContributeInputsAsyncContributesTheSelectedCandidate() + { + using var context = new TestContext(); + var store = context.CreateStore(); + CreatePersistedSession(store, "invoice-1"); + var candidates = CreateCandidates(2); + var selector = CreateSelector( + store, + new TestReceiverWalletAdapter { Candidates = candidates }, + new TestProposalOperations()); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.True(string.IsNullOrEmpty(result.FailureMessage)); + Assert.NotNull(result.ContributedCoins); + Assert.Equal(candidates[0].Coin.OutPoint, Assert.Single(result.ContributedCoins!).OutPoint); + } + + [Fact] + public async Task TryContributeInputsAsyncReselectsWhenReservationConflicts() + { + using var context = new TestContext(); + var store = context.CreateStore(); + CreatePersistedSession(store, "invoice-1"); + CreatePersistedSession(store, "other-invoice"); + var candidates = CreateCandidates(2); + Assert.True(store.TryReserveContributedInput("store-1", "other-invoice", candidates[0].Coin.OutPoint, DateTimeOffset.UtcNow.AddHours(1))); + var selector = CreateSelector( + store, + new TestReceiverWalletAdapter { Candidates = candidates }, + new TestProposalOperations()); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.True(string.IsNullOrEmpty(result.FailureMessage)); + Assert.NotNull(result.ContributedCoins); + Assert.Equal(candidates[1].Coin.OutPoint, Assert.Single(result.ContributedCoins!).OutPoint); + } + + [Fact] + public async Task TryContributeInputsAsyncFailsWhenEveryCandidateIsReserved() + { + using var context = new TestContext(); + var store = context.CreateStore(); + CreatePersistedSession(store, "invoice-1"); + var candidates = CreateCandidates(2); + for (var i = 0; i < candidates.Count; i++) + { + var otherInvoiceId = $"other-invoice-{i}"; + CreatePersistedSession(store, otherInvoiceId); + Assert.True(store.TryReserveContributedInput("store-1", otherInvoiceId, candidates[i].Coin.OutPoint, DateTimeOffset.UtcNow.AddHours(1))); + } + + var selector = CreateSelector( + store, + new TestReceiverWalletAdapter { Candidates = candidates }, + new TestProposalOperations()); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.Null(result.ContributedCoins); + Assert.Contains($"candidate '{candidates[0].Coin.OutPoint}' reservation conflict", result.FailureMessage, StringComparison.Ordinal); + Assert.Contains($"candidate '{candidates[1].Coin.OutPoint}' reservation conflict", result.FailureMessage, StringComparison.Ordinal); + } + + [Fact] + public async Task TryContributeInputsAsyncReselectsWhenContributionIsRejected() + { + using var context = new TestContext(); + var store = context.CreateStore(); + CreatePersistedSession(store, "invoice-1"); + var candidates = CreateCandidates(2); + var operations = new TestProposalOperations + { + RejectedOutPoints = { candidates[0].Coin.OutPoint } + }; + var selector = CreateSelector( + store, + new TestReceiverWalletAdapter { Candidates = candidates }, + operations); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.True(string.IsNullOrEmpty(result.FailureMessage)); + Assert.NotNull(result.ContributedCoins); + Assert.Equal(candidates[1].Coin.OutPoint, Assert.Single(result.ContributedCoins!).OutPoint); + } + + [Fact] + public async Task TryContributeInputsAsyncFailsWhenSelectionCannotBeMappedBackToACoin() + { + using var context = new TestContext(); + var candidates = CreateCandidates(1); + var selector = CreateSelector( + context.CreateStore(), + new TestReceiverWalletAdapter { Candidates = candidates, ResolveToNull = true }, + new TestProposalOperations()); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.Null(result.ContributedCoins); + Assert.Contains("selected receiver input could not be mapped back to a wallet coin", result.FailureMessage, StringComparison.Ordinal); + } + + [Fact] + public async Task TryContributeInputsAsyncFailsWhenTheLibraryCannotSelect() + { + using var context = new TestContext(); + var candidates = CreateCandidates(1); + var selector = CreateSelector( + context.CreateStore(), + new TestReceiverWalletAdapter { Candidates = candidates }, + new TestProposalOperations { SelectionFailureMessage = "no viable input" }); + + var result = await selector.TryContributeInputsAsync(null!, "store-1", "invoice-1", DateTimeOffset.UtcNow.AddHours(1), CancellationToken.None); + + Assert.Null(result.ContributedCoins); + Assert.Contains("receiver input selection failed: no viable input", result.FailureMessage, StringComparison.Ordinal); + } + + private static void CreatePersistedSession(PayjoinReceiverSessionStore store, string invoiceId) + { + store.CreateSession( + invoiceId, + "bcrt1qexampleaddress0000000000000000000000000", + "store-1", + new Uri("https://relay.example/"), + DateTimeOffset.UtcNow.AddHours(1), + ["bootstrap-event"]); + } + + private static List CreateCandidates(int count) + { + var candidates = new List(); + for (var i = 0; i < count; i++) + { + var hash = uint256.Parse($"{i + 1:x64}"); + var coin = new ReceivedCoin { OutPoint = new OutPoint(hash, (uint)i) }; + candidates.Add(new PayjoinReceiverInputCandidate(null!, coin)); + } + + return candidates; + } + private static PayjoinReceiverInputSelector CreateSelector( PayjoinReceiverSessionStore sessionStore, - IPayjoinReceiverWalletAdapter? walletAdapter = null) + IPayjoinReceiverWalletAdapter? walletAdapter = null, + IPayjoinReceiverInputProposalOperations? proposalOperations = null) { return new PayjoinReceiverInputSelector( walletAdapter ?? new TestReceiverWalletAdapter(), + proposalOperations ?? new TestProposalOperations(), sessionStore); } @@ -169,18 +316,29 @@ private sealed class TestReceiverWalletAdapter : IPayjoinReceiverWalletAdapter { public ReceivedCoin[] ConfirmedCoins { get; init; } = Array.Empty(); + public List Candidates { get; init; } = new(); + + public bool ResolveToNull { get; init; } + public Task> GetInputCandidatesAsync( string storeId, CancellationToken cancellationToken) { - return Task.FromResult>(Array.Empty()); + return Task.FromResult>(Candidates); } public PayjoinReceiverInputCandidate? ResolveSelectedCandidate( IReadOnlyList candidates, global::Payjoin.OutPoint selectedOutPoint) { - return null; + if (ResolveToNull) + { + return null; + } + + return candidates.SingleOrDefault(candidate => + string.Equals(candidate.Coin.OutPoint.Hash.ToString(), selectedOutPoint.Txid, StringComparison.OrdinalIgnoreCase) && + candidate.Coin.OutPoint.N == selectedOutPoint.Vout); } public Task GetConfirmedReceiverCoinsAsync( @@ -190,4 +348,36 @@ public Task GetConfirmedReceiverCoinsAsync( return Task.FromResult(ConfirmedCoins); } } + + private sealed class TestProposalOperations : IPayjoinReceiverInputProposalOperations + { + public string? SelectionFailureMessage { get; init; } + + public HashSet RejectedOutPoints { get; } = new(); + + public global::Payjoin.OutPoint SelectPreservingPrivacy( + global::Payjoin.WantsInputs proposal, + IReadOnlyList candidates) + { + if (SelectionFailureMessage is not null) + { + throw new PayjoinReceiverInputSelectionException(SelectionFailureMessage); + } + + var first = candidates[0].Coin.OutPoint; + return new global::Payjoin.OutPoint(first.Hash.ToString(), first.N); + } + + public global::Payjoin.WantsInputs ContributeInputs( + global::Payjoin.WantsInputs proposal, + PayjoinReceiverInputCandidate selected) + { + if (RejectedOutPoints.Contains(selected.Coin.OutPoint)) + { + throw new PayjoinReceiverInputContributionException($"input rejected"); + } + + return null!; + } + } } diff --git a/BTCPayServer.Plugins.Payjoin/Plugin.cs b/BTCPayServer.Plugins.Payjoin/Plugin.cs index 683fcc28..854f1096 100644 --- a/BTCPayServer.Plugins.Payjoin/Plugin.cs +++ b/BTCPayServer.Plugins.Payjoin/Plugin.cs @@ -37,6 +37,7 @@ public override void Execute(IServiceCollection applicationBuilder) applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); + applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(); applicationBuilder.AddSingleton(provider => new PayjoinAccountingBridgeService( provider.GetRequiredService(), diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputProposalOperations.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputProposalOperations.cs new file mode 100644 index 00000000..2d7be51b --- /dev/null +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputProposalOperations.cs @@ -0,0 +1,88 @@ +using Payjoin; +using System; +using System.Collections.Generic; +using System.Linq; +using PayjoinOutPoint = global::Payjoin.OutPoint; + +namespace BTCPayServer.Plugins.Payjoin.Services; + +/// +/// Wraps the rust-payjoin proposal input operations so the selection/retry logic in +/// stays free of FFI types and can be unit tested. +/// +internal interface IPayjoinReceiverInputProposalOperations +{ + /// + /// Asks rust-payjoin to choose the privacy-preserving input from the candidates. + /// Throws when the library cannot select. + /// + PayjoinOutPoint SelectPreservingPrivacy(WantsInputs proposal, IReadOnlyList candidates); + + /// + /// Contributes the selected input to the proposal. + /// Throws when the library rejects it. + /// + WantsInputs ContributeInputs(WantsInputs proposal, PayjoinReceiverInputCandidate selected); +} + +internal sealed class PayjoinReceiverInputProposalOperations : IPayjoinReceiverInputProposalOperations +{ + public PayjoinOutPoint SelectPreservingPrivacy(WantsInputs proposal, IReadOnlyList candidates) + { + try + { + using var selectedInput = proposal.TryPreservingPrivacy(candidates.Select(candidate => candidate.Input).ToArray()); + return selectedInput.Outpoint(); + } + catch (CoinSelectionException ex) + { + throw new PayjoinReceiverInputSelectionException(ex.Message, ex); + } + } + + public WantsInputs ContributeInputs(WantsInputs proposal, PayjoinReceiverInputCandidate selected) + { + try + { + return proposal.ContributeInputs(new[] { selected.Input }); + } + catch (InputContributionException ex) + { + throw new PayjoinReceiverInputContributionException(ex.Message, ex); + } + } +} + +public sealed class PayjoinReceiverInputSelectionException : Exception +{ + public PayjoinReceiverInputSelectionException() + { + } + + public PayjoinReceiverInputSelectionException(string message) + : base(message) + { + } + + public PayjoinReceiverInputSelectionException(string message, Exception? innerException = null) + : base(message, innerException) + { + } +} + +public sealed class PayjoinReceiverInputContributionException : Exception +{ + public PayjoinReceiverInputContributionException() + { + } + + public PayjoinReceiverInputContributionException(string message) + : base(message) + { + } + + public PayjoinReceiverInputContributionException(string message, Exception? innerException = null) + : base(message, innerException) + { + } +} diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs index 2c32d2ea..28c41c8a 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs @@ -11,13 +11,16 @@ namespace BTCPayServer.Plugins.Payjoin.Services; internal sealed class PayjoinReceiverInputSelector : IPayjoinReceiverInputSelector { private readonly IPayjoinReceiverWalletAdapter _walletAdapter; + private readonly IPayjoinReceiverInputProposalOperations _proposalOperations; private readonly PayjoinReceiverSessionStore _sessionStore; public PayjoinReceiverInputSelector( IPayjoinReceiverWalletAdapter walletAdapter, + IPayjoinReceiverInputProposalOperations proposalOperations, PayjoinReceiverSessionStore sessionStore) { _walletAdapter = walletAdapter; + _proposalOperations = proposalOperations; _sessionStore = sessionStore; } @@ -28,6 +31,13 @@ public async Task TryContributeInputsAsync( DateTimeOffset reservationExpiresAt, CancellationToken cancellationToken) { + // Retry model: the candidate set is snapshotted once per attempt and failed entries are + // removed locally. The wallet view does not exclude coins reserved by concurrent sessions, + // so rebuilding the set mid-attempt would re-offer the very input whose reservation just + // failed and the deterministic library selection would pick it again. Each iteration + // strictly shrinks the set, which bounds the loop. Freshness comes from the tier above: + // when this attempt returns a failure, the next poll tick re-enters with a newly built + // candidate set. var candidates = (await _walletAdapter.GetInputCandidatesAsync(storeId, cancellationToken).ConfigureAwait(false)).ToList(); var contributionFailures = new List(); @@ -38,13 +48,13 @@ public async Task TryContributeInputsAsync( while (candidates.Count > 0) { - PayjoinReceiverInputCandidate? selected = null; + PayjoinReceiverInputCandidate? selected; try { - using var selectedInput = proposal.TryPreservingPrivacy(candidates.Select(candidate => candidate.Input).ToArray()); - selected = _walletAdapter.ResolveSelectedCandidate(candidates, selectedInput.Outpoint()); + var selectedOutPoint = _proposalOperations.SelectPreservingPrivacy(proposal, candidates); + selected = _walletAdapter.ResolveSelectedCandidate(candidates, selectedOutPoint); } - catch (CoinSelectionException ex) + catch (PayjoinReceiverInputSelectionException ex) { contributionFailures.Add($"receiver input selection failed: {ex.Message}"); break; @@ -56,11 +66,11 @@ public async Task TryContributeInputsAsync( break; } - var selectedOutPoint = selected.Coin.OutPoint.ToString(); + var selectedCoinOutPoint = selected.Coin.OutPoint.ToString(); WantsInputs? withInputs = null; try { - withInputs = proposal.ContributeInputs(new[] { selected.Input }); + withInputs = _proposalOperations.ContributeInputs(proposal, selected); var contributedCoins = new[] { selected.Coin }; if (_sessionStore.TryReserveContributedInput(storeId, invoiceId, contributedCoins[0].OutPoint, reservationExpiresAt)) { @@ -69,14 +79,14 @@ public async Task TryContributeInputsAsync( // Cross-session reservations can make the privacy-selected coin unavailable. Remove // that candidate and ask rust-payjoin to choose again from the remaining wallet inputs. - contributionFailures.Add($"candidate '{selectedOutPoint}' reservation conflict"); + contributionFailures.Add($"candidate '{selectedCoinOutPoint}' reservation conflict"); candidates.Remove(selected); - withInputs.Dispose(); + withInputs?.Dispose(); withInputs = null; } - catch (InputContributionException ex) + catch (PayjoinReceiverInputContributionException ex) { - contributionFailures.Add($"candidate '{selectedOutPoint}' rejected: {ex.Message}"); + contributionFailures.Add($"candidate '{selectedCoinOutPoint}' rejected: {ex.Message}"); candidates.Remove(selected); } catch From 938de574a94397b23ae5f5b5f78510d18fe743d7 Mon Sep 17 00:00:00 2001 From: chavic Date: Sat, 4 Jul 2026 18:40:52 +0200 Subject: [PATCH 4/5] Release input candidates deterministically and add boundary tests The FFI input pairs built for the candidate set hold native state and were only released by finalizers; the attempt now disposes every candidate once it completes, on success and failure alike, since the library clones what it keeps when an input is contributed. Adds boundary tests that exercise the wallet-coin to InputPair mapping and the selected-input roundtrip with real library objects, alongside the existing reservation-race coverage against the real session store. --- .../PayjoinReceiverWalletAdapterTests.cs | 73 +++++++++++++++++++ .../Services/PayjoinReceiverInputSelector.cs | 31 +++++++- .../Services/PayjoinReceiverWalletAdapter.cs | 2 +- 3 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverWalletAdapterTests.cs diff --git a/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverWalletAdapterTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverWalletAdapterTests.cs new file mode 100644 index 00000000..3c76ece1 --- /dev/null +++ b/BTCPayServer.Plugins.Payjoin.Tests/Services/PayjoinReceiverWalletAdapterTests.cs @@ -0,0 +1,73 @@ +using BTCPayServer.Plugins.Payjoin.Services; +using BTCPayServer.Services.Wallets; +using NBitcoin; +using Xunit; + +namespace BTCPayServer.Plugins.Payjoin.Tests.Services; + +/// +/// Exercises the plugin/rust-payjoin boundary with real FFI objects: the wallet-coin to InputPair +/// mapping and the selected-input roundtrip back to the wallet coin. +/// +public class PayjoinReceiverWalletAdapterTests +{ + [Fact] + public void CreateInputPairRoundTripsTheCoinOutpointThroughTheLibrary() + { + var coin = CreateCoin("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 3, 25_000); + + using var inputPair = PayjoinReceiverWalletAdapter.CreateInputPair(coin); + var outpoint = inputPair.Outpoint(); + + Assert.Equal(coin.OutPoint.Hash.ToString(), outpoint.Txid, ignoreCase: true); + Assert.Equal(coin.OutPoint.N, outpoint.Vout); + } + + [Fact] + public void ResolveSelectedCandidateMapsTheLibrarySelectionBackToTheWalletCoin() + { + var firstCoin = CreateCoin("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0, 10_000); + var secondCoin = CreateCoin("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1, 20_000); + using var firstInput = PayjoinReceiverWalletAdapter.CreateInputPair(firstCoin); + using var secondInput = PayjoinReceiverWalletAdapter.CreateInputPair(secondCoin); + var candidates = new[] + { + new PayjoinReceiverInputCandidate(firstInput, firstCoin), + new PayjoinReceiverInputCandidate(secondInput, secondCoin) + }; + var adapter = new PayjoinReceiverWalletAdapter(null!, null!); + + var resolved = adapter.ResolveSelectedCandidate(candidates, secondInput.Outpoint()); + + Assert.NotNull(resolved); + Assert.Same(secondCoin, resolved!.Coin); + } + + [Fact] + public void ResolveSelectedCandidateReturnsNullForAnUnknownOutpoint() + { + var coin = CreateCoin("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0, 10_000); + using var input = PayjoinReceiverWalletAdapter.CreateInputPair(coin); + var candidates = new[] { new PayjoinReceiverInputCandidate(input, coin) }; + var adapter = new PayjoinReceiverWalletAdapter(null!, null!); + + var resolved = adapter.ResolveSelectedCandidate( + candidates, + new global::Payjoin.OutPoint("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", 9)); + + Assert.Null(resolved); + } + + private static ReceivedCoin CreateCoin(string txId, uint vout, long valueSats) + { + using var key = new Key(); + var outPoint = new OutPoint(uint256.Parse(txId), vout); + var scriptPubKey = key.PubKey.WitHash.ScriptPubKey; + return new ReceivedCoin + { + OutPoint = outPoint, + ScriptPubKey = scriptPubKey, + Coin = new Coin(outPoint, new TxOut(Money.Satoshis(valueSats), scriptPubKey)) + }; + } +} diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs index 28c41c8a..053b15bb 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs @@ -35,11 +35,34 @@ public async Task TryContributeInputsAsync( // removed locally. The wallet view does not exclude coins reserved by concurrent sessions, // so rebuilding the set mid-attempt would re-offer the very input whose reservation just // failed and the deterministic library selection would pick it again. Each iteration - // strictly shrinks the set, which bounds the loop. Freshness comes from the tier above: - // when this attempt returns a failure, the next poll tick re-enters with a newly built - // candidate set. - var candidates = (await _walletAdapter.GetInputCandidatesAsync(storeId, cancellationToken).ConfigureAwait(false)).ToList(); + // strictly shrinks the set, which bounds the loop. A failed attempt currently ends the + // receiver session in PayjoinReceiverSessionProcessor; letting the session retry on a later + // poll tick with a freshly built candidate set is proposed separately. + var allCandidates = (await _walletAdapter.GetInputCandidatesAsync(storeId, cancellationToken).ConfigureAwait(false)).ToList(); + try + { + return TryContributeFromCandidates(proposal, allCandidates, storeId, invoiceId, reservationExpiresAt); + } + finally + { + // The FFI input pairs hold native state; the library clones what it keeps when an input + // is contributed, so every candidate can be released deterministically once the attempt + // is over instead of waiting for finalizers. + foreach (var candidate in allCandidates) + { + candidate.Input?.Dispose(); + } + } + } + private ReceiverInputContributionResult TryContributeFromCandidates( + WantsInputs proposal, + List allCandidates, + string storeId, + string invoiceId, + DateTimeOffset reservationExpiresAt) + { + var candidates = new List(allCandidates); var contributionFailures = new List(); if (candidates.Count == 0) { diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs index 3036ba7f..5d24096f 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs @@ -76,7 +76,7 @@ public async Task GetConfirmedReceiverCoinsAsync( cancellationToken).ConfigureAwait(false); } - private static PayjoinInputPair CreateInputPair(ReceivedCoin coin) + internal static PayjoinInputPair CreateInputPair(ReceivedCoin coin) { var txin = new PayjoinTxIn( new PayjoinOutPoint(coin.OutPoint.Hash.ToString(), coin.OutPoint.N), From 70884290097939b02c9e6a3964d5872f71af8c98 Mon Sep 17 00:00:00 2001 From: chavic Date: Sat, 4 Jul 2026 21:59:32 +0200 Subject: [PATCH 5/5] Document why an exhausted contribution attempt ends the session Transient reservation races resolve inside the attempt by reselecting from the remaining candidates, so an exhausted attempt means nothing was contributable. Keeping the session alive to retry later would let it reserve freshly confirmed coins for a sender that already gave up, starving future payjoins until the monitoring deadline - the concurrency integration tests assert exactly this property. Ending the session mirrors how the v1 endpoint answers unavailability, and the sender's original transaction still pays the invoice. --- .../Services/PayjoinReceiverInputSelector.cs | 7 ++++--- .../Services/PayjoinReceiverSessionProcessor.cs | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs index 053b15bb..1aa8c7af 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs @@ -35,9 +35,10 @@ public async Task TryContributeInputsAsync( // removed locally. The wallet view does not exclude coins reserved by concurrent sessions, // so rebuilding the set mid-attempt would re-offer the very input whose reservation just // failed and the deterministic library selection would pick it again. Each iteration - // strictly shrinks the set, which bounds the loop. A failed attempt currently ends the - // receiver session in PayjoinReceiverSessionProcessor; letting the session retry on a later - // poll tick with a freshly built candidate set is proposed separately. + // strictly shrinks the set, which bounds the loop, and transient reservation races resolve + // here by reselecting from the remaining candidates. An exhausted attempt is terminal: + // PayjoinReceiverSessionProcessor ends the session (see the rationale there) and the sender + // falls back to broadcasting their original transaction. var allCandidates = (await _walletAdapter.GetInputCandidatesAsync(storeId, cancellationToken).ConfigureAwait(false)).ToList(); try { diff --git a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs index 7f4cd9dc..9f9b2067 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverSessionProcessor.cs @@ -354,6 +354,13 @@ private async Task PersistSettlementScriptAsync(string invoiceId, PayjoinReceive return new ReceiverInputContribution(contribution.ProposalWithInputs, contribution.ContributedCoins); } + // An exhausted contribution attempt ends the session deliberately. Keeping it alive to + // retry on later ticks looks tempting for transient contention, but those races already + // resolve inside the attempt, and a session that lingers after its sender gave up would + // grab and reserve freshly confirmed coins until the monitoring deadline, starving future + // payjoins - the concurrency integration tests assert exactly this. Ending the session is + // the async analog of the v1 endpoint answering that payjoin is unavailable: the sender + // falls back and their original transaction still pays the invoice. LogPayjoinReceiverInputContributionFailed(_logger, invoiceId, contribution.FailureMessage, null); RemoveSession(invoiceId, "no receiver input available for payjoin contribution"); return null;