Run dotnet format (#3244)

This commit is contained in:
Nicolas Dorier
2021-12-31 16:59:02 +09:00
committed by GitHub
parent e2d0b7c5f7
commit 04b8eafacb
259 changed files with 1613 additions and 1491 deletions

View File

@@ -9,7 +9,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Operations;
namespace BTCPayServer.Abstractions.Contracts
{
public abstract class BaseDbContextFactory<T> where T: DbContext
public abstract class BaseDbContextFactory<T> where T : DbContext
{
private readonly IOptions<DatabaseOptions> _options;
private readonly string _schemaPrefix;

View File

@@ -14,7 +14,7 @@ namespace BTCPayServer.Abstractions.Extensions
public static void SetActivePage<T>(this ViewDataDictionary viewData, T activePage, string title = null, string activeId = null)
where T : IConvertible
{
SetActivePage(viewData, activePage.ToString(), activePage.GetType().Name,title, activeId );
SetActivePage(viewData, activePage.ToString(), activePage.GetType().Name, title, activeId);
}
public static void SetActivePage(this ViewDataDictionary viewData, string activePage, string category, string title = null, string activeId = null)
@@ -57,9 +57,9 @@ namespace BTCPayServer.Abstractions.Extensions
public static string IsActivePage<T>(this ViewDataDictionary viewData, T page, object id = null)
where T : IConvertible
{
return IsActivePage(viewData, page.ToString(), page.GetType().Name, id );
return IsActivePage(viewData, page.ToString(), page.GetType().Name, id);
}
public static string IsActivePage(this ViewDataDictionary viewData, string page,string category, object id = null)
public static string IsActivePage(this ViewDataDictionary viewData, string page, string category, object id = null)
{
if (!viewData.ContainsKey(ACTIVE_PAGE_KEY))
{
@@ -68,7 +68,7 @@ namespace BTCPayServer.Abstractions.Extensions
var activeId = viewData[ACTIVE_ID_KEY];
var activePage = viewData[ACTIVE_PAGE_KEY]?.ToString();
var activeCategory = viewData[ACTIVE_CATEGORY_KEY]?.ToString();
var categoryAndPageMatch = ( category == null || activeCategory.Equals(category, StringComparison.InvariantCultureIgnoreCase )) && page.Equals(activePage, StringComparison.InvariantCultureIgnoreCase);
var categoryAndPageMatch = (category == null || activeCategory.Equals(category, StringComparison.InvariantCultureIgnoreCase)) && page.Equals(activePage, StringComparison.InvariantCultureIgnoreCase);
var idMatch = id == null || activeId == null || id.Equals(activeId);
return categoryAndPageMatch && idMatch ? "active" : null;
}

View File

@@ -3,7 +3,7 @@ using BTCPayServer.Abstractions.Contracts;
namespace BTCPayServer.Abstractions.Services
{
public abstract class PluginAction<T>:IPluginHookAction
public abstract class PluginAction<T> : IPluginHookAction
{
public abstract string Hook { get; }
public Task Execute(object args)

View File

@@ -3,7 +3,7 @@ using BTCPayServer.Abstractions.Contracts;
namespace BTCPayServer.Abstractions.Services
{
public abstract class PluginHookFilter<T>:IPluginHookFilter
public abstract class PluginHookFilter<T> : IPluginHookFilter
{
public abstract string Hook { get; }

View File

@@ -2,7 +2,7 @@ using BTCPayServer.Abstractions.Contracts;
namespace BTCPayServer.Abstractions.Services
{
public class UIExtension: IUIExtension
public class UIExtension : IUIExtension
{
public UIExtension(string partial, string location)
{

View File

@@ -35,13 +35,15 @@ namespace BTCPayServer.Client
if (textSearch != null)
queryPayload.Add(nameof(textSearch), textSearch);
if (status != null)
queryPayload.Add(nameof(status), status.Select(s=> s.ToString().ToLower()).ToArray());
queryPayload.Add(nameof(status), status.Select(s => s.ToString().ToLower()).ToArray());
if(skip != null) {
if (skip != null)
{
queryPayload.Add(nameof(skip), skip);
}
if(take != null) {
if (take != null)
{
queryPayload.Add(nameof(take), take);
}

View File

@@ -41,7 +41,7 @@ namespace BTCPayServer.Client
{
var response = await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/users/me/notifications/{notificationId}",
method: HttpMethod.Put, bodyPayload: new UpdateNotification() {Seen = seen}), token);
method: HttpMethod.Put, bodyPayload: new UpdateNotification() { Seen = seen }), token);
return await HandleResponse<NotificationData>(response);
}

View File

@@ -63,7 +63,7 @@ namespace BTCPayServer.Client
var response = await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/preview",
bodyPayload: paymentMethod,
queryPayload: new Dictionary<string, object>() {{"offset", offset}, {"amount", amount}},
queryPayload: new Dictionary<string, object>() { { "offset", offset }, { "amount", amount } },
method: HttpMethod.Post), token);
return await HandleResponse<OnChainPaymentMethodPreviewResultData>(response);
}
@@ -74,7 +74,7 @@ namespace BTCPayServer.Client
{
var response = await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/preview",
queryPayload: new Dictionary<string, object>() {{"offset", offset}, {"amount", amount}},
queryPayload: new Dictionary<string, object>() { { "offset", offset }, { "amount", amount } },
method: HttpMethod.Get), token);
return await HandleResponse<OnChainPaymentMethodPreviewResultData>(response);
}

View File

@@ -25,7 +25,7 @@ namespace BTCPayServer.Client
Dictionary<string, object> queryParams = new Dictionary<string, object>();
if (blockTarget != null)
{
queryParams.Add("blockTarget",blockTarget);
queryParams.Add("blockTarget", blockTarget);
}
var response =
await _httpClient.SendAsync(
@@ -50,7 +50,7 @@ namespace BTCPayServer.Client
{
var response =
await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/address",method:HttpMethod.Delete), token);
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/address", method: HttpMethod.Delete), token);
await HandleResponse(response);
}

View File

@@ -16,7 +16,7 @@ namespace BTCPayServer.Client
var response =
await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/payment-requests",
new Dictionary<string, object>() {{nameof(includeArchived), includeArchived}}), token);
new Dictionary<string, object>() { { nameof(includeArchived), includeArchived } }), token);
return await HandleResponse<IEnumerable<PaymentRequestData>>(response);
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using NBitcoin;
using NBitcoin.JsonConverters;
using Newtonsoft.Json;

View File

@@ -29,7 +29,7 @@ namespace BTCPayServer.JsonConverters
throw new JsonSerializationException("Unexpected object type: " + objectType);
case JTokenType.Integer:
case JTokenType.String:
if (objectType == typeof(decimal) || objectType == typeof(decimal?) )
if (objectType == typeof(decimal) || objectType == typeof(decimal?))
return decimal.Parse(token.ToString(), CultureInfo.InvariantCulture);
if (objectType == typeof(double) || objectType == typeof(double?))
return double.Parse(token.ToString(), CultureInfo.InvariantCulture);

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

View File

@@ -18,7 +18,7 @@ namespace BTCPayServer.Client.Models
}
[JsonConverter(typeof(FeeRateJsonConverter))]
public FeeRate FeeRate { get; set; }
public bool ProceedWithPayjoin { get; set; }= true;
public bool ProceedWithPayjoin { get; set; } = true;
public bool ProceedWithBroadcast { get; set; } = true;
public bool NoChange { get; set; } = false;
[JsonProperty(ItemConverterType = typeof(OutpointJsonConverter))]

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Client.JsonConverters;
using BTCPayServer.Client.JsonConverters;
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

View File

