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/PluginRegistrationTests.cs b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs index 65c7a8fb..2fe38359 100644 --- a/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs +++ b/BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs @@ -42,6 +42,12 @@ 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)); + 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 611a0f0a..0700f4c3 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,159 @@ public async Task TryGetPersistedContributedCoinsAsyncReturnsNullWhenNetworkUnav Assert.Null(result); } - private static PayjoinReceiverInputSelector CreateSelector(PayjoinReceiverSessionStore sessionStore, BTCPayNetworkProvider? networkProvider = null) + [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, + IPayjoinReceiverInputProposalOperations? proposalOperations = null) { return new PayjoinReceiverInputSelector( - networkProvider ?? CreateEmptyNetworkProvider(), - new PayjoinAvailabilityService(null!, null!, null!), + walletAdapter ?? new TestReceiverWalletAdapter(), + proposalOperations ?? new TestProposalOperations(), sessionStore); } @@ -125,14 +272,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 +311,73 @@ public override PayjoinPluginDbContext CreateContext(Action(); + + public List Candidates { get; init; } = new(); + + public bool ResolveToNull { get; init; } + + public Task> GetInputCandidatesAsync( + string storeId, + CancellationToken cancellationToken) + { + return Task.FromResult>(Candidates); + } + + public PayjoinReceiverInputCandidate? ResolveSelectedCandidate( + IReadOnlyList candidates, + global::Payjoin.OutPoint selectedOutPoint) + { + 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( + string storeId, + CancellationToken cancellationToken) + { + 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.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.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/Plugin.cs b/BTCPayServer.Plugins.Payjoin/Plugin.cs index 53ccf34a..854f1096 100644 --- a/BTCPayServer.Plugins.Payjoin/Plugin.cs +++ b/BTCPayServer.Plugins.Payjoin/Plugin.cs @@ -36,6 +36,8 @@ public override void Execute(IServiceCollection applicationBuilder) applicationBuilder.AddSingleton(); 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 467043a5..1aa8c7af 100644 --- a/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs +++ b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverInputSelector.cs @@ -10,17 +10,17 @@ namespace BTCPayServer.Plugins.Payjoin.Services; internal sealed class PayjoinReceiverInputSelector : IPayjoinReceiverInputSelector { - private readonly BTCPayNetworkProvider _networkProvider; - private readonly PayjoinAvailabilityService _availabilityService; + private readonly IPayjoinReceiverWalletAdapter _walletAdapter; + private readonly IPayjoinReceiverInputProposalOperations _proposalOperations; private readonly PayjoinReceiverSessionStore _sessionStore; public PayjoinReceiverInputSelector( - BTCPayNetworkProvider networkProvider, - PayjoinAvailabilityService availabilityService, + IPayjoinReceiverWalletAdapter walletAdapter, + IPayjoinReceiverInputProposalOperations proposalOperations, PayjoinReceiverSessionStore sessionStore) { - _networkProvider = networkProvider; - _availabilityService = availabilityService; + _walletAdapter = walletAdapter; + _proposalOperations = proposalOperations; _sessionStore = sessionStore; } @@ -31,35 +31,87 @@ 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); + // 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, 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 + { + 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(); - 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; + try + { + var selectedOutPoint = _proposalOperations.SelectPreservingPrivacy(proposal, candidates); + selected = _walletAdapter.ResolveSelectedCandidate(candidates, selectedOutPoint); + } + catch (PayjoinReceiverInputSelectionException 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 selectedCoinOutPoint = selected.Coin.OutPoint.ToString(); WantsInputs? withInputs = null; try { - withInputs = proposal.ContributeInputs(new[] { receiverInputs[index] }); - var contributedCoins = new[] { receiverCoins[index] }; + withInputs = _proposalOperations.ContributeInputs(proposal, selected); + 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"); - withInputs.Dispose(); + // 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 '{selectedCoinOutPoint}' reservation conflict"); + candidates.Remove(selected); + withInputs?.Dispose(); withInputs = null; } - catch (InputContributionException ex) + catch (PayjoinReceiverInputContributionException ex) { - contributionFailures.Add($"candidate '{receiverCoins[index].OutPoint}' rejected: {ex.Message}"); + contributionFailures.Add($"candidate '{selectedCoinOutPoint}' rejected: {ex.Message}"); + candidates.Remove(selected); } catch { @@ -86,43 +138,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/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..9f9b2067 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: @@ -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; 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/PayjoinReceiverWalletAdapter.cs b/BTCPayServer.Plugins.Payjoin/Services/PayjoinReceiverWalletAdapter.cs new file mode 100644 index 00000000..5d24096f --- /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); + } + + internal 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; +} 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