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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,8 @@ private async Task<PSBT> 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
{
Expand Down Expand Up @@ -242,8 +242,8 @@ private async Task<PSBT> 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);

Expand All @@ -252,11 +252,11 @@ private async Task<PSBT> 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;
}
Expand Down Expand Up @@ -302,11 +302,11 @@ private static string FormatSenderResponseException(global::Payjoin.ResponseExce

private async Task<byte[]> 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);
Expand All @@ -321,7 +321,7 @@ private async Task<byte[]> 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)
Expand All @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions BTCPayServer.Plugins.Payjoin.Tests/PluginRegistrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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(),
Expand All @@ -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<PayjoinReceiverInputCandidate> CreateCandidates(int count)
{
var candidates = new List<PayjoinReceiverInputCandidate>();
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);
}

Expand Down Expand Up @@ -125,14 +272,6 @@ private static PayjoinReceiverSessionState CreateSession(
events);
}

private static BTCPayNetworkProvider CreateEmptyNetworkProvider()
{
return new BTCPayNetworkProvider(
Array.Empty<BTCPayNetworkBase>(),
Substitute.For<NBXplorerNetworkProvider>(ChainName.Regtest),
Substitute.For<BTCPayServer.Logging.Logs>());
}

private sealed class TestContext : IDisposable
{
private readonly TestPayjoinPluginDbContextFactory _dbContextFactory = new();
Expand Down Expand Up @@ -172,4 +311,73 @@ public override PayjoinPluginDbContext CreateContext(Action<NpgsqlDbContextOptio
return new PayjoinPluginDbContext(_dbContextOptions);
}
}

private sealed class TestReceiverWalletAdapter : IPayjoinReceiverWalletAdapter
{
public ReceivedCoin[] ConfirmedCoins { get; init; } = Array.Empty<ReceivedCoin>();

public List<PayjoinReceiverInputCandidate> Candidates { get; init; } = new();

public bool ResolveToNull { get; init; }

public Task<IReadOnlyList<PayjoinReceiverInputCandidate>> GetInputCandidatesAsync(
string storeId,
CancellationToken cancellationToken)
{
return Task.FromResult<IReadOnlyList<PayjoinReceiverInputCandidate>>(Candidates);
}

public PayjoinReceiverInputCandidate? ResolveSelectedCandidate(
IReadOnlyList<PayjoinReceiverInputCandidate> 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<ReceivedCoin[]> GetConfirmedReceiverCoinsAsync(
string storeId,
CancellationToken cancellationToken)
{
return Task.FromResult(ConfirmedCoins);
}
}

private sealed class TestProposalOperations : IPayjoinReceiverInputProposalOperations
{
public string? SelectionFailureMessage { get; init; }

public HashSet<OutPoint> RejectedOutPoints { get; } = new();

public global::Payjoin.OutPoint SelectPreservingPrivacy(
global::Payjoin.WantsInputs proposal,
IReadOnlyList<PayjoinReceiverInputCandidate> 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!;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public void CreateSettlementOutputsCreatesSingleSettlementOutput()
// Assert
Assert.Equal(settlementScript, result.SettlementScript);
Assert.Single(result.ReplacementOutputs);
Assert.Equal<ulong>(50_000UL, result.ReplacementOutputs[0].valueSat);
Assert.Equal(settlementScript, result.ReplacementOutputs[0].scriptPubkey);
Assert.Equal<ulong>(50_000UL, result.ReplacementOutputs[0].ValueSat);
Assert.Equal(settlementScript, result.ReplacementOutputs[0].ScriptPubkey);
}

[Fact]
Expand All @@ -30,7 +30,7 @@ public void CreateSettlementOutputsSupportsPreservingReceiverScript()

Assert.Equal(receiverScript, result.SettlementScript);
Assert.Single(result.ReplacementOutputs);
Assert.Equal<ulong>(75_000UL, result.ReplacementOutputs[0].valueSat);
Assert.Equal(receiverScript, result.ReplacementOutputs[0].scriptPubkey);
Assert.Equal<ulong>(75_000UL, result.ReplacementOutputs[0].ValueSat);
Assert.Equal(receiverScript, result.ReplacementOutputs[0].ScriptPubkey);
}
}
Loading
Loading