@@ -1,4 +1,4 @@
namespace BTCPayServer.Client.Models
namespace BTCPayServer.Client.Models
{
public class GenericPaymentMethodData
{

View File

@@ -1,4 +1,4 @@
namespace BTCPayServer.Client.Models
namespace BTCPayServer.Client.Models
{
public class LNURLPayPaymentMethodBaseData
{

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Client.Models
namespace BTCPayServer.Client.Models
{
public class LNURLPayPaymentMethodData: LNURLPayPaymentMethodBaseData
public class LNURLPayPaymentMethodData : LNURLPayPaymentMethodBaseData
{
/// <summary>
/// Whether the payment method is enabled

View File

@@ -1,4 +1,4 @@
namespace BTCPayServer.Client.Models
namespace BTCPayServer.Client.Models
{
public class LightningNetworkPaymentMethodBaseData
{

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Client.Models
{
public class LightningNetworkPaymentMethodData: LightningNetworkPaymentMethodBaseData
public class LightningNetworkPaymentMethodData : LightningNetworkPaymentMethodBaseData
{
/// <summary>
/// Whether the payment method is enabled

View File

@@ -1,4 +1,4 @@
using NBitcoin;
using NBitcoin;
using Newtonsoft.Json;
namespace BTCPayServer.Client.Models

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Client.JsonConverters;
using BTCPayServer.Client.JsonConverters;
using NBitcoin;
using Newtonsoft.Json;

View File

@@ -36,7 +36,7 @@ namespace BTCPayServer.Client.Models
public virtual bool Available { get; set; }
}
public class ServerInfoSyncStatusData: SyncStatus
public class ServerInfoSyncStatusData : SyncStatus
{
public int ChainHeight { get; set; }
public int? SyncHeight { get; set; }

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Client.Models
{
public class UpdateLightningNetworkPaymentMethodRequest: LightningNetworkPaymentMethodBaseData
public class UpdateLightningNetworkPaymentMethodRequest : LightningNetworkPaymentMethodBaseData
{
/// <summary>
/// Whether the payment method is enabled

View File

@@ -1,4 +1,4 @@
using NBXplorer;
using NBXplorer;
namespace BTCPayServer.Common
{

View File

@@ -37,7 +37,7 @@ namespace BTCPayServer.Data
builder.Entity<PayoutData>()
.HasIndex(o => o.State);
builder.Entity<PayoutData>()
.HasIndex(x => new { DestinationId = x.Destination, x.State});
.HasIndex(x => new { DestinationId = x.Destination, x.State });
}
// utility methods

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Data;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Data;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Data;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

View File

@@ -1,7 +1,7 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace BTCPayServer.Migrations
{

View File

@@ -1,4 +1,4 @@
using System;
using System;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
@@ -21,8 +21,8 @@ namespace BTCPayServer.PluginPacker
var name = args[1];
var outputDir = args[2];
var outputFile = Path.Combine(outputDir, name);
var rootDLLPath = Path.Combine(directory, name +".dll");
if (!File.Exists(rootDLLPath) )
var rootDLLPath = Path.Combine(directory, name + ".dll");
if (!File.Exists(rootDLLPath))
{
throw new Exception($"{rootDLLPath} could not be found");
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

View File

@@ -19,7 +19,7 @@ namespace BTCPayServer.Plugins.Test.Services
{
await using var context = _testPluginDbContextFactory.CreateContext();
await context.TestPluginRecords.AddAsync(new TestPluginData() {Timestamp = DateTimeOffset.UtcNow});
await context.TestPluginRecords.AddAsync(new TestPluginData() { Timestamp = DateTimeOffset.UtcNow });
await context.SaveChangesAsync();
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Abstractions.Services;
@@ -9,7 +9,7 @@ using Microsoft.Extensions.DependencyInjection;
namespace BTCPayServer.Plugins.Test
{
public class TestPlugin: BaseBTCPayServerPlugin
public class TestPlugin : BaseBTCPayServerPlugin
{
public override string Identifier { get; } = "BTCPayServer.Plugins.Test";
public override string Name { get; } = "Test Plugin!";

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

View File

@@ -23,7 +23,7 @@ namespace BTCPayServer.Services.Rates
var data = jobj.ContainsKey("data") ? jobj["data"] : null;
if (jobj["success"]?.Value<int>() != 1)
{
var errorCode = data is null? "Unknown": data["code"].Value<string>();
var errorCode = data is null ? "Unknown" : data["code"].Value<string>();
throw new Exception(
$"BitBank Rates API Error: {errorCode}. See https://github.com/bitbankinc/bitbank-api-docs/blob/master/errors.md for more details.");
}

View File

@@ -28,7 +28,8 @@ namespace BTCPayServer.Tests
public static void AssertNoError(this IWebDriver driver)
{
if (!driver.PageSource.Contains("alert-danger")) return;
if (!driver.PageSource.Contains("alert-danger"))
return;
foreach (var dangerAlert in driver.FindElements(By.ClassName("alert-danger")))
Assert.False(dangerAlert.Displayed, $"No alert should be displayed, but found this on {driver.Url}: {dangerAlert.Text}");
}
@@ -50,7 +51,7 @@ namespace BTCPayServer.Tests
// Sometimes, selenium is flaky...
public static IWebElement FindElementUntilNotStaled(this IWebDriver driver, By by, Action<IWebElement> act)
{
retry:
retry:
try
{
var el = driver.FindElement(by);
@@ -91,8 +92,8 @@ namespace BTCPayServer.Tests
public static void UntilJsIsReady(this WebDriverWait wait)
{
wait.Until(d=>((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
wait.Until(d=>((IJavaScriptExecutor)d).ExecuteScript("return typeof(jQuery) === 'undefined' || jQuery.active === 0").Equals(true));
wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return typeof(jQuery) === 'undefined' || jQuery.active === 0").Equals(true));
}
// Open collapse via JS, because if we click the link it triggers the toggle animation.
@@ -135,7 +136,7 @@ namespace BTCPayServer.Tests
wait.UntilJsIsReady();
int retriesLeft = 4;
retry:
retry:
try
{
var el = driver.FindElement(selector);

View File

@@ -1177,27 +1177,27 @@ namespace BTCPayServer.Tests
//list Existing OrderId
var invoicesExistingOrderId =
await viewOnly.GetInvoices(user.StoreId, orderId: new []{newInvoice.Metadata["orderId"].ToString()});
await viewOnly.GetInvoices(user.StoreId, orderId: new[] { newInvoice.Metadata["orderId"].ToString() });
Assert.NotNull(invoicesExistingOrderId);
Assert.Single(invoicesFiltered);
Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id);
//list NonExisting OrderId
var invoicesNonExistingOrderId =
await viewOnly.GetInvoices(user.StoreId, orderId: new []{"NonExistingOrderId"});
await viewOnly.GetInvoices(user.StoreId, orderId: new[] { "NonExistingOrderId" });
Assert.NotNull(invoicesNonExistingOrderId);
Assert.Empty(invoicesNonExistingOrderId);
//list Existing Status
var invoicesExistingStatus =
await viewOnly.GetInvoices(user.StoreId, status: new []{newInvoice.Status});
await viewOnly.GetInvoices(user.StoreId, status: new[] { newInvoice.Status });
Assert.NotNull(invoicesExistingStatus);
Assert.Single(invoicesExistingStatus);
Assert.Equal(newInvoice.Id, invoicesExistingStatus.First().Id);
//list NonExisting Status
var invoicesNonExistingStatus = await viewOnly.GetInvoices(user.StoreId,
status: new []{BTCPayServer.Client.Models.InvoiceStatus.Invalid});
status: new[] { BTCPayServer.Client.Models.InvoiceStatus.Invalid });
Assert.NotNull(invoicesNonExistingStatus);
Assert.Empty(invoicesNonExistingStatus);
@@ -1623,7 +1623,7 @@ namespace BTCPayServer.Tests
await viewOnlyClient.GenerateOnChainWallet(store.Id, "BTC", new GenerateOnChainWalletRequest() { });
});
await AssertValidationError(new []{"SavePrivateKeys", "ImportKeysToRPC"}, async () =>
await AssertValidationError(new[] { "SavePrivateKeys", "ImportKeysToRPC" }, async () =>
{
await client2.GenerateOnChainWallet(user2.StoreId, "BTC", new GenerateOnChainWalletRequest()
{
@@ -1638,7 +1638,7 @@ namespace BTCPayServer.Tests
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
var generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() {ExistingMnemonic = allMnemonic,});
new GenerateOnChainWalletRequest() { ExistingMnemonic = allMnemonic, });
Assert.Equal(generateResponse.Mnemonic.ToString(), allMnemonic.ToString());
Assert.Equal(generateResponse.DerivationScheme, xpub);
@@ -1646,18 +1646,18 @@ namespace BTCPayServer.Tests
await AssertAPIError("already-configured", async () =>
{
await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() {ExistingMnemonic = allMnemonic,});
new GenerateOnChainWalletRequest() { ExistingMnemonic = allMnemonic, });
});
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() {});
new GenerateOnChainWalletRequest() { });
Assert.NotEqual(generateResponse.Mnemonic.ToString(), allMnemonic.ToString());
Assert.Equal(generateResponse.Mnemonic.DeriveExtKey().Derive(KeyPath.Parse("m/84'/1'/0'")).Neuter().ToString(Network.RegTest), generateResponse.DerivationScheme);
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() { ExistingMnemonic = allMnemonic, AccountNumber = 1});
new GenerateOnChainWalletRequest() { ExistingMnemonic = allMnemonic, AccountNumber = 1 });
Assert.Equal(generateResponse.Mnemonic.ToString(), allMnemonic.ToString());
@@ -1666,10 +1666,10 @@ namespace BTCPayServer.Tests
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() { WordList = Wordlist.Japanese, WordCount = WordCount.TwentyFour});
new GenerateOnChainWalletRequest() { WordList = Wordlist.Japanese, WordCount = WordCount.TwentyFour });
Assert.Equal(24,generateResponse.Mnemonic.Words.Length);
Assert.Equal(Wordlist.Japanese,generateResponse.Mnemonic.WordList);
Assert.Equal(24, generateResponse.Mnemonic.Words.Length);
Assert.Equal(Wordlist.Japanese, generateResponse.Mnemonic.WordList);
}
@@ -2070,14 +2070,14 @@ namespace BTCPayServer.Tests
methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id);
Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out var item));
var lightningNetworkPaymentMethodBaseData =Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
var lightningNetworkPaymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
Assert.Equal("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString);
methods = await adminClient.GetStorePaymentMethods(store.Id);
Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out item));
lightningNetworkPaymentMethodBaseData =Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
lightningNetworkPaymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
Assert.NotEqual("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString);

View File

@@ -4,6 +4,7 @@ using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client.Models;
using BTCPayServer.Controllers;
using BTCPayServer.Data;
@@ -16,11 +17,10 @@ using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Tests.Logging;
using BTCPayServer.Views.Stores;
using BTCPayServer.Views.Wallets;
using Microsoft.AspNetCore.Http;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Views.Stores;
using NBitcoin.Payment;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
@@ -179,7 +179,7 @@ namespace BTCPayServer.Tests
var cashCow = tester.ExplorerNode;
cashCow.Generate(2); // get some money in case
var unsupportedFormats = new[] {ScriptPubKeyType.Legacy};
var unsupportedFormats = new[] { ScriptPubKeyType.Legacy };
foreach (ScriptPubKeyType senderAddressType in Enum.GetValues(typeof(ScriptPubKeyType)))
@@ -287,7 +287,7 @@ namespace BTCPayServer.Tests
var invoiceRepository = s.Server.PayTester.GetService<InvoiceRepository>();
s.RegisterNewUser(true);
foreach (var format in new []{ScriptPubKeyType.Segwit, ScriptPubKeyType.SegwitP2SH})
foreach (var format in new[] { ScriptPubKeyType.Segwit, ScriptPubKeyType.SegwitP2SH })
{
var cryptoCode = "BTC";
var receiver = s.CreateNewStore();
@@ -867,7 +867,7 @@ retry:
//give the cow some cash
await cashCow.GenerateAsync(1);
//let's get some more utxos first
foreach (var m in new []
foreach (var m in new[]
{
Money.Coins(0.011m),
Money.Coins(0.012m),

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Lightning;
using BTCPayServer.Lightning.CLightning;
using BTCPayServer.Views.Manage;
@@ -12,11 +13,10 @@ using BTCPayServer.Views.Stores;
using BTCPayServer.Views.Wallets;
using Microsoft.Extensions.Configuration;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Xunit;
using OpenQA.Selenium.Support.UI;
using Xunit;
namespace BTCPayServer.Tests
{
@@ -90,7 +90,7 @@ namespace BTCPayServer.Tests
public Uri ServerUri;
internal IWebElement FindAlertMessage(StatusMessageModel.StatusSeverity severity = StatusMessageModel.StatusSeverity.Success)
{
return FindAlertMessage(new[] {severity});
return FindAlertMessage(new[] { severity });
}
internal IWebElement FindAlertMessage(params StatusMessageModel.StatusSeverity[] severity)
{
@@ -240,7 +240,7 @@ namespace BTCPayServer.Tests
LightningConnectionType.Charge =>
$"type=charge;server={Server.MerchantCharge.Client.Uri.AbsoluteUri};allowinsecure=true",
LightningConnectionType.CLightning =>
$"type=clightning;server={((CLightningClient) Server.MerchantLightningD).Address.AbsoluteUri}",
$"type=clightning;server={((CLightningClient)Server.MerchantLightningD).Address.AbsoluteUri}",
LightningConnectionType.LndREST =>
$"type=lnd-rest;server={Server.MerchantLnd.Swagger.BaseUrl};allowinsecure=true",
_ => null

View File

@@ -1410,7 +1410,7 @@ namespace BTCPayServer.Tests
//even though we set DisableBolt11PaymentMethod to true, logic when saving it turns it back off as otherwise no lightning option is available at all!
Assert.False(s.Driver.FindElement(By.Id("DisableBolt11PaymentMethod")).Selected);
// Invoice creation should fail, because it is a standard invoice with amount, but DisableBolt11PaymentMethod = true and LNURLStandardInvoiceEnabled = false
s.CreateInvoice(storeId, 0.0000001m, cryptoCode,"",null, expectedSeverity: StatusMessageModel.StatusSeverity.Success);
s.CreateInvoice(storeId, 0.0000001m, cryptoCode, "", null, expectedSeverity: StatusMessageModel.StatusSeverity.Success);
i = s.CreateInvoice(storeId, null, cryptoCode);
s.GoToInvoiceCheckout(i);
@@ -1437,7 +1437,7 @@ namespace BTCPayServer.Tests
// Check that pull payment has lightning option
s.GoToStore(s.StoreId, StoreNavPages.PullPayments);
s.Driver.FindElement(By.Id("NewPullPayment")).Click();
Assert.Equal(new PaymentMethodId(cryptoCode, PaymentTypes.LightningLike),PaymentMethodId.Parse(Assert.Single(s.Driver.FindElements(By.CssSelector("input[name='PaymentMethods']"))).GetAttribute("value")));
Assert.Equal(new PaymentMethodId(cryptoCode, PaymentTypes.LightningLike), PaymentMethodId.Parse(Assert.Single(s.Driver.FindElements(By.CssSelector("input[name='PaymentMethods']"))).GetAttribute("value")));
s.Driver.FindElement(By.Id("Name")).SendKeys("PP1");
s.Driver.FindElement(By.Id("Amount")).Clear();
s.Driver.FindElement(By.Id("Amount")).SendKeys("0.0000001");
@@ -1534,7 +1534,7 @@ namespace BTCPayServer.Tests
var lnurl = new Uri(LNURL.LNURL.ExtractUriFromInternetIdentifier(value).ToString()
.Replace("https", "http"));
var request =(LNURL.LNURLPayRequest) await LNURL.LNURL.FetchInformation(lnurl, new HttpClient());
var request = (LNURL.LNURLPayRequest)await LNURL.LNURL.FetchInformation(lnurl, new HttpClient());
switch (value)
{

View File

@@ -5,6 +5,7 @@ using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Controllers;
@@ -14,6 +15,7 @@ using BTCPayServer.Lightning;
using BTCPayServer.Lightning.CLightning;
using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Payments.PayJoin.Sender;
using BTCPayServer.Services;
using BTCPayServer.Services.Stores;
@@ -23,8 +25,6 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Operations;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Payments.Lightning;
using NBitcoin.Payment;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
@@ -470,7 +470,7 @@ namespace BTCPayServer.Tests
public TEvent AssertHasWebhookEvent<TEvent>(WebhookEventType eventType, Action<TEvent> assert) where TEvent : class
{
int retry = 0;
retry:
retry:
foreach (var evt in WebhookEvents)
{
if (evt.Type == eventType)

View File

@@ -371,7 +371,7 @@ namespace BTCPayServer.Tests
{
await tester.ExplorerNode.SendToAddressAsync(
BitcoinAddress.Create(invoice.BitcoinAddress, Network.RegTest), Money.Coins(0.00005m));
}, e => e.InvoiceId == invoice.Id && e.PaymentMethodId.PaymentType == LightningPaymentType.Instance );
}, e => e.InvoiceId == invoice.Id && e.PaymentMethodId.PaymentType == LightningPaymentType.Instance);
await tester.ExplorerNode.GenerateAsync(1);
Invoice newInvoice = null;
await TestUtils.EventuallyAsync(async () =>
@@ -1663,7 +1663,7 @@ namespace BTCPayServer.Tests
Assert.True($"bitcoin:{paymentMethodSecond.BtcAddress.ToUpperInvariant()}" == split);
// Fallback lightning invoice should be uppercase inside the QR code.
var lightningFallback = paymentMethodSecond.InvoiceBitcoinUrlQR.Split(new [] { "&lightning=" }, StringSplitOptions.None)[1];
var lightningFallback = paymentMethodSecond.InvoiceBitcoinUrlQR.Split(new[] { "&lightning=" }, StringSplitOptions.None)[1];
Assert.True(lightningFallback.ToUpperInvariant() == lightningFallback);
}
}
@@ -2312,7 +2312,7 @@ namespace BTCPayServer.Tests
c =>
{
Assert.False(c.AfterExpiration);
Assert.Equal(new PaymentMethodId("BTC", PaymentTypes.BTCLike).ToStringNormalized(),c.PaymentMethod);
Assert.Equal(new PaymentMethodId("BTC", PaymentTypes.BTCLike).ToStringNormalized(), c.PaymentMethod);
Assert.NotNull(c.Payment);
Assert.Equal(invoice.BitcoinAddress, c.Payment.Destination);
Assert.StartsWith(txId.ToString(), c.Payment.Id);
@@ -2322,7 +2322,7 @@ namespace BTCPayServer.Tests
c =>
{
Assert.False(c.AfterExpiration);
Assert.Equal(new PaymentMethodId("BTC", PaymentTypes.BTCLike).ToStringNormalized(),c.PaymentMethod);
Assert.Equal(new PaymentMethodId("BTC", PaymentTypes.BTCLike).ToStringNormalized(), c.PaymentMethod);
Assert.NotNull(c.Payment);
Assert.Equal(invoice.BitcoinAddress, c.Payment.Destination);
Assert.StartsWith(txId.ToString(), c.Payment.Id);
@@ -2701,11 +2701,11 @@ namespace BTCPayServer.Tests
Port = 1234,
Server = "admin.com",
});
Assert.Equal("admin@admin.com",(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Equal("admin@admin.com",(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
Assert.Equal("admin@admin.com", (await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Equal("admin@admin.com", (await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = true });
Assert.Equal("admin@admin.com",(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Equal("admin@admin.com", (await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Null(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings());
Assert.IsType<RedirectToActionResult>(await acc.GetController<StoresController>().Emails(acc.StoreId, new EmailsViewModel(new EmailSettings()
@@ -2717,7 +2717,7 @@ namespace BTCPayServer.Tests
Server = "store.com"
}), ""));
Assert.Equal("store@store.com",(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
Assert.Equal("store@store.com", (await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
}
}

View File

@@ -1,8 +1,8 @@
using System;
using BTCPayServer.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using BTCPayServer.Configuration;
using BTCPayServer.Logging;
using BTCPayServer.SSH;
using Microsoft.Extensions.Configuration;
@@ -72,7 +72,7 @@ namespace BTCPayServer.Configuration
TorrcFile = conf.GetOrDefault<string>("torrcfile", null);
TorServices = conf.GetOrDefault<string>("torservices", null)
?.Split(new[] {';', ','}, StringSplitOptions.RemoveEmptyEntries);
?.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (!string.IsNullOrEmpty(TorrcFile) && TorServices != null)
throw new ConfigException($"torrcfile or torservices should be provided, but not both");
@@ -145,7 +145,7 @@ namespace BTCPayServer.Configuration
DisableRegistration = conf.GetOrDefault<bool>("disable-registration", true);
PluginRemote = conf.GetOrDefault("plugin-remote", "btcpayserver/btcpayserver-plugins");
RecommendedPlugins = conf.GetOrDefault("recommended-plugins", "").ToLowerInvariant().Split('\r','\n','\t',' ').Where(s => !string.IsNullOrEmpty(s)).Distinct().ToArray();
RecommendedPlugins = conf.GetOrDefault("recommended-plugins", "").ToLowerInvariant().Split('\r', '\n', '\t', ' ').Where(s => !string.IsNullOrEmpty(s)).Distinct().ToArray();
CheatMode = conf.GetOrDefault("cheatmode", false);
if (CheatMode && this.NetworkType == ChainName.Mainnet)
throw new ConfigException($"cheatmode can't be used on mainnet");

View File

@@ -171,7 +171,7 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = twoFModel,
LoginWithFido2ViewModel = fido2Devices? await BuildFido2ViewModel(model.RememberMe, user): null,
LoginWithFido2ViewModel = fido2Devices ? await BuildFido2ViewModel(model.RememberMe, user) : null,
});
}
else
@@ -464,8 +464,13 @@ namespace BTCPayServer.Controllers
return RedirectToAction(nameof(HomeController.Index), "Home");
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, RequiresEmailConfirmation = policies.RequiresConfirmedEmail,
Created = DateTimeOffset.UtcNow };
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
RequiresEmailConfirmation = policies.RequiresConfirmedEmail,
Created = DateTimeOffset.UtcNow
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
@@ -544,7 +549,7 @@ namespace BTCPayServer.Controllers
Severity = StatusMessageModel.StatusSeverity.Info,
Message = "Your email has been confirmed but you still need to set your password."
});
return RedirectToAction("SetPassword", new { email = user.Email, code= await _userManager.GeneratePasswordResetTokenAsync(user)});
return RedirectToAction("SetPassword", new { email = user.Email, code = await _userManager.GeneratePasswordResetTokenAsync(user) });
}
if (result.Succeeded)
@@ -554,7 +559,7 @@ namespace BTCPayServer.Controllers
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Your email has been confirmed."
});
return RedirectToAction("Login", new {email = user.Email});
return RedirectToAction("Login", new { email = user.Email });
}
return View("Error");
@@ -583,7 +588,8 @@ namespace BTCPayServer.Controllers
}
_eventAggregator.Publish(new UserPasswordResetRequestedEvent()
{
User = user, RequestUri = Request.GetAbsoluteRootUri()
User = user,
RequestUri = Request.GetAbsoluteRootUri()
});
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
@@ -614,7 +620,7 @@ namespace BTCPayServer.Controllers
email = user?.Email;
}
var model = new SetPasswordViewModel {Code = code, Email = email, EmailSetInternally = !string.IsNullOrEmpty(email)};
var model = new SetPasswordViewModel { Code = code, Email = email, EmailSetInternally = !string.IsNullOrEmpty(email) };
return View(model);
}
@@ -639,7 +645,8 @@ namespace BTCPayServer.Controllers
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Success, Message = "Password successfully set."
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Password successfully set."
});
return RedirectToAction(nameof(Login));
}

View File

@@ -1,9 +1,9 @@
using System;
using BTCPayServer.Data;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Models;
using BTCPayServer.Models.AppViewModels;
using BTCPayServer.Services.Apps;

View File

@@ -47,10 +47,10 @@ namespace BTCPayServer.Controllers
switch ((await _AppService.GetApp(appId, null)).AppType)
{
case nameof(AppType.Crowdfund):
return RedirectToAction("ViewCrowdfund", new {appId});
return RedirectToAction("ViewCrowdfund", new { appId });
case nameof(AppType.PointOfSale):
return RedirectToAction("ViewPointOfSale", new {appId});
return RedirectToAction("ViewPointOfSale", new { appId });
}
return NotFound();

View File

@@ -12,7 +12,7 @@ namespace BTCPayServer.Controllers.GreenField
{
private readonly NBXplorerDashboard _dashBoard;
public HealthController(NBXplorerDashboard dashBoard )
public HealthController(NBXplorerDashboard dashBoard)
{
_dashBoard = dashBoard;
}

View File

@@ -82,7 +82,7 @@ namespace BTCPayServer.Controllers.GreenField
{
Skip = skip,
Take = take,
StoreId = new[] {store.Id},
StoreId = new[] { store.Id },
IncludeArchived = includeArchived,
StartDate = startDate,
EndDate = endDate,

View File

@@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers.GreenField
_greenfieldPullPaymentController,
_homeController,
_storePaymentMethodsController,
new HttpContextAccessor() {HttpContext = context}
new HttpContextAccessor() { HttpContext = context }
);
}
}
@@ -471,8 +471,8 @@ namespace BTCPayServer.Controllers.GreenField
switch (result)
{
case JsonResult jsonResult:
return (T) jsonResult.Value;
case OkObjectResult {Value: T res}:
return (T)jsonResult.Value;
case OkObjectResult { Value: T res }:
return res;
default:
return default;
@@ -483,9 +483,9 @@ namespace BTCPayServer.Controllers.GreenField
{
switch (result)
{
case UnprocessableEntityObjectResult {Value: List<GreenfieldValidationError> validationErrors}:
case UnprocessableEntityObjectResult { Value: List<GreenfieldValidationError> validationErrors }:
throw new GreenFieldValidationException(validationErrors.ToArray());
case BadRequestObjectResult {Value: GreenfieldAPIError error}:
case BadRequestObjectResult { Value: GreenfieldAPIError error }:
throw new GreenFieldAPIException(400, error);
case NotFoundResult _:
throw new GreenFieldAPIException(404, new GreenfieldAPIError("not-found", ""));
@@ -632,7 +632,7 @@ namespace BTCPayServer.Controllers.GreenField
{
return GetFromActionResult<NotificationData>(
await _notificationsController.UpdateNotification(notificationId,
new UpdateNotification() {Seen = seen}));
new UpdateNotification() { Seen = seen }));
}
public override async Task RemoveNotification(string notificationId, CancellationToken token = default)
@@ -832,7 +832,7 @@ namespace BTCPayServer.Controllers.GreenField
return GetFromActionResult<IEnumerable<InvoiceData>>(
await _greenFieldInvoiceController.GetInvoices(storeId, orderId,
status?.Select(invoiceStatus => invoiceStatus.ToString())?.ToArray(), startDate,
endDate, textSearch, includeArchived,skip,take));
endDate, textSearch, includeArchived, skip, take));
}
public override async Task<InvoiceData> GetInvoice(string storeId, string invoiceId,

View File

@@ -37,7 +37,10 @@ namespace BTCPayServer.Controllers.GreenField
{
var items = await _notificationManager.GetNotifications(new NotificationsQuery()
{
Seen = seen, UserId = _userManager.GetUserId(User), Skip = skip, Take = take
Seen = seen,
UserId = _userManager.GetUserId(User),
Skip = skip,
Take = take
});
return Ok(items.Items.Select(ToModel));
@@ -50,7 +53,8 @@ namespace BTCPayServer.Controllers.GreenField
{
var items = await _notificationManager.GetNotifications(new NotificationsQuery()
{
Ids = new[] {id}, UserId = _userManager.GetUserId(User)
Ids = new[] { id },
UserId = _userManager.GetUserId(User)
});
if (items.Count == 0)
@@ -67,7 +71,7 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> UpdateNotification(string id, UpdateNotification request)
{
var items = await _notificationManager.ToggleSeen(
new NotificationsQuery() {Ids = new[] {id}, UserId = _userManager.GetUserId(User)}, request.Seen);
new NotificationsQuery() { Ids = new[] { id }, UserId = _userManager.GetUserId(User) }, request.Seen);
if (items.Count == 0)
{
@@ -84,7 +88,8 @@ namespace BTCPayServer.Controllers.GreenField
{
await _notificationManager.Remove(new NotificationsQuery()
{
Ids = new[] {id}, UserId = _userManager.GetUserId(User)
Ids = new[] { id },
UserId = _userManager.GetUserId(User)
});
return Ok();

View File

@@ -181,7 +181,7 @@ namespace BTCPayServer.Controllers.GreenField
var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, true);
if (pp is null)
return PullPaymentNotFound();
var payouts = pp.Payouts .Where(p => p.State != PayoutState.Cancelled || includeCancelled).ToList();
var payouts = pp.Payouts.Where(p => p.State != PayoutState.Cancelled || includeCancelled).ToList();
var cd = _currencyNameTable.GetCurrencyData(pp.GetBlob().Currency, false);
return base.Ok(payouts
.Select(p => ToModel(p, cd)).ToList());
@@ -198,7 +198,7 @@ namespace BTCPayServer.Controllers.GreenField
if (pp is null)
return PullPaymentNotFound();
var payout = pp.Payouts.FirstOrDefault(p => p.Id == payoutId);
if(payout is null )
if (payout is null)
return PayoutNotFound();
var cd = _currencyNameTable.GetCurrencyData(payout.PullPaymentData.GetBlob().Currency, false);
return base.Ok(ToModel(payout, cd));
@@ -248,7 +248,7 @@ namespace BTCPayServer.Controllers.GreenField
var destination = await payoutHandler.ParseClaimDestination(paymentMethodId, request!.Destination, true);
if (destination.destination is null)
{
ModelState.AddModelError(nameof(request.Destination), destination.error??"The destination is invalid for the payment specified");
ModelState.AddModelError(nameof(request.Destination), destination.error ?? "The destination is invalid for the payment specified");
return this.CreateValidationError(ModelState);
}

View File

@@ -23,7 +23,7 @@ namespace BTCPayServer.Controllers.GreenField
public GreenFieldServerInfoController(
BTCPayServerEnvironment env,
PaymentMethodHandlerDictionary paymentMethodHandlerDictionary,
IEnumerable<ISyncSummaryProvider>summaryProviders)
IEnumerable<ISyncSummaryProvider> summaryProviders)
{
_env = env;
_paymentMethodHandlerDictionary = paymentMethodHandlerDictionary;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Client;

View File

@@ -85,7 +85,8 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> ShowOnChainWalletOverview(string storeId, string cryptoCode)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var wallet = _btcPayWalletProvider.GetWallet(network);
var balance = await wallet.GetBalance(derivationScheme.AccountDerivation);
@@ -94,8 +95,8 @@ namespace BTCPayServer.Controllers.GreenField
{
Label = derivationScheme.ToPrettyString(),
Balance = balance.Total.GetValue(network),
UnconfirmedBalance= balance.Unconfirmed.GetValue(network),
ConfirmedBalance= balance.Confirmed.GetValue(network),
UnconfirmedBalance = balance.Unconfirmed.GetValue(network),
ConfirmedBalance = balance.Confirmed.GetValue(network),
});
}
@@ -104,9 +105,10 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> GetOnChainFeeRate(string storeId, string cryptoCode, int? blockTarget = null)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var feeRateTarget = blockTarget?? Store.GetStoreBlob().RecommendedFeeBlockTarget;
var feeRateTarget = blockTarget ?? Store.GetStoreBlob().RecommendedFeeBlockTarget;
return Ok(new OnChainWalletFeeRateData()
{
FeeRate = await _feeProviderFactory.CreateFeeProvider(network)
@@ -119,7 +121,8 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> GetOnChainWalletReceiveAddress(string storeId, string cryptoCode, bool forceGenerate = false)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var kpi = await _walletReceiveService.GetOrGenerate(new WalletId(storeId, cryptoCode), forceGenerate);
if (kpi is null)
@@ -146,7 +149,8 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> UnReserveOnChainWalletReceiveAddress(string storeId, string cryptoCode)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var addr = await _walletReceiveService.UnReserveAddress(new WalletId(storeId, cryptoCode));
if (addr is null)
@@ -168,7 +172,8 @@ namespace BTCPayServer.Controllers.GreenField
)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var wallet = _btcPayWalletProvider.GetWallet(network);
var walletId = new WalletId(storeId, cryptoCode);
@@ -186,7 +191,7 @@ namespace BTCPayServer.Controllers.GreenField
filteredFlatList.AddRange(txs.UnconfirmedTransactions.Transactions);
}
if (statusFilter is null || !statusFilter.Any() ||statusFilter.Contains(TransactionStatus.Replaced))
if (statusFilter is null || !statusFilter.Any() || statusFilter.Contains(TransactionStatus.Replaced))
{
filteredFlatList.AddRange(txs.ReplacedTransactions.Transactions);
}
@@ -205,7 +210,8 @@ namespace BTCPayServer.Controllers.GreenField
string transactionId)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var wallet = _btcPayWalletProvider.GetWallet(network);
var tx = await wallet.FetchTransaction(derivationScheme.AccountDerivation, uint256.Parse(transactionId));
@@ -216,7 +222,7 @@ namespace BTCPayServer.Controllers.GreenField
var walletId = new WalletId(storeId, cryptoCode);
var walletTransactionsInfoAsync =
(await _walletRepository.GetWalletTransactionsInfo(walletId, new[] {transactionId})).Values
(await _walletRepository.GetWalletTransactionsInfo(walletId, new[] { transactionId })).Values
.FirstOrDefault();
return Ok(ToModel(walletTransactionsInfoAsync, tx, wallet));
@@ -227,7 +233,8 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> GetOnChainWalletUTXOs(string storeId, string cryptoCode)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
var wallet = _btcPayWalletProvider.GetWallet(network);
@@ -260,7 +267,8 @@ namespace BTCPayServer.Controllers.GreenField
[FromBody] CreateOnChainTransactionRequest request)
{
if (IsInvalidWalletRequest(cryptoCode, out var network,
out var derivationScheme, out var actionResult)) return actionResult;
out var derivationScheme, out var actionResult))
return actionResult;
if (network.ReadonlyWallet)
{
return this.CreateAPIError("not-available",

View File

@@ -36,7 +36,8 @@ namespace BTCPayServer.Controllers.GreenField
var storeBlob = Store.GetStoreBlob();
var excludedPaymentMethods = storeBlob.GetExcludedPaymentMethods();
var canModifyStore = (await _authorizationService.AuthorizeAsync(User, null,
new PolicyRequirement(Policies.CanModifyStoreSettings))).Succeeded;;
new PolicyRequirement(Policies.CanModifyStoreSettings))).Succeeded;
;
return Ok(Store.GetSupportedPaymentMethods(_btcPayNetworkProvider)
.Where(method =>
enabled is null || (enabled is false && excludedPaymentMethods.Match(method.PaymentId)))

View File

@@ -122,7 +122,7 @@ namespace BTCPayServer.Controllers.GreenField
{
Everything = aed.Everything,
SpecificEvents = aed.SpecificEvents
}:
} :
new AuthorizedWebhookEvents() { Everything = true },
AutomaticRedelivery = create.AutomaticRedelivery,
};

View File

@@ -10,17 +10,17 @@ using BTCPayServer.Configuration;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.HostedServices;
using BTCPayServer.Logging;
using BTCPayServer.Security;
using BTCPayServer.Security.GreenField;
using BTCPayServer.Services;
using BTCPayServer.Storage.Services;
using BTCPayServer.Services.Stores;
using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NicolasDorier.RateLimits;
using BTCPayServer.Logging;
namespace BTCPayServer.Controllers.GreenField
{
@@ -169,7 +169,8 @@ namespace BTCPayServer.Controllers.GreenField
if (!anyAdmin)
{
var settings = await _settingsRepository.GetSettingAsync<ThemeSettings>();
if (settings != null) {
if (settings != null)
{
settings.FirstRun = false;
await _settingsRepository.UpdateSetting(settings);
}
@@ -234,7 +235,8 @@ namespace BTCPayServer.Controllers.GreenField
private async Task<bool> IsUserTheOnlyOneAdmin(ApplicationUser user)
{
var isUserAdmin = await _userService.IsAdminUser(user);
if (!isUserAdmin) {
if (!isUserAdmin)
{
return false;
}

View File

@@ -4,9 +4,9 @@ using System.Threading.Tasks;
using BTCPayServer.Data;
using BTCPayServer.Filters;
using BTCPayServer.Payments;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using BTCPayServer.Services;
namespace BTCPayServer.Controllers
{
@@ -78,7 +78,7 @@ namespace BTCPayServer.Controllers
cheater.CashCow.GenerateToAddress(request.BlockCount, blockRewardBitcoinAddress);
return Ok(new
{
SuccessMessage = "Mined "+request.BlockCount+" blocks"
SuccessMessage = "Mined " + request.BlockCount + " blocks"
});
}
return BadRequest(new

View File

@@ -158,7 +158,7 @@ namespace BTCPayServer.Controllers
[HttpGet("invoices/{invoiceId}/refund")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Refund([FromServices]IEnumerable<IPayoutHandler> payoutHandlers, string invoiceId, CancellationToken cancellationToken)
public async Task<IActionResult> Refund([FromServices] IEnumerable<IPayoutHandler> payoutHandlers, string invoiceId, CancellationToken cancellationToken)
{
await using var ctx = _dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
@@ -283,7 +283,8 @@ namespace BTCPayServer.Controllers
case RefundSteps.SelectRate:
createPullPayment = new CreatePullPayment
{
Name = $"Refund {invoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
Name = $"Refund {invoice.Id}",
PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId
};
switch (model.SelectedRefundOption)
@@ -343,7 +344,8 @@ namespace BTCPayServer.Controllers
createPullPayment = new CreatePullPayment
{
Name = $"Refund {invoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
Name = $"Refund {invoice.Id}",
PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId,
Currency = model.CustomCurrency,
Amount = model.CustomAmount
@@ -750,7 +752,7 @@ namespace BTCPayServer.Controllers
var store = model.StoreId == null || fs.ContainsFilter("storeid") ? null : HttpContext.GetStoreData();
var storeIds = store == null
? fs.GetFilterArray("storeid") != null ? fs.GetFilterArray("storeid") : new List<string>().ToArray()
: new []{ store.Id };
: new[] { store.Id };
model.StoreIds = storeIds;

View File

@@ -29,7 +29,7 @@ namespace BTCPayServer.Controllers
{
Is2faEnabled = user.TwoFactorEnabled,
RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
Credentials = await _fido2Service.GetCredentials( _userManager.GetUserId(User))
Credentials = await _fido2Service.GetCredentials(_userManager.GetUserId(User))
};
return View(model);
@@ -104,7 +104,7 @@ namespace BTCPayServer.Controllers
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
TempData[RecoveryCodesKey] = recoveryCodes.ToArray();
return RedirectToAction(nameof(GenerateRecoveryCodes), new {confirm = false});
return RedirectToAction(nameof(GenerateRecoveryCodes), new { confirm = false });
}
public async Task<IActionResult> ResetAuthenticator()
@@ -136,7 +136,7 @@ namespace BTCPayServer.Controllers
recoveryCodes = (await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10)).ToArray();
}
var model = new GenerateRecoveryCodesViewModel {RecoveryCodes = recoveryCodes};
var model = new GenerateRecoveryCodesViewModel { RecoveryCodes = recoveryCodes };
return View(model);
}

View File

@@ -108,7 +108,7 @@ namespace BTCPayServer.Controllers
//check if there is an app identifier that matches and belongs to the current user
var keys = await _apiKeyRepository.GetKeys(new APIKeyRepository.APIKeyQuery()
{
UserId = new[] {_userManager.GetUserId(User)}
UserId = new[] { _userManager.GetUserId(User) }
});
foreach (var key in keys)
{
@@ -201,14 +201,19 @@ namespace BTCPayServer.Controllers
* Go over each permission and associated store IDs and
* join them so that permission for a specific store is parsed correctly
*/
for (var i = 0; i < permissions.Length; i++) {
for (var i = 0; i < permissions.Length; i++)
{
var currPerm = permissions[i];
var storeIds = vm.PermissionValues[i].SpecificStores.ToArray();
if (storeIds.Length > 0) {
for (var x = 0; x < storeIds.Length; x++) {
if (storeIds.Length > 0)
{
for (var x = 0; x < storeIds.Length; x++)
{
permissionsWithStoreIDs.Add($"{currPerm}:{storeIds[x]}");
}
} else {
}
else
{
permissionsWithStoreIDs.Add(currPerm);
}
}
@@ -232,7 +237,8 @@ namespace BTCPayServer.Controllers
var command = commandParts.Length > 1 ? commandParts[1] : null;
var isPerformingAnAction = command == "change-store-mode" || command == "add-store";
// Don't want to accidentally change mode for the user if they are explicitly performing some action
if (isPerformingAnAction) {
if (isPerformingAnAction)
{
continue;
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

View File

@@ -19,7 +19,7 @@ namespace BTCPayServer.Controllers
var user = await _userManager.GetUserAsync(User);
if (user.DisabledNotifications == "all")
{
return View(new NotificationSettingsViewModel() {All = true});
return View(new NotificationSettingsViewModel() { All = true });
}
var disabledNotifications =
user.DisabledNotifications?.Split(';', StringSplitOptions.RemoveEmptyEntries)?.ToList() ??
@@ -29,7 +29,7 @@ namespace BTCPayServer.Controllers
disabledNotifications.Contains(tuple.identifier, StringComparer.InvariantCultureIgnoreCase))))
.ToList();
return View(new NotificationSettingsViewModel() {DisabledNotifications = notifications});
return View(new NotificationSettingsViewModel() { DisabledNotifications = notifications });
}
[HttpPost("notifications")]
@@ -56,7 +56,8 @@ namespace BTCPayServer.Controllers
await _userManager.UpdateAsync(user);
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "Updated successfully.", Severity = StatusMessageModel.StatusSeverity.Success
Message = "Updated successfully.",
Severity = StatusMessageModel.StatusSeverity.Success
});
return RedirectToAction("NotificationSettings");
}

View File

@@ -110,10 +110,12 @@ namespace BTCPayServer.Controllers
var res = await _notificationManager.GetNotifications(new NotificationsQuery()
{
Skip = skip, Take = count, UserId = userId
Skip = skip,
Take = count,
UserId = userId
});
var model = new IndexViewModel() {Skip = skip, Count = count, Items = res.Items, Total = res.Count};
var model = new IndexViewModel() { Skip = skip, Count = count, Items = res.Items, Total = res.Count };
return View(model);
}
@@ -133,7 +135,7 @@ namespace BTCPayServer.Controllers
{
if (ValidUserClaim(out var userId))
{
await _notificationManager.ToggleSeen(new NotificationsQuery() {Ids = new[] {id}, UserId = userId}, null);
await _notificationManager.ToggleSeen(new NotificationsQuery() { Ids = new[] { id }, UserId = userId }, null);
return RedirectToAction(nameof(Index));
}
@@ -148,7 +150,8 @@ namespace BTCPayServer.Controllers
var items = await
_notificationManager.ToggleSeen(new NotificationsQuery()
{
Ids = new[] {id}, UserId = userId
Ids = new[] { id },
UserId = userId
}, true);
var link = items.FirstOrDefault()?.ActionLink ?? "";
@@ -185,21 +188,26 @@ namespace BTCPayServer.Controllers
case "delete":
await _notificationManager.Remove(new NotificationsQuery()
{
UserId = userId, Ids = selectedItems
UserId = userId,
Ids = selectedItems
});
break;
case "mark-seen":
await _notificationManager.ToggleSeen(new NotificationsQuery()
{
UserId = userId, Ids = selectedItems, Seen = false
UserId = userId,
Ids = selectedItems,
Seen = false
}, true);
break;
case "mark-unseen":
await _notificationManager.ToggleSeen(new NotificationsQuery()
{
UserId = userId, Ids = selectedItems, Seen = true
UserId = userId,
Ids = selectedItems,
Seen = true
}, false);
break;
}
@@ -217,7 +225,7 @@ namespace BTCPayServer.Controllers
{
return NotFound();
}
await _notificationManager.ToggleSeen(new NotificationsQuery() {Seen = false, UserId = userId}, true);
await _notificationManager.ToggleSeen(new NotificationsQuery() { Seen = false, UserId = userId }, true);
return Redirect(returnUrl);
}

View File

@@ -251,11 +251,11 @@ namespace BTCPayServer.Controllers
Metadata = invoiceMetadata.ToJObject(),
Currency = blob.Currency,
Amount = amount.Value,
Checkout = {RedirectURL = redirectUrl}
Checkout = { RedirectURL = redirectUrl }
};
var additionalTags = new List<string> {PaymentRequestRepository.GetInternalTag(payReqId)};
var newInvoice = await _InvoiceController.CreateInvoiceCoreRaw(invoiceRequest,store, Request.GetAbsoluteRoot(), additionalTags, cancellationToken);
var additionalTags = new List<string> { PaymentRequestRepository.GetInternalTag(payReqId) };
var newInvoice = await _InvoiceController.CreateInvoiceCoreRaw(invoiceRequest, store, Request.GetAbsoluteRoot(), additionalTags, cancellationToken);
if (redirectToInvoice)
{
@@ -279,7 +279,8 @@ namespace BTCPayServer.Controllers
return NotFound();
}
if (!result.AllowCustomPaymentAmounts) {
if (!result.AllowCustomPaymentAmounts)
{
return BadRequest("Not allowed to cancel this invoice");
}

View File

@@ -109,7 +109,7 @@ namespace BTCPayServer.Controllers
var paymentMethodId = ppBlob.SupportedPaymentMethods.FirstOrDefault(id => vm.SelectedPaymentMethod == id.ToString());
var payoutHandler = paymentMethodId is null? null: _payoutHandlers.FindPayoutHandler(paymentMethodId);
var payoutHandler = paymentMethodId is null ? null : _payoutHandlers.FindPayoutHandler(paymentMethodId);
if (payoutHandler is null)
{
ModelState.AddModelError(nameof(vm.SelectedPaymentMethod), $"Invalid destination with selected payment method");
@@ -118,7 +118,7 @@ namespace BTCPayServer.Controllers
var destination = await payoutHandler?.ParseClaimDestination(paymentMethodId, vm.Destination, true);
if (destination.destination is null)
{
ModelState.AddModelError(nameof(vm.Destination), destination.error??"Invalid destination with selected payment method");
ModelState.AddModelError(nameof(vm.Destination), destination.error ?? "Invalid destination with selected payment method");
return await ViewPullPayment(pullPaymentId);
}

View File

@@ -83,7 +83,7 @@ namespace BTCPayServer.Controllers
[HttpPost("server/plugins/install")]
public async Task<IActionResult> InstallPlugin(
[FromServices] PluginService pluginService, string plugin , bool update = false)
[FromServices] PluginService pluginService, string plugin, bool update = false)
{
try
{
@@ -107,7 +107,8 @@ namespace BTCPayServer.Controllers
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "The plugin could not be downloaded. Try again later.", Severity = StatusMessageModel.StatusSeverity.Error
Message = "The plugin could not be downloaded. Try again later.",
Severity = StatusMessageModel.StatusSeverity.Error
});
}
@@ -127,7 +128,7 @@ namespace BTCPayServer.Controllers
}
return RedirectToAction("ListPlugins",
new {StatusMessage = "Files uploaded, restart server to load plugins"});
new { StatusMessage = "Files uploaded, restart server to load plugins" });
}
}
}

View File

@@ -138,8 +138,14 @@ namespace BTCPayServer.Controllers
if (ModelState.IsValid)
{
IdentityResult result;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, EmailConfirmed = model.EmailConfirmed, RequiresEmailConfirmation = requiresConfirmedEmail,
Created = DateTimeOffset.UtcNow };
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
EmailConfirmed = model.EmailConfirmed,
RequiresEmailConfirmation = requiresConfirmedEmail,
Created = DateTimeOffset.UtcNow
};
if (!string.IsNullOrEmpty(model.Password))
{
@@ -159,7 +165,10 @@ namespace BTCPayServer.Controllers
_eventAggregator.Publish(new UserRegisteredEvent()
{
RequestUri = Request.GetAbsoluteRootUri(), User = user, Admin = model.IsAdmin is true, CallbackUrlGenerated = tcs
RequestUri = Request.GetAbsoluteRootUri(),
User = user,
Admin = model.IsAdmin is true,
CallbackUrlGenerated = tcs
});
var callbackUrl = await tcs.Task;
@@ -173,7 +182,8 @@ namespace BTCPayServer.Controllers
Html =
$"Account created without a set password. An email will be sent (if configured) to set the password.<br/> You may alternatively share this link with them: <a class='alert-link' href='{callbackUrl}'>{callbackUrl}</a>"
});
}else if (!await _UserManager.HasPasswordAsync(user))
}
else if (!await _UserManager.HasPasswordAsync(user))
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{

View File

@@ -28,7 +28,7 @@ namespace BTCPayServer.Controllers
[Route("stores/{storeId}/pull-payments")]
[Authorize(Policy = Policies.CanViewStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[AutoValidateAntiforgeryToken]
public class StorePullPaymentsController: Controller
public class StorePullPaymentsController : Controller
{
private readonly BTCPayNetworkProvider _btcPayNetworkProvider;
private readonly IEnumerable<IPayoutHandler> _payoutHandlers;
@@ -172,7 +172,9 @@ namespace BTCPayServer.Controllers
var vm = this.ParseListQuery(new PullPaymentsModel()
{
Skip = skip, Count = count, Total = await ppsQuery.CountAsync()
Skip = skip,
Count = count,
Total = await ppsQuery.CountAsync()
});
var pps = (await ppsQuery
.Skip(vm.Skip)
@@ -186,7 +188,8 @@ namespace BTCPayServer.Controllers
.Select(o => o.GetBlob(_jsonSerializerSettings).Amount).Sum();
var totalAwaiting = pp.Payouts.Where(p => (p.State == PayoutState.AwaitingPayment ||
p.State == PayoutState.AwaitingApproval) &&
p.IsInPeriod(pp, now)).Select(o => o.GetBlob(_jsonSerializerSettings).Amount).Sum();;
p.IsInPeriod(pp, now)).Select(o => o.GetBlob(_jsonSerializerSettings).Amount).Sum();
;
var ppBlob = pp.GetBlob();
var ni = _currencyNameTable.GetCurrencyData(ppBlob.Currency, true);
var nfi = _currencyNameTable.GetNumberFormatInfo(ppBlob.Currency, true);
@@ -331,17 +334,20 @@ namespace BTCPayServer.Controllers
}
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "Payouts approved", Severity = StatusMessageModel.StatusSeverity.Success
Message = "Payouts approved",
Severity = StatusMessageModel.StatusSeverity.Success
});
break;
}
case "pay":
{
if (handler is { }) return await handler?.InitiatePayment(paymentMethodId, payoutIds);
if (handler is { })
return await handler?.InitiatePayment(paymentMethodId, payoutIds);
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "Paying via this payment method is not supported", Severity = StatusMessageModel.StatusSeverity.Error
Message = "Paying via this payment method is not supported",
Severity = StatusMessageModel.StatusSeverity.Error
});
break;
}
@@ -379,7 +385,8 @@ namespace BTCPayServer.Controllers
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "Payouts marked as paid", Severity = StatusMessageModel.StatusSeverity.Success
Message = "Payouts marked as paid",
Severity = StatusMessageModel.StatusSeverity.Success
});
break;
}
@@ -389,7 +396,8 @@ namespace BTCPayServer.Controllers
new PullPaymentHostedService.CancelRequest(payoutIds));
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Message = "Payouts archived", Severity = StatusMessageModel.StatusSeverity.Success
Message = "Payouts archived",
Severity = StatusMessageModel.StatusSeverity.Success
});
break;
}
@@ -437,7 +445,7 @@ namespace BTCPayServer.Controllers
var vm = this.ParseListQuery(new PayoutsModel
{
PaymentMethods = paymentMethods,
PaymentMethodId = paymentMethodId??paymentMethods.First().ToString(),
PaymentMethodId = paymentMethodId ?? paymentMethods.First().ToString(),
PullPaymentId = pullPaymentId,
PayoutState = payoutState,
Skip = skip,
@@ -459,11 +467,11 @@ namespace BTCPayServer.Controllers
}
vm.PayoutStateCount = payoutRequest.GroupBy(data => data.State)
.Select(e => new {e.Key, Count = e.Count()})
.Select(e => new { e.Key, Count = e.Count() })
.ToDictionary(arg => arg.Key, arg => arg.Count);
foreach (PayoutState value in Enum.GetValues(typeof(PayoutState)))
{
if(vm.PayoutStateCount.ContainsKey(value))
if (vm.PayoutStateCount.ContainsKey(value))
continue;
vm.PayoutStateCount.Add(value, 0);
}

View File

@@ -1,10 +1,10 @@
#nullable enable
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Models;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Client.Models;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using NBitcoin.DataEncoders;
@@ -30,7 +30,8 @@ namespace BTCPayServer.Controllers
var webhooks = await _Repo.GetWebhooks(CurrentStore.Id);
return View(nameof(Webhooks), new WebhooksViewModel()
{
Webhooks = webhooks.Select(async w => {
Webhooks = webhooks.Select(async w =>
{
var lastDelivery = await LastDeliveryForWebhook(w.Id);
var lastDeliveryBlob = lastDelivery?.GetBlob();
@@ -135,9 +136,12 @@ namespace BTCPayServer.Controllers
{
var result = await WebhookNotificationManager.TestWebhook(CurrentStore.Id, webhookId, viewModel.Type);
if (result.Success) {
if (result.Success)
{
TempData[WellKnownTempData.SuccessMessage] = $"{viewModel.Type.ToString()} event delivered successfully! Delivery ID is {result.DeliveryId}";
} else {
}
else
{
TempData[WellKnownTempData.ErrorMessage] = $"{viewModel.Type.ToString()} event could not be delivered. Error message received: {(result.ErrorMessage ?? "unknown")}";
}

View File

@@ -5,6 +5,7 @@ using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.HostedServices;
using BTCPayServer.ModelBinders;
using BTCPayServer.Models;
@@ -13,7 +14,6 @@ using BTCPayServer.Payments.PayJoin.Sender;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using NBitcoin.Payment;
using NBXplorer;
using NBXplorer.Models;

View File

@@ -7,13 +7,16 @@ using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.HostedServices;
using BTCPayServer.ModelBinders;
using BTCPayServer.Models;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Models.WalletViewModels;
using BTCPayServer.Payments;
using BTCPayServer.Payments.PayJoin;
using BTCPayServer.Services;
using BTCPayServer.Services.Labels;
using BTCPayServer.Services.Rates;
@@ -23,9 +26,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Payments.PayJoin;
using NBXplorer;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
@@ -177,7 +177,8 @@ namespace BTCPayServer.Controllers
allColors
.GroupBy(k => k)
.OrderBy(k => k.Count())
.ThenBy(k => {
.ThenBy(k =>
{
var indexInColorScheme = Array.IndexOf(LabelColorScheme, k.Key);
// Ensures that any label color which may not be in our label color scheme is given the least priority
@@ -492,7 +493,7 @@ namespace BTCPayServer.Controllers
.ToArray();
var balance = _walletProvider.GetWallet(network).GetBalance(paymentMethod.AccountDerivation);
model.NBXSeedAvailable = await GetSeed(walletId, network) != null;
var Balance= await balance;
var Balance = await balance;
model.CurrentBalance = (Balance.Available ?? Balance.Total).GetValue(network);
if (Balance.Immature is null)
model.ImmatureBalance = 0;
@@ -934,7 +935,7 @@ namespace BTCPayServer.Controllers
{
EnforceLowR = !(viewModel.SigningContext?.EnforceLowR is false)
};
var changed = psbt.PSBTChanged( () => psbt.SignAll(settings.AccountDerivation, signingKey, rootedKeyPath));
var changed = psbt.PSBTChanged(() => psbt.SignAll(settings.AccountDerivation, signingKey, rootedKeyPath));
if (!changed)
{
ModelState.AddModelError(nameof(viewModel.SeedOrKey), "Impossible to sign the transaction. Probable causes: Incorrect account key path in wallet settings or PSBT already signed.");

View File

@@ -106,14 +106,15 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
var res = raw.ToObject<PayoutTransactionOnChainBlob>(
JsonSerializer.Create(_jsonSerializerSettings.GetSerializer(paymentMethodId.CryptoCode)));
var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode);
if (res == null) return null;
if (res == null)
return null;
res.LinkTemplate = network.BlockExplorerLink;
return res;
}
public void StartBackgroundCheck(Action<Type[]> subscribe)
{
subscribe(new[] {typeof(NewOnChainTransactionEvent), typeof(NewBlockEvent)});
subscribe(new[] { typeof(NewOnChainTransactionEvent), typeof(NewBlockEvent) });
}
public async Task BackgroundCheck(object o)
@@ -172,7 +173,7 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
.ToListAsync()).Where(data =>
PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) &&
CanHandle(paymentMethodId))
.Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple=> tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == false);
.Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple => tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == false);
foreach (var valueTuple in payouts)
{
valueTuple.Item2.Accounted = true;
@@ -199,7 +200,7 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
.ToListAsync()).Where(data =>
PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) &&
CanHandle(paymentMethodId))
.Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple=> tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == true);
.Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple => tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == true);
foreach (var valueTuple in payouts)
{
valueTuple.Item2.TransactionId = null;
@@ -225,7 +226,7 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
.Where(id => id.PaymentType == BitcoinPaymentType.Instance));
}
public async Task<IActionResult> InitiatePayment(PaymentMethodId paymentMethodId ,string[] payoutIds)
public async Task<IActionResult> InitiatePayment(PaymentMethodId paymentMethodId, string[] payoutIds)
{
await using var ctx = this._dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
@@ -262,12 +263,12 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
break;
}
}
if(bip21.Any())
return new RedirectToActionResult("WalletSend", "Wallets", new {walletId = new WalletId(storeId, paymentMethodId.CryptoCode).ToString(), bip21});
if (bip21.Any())
return new RedirectToActionResult("WalletSend", "Wallets", new { walletId = new WalletId(storeId, paymentMethodId.CryptoCode).ToString(), bip21 });
return new RedirectToActionResult("Payouts", "Wallets", new
{
walletId = new WalletId(storeId, paymentMethodId.CryptoCode).ToString(),
pullPaymentId = pullPaymentIds.Length == 1? pullPaymentIds.First(): null
pullPaymentId = pullPaymentIds.Length == 1 ? pullPaymentIds.First() : null
});
}
@@ -390,9 +391,10 @@ public class BitcoinLikePayoutHandler : IPayoutHandler
var isInternal = storeWalletMatched is { };
var proof = ParseProof(payout) as PayoutTransactionOnChainBlob ??
new PayoutTransactionOnChainBlob() {Accounted = isInternal};
new PayoutTransactionOnChainBlob() { Accounted = isInternal };
var txId = newTransaction.NewTransactionEvent.TransactionData.TransactionHash;
if (!proof.Candidates.Add(txId)) return;
if (!proof.Candidates.Add(txId))
return;
if (isInternal)
{
payout.State = PayoutState.InProgress;

View File

@@ -5,7 +5,7 @@ using Newtonsoft.Json;
namespace BTCPayServer.Data
{
public class PayoutTransactionOnChainBlob: IPayoutProof
public class PayoutTransactionOnChainBlob : IPayoutProof
{
[JsonConverter(typeof(NBitcoin.JsonConverters.UInt256JsonConverter))]
public uint256 TransactionId { get; set; }

View File

@@ -5,8 +5,8 @@ using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Payments;
using PayoutData = BTCPayServer.Data.PayoutData;
using Microsoft.AspNetCore.Mvc;
using PayoutData = BTCPayServer.Data.PayoutData;
using StoreData = BTCPayServer.Data.StoreData;
public interface IPayoutHandler

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Data.Payouts.LightningLike
namespace BTCPayServer.Data.Payouts.LightningLike
{
public class LNURLPayClaimDestinaton: ILightningLikeLikeClaimDestination
public class LNURLPayClaimDestinaton : ILightningLikeLikeClaimDestination
{
public LNURLPayClaimDestinaton(string lnurl)
{

View File

@@ -76,7 +76,8 @@ namespace BTCPayServer.Data.Payouts.LightningLike
.ToListAsync())
.Where(payout =>
{
if (approvedStores.TryGetValue(payout.PullPaymentData.StoreId, out var value)) return value;
if (approvedStores.TryGetValue(payout.PullPaymentData.StoreId, out var value))
return value;
value = payout.PullPaymentData.StoreData.UserStores
.Any(store => store.Role == StoreRoles.Owner && store.ApplicationUserId == userId);
approvedStores.Add(payout.PullPaymentData.StoreId, value);
@@ -98,7 +99,9 @@ namespace BTCPayServer.Data.Payouts.LightningLike
return new ConfirmVM()
{
Amount = blob.CryptoAmount.Value, Destination = blob.Destination, PayoutId = payoutData.Id
Amount = blob.CryptoAmount.Value,
Destination = blob.Destination,
PayoutId = payoutData.Id
};
}).ToList();
return View(vm);
@@ -136,7 +139,9 @@ namespace BTCPayServer.Data.Payouts.LightningLike
{
results.Add(new ResultVM()
{
PayoutId = payoutData.Id, Result = result.Result, Destination = payoutBlob.Destination
PayoutId = payoutData.Id,
Result = result.Result,
Destination = payoutBlob.Destination
});
payoutData.State = PayoutState.Completed;
}
@@ -144,7 +149,9 @@ namespace BTCPayServer.Data.Payouts.LightningLike
{
results.Add(new ResultVM()
{
PayoutId = payoutData.Id, Result = result.Result, Destination = payoutBlob.Destination
PayoutId = payoutData.Id,
Result = result.Result,
Destination = payoutBlob.Destination
});
}
}
@@ -249,7 +256,9 @@ namespace BTCPayServer.Data.Payouts.LightningLike
{
results.Add(new ResultVM()
{
PayoutId = payoutData.Id, Result = PayResult.Error, Destination = blob.Destination
PayoutId = payoutData.Id,
Result = PayResult.Error,
Destination = blob.Destination
});
}
}

View File

@@ -92,7 +92,8 @@ namespace BTCPayServer.Data.Payouts.LightningLike
? new BoltInvoiceClaimDestination(destination, invoice)
: null;
if (result == null) return (null, "A valid BOLT11 invoice (with 30+ day expiry) or LNURL Pay or Lightning address was not provided.");
if (result == null)
return (null, "A valid BOLT11 invoice (with 30+ day expiry) or LNURL Pay or Lightning address was not provided.");
if (validate && (invoice.ExpiryDate.UtcDateTime - DateTime.UtcNow).Days < 30)
{
return (null,
@@ -150,7 +151,8 @@ namespace BTCPayServer.Data.Payouts.LightningLike
foreach (UserStore storeDataUserStore in storeData.UserStores)
{
if (!await _userService.IsAdminUser(storeDataUserStore.ApplicationUserId)) continue;
if (!await _userService.IsAdminUser(storeDataUserStore.ApplicationUserId))
continue;
result.Add(supportedPaymentMethod.PaymentId);
break;
}

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Data.Payouts.LightningLike
{
public class PayoutLightningBlob: IPayoutProof
public class PayoutLightningBlob : IPayoutProof
{
public string Bolt11Invoice { get; set; }
public string Preimage { get; set; }

View File

@@ -29,7 +29,7 @@ namespace BTCPayServer.Data
public static PaymentMethodId GetPaymentMethodId(this PayoutData data)
{
return PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId)? paymentMethodId : null;
return PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) ? paymentMethodId : null;
}
public static PayoutBlob GetBlob(this PayoutData data, BTCPayNetworkJsonSerializerSettings serializers)
{
@@ -42,7 +42,7 @@ namespace BTCPayServer.Data
public static void SetProofBlob(this PayoutData data, ManualPayoutProof blob)
{
if(blob is null)
if (blob is null)
return;
var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(blob));
// We only update the property if the bytes actually changed, this prevent from hammering the DB too much

View File

@@ -4,11 +4,11 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services.Rates;
using NBitcoin;
using NBXplorer;
using Newtonsoft.Json.Linq;
using BTCPayServer.Payments.Lightning;
namespace BTCPayServer.Data
{

View File

@@ -37,7 +37,7 @@ namespace BTCPayServer
return (Parse($"{hd.Extkey}{suffix}"), null);
case PubKeyProvider.Origin origin:
var innerResult = ExtractFromPkProvider(origin.Inner, suffix);
return (innerResult.Item1, new[] {origin.KeyOriginInfo});
return (innerResult.Item1, new[] { origin.KeyOriginInfo });
default:
throw new ArgumentOutOfRangeException();
}
@@ -46,7 +46,7 @@ namespace BTCPayServer
ArgumentNullException.ThrowIfNull(str);
str = str.Trim();
var outputDescriptor = OutputDescriptor.Parse(str, Network);
switch(outputDescriptor)
switch (outputDescriptor)
{
case OutputDescriptor.PK _:
case OutputDescriptor.Raw _:
@@ -58,7 +58,7 @@ namespace BTCPayServer
var xpubs = multi.PkProviders.Select(provider => ExtractFromPkProvider(provider));
return (
Parse(
$"{multi.Threshold}-of-{(string.Join('-', xpubs.Select(tuple => tuple.Item1.ToString())))}{(multi.IsSorted?"":"-[keeporder]")}"),
$"{multi.Threshold}-of-{(string.Join('-', xpubs.Select(tuple => tuple.Item1.ToString())))}{(multi.IsSorted ? "" : "-[keeporder]")}"),
xpubs.SelectMany(tuple => tuple.Item2).ToArray());
case OutputDescriptor.PKH pkh:
return ExtractFromPkProvider(pkh.PkProvider, "-[legacy]");

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Invoices;
namespace BTCPayServer.Events
{

View File

@@ -12,6 +12,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using BTCPayServer.Lightning;
@@ -29,7 +30,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NBitcoin;
using BTCPayServer.BIP78.Sender;
using NBitcoin.Payment;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
@@ -564,7 +564,7 @@ namespace BTCPayServer
var defaultSettings = BTCPayDefaultSettings.GetDefaultSettings(networkType);
dataDirectories.DataDir = configuration["datadir"] ?? defaultSettings.DefaultDataDirectory;
dataDirectories.PluginDir = configuration["plugindir"] ?? defaultSettings.DefaultPluginDirectory;
dataDirectories.StorageDir = Path.Combine(dataDirectories.DataDir , Storage.Services.Providers.FileSystemStorage.FileSystemFileProviderService.LocalStorageDirectoryName);
dataDirectories.StorageDir = Path.Combine(dataDirectories.DataDir, Storage.Services.Providers.FileSystemStorage.FileSystemFileProviderService.LocalStorageDirectoryName);
dataDirectories.TempStorageDir = Path.Combine(dataDirectories.StorageDir, "tmp");
return dataDirectories;
}

View File

@@ -38,7 +38,7 @@ namespace BTCPayServer
.Replace("-", "", StringComparison.InvariantCulture)
.PadLeft(divisibility, '0');
amt = amt.Length == divisibility ? $"0.{amt}" : amt.Insert(amt.Length - divisibility, ".");
return decimal.Parse($"{(negative? "-": string.Empty)}{amt}", CultureInfo.InvariantCulture);
return decimal.Parse($"{(negative ? "-" : string.Empty)}{amt}", CultureInfo.InvariantCulture);
}
public static string ShowMoney(this IMoney money, BTCPayNetwork network)
{

View File

@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Services;

View File

@@ -12,7 +12,8 @@ namespace BTCPayServer
{
return input.Substring(0, input.Length - suffixToRemove.Length);
}
else return input;
else
return input;
}
}
}

View File

@@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Mvc
controller: "Account",
values: new { userId, code },
scheme: scheme,
host:host,
host: host,
pathBase: pathbase
);
}
@@ -63,13 +63,13 @@ namespace Microsoft.AspNetCore.Mvc
scheme, host, pathbase);
}
public static string PayoutLink(this LinkGenerator urlHelper, string walletIdOrStoreId,string pullPaymentId, string scheme, HostString host, string pathbase)
public static string PayoutLink(this LinkGenerator urlHelper, string walletIdOrStoreId, string pullPaymentId, string scheme, HostString host, string pathbase)
{
WalletId.TryParse(walletIdOrStoreId, out var wallet);
return urlHelper.GetUriByAction(
action: nameof(StorePullPaymentsController.Payouts),
controller: "StorePullPayments",
values: new {storeId= wallet?.StoreId?? walletIdOrStoreId , pullPaymentId},
values: new { storeId = wallet?.StoreId ?? walletIdOrStoreId, pullPaymentId },
scheme, host, pathbase);
}
}

