Harden account and payment handling
What changed, and why it matters
This is a large hardening patch for BTCPay Server that fixes several security weaknesses around account handling, payments, refunds, and plugins. Key changes include: preventing Blazor circuits from staying authenticated after a user's admin rights or account status changes; stopping users from creating multiple simultaneous refunds for the same invoice; requiring extra permission when a payout approval specifies a custom exchange rate; preventing hot-wallet flags from being silently carried over to a different wallet; adding rate limits to anonymous monetization signups and LNURL invoice generation; fixing PayJoin transaction locking so funds are not accidentally double-spent; and making plugin dependency downloads safer against cycles and partial installs. The commit message and code comments frame these as hardening measures rather than a single critical vulnerability.
Treat this as a security hardening release and deploy promptly. Review the listed components for any custom forks or local patches that may conflict with the new revalidation, refund serialization, payout approval, hot-wallet, or PayJoin behavior. Run the included tests, especially CircuitUserRevalidatorTests, GreenfieldAPITests, PayJoinTests, PluginManagerTests, and RateAccountingSecurityTests, before production deployment. No CVE or advisory is supplied, so monitor BTCPay Server release notes for formal disclosure details.
Security signals we found
Blazor circuit principal revalidation against live user state
Cookie principal rejection when user is administratively restricted
Refund creation serialized with SELECT FOR UPDATE and single open refund enforcement
Payout approval with explicit RateRule gated by CanCreatePullPayments
Hot-wallet flag no longer transferable to a different derivation scheme
HighSpeed speed policy normalized to MediumSpeed, removing zero-confirmation handling
Rate limiting added to anonymous monetization signup and LNURL invoice generation
PayJoin UTXO locking and delayed-broadcast cleanup to prevent double-spend/lock leaks
Plugin dependency resolution hardened against cycles and partial installs
On-chain automated payout claims and reversion on broadcast failure
Evidence from the diff
The commit is a broad defensive patch across BTCPay Server. Notable security-relevant changes: (1) New CircuitUserRevalidator and RevalidatingAuthenticationStateProvider revalidate Blazor circuit principals against the database on each interval, rejecting stale admin roles and disabled/restricted users; cookie validation also rejects restricted principals. (2) Refund creation is serialized with a SELECT FOR UPDATE on Invoices and only one non-archived refund is allowed per invoice; both UI and Greenfield paths enforce this. (3) Greenfield ApprovePayout now requires CanCreatePullPayments when an explicit RateRule is supplied, preventing payout managers from overriding store rates. (4) BitcoinLikePaymentHandler now preserves IsHotWallet only when the derivation scheme matches the previous config, blocking hot-wallet flag migration to a different xpub. (5) SpeedPolicy.HighSpeed is normalized to MediumSpeed everywhere, removing the zero-confirmation path. (6) UIUserMonetizationController.NewUser and UILNURLController.GetLNURLForInvoice receive rate-limiting. (7) PayJoinEndpointController records payjoin outpoints in PlannedTransaction and only schedules original-transaction broadcast when linked to an invoice; DelayedTransactionBroadcaster releases UTXO locks after broadcast. (8) PluginManager dependency resolution now detects cycles, avoids duplicate downloads, and preserves pending install state on failure. (9) OnChainAutomatedPayoutProcessor uses MarkPaid claims with expected-state/proof checks and reverts on broadcast failure. (10) Multisig setup validates signer readiness before confirmation. No CVE or vendor advisory is present in the supplied materials.
Changed components
BTCPayServer.Blazor (CircuitUserRevalidator, RevalidatingAuthenticationStateProvider)BTCPayServer.Controllers.UIAccountControllerBTCPayServer.Controllers.UIInvoiceController / GreenfieldInvoiceControllerBTCPayServer.Controllers.Greenfield.GreenfieldPullPaymentControllerBTCPayServer.HostedServices.PullPaymentHostedServiceBTCPayServer.Payments.Bitcoin.BitcoinLikePaymentHandler / NBXplorerListenerBTCPayServer.Payments.PayJoin.PayJoinEndpointControllerBTCPayServer.Payments.Lightning.UILNURLController / LightningListenerBTCPayServer.PayoutProcessors.OnChain.OnChainAutomatedPayoutProcessorBTCPayServer.Plugins.PluginManager / PluginServiceBTCPayServer.Plugins.Monetization / Subscriptions / MultisigInspect captured patch +1310 / −416
### BTCPayServer.Client/Models/InvoiceData.cs
@@ -65,9 +65,14 @@ public static ReceiptOptions CreateDefault()
}
public class CheckoutOptions
{
+ private SpeedPolicy? _speedPolicy;
[JsonConverter(typeof(StringEnumConverter))]
- public SpeedPolicy? SpeedPolicy { get; set; }
+ public SpeedPolicy? SpeedPolicy
+ {
+ get => _speedPolicy?.Normalize();
+ set => _speedPolicy = value?.Normalize();
+ }
public string[] PaymentMethods { get; set; }
public string DefaultPaymentMethod { get; set; }
### BTCPayServer.Client/Models/StoreBaseData.cs
@@ -43,8 +43,14 @@ public abstract class StoreBaseData
[JsonConverter(typeof(TimeSpanJsonConverter.WholeDays))]
public TimeSpan? PublicInvoiceExpiration { get; set; }
+ private SpeedPolicy? _speedPolicy;
+
[JsonConverter(typeof(StringEnumConverter))]
- public SpeedPolicy? SpeedPolicy { get; set; }
+ public SpeedPolicy? SpeedPolicy
+ {
+ get => _speedPolicy?.Normalize();
+ set => _speedPolicy = value?.Normalize();
+ }
public string LightningDescriptionTemplate { get; set; }
public double? PaymentTolerance { get; set; }
public bool? AnyoneCanCreateInvoice { get; set; }
@@ -109,9 +115,16 @@ public enum NetworkFeeMode
public enum SpeedPolicy
{
+ // Retained for stored data and older clients; Normalize maps it to MediumSpeed.
HighSpeed = 0,
MediumSpeed = 1,
LowSpeed = 2,
LowMediumSpeed = 3
}
+
+ public static class SpeedPolicyExtensions
+ {
+ public static SpeedPolicy Normalize(this SpeedPolicy speedPolicy)
+ => speedPolicy == SpeedPolicy.HighSpeed ? SpeedPolicy.MediumSpeed : speedPolicy;
+ }
}
### BTCPayServer.Data/Data/PlannedTransaction.cs
@@ -10,5 +10,7 @@ public class PlannedTransaction
public string Id { get; set; } // Id in the format [cryptocode]-[txid]
public DateTimeOffset BroadcastAt { get; set; }
public byte[] Blob { get; set; }
+ public string PayjoinTransactionId { get; set; }
+ public string[] PayjoinOutpoints { get; set; }
}
}
### BTCPayServer.Data/Data/StoreData.cs
@@ -26,7 +26,13 @@ public class StoreData
public string StoreName { get; set; }
- public SpeedPolicy SpeedPolicy { get; set; } = SpeedPolicy.MediumSpeed;
+ private SpeedPolicy _speedPolicy = SpeedPolicy.MediumSpeed;
+
+ public SpeedPolicy SpeedPolicy
+ {
+ get => _speedPolicy.Normalize();
+ set => _speedPolicy = value.Normalize();
+ }
public string StoreWebsite { get; set; }
### BTCPayServer.Data/Migrations/20261118085602_AddPlannedPayjoinCleanup.cs
@@ -0,0 +1,29 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+using BTCPayServer.Data;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+
+#nullable disable
+
+namespace BTCPayServer.Migrations
+{
+ [DbContext(typeof(ApplicationDbContext))]
+ [Migration("20261118085602_AddPlannedPayjoinCleanup")]
+ public partial class AddPlannedPayjoinCleanup : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<string[]>(
+ name: "PayjoinOutpoints",
+ table: "PlannedTransactions",
+ type: "text[]",
+ nullable: true);
+
+ migrationBuilder.AddColumn<string>(
+ name: "PayjoinTransactionId",
+ table: "PlannedTransactions",
+ type: "text",
+ nullable: true);
+ }
+ }
+}
### BTCPayServer.Data/Migrations/ApplicationDbContextModelSnapshot.cs
@@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
- .HasAnnotation("ProductVersion", "10.0.14")
+ .HasAnnotation("ProductVersion", "10.0.15")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -902,6 +902,12 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<DateTimeOffset>("BroadcastAt")
.HasColumnType("timestamp with time zone");
+ b.PrimitiveCollection<string[]>("PayjoinOutpoints")
+ .HasColumnType("text[]");
+
+ b.Property<string>("PayjoinTransactionId")
+ .HasColumnType("text");
+
b.HasKey("Id");
b.ToTable("PlannedTransactions");
### BTCPayServer.Tests/AuthorizationPolicyTests.cs
@@ -4,8 +4,10 @@
using BTCPayServer.Client;
using BTCPayServer.Controllers;
using BTCPayServer.Controllers.Greenfield;
+using BTCPayServer.Plugins.Monetization.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using NicolasDorier.RateLimits;
using Xunit;
namespace BTCPayServer.Tests;
@@ -57,4 +59,15 @@ public void FileUploadRequiresAntiforgeryValidation()
Assert.NotNull(method);
Assert.Empty(method.GetCustomAttributes<IgnoreAntiforgeryTokenAttribute>(true));
}
+
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public void AnonymousMonetizationSignupIsRateLimited()
+ {
+ var method = typeof(UIUserMonetizationController).GetMethod(nameof(UIUserMonetizationController.NewUser));
+ Assert.NotNull(method);
+ var limit = Assert.Single(method.GetCustomAttributes<RateLimitsFilterAttribute>(true));
+ Assert.Equal(ZoneLimits.PublicInvoices, limit.ZoneName);
+ Assert.Equal(RateLimitsScope.RemoteAddress, limit.Scope);
+ }
}
### BTCPayServer.Tests/CircuitUserRevalidatorTests.cs
@@ -0,0 +1,55 @@
+using System.Security.Claims;
+using System.Threading.Tasks;
+using BTCPayServer.Blazor;
+using BTCPayServer.Data;
+using BTCPayServer.Services;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.Extensions.DependencyInjection;
+using Xunit;
+
+namespace BTCPayServer.Tests;
+
+public class CircuitUserRevalidatorTests(ITestOutputHelper helper) : UnitTestBase(helper)
+{
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public async Task RevalidateRefusesPrincipalWithoutAuthenticatedIdentity()
+ {
+ var revalidator = new CircuitUserRevalidator(new UnusableScopeFactory());
+
+ Assert.Null(await revalidator.Revalidate(null));
+ Assert.Null(await revalidator.Revalidate(new ClaimsPrincipal(new ClaimsIdentity())));
+ Assert.Null(await revalidator.Revalidate(new ClaimsPrincipal(
+ new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "someone")]))));
+ }
+
+ [Fact(Timeout = TestUtils.TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task RevalidateRefusesCircuitWithStaleAdminRole()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var account = tester.NewAccount();
+ await account.RegisterAsync(isAdmin: true);
+ await using var scope = tester.PayTester.ServiceProvider.CreateAsyncScope();
+ var signInManager = scope.ServiceProvider.GetRequiredService<SignInManager<ApplicationUser>>();
+ var user = await signInManager.UserManager.FindByIdAsync(account.UserId);
+ var adminPrincipal = await signInManager.CreateUserPrincipalAsync(user);
+ Assert.True(adminPrincipal.IsInRole(Roles.ServerAdmin));
+ var revalidator = scope.ServiceProvider.GetRequiredService<CircuitUserRevalidator>();
+ Assert.NotNull(await revalidator.Revalidate(adminPrincipal));
+
+ var userService = scope.ServiceProvider.GetRequiredService<UserService>();
+ Assert.True(await userService.SetAdminUser(account.UserId, false));
+ Assert.Null(await revalidator.Revalidate(adminPrincipal));
+ }
+
+ private class UnusableScopeFactory : IServiceScopeFactory
+ {
+ public IServiceScope CreateScope()
+ {
+ Assert.Fail("An unauthenticated principal must be refused before any service is resolved.");
+ return null;
+ }
+ }
+}
### BTCPayServer.Tests/FastTests.cs
@@ -23,6 +23,7 @@
using BTCPayServer.Hosting;
using BTCPayServer.JsonConverters;
using BTCPayServer.Payments;
+using BTCPayServer.Payments.Bitcoin;
using BTCPayServer.Plugins.Wallets.Views.ViewModels;
using BTCPayServer.Rating;
using BTCPayServer.Security;
@@ -37,6 +38,7 @@
using BTCPayServer.Services.WalletFileParsing;
using BTCPayServer.Validation;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.DependencyInjection;
@@ -818,6 +820,18 @@ public void CanRenderInvoiceUriTemplates()
Assert.Equal("https://example.com/{invalid[}?orderId=", entity.NotificationURL.OriginalString);
}
+ [Fact]
+ public void CanOnlyMarkInvoiceStatusOnce()
+ {
+ var settled = new InvoiceState(InvoiceStatus.Settled, InvoiceExceptionStatus.Marked);
+ Assert.False(settled.CanMarkComplete());
+ var invalid = new InvoiceState(InvoiceStatus.Invalid, InvoiceExceptionStatus.Marked);
+ Assert.False(invalid.CanMarkInvalid());
+ // An invoice marked invalid can still be marked settled afterwards.
+ Assert.True(invalid.CanMarkComplete());
+ Assert.True(new InvoiceState(InvoiceStatus.New, InvoiceExceptionStatus.None).CanMarkComplete());
+ }
+
[Fact]
public void CanCalculateDust()
{
@@ -866,6 +880,73 @@ public void CanCalculateDust()
#pragma warning restore CS0618
}
+ [Fact]
+ public void CanCalculateConfirmationRequired()
+ {
+ static InvoiceEntity Invoice(SpeedPolicy policy) => new() { SpeedPolicy = policy };
+ static BitcoinLikePaymentData Payment() => new();
+
+ Assert.Equal(1, NBXplorerListener.ConfirmationRequired(Invoice(SpeedPolicy.HighSpeed), Payment()));
+ Assert.Equal(1, NBXplorerListener.ConfirmationRequired(Invoice(SpeedPolicy.MediumSpeed), Payment()));
+ Assert.Equal(2, NBXplorerListener.ConfirmationRequired(Invoice(SpeedPolicy.LowMediumSpeed), Payment()));
+ Assert.Equal(6, NBXplorerListener.ConfirmationRequired(Invoice(SpeedPolicy.LowSpeed), Payment()));
+ }
+
+ [Fact]
+ public void LegacyHighSpeedNormalizesToMedium()
+ {
+ var store = new BTCPayServer.Data.StoreData { SpeedPolicy = SpeedPolicy.HighSpeed };
+ var invoice = new InvoiceEntity { SpeedPolicy = SpeedPolicy.HighSpeed };
+ Assert.Equal(SpeedPolicy.MediumSpeed, store.SpeedPolicy);
+ Assert.Equal(1, NBXplorerListener.ConfirmationRequired(invoice, new BitcoinLikePaymentData()));
+
+ var apiStore = JsonConvert.DeserializeObject<BTCPayServer.Client.Models.StoreData>(
+ "{\"speedPolicy\":\"HighSpeed\"}");
+ Assert.Equal(SpeedPolicy.MediumSpeed, apiStore.SpeedPolicy);
+ Assert.Contains("\"MediumSpeed\"", JsonConvert.SerializeObject(apiStore));
+
+ var apiInvoice = JsonConvert.DeserializeObject<BTCPayServer.Client.Models.InvoiceData>(
+ "{\"checkout\":{\"speedPolicy\":\"HighSpeed\"}}");
+ Assert.Equal(SpeedPolicy.MediumSpeed, apiInvoice.Checkout.SpeedPolicy);
+ }
+
+ [Fact]
+ public void CanKeepHotWalletOnConfigUpdate()
+ {
+ var network = CreateNetworkProvider(ChainName.Regtest).GetNetwork<BTCPayNetwork>("BTC");
+ var handler = new BitcoinLikePaymentHandler(BTC, null, network, null, null, null, null, null);
+ DerivationSchemeSettings HotWallet(string xpub) =>
+ new(network.GetDerivationSchemeParser().Parse(xpub), network) { IsHotWallet = true };
+ string NewXpub() => new ExtKey().Neuter().GetWif(network.NBitcoinNetwork).ToString();
+
+ var xpub = NewXpub();
+ var previous = JToken.FromObject(HotWallet(xpub), handler.Serializer);
+
+ var ctx = Validate(handler, new JObject { ["derivationScheme"] = xpub }, previous);
+ Assert.True(ctx.ModelState.IsValid);
+ Assert.True(handler.ParsePaymentMethodConfig(ctx.Config).IsHotWallet);
+
+ ctx = Validate(handler, JToken.FromObject(xpub), previous);
+ Assert.True(ctx.ModelState.IsValid);
+ Assert.True(handler.ParsePaymentMethodConfig(ctx.Config).IsHotWallet);
+
+ // Pointing at another wallet gives no reason to believe we hold its keys
+ ctx = Validate(handler, new JObject { ["derivationScheme"] = NewXpub() }, previous);
+ Assert.True(ctx.ModelState.IsValid);
+ Assert.False(handler.ParsePaymentMethodConfig(ctx.Config).IsHotWallet);
+
+ var watchOnly = JToken.FromObject(new DerivationSchemeSettings(network.GetDerivationSchemeParser().Parse(xpub), network), handler.Serializer);
+ ctx = Validate(handler, JToken.FromObject(HotWallet(xpub), handler.Serializer), watchOnly);
+ Assert.False(ctx.ModelState.IsValid);
+ }
+
+ private static PaymentMethodConfigValidationContext Validate(BitcoinLikePaymentHandler handler, JToken config, JToken previousConfig)
+ {
+ var ctx = new PaymentMethodConfigValidationContext(null, new ModelStateDictionary(), config, null, previousConfig, null);
+ handler.ValidatePaymentMethodConfig(ctx).GetAwaiter().GetResult();
+ return ctx;
+ }
+
[Fact]
public void CanCalculateCryptoDue()
{
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -1460,6 +1460,47 @@ private static async Task<HttpResponseMessage> PostRaw(ServerTester tester, stri
return await http.SendAsync(req);
}
+ [Fact(Timeout = TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task ApprovePayoutRateRuleRequiresPullPaymentPermission()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var acc = tester.NewAccount();
+ await acc.RegisterAsync();
+ await acc.CreateStoreAsync();
+ var storeId = (await acc.RegisterDerivationSchemeAsync("BTC", importKeysToNBX: true)).StoreId;
+ var client = await acc.CreateClient();
+ var payoutsClient = await acc.CreateClient(Policies.CanManagePayouts);
+ var pp = await client.CreatePullPayment(storeId, new CreatePullPaymentRequest()
+ {
+ Name = "Test USD",
+ Amount = 5000m,
+ Currency = "USD",
+ PayoutMethods = new[] { "BTC" }
+ });
+ var address = await tester.ExplorerNode.GetNewAddressAsync();
+ var payout = await client.CreatePayout(pp.Id, new CreatePayoutRequest()
+ {
+ Destination = address.ToString(),
+ PayoutMethodId = "BTC"
+ });
+
+ await AssertHttpError(403, async () => await payoutsClient.ApprovePayout(payout.Id, new ApprovePayoutRequest()
+ {
+ Revision = payout.Revision,
+ RateRule = "1"
+ }));
+
+ // Without an explicit rate the payouts permission alone still approves, at the store rate.
+ var approved = await payoutsClient.ApprovePayout(payout.Id, new ApprovePayoutRequest()
+ {
+ Revision = payout.Revision
+ });
+ Assert.Equal(PayoutState.AwaitingPayment, approved.State);
+ Assert.Equal(1.0m, approved.PayoutAmount);
+ }
+
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanProcessPayoutsExternally()
@@ -1832,7 +1873,7 @@ await clientProfile.UpdateCurrentUser(new UpdateApplicationUserRequest
await clientBasic.GetCurrentUser();
}
});
- Assert.Contains("Rate limited", err.Message);
+ Assert.Equal("Basic authentication failed", err.Message);
}
[Fact(Timeout = TestTimeout)]
@@ -2076,7 +2117,19 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Equal(1, pp.Amount);
Assert.Equal(pp.Name, $"Refund {invoice.Id}");
+ // a further non-Custom refund is refused while that one is still open
+ validationError = await AssertValidationError(new[] { "RefundVariant" }, async () =>
+ {
+ await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest()
+ {
+ PayoutMethodId = method.PaymentMethodId,
+ RefundVariant = RefundVariant.RateThen
+ });
+ });
+ Assert.Contains("already has a refund", validationError.Message, StringComparison.OrdinalIgnoreCase);
+
// test RefundVariant.CurrentRate
+ await client.ArchivePullPayment(pp.Id);
pp = await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest()
{
PayoutMethodId = method.PaymentMethodId,
@@ -2087,6 +2140,7 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Equal(1, pp.Amount);
// test RefundVariant.Fiat
+ await client.ArchivePullPayment(pp.Id);
pp = await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest()
{
PayoutMethodId = method.PaymentMethodId,
@@ -2097,6 +2151,7 @@ await TestUtils.EventuallyAsync(async () =>
Assert.False(pp.AutoApproveClaims);
Assert.Equal(5000, pp.Amount);
Assert.Equal("my test name", pp.Name);
+ var fiatRefundId = pp.Id;
// test RefundVariant.Custom
validationError = await AssertValidationError(new[] { "CustomAmount", "CustomCurrency" }, async () =>
@@ -2120,6 +2175,7 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Equal("JPY", pp.Currency);
Assert.False(pp.AutoApproveClaims);
Assert.Equal(69420, pp.Amount);
+ var customRefundId = pp.Id;
// should auto-approve if currencies match
pp = await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest()
@@ -2155,6 +2211,9 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Contains("Refund amount must be greater than 0", validationError.Message);
// should auto-approve
+ await client.ArchivePullPayment(fiatRefundId);
+ await client.ArchivePullPayment(customRefundId);
+ await client.ArchivePullPayment(pp.Id);
pp = await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest
{
PayoutMethodId = method.PaymentMethodId,
@@ -2217,6 +2276,7 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Equal(method.Due, pp.Amount);
// once more with subtract percentage
+ await client.ArchivePullPayment(pp.Id);
pp = await client.RefundInvoice(invoice.Id, new RefundInvoiceRequest
{
PayoutMethodId = method.PaymentMethodId,
@@ -4462,16 +4522,31 @@ await tester.WaitForEvent<NewOnChainTransactionEvent>(async () =>
break;
}
};
+ var destination = (await adminClient.GetOnChainWalletReceiveAddress(admin.StoreId, "BTC", true)).Address;
+ var destinationScript = BitcoinAddress.Create(destination, tester.ExplorerClient.Network.NBitcoinNetwork).ScriptPubKey;
+ var claimedBeforeBroadcast = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
+ var eventAggregator = tester.PayTester.GetService<EventAggregator>();
+ using var claimSubscription = eventAggregator.SubscribeAny<PayoutEvent>(evt =>
+ {
+ if (evt.Payout.State == PayoutState.InProgress && evt.Payout.DedupId == destination)
+ claimedBeforeBroadcast.TrySetResult(true);
+ });
+ using var broadcastSubscription = eventAggregator.SubscribeAny<NewOnChainTransactionEvent>(evt =>
+ {
+ if (evt.NewTransactionEvent.TransactionData.Transaction?.Outputs.Any(o => o.ScriptPubKey == destinationScript) is true)
+ claimedBeforeBroadcast.TrySetResult(false);
+ });
var payoutThatShouldBeProcessedStraightAway = await adminClient.CreatePayout(admin.StoreId, new CreatePayoutThroughStoreRequest()
{
PullPaymentId = pullPayment.Id,
Amount = 0.5m,
Approved = true,
PayoutMethodId = "BTC",
- Destination = (await adminClient.GetOnChainWalletReceiveAddress(admin.StoreId, "BTC", true)).Address,
+ Destination = destination,
});
await beforeHookTcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
await afterHookTcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ Assert.True(await claimedBeforeBroadcast.Task.WaitAsync(TimeSpan.FromSeconds(5)));
payouts = await adminClient.GetStorePayouts(admin.StoreId);
try
{
### BTCPayServer.Tests/LightningTests.cs
@@ -765,7 +765,7 @@ public async Task EnsureNewLightningInvoiceOnPartialPayment()
await user.RegisterDerivationSchemeAsync("BTC");
await user.RegisterLightningNodeAsync("BTC", LightningTestImplementation.CoreLightning);
await user.SetNetworkFeeMode(NetworkFeeMode.Never);
- await user.ModifyGeneralSettings(p => p.SpeedPolicy = SpeedPolicy.HighSpeed);
+ await user.ModifyGeneralSettings(p => p.SpeedPolicy = SpeedPolicy.MediumSpeed);
var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice(0.0001m, "BTC"));
await tester.WaitForEvent<InvoiceNewPaymentDetailsEvent>(async () =>
{
@@ -775,6 +775,7 @@ await tester.ExplorerNode.SendToAddressAsync(
Replaceable = false
});
}, e => e.InvoiceId == invoice.Id && e.PaymentMethodId == PaymentTypes.LN.GetPaymentMethodId("BTC"));
+ await tester.ExplorerNode.GenerateAsync(1); // On-chain BTC payments need 1 confirmation to settle
Invoice newInvoice = null;
await TestUtils.EventuallyAsync(async () =>
{
### BTCPayServer.Tests/MonetizationTests.cs
@@ -399,7 +399,7 @@ public async Task CanBypassMonetizationForUsers()
await s.FindAlertMessage(partialText: "is now test");
await using (var portal = await offeringPMO.GoToPortal("enrolled-invited@gmail.com", closeAfter: false))
{
- await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(portal.GoToNextPhase);
+ await s.Server.WaitForEvent<SubscriptionEvent.SubscriberPhaseChanged>(portal.GoToNextPhase);
}
await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(async () =>
{
### BTCPayServer.Tests/PSBTTests.cs
@@ -1,6 +1,8 @@
using System.Linq;
using System.Threading.Tasks;
+using BTCPayServer.Controllers;
using BTCPayServer.Plugins.Wallets.Views.ViewModels;
+using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using NBitcoin;
using Xunit;
@@ -24,6 +26,38 @@ public async Task RejectsOversizedTextualPSBTBeforeParsing()
Assert.Contains(modelState["PSBT"].Errors, error => error.ErrorMessage == "The PSBT is too large.");
}
+ [Fact]
+ [Trait("Fast", "Fast")]
+ public void SeedSigningLinkOnlyCarriesTheTransactionToSign()
+ {
+ // The seed signing GET touches no service, so an instance without dependencies is enough.
+ var controller = new UIWalletsController(null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null);
+
+ var result = Assert.IsType<ViewResult>(controller.SignWithSeed(null, new SigningContextModel
+ {
+ PSBT = "the-psbt",
+ EnforceLowR = false,
+ OriginalPSBT = "the-original-psbt",
+ PendingTransactionId = "the-pending-transaction",
+ PayJoinBIP21 = "the-bip21",
+ ChangeAddress = "the-change-address",
+ Comment = "the-comment",
+ BalanceChangeFromReplacement = long.MaxValue
+ }, null, null));
+
+ var signingContext = Assert.IsType<SignWithSeedViewModel>(result.Model).SigningContext;
+ Assert.Equal("the-psbt", signingContext.PSBT);
+ Assert.False(signingContext.EnforceLowR);
+ Assert.Null(signingContext.OriginalPSBT);
+ Assert.Null(signingContext.PendingTransactionId);
+ Assert.Null(signingContext.PayJoinBIP21);
+ Assert.Null(signingContext.ChangeAddress);
+ Assert.Null(signingContext.Comment);
+ Assert.Equal(0, signingContext.BalanceChangeFromReplacement);
+ }
+
[Fact]
[Trait("Fast", "Fast")]
public void AddsWitnessUtxoToSegwitInputs()
### BTCPayServer.Tests/PayJoinTests.cs
@@ -59,6 +59,35 @@ public async Task CanUseTheDelayedBroadcaster()
Assert.Equal(1, await broadcaster.ProcessAll());
Assert.Equal(0, await broadcaster.ProcessAll());
}
+
+ [Fact]
+ [Trait("Integration", "Integration")]
+ public async Task DelayedPayjoinReleasesThePersistedLockAfterBroadcast()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var network = tester.NetworkProvider.GetNetwork<BTCPayNetwork>("BTC");
+ var broadcaster = tester.PayTester.GetService<DelayedTransactionBroadcaster>();
+ var locks = tester.PayTester.GetService<UTXOLocker>();
+ var address = new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network.NBitcoinNetwork);
+ var txid = await tester.ExplorerNode.SendToAddressAsync(address, Money.Coins(0.01m));
+ var original = await tester.ExplorerNode.GetRawTransactionAsync(txid);
+ await tester.ExplorerNode.GenerateAsync(1);
+
+ var outpoint = RandomOutpoint();
+ Assert.True(await locks.TryLock(outpoint));
+ var broadcastAt = DateTimeOffset.UtcNow.AddSeconds(-1);
+ await broadcaster.Schedule(broadcastAt, original, network);
+ await broadcaster.Schedule(broadcastAt, original, network, RandomOutpoint().Hash, [outpoint]);
+ var restartedBroadcaster = new DelayedTransactionBroadcaster(tester.NetworkProvider,
+ tester.PayTester.GetService<ExplorerClientProvider>(),
+ tester.PayTester.GetService<ApplicationDbContextFactory>(), broadcaster.Logs);
+ Assert.Contains(outpoint, await locks.FindLocks([outpoint]));
+ Assert.Equal(1, await restartedBroadcaster.ProcessAll());
+ Assert.Empty(await locks.FindLocks([outpoint]));
+ Assert.Equal(0, await restartedBroadcaster.ProcessAll());
+ }
+
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUsePayjoinRepository()
### BTCPayServer.Tests/PluginManagerTests.cs
@@ -188,6 +188,92 @@ public async Task DownloadRemotePlugin_RejectsManifestIdentifierMismatch()
}
}
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task DownloadPluginAndDependencies_LeavesPendingInstallIntactWhenDependenciesAreCyclic(bool dependencyInstalled)
+ {
+ using var httpClient = CreatePluginCatalogClient(
+ MakeAvailablePlugin("PluginA", "1.0.0", ("pluginb", ">=1.0.0")),
+ MakeAvailablePlugin("PluginB", "1.0.0", ("plugina", ">=1.0.0")));
+ IBTCPayServerPlugin[] loaded = dependencyInstalled
+ ? [MakeLoadedPlugin("PluginB", ("PluginA", ">=1.0.0"))]
+ : [];
+ var pluginDir = Path.Combine(Path.GetTempPath(), $"btcpay-plugin-cycle-test-{Guid.NewGuid():N}");
+ Directory.CreateDirectory(pluginDir);
+ try
+ {
+ var pendingArchive = Path.Combine(pluginDir, "PluginA.btcpay");
+ byte[] originalContents = [0x00, 0x01];
+ await File.WriteAllBytesAsync(pendingArchive, originalContents);
+ PluginManager.QueueCommands(pluginDir, ("install", "PluginA"));
+ var controller = CreatePluginManagerController(pluginDir, loaded, httpClient);
+
+ var error = await controller.DownloadPluginAndDependencies("PluginA", null);
+
+ Assert.Contains("cycl", error, StringComparison.OrdinalIgnoreCase);
+ Assert.Equal(("install", "PluginA"), Assert.Single(PluginManager.GetPendingCommands(pluginDir)));
+ Assert.Equal(originalContents, await File.ReadAllBytesAsync(pendingArchive));
+ Assert.False(File.Exists(Path.Combine(pluginDir, "PluginB.btcpay")));
+ }
+ finally
+ {
+ Directory.Delete(pluginDir, true);
+ }
+ }
+
+ [Fact]
+ public async Task DownloadPluginAndDependencies_SchedulesSharedDependencyOnlyOnce()
+ {
+ using var httpClient = CreatePluginCatalogClient(
+ MakeAvailablePlugin("PluginA", "1.0.0", ("PluginB", ">=1.0.0"), ("PluginC", ">=1.0.0")),
+ MakeAvailablePlugin("PluginB", "1.0.0", ("plugind", ">=1.0.0")),
+ MakeAvailablePlugin("PluginC", "1.0.0", ("PluginD", ">=1.0.0")),
+ MakeAvailablePlugin("PluginD", "1.0.0"));
+ var pluginDir = Path.Combine(Path.GetTempPath(), $"btcpay-plugin-dependencies-test-{Guid.NewGuid():N}");
+ try
+ {
+ var controller = CreatePluginManagerController(pluginDir, [], httpClient);
+
+ var error = await controller.DownloadPluginAndDependencies("PluginA", null);
+
+ Assert.Null(error);
+ Assert.Equal(
+ new[] { "PluginD", "PluginB", "PluginC", "PluginA" },
+ PluginManager.GetPendingCommands(pluginDir).Select(command => command.plugin));
+ Assert.True(File.Exists(Path.Combine(pluginDir, "PluginD.btcpay")));
+ }
+ finally
+ {
+ if (Directory.Exists(pluginDir))
+ Directory.Delete(pluginDir, true);
+ }
+ }
+
+ private static HttpClient CreatePluginCatalogClient(params PluginService.AvailablePlugin[] plugins)
+ {
+ var catalog = plugins.ToDictionary(plugin => plugin.Identifier, StringComparer.OrdinalIgnoreCase);
+ return new HttpClient(new TestHttpMessageHandler(request =>
+ {
+ var path = Uri.UnescapeDataString(request.RequestUri!.AbsolutePath);
+ var identifier = path.Split('/')[4].Trim('[', ']');
+ if (!catalog.TryGetValue(identifier, out var plugin))
+ return new HttpResponseMessage(HttpStatusCode.NotFound);
+ if (path.EndsWith("/download", StringComparison.Ordinal))
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent([0x50, 0x4b]) };
+
+ var manifest = JsonConvert.SerializeObject(new
+ {
+ projectSlug = plugin.CatalogSlug,
+ buildId = 1,
+ manifestInfo = plugin,
+ buildInfo = new { }
+ });
+ return TestHttpMessageHandler.JsonResponse(
+ path.Contains("/versions/", StringComparison.Ordinal) ? manifest : $"[{manifest}]");
+ })) { BaseAddress = new Uri("https://plugins.example/") };
+ }
+
[Fact]
public async Task InstalledPluginsViewModel_DropsUnsafeMetadataLinks()
{
### BTCPayServer.Tests/RateAccountingSecurityTests.cs
@@ -1,11 +1,20 @@
+using System;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
+using BTCPayServer.Abstractions.Models;
using BTCPayServer.Data;
+using BTCPayServer.HostedServices;
using BTCPayServer.Logging;
using BTCPayServer.Payments;
+using BTCPayServer.Payments.Bitcoin;
+using BTCPayServer.Payouts;
using BTCPayServer.Rating;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Rates;
+using Microsoft.AspNetCore.Mvc;
+using NBitcoin;
+using NBXplorer;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
@@ -92,6 +101,59 @@ await context.FetchingRates(
Assert.False(invoice.TryGetRate("BTC", out _));
}
+ [Fact]
+ public async Task PayoutApprovalRateIgnoresStoreSpread()
+ {
+ var network = new BTCPayNetwork
+ {
+ CryptoCode = "BTC",
+ NBXplorerNetwork = new NBXplorerNetworkProvider(ChainName.Regtest).GetFromCryptoCode("BTC")
+ };
+ var handlers = new PayoutMethodHandlerDictionary([new TestPayoutHandler(network)]);
+ var store = new StoreData { Id = "store" };
+ store.SetStoreBlob(new StoreBlob
+ {
+ Spread = 0.5m,
+ PrimaryRateSettings = new StoreBlob.RateSettings
+ {
+ RateScripting = true,
+ RateScript = "BTC_USD = 100;"
+ }
+ });
+ var payout = new Data.PayoutData
+ {
+ StoreDataId = store.Id,
+ StoreData = store,
+ PayoutMethodId = PayoutTypes.CHAIN.GetPayoutMethodId("BTC").ToString(),
+ PullPaymentData = new Data.PullPaymentData { Currency = "USD" }
+ };
+ var service = new PullPaymentHostedService(null, null, null, null, handlers,
+ new DefaultRulesCollection([new DefaultRules("X_X = kraken(X_X);")]), null,
+ new RateFetcher(null!), null, new Logs(), null, null, null);
+
+ var rate = await service.GetRate(payout, null, CancellationToken.None);
+
+ Assert.Equal(100m, rate.BidAsk.Ask);
+ }
+
+ private sealed class TestPayoutHandler(BTCPayNetwork network) : IPayoutHandler, IHasNetwork
+ {
+ public BTCPayNetwork Network { get; } = network;
+ public string Currency => Network.CryptoCode;
+ public PayoutMethodId PayoutMethodId { get; } = PayoutTypes.CHAIN.GetPayoutMethodId(network.CryptoCode);
+ public bool IsSupported(StoreData storeData) => true;
+ public Task TrackClaim(ClaimRequest claimRequest, Data.PayoutData payoutData) => throw new NotImplementedException();
+ public Task<(IClaimDestination destination, string error)> ParseClaimDestination(string destination, CancellationToken cancellationToken) => throw new NotImplementedException();
+ public (bool valid, string error) ValidateClaimDestination(IClaimDestination claimDestination, PullPaymentBlob pullPaymentBlob) => throw new NotImplementedException();
+ public IPayoutProof ParseProof(Data.PayoutData payout) => throw new NotImplementedException();
+ public void StartBackgroundCheck(Action<Type[]> subscribe) => throw new NotImplementedException();
+ public Task BackgroundCheck(object o) => throw new NotImplementedException();
+ public Task<decimal> GetMinimumPayoutAmount(IClaimDestination claimDestination) => throw new NotImplementedException();
+ public Dictionary<Client.Models.PayoutState, List<(string Action, string Text)>> GetPayoutSpecificActions() => throw new NotImplementedException();
+ public Task<StatusMessageModel> DoSpecificAction(string action, string[] payoutIds, string storeId) => throw new NotImplementedException();
+ public Task<IActionResult> InitiatePayment(string[] payoutIds) => throw new NotImplementedException();
+ }
+
private sealed class TestPaymentMethodHandler : IPaymentMethodHandler
{
public PaymentMethodId PaymentMethodId { get; } = PaymentMethodId.Parse("BTC-NEGATIVE");
### BTCPayServer.Tests/SubscriptionTests.cs
@@ -1083,6 +1083,8 @@ await offering.AssertHasSubscriber("basic2@example.com",
Assert.True(disabled.Subscriber.IsSuspended);
Assert.Equal(disabled.Subscriber.SuspensionReason, disabled.SuspensionReason);
Assert.Equal("The plan has been started by an invoice which later became invalid.", disabled.Subscriber.SuspensionReason);
+ Assert.NotNull(disabled.Subscriber.PaidAmount);
+ Assert.Equal(-disabled.Subscriber.PaidAmount.Value, disabled.Subscriber.GetCredit());
await s.FastReloadAsync();
### BTCPayServer/Blazor/CircuitUserRevalidator.cs
@@ -0,0 +1,42 @@
+#nullable enable
+using System.Security.Claims;
+using System.Threading.Tasks;
+using BTCPayServer.Data;
+using BTCPayServer.Services;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace BTCPayServer.Blazor;
+
+/// <summary>
+/// A Blazor circuit keeps the principal it connected with, so a component acting later must
+/// confirm against the database that the account behind it is still allowed to act.
+/// </summary>
+public class CircuitUserRevalidator(IServiceScopeFactory serviceScopeFactory)
+{
+ public async Task<ApplicationUser?> Revalidate(ClaimsPrincipal? principal, string? requiredRole = null)
+ {
+ if (principal?.Identity?.IsAuthenticated is not true)
+ return null;
+
+ // A fresh scope: the circuit's own services cache the user loaded when it connected.
+ await using var scope = serviceScopeFactory.CreateAsyncScope();
+ var signInManager = scope.ServiceProvider.GetRequiredService<SignInManager<ApplicationUser>>();
+ var user = await signInManager.ValidateSecurityStampAsync(principal);
+ if (user is null)
+ return null;
+
+ var userService = scope.ServiceProvider.GetRequiredService<UserService>();
+ if (!await userService.CanLogin(new UserService.CanLoginContext(user)))
+ return null;
+
+ if (requiredRole is not null && !await signInManager.UserManager.IsInRoleAsync(user, requiredRole))
+ return null;
+
+ if (requiredRole != Roles.ServerAdmin && principal.IsInRole(Roles.ServerAdmin) &&
+ !await signInManager.UserManager.IsInRoleAsync(user, Roles.ServerAdmin))
+ return null;
+
+ return user;
+ }
+}
### BTCPayServer/Blazor/RevalidatingAuthenticationStateProvider.cs
@@ -0,0 +1,23 @@
+#nullable enable
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Components.Authorization;
+using Microsoft.AspNetCore.Components.Server;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace BTCPayServer.Blazor;
+
+public class RevalidatingAuthenticationStateProvider(
+ CircuitUserRevalidator circuitUserRevalidator,
+ IOptions<SecurityStampValidatorOptions> securityStampValidatorOptions,
+ ILoggerFactory loggerFactory) : RevalidatingServerAuthenticationStateProvider(loggerFactory)
+{
+ // Revoked circuits drop their authentication within the same window as cookies.
+ protected override TimeSpan RevalidationInterval => securityStampValidatorOptions.Value.ValidationInterval;
+
+ protected override async Task<bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken)
+ => await circuitUserRevalidator.Revalidate(authenticationState.User) is not null;
+}
### BTCPayServer/Controllers/GreenField/GreenfieldInvoiceController.cs
@@ -511,7 +511,12 @@ public async Task<IActionResult> RefundInvoice(
}
createPullPayment.AutoApproveClaims = createPullPayment.AutoApproveClaims && (await _authorizationService.AuthorizeAsync(User, storeId ,Policies.CanCreatePullPayments)).Succeeded;
- var ppId = await _pullPaymentService.CreateRefundPullPayment(store, createPullPayment, invoice.Id);
+ var ppId = await _pullPaymentService.CreateRefundPullPayment(store, createPullPayment, invoice.Id, request.RefundVariant is RefundVariant.Custom);
+ if (ppId is null)
+ {
+ ModelState.AddModelError(nameof(request.RefundVariant), "This invoice already has a refund which is not archived");
+ return this.CreateValidationError(ModelState);
+ }
var pp = await _pullPaymentService.GetPullPayment(ppId, false);
return this.Ok(CreatePullPaymentData(pp));
@@ -703,7 +708,7 @@ public static InvoiceData ToModel(InvoiceEntity entity, LinkGenerator linkGenera
PaymentMethods =
entity.GetPaymentPrompts().Select(method => method.PaymentMethodId.ToString()).ToArray(),
DefaultPaymentMethod = entity.DefaultPaymentMethod?.ToString(),
- SpeedPolicy = entity.SpeedPolicy,
+ SpeedPolicy = entity.SpeedPolicy.Normalize(),
RedirectAutomatically = entity.RedirectAutomatically,
RedirectURL = entity.RedirectURLTemplate
},
### BTCPayServer/Controllers/GreenField/GreenfieldPullPaymentController.cs
@@ -634,6 +634,14 @@ public async Task<IActionResult> CancelPayout(string payoutId)
[Authorize(Policy = Policies.CanManagePayouts, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> ApprovePayout(string payoutId, ApprovePayoutRequest approvePayoutRequest, CancellationToken cancellationToken = default)
{
+ if (approvePayoutRequest?.RateRule is not null)
+ {
+ if (!(await _authorizationService.AuthorizeAsync(User, CurrentStoreId,
+ new PolicyRequirement(Policies.CanCreatePullPayments))).Succeeded)
+ {
+ return this.CreateAPIPermissionError(Policies.CanCreatePullPayments);
+ }
+ }
using var ctx = _dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var revision = approvePayoutRequest?.Revision;
### BTCPayServer/Controllers/UIAccountController.cs
@@ -490,17 +490,22 @@ private async Task<IActionResult> RedirectLoginSuccess(ApplicationUser user, Log
var loginContext = this.CreateLoginContext(user);
if (!await userService.CanLogin(loginContext))
{
- signInManager.AuthenticationScheme = AuthenticationSchemes.LimitedLogin;
- await signInManager.SignInAsync(user, session.ToAuthenticationProperties(true), session.AuthenticationMethod);
+ if (!user.AccessRestrictions.Exists(restriction => restriction.Type == UserAccessRestrictionConstants.Administrative))
+ {
+ await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
+ signInManager.AuthenticationScheme = AuthenticationSchemes.LimitedLogin;
+ await signInManager.SignInAsync(user, session.ToAuthenticationProperties(true), session.AuthenticationMethod);
- if (loginContext.FailedRedirectUrl is { } url)
- return Redirect(url);
+ if (loginContext.FailedRedirectUrl is { } url)
+ return Redirect(url);
+ }
TempData.SetStatusLoginResult(loginContext);
return RedirectToAction(nameof(Login), new { returnUrl = session.ReturnUrl });
}
else
{
+ await HttpContext.SignOutAsync(AuthenticationSchemes.LimitedLogin);
await signInManager.SignInAsync(user, session.ToAuthenticationProperties(false), session.AuthenticationMethod);
if (await userManager.IsInRoleAsync(user, Roles.ServerAdmin))
{
@@ -604,9 +609,11 @@ public async Task<IActionResult> Register(RegisterViewModel model, string return
public bool RegisteredAdmin { get; set; }
[HttpPost("/logout")]
+ [Authorize(AuthenticationSchemes = AuthenticationSchemes.LimitedLogin)]
public async Task<IActionResult> Logout()
{
await signInManager.SignOutAsync();
+ await HttpContext.SignOutAsync(AuthenticationSchemes.LimitedLogin);
HttpContext.DeleteUserPrefsCookie();
return RedirectToAction(nameof(Login));
}
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -12,6 +12,7 @@
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Filters;
+using BTCPayServer.HostedServices;
using BTCPayServer.Models;
using BTCPayServer.Models.AppViewModels;
using BTCPayServer.Models.InvoicingModels;
@@ -134,9 +135,8 @@ public async Task<IActionResult> Invoice(string invoiceId)
Id = invoice.Id,
Entity = invoice,
State = invoiceState,
- TransactionSpeed = invoice.SpeedPolicy == SpeedPolicy.HighSpeed ? "high" :
- invoice.SpeedPolicy == SpeedPolicy.MediumSpeed ? "medium" :
- invoice.SpeedPolicy == SpeedPolicy.LowMediumSpeed ? "low-medium" :
+ TransactionSpeed = invoice.SpeedPolicy.Normalize() == SpeedPolicy.MediumSpeed ? "medium" :
+ invoice.SpeedPolicy.Normalize() == SpeedPolicy.LowMediumSpeed ? "low-medium" :
"low",
CreatedDate = invoice.InvoiceTime,
ExpirationDate = invoice.ExpirationTime,
@@ -289,12 +289,13 @@ public async Task<IActionResult> Refund(string invoiceId, CancellationToken canc
.FirstOrDefaultAsync(cancellationToken);
if (invoice is null)
return NotFound();
- var currentRefund = invoice.Refunds.OrderByDescending(r => r.PullPaymentData.StartDate).FirstOrDefault();
+ var currentRefund = invoice.Refunds.Where(r => !r.PullPaymentData.Archived)
+ .OrderByDescending(r => r.PullPaymentData.StartDate).FirstOrDefault();
if (currentRefund?.PullPaymentDataId is null && User.GetIdOrNull() is null)
return NotFound();
if (!invoice.GetInvoiceState().CanRefund())
return NotFound();
- if (currentRefund?.PullPaymentDataId is string ppId && !currentRefund.PullPaymentData.Archived)
+ if (currentRefund?.PullPaymentDataId is string ppId)
{
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(UIPullPaymentController.ViewPullPayment),
@@ -343,6 +344,13 @@ public async Task<IActionResult> Refund(string invoiceId, RefundModel model, Can
if (invoice?.GetInvoiceState().CanRefund() is not true)
return NotFound();
+ if (await PullPaymentHostedService.FindOpenRefundId(ctx, invoiceId, cancellationToken) is { } currentPpId)
+ {
+ return RedirectToAction(nameof(UIPullPaymentController.ViewPullPayment),
+ "UIPullPayment",
+ new { pullPaymentId = currentPpId });
+ }
+
var store = HttpContext.GetStoreData();
var pmi = PayoutMethodId.Parse(model.SelectedPayoutMethod);
var cdCurrency = _CurrencyNameTable.GetCurrencyData(invoice.Currency, true);
@@ -547,12 +555,15 @@ public async Task<IActionResult> Refund(string invoiceId, RefundModel model, Can
return View("_RefundModal", model);
}
- var ppId = await _paymentHostedService.CreateRefundPullPayment(store, createPullPayment, invoice.Id);
- TempData.SetStatusMessageModel(new StatusMessageModel
+ var (ppId, created) = await _paymentHostedService.GetOrCreateRefundPullPayment(store, createPullPayment, invoice.Id);
+ if (created)
{
- Html = "Refund successfully created!<br />Share the link to this page with a customer.<br />The customer needs to enter their address and claim the refund.<br />Once a customer claims the refund, you will get a notification and would need to approve and initiate it from your Store > Payouts.",
- Severity = StatusMessageModel.StatusSeverity.Success
- });
+ TempData.SetStatusMessageModel(new StatusMessageModel
+ {
+ Html = "Refund successfully created!<br />Share the link to this page with a customer.<br />The customer needs to enter their address and claim the refund.<br />Once a customer claims the refund, you will get a notification and would need to approve and initiate it from your Store > Payouts.",
+ Severity = StatusMessageModel.StatusSeverity.Success
+ });
+ }
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(UIPullPaymentController.ViewPullPayment),
### BTCPayServer/Controllers/UIInvoiceController.cs
@@ -181,7 +181,7 @@ public async Task<InvoiceEntity> CreateInvoiceCoreRaw(CreateInvoiceRequest invoi
entity.Price = 0.0m;
entity.Type = InvoiceType.TopUp;
}
- entity.SpeedPolicy = invoice.Checkout.SpeedPolicy ?? store.SpeedPolicy;
+ entity.SpeedPolicy = (invoice.Checkout.SpeedPolicy ?? store.SpeedPolicy).Normalize();
if (invoice.Checkout.DefaultPaymentMethod is not null && PaymentMethodId.TryParse(invoice.Checkout.DefaultPaymentMethod, out var paymentMethodId))
{
entity.DefaultPaymentMethod = paymentMethodId;
### BTCPayServer/Controllers/UILNURLController.cs
@@ -17,6 +17,7 @@
using BTCPayServer.Events;
using BTCPayServer.HostedServices;
using BTCPayServer.Lightning;
+using BTCPayServer.Logging;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Payments.LNURLPay;
@@ -38,9 +39,11 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
+using Microsoft.Extensions.Logging;
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
+using NicolasDorier.RateLimits;
using LightningAddressData = BTCPayServer.Data.LightningAddressData;
namespace BTCPayServer
@@ -64,6 +67,8 @@ public class UILNURLController : Controller
private readonly PayoutProcessorService _payoutProcessorService;
private readonly CurrencyNameTable _currencies;
private readonly DisplayFormatter _displayFormatter;
+ private readonly IRateLimitService _rateLimitService;
+ public Logs Logs { get; }
public IStringLocalizer StringLocalizer { get; }
public UILNURLController(InvoiceRepository invoiceRepository,
@@ -80,10 +85,14 @@ public UILNURLController(InvoiceRepository invoiceRepository,
IPluginHookService pluginHookService,
IStringLocalizer stringLocalizer,
InvoiceActivator invoiceActivator,
- CurrencyNameTable currencies, DisplayFormatter displayFormatter)
+ CurrencyNameTable currencies, DisplayFormatter displayFormatter,
+ IRateLimitService rateLimitService,
+ Logs logs)
{
+ Logs = logs;
_currencies = currencies;
_displayFormatter = displayFormatter;
+ _rateLimitService = rateLimitService;
_invoiceRepository = invoiceRepository;
_eventAggregator = eventAggregator;
_payoutHandlers = payoutHandlers;
@@ -836,13 +845,18 @@ public async Task<IActionResult> GetLNURLForInvoice(string invoiceId, string cry
string replacedInvoiceId = null;
if (string.IsNullOrEmpty(lightningPaymentMethod.Destination) || promptDetails.GeneratedBoltAmount != amt)
{
- replacementClient = _handlers.GetLightningHandler(network).CreateLightningClient(lnConfig);
- if (!string.IsNullOrEmpty(lightningPaymentMethod.Destination))
- replacedInvoiceId = promptDetails.InvoiceId;
+ if (!await _rateLimitService.Throttle(ZoneLimits.PublicInvoices, $"lnurl-invoice:{invoiceId}", HttpContext.RequestAborted))
+ return BadRequest(new LNUrlStatusResponse
+ {
+ Status = "ERROR",
+ Reason = "Too many requests, please try again later."
+ });
+ replacedInvoiceId = promptDetails.InvoiceId;
LightningInvoice invoice;
try
{
+ replacementClient = _handlers.GetLightningHandler(network).CreateLightningClient(lnConfig);
var expiry = i.ExpirationTime.ToUniversalTime() - DateTimeOffset.UtcNow;
HttpContext.Items.Add(nameof(invoiceId), invoiceId);
var description = (await _pluginHookService.ApplyFilter("modify-lnurlp-description", lnurlPayRequest.Metadata)) as string;
@@ -858,11 +872,11 @@ public async Task<IActionResult> GetLNURLForInvoice(string invoiceId, string cry
}
catch (Exception ex)
{
+ Logs.PayServer.LogError(ex, "Could not generate a lightning invoice for invoice {InvoiceId}", invoiceId);
return BadRequest(new LNUrlStatusResponse
{
Status = "ERROR",
- Reason = "Lightning node could not generate invoice" + (
- string.IsNullOrEmpty(ex.Message) ? "" : $": {ex.Message}")
+ Reason = "Lightning node could not generate invoice"
});
}
### BTCPayServer/HostedServices/PullPaymentHostedService.cs
@@ -102,37 +102,76 @@ public static string GetErrorMessage(Result result)
}
public async Task<string> CreatePullPayment(Data.StoreData store, CreatePullPaymentRequest create)
{
- return (await CreatePullPaymentCore(store, create)).Id;
+ await using var ctx = _dbContextFactory.CreateContext();
+ var pullPayment = BuildPullPayment(store, create);
+ ctx.PullPayments.Add(pullPayment);
+ await ctx.SaveChangesAsync();
+ return pullPayment.Id;
}
- public async Task<string> CreateRefundPullPayment(Data.StoreData store, CreatePullPaymentRequest create, string invoiceId)
+ public Task<string> CreateRefundPullPayment(Data.StoreData store, CreatePullPaymentRequest create, string invoiceId)
+ => CreateRefundPullPayment(store, create, invoiceId, allowAdditionalRefund: true);
+
+ /// <summary>
+ /// Creates the refund pull payment of an invoice. Returns null when <paramref name="allowAdditionalRefund"/>
+ /// is false and the invoice already has a refund pull payment which is not archived.
+ /// </summary>
+ public async Task<string> CreateRefundPullPayment(Data.StoreData store, CreatePullPaymentRequest create, string invoiceId, bool allowAdditionalRefund)
{
- var pullPayment = await CreatePullPaymentCore(store, create);
- await using var ctx = _dbContextFactory.CreateContext();
- ctx.Refunds.Add(new RefundData()
+ var (id, created) = await GetOrCreateRefundPullPayment(store, create, invoiceId, allowAdditionalRefund);
+ return created ? id : null;
+ }
+
+ internal static Task<string> FindOpenRefundId(ApplicationDbContext ctx, string invoiceId, CancellationToken cancellationToken = default)
+ => ctx.Refunds.Where(r => r.InvoiceDataId == invoiceId && !r.PullPaymentData.Archived)
+ .OrderByDescending(r => r.PullPaymentData.StartDate)
+ .Select(r => r.PullPaymentDataId)
+ .FirstOrDefaultAsync(cancellationToken);
+
+ internal async Task<(string Id, bool Created)> GetOrCreateRefundPullPayment(Data.StoreData store, CreatePullPaymentRequest create,
+ string invoiceId, bool allowAdditionalRefund = false)
+ {
+ Data.PullPaymentData pullPayment = null;
+ await using var strategyContext = _dbContextFactory.CreateContext();
+ var result = await strategyContext.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
- InvoiceDataId = invoiceId,
- PullPaymentDataId = pullPayment.Id
+ await using var ctx = _dbContextFactory.CreateContext();
+ await using var transaction = await ctx.Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);
+ await ctx.Database.ExecuteSqlInterpolatedAsync($"""
+ SELECT 1 FROM "Invoices" WHERE "Id" = {invoiceId} FOR UPDATE
+ """);
+ if (pullPayment is not null && await ctx.Refunds.AnyAsync(r => r.PullPaymentDataId == pullPayment.Id))
+ return (Id: pullPayment.Id, Created: true);
+ if (!allowAdditionalRefund && await FindOpenRefundId(ctx, invoiceId) is { } existingId)
+ return (Id: existingId, Created: false);
+
+ pullPayment ??= BuildPullPayment(store, create);
+ ctx.PullPayments.Add(pullPayment);
+ ctx.Refunds.Add(new RefundData()
+ {
+ InvoiceDataId = invoiceId,
+ PullPaymentDataId = pullPayment.Id
+ });
+ await ctx.SaveChangesAsync();
+ await transaction.CommitAsync();
+ return (Id: pullPayment.Id, Created: true);
});
- await ctx.SaveChangesAsync();
- var invoice = await _invoiceRepository.GetInvoice(invoiceId);
- if (invoice is not null)
- _eventAggregator.Publish(new Events.InvoiceEvent(invoice, Events.InvoiceEvent.Refund) { PullPaymentId = pullPayment.Id });
- return pullPayment.Id;
+ if (result.Created && await _invoiceRepository.GetInvoice(invoiceId) is { } invoice)
+ _eventAggregator.Publish(new Events.InvoiceEvent(invoice, Events.InvoiceEvent.Refund) { PullPaymentId = result.Id });
+ return result;
}
- private async Task<Data.PullPaymentData> CreatePullPaymentCore(Data.StoreData store, CreatePullPaymentRequest create)
+ private Data.PullPaymentData BuildPullPayment(Data.StoreData store, CreatePullPaymentRequest create)
{
+ ArgumentNullException.ThrowIfNull(create);
var supported = this._handlers.GetSupportedPayoutMethods(store);
create.PayoutMethods ??= supported.Select(s => s.ToString()).ToArray();
create.PayoutMethods = create.PayoutMethods.Where(pm => _handlers.Support(PayoutMethodId.Parse(pm))).ToArray();
if (create.PayoutMethods.Length == 0)
throw new InvalidOperationException("request.PayoutMethods should have at least one payout method");
- ArgumentNullException.ThrowIfNull(create);
if (create.Amount <= 0.0m)
throw new ArgumentException("Amount out of bound", nameof(create));
- using var ctx = this._dbContextFactory.CreateContext();
var o = new Data.PullPaymentData();
o.StartDate = create.StartsAt is DateTimeOffset date
? date
@@ -157,8 +196,6 @@ public async Task<string> CreateRefundPullPayment(Data.StoreData store, CreatePu
},
BOLT11Expiration = create.BOLT11Expiration ?? store.GetStoreBlob().RefundBOLT11Expiration
});
- ctx.PullPayments.Add(o);
- await ctx.SaveChangesAsync();
return o;
}
@@ -480,8 +517,8 @@ public Task<RateResult> GetRate(PayoutData payout, string explicitRateRule, Canc
if (explicitRateRule is null)
{
var storeBlob = payout.StoreData.GetStoreBlob();
- var rules = storeBlob.GetRateRules(_defaultRules);
storeBlob.Spread = 0.0m;
+ var rules = storeBlob.GetRateRules(_defaultRules);
rule = rules.GetRuleFor(currencyPair);
}
else
@@ -601,7 +638,8 @@ private async Task HandleMarkPaid(InternalPayoutPaidRequest req)
if (req.Request.ExpectedState is { } expectedState &&
(payout.State != expectedState ||
- !JToken.DeepEquals(payout.GetProofBlobJson(), req.Request.ExpectedProof)))
+ (req.Request.MatchExpectedProof &&
+ !JToken.DeepEquals(payout.GetProofBlobJson(), req.Request.ExpectedProof))))
{
req.Completion.SetResult(MarkPayoutRequest.PayoutPaidResult.InvalidState);
return;
@@ -623,7 +661,7 @@ private async Task HandleMarkPaid(InternalPayoutPaidRequest req)
payout.SetProofBlob(req.Request.Proof);
break;
default:
- payout.SetProofBlob(null);
+ payout.SetProofBlob(req.Request.RestoreProof ? req.Request.Proof : null);
break;
}
payout.State = req.Request.State;
@@ -989,7 +1027,18 @@ public enum PayoutPaidResult
public PayoutState State { get; set; } = PayoutState.Completed;
public PayoutBlob UpdateBlob { get; internal set; }
public PayoutState? ExpectedState { get; internal set; }
- public JObject ExpectedProof { get; internal set; }
+ private JObject _expectedProof;
+ public JObject ExpectedProof
+ {
+ get => _expectedProof;
+ internal set
+ {
+ _expectedProof = value;
+ MatchExpectedProof = true;
+ }
+ }
+ internal bool MatchExpectedProof { get; private set; }
+ internal bool RestoreProof { get; set; }
public static string GetErrorMessage(PayoutPaidResult result)
{
### BTCPayServer/Hosting/BTCPayServerServices.cs
@@ -7,6 +7,7 @@
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Abstractions.Services;
+using BTCPayServer.Blazor;
using BTCPayServer.Common;
using BTCPayServer.Configuration;
using BTCPayServer.Controllers;
@@ -173,6 +174,7 @@ public static IServiceCollection AddBTCPayServer(this IServiceCollection service
services.TryAddSingleton<PaymentRequestService>();
services.TryAddSingleton<UserService>();
services.AddSingleton<UserService.LoginExtension, UserService.DefaultLoginExtension>();
+ services.TryAddSingleton<CircuitUserRevalidator>();
services.TryAddSingleton<UriResolver>();
services.TryAddSingleton<WalletHistogramService>();
@@ -944,6 +946,17 @@ private static void AddBtcPayServerAuthenticationSchemes(this IServiceCollection
options.SlidingExpiration = false;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest;
+ options.Events.OnValidatePrincipal = async context =>
+ {
+ var services = context.HttpContext.RequestServices;
+ var signInManager = services.GetRequiredService<SignInManager<ApplicationUser>>();
+ var user = await signInManager.ValidateSecurityStampAsync(context.Principal);
+ if (user is not null && !await services.GetRequiredService<UserService>()
+ .IsRestricted(user.Id, UserAccessRestrictionConstants.Administrative))
+ return;
+ context.RejectPrincipal();
+ await context.HttpContext.SignOutAsync(AuthenticationSchemes.LimitedLogin);
+ };
options.LoginPath = "/login";
options.AccessDeniedPath = "/errors/403";
options.LogoutPath = "/logout";
### BTCPayServer/Hosting/Startup.cs
@@ -3,6 +3,7 @@
using System.Linq;
using System.Net;
using BTCPayServer.Abstractions.Extensions;
+using BTCPayServer.Blazor;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using BTCPayServer.Fido2;
@@ -17,6 +18,7 @@
using Fido2NetLib;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
@@ -205,6 +207,7 @@ public void ConfigureServices(IServiceCollection services)
// easily too big to get signed without this.
o.MaximumReceiveMessageSize = BlazorMaximumReceiveMessageSize;
});
+ services.AddScoped<AuthenticationStateProvider, RevalidatingAuthenticationStateProvider>();
LowercaseTransformer.Register(services);
ValidateControllerNameTransformer.Register(services);
### BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentHandler.cs
@@ -253,6 +253,7 @@ public Task ValidatePaymentMethodConfig(PaymentMethodConfigValidationContext val
if (validationContext.Config is JValue { Type: JTokenType.String, Value: string config }
&& parser.TryParseXpub(config, ref settings))
{
+ settings.IsHotWallet = KeepsPreviousHotWallet(validationContext, settings);
validationContext.Config = JToken.FromObject(settings, Serializer);
return Task.CompletedTask;
}
@@ -288,17 +289,28 @@ public Task ValidatePaymentMethodConfig(PaymentMethodConfigValidationContext val
if (res.IsHotWallet)
{
- var previous = validationContext.PreviousConfig?.ToObject<DerivationSchemeSettings>(Serializer);
- if (previous?.IsHotWallet is not true ||
- previous.AccountDerivation?.ToString() != res.AccountDerivation?.ToString())
+ if (!KeepsPreviousHotWallet(validationContext, res))
{
validationContext.ModelState.AddModelError(nameof(res.IsHotWallet),
"IsHotWallet cannot be set through this API. Generate or import a wallet with private keys instead.");
}
}
+ // Not every accepted shape carries the flag, so an update of the same wallet must not clear it
+ else if (KeepsPreviousHotWallet(validationContext, res))
+ {
+ res.IsHotWallet = true;
+ validationContext.Config = JToken.FromObject(res, Serializer);
+ }
return Task.CompletedTask;
}
+ private bool KeepsPreviousHotWallet(PaymentMethodConfigValidationContext validationContext, DerivationSchemeSettings res)
+ {
+ var previous = validationContext.PreviousConfig?.ToObject<DerivationSchemeSettings>(Serializer);
+ return previous?.IsHotWallet is true &&
+ previous.AccountDerivation?.ToString() == res.AccountDerivation?.ToString();
+ }
+
public BitcoinLikePaymentData ParsePaymentDetails(JToken details)
{
return details.ToObject<BitcoinLikePaymentData>(Serializer) ?? throw new FormatException($"Invalid {nameof(BitcoinLikePaymentData)}");
### BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs
@@ -379,13 +379,11 @@ async Task<InvoiceEntity> UpdatePaymentStates(BTCPayWallet wallet, InvoiceEntity
}
public static int ConfirmationRequired(InvoiceEntity invoice, BitcoinLikePaymentData paymentData)
- => (invoice, paymentData) switch
+ => invoice.SpeedPolicy.Normalize() switch
{
- ({ SpeedPolicy: SpeedPolicy.HighSpeed }, { RBF: true }) => 1,
- ({ SpeedPolicy: SpeedPolicy.HighSpeed }, _) => 0,
- ({ SpeedPolicy: SpeedPolicy.MediumSpeed }, _) => 1,
- ({ SpeedPolicy: SpeedPolicy.LowMediumSpeed }, _) => 2,
- ({ SpeedPolicy: SpeedPolicy.LowSpeed }, _) => 6,
+ SpeedPolicy.MediumSpeed => 1,
+ SpeedPolicy.LowMediumSpeed => 2,
+ SpeedPolicy.LowSpeed => 6,
_ => 6,
};
### BTCPayServer/Payments/Lightning/LightningListener.cs
@@ -270,17 +270,21 @@ private void CheckConnections()
{
lock (_InstanceListeners)
{
- foreach (var key in _InstanceListeners.Keys)
+ foreach (var (key, instance) in _InstanceListeners.ToArray())
{
CheckConnection(key.Item1, key.Item2, key.Item3);
+ if (instance is { Empty: true, IsListening: false })
+ _InstanceListeners.Remove(key);
}
}
}
public void CheckConnection(string cryptoCode, string connStr, bool allowUnsafe)
{
- if (_InstanceListeners.TryGetValue((cryptoCode, connStr, allowUnsafe), out var instance))
+ lock (_InstanceListeners)
{
+ if (!_InstanceListeners.TryGetValue((cryptoCode, connStr, allowUnsafe), out var instance))
+ return;
instance.RemoveExpiredInvoices();
if (!instance.Empty)
instance.EnsureListening(_Cts.Token);
### BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs
@@ -200,8 +200,8 @@ ObjectResult CreatePayjoinErrorAndLog(int httpCode, PayjoinReceiverWellknownErro
psbt = PSBT.FromTransaction(tx, network.NBitcoinNetwork);
for (int i = 0; i < tx.Inputs.Count; i++)
{
- psbt.Inputs[i].FinalScriptSig = tx.Inputs[i].ScriptSig;
- psbt.Inputs[i].FinalScriptWitness = tx.Inputs[i].WitScript;
+ psbt.Inputs[i].FinalScriptSig = ctx.OriginalTransaction.Inputs[i].ScriptSig;
+ psbt.Inputs[i].FinalScriptWitness = ctx.OriginalTransaction.Inputs[i].WitScript;
}
}
@@ -401,7 +401,8 @@ accountDerivation is null ||
return CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "We do not have any UTXO available for contributing to a payjoin");
}
- await _broadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2.0), ctx.OriginalTransaction, network);
+ if (invoice is not null)
+ await _broadcaster.Schedule(DateTimeOffset.UtcNow + OriginalBroadcastDelay, ctx.OriginalTransaction, network);
var extKeyStr = await explorer.GetMetadataAsync<string>(
accountDerivation,
@@ -551,7 +552,6 @@ maxadditionalfeecontribution is long v3 &&
}
_eventAggregator.Publish(new InvoiceEvent(invoice, InvoiceEvent.ReceivedPayment) { Payment = payment });
}
-
await _btcPayWalletProvider.GetWallet(network).SaveOffchainTransactionAsync(ctx.OriginalTransaction);
foreach (var utxo in selectedUTXOs)
@@ -560,6 +560,9 @@ maxadditionalfeecontribution is long v3 &&
}
await _walletRepository.AddWalletTransactionAttachment(walletId, details.PayjoinInformation.CoinjoinTransactionHash, Attachment.Payjoin());
+ if (invoice is null)
+ await _broadcaster.Schedule(DateTimeOffset.UtcNow + OriginalBroadcastDelay, ctx.OriginalTransaction, network,
+ details.PayjoinInformation.CoinjoinTransactionHash, details.PayjoinInformation.ContributedOutPoints);
ctx.Success();
// BTCPay Server support PSBT set as hex
@@ -582,6 +585,8 @@ private IActionResult InvoiceNotFullyPaid()
"The transaction must pay the whole invoice"));
}
+ private static readonly TimeSpan OriginalBroadcastDelay = TimeSpan.FromMinutes(2.0);
+
private uint256 GetExpectedHash(PSBT psbt, Coin?[] coins)
{
psbt = psbt.Clone();
### BTCPayServer/PayoutProcessors/OnChain/OnChainAutomatedPayoutProcessor.cs
@@ -7,6 +7,7 @@
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Events;
+using BTCPayServer.HostedServices;
using BTCPayServer.Payments;
using BTCPayServer.Payouts;
using BTCPayServer.Services;
@@ -15,8 +16,12 @@
using BTCPayServer.Services.Wallets;
using Microsoft.Extensions.Logging;
using NBitcoin;
+using NBitcoin.RPC;
using NBXplorer;
using NBXplorer.DerivationStrategy;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using MarkPayoutRequest = BTCPayServer.HostedServices.MarkPayoutRequest;
using PayoutData = BTCPayServer.Data.PayoutData;
using PayoutProcessorData = BTCPayServer.Data.PayoutProcessorData;
@@ -28,6 +33,7 @@ public class OnChainAutomatedPayoutProcessor : BaseAutomatedPayoutProcessor<OnCh
private readonly BTCPayWalletProvider _btcPayWalletProvider;
private readonly BTCPayNetworkJsonSerializerSettings _btcPayNetworkJsonSerializerSettings;
private readonly BitcoinLikePayoutHandler _bitcoinLikePayoutHandler;
+ private readonly PullPaymentHostedService _pullPaymentHostedService;
public BTCPayNetwork Network { get; }
@@ -47,7 +53,8 @@ public OnChainAutomatedPayoutProcessor(
PayoutMethodHandlerDictionary payoutHandlers,
PaymentMethodHandlerDictionary handlers,
IPluginHookService pluginHookService,
- IFeeProviderFactory feeProviderFactory) :
+ IFeeProviderFactory feeProviderFactory,
+ PullPaymentHostedService pullPaymentHostedService) :
base(
PaymentTypes.CHAIN.GetPaymentMethodId(GetPayoutHandler(payoutHandlers, payoutMethodId).Network.CryptoCode),
logger, storeRepository, payoutProcesserSettings, applicationDbContextFactory,
@@ -60,6 +67,7 @@ public OnChainAutomatedPayoutProcessor(
Network = _bitcoinLikePayoutHandler.Network;
WalletRepository = walletRepository;
_feeProviderFactory = feeProviderFactory;
+ _pullPaymentHostedService = pullPaymentHostedService;
}
private static BitcoinLikePayoutHandler GetPayoutHandler(PayoutMethodHandlerDictionary payoutHandlers, PayoutMethodId payoutMethodId)
@@ -166,32 +174,49 @@ protected override async Task Process(object paymentMethodConfig, List<PayoutDat
try
{
var txHash = workingTx.GetHash();
- var previousProofs = transfersProcessing.ToDictionary(p => p.Id, p => p.Proof);
- foreach (var payoutData in transfersProcessing)
+ var proof = JObject.FromObject(
+ new PayoutTransactionOnChainBlob()
+ {
+ Accounted = true,
+ TransactionId = txHash,
+ Candidates = new HashSet<uint256>() { txHash }
+ },
+ JsonSerializer.Create(_btcPayNetworkJsonSerializerSettings.GetSerializer(PayoutMethodId)));
+ var claimed = new List<PayoutData>();
+ try
{
- payoutData.State = PayoutState.InProgress;
- _bitcoinLikePayoutHandler.SetProofBlob(payoutData,
- new PayoutTransactionOnChainBlob()
+ foreach (var payoutData in transfersProcessing)
+ {
+ var claim = await _pullPaymentHostedService.MarkPaid(new MarkPayoutRequest()
{
- Accounted = true,
- TransactionId = txHash,
- Candidates = new HashSet<uint256>() { txHash }
+ PayoutId = payoutData.Id,
+ State = PayoutState.InProgress,
+ Proof = proof,
+ ExpectedState = PayoutState.AwaitingPayment,
+ ExpectedProof = payoutData.GetProofBlobJson()
});
+ if (claim != MarkPayoutRequest.PayoutPaidResult.Ok)
+ return;
+ claimed.Add(payoutData);
+ }
+ }
+ finally
+ {
+ if (claimed.Count != transfersProcessing.Count)
+ await RevertClaims(claimed, proof);
}
- var cts = new CancellationTokenSource();
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(20));
var task = _eventAggregator.WaitNext<NewOnChainTransactionEvent>(
e => e.NewTransactionEvent.TransactionData.TransactionHash == txHash,
cts.Token);
var broadcastResult = await explorerClient.BroadcastAsync(workingTx, cts.Token);
- if (!broadcastResult.Success)
+ if (!broadcastResult.Success &&
+ broadcastResult.RPCCode != RPCErrorCode.RPC_TRANSACTION_ALREADY_IN_CHAIN &&
+ await explorerClient.GetTransactionAsync(txHash, cts.Token) is null)
{
- // The node refused the transaction, so nothing has been paid: leave those payouts for the next run
- foreach (var payoutData in transfersProcessing)
- {
- payoutData.State = PayoutState.AwaitingPayment;
- payoutData.Proof = previousProofs[payoutData.Id];
- }
+ if (broadcastResult.RPCCode is RPCErrorCode.RPC_TRANSACTION_ERROR or RPCErrorCode.RPC_TRANSACTION_REJECTED)
+ await RevertClaims(claimed, proof);
return;
}
var walletId = new WalletId(PayoutProcessorSettings.StoreId, Network.CryptoCode);
@@ -213,6 +238,22 @@ await WalletRepository.AddWalletTransactionAttachment(walletId,
}
}
+ private async Task RevertClaims(List<PayoutData> claimed, JObject proof)
+ {
+ foreach (var payoutData in claimed)
+ {
+ await _pullPaymentHostedService.MarkPaid(new MarkPayoutRequest()
+ {
+ PayoutId = payoutData.Id,
+ State = PayoutState.AwaitingPayment,
+ Proof = payoutData.GetProofBlobJson(),
+ RestoreProof = true,
+ ExpectedState = PayoutState.InProgress,
+ ExpectedProof = proof
+ });
+ }
+ }
+
private void DisableProcessor(List<PayoutData> payouts)
{
foreach (var payout in payouts)
### BTCPayServer/Plugins/Bitpay/Controllers/BitpayInvoiceController.cs
@@ -256,7 +256,7 @@ private SpeedPolicy ParseSpeedPolicy(string transactionSpeed, SpeedPolicy defaul
mappings.Add("low", SpeedPolicy.LowSpeed);
mappings.Add("low-medium", SpeedPolicy.LowMediumSpeed);
mappings.Add("medium", SpeedPolicy.MediumSpeed);
- mappings.Add("high", SpeedPolicy.HighSpeed);
+ mappings.Add("high", SpeedPolicy.MediumSpeed);
if (!mappings.TryGetValue(transactionSpeed, out SpeedPolicy policy))
policy = defaultPolicy;
return policy;
### BTCPayServer/Plugins/Impersonation/UserLoginCode.razor
@@ -12,6 +12,7 @@
@using Microsoft.Extensions.Localization
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IAuthorizationService AuthorizationService
+@inject CircuitUserRevalidator CircuitUserRevalidator
@inject UserManager<ApplicationUser> UserManager
@inject UserLoginCodeService UserLoginCodeService
@inject LinkGenerator LinkGenerator
@@ -52,18 +53,21 @@
private Timer _timer;
protected override async Task OnParametersSetAsync()
+ {
+ _user = await GetAuthorizedUser();
+ if (_user is null) return;
+ GenerateCodeAndStartTimer();
+ }
+
+ private async Task<ApplicationUser> GetAuthorizedUser()
{
var auth = await AuthenticationStateProvider.GetAuthenticationStateAsync();
- var userId = auth.User.Identity?.IsAuthenticated is true
- ? auth.User.GetIdOrNull()
- : null;
- if (userId is null) return;
- var loggedInUser = await UserManager.FindByIdAsync(ImpersonatedUserId ?? userId);
- if (loggedInUser is null) return;
+ if (await CircuitUserRevalidator.Revalidate(auth.User) is not { } signedInUser) return null;
+ var loggedInUser = await UserManager.FindByIdAsync(ImpersonatedUserId ?? signedInUser.Id);
+ if (loggedInUser is null) return null;
if (await AuthorizationService.AuthorizeAsync(auth.User, loggedInUser.Id, [new PolicyRequirement(ImpersonationPlugin.CanImpersonateUser)]) is not { Succeeded: true })
- return;
- _user = loggedInUser;
- GenerateCodeAndStartTimer();
+ return null;
+ return loggedInUser;
}
public void Dispose()
@@ -85,10 +89,27 @@
private void CountDownTimer(object source, ElapsedEventArgs e)
{
if (_seconds > 0)
+ {
_seconds -= 1;
+ InvokeAsync(StateHasChanged);
+ return;
+ }
+ ((Timer)source).Enabled = false;
+ InvokeAsync(RegenerateCode);
+ }
+
+ private async Task RegenerateCode()
+ {
+ _user = await GetAuthorizedUser();
+ if (_user is null)
+ {
+ _data = null;
+ _timer?.Dispose();
+ _timer = null;
+ }
else
GenerateCodeAndStartTimer();
- InvokeAsync(StateHasChanged);
+ StateHasChanged();
}
private string GetData(string loginCode)
### BTCPayServer/Plugins/Maintenance/Components/MaintenanceCommands.razor
@@ -17,6 +17,7 @@
@implements IDisposable
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IAuthorizationService AuthorizationService
+@inject CircuitUserRevalidator CircuitUserRevalidator
@inject HostIntegrationState HostIntegrationState
@inject ProcessRunner ProcessRunner
@inject SettingsRepository SettingsRepository
@@ -160,7 +161,7 @@
{
var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var authorization = await AuthorizationService.AuthorizeAsync(authenticationState.User, Policies.CanModifyServerSettings);
- if (!authorization.Succeeded)
+ if (!authorization.Succeeded || await CircuitUserRevalidator.Revalidate(authenticationState.User, Roles.ServerAdmin) is null)
throw new InvalidOperationException(StringLocalizer["You are not authorized to run maintenance commands."].Value);
if (HostIntegrationState.Current?.Commands?.Contains(command) is not true)
### BTCPayServer/Plugins/Monetization/Controllers/UIUserMonetizationController.cs
@@ -13,6 +13,7 @@
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
+using NicolasDorier.RateLimits;
namespace BTCPayServer.Plugins.Monetization.Controllers;
@@ -31,6 +32,7 @@ IStringLocalizer stringLocalizer
[HttpGet("~/monetization/new-user")]
[AllowAnonymous]
+ [RateLimitsFilter(ZoneLimits.PublicInvoices, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> NewUser()
{
if (settings is not { OfferingId: { } offeringId, DefaultPlanId: { } defaultPlanId })
### BTCPayServer/Plugins/Monetization/MonetizationHostedService.cs
@@ -76,19 +76,18 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
}
}
- if (evt is SubscriptionEvent.SubscriberActivated or SubscriptionEvent.SubscriberDisabled)
+ if (evt is SubscriptionEvent.SubscriberActivated or SubscriptionEvent.SubscriberDisabled ||
+ (evt is SubscriptionEvent.PlanStarted ps && ps.PreviousPlan.Id != ps.Subscriber.Plan.Id))
{
- await UpdateUserAccessRestriction((SubscriptionEvent.SubscriberEvent)evt, userManager, evt is SubscriptionEvent.SubscriberActivated);
- }
-
- if (evt is SubscriptionEvent.PlanStarted ps && ps.PreviousPlan.Id != ps.Subscriber.Plan.Id)
- {
- await using var ctx = dbContextFactory.CreateContext();
- var canAccess = await ctx.Plans.HasFeature(ps.Subscriber.PlanId, MonetizationFeatures.CanAccess);
- await UpdateUserAccessRestriction(ps, userManager, canAccess);
+ var subscriber = ((SubscriptionEvent.SubscriberEvent)evt).Subscriber;
+ if (subscriber.GetApplicationUserId() is { } subscriberUserId)
+ {
+ await using var ctx = dbContextFactory.CreateContext();
+ await UpdateUserAccessRestrictions(ctx, subscriber.OfferingId, [subscriberUserId]);
+ }
}
- if (evt is SubscriptionEvent.PlanUpdated pu)
+ if (evt is SubscriptionEvent.PlanUpdated pu && monetizationSettingsAccessor.Settings.OfferingId == pu.Plan.OfferingId)
{
await using var ctx = dbContextFactory.CreateContext();
await UpdateUserAccessRestrictions(ctx, pu.Plan);
@@ -101,41 +100,25 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
DefaultPlanId: { } byPassDefaultPlanId
})
{
- if (changed.Bypass)
+ await using var ctx = dbContextFactory.CreateContext();
+ var userSub = await ctx.Subscribers.GetBySelector(byPassOfferingId, CustomerSelector.ByIdentity(SubscriberDataExtensions.IdentityType, changed.User.Id));
+ if (userSub is not null)
{
- await using var ctx = dbContextFactory.CreateContext();
- var userSub = await ctx.Subscribers.GetBySelector(byPassOfferingId, CustomerSelector.ByIdentity(SubscriberDataExtensions.IdentityType, changed.User.Id));
- if (userSub is not null)
- {
- await userService.SetAccessRestriction(changed.User.Id, UserAccessRestrictionConstants.Monetization, false);
- EventAggregator.Publish(new MonetizationAccessUpdated([(changed.User.Id, false)]));
- }
+ await UpdateUserAccessRestrictions(ctx, byPassOfferingId, [changed.User.Id]);
}
- else
+ else if (!changed.Bypass)
{
- await using var ctx = dbContextFactory.CreateContext();
- var userSub = await ctx.Subscribers.GetBySelector(byPassOfferingId, CustomerSelector.ByIdentity(SubscriberDataExtensions.IdentityType, changed.User.Id));
- if (userSub is not null)
+ var inserted = await MigrateUsers(byPassOfferingId, byPassDefaultPlanId, OneUserQuery, parameters =>
{
- var restricted = (!userSub.IsActive || userSub.Phase == SubscriberData.PhaseTypes.Expired) &&
- !await userService.IsAdminUser(changed.User);
- await userService.SetAccessRestriction(changed.User.Id, UserAccessRestrictionConstants.Monetization, restricted);
- EventAggregator.Publish(new MonetizationAccessUpdated([(changed.User.Id, restricted)]));
- }
- else
+ parameters.Add("userId", changed.User.Id);
+ parameters.Add("email", changed.User.Email);
+ parameters.Add("customerId", CustomerData.GenerateId());
+ });
+ if (inserted.Length == 1)
{
- var inserted = await MigrateUsers(byPassOfferingId, byPassDefaultPlanId, OneUserQuery, parameters =>
- {
- parameters.Add("userId", changed.User.Id);
- parameters.Add("email", changed.User.Email);
- parameters.Add("customerId", CustomerData.GenerateId());
- });
- if (inserted.Length == 1)
- {
- var s = await ctx.Subscribers.GetByCustomerId(inserted[0].CustomerId, byPassOfferingId);
- if (s is not null)
- EventAggregator.Publish(new SubscriptionEvent.NewSubscriber(s, changed.RequestBaseUrl));
- }
+ var s = await ctx.Subscribers.GetByCustomerId(inserted[0].CustomerId, byPassOfferingId);
+ if (s is not null)
+ EventAggregator.Publish(new SubscriptionEvent.NewSubscriber(s, changed.RequestBaseUrl));
}
}
}
@@ -196,20 +179,6 @@ DELETE FROM customers_identities ci
}
}
- private async Task UpdateUserAccessRestriction(SubscriptionEvent.SubscriberEvent evt, UserManager<ApplicationUser> userManager, bool activated)
- {
- var userId = evt.Subscriber.GetApplicationUserId();
- var user = await userManager.FindByIdAsync(userId ?? "");
- if (user is null)
- return;
-
- var restricted = !activated && !user.BypassMonetization && !await userService.IsAdminUser(user);
- if (await userService.SetAccessRestriction(user.Id, UserAccessRestrictionConstants.Monetization, restricted) is not UserService.SetDisabledResult.Error)
- {
- EventAggregator.Publish(new MonetizationAccessUpdated([(user.Id, restricted)]));
- }
- }
-
private async Task AttachUserIdToSubscriber(string id, SubscriptionEvent.NewSubscriber newSub)
{
await using var ctx = dbContextFactory.CreateContext();
@@ -356,20 +325,20 @@ FROM inserted_subs i
if (userIds.Length != 0)
{
await SubscriptionHostedService.UpdatePlanStats(ctx, plan.Id);
- await UpdateUserAccessRestrictions(ctx, plan, userIds.Select(c => c.UserId).ToArray());
+ await UpdateUserAccessRestrictions(ctx, plan.OfferingId, userIds.Select(c => c.UserId).ToArray());
// We expect the caller to call NewSubscriberEvent.
}
return userIds;
}
- private async Task UpdateUserAccessRestrictions(ApplicationDbContext ctx, PlanData plan, string[]? userIds = null)
+ private async Task UpdateUserAccessRestrictions(ApplicationDbContext ctx, PlanData plan)
+ => await UpdateUserAccessRestrictions(ctx, plan.OfferingId, await GetUserIdsInPlan(ctx, plan));
+
+ private async Task UpdateUserAccessRestrictions(ApplicationDbContext ctx, string offeringId, string[] userIds)
{
- if (userIds is null)
- userIds = await GetUserIdsInPlan(ctx, plan);
if (userIds.Length == 0)
return;
- var canAccess = await ctx.Plans.HasFeature(plan.Id, MonetizationFeatures.CanAccess);
var updated = (await ctx.Database.GetDbConnection()
.QueryAsync<(string UserId, bool Restricted)>("""
WITH exempt_users AS (
@@ -383,14 +352,17 @@ SELECT user_role."UserId"
WHERE role."Name" = @adminRole
),
desired AS (
- SELECT requested.user_id, NOT (ss.active AND @canAccess) AS restricted
+ SELECT requested.user_id, exempt.user_id IS NULL AND NOT (ss.active AND EXISTS (
+ SELECT 1 FROM subs_plans_features plan_feature
+ JOIN subs_features feature ON feature.id = plan_feature.feature_id
+ WHERE plan_feature.plan_id = ss.plan_id AND feature.custom_id = @canAccessFeature
+ )) AS restricted
FROM unnest(@userIds) AS requested(user_id)
JOIN customers_identities ci ON ci.type = @applicationUserId AND ci.value = requested.user_id
JOIN subs_subscribers ss ON ss.customer_id = ci.customer_id
- JOIN "AspNetUsers" ON "AspNetUsers"."Id" = requested.user_id
LEFT JOIN exempt_users exempt ON exempt.user_id = requested.user_id
- WHERE ss.plan_id = @planId
- AND exempt.user_id IS NULL
+ JOIN "AspNetUsers" ON "AspNetUsers"."Id" = requested.user_id
+ WHERE ss.offering_id = @offeringId
),
deleted AS (
DELETE FROM user_access_restrictions restriction
@@ -408,23 +380,15 @@ WHERE restricted
ON CONFLICT DO NOTHING
RETURNING user_id, true AS restricted
),
- exempt_deleted AS (
- DELETE FROM user_access_restrictions restriction
- USING exempt_users exempt
- WHERE restriction.user_id = exempt.user_id
- AND restriction.type = @restrictionType
- RETURNING restriction.user_id, false AS restricted
- ),
changed AS (
SELECT * FROM deleted
UNION ALL
SELECT * FROM inserted
- UNION ALL
- SELECT * FROM exempt_deleted
),
stamps AS (
UPDATE "AspNetUsers" users
- SET "SecurityStamp" = translate(encode(decode(md5(users."Id" || @salt), 'hex'), 'base64'), '/=+-', '')
+ SET "SecurityStamp" = translate(encode(decode(md5(users."Id" || @salt), 'hex'), 'base64'), '/=+-', ''),
+ "ConcurrencyStamp" = md5(users."Id" || @salt || 'concurrency')
FROM changed
WHERE users."Id" = changed.user_id AND changed.restricted
RETURNING users."Id"
@@ -435,9 +399,9 @@ FROM changed
new
{
userIds,
- planId = plan.Id,
+ offeringId,
applicationUserId = SubscriberDataExtensions.IdentityType,
- canAccess,
+ canAccessFeature = MonetizationFeatures.CanAccess,
adminRole = Roles.ServerAdmin,
restrictionType = UserAccessRestrictionConstants.Monetization,
salt = RandomUtils.GetUInt256().ToString()
### BTCPayServer/Plugins/Multisig/Controllers/UIMultisigWalletsController.cs
@@ -179,26 +179,35 @@ public async Task<IActionResult> FinalizeMultisigSetup(string multisigSetupId, M
if (network is null)
return NotFound();
+ if (await ValidateSignersReady(pending) is { } error)
+ return error;
+
return vm.Confirmation
- ? await ConfirmMultisigSetup(vm, store, network)
- : await FinalizeMultisigRequest(pending, network);
+ ? await ConfirmMultisigSetup(vm, store, network, pending)
+ : FinalizeMultisigRequest(pending, network);
}
- private async Task<IActionResult> ConfirmMultisigSetup(MultisigSetupViewModel vm, StoreData store, BTCPayNetwork network)
+ private async Task<IActionResult?> ValidateSignersReady(MultisigSetupData pending)
{
- if (string.IsNullOrEmpty(vm.MultisigRequestId))
+ if (pending.Participants.Count != pending.TotalSigners || pending.Participants.Any(p => string.IsNullOrWhiteSpace(p.AccountKey)))
{
- ModelState.AddModelError(nameof(vm.MultisigRequestId), StringLocalizer["The multisig request was not found or has expired."].Value);
- return View("MultisigConfirm", vm);
+ TempData[WellKnownTempData.ErrorMessage] = StringLocalizer["Complete signer collection before creating the multisig wallet."].Value;
+ return RedirectToMultisigSetup(pending.RequestId);
}
- var pending = await multisigService.GetPendingMultisigSetupContext(vm.StoreId, vm.MultisigRequestId);
- if (pending is null)
+ var eligibleParticipants = await multisigService.GetStoreUsers(pending.StoreId, pending.Participants.Select(p => p.UserId));
+ var eligibleParticipantIds = eligibleParticipants.Select(p => p.UserId).ToHashSet(StringComparer.Ordinal);
+ if (pending.Participants.Any(p => !eligibleParticipantIds.Contains(p.UserId)))
{
- ModelState.AddModelError(nameof(vm.MultisigRequestId), StringLocalizer["The multisig request was not found or has expired."].Value);
- return View("MultisigConfirm", vm);
+ TempData[WellKnownTempData.ErrorMessage] = StringLocalizer["One or more signers no longer have wallet signing permission."].Value;
+ return RedirectToMultisigSetup(pending.RequestId);
}
+ return null;
+ }
+
+ private async Task<IActionResult> ConfirmMultisigSetup(MultisigSetupViewModel vm, StoreData store, BTCPayNetwork network, MultisigSetupData pending)
+ {
var strategy = pending.GetDerivationSchemeSettings(network);
var wallet = walletProvider.GetWallet(network);
if (wallet is null)
@@ -216,32 +225,14 @@ private async Task<IActionResult> ConfirmMultisigSetup(MultisigSetupViewModel vm
await storeRepository.UpdateStore(store);
eventAggregator.Publish(new WalletChangedEvent { WalletId = new WalletId(store.Id, network.CryptoCode) });
- var finalizedPendingSetting = await multisigService.GetPendingMultisigSetupContext(vm.StoreId, vm.MultisigRequestId);
- if (finalizedPendingSetting is not null)
- {
- await multisigService.DeletePendingMultisigSetup(vm.StoreId, vm.MultisigRequestId);
- multisigNotificationService.PublishWalletCreatedEvent(finalizedPendingSetting);
- }
+ await multisigService.DeletePendingMultisigSetup(pending.StoreId, pending.RequestId);
+ multisigNotificationService.PublishWalletCreatedEvent(pending);
TempData[WellKnownTempData.SuccessMessage] = StringLocalizer["Wallet settings for {0} have been updated.", network.CryptoCode].Value;
return RedirectToAction(nameof(BTCPayServer.Controllers.UIStoreOnChainWalletsController.WalletSettings), "UIStoreOnChainWallets", new { area = WalletsPlugin.Area, storeId = vm.StoreId, cryptoCode = vm.CryptoCode });
}
- private async Task<IActionResult> FinalizeMultisigRequest(MultisigSetupData pending, BTCPayNetwork network)
+ private IActionResult FinalizeMultisigRequest(MultisigSetupData pending, BTCPayNetwork network)
{
- if (pending.Participants.Count != pending.TotalSigners || pending.Participants.Any(p => string.IsNullOrWhiteSpace(p.AccountKey)))
- {
- TempData[WellKnownTempData.ErrorMessage] = StringLocalizer["Complete signer collection before creating the multisig wallet."].Value;
- return RedirectToMultisigSetup(pending.RequestId);
- }
-
- var eligibleParticipants = await multisigService.GetStoreUsers(pending.StoreId, pending.Participants.Select(p => p.UserId));
- var eligibleParticipantIds = eligibleParticipants.Select(p => p.UserId).ToHashSet(StringComparer.Ordinal);
- if (pending.Participants.Any(p => !eligibleParticipantIds.Contains(p.UserId)))
- {
- TempData[WellKnownTempData.ErrorMessage] = StringLocalizer["One or more signers no longer have wallet signing permission."].Value;
- return RedirectToMultisigSetup(pending.RequestId);
- }
-
var strategy = pending.GetDerivationSchemeSettings(network);
var vm = new MultisigSetupViewModel
{
### BTCPayServer/Plugins/PluginManager/Controllers/UIPluginManagerController.cs
@@ -139,9 +139,8 @@ public async Task<IActionResult> InstallPlugin(
string version = null,
string returnTo = null)
{
- var ctx = new DownloadPluginContext(plugin, version, new(), new(), null);
- await DownloadPluginAndDependencies(ctx);
- if (ctx.DependencyFailed.Count == 0)
+ var error = await DownloadPluginAndDependencies(plugin, version);
+ if (error is null)
{
TempData.SetStatusMessageModel(new StatusMessageModel
{
@@ -151,8 +150,6 @@ public async Task<IActionResult> InstallPlugin(
}
else
{
- var error = String.Join(" \n", ctx.DependencyFailed
- .Select(d => $"{d.Key}: {d.Value}"));
TempData.SetStatusMessageModel(new StatusMessageModel
{
Message = stringLocalizer["The plugin could not be downloaded. Try again later."].Value + " \n" + error,
@@ -183,59 +180,83 @@ public async Task<IActionResult> UploadPlugin(List<IFormFile> files)
return RedirectToAction(nameof(ListPlugins));
}
- private record DownloadPluginContext(string Plugin, string Version, HashSet<string> Downloaded, Dictionary<string, string> DependencyFailed, VersionCondition VersionCondition);
-
- private async Task DownloadPluginAndDependencies(DownloadPluginContext ctx)
+ internal async Task<string> DownloadPluginAndDependencies(string plugin, string version)
{
- if (ctx.Downloaded.Contains(ctx.Plugin)
- ||
- ctx.DependencyFailed.ContainsKey(ctx.Plugin))
- return;
- AvailablePlugin manifest;
+ var selected = new Dictionary<string, AvailablePlugin>(StringComparer.OrdinalIgnoreCase);
+ var resolving = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
- manifest = await pluginService.DownloadRemotePlugin(ctx.Plugin, ctx.Version, ctx.VersionCondition);
+ await ResolvePlugin(plugin, version, null);
+ var installOrder = GetPluginInstallOrder(selected);
+ foreach (var candidate in installOrder)
+ await pluginService.DownloadResolvedPlugin(candidate.Identifier, candidate);
+ foreach (var candidate in installOrder)
+ pluginService.InstallPlugin(candidate.Identifier);
+ return null;
}
catch (Exception ex)
{
- ctx.DependencyFailed.Add(ctx.Plugin, ex.Message);
- return;
+ return $"{plugin}: {ex.Message}";
}
- foreach (var dep in manifest.Dependencies)
+ async Task ResolvePlugin(string identifier, string requestedVersion, VersionCondition condition)
{
- if (!PluginManager.DependencyMet(dep, pluginService.Installed))
+ if (selected.TryGetValue(identifier, out var resolved))
+ {
+ if (condition?.IsFulfilled(resolved.Version) == false)
+ throw new InvalidOperationException($"The selected version of {identifier} does not satisfy {condition}.");
+ return;
+ }
+
+ if (!resolving.Add(identifier))
+ throw new InvalidOperationException($"Plugin dependency cycle involving {identifier}.");
+
+ var manifest = await pluginService.ResolveRemotePlugin(identifier, requestedVersion, condition);
+ foreach (var dep in manifest.Dependencies ?? [])
{
+ if (PluginManager.DependencyMet(dep, pluginService.Installed))
+ continue;
+
if (dep.Identifier.Equals("BTCPayServer", StringComparison.OrdinalIgnoreCase))
- {
- ctx.DependencyFailed.Add(ctx.Plugin, $"This condition can't be satisfied {dep}");
- return;
- }
+ throw new InvalidOperationException($"This condition can't be satisfied {dep}");
- var cond = dep.ParseCondition();
- var childCtx = ctx with
- {
- Plugin = dep.Identifier,
- Version = null,
- VersionCondition = cond
- };
- if (childCtx.VersionCondition is VersionCondition.Not)
- {
- ctx.DependencyFailed.Add(ctx.Plugin, $"The currently installed plugin {dep.Identifier} is incompatible with this plugin.");
- return;
- }
+ var dependencyCondition = dep.ParseCondition();
+ if (dependencyCondition is VersionCondition.Not)
+ throw new InvalidOperationException($"The currently installed plugin {dep.Identifier} is incompatible with this plugin.");
- await DownloadPluginAndDependencies(childCtx);
- if (childCtx.DependencyFailed.ContainsKey(childCtx.Plugin))
- {
- ctx.DependencyFailed.Add(ctx.Plugin, $"Failed to download dependency {dep.Identifier}");
- return;
- }
+ await ResolvePlugin(dep.Identifier, null, dependencyCondition);
}
+ resolving.Remove(identifier);
+ selected.Add(identifier, manifest);
}
+ }
- pluginService.InstallPlugin(ctx.Plugin);
- ctx.Downloaded.Add(ctx.Plugin);
+ private AvailablePlugin[] GetPluginInstallOrder(Dictionary<string, AvailablePlugin> selected)
+ {
+ var projected = pluginService.LoadedPlugins.ToDictionary(
+ plugin => plugin.Identifier, plugin => (plugin.Version, plugin.Dependencies), StringComparer.OrdinalIgnoreCase);
+ foreach (var (command, identifier) in pluginService.GetPendingCommands())
+ {
+ if (command is "delete" or "disable")
+ projected.Remove(identifier);
+ else if (pluginService.GetPendingPluginManifest(command, identifier) is { } pending)
+ projected[identifier] = (pending.Version, pending.Dependencies);
+ }
+ foreach (var (identifier, candidate) in selected)
+ projected[identifier] = (candidate.Version, candidate.Dependencies);
+
+ var versions = projected.ToDictionary(pair => pair.Key, pair => pair.Value.Version, StringComparer.OrdinalIgnoreCase);
+ foreach (var candidate in selected.Values)
+ {
+ if (!PluginManager.DependenciesMet(candidate.Dependencies ?? [], versions))
+ throw new InvalidOperationException($"The selected plugin versions do not meet the dependencies of {candidate.Identifier}.");
+ }
+
+ return projected.Keys.Select(identifier => identifier.ToUpperInvariant()).ToArray()
+ .TopologicalSort(identifier => (projected[identifier].Dependencies ?? []).Select(dep => dep.Identifier.ToUpperInvariant()))
+ .Where(selected.ContainsKey)
+ .Select(identifier => selected[identifier])
+ .ToArray();
}
internal async Task<InstalledPluginsViewModel> CreateInstalledPluginsViewModel(
### BTCPayServer/Plugins/PluginManager/PluginService.cs
@@ -143,6 +143,13 @@ internal async Task<AvailablePlugin> GetDirectoryPluginBySlug(string pluginSlug)
#nullable restore
public async Task<AvailablePlugin> DownloadRemotePlugin(string pluginIdentifier, string version, VersionCondition condition = null)
+ {
+ var manifest = await ResolveRemotePlugin(pluginIdentifier, version, condition);
+ await DownloadResolvedPlugin(pluginIdentifier, manifest);
+ return manifest;
+ }
+
+ internal async Task<AvailablePlugin> ResolveRemotePlugin(string pluginIdentifier, string version, VersionCondition condition)
{
string btcpayVersion = GetShortBtcpayVersion();
var versions = await _pluginBuilderClient.GetPluginVersionsForDownload(pluginIdentifier,
@@ -151,13 +158,8 @@ public async Task<AvailablePlugin> DownloadRemotePlugin(string pluginIdentifier,
.Select(v => v.ManifestInfo?.ToObject<AvailablePlugin>());
var selectedVersion = SelectCompatiblePluginVersion(pluginIdentifier, version, condition, compatiblePlugins);
- var dest = _dataDirectories.Value.PluginDir;
- var filedest = Path.Join(dest, pluginIdentifier + ".btcpay");
- var filemanifestdest = Path.Join(dest, pluginIdentifier + ".json");
var pluginSelector = $"[{Uri.EscapeDataString(pluginIdentifier)}]";
var selectedVersionParameter = Uri.EscapeDataString(selectedVersion.ToString());
- Directory.CreateDirectory(Path.GetDirectoryName(filedest));
- var url = $"api/v1/plugins/{pluginSelector}/versions/{selectedVersionParameter}/download";
var publishedVersion = await _pluginBuilderClient.GetPlugin(pluginSelector, selectedVersionParameter);
if (publishedVersion is null)
throw new InvalidDataException($"Plugin version not found for {pluginIdentifier} {selectedVersion}.");
@@ -169,13 +171,24 @@ public async Task<AvailablePlugin> DownloadRemotePlugin(string pluginIdentifier,
throw new InvalidDataException($"Plugin manifest identifier {manifest.Identifier} does not match requested plugin {pluginIdentifier}.");
if (!selectedVersion.Equals(manifest.Version))
throw new InvalidDataException($"Plugin manifest version {manifest.Version} does not match requested version {selectedVersion}.");
+ return manifest;
+ }
+
+ internal async Task DownloadResolvedPlugin(string pluginIdentifier, AvailablePlugin manifest)
+ {
+ var dest = _dataDirectories.Value.PluginDir;
+ var filedest = Path.Join(dest, pluginIdentifier + ".btcpay");
+ var filemanifestdest = Path.Join(dest, pluginIdentifier + ".json");
+ var pluginSelector = $"[{Uri.EscapeDataString(pluginIdentifier)}]";
+ var selectedVersionParameter = Uri.EscapeDataString(manifest.Version.ToString());
+ var url = $"api/v1/plugins/{pluginSelector}/versions/{selectedVersionParameter}/download";
using var resp2 = await _pluginBuilderClient.HttpClient.GetAsync(url);
resp2.EnsureSuccessStatusCode();
+ Directory.CreateDirectory(dest);
await using var fs = new FileStream(filedest, FileMode.Create, FileAccess.ReadWrite);
await resp2.Content.CopyToAsync(fs);
await fs.FlushAsync();
await File.WriteAllTextAsync(filemanifestdest, JsonConvert.SerializeObject(manifest, Formatting.Indented));
- return manifest;
}
internal static Version SelectCompatiblePluginVersion(
### BTCPayServer/Plugins/Subscriptions/Controllers/UISubscriberPortalController.cs
@@ -100,6 +100,7 @@ public async Task<IActionResult> SubscriberPortal(string portalSessionId, string
var creditHist = await ctx.SubscriberCreditHistory
.Where(s => s.SubscriberId == session.SubscriberId && s.Currency == session.Subscriber.Plan.Currency)
.OrderByDescending(s => s.CreatedAt)
+ .ThenByDescending(s => s.Id)
.Take(50)
.ToArrayAsync(cancellationToken);
foreach (var hist in creditHist)
### BTCPayServer/Plugins/Subscriptions/SubscriptionContext.cs
@@ -13,6 +13,7 @@
using BTCPayServer.Services.Rates;
using Dapper;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Storage;
namespace BTCPayServer.Plugins.Subscriptions;
@@ -24,6 +25,7 @@ public class SubscriptionContext(ApplicationDbContext ctx, EventAggregator aggre
public ApplicationDbContext Context => ctx;
public void AddEvent(object evt) => _evts.Add(evt);
public IReadOnlyList<object> Events => _evts;
+ internal void DiscardEvents(int fromIndex = 0) => _evts.RemoveRange(fromIndex, _evts.Count - fromIndex);
public decimal RoundAmount(decimal amount, string currency)
=> RoundAmount(amount, currency, MidpointRounding.ToEven);
@@ -36,11 +38,17 @@ public decimal GetAmountToCredit(InvoiceEntity invoice)
// If the subscriber settled more than expected, we credit the subscriber with the difference.
=> RoundAmount(invoice.Status is InvoiceStatus.Processing ? invoice.PaidAmount.Net : invoice.NetSettled, invoice.Currency, MidpointRounding.ToZero);
- public async Task<decimal> CreditSubscriber(SubscriberData sub, string description, decimal credit)
- => (await TryCreditDebitSubscriber(sub, description, credit, 0m, true))!.Value;
+ public Task<decimal> CreditSubscriber(SubscriberData sub, string description, decimal credit)
+ => CreditSubscriber(sub, description, credit, null);
- public async Task<bool> TryChargeSubscriber(SubscriberData sub, string description, decimal charge, bool allowOverdraft = false)
- => (await TryCreditDebitSubscriber(sub, description, 0m, charge, allowOverdraft)) is not null;
+ public async Task<decimal> CreditSubscriber(SubscriberData sub, string description, decimal credit, string? currency)
+ => (await TryCreditDebitSubscriber(sub, description, credit, 0m, true, currency))!.Value;
+
+ public Task<bool> TryChargeSubscriber(SubscriberData sub, string description, decimal charge, bool allowOverdraft = false)
+ => TryChargeSubscriber(sub, description, charge, allowOverdraft, null);
+
+ public async Task<bool> TryChargeSubscriber(SubscriberData sub, string description, decimal charge, bool allowOverdraft, string? currency)
+ => (await TryCreditDebitSubscriber(sub, description, 0m, charge, allowOverdraft, currency)) is not null;
private static async Task<decimal?> UpdateCredit(BalanceTransaction tx, bool force, ApplicationDbContext ctx)
{
@@ -83,11 +91,11 @@ FROM up
{
id = tx.SubscriberId, currency = tx.Currency, diff, force, desc = tx.Description,
credit = tx.Credit, minBalance = -GreenfieldConstants.MaxAmount, maxBalance = GreenfieldConstants.MaxAmount
- });
+ }, ctx.Database.CurrentTransaction?.GetDbTransaction());
return amount;
}
- private static async Task ReloadCredits(SubscriberData sub, ApplicationDbContext ctx)
+ internal async Task ReloadCredits(SubscriberData sub)
{
foreach (var c in sub.Credits)
ctx.Entry(c).State = EntityState.Detached;
@@ -103,7 +111,7 @@ private static async Task ReloadCredits(SubscriberData sub, ApplicationDbContext
credit = RoundAmount(credit, currency);
var tx = new BalanceTransaction(sub.Id, currency, credit, charge, description);
var amount = await UpdateCredit(tx, allowOverdraft, ctx);
- await ReloadCredits(sub, ctx);
+ await ReloadCredits(sub);
if (amount is { } newTotal)
{
if (tx.Credit != 0)
### BTCPayServer/Plugins/Subscriptions/SubscriptionHostedService.cs
@@ -18,7 +18,9 @@
using Dapper;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static BTCPayServer.Data.Subscriptions.SubscriberData;
@@ -58,10 +60,12 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
EventCode: InvoiceEventCode.Completed or
InvoiceEventCode.MarkedCompleted or
InvoiceEventCode.MarkedInvalid or
+ InvoiceEventCode.FailedToConfirm or
+ InvoiceEventCode.Expired or
InvoiceEventCode.PaidInFull,
Invoice:
{
- Status: InvoiceStatus.Settled or InvoiceStatus.Invalid or InvoiceStatus.Processing
+ Status: InvoiceStatus.Settled or InvoiceStatus.Invalid or InvoiceStatus.Processing or InvoiceStatus.Expired
} settledInvoice
} &&
GetPlanCheckoutIdFromInvoice(settledInvoice) is string checkoutId)
@@ -88,6 +92,11 @@ InvoiceEventCode.MarkedInvalid or
throw new InvalidOperationException("Checkout not found or expired");
if (checkout.Invoice is { Status: not (Data.InvoiceData.Expired or Data.InvoiceData.Invalid) })
return;
+ if (checkout.CreditedByInvoice != 0m)
+ throw new InvalidOperationException("The previous checkout invoice has not been reconciled");
+ if (checkout.Subscriber is { } subscriber &&
+ !subscriber.Plan.Currency.Equals(checkout.Plan.Currency, StringComparison.OrdinalIgnoreCase))
+ throw new InvalidOperationException("The checkout's plan isn't in the same currency as the subscriber's plan");
if (checkout.SuccessRedirectUrl is null)
{
var redirectLink = checkout.Plan.Offering.SuccessRedirectUrl ??
@@ -448,102 +457,116 @@ private async Task StartPlanCheckoutWithoutInvoice(SubscriptionContext subCtx, P
private async Task ProcessSubscriptionPayment(InvoiceEntity invoice, string checkoutId, CancellationToken cancellationToken = default)
{
- var needUpdate = false;
+ await using var ctx = applicationDbContextFactory.CreateContext();
+ await ctx.Database.CreateExecutionStrategy().ExecuteAsync(
+ token => ProcessSubscriptionPaymentCore(invoice, checkoutId, token), cancellationToken);
+ }
+
+ private async Task ProcessSubscriptionPaymentCore(InvoiceEntity invoice, string checkoutId, CancellationToken cancellationToken)
+ {
await using var subCtx = CreateContext(cancellationToken);
var ctx = subCtx.Context;
+ await using var tx = await ctx.Database.BeginTransactionAsync(cancellationToken);
+ var lockedCheckoutId = await ctx.Database.GetDbConnection().ExecuteScalarAsync<string?>(new CommandDefinition(
+ "SELECT id FROM subs_plan_checkouts WHERE id = @checkoutId FOR UPDATE",
+ new { checkoutId }, tx.GetDbTransaction(), cancellationToken: cancellationToken));
+ if (lockedCheckoutId is null)
+ return;
+
var checkout = await ctx.PlanCheckouts.GetCheckout(checkoutId);
- var plan = checkout?.Plan;
- if (checkout is null || plan is null ||
+ if (checkout?.Invoice is null || checkout.InvoiceId != invoice.Id ||
+ checkout.Invoice.Status != invoice.Status.ToString() ||
checkout.Plan.Offering.App.StoreDataId != invoice.StoreId)
return;
- // If subscrberId isn't set, then it should be a new subscriber.
if (checkout.Subscriber is null && !checkout.NewSubscriber)
throw new InvalidOperationException("Bug: Subscriber is null and not a new subscriber");
+ try
+ {
+ await ReconcileCheckoutInvoice(subCtx, checkout, invoice);
+ await tx.CommitAsync(cancellationToken);
+ }
+ catch
+ {
+ subCtx.DiscardEvents();
+ throw;
+ }
+ }
+
+ private async Task ReconcileCheckoutInvoice(SubscriptionContext subCtx, PlanCheckoutData checkout, InvoiceEntity invoice)
+ {
+ var ctx = subCtx.Context;
+ var processing = invoice.Status == InvoiceStatus.Processing;
+ var failed = invoice.Status is InvoiceStatus.Invalid or InvoiceStatus.Expired;
var sub = checkout.Subscriber;
- var processingInvoiceId = invoice.Status == InvoiceStatus.Processing ? invoice.Id : null;
- if (sub is not null &&
- sub.ProcessingInvoiceId != processingInvoiceId)
+ if (sub is null && !failed && (!processing || checkout.Plan.OptimisticActivation))
{
- sub.ProcessingInvoiceId = processingInvoiceId;
- await ctx.SaveChangesAsync();
+ sub = await CreateSubscription(subCtx, checkout, processing);
+ if (sub is not null)
+ ctx.SubscribersInvoices.Add(new SubscriberInvoiceData { SubscriberId = sub.Id, InvoiceId = invoice.Id });
}
- if (invoice.Status == InvoiceStatus.Processing && !plan.OptimisticActivation)
+ if (sub is null)
return;
- if (invoice.Status is InvoiceStatus.Settled or InvoiceStatus.Processing)
+ if (processing && sub.ProcessingInvoiceId is null)
+ sub.ProcessingInvoiceId = invoice.Id;
+ if (!processing && sub.ProcessingInvoiceId == invoice.Id)
{
- // We only create a new subscriber lazily when a payment has been received
- if (sub is null)
- {
- var optimisticActivation = invoice.Status == InvoiceStatus.Processing && plan.OptimisticActivation;
- sub = await CreateSubscription(subCtx, checkout, optimisticActivation);
- if (sub is null)
- return;
-
- ctx.SubscribersInvoices.Add(new SubscriberInvoiceData()
- {
- SubscriberId = sub.Id,
- InvoiceId = invoice.Id
- });
- await ctx.SaveChangesAsync();
- }
-
- var invoiceCredit = subCtx.GetAmountToCredit(invoice);
- if (checkout.CreditedByInvoice != invoiceCredit)
- {
- var diff = invoiceCredit - checkout.CreditedByInvoice;
- if (diff > 0)
- {
- checkout.CreditedByInvoice += diff;
- await subCtx.CreditSubscriber(sub, $"Credit purchase (Inv: {invoice.Id})", diff);
- await TryStartPlan(subCtx, checkout, sub);
- }
- else
- {
- await subCtx.TryChargeSubscriber(sub, $"Adjustement (Inv: {invoice.Id})", -diff, allowOverdraft: true);
- checkout.CreditedByInvoice -= -diff;
- }
- }
-
- if (invoice.Status == InvoiceStatus.Settled && sub.Plan.OptimisticActivation)
- // Maybe we don't need this column
+ sub.ProcessingInvoiceId = null;
+ if (!failed)
sub.OptimisticActivation = false;
+ }
- needUpdate = true;
- await ctx.SaveChangesAsync();
+ if (processing)
+ {
+ if (checkout.Plan.OptimisticActivation && checkout.CreditPurchase is null)
+ await TryStartPlan(subCtx, checkout, sub, invoice);
+ await ctx.SaveChangesAsync(subCtx.CancellationToken);
+ if (checkout.PlanStarted)
+ await UpdateSubscriptionStates(subCtx, sub.Id);
+ return;
}
- else if (sub is not null && invoice.Status == InvoiceStatus.Invalid &&
- checkout is { PlanStarted: true, CreditedByInvoice: not 0m })
+
+ if (failed && checkout.PlanStarted && checkout.CreditedByInvoice > 0m)
{
- // We should probably ask the merchant before reversing the credit...
- // await TryChargeSubscriber(ctx, sub, checkout.Credited, force: true);
- // checkout.Credited = 0m;
sub.IsSuspended = true;
sub.SuspensionReason = "The plan has been started by an invoice which later became invalid.";
- needUpdate = true;
- await ctx.SaveChangesAsync();
}
- if (sub is not null)
+ var invoiceCredit = failed ? 0m : subCtx.GetAmountToCredit(invoice);
+ var diff = invoiceCredit - checkout.CreditedByInvoice;
+ if (diff > 0m)
{
- if (needUpdate)
- await UpdateSubscriptionStates(subCtx, sub.Id);
+ await subCtx.CreditSubscriber(sub, $"Credit purchase (Inv: {invoice.Id})", diff, invoice.Currency);
+ checkout.CreditedByInvoice = invoiceCredit;
+ await TryStartPlan(subCtx, checkout, sub);
}
+ else if (diff < 0m)
+ {
+ var description = failed ? $"Reversal (Inv: {invoice.Id})" : $"Adjustment (Inv: {invoice.Id})";
+ if (await subCtx.TryChargeSubscriber(sub, description, -diff, allowOverdraft: true, currency: invoice.Currency))
+ checkout.CreditedByInvoice = invoiceCredit;
+ else
+ Logs.PayServer.LogWarning("Subscriber credit adjustment for invoice {InvoiceId} exceeds balance limits", invoice.Id);
+ }
+
+ await ctx.SaveChangesAsync(subCtx.CancellationToken);
+ if (!failed || diff != 0m)
+ await UpdateSubscriptionStates(subCtx, sub.Id);
}
- private async Task TryStartPlan(SubscriptionContext subCtx, PlanCheckoutData checkout, SubscriberData sub)
+ private async Task TryStartPlan(SubscriptionContext subCtx, PlanCheckoutData checkout, SubscriberData sub, InvoiceEntity? unconfirmedInvoice = null)
{
- if (checkout.PlanStarted)
+ if (checkout.PlanStarted || !checkout.Plan.Currency.Equals(sub.Plan.Currency, StringComparison.OrdinalIgnoreCase))
return;
var prevPlan = sub.Plan;
var now = subCtx.Now;
using var scope = sub.NewPlanScope(checkout.Plan);
if (sub.CanStartNextPlanEx(checkout.NewSubscriber))
{
- if (checkout.IsTrial || await subCtx.TryChargeSubscriber(sub, $"Starting plan '{sub.NextPlan.Name}'", sub.NextPlan.Price))
+ if (checkout.IsTrial || await TryChargeForPlan($"Starting plan '{sub.NextPlan.Name}'", 0m))
{
sub.StartNextPlan(now, checkout.IsTrial);
scope.Commit();
@@ -567,7 +590,7 @@ private async Task TryStartPlan(SubscriptionContext subCtx, PlanCheckoutData che
PlanChangeData.ChangeType.Downgrade => $"Downgrade to new plan '{sub.NewPlan?.Name}'",
_ => $"Migration to plan '{sub.NewPlan?.Name}'"
};
- if (checkout.IsTrial || await subCtx.TryCreditDebitSubscriber(sub, description, unusedAmount, sub.NextPlan.Price) is not null)
+ if (checkout.IsTrial || await TryChargeForPlan(description, unusedAmount))
{
checkout.RefundAmount = unusedAmount;
sub.StartNextPlan(now, checkout.IsTrial);
@@ -577,6 +600,39 @@ private async Task TryStartPlan(SubscriptionContext subCtx, PlanCheckoutData che
}
if (checkout.PlanStarted)
subCtx.AddEvent(new SubscriptionEvent.PlanStarted(sub, prevPlan));
+
+ async Task<bool> TryChargeForPlan(string description, decimal refund)
+ {
+ var plan = sub.NextPlan;
+ if (unconfirmedInvoice is null)
+ return await subCtx.TryCreditDebitSubscriber(sub, description, refund, plan.Price) is not null;
+ if (!plan.Currency.Equals(unconfirmedInvoice.Currency, StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ var maxProvisionalCredit = Math.Max(0m, subCtx.RoundAmount(plan.Price, plan.Currency) - refund);
+ var availablePayment = subCtx.GetAmountToCredit(unconfirmedInvoice);
+ var credit = Math.Min(maxProvisionalCredit, availablePayment) - checkout.CreditedByInvoice;
+ if (credit <= 0m)
+ return await subCtx.TryCreditDebitSubscriber(sub, description, refund, plan.Price) is not null;
+
+ var tx = subCtx.Context.Database.CurrentTransaction!;
+ var cancellationToken = subCtx.CancellationToken;
+ var eventCount = subCtx.Events.Count;
+ const string savepoint = "plan_purchase";
+ await tx.CreateSavepointAsync(savepoint, cancellationToken);
+ if (await subCtx.TryCreditDebitSubscriber(sub, $"Credit purchase (Inv: {unconfirmedInvoice.Id})", credit, 0m, currency: unconfirmedInvoice.Currency) is not null &&
+ await subCtx.TryCreditDebitSubscriber(sub, description, refund, plan.Price) is not null)
+ {
+ checkout.CreditedByInvoice += credit;
+ await tx.ReleaseSavepointAsync(savepoint, cancellationToken);
+ return true;
+ }
+
+ await tx.RollbackToSavepointAsync(savepoint, cancellationToken);
+ subCtx.DiscardEvents(eventCount);
+ await subCtx.ReloadCredits(sub);
+ return false;
+ }
}
record MoveTimeRequest(MemberSelector MemberSelector, TimeSpan Period);
@@ -738,6 +794,9 @@ public async Task<PlanMigrationResult> CreatePlanMigrationCheckout(string portal
if (planChangeRecord == null)
return new PlanMigrationResult.NotFound();
+ if (!plan.Currency.Equals(portal.Subscriber.Plan.Currency, StringComparison.OrdinalIgnoreCase))
+ return new PlanMigrationResult.NotFound();
+
if (planChangeRecord.Timing == PlanChangeData.ChangeTiming.AtPeriodEnd)
{
if (portal.Subscriber.PeriodEnd is not null && portal.Subscriber.PeriodEnd > DateTimeOffset.UtcNow
### BTCPayServer/Plugins/Subscriptions/SubscriptionsReportProvider.cs
@@ -105,7 +105,7 @@ public override async Task Query(QueryContext queryContext, CancellationToken ca
.Include(h => h.SubscriberCredit).ThenInclude(c => c.Subscriber).ThenInclude(s => s.Customer).ThenInclude(c => c.CustomerIdentities)
.Where(h => h.SubscriberCredit.Subscriber.Plan.Offering.App.StoreDataId == queryContext.StoreId)
.Where(h => h.CreatedAt >= queryContext.From && h.CreatedAt <= queryContext.To)
- .OrderBy(h => h.CreatedAt).ToListAsync(cancellation);
+ .OrderBy(h => h.CreatedAt).ThenBy(h => h.Id).ToListAsync(cancellation);
foreach (var entry in history)
{
### BTCPayServer/Plugins/Wallets/Controllers/GreenfieldStoreOnChainWalletsController.cs
@@ -26,6 +26,7 @@
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitcoin.Payment;
+using NBitcoin.RPC;
using NBXplorer;
using NBXplorer.Models;
using Newtonsoft.Json.Linq;
@@ -46,7 +47,6 @@ public class GreenfieldStoreOnChainWalletsController(
PoliciesSettings policiesSettings,
UIWalletsController walletsController,
PayjoinClient payjoinClient,
- DelayedTransactionBroadcaster delayedTransactionBroadcaster,
WalletReceiveService walletReceiveService,
IFeeProviderFactory feeProviderFactory,
WalletHistogramService walletHistogramService,
@@ -609,47 +609,50 @@ payjoinOutputIndex is null
psbt.PSBT.Finalize();
var transaction = psbt.PSBT.ExtractTransaction();
var transactionHash = transaction.GetHash();
- BroadcastResult broadcastResult;
+ if (!request.ProceedWithBroadcast)
+ {
+ return Ok(new JValue(transaction.ToHex()));
+ }
+
if (!string.IsNullOrEmpty(signingContext?.PayJoinBIP21))
{
- signingContext.OriginalPSBT = psbt.PSBT.ToBase64();
try
{
- await delayedTransactionBroadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2.0),
- transaction, network);
payjoinClient.MinimumFeeRate = minRelayFee;
+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var payjoinPSBT = await payjoinClient.RequestPayjoin(
new BitcoinUrlBuilder(signingContext.PayJoinBIP21, network.NBitcoinNetwork),
new PayjoinWallet(derivationScheme),
- signedPSBT, CancellationToken.None);
+ signedPSBT, cts.Token);
payjoinPSBT.Settings.SigningOptions =
new SigningOptions() { EnforceLowR = !(signingContext?.EnforceLowR is false) };
payjoinPSBT = payjoinPSBT.SignAll(derivationScheme.AccountDerivation, accountKey, rootedKeyPath);
+ var balanceChange = payjoinPSBT.GetBalance(derivationScheme.AccountDerivation, signingKey, rootedKeyPath);
payjoinPSBT.Finalize();
var payjoinTransaction = payjoinPSBT.ExtractTransaction();
var hash = payjoinTransaction.GetHash();
await walletRepository.AddWalletTransactionAttachment(new WalletId(Store.Id, network.CryptoCode),
hash, Attachment.Payjoin());
- broadcastResult = await explorerClient.BroadcastAsync(payjoinTransaction);
- if (broadcastResult.Success)
+ var payjoinBroadcast = await explorerClient.BroadcastAsync(payjoinTransaction, cts.Token);
+ if (IsAcceptedBroadcast(payjoinBroadcast))
{
- return await GetOnChainWalletTransaction(storeId, paymentMethodId, hash.ToString());
+ return BroadcastTransactionResult(hash, balanceChange.GetValue(network));
}
}
- catch (PayjoinException)
+ catch (Exception)
{
//not a critical thing, payjoin is great if possible, fine if not
}
}
- if (!request.ProceedWithBroadcast)
- {
- return Ok(new JValue(transaction.ToHex()));
- }
-
- broadcastResult = await explorerClient.BroadcastAsync(transaction);
- if (broadcastResult.Success)
+ var broadcastResult = await explorerClient.BroadcastAsync(transaction);
+ if (IsAcceptedBroadcast(broadcastResult))
{
+ if (signingContext?.PayJoinBIP21 is not null)
+ {
+ var balanceChange = signedPSBT.GetBalance(derivationScheme.AccountDerivation, signingKey, rootedKeyPath);
+ return BroadcastTransactionResult(transactionHash, balanceChange.GetValue(network));
+ }
return await GetOnChainWalletTransaction(storeId, paymentMethodId, transactionHash.ToString());
}
else
@@ -658,6 +661,19 @@ await walletRepository.AddWalletTransactionAttachment(new WalletId(Store.Id, net
}
}
+ private static bool IsAcceptedBroadcast(BroadcastResult result) =>
+ result.Success || result.RPCCode == RPCErrorCode.RPC_TRANSACTION_ALREADY_IN_CHAIN;
+
+ private IActionResult BroadcastTransactionResult(uint256 hash, decimal balanceChange) =>
+ Ok(new OnChainWalletTransactionData
+ {
+ TransactionHash = hash,
+ Amount = balanceChange,
+ Timestamp = DateTimeOffset.UtcNow,
+ Status = TransactionStatus.Unconfirmed,
+ Comment = string.Empty
+ });
+
[Authorize(Policy = WalletPolicies.CanBroadcastWalletTransactions, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpPost("~/api/v1/stores/{storeId}/payment-methods/{paymentMethodId}/wallet/transactions/broadcast")]
public async Task<IActionResult> BroadcastOnChainTransaction(string storeId, string paymentMethodId,
### BTCPayServer/Plugins/Wallets/Controllers/UIWalletsController.cs
@@ -1722,8 +1722,11 @@ private IActionResult RedirectToWalletPSBT(WalletPSBTViewModel vm)
public IActionResult SignWithSeed([ModelBinder(typeof(WalletIdModelBinder))] WalletId walletId,
SigningContextModel signingContext, string? returnUrl, string? backUrl)
{
- signingContext.PendingTransactionId = null;
- signingContext.OriginalPSBT = null;
+ signingContext = new SigningContextModel
+ {
+ PSBT = signingContext.PSBT,
+ EnforceLowR = signingContext.EnforceLowR
+ };
return ViewSignWithSeed(signingContext, returnUrl, backUrl);
}
### BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs
@@ -66,29 +66,38 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
// Give new accounts time to create API keys via the Greenfield API.
TimeSpan? accountAge = user?.Created is { } created ? DateTimeOffset.UtcNow - created : null;
var isNewAccount = accountAge >= TimeSpan.Zero && accountAge <= TimeSpan.FromMinutes(5);
- if (!isNewAccount)
- {
- if (Context.Connection.RemoteIpAddress?.ToString() is string ip)
- if (!await rateLimitService.Throttle(ZoneLimits.Login, ip))
- return Fail($"Basic authentication failed: Rate limited. Please use authentication with API Keys to avoid throttling.");
- }
+ const string invalidCredentials = "Basic authentication failed";
+ var ip = Context.Connection.RemoteIpAddress?.ToString();
+ if (!isNewAccount && ip is not null && !await rateLimitService.Throttle(ZoneLimits.Login, ip))
+ return Fail(invalidCredentials);
+
+ if (user is null)
+ return Fail(invalidCredentials);
var loggingContext = new UserService.CanLoginContext(user, baseUrl: Request.GetRequestBaseUrl());
- if (!await userService.CanLogin(loggingContext))
+ var canLogin = await userService.CanLogin(loggingContext);
+ var allowsBasic = isNewAccount || user.GetBlob()?.AllowGreenfieldBasicAuth is true;
+ var requiresTwoFactor = canLogin && allowsBasic && await signInManager.IsTwoFactorEnabledAsync(user);
+ var canUseBasic = canLogin && allowsBasic && !requiresTwoFactor;
+ if (isNewAccount && !canUseBasic && ip is not null && !await rateLimitService.Throttle(ZoneLimits.Login, ip))
+ return Fail(invalidCredentials);
+
+ var passwordVerified = canUseBasic
+ ? (await signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true)).Succeeded
+ : await userManager.CheckPasswordAsync(user, password);
+ if (!passwordVerified)
+ return Fail(invalidCredentials);
+
+ if (!canLogin)
{
return Fail($"Basic authentication failed: {loggingContext.Failures[0].Text.Value}");
}
- if (user is null)
- return Fail($"Basic authentication failed");
- if (!isNewAccount && user.GetBlob()?.AllowGreenfieldBasicAuth is not true)
+ if (!allowsBasic)
return Fail("Basic authentication for the Greenfield API is not enabled for this user.");
- if (await signInManager.IsTwoFactorEnabledAsync(user))
+ if (requiresTwoFactor)
{
return Fail("Cannot use Basic authentication when multi-factor is enabled.");
}
- var result = await signInManager.CheckPasswordSignInAsync(user, password, true);
- if (!result.Succeeded)
- return Fail(result.ToString());
var claims = new List<Claim>()
{
new Claim(identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, user.Id),
### BTCPayServer/Services/DelayedTransactionBroadcaster.cs
@@ -7,8 +7,10 @@
using BTCPayServer.Logging;
using Dapper;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using NBitcoin;
+using NBitcoin.RPC;
namespace BTCPayServer.Services
{
@@ -20,6 +22,8 @@ class Record
public DateTimeOffset BroadcastTime;
public Transaction Transaction;
public BTCPayNetwork Network;
+ public string PayjoinTransactionId;
+ public string[] PayjoinOutpoints;
}
private readonly BTCPayNetworkProvider _networkProvider;
@@ -41,22 +45,32 @@ public DelayedTransactionBroadcaster(
this.Logs = logs;
}
- public async Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network)
+ public Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network)
+ => Schedule(broadcastTime, transaction, network, null, null);
+
+ internal async Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network,
+ uint256 payjoinTransactionId, OutPoint[] payjoinOutpoints)
{
ArgumentNullException.ThrowIfNull(transaction);
ArgumentNullException.ThrowIfNull(network);
using var db = _dbContextFactory.CreateContext();
var conn = db.Database.GetDbConnection();
await conn.ExecuteAsync(
"""
- INSERT INTO "PlannedTransactions"("Id", "BroadcastAt", "Blob") VALUES(@Id, @BroadcastAt, @Blob)
- ON CONFLICT DO NOTHING
+ INSERT INTO "PlannedTransactions"("Id", "BroadcastAt", "Blob", "PayjoinTransactionId", "PayjoinOutpoints")
+ VALUES(@Id, @BroadcastAt, @Blob, @PayjoinTransactionId, @PayjoinOutpoints)
+ ON CONFLICT ("Id") DO UPDATE SET
+ "PayjoinTransactionId" = EXCLUDED."PayjoinTransactionId",
+ "PayjoinOutpoints" = EXCLUDED."PayjoinOutpoints"
+ WHERE "PlannedTransactions"."PayjoinTransactionId" IS NULL AND EXCLUDED."PayjoinTransactionId" IS NOT NULL
""",
new
{
Id = $"{network.CryptoCode}-{transaction.GetHash()}",
BroadcastAt = broadcastTime,
- Blob = transaction.ToBytes()
+ Blob = transaction.ToBytes(),
+ PayjoinTransactionId = payjoinTransactionId?.ToString(),
+ PayjoinOutpoints = payjoinOutpoints?.Select(o => o.ToString()).ToArray()
});
}
@@ -65,32 +79,35 @@ public async Task<int> ProcessAll(CancellationToken cancellationToken = default)
if (disabled)
return 0;
List<Record> scheduled = new List<Record>();
- using (var db = _dbContextFactory.CreateContext())
+ using (var readContext = _dbContextFactory.CreateContext())
{
- scheduled = (await db.PlannedTransactions
- .ToListAsync()).Select(ToRecord)
+ scheduled = (await readContext.PlannedTransactions
+ .ToListAsync(cancellationToken)).Select(ToRecord)
.Where(r => r != null)
// Client side filtering because entity framework is retarded.
.Where(r => r.BroadcastTime < DateTimeOffset.UtcNow).ToList();
}
- List<Record> rescheduled = new List<Record>();
List<Record> broadcasted = new List<Record>();
var broadcasts = scheduled.Select(async (record) =>
{
var explorer = _explorerClientProvider.GetExplorerClient(record.Network);
if (explorer is null)
- return false;
+ return record.PayjoinTransactionId is not null;
try
{
- // We don't look the result, this is a best effort basis.
+ if (record.PayjoinTransactionId is not null &&
+ (await explorer.GetTransactionAsync(uint256.Parse(record.PayjoinTransactionId), cancellationToken))?.Confirmations > 0)
+ return false;
+
var result = await explorer.BroadcastAsync(record.Transaction, cancellationToken);
if (result.Success)
{
Logs.PayServer.LogInformation($"{record.Network.CryptoCode}: {record.Transaction.GetHash()} has been successfully broadcasted");
}
- return false;
+ return record.PayjoinTransactionId is not null && !result.Success &&
+ result.RPCCode != RPCErrorCode.RPC_TRANSACTION_ALREADY_IN_CHAIN;
}
catch
{
@@ -101,18 +118,33 @@ public async Task<int> ProcessAll(CancellationToken cancellationToken = default)
for (int i = 0; i < scheduled.Count; i++)
{
- var needReschedule = await broadcasts[i];
- (needReschedule ? rescheduled : broadcasted).Add(scheduled[i]);
+ if (!await broadcasts[i])
+ broadcasted.Add(scheduled[i]);
}
- using (var db = _dbContextFactory.CreateContext())
+ if (broadcasted.Count == 0)
+ return 0;
+
+ await using var db = _dbContextFactory.CreateContext();
+ return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
- foreach (Record record in broadcasted)
+ await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
+ var removed = 0;
+ foreach (var record in broadcasted.OrderBy(r => r.Id, StringComparer.Ordinal))
{
- db.PlannedTransactions.Remove(new PlannedTransaction() { Id = record.Id });
+ var deleted = await db.PlannedTransactions
+ .Where(p => p.Id == record.Id && p.PayjoinTransactionId == record.PayjoinTransactionId)
+ .ExecuteDeleteAsync(cancellationToken);
+ if (deleted == 0)
+ continue;
+ removed += deleted;
+ var outpoints = record.PayjoinOutpoints;
+ if (outpoints is not null)
+ await db.PayjoinLocks.Where(l => outpoints.Contains(l.Id)).ExecuteDeleteAsync(cancellationToken);
}
- return await db.SaveChangesAsync();
- }
+ await transaction.CommitAsync(cancellationToken);
+ return removed;
+ });
}
private Record ToRecord(PlannedTransaction plannedTransaction)
@@ -126,7 +158,9 @@ private Record ToRecord(PlannedTransaction plannedTransaction)
Id = plannedTransaction.Id,
Network = network,
Transaction = Transaction.Load(plannedTransaction.Blob, network.NBitcoinNetwork),
- BroadcastTime = plannedTransaction.BroadcastAt
+ BroadcastTime = plannedTransaction.BroadcastAt,
+ PayjoinTransactionId = plannedTransaction.PayjoinTransactionId,
+ PayjoinOutpoints = plannedTransaction.PayjoinOutpoints
};
}
### BTCPayServer/Services/Invoices/InvoiceRepository.cs
@@ -629,6 +629,8 @@ public async Task UpdateInvoiceMetadata(string invoiceId, string metadataKey, ob
public async Task<bool> MarkInvoiceStatus(string invoiceId, InvoiceStatus status)
{
+ var retriesRemaining = 2;
+retry:
using (var context = _applicationDbContextFactory.CreateContext())
{
var invoiceData = await GetInvoiceRaw(invoiceId, context);
@@ -664,7 +666,15 @@ public async Task<bool> MarkInvoiceStatus(string invoiceId, InvoiceStatus status
invoiceData.Status = status.ToString();
invoiceData.ExceptionStatus = InvoiceExceptionStatus.Marked.ToString();
var invoiceEvent = new InvoiceEvent(ToEntity(invoiceData), eventName) { PreviousStatus = previousStatus };
- await context.SaveChangesAsync();
+ try
+ {
+ await context.SaveChangesAsync();
+ }
+ catch (DbUpdateConcurrencyException) when (retriesRemaining > 0)
+ {
+ retriesRemaining--;
+ goto retry;
+ }
_eventAggregator.Publish(invoiceEvent);
}
### BTCPayServer/Services/UserService.cs
@@ -258,37 +258,51 @@ public async Task<SetDisabledResult> SetAccessRestriction(
if (user is null)
return new SetDisabledResult.Unchanged();
- await using var ctx = _applicationDbContextFactory.CreateContext();
- var existing = await ctx.UserAccessRestrictions.FindAsync(userId, type);
- if (restricted == (existing is not null))
- return new SetDisabledResult.Unchanged();
-
+ await using var strategyContext = _applicationDbContextFactory.CreateContext();
+ var commitAttempted = false;
try
{
- if (restricted)
+ var result = await strategyContext.Database.CreateExecutionStrategy().ExecuteAsync<SetDisabledResult>(async () =>
{
- ctx.UserAccessRestrictions.Add(new UserAccessRestriction
+ await using var ctx = _applicationDbContextFactory.CreateContext();
+ await using var transaction = await ctx.Database.BeginTransactionAsync();
+ var existing = await ctx.UserAccessRestrictions.FindAsync(userId, type);
+ if (restricted == (existing is not null))
+ // A lost commit response may leave the requested change persisted.
+ return commitAttempted ? new SetDisabledResult.Success { User = user } : new SetDisabledResult.Unchanged();
+
+ if (restricted)
{
- ApplicationUserId = userId,
- Type = type,
- CreatedAt = DateTimeOffset.UtcNow
- });
- }
- else
- {
- ctx.UserAccessRestrictions.Remove(existing!);
- }
+ ctx.UserAccessRestrictions.Add(new UserAccessRestriction
+ {
+ ApplicationUserId = userId,
+ Type = type,
+ CreatedAt = DateTimeOffset.UtcNow
+ });
+ }
+ else
+ {
+ ctx.UserAccessRestrictions.Remove(existing!);
+ }
- await ctx.SaveChangesAsync();
+ await ctx.SaveChangesAsync();
- if (restricted)
- {
- await userManager.UpdateSecurityStampAsync(user);
- // Force immediate cookie revalidation instead of waiting for the stamp validation interval.
- _securityStampInvalidator.Invalidate(user.Id);
- }
- await ctx.Users.UpdateStoreNoActiveUserForUsers([userId]);
- return new SetDisabledResult.Success { User = user };
+ if (restricted)
+ {
+ var securityStamp = Guid.NewGuid().ToString();
+ var concurrencyStamp = Guid.NewGuid().ToString();
+ await ctx.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(setters => setters
+ .SetProperty(u => u.SecurityStamp, securityStamp)
+ .SetProperty(u => u.ConcurrencyStamp, concurrencyStamp));
+ }
+ await ctx.Users.UpdateStoreNoActiveUserForUsers([userId]);
+ commitAttempted = true;
+ await transaction.CommitAsync();
+ return new SetDisabledResult.Success { User = user };
+ });
+ if (restricted && result is SetDisabledResult.Success)
+ _securityStampInvalidator.Invalidate(userId);
+ return result;
}
catch (DbUpdateException ex)
{
### BTCPayServer/Views/UIStores/GeneralSettings.cshtml
@@ -214,16 +214,11 @@
<a href="https://docs.btcpayserver.org/FAQ/Stores/#consider-the-invoice-confirmed-when-the-payment-transaction" target="_blank" rel="noreferrer noopener" title="@StringLocalizer["More information..."]">
<vc:icon symbol="info"/>
</a>
- <select asp-for="SpeedPolicy" class="form-select w-auto" onchange="document.getElementById('unconfirmed-warning').hidden = this.value !== '0'">
- <option value="0" text-translate="true">Is unconfirmed</option>
+ <select asp-for="SpeedPolicy" class="form-select w-auto">
<option value="1" text-translate="true">Has at least 1 confirmation</option>
<option value="3" text-translate="true">Has at least 2 confirmations</option>
<option value="2" text-translate="true">Has at least 6 confirmations</option>
</select>
- <p class="info-note my-3 text-warning" id="unconfirmed-warning" role="alert" hidden="@(Model.SpeedPolicy != 0)">
- <vc:icon symbol="warning"/>
- <span text-translate="true">Choosing to accept an unconfirmed invoice can lead to double-spending and is strongly discouraged.</span>
- </p>
<span asp-validation-for="SpeedPolicy" class="text-danger"></span>
</div>
<div class="form-group d-flex align-items-center">
### BTCPayServer/wwwroot/swagger/v1/swagger.template.invoices.json
@@ -568,7 +568,7 @@
"$ref": "#/components/parameters/InvoiceId"
}
],
- "description": "Refund invoice. The store is resolved automatically from the invoice.",
+ "description": "Refund invoice. The store is resolved automatically from the invoice. Unless the `refundVariant` is `Custom`, this fails if the invoice already has a refund which is not archived.",
"operationId": "Invoices_Refund",
"requestBody": {
"required": true,
### BTCPayServer/wwwroot/swagger/v1/swagger.template.json
@@ -103,15 +103,13 @@
},
"SpeedPolicy": {
"type": "string",
- "description": "This is a risk mitigation parameter for the merchant to configure how they want to fulfill orders depending on the number of block confirmations for the transaction made by the consumer on the selected cryptocurrency.\n`\"HighSpeed\"`: 0 confirmations (1 confirmation if RBF enabled in transaction) \n`\"MediumSpeed\"`: 1 confirmation \n`\"LowMediumSpeed\"`: 2 confirmations \n`\"LowSpeed\"`: 6 confirmations\n",
+ "description": "This is a risk mitigation parameter for the merchant to configure how they want to fulfill orders depending on the number of block confirmations for the transaction made by the consumer on the selected cryptocurrency.\n`\"MediumSpeed\"`: 1 confirmation \n`\"LowMediumSpeed\"`: 2 confirmations \n`\"LowSpeed\"`: 6 confirmations\n",
"x-enumNames": [
- "HighSpeed",
"MediumSpeed",
"LowSpeed",
"LowMediumSpeed"
],
"enum": [
- "HighSpeed",
"MediumSpeed",
"LowSpeed",
"LowMediumSpeed"
@@ -233,4 +231,4 @@
"Basic": []
}
]
-}
\ No newline at end of file
+}
### BTCPayServer/wwwroot/swagger/v1/swagger.template.pull-payments.json
@@ -668,7 +668,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmanagepullpayments"
+ "btcpay.store.canviewpayouts"
],
"Basic": []
}
@@ -692,7 +692,7 @@
"type": "string",
"nullable": true,
"example": "kraken(BTC_USD)",
- "description": "The rate rule to calculate the rate of the payout. This can also be a fixed decimal. (if null or unspecified, will use the same rate setting as the store's settings)"
+ "description": "The rate rule to calculate the rate of the payout. This can also be a fixed decimal. (if null or unspecified, will use the same rate setting as the store's settings). Specifying it additionally requires the `btcpay.store.cancreatepullpayments` permission."
}
}
}
@@ -740,7 +740,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmanagepullpayments"
+ "btcpay.store.canmanagepayouts"
],
"Basic": []
}
@@ -764,7 +764,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmanagepullpayments"
+ "btcpay.store.canmanagepayouts"
],
"Basic": []
}
@@ -821,7 +821,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmanagepullpayments"
+ "btcpay.store.canmanagepayouts"
],
"Basic": []
}
@@ -895,7 +895,7 @@
"security": [
{
"API_Key": [
- "btcpay.store.canmanagepullpayments"
+ "btcpay.store.canmanagepayouts"
],
"Basic": []
}Why this scored 78/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.