Harden payment and wallet validation (#7664)
What changed, and why it matters
This commit fixes several input-validation bugs in BTCPay Server. The most important change corrects a logic error in store settings validation: previously, expiration times were only rejected if they were simultaneously too short AND too long, which effectively allowed any value. The commit also blocks negative or zero amounts for Lightning payments and LNURL invoices, prevents crashes when parsing malformed wallet backup files, and fixes a charting bug for empty wallets. These are hardening fixes rather than a single critical vulnerability.
Review and merge the patch, then ensure the new validation rules are enforced server-side for all API clients. Consider whether the corrected store expiration validation should be backported, as the prior logic effectively disabled the intended limits.
Security signals we found
Validation logic bug: && instead of || allowed out-of-range store expiration values
Negative/zero amount accepted for Lightning invoice payment and LNURL pay
Unhardened BSMS wallet file parsing could throw on malformed input
Missing null check on exchange rate before creating refund pull payment
Empty wallet histogram series could cause index-out-of-range/corrupted data
Evidence from the diff
The patch hardens validation across Greenfield API controllers and wallet parsing. Key changes: (1) GreenfieldStoresController.cs replaces && with || in InvoiceExpiration/DisplayExpirationTimer/MonitoringExpiration range checks, so values outside the allowed min/max are actually rejected. (2) GreenfieldLightningNodeApiController.cs and UILNURLController.cs reject negative/zero Amount values for Lightning invoice payments and LNURL pay requests. (3) BSMSWalletFileParser.cs wraps descriptor/address parsing in a try/catch and nulls output on mismatch, preventing exceptions from malformed BSMS wallet files. (4) GreenfieldInvoiceController.cs adds a null check on rateResult.BidAsk before refunding at the current rate. (5) WalletHistogramService.cs handles empty series to avoid index-out-of-range errors. Tests are added for each scenario.
Changed components
BTCPayServer/Controllers/GreenField/GreenfieldStoresController.csBTCPayServer/Controllers/GreenField/GreenfieldLightningNodeApiController.csBTCPayServer/Controllers/GreenField/GreenfieldInvoiceController.csBTCPayServer/Controllers/UILNURLController.csBTCPayServer/Services/WalletFileParsing/BSMSWalletFileParser.csBTCPayServer/Services/Wallets/WalletHistogramService.csInspect captured patch +105 / −12
### BTCPayServer.Tests/FastTests.cs
@@ -30,6 +30,7 @@
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Services.Wallets.Import;
+using BTCPayServer.Services.WalletFileParsing;
using BTCPayServer.Validation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
@@ -1240,6 +1241,27 @@ public void ParseDerivationSchemeSettings()
Assert.Equal("BSMS", nunchuk.Source);
Assert.Null(error);
+ var bsmsParser = new BSMSWalletFileParser();
+ Assert.False(bsmsParser.TryParse(mainnet, """
+ BSMS 1.0
+ invalid descriptor
+ /0/*
+ invalid address
+ """, out var invalidBsms));
+ Assert.Null(invalidBsms);
+ Assert.False(bsmsParser.TryParse(mainnet, """
+ BSMS 1.0
+ invalid descriptor
+ /0/*
+ bc1qfzu57kgu5jthl934f9xrdzzx8mmemx7gn07tf0grnvz504j6kzusu2v0ku
+ """, out invalidBsms));
+ Assert.Null(invalidBsms);
+ var mismatchedAddress = new Key().PubKey.WitHash.GetAddress(Network.Main).ToString();
+ Assert.False(bsmsParser.TryParse(mainnet,
+ bsms.Replace("bc1qfzu57kgu5jthl934f9xrdzzx8mmemx7gn07tf0grnvz504j6kzusu2v0ku", mismatchedAddress),
+ out invalidBsms));
+ Assert.Null(invalidBsms);
+
// Failure case
Assert.False(parsers.TryParseWalletFile(
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -1521,6 +1521,20 @@ await AssertValidationError(["CssUrl", "LogoUrl", "BrandColor", "SupportUrl", "W
Website = "javascript:document.body.dataset.pwned=1",
BrandColor = "invalid"
}));
+ await AssertValidationError(["InvoiceExpiration", "DisplayExpirationTimer", "MonitoringExpiration"], async () =>
+ await client.UpdateStore(newStore.Id, new UpdateStoreRequest
+ {
+ InvoiceExpiration = TimeSpan.Zero,
+ DisplayExpirationTimer = TimeSpan.Zero,
+ MonitoringExpiration = TimeSpan.Zero
+ }));
+ await AssertValidationError(["InvoiceExpiration", "DisplayExpirationTimer", "MonitoringExpiration"], async () =>
+ await client.UpdateStore(newStore.Id, new UpdateStoreRequest
+ {
+ InvoiceExpiration = TimeSpan.FromDays(25),
+ DisplayExpirationTimer = TimeSpan.FromDays(25),
+ MonitoringExpiration = TimeSpan.FromDays(25)
+ }));
//update store
Assert.Empty(newStore.PaymentMethodCriteria);
@@ -2915,6 +2929,10 @@ await AssertHttpError(403, async () =>
});
Assert.Empty(await walletViewerClient.GetOnChainWalletUTXOs(walletId.StoreId, walletId.CryptoCode));
Assert.Empty(await client.GetOnChainWalletUTXOs(walletId.StoreId, walletId.CryptoCode));
+ var emptyHistogram = await client.GetOnChainWalletHistogram(walletId.StoreId, walletId.CryptoCode);
+ Assert.Equal(0m, emptyHistogram.Balance);
+ Assert.Equal(emptyHistogram.Balance, emptyHistogram.Series.Last());
+ Assert.Equal(emptyHistogram.Series.Count, emptyHistogram.Labels.Count);
uint256 txhash = null;
await tester.WaitForEvent<NewOnChainTransactionEvent>(async () =>
{
### BTCPayServer.Tests/LightningTests.cs
@@ -162,6 +162,14 @@ public async Task CanUseLightningAPI()
Assert.NotEmpty(merchantPendingInvoices);
Assert.Contains(merchantPendingInvoices, i => i.Id == merchantInvoice.Id);
+ var validationErr = await Assert.ThrowsAsync<GreenfieldValidationException>(async () =>
+ await client.PayLightningInvoice(user.StoreId, "BTC", new PayLightningInvoiceRequest
+ {
+ BOLT11 = merchantInvoice.BOLT11,
+ Amount = LightMoney.Satoshis(-1)
+ }));
+ Assert.Contains(validationErr.ValidationErrors, error => error.Path == "Amount");
+
var payResponse = await client.PayLightningInvoice(user.StoreId, "BTC", new PayLightningInvoiceRequest
{
BOLT11 = merchantInvoice.BOLT11
@@ -187,7 +195,7 @@ await Assert.ThrowsAsync<GreenfieldValidationException>(async () => await client
BOLT11 = "lol"
}));
- var validationErr = await Assert.ThrowsAsync<GreenfieldValidationException>(async () => await client.CreateLightningInvoice(user.StoreId, "BTC",
+ validationErr = await Assert.ThrowsAsync<GreenfieldValidationException>(async () => await client.CreateLightningInvoice(user.StoreId, "BTC",
new CreateLightningInvoiceRequest()
{
Amount = -1,
### BTCPayServer.Tests/PlaywrightTests.cs
@@ -376,6 +376,20 @@ await ConnectChannels.ConnectAll(s.Server.ExplorerNode,
await s.Page.CheckAsync("#LUD12Enabled");
await s.ClickPagePrimary();
+ var store = await s.Server.PayTester.StoreRepository.FindStore(storeId);
+ var storeBlob = store.GetStoreBlob();
+ storeBlob.AnyoneCanInvoice = true;
+ store.SetStoreBlob(storeBlob);
+ await s.Server.PayTester.StoreRepository.UpdateStore(store);
+ using (var zeroAmountResponse = await s.Server.PayTester.HttpClient.GetAsync($"BTC/lnurl/{storeId}/pay?amount=0"))
+ {
+ Assert.Equal(HttpStatusCode.BadRequest, zeroAmountResponse.StatusCode);
+ }
+ using (var negativeAmountResponse = await s.Server.PayTester.HttpClient.GetAsync($"BTC/lnurl/{storeId}/pay?amount=-1"))
+ {
+ Assert.Equal(HttpStatusCode.BadRequest, negativeAmountResponse.StatusCode);
+ }
+
// Topup Invoice test
var i = await s.CreateInvoice(storeId, null, cryptoCode);
await s.GoToInvoiceCheckout(i);
### BTCPayServer/Controllers/GreenField/GreenfieldInvoiceController.cs
@@ -431,6 +431,12 @@ public async Task<IActionResult> RefundInvoice(
break;
case RefundVariant.CurrentRate:
+ if (rateResult.BidAsk is null)
+ {
+ ModelState.AddModelError(nameof(request.RefundVariant),
+ $"Impossible to fetch rate: {rateResult.EvaluatedRule}");
+ return this.CreateValidationError(ModelState);
+ }
createPullPayment.Currency = paymentPrompt.Currency;
createPullPayment.Amount = Math.Round(paidCurrency / rateResult.BidAsk.Bid, appliedDivisibility);
createPullPayment.AutoApproveClaims = true;
### BTCPayServer/Controllers/GreenField/GreenfieldLightningNodeApiController.cs
@@ -239,6 +239,10 @@ public virtual async Task<IActionResult> PayInvoice(string cryptoCode, PayLightn
{
ModelState.AddModelError(nameof(lightningInvoice.BOLT11), "The BOLT11 invoice was invalid.");
}
+ if (lightningInvoice.Amount is not null && lightningInvoice.Amount < LightMoney.Zero)
+ {
+ ModelState.AddModelError(nameof(lightningInvoice.Amount), "Amount must be greater than or equal to 0");
+ }
if (!ModelState.IsValid)
{
### BTCPayServer/Controllers/GreenField/GreenfieldStoresController.cs
@@ -358,11 +358,11 @@ private IActionResult Validate(StoreBaseData request)
{
ModelState.AddModelError(nameof(request.SupportUrl), "Support URL is not a valid url");
}
- if (request.InvoiceExpiration < TimeSpan.FromMinutes(1) && request.InvoiceExpiration > TimeSpan.FromMinutes(60 * 24 * 24))
+ if (request.InvoiceExpiration < TimeSpan.FromMinutes(1) || request.InvoiceExpiration > TimeSpan.FromMinutes(60 * 24 * 24))
ModelState.AddModelError(nameof(request.InvoiceExpiration), "InvoiceExpiration can only be between 1 and 34560 mins");
- if (request.DisplayExpirationTimer < TimeSpan.FromMinutes(1) && request.DisplayExpirationTimer > TimeSpan.FromMinutes(60 * 24 * 24))
+ if (request.DisplayExpirationTimer < TimeSpan.FromMinutes(1) || request.DisplayExpirationTimer > TimeSpan.FromMinutes(60 * 24 * 24))
ModelState.AddModelError(nameof(request.DisplayExpirationTimer), "DisplayExpirationTimer can only be between 1 and 34560 mins");
- if (request.MonitoringExpiration < TimeSpan.FromMinutes(10) && request.MonitoringExpiration > TimeSpan.FromMinutes(60 * 24 * 24))
+ if (request.MonitoringExpiration < TimeSpan.FromMinutes(10) || request.MonitoringExpiration > TimeSpan.FromMinutes(60 * 24 * 24))
ModelState.AddModelError(nameof(request.MonitoringExpiration), "MonitoringExpiration can only be between 10 and 34560 mins");
if (request.PaymentTolerance < 0 || request.PaymentTolerance > 100)
ModelState.AddModelError(nameof(request.PaymentTolerance), "PaymentTolerance can only be between 0 and 100 percent");
### BTCPayServer/Controllers/UILNURLController.cs
@@ -573,9 +573,11 @@ public async Task<IActionResult> GetLNUrlForStore(
if (store is null)
return NotFound();
- var blob = store.GetStoreBlob();
+ var blob = store.GetStoreBlob();
if (!blob.AnyoneCanInvoice)
return NotFound(StringLocalizer["'Anyone can invoice' is turned off"]);
+ if (amount is <= 0)
+ return BadRequest(StringLocalizer["Please provide an amount greater than 0"]);
var metadata = new InvoiceMetadata();
if (!string.IsNullOrEmpty(orderId))
{
### BTCPayServer/Services/WalletFileParsing/BSMSWalletFileParser.cs
@@ -29,12 +29,23 @@ public bool TryParse(BTCPayNetwork network, string data, [MaybeNullWhen(false)]
return false;
- descriptor = descriptor.Replace("/**", derivationPath);
- var testAddress = BitcoinAddress.Create(lines[3], network.NBitcoinNetwork);
+ try
+ {
+ descriptor = descriptor.Replace("/**", derivationPath);
+ var testAddress = BitcoinAddress.Create(lines[3], network.NBitcoinNetwork);
- derivationSchemeSettings = network.GetDerivationSchemeParser().ParseOD(descriptor);
- derivationSchemeSettings.Source = "BSMS";
- var line = derivationSchemeSettings.AccountDerivation.GetLineFor(DerivationFeature.Deposit).Derive(0);
- return testAddress.ScriptPubKey == line.ScriptPubKey;
+ derivationSchemeSettings = network.GetDerivationSchemeParser().ParseOD(descriptor);
+ derivationSchemeSettings.Source = "BSMS";
+ var line = derivationSchemeSettings.AccountDerivation.GetLineFor(DerivationFeature.Deposit).Derive(0);
+ if (testAddress.ScriptPubKey == line.ScriptPubKey)
+ return true;
+ derivationSchemeSettings = null;
+ return false;
+ }
+ catch
+ {
+ derivationSchemeSettings = null;
+ return false;
+ }
}
}
### BTCPayServer/Services/Wallets/WalletHistogramService.cs
@@ -61,7 +61,15 @@ public virtual async Task<HistogramData> GetHistogram(StoreData store, WalletId
series.Add((decimal)r.balance);
labels.Add((DateTimeOffset)r.date);
}
- series[^1] = balance;
+ if (series.Count is 0)
+ {
+ series.Add(balance);
+ labels.Add(to);
+ }
+ else
+ {
+ series[^1] = balance;
+ }
return new HistogramData
{
Series = series,Why this scored 49/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.