View File

@@ -1,4 +1,4 @@
using System.Linq;
using System.Linq;
using BTCPayServer.Data;
using BTCPayServer.Services.Invoices;
using Newtonsoft.Json.Linq;

View File

@@ -50,7 +50,8 @@ namespace BTCPayServer.Fido2
// 3. Create options
var authenticatorSelection = new AuthenticatorSelection
{
RequireResidentKey = false, UserVerification = UserVerificationRequirement.Preferred
RequireResidentKey = false,
UserVerification = UserVerificationRequirement.Preferred
};
var exts = new AuthenticationExtensionsClientInputs()
@@ -61,12 +62,13 @@ namespace BTCPayServer.Fido2
UserVerificationMethod = true,
BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds
{
FAR = float.MaxValue, FRR = float.MaxValue
FAR = float.MaxValue,
FRR = float.MaxValue
},
};
var options = _fido2.RequestNewCredential(
new Fido2User() {DisplayName = user.UserName, Name = user.UserName, Id = user.Id.ToBytesUTF8()},
new Fido2User() { DisplayName = user.UserName, Name = user.UserName, Id = user.Id.ToBytesUTF8() },
existingKeys, authenticatorSelection, AttestationConveyancePreference.None, exts);
// options.Rp = new PublicKeyCredentialRpEntity(Request.Host.Host, options.Rp.Name, "");
@@ -93,7 +95,7 @@ namespace BTCPayServer.Fido2
await _fido2.MakeNewCredentialAsync(attestationResponse, options, args => Task.FromResult(true));
// 3. Store the credentials in db
var newCredential = new Fido2Credential() {Name = name, ApplicationUserId = userId};
var newCredential = new Fido2Credential() { Name = name, ApplicationUserId = userId };
newCredential.SetBlob(new Fido2CredentialBlob()
{
@@ -129,7 +131,7 @@ namespace BTCPayServer.Fido2
public async Task Remove(string id, string userId)
{
await using var context = _contextFactory.CreateContext();
var device = await context.Fido2Credentials.FindAsync( id);
var device = await context.Fido2Credentials.FindAsync(id);
if (device == null || !device.ApplicationUserId.Equals(userId, StringComparison.InvariantCulture))
{
return;
@@ -168,7 +170,7 @@ namespace BTCPayServer.Fido2
},
UserVerificationIndex = true,
Location = true,
UserVerificationMethod = true ,
UserVerificationMethod = true,
Extensions = true,
AppID = _fido2Configuration.Origin
};
@@ -183,7 +185,8 @@ namespace BTCPayServer.Fido2
return options;
}
public async Task<bool> CompleteLogin(string userId, AuthenticatorAssertionRawResponse response){
public async Task<bool> CompleteLogin(string userId, AuthenticatorAssertionRawResponse response)
{
await using var dbContext = _contextFactory.CreateContext();
var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
.FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

View File

@@ -40,7 +40,8 @@ namespace BTCPayServer.Fido2
}
public string Verify(string code)
{
if (!_memoryCache.TryGetValue(code, out var userId)) return null;
if (!_memoryCache.TryGetValue(code, out var userId))
return null;
_memoryCache.Remove(GetCacheKey((string)userId));
_memoryCache.Remove(code);
return (string)userId;

View File

@@ -1,10 +1,10 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.Extensions.DependencyInjection;
namespace BTCPayServer.Filters
{

View File

@@ -44,7 +44,8 @@ namespace BTCPayServer.Filters
return true;
}
if (AppType == policies.RootAppType) {
if (AppType == policies.RootAppType)
{
context.RouteContext.RouteData.Values.Add("appId", policies.RootAppId);
return true;

View File

@@ -8,8 +8,8 @@ using BTCPayServer.Data;
using BTCPayServer.Logging;
using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace BTCPayServer.HostedServices
{

View File

@@ -74,7 +74,7 @@ namespace BTCPayServer.HostedServices
break;
case UserPasswordResetRequestedEvent userPasswordResetRequestedEvent2:
userPasswordResetRequestedEvent = userPasswordResetRequestedEvent2;
passwordSetter:
passwordSetter:
code = await _userManager.GeneratePasswordResetTokenAsync(userPasswordResetRequestedEvent.User);
var newPassword = await _userManager.HasPasswordAsync(userPasswordResetRequestedEvent.User);
callbackUrl = _generator.ResetPasswordCallbackLink(userPasswordResetRequestedEvent.User.Id, code,

View File

@@ -6,8 +6,8 @@ using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Abstractions.Services;
using BTCPayServer.Common;
using BTCPayServer.Client;
using BTCPayServer.Common;
using BTCPayServer.Configuration;
using BTCPayServer.Controllers;
using BTCPayServer.Controllers.GreenField;
@@ -51,12 +51,12 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NBitcoin;
using NBitcoin.RPC;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
using Newtonsoft.Json;
using NicolasDorier.RateLimits;
using Serilog;
using NBitcoin.RPC;
#if ALTCOINS
using BTCPayServer.Services.Altcoins.Monero;
#endif
@@ -226,7 +226,7 @@ namespace BTCPayServer.Hosting
var services = configuration.GetOrDefault<string>("externalservices", null);
if (services != null)
{
foreach (var service in services.Split(new[] {';', ','}, StringSplitOptions.RemoveEmptyEntries)
foreach (var service in services.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => (p, SeparatorIndex: p.IndexOf(':', StringComparison.OrdinalIgnoreCase)))
.Where(p => p.SeparatorIndex != -1)
.Select(p => (Name: p.p.Substring(0, p.SeparatorIndex),
@@ -292,7 +292,7 @@ namespace BTCPayServer.Hosting
services.TryAddSingleton<PaymentRequestRepository>();
services.TryAddSingleton<BTCPayWalletProvider>();
services.TryAddSingleton<WalletReceiveService>();
services.AddSingleton<IHostedService>( provider => provider.GetService<WalletReceiveService>());
services.AddSingleton<IHostedService>(provider => provider.GetService<WalletReceiveService>());
services.TryAddSingleton<CurrencyNameTable>(CurrencyNameTable.Instance);
services.TryAddSingleton<IFeeProviderFactory>(o => new NBXplorerFeeProviderFactory(o.GetRequiredService<ExplorerClientProvider>())
{

Some files were not shown because too many files have changed in this diff Show More