diff --git a/BTCPayServer.Abstractions/Configuration/DataDirectories.cs b/BTCPayServer.Abstractions/Configuration/DataDirectories.cs index 0e5f25a87..9142670d2 100644 --- a/BTCPayServer.Abstractions/Configuration/DataDirectories.cs +++ b/BTCPayServer.Abstractions/Configuration/DataDirectories.cs @@ -2,11 +2,11 @@ namespace BTCPayServer.Configuration { public class DataDirectories { - public string DataDir { get; set; } - public string PluginDir { get; set; } + public string DataDir { get; set; } + public string PluginDir { get; set; } public string TempStorageDir { get; set; } public string StorageDir { get; set; } } - - + + } diff --git a/BTCPayServer.Abstractions/Contracts/BaseDbContextFactory.cs b/BTCPayServer.Abstractions/Contracts/BaseDbContextFactory.cs index 5cc4df6c5..767e5bc52 100644 --- a/BTCPayServer.Abstractions/Contracts/BaseDbContextFactory.cs +++ b/BTCPayServer.Abstractions/Contracts/BaseDbContextFactory.cs @@ -9,7 +9,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Operations; namespace BTCPayServer.Abstractions.Contracts { - public abstract class BaseDbContextFactory where T: DbContext + public abstract class BaseDbContextFactory where T : DbContext { private readonly IOptions _options; private readonly string _schemaPrefix; @@ -95,7 +95,7 @@ namespace BTCPayServer.Abstractions.Contracts builder.UseMySql(_options.Value.ConnectionString, ServerVersion.AutoDetect(_options.Value.ConnectionString), o => { o.EnableRetryOnFailure(10); - + if (!string.IsNullOrEmpty(_schemaPrefix)) { o.MigrationsHistoryTable(_schemaPrefix); @@ -106,6 +106,6 @@ namespace BTCPayServer.Abstractions.Contracts throw new ArgumentOutOfRangeException(); } } - + } } diff --git a/BTCPayServer.Abstractions/Contracts/IBTCPayServerPlugin.cs b/BTCPayServer.Abstractions/Contracts/IBTCPayServerPlugin.cs index b59b9cd18..776ee0ded 100644 --- a/BTCPayServer.Abstractions/Contracts/IBTCPayServerPlugin.cs +++ b/BTCPayServer.Abstractions/Contracts/IBTCPayServerPlugin.cs @@ -28,5 +28,5 @@ namespace BTCPayServer.Abstractions.Contracts } } } - + } diff --git a/BTCPayServer.Abstractions/Contracts/INotificationHandler.cs b/BTCPayServer.Abstractions/Contracts/INotificationHandler.cs index b756feb9b..0caaed572 100644 --- a/BTCPayServer.Abstractions/Contracts/INotificationHandler.cs +++ b/BTCPayServer.Abstractions/Contracts/INotificationHandler.cs @@ -7,7 +7,7 @@ namespace BTCPayServer.Abstractions.Contracts public abstract string Identifier { get; } public abstract string NotificationType { get; } } - + public interface INotificationHandler { string NotificationType { get; } @@ -15,7 +15,7 @@ namespace BTCPayServer.Abstractions.Contracts public (string identifier, string name)[] Meta { get; } void FillViewModel(object notification, NotificationViewModel vm); } - + public class NotificationViewModel { public string Id { get; set; } diff --git a/BTCPayServer.Abstractions/Contracts/IPluginHookFilter.cs b/BTCPayServer.Abstractions/Contracts/IPluginHookFilter.cs index 6e319783e..8a6b2fcd0 100644 --- a/BTCPayServer.Abstractions/Contracts/IPluginHookFilter.cs +++ b/BTCPayServer.Abstractions/Contracts/IPluginHookFilter.cs @@ -5,7 +5,7 @@ namespace BTCPayServer.Abstractions.Contracts public interface IPluginHookFilter { public string Hook { get; } - + Task Execute(object args); } } diff --git a/BTCPayServer.Abstractions/Contracts/IUIExtension.cs b/BTCPayServer.Abstractions/Contracts/IUIExtension.cs index 1539d8d53..aba21e5c8 100644 --- a/BTCPayServer.Abstractions/Contracts/IUIExtension.cs +++ b/BTCPayServer.Abstractions/Contracts/IUIExtension.cs @@ -3,7 +3,7 @@ namespace BTCPayServer.Abstractions.Contracts public interface IUIExtension { string Partial { get; } - + string Location { get; } } } diff --git a/BTCPayServer.Abstractions/Extensions/ViewsRazor.cs b/BTCPayServer.Abstractions/Extensions/ViewsRazor.cs index fb2d32b47..6f51d46c3 100644 --- a/BTCPayServer.Abstractions/Extensions/ViewsRazor.cs +++ b/BTCPayServer.Abstractions/Extensions/ViewsRazor.cs @@ -14,9 +14,9 @@ namespace BTCPayServer.Abstractions.Extensions public static void SetActivePage(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) { // Page Title @@ -57,9 +57,9 @@ namespace BTCPayServer.Abstractions.Extensions public static string IsActivePage(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; } @@ -84,11 +84,11 @@ namespace BTCPayServer.Abstractions.Extensions var displayDate = date.ToString("o", CultureInfo.InvariantCulture); return new HtmlString($"{displayDate}"); } - + public static string ToTimeAgo(this DateTimeOffset date) { var diff = DateTimeOffset.UtcNow - date; - var formatted = diff.Seconds > 0 + var formatted = diff.Seconds > 0 ? $"{diff.TimeString()} ago" : $"in {diff.Negate().TimeString()}"; return formatted; diff --git a/BTCPayServer.Abstractions/Services/PluginAction.cs b/BTCPayServer.Abstractions/Services/PluginAction.cs index 8b034cbad..e70b6d8f8 100644 --- a/BTCPayServer.Abstractions/Services/PluginAction.cs +++ b/BTCPayServer.Abstractions/Services/PluginAction.cs @@ -3,7 +3,7 @@ using BTCPayServer.Abstractions.Contracts; namespace BTCPayServer.Abstractions.Services { - public abstract class PluginAction:IPluginHookAction + public abstract class PluginAction : IPluginHookAction { public abstract string Hook { get; } public Task Execute(object args) diff --git a/BTCPayServer.Abstractions/Services/PluginHookFilter.cs b/BTCPayServer.Abstractions/Services/PluginHookFilter.cs index 5bb564f88..5ccfad1b5 100644 --- a/BTCPayServer.Abstractions/Services/PluginHookFilter.cs +++ b/BTCPayServer.Abstractions/Services/PluginHookFilter.cs @@ -3,7 +3,7 @@ using BTCPayServer.Abstractions.Contracts; namespace BTCPayServer.Abstractions.Services { - public abstract class PluginHookFilter:IPluginHookFilter + public abstract class PluginHookFilter : IPluginHookFilter { public abstract string Hook { get; } diff --git a/BTCPayServer.Abstractions/Services/UIExtension.cs b/BTCPayServer.Abstractions/Services/UIExtension.cs index 512f698bb..ba06187dd 100644 --- a/BTCPayServer.Abstractions/Services/UIExtension.cs +++ b/BTCPayServer.Abstractions/Services/UIExtension.cs @@ -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) { diff --git a/BTCPayServer.Client/BTCPayServerClient.Invoices.cs b/BTCPayServer.Client/BTCPayServerClient.Invoices.cs index c4450b7e8..16788b3a3 100644 --- a/BTCPayServer.Client/BTCPayServerClient.Invoices.cs +++ b/BTCPayServer.Client/BTCPayServerClient.Invoices.cs @@ -35,16 +35,18 @@ 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); } - + var response = await _httpClient.SendAsync( CreateHttpRequest($"api/v1/stores/{storeId}/invoices", @@ -114,7 +116,7 @@ namespace BTCPayServer.Client public virtual async Task UnarchiveInvoice(string storeId, string invoiceId, CancellationToken token = default) { var response = await _httpClient.SendAsync( - CreateHttpRequest($"api/v1/stores/{storeId}/invoices/{invoiceId}/unarchive", + CreateHttpRequest($"api/v1/stores/{storeId}/invoices/{invoiceId}/unarchive", method: HttpMethod.Post), token); return await HandleResponse(response); } @@ -122,7 +124,7 @@ namespace BTCPayServer.Client public virtual async Task ActivateInvoicePaymentMethod(string storeId, string invoiceId, string paymentMethod, CancellationToken token = default) { var response = await _httpClient.SendAsync( - CreateHttpRequest($"api/v1/stores/{storeId}/invoices/{invoiceId}/payment-methods/{paymentMethod}/activate", + CreateHttpRequest($"api/v1/stores/{storeId}/invoices/{invoiceId}/payment-methods/{paymentMethod}/activate", method: HttpMethod.Post), token); await HandleResponse(response); } diff --git a/BTCPayServer.Client/BTCPayServerClient.Notifications.cs b/BTCPayServer.Client/BTCPayServerClient.Notifications.cs index 6a9a60d1c..943e28560 100644 --- a/BTCPayServer.Client/BTCPayServerClient.Notifications.cs +++ b/BTCPayServer.Client/BTCPayServerClient.Notifications.cs @@ -9,11 +9,11 @@ namespace BTCPayServer.Client { public partial class BTCPayServerClient { - public virtual async Task> GetNotifications(bool? seen = null, int? skip = null, + public virtual async Task> GetNotifications(bool? seen = null, int? skip = null, int? take = null, CancellationToken token = default) { Dictionary queryPayload = new Dictionary(); - + if (seen != null) queryPayload.Add(nameof(seen), seen); if (skip != null) @@ -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(response); } diff --git a/BTCPayServer.Client/BTCPayServerClient.OnChainPaymentMethods.cs b/BTCPayServer.Client/BTCPayServerClient.OnChainPaymentMethods.cs index 5b5003ead..b1b6ebb6b 100644 --- a/BTCPayServer.Client/BTCPayServerClient.OnChainPaymentMethods.cs +++ b/BTCPayServer.Client/BTCPayServerClient.OnChainPaymentMethods.cs @@ -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() {{"offset", offset}, {"amount", amount}}, + queryPayload: new Dictionary() { { "offset", offset }, { "amount", amount } }, method: HttpMethod.Post), token); return await HandleResponse(response); } @@ -74,11 +74,11 @@ namespace BTCPayServer.Client { var response = await _httpClient.SendAsync( CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/preview", - queryPayload: new Dictionary() {{"offset", offset}, {"amount", amount}}, + queryPayload: new Dictionary() { { "offset", offset }, { "amount", amount } }, method: HttpMethod.Get), token); return await HandleResponse(response); } - + public virtual async Task GenerateOnChainWallet(string storeId, string cryptoCode, GenerateOnChainWalletRequest request, CancellationToken token = default) diff --git a/BTCPayServer.Client/BTCPayServerClient.OnChainWallet.cs b/BTCPayServer.Client/BTCPayServerClient.OnChainWallet.cs index c6caaaa9f..ee024f1cf 100644 --- a/BTCPayServer.Client/BTCPayServerClient.OnChainWallet.cs +++ b/BTCPayServer.Client/BTCPayServerClient.OnChainWallet.cs @@ -25,14 +25,14 @@ namespace BTCPayServer.Client Dictionary queryParams = new Dictionary(); if (blockTarget != null) { - queryParams.Add("blockTarget",blockTarget); + queryParams.Add("blockTarget", blockTarget); } var response = await _httpClient.SendAsync( CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/feeRate", queryParams), token); return await HandleResponse(response); } - + public virtual async Task GetOnChainWalletReceiveAddress(string storeId, string cryptoCode, bool forceGenerate = false, CancellationToken token = default) { @@ -44,16 +44,16 @@ namespace BTCPayServer.Client }), token); return await HandleResponse(response); } - + public virtual async Task UnReserveOnChainWalletReceiveAddress(string storeId, string cryptoCode, CancellationToken token = default) { 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); } - + public virtual async Task> ShowOnChainWalletTransactions( string storeId, string cryptoCode, TransactionStatus[] statusFilter = null, CancellationToken token = default) @@ -68,7 +68,7 @@ namespace BTCPayServer.Client CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions", query), token); return await HandleResponse>(response); } - + public virtual async Task GetOnChainWalletTransaction( string storeId, string cryptoCode, string transactionId, CancellationToken token = default) @@ -78,7 +78,7 @@ namespace BTCPayServer.Client CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions/{transactionId}"), token); return await HandleResponse(response); } - + public virtual async Task> GetOnChainWalletUTXOs(string storeId, string cryptoCode, CancellationToken token = default) @@ -88,7 +88,7 @@ namespace BTCPayServer.Client CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/utxos"), token); return await HandleResponse>(response); } - + public virtual async Task CreateOnChainTransaction(string storeId, string cryptoCode, CreateOnChainTransactionRequest request, CancellationToken token = default) @@ -103,7 +103,7 @@ namespace BTCPayServer.Client CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions", null, request, HttpMethod.Post), token); return await HandleResponse(response); } - + public virtual async Task CreateOnChainTransactionButDoNotBroadcast(string storeId, string cryptoCode, CreateOnChainTransactionRequest request, Network network, CancellationToken token = default) diff --git a/BTCPayServer.Client/BTCPayServerClient.PaymentRequests.cs b/BTCPayServer.Client/BTCPayServerClient.PaymentRequests.cs index eff1f46f1..64b493e2d 100644 --- a/BTCPayServer.Client/BTCPayServerClient.PaymentRequests.cs +++ b/BTCPayServer.Client/BTCPayServerClient.PaymentRequests.cs @@ -16,7 +16,7 @@ namespace BTCPayServer.Client var response = await _httpClient.SendAsync( CreateHttpRequest($"api/v1/stores/{storeId}/payment-requests", - new Dictionary() {{nameof(includeArchived), includeArchived}}), token); + new Dictionary() { { nameof(includeArchived), includeArchived } }), token); return await HandleResponse>(response); } diff --git a/BTCPayServer.Client/JsonConverters/MnemonicJsonConverter.cs b/BTCPayServer.Client/JsonConverters/MnemonicJsonConverter.cs index 4f7f1a897..00e0e63ae 100644 --- a/BTCPayServer.Client/JsonConverters/MnemonicJsonConverter.cs +++ b/BTCPayServer.Client/JsonConverters/MnemonicJsonConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using NBitcoin; using NBitcoin.JsonConverters; using Newtonsoft.Json; diff --git a/BTCPayServer.Client/JsonConverters/NumericStringJsonConverter.cs b/BTCPayServer.Client/JsonConverters/NumericStringJsonConverter.cs index d07bfb815..d79ca6f97 100644 --- a/BTCPayServer.Client/JsonConverters/NumericStringJsonConverter.cs +++ b/BTCPayServer.Client/JsonConverters/NumericStringJsonConverter.cs @@ -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); diff --git a/BTCPayServer.Client/JsonConverters/WordcountJsonConverter.cs b/BTCPayServer.Client/JsonConverters/WordcountJsonConverter.cs index 3f02beda2..1d83c9932 100644 --- a/BTCPayServer.Client/JsonConverters/WordcountJsonConverter.cs +++ b/BTCPayServer.Client/JsonConverters/WordcountJsonConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; diff --git a/BTCPayServer.Client/JsonConverters/WordlistJsonConverter.cs b/BTCPayServer.Client/JsonConverters/WordlistJsonConverter.cs index 6dd533a51..95724c8e4 100644 --- a/BTCPayServer.Client/JsonConverters/WordlistJsonConverter.cs +++ b/BTCPayServer.Client/JsonConverters/WordlistJsonConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -21,7 +21,7 @@ public class WordlistJsonConverter : JsonConverter {"PortugueseBrazil", Wordlist.PortugueseBrazil}, {"Czech", Wordlist.Czech} }; - + _WordlistsReverse = _Wordlists.ToDictionary(kv => kv.Value, kv => kv.Key); } diff --git a/BTCPayServer.Client/Models/AddCustomerEmailRequest.cs b/BTCPayServer.Client/Models/AddCustomerEmailRequest.cs index f34e15c86..c4ada191e 100644 --- a/BTCPayServer.Client/Models/AddCustomerEmailRequest.cs +++ b/BTCPayServer.Client/Models/AddCustomerEmailRequest.cs @@ -4,4 +4,4 @@ namespace BTCPayServer.Client.Models { public string Email { get; set; } } -} \ No newline at end of file +} diff --git a/BTCPayServer.Client/Models/CreateOnChainTransactionRequest.cs b/BTCPayServer.Client/Models/CreateOnChainTransactionRequest.cs index 3c2d8f671..7a74f3f28 100644 --- a/BTCPayServer.Client/Models/CreateOnChainTransactionRequest.cs +++ b/BTCPayServer.Client/Models/CreateOnChainTransactionRequest.cs @@ -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))] diff --git a/BTCPayServer.Client/Models/GenerateOnChainWalletRequest.cs b/BTCPayServer.Client/Models/GenerateOnChainWalletRequest.cs index 48b213215..9535ad3f5 100644 --- a/BTCPayServer.Client/Models/GenerateOnChainWalletRequest.cs +++ b/BTCPayServer.Client/Models/GenerateOnChainWalletRequest.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Client.JsonConverters; +using BTCPayServer.Client.JsonConverters; using NBitcoin; using Newtonsoft.Json; using Newtonsoft.Json.Converters; @@ -8,7 +8,7 @@ namespace BTCPayServer.Client public class GenerateOnChainWalletRequest { public int AccountNumber { get; set; } = 0; - [JsonConverter(typeof(MnemonicJsonConverter))] + [JsonConverter(typeof(MnemonicJsonConverter))] public Mnemonic ExistingMnemonic { get; set; } [JsonConverter(typeof(WordlistJsonConverter))] public NBitcoin.Wordlist WordList { get; set; } diff --git a/BTCPayServer.Client/Models/GenericPaymentMethodData.cs b/BTCPayServer.Client/Models/GenericPaymentMethodData.cs index b97b243d4..fe554d513 100644 --- a/BTCPayServer.Client/Models/GenericPaymentMethodData.cs +++ b/BTCPayServer.Client/Models/GenericPaymentMethodData.cs @@ -1,4 +1,4 @@ -namespace BTCPayServer.Client.Models +namespace BTCPayServer.Client.Models { public class GenericPaymentMethodData { diff --git a/BTCPayServer.Client/Models/GreenfieldPermissionAPIError.cs b/BTCPayServer.Client/Models/GreenfieldPermissionAPIError.cs index 482a4992a..191410ff7 100644 --- a/BTCPayServer.Client/Models/GreenfieldPermissionAPIError.cs +++ b/BTCPayServer.Client/Models/GreenfieldPermissionAPIError.cs @@ -12,6 +12,6 @@ namespace BTCPayServer.Client.Models } public string MissingPermission { get; } - + } } diff --git a/BTCPayServer.Client/Models/InvoiceExceptionStatus.cs b/BTCPayServer.Client/Models/InvoiceExceptionStatus.cs index e526fde3a..40087c715 100644 --- a/BTCPayServer.Client/Models/InvoiceExceptionStatus.cs +++ b/BTCPayServer.Client/Models/InvoiceExceptionStatus.cs @@ -9,4 +9,4 @@ namespace BTCPayServer.Client.Models Invalid, PaidOver } -} \ No newline at end of file +} diff --git a/BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs b/BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs index 81dcbb66e..9e68ea010 100644 --- a/BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs +++ b/BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs @@ -52,7 +52,7 @@ namespace BTCPayServer.Client.Models public PaymentStatus Status { get; set; } public string Destination { get; set; } - + public enum PaymentStatus { Invalid, diff --git a/BTCPayServer.Client/Models/LNURLPayPaymentMethodBaseData.cs b/BTCPayServer.Client/Models/LNURLPayPaymentMethodBaseData.cs index 4f69254be..9e37f94d8 100644 --- a/BTCPayServer.Client/Models/LNURLPayPaymentMethodBaseData.cs +++ b/BTCPayServer.Client/Models/LNURLPayPaymentMethodBaseData.cs @@ -1,4 +1,4 @@ -namespace BTCPayServer.Client.Models +namespace BTCPayServer.Client.Models { public class LNURLPayPaymentMethodBaseData { @@ -8,7 +8,7 @@ public LNURLPayPaymentMethodBaseData() { - + } } } diff --git a/BTCPayServer.Client/Models/LNURLPayPaymentMethodData.cs b/BTCPayServer.Client/Models/LNURLPayPaymentMethodData.cs index c3825d385..23d665952 100644 --- a/BTCPayServer.Client/Models/LNURLPayPaymentMethodData.cs +++ b/BTCPayServer.Client/Models/LNURLPayPaymentMethodData.cs @@ -1,6 +1,6 @@ -namespace BTCPayServer.Client.Models +namespace BTCPayServer.Client.Models { - public class LNURLPayPaymentMethodData: LNURLPayPaymentMethodBaseData + public class LNURLPayPaymentMethodData : LNURLPayPaymentMethodBaseData { /// /// Whether the payment method is enabled @@ -16,7 +16,7 @@ { } - public LNURLPayPaymentMethodData(string cryptoCode, bool enabled, bool useBech32Scheme, bool enableForStandardInvoices) + public LNURLPayPaymentMethodData(string cryptoCode, bool enabled, bool useBech32Scheme, bool enableForStandardInvoices) { Enabled = enabled; CryptoCode = cryptoCode; diff --git a/BTCPayServer.Client/Models/LabelData.cs b/BTCPayServer.Client/Models/LabelData.cs index 6b71102b3..36c87260d 100644 --- a/BTCPayServer.Client/Models/LabelData.cs +++ b/BTCPayServer.Client/Models/LabelData.cs @@ -11,4 +11,4 @@ namespace BTCPayServer.Client.Models [JsonExtensionData] public Dictionary AdditionalData { get; set; } } -} \ No newline at end of file +} diff --git a/BTCPayServer.Client/Models/LightningNetworkPaymentMethodBaseData.cs b/BTCPayServer.Client/Models/LightningNetworkPaymentMethodBaseData.cs index a663bca04..6128f3705 100644 --- a/BTCPayServer.Client/Models/LightningNetworkPaymentMethodBaseData.cs +++ b/BTCPayServer.Client/Models/LightningNetworkPaymentMethodBaseData.cs @@ -1,4 +1,4 @@ -namespace BTCPayServer.Client.Models +namespace BTCPayServer.Client.Models { public class LightningNetworkPaymentMethodBaseData { @@ -7,7 +7,7 @@ public bool DisableBOLT11PaymentOption { get; set; } public LightningNetworkPaymentMethodBaseData() { - + } } } diff --git a/BTCPayServer.Client/Models/LightningNetworkPaymentMethodData.cs b/BTCPayServer.Client/Models/LightningNetworkPaymentMethodData.cs index 11a96a475..02dbed6ac 100644 --- a/BTCPayServer.Client/Models/LightningNetworkPaymentMethodData.cs +++ b/BTCPayServer.Client/Models/LightningNetworkPaymentMethodData.cs @@ -1,6 +1,6 @@ namespace BTCPayServer.Client.Models { - public class LightningNetworkPaymentMethodData: LightningNetworkPaymentMethodBaseData + public class LightningNetworkPaymentMethodData : LightningNetworkPaymentMethodBaseData { /// /// Whether the payment method is enabled diff --git a/BTCPayServer.Client/Models/OnChainPaymentMethodBaseData.cs b/BTCPayServer.Client/Models/OnChainPaymentMethodBaseData.cs index a64e6f0e8..9586acfad 100644 --- a/BTCPayServer.Client/Models/OnChainPaymentMethodBaseData.cs +++ b/BTCPayServer.Client/Models/OnChainPaymentMethodBaseData.cs @@ -1,4 +1,4 @@ -using NBitcoin; +using NBitcoin; using Newtonsoft.Json; namespace BTCPayServer.Client.Models @@ -19,6 +19,6 @@ namespace BTCPayServer.Client.Models { } - + } } diff --git a/BTCPayServer.Client/Models/OnChainPaymentMethodData.cs b/BTCPayServer.Client/Models/OnChainPaymentMethodData.cs index bf2e135d9..412e20a97 100644 --- a/BTCPayServer.Client/Models/OnChainPaymentMethodData.cs +++ b/BTCPayServer.Client/Models/OnChainPaymentMethodData.cs @@ -11,7 +11,7 @@ namespace BTCPayServer.Client.Models public OnChainPaymentMethodDataPreview() { - + } public OnChainPaymentMethodDataPreview(string cryptoCode, string derivationScheme, string label, RootedKeyPath accountKeyPath) @@ -34,7 +34,7 @@ namespace BTCPayServer.Client.Models public OnChainPaymentMethodData() { - + } public OnChainPaymentMethodData(string cryptoCode, string derivationScheme, bool enabled, string label, RootedKeyPath accountKeyPath, string paymentMethod) : diff --git a/BTCPayServer.Client/Models/OnChainPaymentMethodDataWithSensitiveData.cs b/BTCPayServer.Client/Models/OnChainPaymentMethodDataWithSensitiveData.cs index c7ce11536..b161d705b 100644 --- a/BTCPayServer.Client/Models/OnChainPaymentMethodDataWithSensitiveData.cs +++ b/BTCPayServer.Client/Models/OnChainPaymentMethodDataWithSensitiveData.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Client.JsonConverters; +using BTCPayServer.Client.JsonConverters; using NBitcoin; using Newtonsoft.Json; diff --git a/BTCPayServer.Client/Models/ServerInfoData.cs b/BTCPayServer.Client/Models/ServerInfoData.cs index 1e33f2d99..b799ff482 100644 --- a/BTCPayServer.Client/Models/ServerInfoData.cs +++ b/BTCPayServer.Client/Models/ServerInfoData.cs @@ -29,14 +29,14 @@ namespace BTCPayServer.Client.Models /// public IEnumerable SyncStatus { get; set; } } - + public class SyncStatus { public string CryptoCode { get; set; } public virtual bool Available { get; set; } } - public class ServerInfoSyncStatusData: SyncStatus + public class ServerInfoSyncStatusData : SyncStatus { public int ChainHeight { get; set; } public int? SyncHeight { get; set; } diff --git a/BTCPayServer.Client/Models/StoreBaseData.cs b/BTCPayServer.Client/Models/StoreBaseData.cs index f4dec3e49..b5203436e 100644 --- a/BTCPayServer.Client/Models/StoreBaseData.cs +++ b/BTCPayServer.Client/Models/StoreBaseData.cs @@ -41,9 +41,9 @@ namespace BTCPayServer.Client.Models public bool ShowRecommendedFee { get; set; } = true; [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int RecommendedFeeBlockTarget { get; set; } = 1; - + public string DefaultPaymentMethod { get; set; } - + [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string DefaultLang { get; set; } = "en"; diff --git a/BTCPayServer.Client/Models/TransactionStatus.cs b/BTCPayServer.Client/Models/TransactionStatus.cs index 3fef01758..fc97802f2 100644 --- a/BTCPayServer.Client/Models/TransactionStatus.cs +++ b/BTCPayServer.Client/Models/TransactionStatus.cs @@ -6,4 +6,4 @@ namespace BTCPayServer.Client.Models Confirmed, Replaced } -} \ No newline at end of file +} diff --git a/BTCPayServer.Client/Models/UpdateLightningNetworkPaymentMethodRequest.cs b/BTCPayServer.Client/Models/UpdateLightningNetworkPaymentMethodRequest.cs index 0cb2f1b48..d4183320e 100644 --- a/BTCPayServer.Client/Models/UpdateLightningNetworkPaymentMethodRequest.cs +++ b/BTCPayServer.Client/Models/UpdateLightningNetworkPaymentMethodRequest.cs @@ -1,6 +1,6 @@ namespace BTCPayServer.Client.Models { - public class UpdateLightningNetworkPaymentMethodRequest: LightningNetworkPaymentMethodBaseData + public class UpdateLightningNetworkPaymentMethodRequest : LightningNetworkPaymentMethodBaseData { /// /// Whether the payment method is enabled diff --git a/BTCPayServer.Client/Models/UpdateOnChainPaymentMethodRequest.cs b/BTCPayServer.Client/Models/UpdateOnChainPaymentMethodRequest.cs index 6ab05c948..08946834e 100644 --- a/BTCPayServer.Client/Models/UpdateOnChainPaymentMethodRequest.cs +++ b/BTCPayServer.Client/Models/UpdateOnChainPaymentMethodRequest.cs @@ -11,7 +11,7 @@ namespace BTCPayServer.Client.Models public UpdateOnChainPaymentMethodRequest() { - + } public UpdateOnChainPaymentMethodRequest(bool enabled, string derivationScheme, string label, RootedKeyPath accountKeyPath) diff --git a/BTCPayServer.Common/IExplorerClientProvider.cs b/BTCPayServer.Common/IExplorerClientProvider.cs index 4760e529b..0a7d0ce09 100644 --- a/BTCPayServer.Common/IExplorerClientProvider.cs +++ b/BTCPayServer.Common/IExplorerClientProvider.cs @@ -1,4 +1,4 @@ -using NBXplorer; +using NBXplorer; namespace BTCPayServer.Common { diff --git a/BTCPayServer.Data/Data/APIKeyData.cs b/BTCPayServer.Data/Data/APIKeyData.cs index 721a1614a..6a60f625a 100644 --- a/BTCPayServer.Data/Data/APIKeyData.cs +++ b/BTCPayServer.Data/Data/APIKeyData.cs @@ -8,10 +8,10 @@ namespace BTCPayServer.Data [MaxLength(50)] public string Id { get; set; } - [MaxLength(50)] + [MaxLength(50)] public string StoreId { get; set; } - [MaxLength(50)] + [MaxLength(50)] public string UserId { get; set; } public APIKeyType Type { get; set; } = APIKeyType.Legacy; diff --git a/BTCPayServer.Data/Data/ApplicationUser.cs b/BTCPayServer.Data/Data/ApplicationUser.cs index 5cd889d56..78df548a5 100644 --- a/BTCPayServer.Data/Data/ApplicationUser.cs +++ b/BTCPayServer.Data/Data/ApplicationUser.cs @@ -19,7 +19,7 @@ namespace BTCPayServer.Data public List Notifications { get; set; } public List UserStores { get; set; } public List Fido2Credentials { get; set; } - + public byte[] Blob { get; set; } public List> UserRoles { get; set; } diff --git a/BTCPayServer.Data/Data/PayoutData.cs b/BTCPayServer.Data/Data/PayoutData.cs index b021a44ec..2a6b7d3e7 100644 --- a/BTCPayServer.Data/Data/PayoutData.cs +++ b/BTCPayServer.Data/Data/PayoutData.cs @@ -37,7 +37,7 @@ namespace BTCPayServer.Data builder.Entity() .HasIndex(o => o.State); builder.Entity() - .HasIndex(x => new { DestinationId = x.Destination, x.State}); + .HasIndex(x => new { DestinationId = x.Destination, x.State }); } // utility methods diff --git a/BTCPayServer.Data/Data/U2FDevice.cs b/BTCPayServer.Data/Data/U2FDevice.cs index 03854ec9c..dca87b709 100644 --- a/BTCPayServer.Data/Data/U2FDevice.cs +++ b/BTCPayServer.Data/Data/U2FDevice.cs @@ -19,8 +19,8 @@ namespace BTCPayServer.Data public string ApplicationUserId { get; set; } public ApplicationUser ApplicationUser { get; set; } - - + + internal static void OnModelCreating(ModelBuilder builder) { #pragma warning disable CS0618 // Type or member is obsolete diff --git a/BTCPayServer.Data/Migrations/20200625064111_refundnotificationpullpayments.cs b/BTCPayServer.Data/Migrations/20200625064111_refundnotificationpullpayments.cs index ef9d29205..94ebe854a 100644 --- a/BTCPayServer.Data/Migrations/20200625064111_refundnotificationpullpayments.cs +++ b/BTCPayServer.Data/Migrations/20200625064111_refundnotificationpullpayments.cs @@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations name: "CurrentRefundId", table: "Invoices", nullable: true, - maxLength: maxLength); + maxLength: maxLength); migrationBuilder.CreateTable( name: "Notifications", diff --git a/BTCPayServer.Data/Migrations/20200901161733_AddInvoiceEventLogSeverity.cs b/BTCPayServer.Data/Migrations/20200901161733_AddInvoiceEventLogSeverity.cs index 6b0c35fc1..f04d54534 100644 --- a/BTCPayServer.Data/Migrations/20200901161733_AddInvoiceEventLogSeverity.cs +++ b/BTCPayServer.Data/Migrations/20200901161733_AddInvoiceEventLogSeverity.cs @@ -1,10 +1,10 @@ -using BTCPayServer.Data; +using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; namespace BTCPayServer.Migrations { - + [DbContext(typeof(ApplicationDbContext))] [Migration("20200901161733_AddInvoiceEventLogSeverity")] public partial class AddInvoiceEventLogSeverity : Migration diff --git a/BTCPayServer.Data/Migrations/20201002145033_AddCreateDateToUser.cs b/BTCPayServer.Data/Migrations/20201002145033_AddCreateDateToUser.cs index 55397f2f2..b148e730b 100644 --- a/BTCPayServer.Data/Migrations/20201002145033_AddCreateDateToUser.cs +++ b/BTCPayServer.Data/Migrations/20201002145033_AddCreateDateToUser.cs @@ -1,4 +1,4 @@ -using System; +using System; using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; diff --git a/BTCPayServer.Data/Migrations/20201007090617_u2fDeviceCascade.cs b/BTCPayServer.Data/Migrations/20201007090617_u2fDeviceCascade.cs index 2b97a86d0..1df268191 100644 --- a/BTCPayServer.Data/Migrations/20201007090617_u2fDeviceCascade.cs +++ b/BTCPayServer.Data/Migrations/20201007090617_u2fDeviceCascade.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Data; +using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; diff --git a/BTCPayServer.Data/Migrations/20201015151438_AddDisabledNotificationsToUser.cs b/BTCPayServer.Data/Migrations/20201015151438_AddDisabledNotificationsToUser.cs index 0bdb584f7..bc43b7a42 100644 --- a/BTCPayServer.Data/Migrations/20201015151438_AddDisabledNotificationsToUser.cs +++ b/BTCPayServer.Data/Migrations/20201015151438_AddDisabledNotificationsToUser.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Data; +using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; diff --git a/BTCPayServer.Data/Migrations/20201208054211_invoicesorderindex.cs b/BTCPayServer.Data/Migrations/20201208054211_invoicesorderindex.cs index a93f4198f..cf596e620 100644 --- a/BTCPayServer.Data/Migrations/20201208054211_invoicesorderindex.cs +++ b/BTCPayServer.Data/Migrations/20201208054211_invoicesorderindex.cs @@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations oldClrType: typeof(string)); } - migrationBuilder.CreateIndex( + migrationBuilder.CreateIndex( name: "IX_Invoices_OrderId", table: "Invoices", column: "OrderId"); diff --git a/BTCPayServer.Data/Migrations/20201228225040_AddingInvoiceSearchesTable.cs b/BTCPayServer.Data/Migrations/20201228225040_AddingInvoiceSearchesTable.cs index 6cd16b38f..197181929 100644 --- a/BTCPayServer.Data/Migrations/20201228225040_AddingInvoiceSearchesTable.cs +++ b/BTCPayServer.Data/Migrations/20201228225040_AddingInvoiceSearchesTable.cs @@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .Annotation("MySql:ValueGeneratedOnAdd", true) .Annotation("Sqlite:Autoincrement", true), - // eof manually added + // eof manually added InvoiceDataId = table.Column(maxLength: 255, nullable: true), Value = table.Column(maxLength: 512, nullable: true) }, diff --git a/BTCPayServer.Data/Migrations/20210314092253_Fido2Credentials.cs b/BTCPayServer.Data/Migrations/20210314092253_Fido2Credentials.cs index 0842644d5..246079fe5 100644 --- a/BTCPayServer.Data/Migrations/20210314092253_Fido2Credentials.cs +++ b/BTCPayServer.Data/Migrations/20210314092253_Fido2Credentials.cs @@ -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 { diff --git a/BTCPayServer.Data/Migrations/20211125081400_AddUserBlob.cs b/BTCPayServer.Data/Migrations/20211125081400_AddUserBlob.cs index dccd38850..399bb9518 100644 --- a/BTCPayServer.Data/Migrations/20211125081400_AddUserBlob.cs +++ b/BTCPayServer.Data/Migrations/20211125081400_AddUserBlob.cs @@ -1,4 +1,4 @@ -using System; +using System; using BTCPayServer.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/BTCPayServer.PluginPacker/Program.cs b/BTCPayServer.PluginPacker/Program.cs index 6fac20b7b..b37d08c4b 100644 --- a/BTCPayServer.PluginPacker/Program.cs +++ b/BTCPayServer.PluginPacker/Program.cs @@ -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"); } @@ -45,7 +45,7 @@ namespace BTCPayServer.PluginPacker File.WriteAllText(outputFile + ".btcpay.json", json); Console.WriteLine($"Created {outputFile}.btcpay at {directory}"); } - + private static Type[] GetAllExtensionTypesFromAssembly(Assembly assembly) { return assembly.GetTypes().Where(type => diff --git a/BTCPayServer.Plugins.Test/Controllers/TestExtensionController.cs b/BTCPayServer.Plugins.Test/Controllers/TestExtensionController.cs index da62a1439..5f36e4c79 100644 --- a/BTCPayServer.Plugins.Test/Controllers/TestExtensionController.cs +++ b/BTCPayServer.Plugins.Test/Controllers/TestExtensionController.cs @@ -15,7 +15,7 @@ namespace BTCPayServer.Plugins.Test { _testPluginService = testPluginService; } - + // GET public async Task Index() { @@ -24,8 +24,8 @@ namespace BTCPayServer.Plugins.Test Data = await _testPluginService.Get() }); } - - + + } public class TestPluginPageViewModel diff --git a/BTCPayServer.Plugins.Test/Data/TestPluginData.cs b/BTCPayServer.Plugins.Test/Data/TestPluginData.cs index f60515d95..776ec80c9 100644 --- a/BTCPayServer.Plugins.Test/Data/TestPluginData.cs +++ b/BTCPayServer.Plugins.Test/Data/TestPluginData.cs @@ -8,7 +8,7 @@ namespace BTCPayServer.Plugins.Test.Data [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public string Id { get; set; } public DateTimeOffset Timestamp { get; set; } - - + + } } diff --git a/BTCPayServer.Plugins.Test/Data/TestPluginDbContext.cs b/BTCPayServer.Plugins.Test/Data/TestPluginDbContext.cs index a8e51b1cc..022bbb58e 100644 --- a/BTCPayServer.Plugins.Test/Data/TestPluginDbContext.cs +++ b/BTCPayServer.Plugins.Test/Data/TestPluginDbContext.cs @@ -10,7 +10,7 @@ namespace BTCPayServer.Plugins.Test private readonly bool _designTime; public DbSet TestPluginRecords { get; set; } - + public TestPluginDbContext(DbContextOptions options, bool designTime = false) : base(options) { diff --git a/BTCPayServer.Plugins.Test/Migrations/20201117154419_Init.cs b/BTCPayServer.Plugins.Test/Migrations/20201117154419_Init.cs index 84737650e..0af1b4cb8 100644 --- a/BTCPayServer.Plugins.Test/Migrations/20201117154419_Init.cs +++ b/BTCPayServer.Plugins.Test/Migrations/20201117154419_Init.cs @@ -1,4 +1,4 @@ -using System; +using System; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; diff --git a/BTCPayServer.Plugins.Test/Services/TestPluginDbContextFactory.cs b/BTCPayServer.Plugins.Test/Services/TestPluginDbContextFactory.cs index c42f6f932..204f54477 100644 --- a/BTCPayServer.Plugins.Test/Services/TestPluginDbContextFactory.cs +++ b/BTCPayServer.Plugins.Test/Services/TestPluginDbContextFactory.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.Options; namespace BTCPayServer.Plugins.Test { - + public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory { public TestPluginDbContext CreateDbContext(string[] args) @@ -31,7 +31,7 @@ namespace BTCPayServer.Plugins.Test var builder = new DbContextOptionsBuilder(); ConfigureBuilder(builder); return new TestPluginDbContext(builder.Options); - + } } } diff --git a/BTCPayServer.Plugins.Test/Services/TestPluginService.cs b/BTCPayServer.Plugins.Test/Services/TestPluginService.cs index aaabb31de..84aecd83b 100644 --- a/BTCPayServer.Plugins.Test/Services/TestPluginService.cs +++ b/BTCPayServer.Plugins.Test/Services/TestPluginService.cs @@ -19,11 +19,11 @@ 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(); } - - + + public async Task> Get() { await using var context = _testPluginDbContextFactory.CreateContext(); diff --git a/BTCPayServer.Plugins.Test/TestExtension.cs b/BTCPayServer.Plugins.Test/TestExtension.cs index 2d6fe164d..ac038b8f8 100644 --- a/BTCPayServer.Plugins.Test/TestExtension.cs +++ b/BTCPayServer.Plugins.Test/TestExtension.cs @@ -1,4 +1,4 @@ -using System; +using System; using BTCPayServer.Abstractions.Contracts; using BTCPayServer.Abstractions.Models; using BTCPayServer.Abstractions.Services; @@ -9,11 +9,11 @@ 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!"; - public override string Description { get; } = "This is a description of the loaded test extension!"; + public override string Identifier { get; } = "BTCPayServer.Plugins.Test"; + public override string Name { get; } = "Test Plugin!"; + public override string Description { get; } = "This is a description of the loaded test extension!"; public override void Execute(IServiceCollection services) { @@ -33,7 +33,7 @@ namespace BTCPayServer.Plugins.Test base.Execute(applicationBuilder, applicationBuilderApplicationServices); applicationBuilderApplicationServices.GetService().CreateContext().Database.Migrate(); applicationBuilderApplicationServices.GetService().AddTestDataRecord().GetAwaiter().GetResult(); - + } } } diff --git a/BTCPayServer.Rating/Providers/ArgoneumRateProvider.cs b/BTCPayServer.Rating/Providers/ArgoneumRateProvider.cs index a0048f734..fa03577d1 100644 --- a/BTCPayServer.Rating/Providers/ArgoneumRateProvider.cs +++ b/BTCPayServer.Rating/Providers/ArgoneumRateProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; diff --git a/BTCPayServer.Rating/Providers/BitbankRateProvider.cs b/BTCPayServer.Rating/Providers/BitbankRateProvider.cs index 560337bfb..5c146ecc7 100644 --- a/BTCPayServer.Rating/Providers/BitbankRateProvider.cs +++ b/BTCPayServer.Rating/Providers/BitbankRateProvider.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.Services.Rates var data = jobj.ContainsKey("data") ? jobj["data"] : null; if (jobj["success"]?.Value() != 1) { - var errorCode = data is null? "Unknown": data["code"].Value(); + var errorCode = data is null ? "Unknown" : data["code"].Value(); throw new Exception( $"BitBank Rates API Error: {errorCode}. See https://github.com/bitbankinc/bitbank-api-docs/blob/master/errors.md for more details."); } diff --git a/BTCPayServer.Tests/ApiKeysTests.cs b/BTCPayServer.Tests/ApiKeysTests.cs index 11a9af9e4..ff96e653c 100644 --- a/BTCPayServer.Tests/ApiKeysTests.cs +++ b/BTCPayServer.Tests/ApiKeysTests.cs @@ -142,7 +142,7 @@ namespace BTCPayServer.Tests (await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions); authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri, - new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, applicationDetails: (null, new Uri(callbackUrl))).ToString(); + new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, applicationDetails: (null, new Uri(callbackUrl))).ToString(); s.Driver.Navigate().GoToUrl(authUrl); Assert.DoesNotContain("kukksappname", s.Driver.PageSource); @@ -169,11 +169,11 @@ namespace BTCPayServer.Tests s.Driver.Navigate().GoToUrl(authUrl); s.Driver.FindElement(By.Id("continue")).Click(); Assert.Equal(callbackUrl, s.Driver.Url); - + //same app but different redirect = nono authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri, new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, (appidentifier, new Uri("https://international.local/callback"))).ToString(); - + s.Driver.Navigate().GoToUrl(authUrl); Assert.False(s.Driver.Url.StartsWith("https://international.com/callback")); diff --git a/BTCPayServer.Tests/CheckoutUITests.cs b/BTCPayServer.Tests/CheckoutUITests.cs index ceb1a93bf..a243bc55c 100644 --- a/BTCPayServer.Tests/CheckoutUITests.cs +++ b/BTCPayServer.Tests/CheckoutUITests.cs @@ -200,7 +200,7 @@ namespace BTCPayServer.Tests s.Driver.SetCheckbox(By.Id("LightningAmountInSatoshi"), true); s.Driver.FindElement(By.Id("save")).Click(); Assert.Contains("BTC Lightning settings successfully updated", s.FindAlertMessage().Text); - + var invoiceId = s.CreateInvoice(storeId, 10, "USD", "a@g.com"); s.GoToInvoiceCheckout(invoiceId); Assert.Contains("Sats", s.Driver.FindElement(By.ClassName("payment__currencies_noborder")).Text); diff --git a/BTCPayServer.Tests/CrowdfundTests.cs b/BTCPayServer.Tests/CrowdfundTests.cs index 511c89bae..98fa79c7c 100644 --- a/BTCPayServer.Tests/CrowdfundTests.cs +++ b/BTCPayServer.Tests/CrowdfundTests.cs @@ -92,7 +92,7 @@ namespace BTCPayServer.Tests var anonAppPubsController = tester.PayTester.GetController(); var publicApps = user.GetController(); - + Assert.IsType(await anonAppPubsController.ContributeToCrowdfund(app.Id, new ContributeToCrowdfund() { Amount = new decimal(0.01) @@ -187,7 +187,7 @@ namespace BTCPayServer.Tests var model = Assert.IsType(Assert .IsType(publicApps.ViewCrowdfund(app.Id, String.Empty).Result).Model); - + Assert.Equal(crowdfundViewModel.TargetAmount, model.TargetAmount); Assert.Equal(crowdfundViewModel.EndDate, model.EndDate); Assert.Equal(crowdfundViewModel.StartDate, model.StartDate); @@ -195,7 +195,7 @@ namespace BTCPayServer.Tests Assert.Equal(0m, model.Info.CurrentAmount); Assert.Equal(0m, model.Info.CurrentPendingAmount); Assert.Equal(0m, model.Info.ProgressPercentage); - + TestLogs.LogInformation("Unpaid invoices should show as pending contribution because it is hardcap"); TestLogs.LogInformation("Because UseAllStoreInvoices is true, we can manually create an invoice and it should show as contribution"); var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice @@ -208,7 +208,7 @@ namespace BTCPayServer.Tests TransactionSpeed = "high", FullNotifications = true }, Facade.Merchant); - + model = Assert.IsType(Assert .IsType(publicApps.ViewCrowdfund(app.Id, string.Empty).Result).Model); diff --git a/BTCPayServer.Tests/Extensions.cs b/BTCPayServer.Tests/Extensions.cs index d769c23e3..56c5c8923 100644 --- a/BTCPayServer.Tests/Extensions.cs +++ b/BTCPayServer.Tests/Extensions.cs @@ -28,11 +28,12 @@ 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}"); } - + public static T AssertViewModel(this IActionResult result) { Assert.NotNull(result); @@ -50,7 +51,7 @@ namespace BTCPayServer.Tests // Sometimes, selenium is flaky... public static IWebElement FindElementUntilNotStaled(this IWebDriver driver, By by, Action act) { - retry: +retry: try { var el = driver.FindElement(by); @@ -91,18 +92,18 @@ 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. // This leads to Selenium trying to click the button while it is moving resulting in an error. public static void ToggleCollapse(this IWebDriver driver, string collapseId) { driver.ExecuteJavaScript($"document.getElementById('{collapseId}').classList.add('show')"); } - - + + public static void SetAttribute(this IWebDriver driver, string element, string attribute, string value) { @@ -135,7 +136,7 @@ namespace BTCPayServer.Tests wait.UntilJsIsReady(); int retriesLeft = 4; - retry: +retry: try { var el = driver.FindElement(selector); diff --git a/BTCPayServer.Tests/GreenfieldAPITests.cs b/BTCPayServer.Tests/GreenfieldAPITests.cs index 8ee543b5b..fce9f3449 100644 --- a/BTCPayServer.Tests/GreenfieldAPITests.cs +++ b/BTCPayServer.Tests/GreenfieldAPITests.cs @@ -460,7 +460,7 @@ namespace BTCPayServer.Tests Assert.Null(payout.PaymentMethodAmount); TestLogs.LogInformation("Can't overdraft"); - + var destination2 = (await tester.ExplorerNode.GetNewAddressAsync()).ToString(); await this.AssertAPIError("overdraft", async () => await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest() { @@ -1142,25 +1142,25 @@ namespace BTCPayServer.Tests Assert.Empty(invoices); //list Filtered - var invoicesFiltered = await viewOnly.GetInvoices(user.StoreId, - orderId: null, status: null, startDate: DateTimeOffset.Now.AddHours(-1), - endDate: DateTimeOffset.Now.AddHours(1)); + var invoicesFiltered = await viewOnly.GetInvoices(user.StoreId, + orderId: null, status: null, startDate: DateTimeOffset.Now.AddHours(-1), + endDate: DateTimeOffset.Now.AddHours(1)); - Assert.NotNull(invoicesFiltered); - Assert.Single(invoicesFiltered); - Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); + Assert.NotNull(invoicesFiltered); + Assert.Single(invoicesFiltered); + Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); Assert.NotNull(invoicesFiltered); Assert.Single(invoicesFiltered); Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); - //list Yesterday - var invoicesYesterday = await viewOnly.GetInvoices(user.StoreId, - orderId: null, status: null, startDate: DateTimeOffset.Now.AddDays(-2), - endDate: DateTimeOffset.Now.AddDays(-1)); - Assert.NotNull(invoicesYesterday); - Assert.Empty(invoicesYesterday); + //list Yesterday + var invoicesYesterday = await viewOnly.GetInvoices(user.StoreId, + orderId: null, status: null, startDate: DateTimeOffset.Now.AddDays(-2), + endDate: DateTimeOffset.Now.AddDays(-1)); + Assert.NotNull(invoicesYesterday); + Assert.Empty(invoicesYesterday); // Error, startDate and endDate inverted await AssertValidationError(new[] { "startDate", "endDate" }, @@ -1177,31 +1177,31 @@ namespace BTCPayServer.Tests //list Existing OrderId var invoicesExistingOrderId = - await viewOnly.GetInvoices(user.StoreId, orderId: new []{newInvoice.Metadata["orderId"].ToString()}); - Assert.NotNull(invoicesExistingOrderId); - Assert.Single(invoicesFiltered); - Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); + 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"}); - Assert.NotNull(invoicesNonExistingOrderId); - Assert.Empty(invoicesNonExistingOrderId); + //list NonExisting OrderId + var invoicesNonExistingOrderId = + 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 }); + 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 }); + Assert.NotNull(invoicesNonExistingStatus); + Assert.Empty(invoicesNonExistingStatus); - //list Existing Status - var invoicesExistingStatus = - 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}); - Assert.NotNull(invoicesNonExistingStatus); - Assert.Empty(invoicesNonExistingStatus); - - //get var invoice = await viewOnly.GetInvoice(user.StoreId, newInvoice.Id); Assert.Equal(newInvoice.Metadata, invoice.Metadata); @@ -1216,14 +1216,14 @@ namespace BTCPayServer.Tests //update newInvoice = await client.CreateInvoice(user.StoreId, new CreateInvoiceRequest() { Currency = "USD", Amount = 1 }); - Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); - Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); + Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); + Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); await client.MarkInvoiceStatus(user.StoreId, newInvoice.Id, new MarkInvoiceStatusRequest() { Status = InvoiceStatus.Settled }); newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id); - + Assert.DoesNotContain(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); newInvoice = await client.CreateInvoice(user.StoreId, @@ -1234,7 +1234,7 @@ namespace BTCPayServer.Tests }); newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id); - + Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); Assert.DoesNotContain(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); await AssertHttpError(403, async () => @@ -1369,7 +1369,7 @@ namespace BTCPayServer.Tests Checkout = new CreateInvoiceRequest.CheckoutOptions() { PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" }, - DefaultPaymentMethod = "BTC_LightningLike" + DefaultPaymentMethod = "BTC_LightningLike" } }); Assert.Equal("BTC_LightningLike", invoiceWithdefaultPaymentMethodLN.Checkout.DefaultPaymentMethod); @@ -1382,17 +1382,17 @@ namespace BTCPayServer.Tests Checkout = new CreateInvoiceRequest.CheckoutOptions() { PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" }, - DefaultPaymentMethod = "BTC" + DefaultPaymentMethod = "BTC" } }); Assert.Equal("BTC", invoiceWithdefaultPaymentMethodOnChain.Checkout.DefaultPaymentMethod); - + store = await client.GetStore(user.StoreId); store.LazyPaymentMethods = false; store = await client.UpdateStore(store.Id, JObject.FromObject(store).ToObject()); - - + + //let's see the overdue amount invoice = await client.CreateInvoice(user.StoreId, new CreateInvoiceRequest() @@ -1402,24 +1402,24 @@ namespace BTCPayServer.Tests Checkout = new CreateInvoiceRequest.CheckoutOptions() { PaymentMethods = new[] { "BTC" }, - DefaultPaymentMethod = "BTC" + DefaultPaymentMethod = "BTC" } }); var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id)); - Assert.Equal(0.0001m, pm.Due); - - await tester.WaitForEvent(async () => - { - await tester.ExplorerNode.SendToAddressAsync( - BitcoinAddress.Create(pm.Destination, tester.ExplorerClient.Network.NBitcoinNetwork), - new Money(0.0002m, MoneyUnit.BTC)); - }); - await TestUtils.EventuallyAsync(async () => - { - var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id)); - Assert.Single(pm.Payments); - Assert.Equal(-0.0001m, pm.Due); - }); + Assert.Equal(0.0001m, pm.Due); + + await tester.WaitForEvent(async () => + { + await tester.ExplorerNode.SendToAddressAsync( + BitcoinAddress.Create(pm.Destination, tester.ExplorerClient.Network.NBitcoinNetwork), + new Money(0.0002m, MoneyUnit.BTC)); + }); + await TestUtils.EventuallyAsync(async () => + { + var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id)); + Assert.Single(pm.Payments); + Assert.Equal(-0.0001m, pm.Due); + }); } } @@ -1567,7 +1567,7 @@ namespace BTCPayServer.Tests var user2 = tester.NewAccount(); await user.GrantAccessAsync(true); await user2.GrantAccessAsync(false); - + var client = await user.CreateClient(Policies.CanModifyStoreSettings); var client2 = await user2.CreateClient(Policies.CanModifyStoreSettings); var viewOnlyClient = await user.CreateClient(Policies.CanViewStoreSettings); @@ -1578,8 +1578,8 @@ namespace BTCPayServer.Tests await AssertHttpError(403, async () => { await viewOnlyClient.UpdateStoreOnChainPaymentMethod(store.Id, "BTC", new UpdateOnChainPaymentMethodRequest() { }); - }); - + }); + var xpriv = new Mnemonic("all all all all all all all all all all all all").DeriveExtKey() .Derive(KeyPath.Parse("m/84'/1'/0'")); var xpub = xpriv.Neuter().ToString(Network.RegTest); @@ -1617,59 +1617,59 @@ namespace BTCPayServer.Tests { await client.GetStoreOnChainPaymentMethod(store.Id, "BTC"); }); - + await AssertHttpError(403, async () => { await viewOnlyClient.GenerateOnChainWallet(store.Id, "BTC", new GenerateOnChainWalletRequest() { }); }); - - await AssertValidationError(new []{"SavePrivateKeys", "ImportKeysToRPC"}, async () => - { - await client2.GenerateOnChainWallet(user2.StoreId, "BTC", new GenerateOnChainWalletRequest() - { - SavePrivateKeys = true, - ImportKeysToRPC = true - }); - }); - + await AssertValidationError(new[] { "SavePrivateKeys", "ImportKeysToRPC" }, async () => + { + await client2.GenerateOnChainWallet(user2.StoreId, "BTC", new GenerateOnChainWalletRequest() + { + SavePrivateKeys = true, + ImportKeysToRPC = true + }); + }); + + var allMnemonic = new Mnemonic("all all all all all all all all all all all all"); - - + + 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); - + 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()); - + Assert.Equal(new Mnemonic("all all all all all all all all all all all all").DeriveExtKey() .Derive(KeyPath.Parse("m/84'/1'/1'")).Neuter().ToString(Network.RegTest), generateResponse.DerivationScheme); - + 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); } @@ -1784,7 +1784,7 @@ namespace BTCPayServer.Tests settings.AllowLightningInternalNodeForAll = true; await tester.PayTester.GetService().UpdateSetting(settings); - await nonAdminUserClient.UpdateStoreLightningNetworkPaymentMethod(nonAdminUser.StoreId, "BTC", new UpdateLightningNetworkPaymentMethodRequest() + await nonAdminUserClient.UpdateStoreLightningNetworkPaymentMethod(nonAdminUser.StoreId, "BTC", new UpdateLightningNetworkPaymentMethodRequest() { Enabled = method.Enabled, ConnectionString = method.ConnectionString @@ -2010,7 +2010,7 @@ namespace BTCPayServer.Tests new[] { TransactionStatus.Confirmed }), data => data.TransactionHash == txdata.TransactionHash); } - + [Fact(Timeout = 60 * 2 * 1000)] [Trait("Lightning", "Lightning")] [Trait("Integration", "Integration")] @@ -2040,7 +2040,7 @@ namespace BTCPayServer.Tests var methods = await adminClient.GetStorePaymentMethods(store.Id); Assert.Single(methods); VerifyLightning(methods); - + var randK = new Mnemonic(Wordlist.English, WordCount.Twelve).DeriveExtKey().Neuter().ToString(Network.RegTest); await adminClient.UpdateStoreOnChainPaymentMethod(admin.StoreId, "BTC", new UpdateOnChainPaymentMethodRequest(true, randK, "testing", null)); @@ -2051,35 +2051,35 @@ namespace BTCPayServer.Tests var paymentMethodBaseData = Assert.IsType(item.Data).ToObject(); Assert.Equal(randK, paymentMethodBaseData.DerivationScheme); } - + methods = await adminClient.GetStorePaymentMethods(store.Id); Assert.Equal(2, methods.Count); VerifyLightning(methods); VerifyOnChain(methods); - - + + methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id); - + VerifyLightning(methods); - - - await adminClient.UpdateStoreLightningNetworkPaymentMethod(store.Id, "BTC", - new UpdateLightningNetworkPaymentMethodRequest( - tester.GetLightningConnectionString(LightningConnectionType.CLightning, true), true)); + + + await adminClient.UpdateStoreLightningNetworkPaymentMethod(store.Id, "BTC", + new UpdateLightningNetworkPaymentMethodRequest( + tester.GetLightningConnectionString(LightningConnectionType.CLightning, true), true)); methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id); - + Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out var item)); - var lightningNetworkPaymentMethodBaseData =Assert.IsType(item.Data).ToObject(); + var lightningNetworkPaymentMethodBaseData = Assert.IsType(item.Data).ToObject(); 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(item.Data).ToObject(); + lightningNetworkPaymentMethodBaseData = Assert.IsType(item.Data).ToObject(); Assert.NotEqual("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString); - + } } diff --git a/BTCPayServer.Tests/LanguageServiceTests.cs b/BTCPayServer.Tests/LanguageServiceTests.cs index 7b50e022c..5bb7c6f6a 100644 --- a/BTCPayServer.Tests/LanguageServiceTests.cs +++ b/BTCPayServer.Tests/LanguageServiceTests.cs @@ -22,7 +22,7 @@ namespace BTCPayServer.Tests { await tester.StartAsync(); var languageService = tester.PayTester.GetService(); - + // Most common format. First option does not have a quality score. Others do in descending order. // Result should be nl-NL (because the default weight is 1 for nl) var lang1 = languageService.FindLanguageInAcceptLanguageHeader("nl,fr;q=0.7,en;q=0.5"); diff --git a/BTCPayServer.Tests/PSBTTests.cs b/BTCPayServer.Tests/PSBTTests.cs index cc5fdc8a0..bc594bc38 100644 --- a/BTCPayServer.Tests/PSBTTests.cs +++ b/BTCPayServer.Tests/PSBTTests.cs @@ -95,7 +95,7 @@ namespace BTCPayServer.Tests Assert.Equal(2 + 1, psbtReady.Destinations.Count); // The fee is a destination Assert.Contains(psbtReady.Destinations, d => d.Destination == sendDestination && !d.Positive); Assert.Contains(psbtReady.Destinations, d => d.Positive); - + vmPSBT.PSBT = unsignedPSBT.ToBase64(); var combineVM = await walletController.WalletPSBT(walletId, vmPSBT, "combine").AssertViewModelAsync(); Assert.Equal(vmPSBT.PSBT, combineVM.OtherPSBT); diff --git a/BTCPayServer.Tests/PayJoinTests.cs b/BTCPayServer.Tests/PayJoinTests.cs index 93723d36d..0d46de989 100644 --- a/BTCPayServer.Tests/PayJoinTests.cs +++ b/BTCPayServer.Tests/PayJoinTests.cs @@ -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(); 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(); @@ -300,7 +300,7 @@ namespace BTCPayServer.Tests var bip21 = s.Driver.FindElement(By.ClassName("payment__details__instruction__open-wallet__btn")) .GetAttribute("href"); Assert.Contains($"{PayjoinClient.BIP21EndpointKey}=", bip21); - + s.GoToWalletSettings(receiver.storeId, cryptoCode); Assert.True(s.Driver.FindElement(By.Id("PayJoinEnabled")).Selected); @@ -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), @@ -940,7 +940,7 @@ retry: coin5 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.025m); coin6 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.026m); }); - + var signingKeySettings = derivationSchemeSettings.GetSigningAccountKeySettings(); signingKeySettings.RootFingerprint = diff --git a/BTCPayServer.Tests/PaymentRequestTests.cs b/BTCPayServer.Tests/PaymentRequestTests.cs index 6525c3a3c..265a0afab 100644 --- a/BTCPayServer.Tests/PaymentRequestTests.cs +++ b/BTCPayServer.Tests/PaymentRequestTests.cs @@ -32,7 +32,7 @@ namespace BTCPayServer.Tests user.RegisterDerivationScheme("BTC"); var user2 = tester.NewAccount(); - + await user2.GrantAccessAsync(); var paymentRequestController = user.GetController(); @@ -51,7 +51,7 @@ namespace BTCPayServer.Tests .RouteValues.Values.Last().ToString(); paymentRequestController.HttpContext.SetPaymentRequestData(new PaymentRequestData { Id = id, StoreDataId = request.StoreId }); - + // Permission guard for guests editing Assert .IsType(guestpaymentRequestController.EditPaymentRequest(user.StoreId, id)); @@ -78,7 +78,7 @@ namespace BTCPayServer.Tests Assert.Empty(Assert .IsType(Assert .IsType(await paymentRequestController.GetPaymentRequests(user.StoreId)).Model).Items); - + // Unarchive Assert .IsType(await paymentRequestController.TogglePaymentRequestArchival(id)); diff --git a/BTCPayServer.Tests/SeleniumTester.cs b/BTCPayServer.Tests/SeleniumTester.cs index ab73c9d80..8d15e1d6f 100644 --- a/BTCPayServer.Tests/SeleniumTester.cs +++ b/BTCPayServer.Tests/SeleniumTester.cs @@ -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 { @@ -82,7 +82,7 @@ namespace BTCPayServer.Tests GoToRegister(); Driver.AssertNoError(); } - + /// /// Use this ServerUri when trying to browse with selenium /// Because for some reason, the selenium container can't resolve the tests container domain name @@ -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) { @@ -187,7 +187,7 @@ namespace BTCPayServer.Tests Driver.FindElement(By.Id("ScriptPubKeyType")).Click(); Driver.FindElement(By.CssSelector($"#ScriptPubKeyType option[value={format}]")).Click(); - + Driver.ToggleCollapse("AdvancedSettings"); Driver.SetCheckbox(By.Id("ImportKeysToRPC"), importkeys); Driver.FindElement(By.Id("Continue")).Click(); @@ -210,7 +210,7 @@ namespace BTCPayServer.Tests Driver.FindElement(By.Id("confirm")).Click(); Driver.FindElement(By.Id("submit")).Click(); } - + WalletId = new WalletId(StoreId, cryptoCode); return new Mnemonic(seed); } @@ -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 @@ -402,9 +402,9 @@ namespace BTCPayServer.Tests } public string CreateInvoice( - string storeId, - decimal? amount = 100, - string currency = "USD", + string storeId, + decimal? amount = 100, + string currency = "USD", string refundEmail = "", string defaultPaymentMethod = null, bool? requiresRefundEmail = null, diff --git a/BTCPayServer.Tests/SeleniumTests.cs b/BTCPayServer.Tests/SeleniumTests.cs index 7eef619f4..82d9ea40c 100644 --- a/BTCPayServer.Tests/SeleniumTests.cs +++ b/BTCPayServer.Tests/SeleniumTests.cs @@ -122,7 +122,7 @@ namespace BTCPayServer.Tests s.Driver.FindElement(By.Id("Email")).SendKeys(u2.RegisterDetails.Email); s.Driver.FindElement(By.Id("save")).Click(); - Assert.Contains("The email address is already in use with an other account.", + Assert.Contains("The email address is already in use with an other account.", s.FindAlertMessage(StatusMessageModel.StatusSeverity.Error).Text); s.GoToProfile(); @@ -402,11 +402,11 @@ namespace BTCPayServer.Tests Assert.DoesNotContain("Archived", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text); s.Driver.FindElement(By.Id("btn-archive-toggle")).Click(); Assert.Contains("Unarchive", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text); - + //check that it no longer appears in list s.GoToInvoices(storeId); Assert.DoesNotContain(invoiceId, s.Driver.PageSource); - + //ok, let's unarchive and see that it shows again s.Driver.Navigate().GoToUrl(invoiceUrl); s.Driver.FindElement(By.Id("btn-archive-toggle")).Click(); @@ -422,7 +422,7 @@ namespace BTCPayServer.Tests s.Driver.Navigate().GoToUrl(invoiceUrl); Assert.Contains("ReturnUrl", s.Driver.Url); s.GoToRegister(); - + // When logged in as different user we should not be able to access store and invoice details var bob = s.RegisterNewUser(); s.Driver.Navigate().GoToUrl(storeUrl); @@ -900,13 +900,13 @@ namespace BTCPayServer.Tests s.Driver.FindElement(By.Id("AccountKeys_0__MasterFingerprint")).GetAttribute("value")); Assert.Contains("m/84'/1'/0'", s.Driver.FindElement(By.Id("AccountKeys_0__AccountKeyPath")).GetAttribute("value")); - + s.Driver.FindElement(By.Id($"StoreNav-Wallet{cryptoCode}")).Click(); - + // Make sure we can rescan, because we are admin! s.Driver.FindElement(By.Id("SectionNav-Rescan")).Click(); Assert.Contains("The batch size make sure", s.Driver.PageSource); - + // Check the tx sent earlier arrived s.Driver.FindElement(By.Id("SectionNav-Transactions")).Click(); @@ -1110,7 +1110,7 @@ namespace BTCPayServer.Tests //offline/external payout test s.Driver.FindElement(By.Id("NotificationsHandle")).Click(); s.Driver.FindElement(By.CssSelector("#notificationsForm button")).Click(); - + var newStore = s.CreateNewStore(); s.GenerateWallet("BTC", "", true, true); var newWalletId = new WalletId(newStore.storeId, "BTC"); @@ -1170,7 +1170,7 @@ namespace BTCPayServer.Tests var paymentMethodOptions = s.Driver.FindElements(By.CssSelector("input[name='PaymentMethods']")); Assert.Equal(2, paymentMethodOptions.Count); - + s.Driver.FindElement(By.Id("Name")).SendKeys("Lightning Test"); s.Driver.FindElement(By.Id("Amount")).Clear(); s.Driver.FindElement(By.Id("Amount")).SendKeys(payoutAmount.ToString()); @@ -1306,7 +1306,7 @@ namespace BTCPayServer.Tests Assert.DoesNotContain("show", s.Driver.FindElement(By.Id("LNURLSettings")).GetAttribute("class")); s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true); SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode); - + // Topup Invoice test var i = s.CreateInvoice(storeId, null, cryptoCode); s.GoToInvoiceCheckout(i); @@ -1331,7 +1331,7 @@ namespace BTCPayServer.Tests // Initial bolt was cancelled await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr); }); - + await s.Server.CustomerLightningD.Pay(lnurlResponse2.Pr); await TestUtils.EventuallyAsync(async () => { @@ -1374,7 +1374,7 @@ namespace BTCPayServer.Tests await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr); Assert.Equal(new LightMoney(0.0000001m, LightMoneyUnit.BTC), lnurlResponse2.GetPaymentRequest(network).MinimumAmount); - + s.GoToLightningSettings(s.StoreId, cryptoCode); // LNURL is enabled and settings are expanded Assert.True(s.Driver.FindElement(By.Id("LNURLEnabled")).Selected); @@ -1382,7 +1382,7 @@ namespace BTCPayServer.Tests s.Driver.SetCheckbox(By.Id("LNURLStandardInvoiceEnabled"), false); s.Driver.FindElement(By.Id("save")).Click(); Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text); - + i = s.CreateInvoice(storeId, 0.000001m, cryptoCode); s.GoToInvoiceCheckout(i); s.Driver.FindElement(By.ClassName("payment__currencies_noborder")); @@ -1398,7 +1398,7 @@ namespace BTCPayServer.Tests s.Driver.SetCheckbox(By.Id("DisableBolt11PaymentMethod"), true); s.Driver.FindElement(By.Id("save")).Click(); Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text); - + // Ensure the toggles are set correctly s.GoToLightningSettings(s.StoreId, cryptoCode); @@ -1406,11 +1406,11 @@ namespace BTCPayServer.Tests // checkboxes is not good choice here, in next release we should have multi choice instead Assert.False(s.Driver.FindElement(By.Id("LNURLBech32Mode")).Selected); Assert.False(s.Driver.FindElement(By.Id("LNURLStandardInvoiceEnabled")).Selected); - + //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); @@ -1419,7 +1419,7 @@ namespace BTCPayServer.Tests lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value"); Assert.StartsWith("lnurlp", lnurl); LNURL.LNURL.Parse(lnurl, out tag); - + s.GoToHome(); var newStore = s.CreateNewStore(false); s.AddLightningNode(cryptoCode, LightningConnectionType.LndREST, false); @@ -1433,11 +1433,11 @@ namespace BTCPayServer.Tests s.Driver.FindElement(By.Id("copy-tab")).Click(); lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value"); parsed = LNURL.LNURL.Parse(lnurl, out tag); - + // 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"); @@ -1449,7 +1449,7 @@ namespace BTCPayServer.Tests s.Driver.FindElement(By.Id("ClaimedAmount")).Clear(); s.Driver.FindElement(By.Id("ClaimedAmount")).SendKeys("0.0000001" + Keys.Enter); s.FindAlertMessage(); - + s.GoToStore(s.StoreId, StoreNavPages.PullPayments); var payouts = s.Driver.FindElements(By.ClassName("pp-payout")); payouts[0].Click(); @@ -1494,11 +1494,11 @@ namespace BTCPayServer.Tests s.AddLightningNode("BTC", LightningConnectionType.LndREST, false); //ensure ln address is not available as lnurl is not configured s.Driver.AssertElementNotFound(By.Id("StoreNav-LightningAddress")); - + s.GoToLightningSettings(s.StoreId, cryptoCode); s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true); SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode); - + s.Driver.FindElement(By.Id("StoreNav-LightningAddress")).Click(); s.Driver.ToggleCollapse("AddAddress"); @@ -1534,8 +1534,8 @@ 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) { case { } v when v.StartsWith(lnaddress2): @@ -1562,20 +1562,20 @@ namespace BTCPayServer.Tests var code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value"); s.Driver.FindElement(By.Id("regeneratecode")).Click(); Assert.NotEqual(code, s.Driver.FindElement(By.Id("logincode")).GetAttribute("value")); - + code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value"); s.Logout(); s.GoToLogin(); s.Driver.SetAttribute("LoginCode", "value", "bad code"); s.Driver.InvokeJSFunction("logincode-form", "submit"); - - + + s.Driver.SetAttribute("LoginCode", "value", code); s.Driver.InvokeJSFunction("logincode-form", "submit"); s.GoToProfile(); Assert.Contains(user, s.Driver.PageSource); } - + // For god know why, selenium have problems clicking on the save button, resulting in ultimate hacks // to make it works. diff --git a/BTCPayServer.Tests/TestAccount.cs b/BTCPayServer.Tests/TestAccount.cs index 7a75963b1..481d76561 100644 --- a/BTCPayServer.Tests/TestAccount.cs +++ b/BTCPayServer.Tests/TestAccount.cs @@ -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; @@ -141,7 +141,7 @@ namespace BTCPayServer.Tests modify(paymentMethods); await storeController.PaymentMethods(paymentMethods); } - + public async Task ModifyWalletSettings(Action modify) { var storeController = GetController(); @@ -150,7 +150,7 @@ namespace BTCPayServer.Tests modify(walletSettings); storeController.UpdateWalletSettings(walletSettings).GetAwaiter().GetResult(); } - + public async Task ModifyOnchainPaymentSettings(Action modify) { var storeController = GetController(); @@ -227,7 +227,7 @@ namespace BTCPayServer.Tests //this addresses an obscure issue where LockSubscription is unintentionally set to "true", //resulting in a large number of tests failing. - if (account.RegisteredUserId == null) + if (account.RegisteredUserId == null) { var settings = parent.PayTester.GetService(); var policies = await settings.GetSettingAsync() ?? new PoliciesSettings(); @@ -470,7 +470,7 @@ namespace BTCPayServer.Tests public TEvent AssertHasWebhookEvent(WebhookEventType eventType, Action assert) where TEvent : class { int retry = 0; - retry: +retry: foreach (var evt in WebhookEvents) { if (evt.Type == eventType) diff --git a/BTCPayServer.Tests/UnitTest1.cs b/BTCPayServer.Tests/UnitTest1.cs index 204bf7c30..0c09ce224 100644 --- a/BTCPayServer.Tests/UnitTest1.cs +++ b/BTCPayServer.Tests/UnitTest1.cs @@ -159,7 +159,7 @@ namespace BTCPayServer.Tests Assert.True(valid); } } - + [Fact] [Trait("Integration", "Integration")] public async Task EnsureSwaggerPermissionsDocumented() @@ -171,7 +171,7 @@ namespace BTCPayServer.Tests var description = "BTCPay Server supports authenticating and authorizing users through an API Key that is generated by them. Send the API Key as a header value to Authorization with the format: `token {token}`. For a smoother experience, you can generate a url that redirects users to an API key creation screen.\n\n The following permissions are available to the context of the user creating the API Key:\n\n#OTHERPERMISSIONS#\n\nThe following permissions are available if the user is an administrator:\n\n#SERVERPERMISSIONS#\n\nThe following permissions applies to all stores of the user, you can limit to a specific store with the following format: `btcpay.store.cancreateinvoice:6HSHAEU4iYWtjxtyRs9KyPjM9GAQp8kw2T9VWbGG1FnZ`:\n\n#STOREPERMISSIONS#\n\nNote that API Keys only limits permission of a user and can never expand it. If an API Key has the permission `btcpay.server.canmodifyserversettings` but that the user account creating this API Key is not administrator, the API Key will not be able to modify the server settings.\nSome permissions may include other permissions, see [this operation](#operation/permissionsMetadata).\n"; - + var storePolicies = ManageController.AddApiKeyViewModel.PermissionValueItem.PermissionDescriptions.Where(pair => Policies.IsStorePolicy(pair.Key) && !pair.Key.EndsWith(":", StringComparison.InvariantCulture)); @@ -189,7 +189,7 @@ namespace BTCPayServer.Tests .Replace("#STOREPERMISSIONS#", string.Join("\n", storePolicies.Select(pair => $"* `{pair.Key}`: {pair.Value.Title}"))); TestLogs.LogInformation(description); - + var sresp = Assert .IsType(await tester.PayTester.GetController(acc.UserId, acc.StoreId) .Swagger()).Value.ToJson(); @@ -350,7 +350,7 @@ namespace BTCPayServer.Tests Assert.Equal(0, result.Content.Headers.ContentLength.Value); } } - + [Fact(Timeout = 60 * 2 * 1000)] [Trait("Integration", "Integration")] [Trait("Lightning", "Lightning")] @@ -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 () => @@ -384,7 +384,7 @@ namespace BTCPayServer.Tests Assert.Equal(newInvoice.BtcDue.GetValue(), BOLT11PaymentRequest.Parse(newBolt11, Network.RegTest).MinimumAmount.ToDecimal(LightMoneyUnit.BTC)); }, 40000); - + TestLogs.LogInformation($"Paying invoice {newInvoice.Id} remaining due amount {newInvoice.BtcDue.GetValue()} via lightning"); var evt = await tester.WaitForEvent(async () => { @@ -401,7 +401,7 @@ namespace BTCPayServer.Tests { await tester.SendLightningPaymentAsync(invoice); }); - + //NOTE: Eclair does not support cancelling invoice so the below test case would make sense for it // TestLogs.LogInformation($"Paying invoice {invoice.Id} original full amount bolt11 invoice "); // evt = await tester.WaitForEvent(async () => @@ -1354,7 +1354,7 @@ namespace BTCPayServer.Tests rng = new Random(seed); TestLogs.LogInformation("Seed: " + seed); foreach (var networkFeeMode in Enum.GetValues(typeof(NetworkFeeMode)).Cast()) - { + { await user.SetNetworkFeeMode(networkFeeMode); await AssertTopUpBtcPrice(tester, user, Money.Coins(1.0m), 5000.0m, networkFeeMode); await AssertTopUpBtcPrice(tester, user, Money.Coins(1.23456789m), 5000.0m * 1.23456789m, networkFeeMode); @@ -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); } } @@ -1990,7 +1990,7 @@ namespace BTCPayServer.Tests }); } } - + [Fact(Timeout = LongRunningTestTimeout)] [Trait("Integration", "Integration")] public async Task CanCreateAndDeleteApps() @@ -2043,7 +2043,7 @@ namespace BTCPayServer.Tests var user = tester.NewAccount(); user.GrantAccess(true); user.RegisterDerivationScheme("BTC"); - + DateTimeOffset expiration = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(21); // This should fail, the amount is too low to be above the dust limit of bitcoin @@ -2112,7 +2112,7 @@ namespace BTCPayServer.Tests var zeroInvoice = await greenfield.CreateInvoice(user.StoreId, new CreateInvoiceRequest() { Amount = 0m, - Currency = "USD" + Currency = "USD" }); Assert.Equal(InvoiceStatus.New, zeroInvoice.Status); await TestUtils.EventuallyAsync(async () => @@ -2312,20 +2312,20 @@ 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); - + }); user.AssertHasWebhookEvent(WebhookEventType.InvoicePaymentSettled, 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); + Assert.StartsWith(txId.ToString(), c.Payment.Id); }); } } @@ -2525,7 +2525,7 @@ namespace BTCPayServer.Tests var acc = tester.NewAccount(); await acc.GrantAccessAsync(true); await acc.CreateStoreAsync(); - + // Test if legacy DerivationStrategy column is converted to DerivationStrategies var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId); var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav"; @@ -2540,7 +2540,7 @@ namespace BTCPayServer.Tests Assert.Equal(derivation, v.AccountOriginal.ToString()); Assert.Equal(xpub, v.SigningKey.ToString()); Assert.Equal(xpub, v.GetSigningAccountKeySettings().AccountKey.ToString()); - + await acc.RegisterLightningNodeAsync("BTC", LightningConnectionType.CLightning, true); store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId); var lnMethod = store.GetSupportedPaymentMethods(tester.NetworkProvider).OfType().First(); @@ -2687,37 +2687,37 @@ namespace BTCPayServer.Tests var settings = tester.PayTester.GetService(); var emailSenderFactory = tester.PayTester.GetService(); - + Assert.Null(await Assert.IsType(await emailSenderFactory.GetEmailSender()).GetEmailSettings()); Assert.Null(await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()); - + await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = false }); await settings.UpdateSetting(new EmailSettings() { - From = "admin@admin.com", - Login = "admin@admin.com", - Password = "admin@admin.com", - Port = 1234, - Server = "admin.com", + From = "admin@admin.com", + Login = "admin@admin.com", + Password = "admin@admin.com", + Port = 1234, + Server = "admin.com", }); - Assert.Equal("admin@admin.com",(await Assert.IsType(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); - Assert.Equal("admin@admin.com",(await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); + Assert.Equal("admin@admin.com", (await Assert.IsType(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); + Assert.Equal("admin@admin.com", (await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = true }); - Assert.Equal("admin@admin.com",(await Assert.IsType(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); + Assert.Equal("admin@admin.com", (await Assert.IsType(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); Assert.Null(await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()); Assert.IsType(await acc.GetController().Emails(acc.StoreId, new EmailsViewModel(new EmailSettings() { - From = "store@store.com", + From = "store@store.com", Login = "store@store.com", Password = "store@store.com", Port = 1234, Server = "store.com" }), "")); - - Assert.Equal("store@store.com",(await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); + + Assert.Equal("store@store.com", (await Assert.IsType(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); } } diff --git a/BTCPayServer/Components/MainNav/MainNav.cs b/BTCPayServer/Components/MainNav/MainNav.cs index bac91064a..40159fcfc 100644 --- a/BTCPayServer/Components/MainNav/MainNav.cs +++ b/BTCPayServer/Components/MainNav/MainNav.cs @@ -31,7 +31,7 @@ namespace BTCPayServer.Components.MainNav AppService appService, StoreRepository storeRepo, StoresController storesController, - BTCPayNetworkProvider networkProvider, + BTCPayNetworkProvider networkProvider, UserManager userManager, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary) { @@ -53,13 +53,13 @@ namespace BTCPayServer.Components.MainNav if (store != null) { var storeBlob = store.GetStoreBlob(); - + // Wallets - _storesController.AddPaymentMethods(store, storeBlob, + _storesController.AddPaymentMethods(store, storeBlob, out var derivationSchemes, out var lightningNodes); vm.DerivationSchemes = derivationSchemes; vm.LightningNodes = lightningNodes; - + // Apps var apps = await _appService.GetAllApps(UserId, false, store.Id); vm.Apps = apps.Select(a => new StoreApp @@ -70,7 +70,7 @@ namespace BTCPayServer.Components.MainNav IsOwner = a.IsOwner }).ToList(); } - + return View(vm); } diff --git a/BTCPayServer/Components/MainNav/MainNavViewModel.cs b/BTCPayServer/Components/MainNav/MainNavViewModel.cs index 4f777095a..3a2c491c3 100644 --- a/BTCPayServer/Components/MainNav/MainNavViewModel.cs +++ b/BTCPayServer/Components/MainNav/MainNavViewModel.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Components.MainNav public List Apps { get; set; } public bool AltcoinsBuild { get; set; } } - + public class StoreApp { public string Id { get; set; } diff --git a/BTCPayServer/Components/StoreSelector/StoreSelector.cs b/BTCPayServer/Components/StoreSelector/StoreSelector.cs index 90d8ad8a6..b3c20d0e3 100644 --- a/BTCPayServer/Components/StoreSelector/StoreSelector.cs +++ b/BTCPayServer/Components/StoreSelector/StoreSelector.cs @@ -15,7 +15,7 @@ namespace BTCPayServer.Components.StoreSelector private readonly UserManager _userManager; public StoreSelector( - StoreRepository storeRepo, + StoreRepository storeRepo, BTCPayNetworkProvider networkProvider, UserManager userManager) { @@ -47,14 +47,14 @@ namespace BTCPayServer.Components.StoreSelector }; }) .ToList(); - + var vm = new StoreSelectorViewModel { Options = options, CurrentStoreId = currentStore?.Id, CurrentDisplayName = currentStore?.StoreName }; - + return View(vm); } } diff --git a/BTCPayServer/Components/StoreSelector/StoreSelectorViewModel.cs b/BTCPayServer/Components/StoreSelector/StoreSelectorViewModel.cs index ff7c97591..1a77b2ee7 100644 --- a/BTCPayServer/Components/StoreSelector/StoreSelectorViewModel.cs +++ b/BTCPayServer/Components/StoreSelector/StoreSelectorViewModel.cs @@ -8,7 +8,7 @@ namespace BTCPayServer.Components.StoreSelector public string CurrentStoreId { get; set; } public string CurrentDisplayName { get; set; } } - + public class StoreSelectorOption { public bool Selected { get; set; } diff --git a/BTCPayServer/Configuration/BTCPayServerOptions.cs b/BTCPayServer/Configuration/BTCPayServerOptions.cs index 8a3bcf51f..e800e593d 100644 --- a/BTCPayServer/Configuration/BTCPayServerOptions.cs +++ b/BTCPayServer/Configuration/BTCPayServerOptions.cs @@ -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; @@ -59,20 +59,20 @@ namespace BTCPayServer.Configuration public void LoadArgs(IConfiguration conf, Logs Logs) { NetworkType = DefaultConfiguration.GetNetworkType(conf); - + Logs.Configuration.LogInformation("Network: " + NetworkType.ToString()); if (conf.GetOrDefault("launchsettings", false) && NetworkType != ChainName.Regtest) throw new ConfigException($"You need to run BTCPayServer with the run.sh or run.ps1 script"); - - + + BundleJsCss = conf.GetOrDefault("bundlejscss", true); DockerDeployment = conf.GetOrDefault("dockerdeployment", true); TorrcFile = conf.GetOrDefault("torrcfile", null); TorServices = conf.GetOrDefault("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("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"); diff --git a/BTCPayServer/Configuration/NBXplorerConnectionSetting.cs b/BTCPayServer/Configuration/NBXplorerConnectionSetting.cs index 309c5992f..c2d88e61f 100644 --- a/BTCPayServer/Configuration/NBXplorerConnectionSetting.cs +++ b/BTCPayServer/Configuration/NBXplorerConnectionSetting.cs @@ -8,4 +8,4 @@ namespace BTCPayServer.Configuration public Uri ExplorerUri { get; internal set; } public string CookieFile { get; internal set; } } -} \ No newline at end of file +} diff --git a/BTCPayServer/Controllers/AccountController.cs b/BTCPayServer/Controllers/AccountController.cs index 32f82eb61..64a4a71a3 100644 --- a/BTCPayServer/Controllers/AccountController.cs +++ b/BTCPayServer/Controllers/AccountController.cs @@ -108,8 +108,8 @@ namespace BTCPayServer.Controllers ModelState.AddModelError(string.Empty, "Login code was invalid"); return await Login(returnUrl, null); - } - var user = await _userManager.FindByIdAsync(userId); + } + var user = await _userManager.FindByIdAsync(userId); _logger.LogInformation("User with ID {UserId} logged in with a login code.", user.Id); await _signInManager.SignInAsync(user, false, "LoginCode"); @@ -150,9 +150,9 @@ namespace BTCPayServer.Controllers ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } - + var fido2Devices = await _fido2Service.HasCredentials(user.Id); - if (!await _userManager.IsLockedOutAsync(user) && fido2Devices) + if (!await _userManager.IsLockedOutAsync(user) && fido2Devices) { if (await _userManager.CheckPasswordAsync(user, model.Password)) { @@ -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) { @@ -534,17 +539,17 @@ namespace BTCPayServer.Controllers { throw new ApplicationException($"Unable to load user with ID '{userId}'."); } - + var result = await _userManager.ConfirmEmailAsync(user, code); if (!await _userManager.HasPasswordAsync(user)) { - + TempData.SetStatusMessageModel(new StatusMessageModel() { 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)); } diff --git a/BTCPayServer/Controllers/AppsController.Crowdfund.cs b/BTCPayServer/Controllers/AppsController.Crowdfund.cs index 984accae9..3d417bde8 100644 --- a/BTCPayServer/Controllers/AppsController.Crowdfund.cs +++ b/BTCPayServer/Controllers/AppsController.Crowdfund.cs @@ -30,7 +30,7 @@ namespace BTCPayServer.Controllers var app = GetCurrentApp(); if (app == null) return NotFound(); - + var settings = app.GetSettings(); var vm = new UpdateCrowdfundViewModel { @@ -68,14 +68,14 @@ namespace BTCPayServer.Controllers }; return View(vm); } - + [HttpPost("{appId}/settings/crowdfund")] public async Task UpdateCrowdfund(string appId, UpdateCrowdfundViewModel vm, string command) { var app = GetCurrentApp(); if (app == null) return NotFound(); - + vm.TargetCurrency = await GetStoreDefaultCurrentIfEmpty(app.StoreDataId, vm.TargetCurrency); if (_currencies.GetCurrencyData(vm.TargetCurrency, false) == null) ModelState.AddModelError(nameof(vm.TargetCurrency), "Invalid currency"); diff --git a/BTCPayServer/Controllers/AppsController.PointOfSale.cs b/BTCPayServer/Controllers/AppsController.PointOfSale.cs index 2c3dc13d1..f85f94e60 100644 --- a/BTCPayServer/Controllers/AppsController.PointOfSale.cs +++ b/BTCPayServer/Controllers/AppsController.PointOfSale.cs @@ -76,7 +76,7 @@ namespace BTCPayServer.Controllers public string CustomTipText { get; set; } = CUSTOM_TIP_TEXT_DEF; public static readonly int[] CUSTOM_TIP_PERCENTAGES_DEF = new int[] { 15, 18, 20 }; public int[] CustomTipPercentages { get; set; } = CUSTOM_TIP_PERCENTAGES_DEF; - + public string CustomCSSLink { get; set; } public string EmbeddedCSS { get; set; } @@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers var app = GetCurrentApp(); if (app == null) return NotFound(); - + var settings = app.GetSettings(); settings.DefaultView = settings.EnableShoppingCart ? PosViewType.Cart : settings.DefaultView; settings.EnableShoppingCart = false; @@ -167,7 +167,7 @@ namespace BTCPayServer.Controllers var app = GetCurrentApp(); if (app == null) return NotFound(); - + if (!ModelState.IsValid) return View(vm); @@ -213,14 +213,14 @@ namespace BTCPayServer.Controllers TempData[WellKnownTempData.SuccessMessage] = "App updated"; return RedirectToAction(nameof(UpdatePointOfSale), new { appId }); } - + private int[] ListSplit(string list, string separator = ",") { if (string.IsNullOrEmpty(list)) { return Array.Empty(); } - + // Remove all characters except numeric and comma Regex charsToDestroy = new Regex(@"[^\d|\" + separator + "]"); list = charsToDestroy.Replace(list, ""); diff --git a/BTCPayServer/Controllers/AppsController.cs b/BTCPayServer/Controllers/AppsController.cs index fad685b0a..6b501e92b 100644 --- a/BTCPayServer/Controllers/AppsController.cs +++ b/BTCPayServer/Controllers/AppsController.cs @@ -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; @@ -41,10 +41,10 @@ namespace BTCPayServer.Controllers private readonly AppService _appService; public string CreatedAppId { get; set; } - + [HttpGet("/stores/{storeId}/apps")] public async Task ListApps( - string storeId, + string storeId, string sortOrder = null, string sortOrderColumn = null ) @@ -52,9 +52,9 @@ namespace BTCPayServer.Controllers var store = GetCurrentStore(); var apps = await _appService.GetAllApps(GetUserId(), false, store.Id); - if (sortOrder != null && sortOrderColumn != null) + if (sortOrder != null && sortOrderColumn != null) { - apps = apps.OrderByDescending(app => + apps = apps.OrderByDescending(app => { switch (sortOrderColumn) { @@ -80,7 +80,7 @@ namespace BTCPayServer.Controllers break; } } - + return View(new ListAppsViewModel { Apps = apps @@ -151,7 +151,7 @@ namespace BTCPayServer.Controllers var app = GetCurrentApp(); if (app == null) return NotFound(); - + return View("Confirm", new ConfirmModel("Delete app", $"The app {app.Name} and its settings will be permanently deleted. Are you sure?", "Delete")); } @@ -161,10 +161,10 @@ namespace BTCPayServer.Controllers var app = GetCurrentApp(); if (app == null) return NotFound(); - + if (await _appService.DeleteApp(app)) TempData[WellKnownTempData.SuccessMessage] = "App deleted successfully."; - + return RedirectToAction(nameof(ListApps), new { storeId = app.StoreDataId }); } @@ -180,7 +180,7 @@ namespace BTCPayServer.Controllers private string GetUserId() => _userManager.GetUserId(User); private StoreData GetCurrentStore() => HttpContext.GetStoreData(); - + private AppData GetCurrentApp() => HttpContext.GetAppData(); } } diff --git a/BTCPayServer/Controllers/AppsPublicController.cs b/BTCPayServer/Controllers/AppsPublicController.cs index 527dadccb..f631a902a 100644 --- a/BTCPayServer/Controllers/AppsPublicController.cs +++ b/BTCPayServer/Controllers/AppsPublicController.cs @@ -43,19 +43,19 @@ namespace BTCPayServer.Controllers [HttpGet("/apps/{appId}")] public async Task RedirectToApp(string appId) { - + 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(); } - + [HttpGet] [Route("/")] [Route("/apps/{appId}/pos/{viewType?}")] @@ -122,7 +122,7 @@ namespace BTCPayServer.Controllers string notificationUrl, string redirectUrl, string choiceKey, - string posData = null, + string posData = null, RequiresRefundEmail requiresRefundEmail = RequiresRefundEmail.InheritFromStore, CancellationToken cancellationToken = default) { @@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers if (choice == null) return NotFound(); title = choice.Title; - if (choice.Price.Type == ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup) + if (choice.Price.Type == ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup) { price = null; } @@ -160,7 +160,7 @@ namespace BTCPayServer.Controllers if (amount > price) price = amount; } - + if (choice.Inventory.HasValue) { @@ -230,7 +230,7 @@ namespace BTCPayServer.Controllers PosData = string.IsNullOrEmpty(posData) ? null : posData, RedirectAutomatically = settings.RedirectAutomatically, SupportedTransactionCurrencies = paymentMethods, - RequiresRefundEmail = requiresRefundEmail == RequiresRefundEmail.InheritFromStore + RequiresRefundEmail = requiresRefundEmail == RequiresRefundEmail.InheritFromStore ? store.GetStoreBlob().RequiresRefundEmail : requiresRefundEmail == RequiresRefundEmail.On, }, store, HttpContext.Request.GetAbsoluteRoot(), @@ -274,7 +274,7 @@ namespace BTCPayServer.Controllers return NotFound("A Target Currency must be set for this app in order to be loadable."); } var appInfo = await GetAppInfo(appId); - + if (settings.Enabled) return View(appInfo); if (!isAdmin) @@ -292,7 +292,7 @@ namespace BTCPayServer.Controllers [DomainMappingConstraintAttribute(AppType.Crowdfund)] public async Task ContributeToCrowdfund(string appId, ContributeToCrowdfund request, CancellationToken cancellationToken) { - + var app = await _AppService.GetApp(appId, AppType.Crowdfund, true); if (app == null) diff --git a/BTCPayServer/Controllers/GreenField/HealthController.cs b/BTCPayServer/Controllers/GreenField/HealthController.cs index 6509f527f..05aa47cb2 100644 --- a/BTCPayServer/Controllers/GreenField/HealthController.cs +++ b/BTCPayServer/Controllers/GreenField/HealthController.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Controllers.GreenField { private readonly NBXplorerDashboard _dashBoard; - public HealthController(NBXplorerDashboard dashBoard ) + public HealthController(NBXplorerDashboard dashBoard) { _dashBoard = dashBoard; } diff --git a/BTCPayServer/Controllers/GreenField/InvoiceController.cs b/BTCPayServer/Controllers/GreenField/InvoiceController.cs index 2aaf7e96b..72f5f1396 100644 --- a/BTCPayServer/Controllers/GreenField/InvoiceController.cs +++ b/BTCPayServer/Controllers/GreenField/InvoiceController.cs @@ -53,7 +53,7 @@ namespace BTCPayServer.Controllers.GreenField [FromQuery] [ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))] DateTimeOffset? startDate = null, - [FromQuery] + [FromQuery] [ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))] DateTimeOffset? endDate = null, [FromQuery] string? textSearch = null, @@ -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, @@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers.GreenField return Ok(invoices.Select(ToModel)); } - + [Authorize(Policy = Policies.CanViewInvoices, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}")] @@ -283,7 +283,7 @@ namespace BTCPayServer.Controllers.GreenField await _invoiceRepository.ToggleInvoiceArchival(invoiceId, false, storeId); return await GetInvoice(storeId, invoiceId); } - + [Authorize(Policy = Policies.CanViewInvoices, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}/payment-methods")] @@ -369,7 +369,7 @@ namespace BTCPayServer.Controllers.GreenField }; }).ToArray(); } - + public static InvoicePaymentMethodDataModel.Payment ToPaymentModel(InvoiceEntity entity, PaymentEntity paymentEntity) { var data = paymentEntity.GetCryptoPaymentData(); diff --git a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Internal.cs b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Internal.cs index 99ec79e7e..9b59b80d8 100644 --- a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Internal.cs +++ b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Internal.cs @@ -27,7 +27,7 @@ namespace BTCPayServer.Controllers.GreenField public InternalLightningNodeApiController( - BTCPayNetworkProvider btcPayNetworkProvider, ISettingsRepository settingsRepository, LightningClientFactoryService lightningClientFactory, + BTCPayNetworkProvider btcPayNetworkProvider, ISettingsRepository settingsRepository, LightningClientFactoryService lightningClientFactory, IOptions lightningNetworkOptions, IAuthorizationService authorizationService) : base( btcPayNetworkProvider, settingsRepository, authorizationService) diff --git a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Store.cs b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Store.cs index 250285e3a..f4d015f2f 100644 --- a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Store.cs +++ b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.Store.cs @@ -105,7 +105,7 @@ namespace BTCPayServer.Controllers.GreenField protected override Task GetLightningClient(string cryptoCode, bool doingAdminThings) { - + var network = _btcPayNetworkProvider.GetNetwork(cryptoCode); var store = HttpContext.GetStoreData(); if (store == null || network == null) diff --git a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.cs b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.cs index d6c52b3ad..f5154a3ef 100644 --- a/BTCPayServer/Controllers/GreenField/LightningNodeApiController.cs +++ b/BTCPayServer/Controllers/GreenField/LightningNodeApiController.cs @@ -267,7 +267,7 @@ namespace BTCPayServer.Controllers.GreenField protected async Task CanUseInternalLightning(bool doingAdminThings) { - + return (!doingAdminThings && (await _settingsRepository.GetPolicies()).AllowLightningInternalNodeForAll) || (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanUseInternalLightningNode))).Succeeded; diff --git a/BTCPayServer/Controllers/GreenField/LocalBTCPayServerClient.cs b/BTCPayServer/Controllers/GreenField/LocalBTCPayServerClient.cs index 54cc48a21..d50d366e5 100644 --- a/BTCPayServer/Controllers/GreenField/LocalBTCPayServerClient.cs +++ b/BTCPayServer/Controllers/GreenField/LocalBTCPayServerClient.cs @@ -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 validationErrors}: + case UnprocessableEntityObjectResult { Value: List 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", "")); @@ -612,8 +612,8 @@ namespace BTCPayServer.Controllers.GreenField { HandleActionResult(await _apiKeysController.RevokeKey(apikey)); } - - public override async Task> GetNotifications(bool? seen = null, + + public override async Task> GetNotifications(bool? seen = null, int? skip = null, int? take = null, CancellationToken token = default) { return GetFromActionResult>( @@ -632,7 +632,7 @@ namespace BTCPayServer.Controllers.GreenField { return GetFromActionResult( await _notificationsController.UpdateNotification(notificationId, - new UpdateNotification() {Seen = seen})); + new UpdateNotification() { Seen = seen })); } public override async Task RemoveNotification(string notificationId, CancellationToken token = default) @@ -752,7 +752,7 @@ namespace BTCPayServer.Controllers.GreenField { return GetFromActionResult(await _storesController.UpdateStore(storeId, request)); } - + public override Task> GetStoreLNURLPayPaymentMethods(string storeId, bool? enabled, CancellationToken token = default) @@ -784,7 +784,7 @@ namespace BTCPayServer.Controllers.GreenField _storeLnurlPayPaymentMethodsController.UpdateLNURLPayPaymentMethod(storeId, cryptoCode, paymentMethod)); } - + public override Task> GetStoreLightningNetworkPaymentMethods(string storeId, bool? enabled, CancellationToken token = default) @@ -826,13 +826,13 @@ namespace BTCPayServer.Controllers.GreenField int? skip = null, int? take = null, CancellationToken token = default - + ) { return GetFromActionResult>( 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 GetInvoice(string storeId, string invoiceId, @@ -928,7 +928,7 @@ namespace BTCPayServer.Controllers.GreenField public override async Task GenerateOnChainWallet(string storeId, string cryptoCode, GenerateOnChainWalletRequest request, CancellationToken token = default) { - return GetFromActionResult(await _chainPaymentMethodsController.GenerateOnChainWallet(storeId, cryptoCode, new GenerateWalletRequest() + return GetFromActionResult(await _chainPaymentMethodsController.GenerateOnChainWallet(storeId, cryptoCode, new GenerateWalletRequest() { Passphrase = request.Passphrase, AccountNumber = request.AccountNumber, diff --git a/BTCPayServer/Controllers/GreenField/NotificationsController.cs b/BTCPayServer/Controllers/GreenField/NotificationsController.cs index f94ae17d2..85e351b78 100644 --- a/BTCPayServer/Controllers/GreenField/NotificationsController.cs +++ b/BTCPayServer/Controllers/GreenField/NotificationsController.cs @@ -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 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(); diff --git a/BTCPayServer/Controllers/GreenField/PaymentRequestsController.cs b/BTCPayServer/Controllers/GreenField/PaymentRequestsController.cs index 6f15c1fd6..3c4d34bf6 100644 --- a/BTCPayServer/Controllers/GreenField/PaymentRequestsController.cs +++ b/BTCPayServer/Controllers/GreenField/PaymentRequestsController.cs @@ -164,7 +164,7 @@ namespace BTCPayServer.Controllers.GreenField CustomCSSLink = blob.CustomCSSLink }; } - + private IActionResult PaymentRequestNotFound() { return this.CreateAPIError(404, "payment-request-not-found", "The payment request was not found"); diff --git a/BTCPayServer/Controllers/GreenField/PullPaymentController.cs b/BTCPayServer/Controllers/GreenField/PullPaymentController.cs index 48b46f857..37b6b168d 100644 --- a/BTCPayServer/Controllers/GreenField/PullPaymentController.cs +++ b/BTCPayServer/Controllers/GreenField/PullPaymentController.cs @@ -107,14 +107,14 @@ namespace BTCPayServer.Controllers.GreenField PaymentMethodId.TryParse(s, out var pmi); return pmi; }).ToArray(); - var supported = (await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData())).ToArray(); - for (int i = 0; i < paymentMethods.Length; i++) - { - if (!supported.Contains(paymentMethods[i])) - { - request.AddModelError(paymentRequest => paymentRequest.PaymentMethods[i], "Invalid or unsupported payment method", this); - } - } + var supported = (await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData())).ToArray(); + for (int i = 0; i < paymentMethods.Length; i++) + { + if (!supported.Contains(paymentMethods[i])) + { + request.AddModelError(paymentRequest => paymentRequest.PaymentMethods[i], "Invalid or unsupported payment method", this); + } + } } else { @@ -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)); @@ -232,7 +232,7 @@ namespace BTCPayServer.Controllers.GreenField ModelState.AddModelError(nameof(request.PaymentMethod), "Invalid payment method"); return this.CreateValidationError(ModelState); } - + var payoutHandler = _payoutHandlers.FindPayoutHandler(paymentMethodId); if (payoutHandler is null) { @@ -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); } @@ -404,7 +404,7 @@ namespace BTCPayServer.Controllers.GreenField throw new NotSupportedException(); } } - + private IActionResult PayoutNotFound() { return this.CreateAPIError(404, "payout-not-found", "The payout was not found"); diff --git a/BTCPayServer/Controllers/GreenField/ServerInfoController.cs b/BTCPayServer/Controllers/GreenField/ServerInfoController.cs index 07331c239..5b9a3e2de 100644 --- a/BTCPayServer/Controllers/GreenField/ServerInfoController.cs +++ b/BTCPayServer/Controllers/GreenField/ServerInfoController.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.Controllers.GreenField public GreenFieldServerInfoController( BTCPayServerEnvironment env, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary, - IEnumerablesummaryProviders) + IEnumerable summaryProviders) { _env = env; _paymentMethodHandlerDictionary = paymentMethodHandlerDictionary; @@ -37,7 +37,7 @@ namespace BTCPayServer.Controllers.GreenField var supportedPaymentMethods = _paymentMethodHandlerDictionary .SelectMany(handler => handler.GetSupportedPaymentMethods().Select(id => id.ToString())) .Distinct(); - + ServerInfoData model = new ServerInfoData2 { FullySynched = _summaryProviders.All(provider => provider.AllAvailable()), @@ -48,7 +48,7 @@ namespace BTCPayServer.Controllers.GreenField }; return Ok(model); } - + public class ServerInfoData2 : ServerInfoData { public new IEnumerable SyncStatus { get; set; } diff --git a/BTCPayServer/Controllers/GreenField/StoreLNURLPayPaymentMethodsController.cs b/BTCPayServer/Controllers/GreenField/StoreLNURLPayPaymentMethodsController.cs index 02d19eac7..42052dd58 100644 --- a/BTCPayServer/Controllers/GreenField/StoreLNURLPayPaymentMethodsController.cs +++ b/BTCPayServer/Controllers/GreenField/StoreLNURLPayPaymentMethodsController.cs @@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers.GreenField string storeId, string cryptoCode) { - + AssertCryptoCodeWallet(cryptoCode, out _); var id = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay); @@ -109,7 +109,7 @@ namespace BTCPayServer.Controllers.GreenField [FromBody] LNURLPayPaymentMethodData paymentMethodData) { var paymentMethodId = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay); - + AssertCryptoCodeWallet(cryptoCode, out _); var lnMethod = StoreLightningNetworkPaymentMethodsController.GetExistingLightningLikePaymentMethod(_btcPayNetworkProvider, @@ -130,7 +130,7 @@ namespace BTCPayServer.Controllers.GreenField UseBech32Scheme = paymentMethodData.UseBech32Scheme, EnableForStandardInvoices = paymentMethodData.EnableForStandardInvoices }; - + var store = Store; var storeBlob = store.GetStoreBlob(); store.SetSupportedPaymentMethod(paymentMethodId, paymentMethod); @@ -166,6 +166,6 @@ namespace BTCPayServer.Controllers.GreenField if (network is null) throw new JsonHttpException(this.CreateAPIError(404, "unknown-cryptocode", "This crypto code isn't set up in this BTCPay Server instance")); } - + } } diff --git a/BTCPayServer/Controllers/GreenField/StoreLightningNetworkPaymentMethodsController.cs b/BTCPayServer/Controllers/GreenField/StoreLightningNetworkPaymentMethodsController.cs index 657b40da6..92e55366f 100644 --- a/BTCPayServer/Controllers/GreenField/StoreLightningNetworkPaymentMethodsController.cs +++ b/BTCPayServer/Controllers/GreenField/StoreLightningNetworkPaymentMethodsController.cs @@ -201,7 +201,7 @@ namespace BTCPayServer.Controllers.GreenField return paymentMethod is null ? null : new LightningNetworkPaymentMethodData(paymentMethod.PaymentId.CryptoCode, - paymentMethod.GetDisplayableConnectionString(), !excluded, + paymentMethod.GetDisplayableConnectionString(), !excluded, paymentMethod.PaymentId.ToStringNormalized(), paymentMethod.DisableBOLT11PaymentOption); } diff --git a/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.WalletGeneration.cs b/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.WalletGeneration.cs index ed9e7456c..e055deb86 100644 --- a/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.WalletGeneration.cs +++ b/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.WalletGeneration.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Client; @@ -18,7 +18,7 @@ namespace BTCPayServer.Controllers.GreenField public async Task GenerateOnChainWallet(string storeId, string cryptoCode, GenerateWalletRequest request) { - + AssertCryptoCodeWallet(cryptoCode, out var network, out var wallet); if (!_walletProvider.IsAvailable(network)) @@ -26,7 +26,7 @@ namespace BTCPayServer.Controllers.GreenField return this.CreateAPIError("not-available", $"{cryptoCode} services are not currently available"); } - + var method = GetExistingBtcLikePaymentMethod(cryptoCode); if (method != null) { @@ -91,7 +91,7 @@ namespace BTCPayServer.Controllers.GreenField rawResult.Enabled, rawResult.Label, rawResult.AccountKeyPath, response.GetMnemonic(), derivationSchemeSettings.PaymentId.ToStringNormalized()); return Ok(result); } - + private async Task<(bool HotWallet, bool RPCImport)> CanUseHotWallet() { return await _authorizationService.CanUseHotWallet(await _settingsRepository.GetPolicies(), User); diff --git a/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.cs b/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.cs index fc77c0bcc..4307ff021 100644 --- a/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.cs +++ b/BTCPayServer/Controllers/GreenField/StoreOnChainPaymentMethodsController.cs @@ -179,12 +179,12 @@ namespace BTCPayServer.Controllers.GreenField new OnChainPaymentMethodPreviewResultData. OnChainPaymentMethodPreviewResultAddressItem() - { - KeyPath = deposit.GetKeyPath((uint)i).ToString(), - Address = strategy.Network.NBXplorerNetwork.CreateAddress(strategy.AccountDerivation, + { + KeyPath = deposit.GetKeyPath((uint)i).ToString(), + Address = strategy.Network.NBXplorerNetwork.CreateAddress(strategy.AccountDerivation, line.KeyPathTemplate.GetKeyPath((uint)i), derivation.ScriptPubKey).ToString() - }); + }); } return Ok(result); diff --git a/BTCPayServer/Controllers/GreenField/StoreOnChainWalletsController.cs b/BTCPayServer/Controllers/GreenField/StoreOnChainWalletsController.cs index 2ba353412..43e4e6ee9 100644 --- a/BTCPayServer/Controllers/GreenField/StoreOnChainWalletsController.cs +++ b/BTCPayServer/Controllers/GreenField/StoreOnChainWalletsController.cs @@ -61,7 +61,7 @@ namespace BTCPayServer.Controllers.GreenField WalletsController walletsController, PayjoinClient payjoinClient, DelayedTransactionBroadcaster delayedTransactionBroadcaster, - EventAggregator eventAggregator, + EventAggregator eventAggregator, WalletReceiveService walletReceiveService, IFeeProviderFactory feeProviderFactory) { @@ -85,41 +85,44 @@ namespace BTCPayServer.Controllers.GreenField public async Task 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); - + return Ok(new OnChainWalletOverviewData() { 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), }); } - + [Authorize(Policy = Policies.CanViewStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/feerate")] public async Task 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) + FeeRate = await _feeProviderFactory.CreateFeeProvider(network) .GetFeeRateAsync(feeRateTarget), }); } - + [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/address")] public async Task 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) @@ -140,13 +143,14 @@ namespace BTCPayServer.Controllers.GreenField KeyPath = kpi.KeyPath }); } - + [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpDelete("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/address")] public async Task 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) @@ -160,7 +164,7 @@ namespace BTCPayServer.Controllers.GreenField [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/transactions")] public async Task ShowOnChainWalletTransactions( - string storeId, + string storeId, string cryptoCode, [FromQuery] TransactionStatus[]? statusFilter = null, [FromQuery] int skip = 0, @@ -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 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); @@ -248,7 +255,7 @@ namespace BTCPayServer.Controllers.GreenField Timestamp = coin.Timestamp, KeyPath = coin.KeyPath, Confirmations = coin.Confirmations, - Address = network.NBXplorerNetwork.CreateAddress(derivationScheme.AccountDerivation, coin.KeyPath, coin.ScriptPubKey).ToString() + Address = network.NBXplorerNetwork.CreateAddress(derivationScheme.AccountDerivation, coin.KeyPath, coin.ScriptPubKey).ToString() }; }).ToList() ); @@ -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", @@ -311,7 +319,7 @@ namespace BTCPayServer.Controllers.GreenField { amount = null; } - var address = string.Empty; + var address = string.Empty; try { bip21 = new BitcoinUrlBuilder(destination.Destination, network.NBitcoinNetwork); @@ -440,7 +448,7 @@ namespace BTCPayServer.Controllers.GreenField return this.CreateAPIError("not-available", $"{cryptoCode} sending services are not currently available"); } - + var signingKey = ExtKey.Parse(signingKeyStr, network.NBitcoinNetwork); var signingKeySettings = derivationScheme.GetSigningAccountKeySettings(); diff --git a/BTCPayServer/Controllers/GreenField/StorePaymentMethodsController.cs b/BTCPayServer/Controllers/GreenField/StorePaymentMethodsController.cs index 72e1d747e..65a8621ee 100644 --- a/BTCPayServer/Controllers/GreenField/StorePaymentMethodsController.cs +++ b/BTCPayServer/Controllers/GreenField/StorePaymentMethodsController.cs @@ -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))) diff --git a/BTCPayServer/Controllers/GreenField/StoreWebhooksController.cs b/BTCPayServer/Controllers/GreenField/StoreWebhooksController.cs index e8aaf7965..00ac5c257 100644 --- a/BTCPayServer/Controllers/GreenField/StoreWebhooksController.cs +++ b/BTCPayServer/Controllers/GreenField/StoreWebhooksController.cs @@ -122,13 +122,13 @@ namespace BTCPayServer.Controllers.GreenField { Everything = aed.Everything, SpecificEvents = aed.SpecificEvents - }: + } : new AuthorizedWebhookEvents() { Everything = true }, - AutomaticRedelivery = create.AutomaticRedelivery, + AutomaticRedelivery = create.AutomaticRedelivery, }; } - + [HttpGet("~/api/v1/stores/{storeId}/webhooks/{webhookId}/deliveries/{deliveryId?}")] public async Task ListDeliveries(string storeId, string webhookId, string deliveryId, int? count = null) { diff --git a/BTCPayServer/Controllers/GreenField/StoresController.cs b/BTCPayServer/Controllers/GreenField/StoresController.cs index 0c1943201..ef9880b41 100644 --- a/BTCPayServer/Controllers/GreenField/StoresController.cs +++ b/BTCPayServer/Controllers/GreenField/StoresController.cs @@ -82,7 +82,7 @@ namespace BTCPayServer.Controllers.GreenField } var store = new Data.StoreData(); - + PaymentMethodId.TryParse(request.DefaultPaymentMethod, out var defaultPaymentMethodId); ToModel(request, store, defaultPaymentMethodId); await _storeRepository.CreateStore(_userManager.GetUserId(User), store); @@ -197,7 +197,7 @@ namespace BTCPayServer.Controllers.GreenField { ModelState.AddModelError(nameof(request.Name), "DefaultPaymentMethod is invalid"); } - + if (string.IsNullOrEmpty(request.Name)) ModelState.AddModelError(nameof(request.Name), "Name is missing"); else if (request.Name.Length < 1 || request.Name.Length > 50) @@ -215,7 +215,7 @@ namespace BTCPayServer.Controllers.GreenField return !ModelState.IsValid ? this.CreateValidationError(ModelState) : null; } - + private IActionResult StoreNotFound() { return this.CreateAPIError(404, "store-not-found", "The store was not found"); diff --git a/BTCPayServer/Controllers/GreenField/UsersController.cs b/BTCPayServer/Controllers/GreenField/UsersController.cs index 7bac69797..0fc99a852 100644 --- a/BTCPayServer/Controllers/GreenField/UsersController.cs +++ b/BTCPayServer/Controllers/GreenField/UsersController.cs @@ -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 { @@ -41,8 +41,8 @@ namespace BTCPayServer.Controllers.GreenField private readonly IAuthorizationService _authorizationService; private readonly UserService _userService; - public UsersController(UserManager userManager, - RoleManager roleManager, + public UsersController(UserManager userManager, + RoleManager roleManager, SettingsRepository settingsRepository, EventAggregator eventAggregator, IPasswordValidator passwordValidator, @@ -169,7 +169,8 @@ namespace BTCPayServer.Controllers.GreenField if (!anyAdmin) { var settings = await _settingsRepository.GetSettingAsync(); - if (settings != null) { + if (settings != null) + { settings.FirstRun = false; await _settingsRepository.UpdateSetting(settings); } @@ -234,7 +235,8 @@ namespace BTCPayServer.Controllers.GreenField private async Task IsUserTheOnlyOneAdmin(ApplicationUser user) { var isUserAdmin = await _userService.IsAdminUser(user); - if (!isUserAdmin) { + if (!isUserAdmin) + { return false; } diff --git a/BTCPayServer/Controllers/HomeController.cs b/BTCPayServer/Controllers/HomeController.cs index f47cb9b73..66b7189a7 100644 --- a/BTCPayServer/Controllers/HomeController.cs +++ b/BTCPayServer/Controllers/HomeController.cs @@ -80,7 +80,7 @@ namespace BTCPayServer.Controllers } return View("Home"); } - + return Challenge(); } @@ -91,7 +91,7 @@ namespace BTCPayServer.Controllers return Json(LanguageService.GetLanguages(), new JsonSerializerSettings { Formatting = Formatting.Indented }); } - + [Route("misc/permissions")] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie + "," + AuthenticationSchemes.Greenfield)] public IActionResult Permissions() diff --git a/BTCPayServer/Controllers/InvoiceController.Testing.cs b/BTCPayServer/Controllers/InvoiceController.Testing.cs index 54d7024ee..57595b5f9 100644 --- a/BTCPayServer/Controllers/InvoiceController.Testing.cs +++ b/BTCPayServer/Controllers/InvoiceController.Testing.cs @@ -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 { @@ -23,7 +23,7 @@ namespace BTCPayServer.Controllers public int BlockCount { get; set; } = 1; public string CryptoCode { get; set; } = "BTC"; } - + [HttpPost] [Route("i/{invoiceId}/test-payment")] [CheatModeRoute] @@ -31,20 +31,20 @@ namespace BTCPayServer.Controllers { var invoice = await _InvoiceRepository.GetInvoice(invoiceId); var store = await _StoreRepository.FindStore(invoice.StoreId); - + // TODO support altcoins, not just bitcoin var network = _NetworkProvider.GetNetwork(request.CryptoCode); var paymentMethodId = store.GetDefaultPaymentId() ?? store.GetEnabledPaymentIds(_NetworkProvider).FirstOrDefault(p => p.CryptoCode == request.CryptoCode && p.PaymentType == PaymentTypes.BTCLike); var bitcoinAddressString = invoice.GetPaymentMethod(paymentMethodId).GetPaymentMethodDetails().GetPaymentDestination(); var bitcoinAddressObj = BitcoinAddress.Create(bitcoinAddressString, network.NBitcoinNetwork); var BtcAmount = request.Amount; - + try { var paymentMethod = invoice.GetPaymentMethod(paymentMethodId); var rate = paymentMethod.Rate; var txid = cheater.CashCow.SendToAddress(bitcoinAddressObj, new Money(BtcAmount, MoneyUnit.BTC)).ToString(); - + // TODO The value of totalDue is wrong. How can we get the real total due? invoice.Price is only correct if this is the 2nd payment, not for a 3rd or 4th payment. var totalDue = invoice.Price; return Ok(new @@ -63,7 +63,7 @@ namespace BTCPayServer.Controllers }); } } - + [HttpPost] [Route("i/{invoiceId}/mine-blocks")] [CheatModeRoute] @@ -73,13 +73,13 @@ namespace BTCPayServer.Controllers var blockRewardBitcoinAddress = cheater.CashCow.GetNewAddress(); try { - if (request.BlockCount > 0) + if (request.BlockCount > 0) { cheater.CashCow.GenerateToAddress(request.BlockCount, blockRewardBitcoinAddress); return Ok(new { - SuccessMessage = "Mined "+request.BlockCount+" blocks" - }); + SuccessMessage = "Mined " + request.BlockCount + " blocks" + }); } return BadRequest(new { diff --git a/BTCPayServer/Controllers/InvoiceController.UI.cs b/BTCPayServer/Controllers/InvoiceController.UI.cs index 1211b56e9..349a2826b 100644 --- a/BTCPayServer/Controllers/InvoiceController.UI.cs +++ b/BTCPayServer/Controllers/InvoiceController.UI.cs @@ -53,7 +53,7 @@ namespace BTCPayServer.Controllers return NotFound(); return File(delivery.GetBlob().Request, "application/json"); } - + [HttpPost("invoices/{invoiceId}/deliveries/{deliveryId}/redeliver")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public async Task RedeliverWebhook(string storeId, string invoiceId, string deliveryId) @@ -141,7 +141,7 @@ namespace BTCPayServer.Controllers var details = InvoicePopulatePayments(invoice); model.CryptoPayments = details.CryptoPayments; model.Payments = details.Payments; - + return View(model); } @@ -158,7 +158,7 @@ namespace BTCPayServer.Controllers [HttpGet("invoices/{invoiceId}/refund")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] - public async Task Refund([FromServices]IEnumerable payoutHandlers, string invoiceId, CancellationToken cancellationToken) + public async Task Refund([FromServices] IEnumerable payoutHandlers, string invoiceId, CancellationToken cancellationToken) { await using var ctx = _dbContextFactory.CreateContext(); ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; @@ -182,7 +182,7 @@ namespace BTCPayServer.Controllers "PullPayment", new { pullPaymentId = ppId }); } - + var paymentMethods = invoice.GetBlob(_NetworkProvider).GetPaymentMethods(); var pmis = paymentMethods.Select(method => method.GetId()).ToList(); var options = (await payoutHandlers.GetSupportedPaymentMethods(invoice.StoreData)).Where(id => pmis.Contains(id)).ToList(); @@ -195,7 +195,7 @@ namespace BTCPayServer.Controllers }); return RedirectToAction(nameof(Invoice), new { invoiceId }); } - + var defaultRefund = invoice.Payments .Select(p => p.GetBlob(_NetworkProvider)) .Select(p => p?.GetPaymentMethodId()) @@ -217,7 +217,7 @@ namespace BTCPayServer.Controllers } return View(refund); } - + [HttpPost("invoices/{invoiceId}/refund")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public async Task Refund(string invoiceId, RefundModel model, CancellationToken cancellationToken) @@ -230,7 +230,7 @@ namespace BTCPayServer.Controllers if (!CanRefund(invoice.GetInvoiceState())) return NotFound(); - + var store = GetCurrentStore(); var paymentMethodId = PaymentMethodId.Parse(model.SelectedPaymentMethod); var cdCurrency = _CurrencyNameTable.GetCurrencyData(invoice.Currency, true); @@ -245,7 +245,7 @@ namespace BTCPayServer.Controllers model.Title = "What to refund?"; var pms = invoice.GetPaymentMethods(); var paymentMethod = pms.SingleOrDefault(method => method.GetId() == paymentMethodId); - + //TODO: Make this clean if (paymentMethod is null && paymentMethodId.PaymentType == LightningPaymentType.Instance) { @@ -279,37 +279,38 @@ namespace BTCPayServer.Controllers model.FiatText = _CurrencyNameTable.DisplayFormatCurrency(model.FiatAmount, invoice.Currency); return View(model); - + 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) - { - case "RateThen": - createPullPayment.Currency = paymentMethodId.CryptoCode; - createPullPayment.Amount = model.CryptoAmountThen; - break; - case "CurrentRate": - createPullPayment.Currency = paymentMethodId.CryptoCode; - createPullPayment.Amount = model.CryptoAmountNow; - break; - case "Fiat": - createPullPayment.Currency = invoice.Currency; - createPullPayment.Amount = model.FiatAmount; - break; - case "Custom": - model.Title = "How much to refund?"; - model.CustomCurrency = invoice.Currency; - model.CustomAmount = model.FiatAmount; - model.RefundStep = RefundSteps.SelectCustomAmount; - return View(model); - default: - ModelState.AddModelError(nameof(model.SelectedRefundOption), "Invalid choice"); - return View(model); - } + { + case "RateThen": + createPullPayment.Currency = paymentMethodId.CryptoCode; + createPullPayment.Amount = model.CryptoAmountThen; + break; + case "CurrentRate": + createPullPayment.Currency = paymentMethodId.CryptoCode; + createPullPayment.Amount = model.CryptoAmountNow; + break; + case "Fiat": + createPullPayment.Currency = invoice.Currency; + createPullPayment.Amount = model.FiatAmount; + break; + case "Custom": + model.Title = "How much to refund?"; + model.CustomCurrency = invoice.Currency; + model.CustomAmount = model.FiatAmount; + model.RefundStep = RefundSteps.SelectCustomAmount; + return View(model); + default: + ModelState.AddModelError(nameof(model.SelectedRefundOption), "Invalid choice"); + return View(model); + } break; case RefundSteps.SelectCustomAmount: @@ -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 @@ -466,7 +468,7 @@ namespace BTCPayServer.Controllers model.IsModal = true; return View(nameof(Checkout), model); } - + [HttpGet("invoice-noscript")] public async Task CheckoutNoScript(string? invoiceId, string? id = null, string? paymentMethodId = null, [FromQuery] string? lang = null) { @@ -563,10 +565,10 @@ namespace BTCPayServer.Controllers lang = _languageService.AutoDetectLanguageUsingHeader(HttpContext.Request.Headers, null).Code; break; case { } langs when !string.IsNullOrEmpty(langs): - { - lang = _languageService.FindLanguage(langs)?.Code; - break; - } + { + lang = _languageService.FindLanguage(langs)?.Code; + break; + } } lang ??= storeBlob.DefaultLang; @@ -745,15 +747,15 @@ namespace BTCPayServer.Controllers public async Task ListInvoices(InvoicesModel? model = null) { model = this.ParseListQuery(model ?? new InvoicesModel()); - + var fs = new SearchString(model.SearchTerm); var store = model.StoreId == null || fs.ContainsFilter("storeid") ? null : HttpContext.GetStoreData(); var storeIds = store == null ? fs.GetFilterArray("storeid") != null ? fs.GetFilterArray("storeid") : new List().ToArray() - : new []{ store.Id }; + : new[] { store.Id }; model.StoreIds = storeIds; - + InvoiceQuery invoiceQuery = GetInvoiceQuery(model.SearchTerm, model.TimezoneOffset ?? 0); invoiceQuery.StoreId = storeIds; var counting = _InvoiceRepository.GetInvoicesTotal(invoiceQuery); @@ -824,7 +826,7 @@ namespace BTCPayServer.Controllers Response.Headers.Add("X-Content-Type-Options", "nosniff"); return Content(res, "application/" + format); } - + private SelectList GetPaymentMethodsSelectList() { return new SelectList(_paymentMethodHandlerDictionary.Distinct().SelectMany(handler => @@ -851,7 +853,7 @@ namespace BTCPayServer.Controllers TempData[WellKnownTempData.ErrorMessage] = "You need to create at least one store before creating a transaction"; return RedirectToAction(nameof(UserStoresController.ListStores), "UserStores"); } - + if (model?.StoreId != null) { var store = await _StoreRepository.FindStore(model.StoreId, GetUserId()); @@ -862,7 +864,7 @@ namespace BTCPayServer.Controllers var vm = new CreateInvoiceModel { - Stores = stores, + Stores = stores, StoreId = model?.StoreId, AvailablePaymentMethods = GetPaymentMethodsSelectList() }; @@ -916,7 +918,7 @@ namespace BTCPayServer.Controllers DefaultPaymentMethod = model.DefaultPaymentMethod, NotificationEmail = model.NotificationEmail, ExtendedNotifications = model.NotificationEmail != null, - RequiresRefundEmail = model.RequiresRefundEmail == RequiresRefundEmail.InheritFromStore + RequiresRefundEmail = model.RequiresRefundEmail == RequiresRefundEmail.InheritFromStore ? store.GetStoreBlob().RequiresRefundEmail : model.RequiresRefundEmail == RequiresRefundEmail.On }, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken: cancellationToken); @@ -974,7 +976,7 @@ namespace BTCPayServer.Controllers } private StoreData GetCurrentStore() => HttpContext.GetStoreData(); - + private InvoiceEntity GetCurrentInvoice() => HttpContext.GetInvoiceData(); private string GetUserId() => _UserManager.GetUserId(User); diff --git a/BTCPayServer/Controllers/ManageController.2FA.cs b/BTCPayServer/Controllers/ManageController.2FA.cs index 1496711f2..c5eb7d865 100644 --- a/BTCPayServer/Controllers/ManageController.2FA.cs +++ b/BTCPayServer/Controllers/ManageController.2FA.cs @@ -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 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); } diff --git a/BTCPayServer/Controllers/ManageController.APIKeys.cs b/BTCPayServer/Controllers/ManageController.APIKeys.cs index 2a532a07b..fba6c9d8a 100644 --- a/BTCPayServer/Controllers/ManageController.APIKeys.cs +++ b/BTCPayServer/Controllers/ManageController.APIKeys.cs @@ -80,7 +80,7 @@ namespace BTCPayServer.Controllers return View("AddApiKey", await SetViewModelValues(new AddApiKeyViewModel())); } - + [HttpGet("~/api-keys/authorize")] public async Task AuthorizeAPIKey(string[] permissions, string applicationName = null, Uri redirect = null, bool strict = true, bool selectiveStores = false, string applicationIdentifier = null) @@ -104,11 +104,11 @@ namespace BTCPayServer.Controllers } if (!string.IsNullOrEmpty(applicationIdentifier) && redirect != null) { - + //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; } @@ -299,7 +305,7 @@ namespace BTCPayServer.Controllers var key = command == "authorize" ? await CreateKey(viewModel, (viewModel.ApplicationIdentifier, viewModel.RedirectUrl?.AbsoluteUri)) : await _apiKeyRepository.GetKey(viewModel.ApiKey); - + if (viewModel.RedirectUrl != null) { var permissions = key.GetBlob().Permissions; diff --git a/BTCPayServer/Controllers/ManageController.LoginCodes.cs b/BTCPayServer/Controllers/ManageController.LoginCodes.cs index ef8f09400..71104a49b 100644 --- a/BTCPayServer/Controllers/ManageController.LoginCodes.cs +++ b/BTCPayServer/Controllers/ManageController.LoginCodes.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; diff --git a/BTCPayServer/Controllers/ManageController.Notifications.cs b/BTCPayServer/Controllers/ManageController.Notifications.cs index 9795e32bb..79bcc4b8c 100644 --- a/BTCPayServer/Controllers/ManageController.Notifications.cs +++ b/BTCPayServer/Controllers/ManageController.Notifications.cs @@ -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"); } diff --git a/BTCPayServer/Controllers/ManageController.cs b/BTCPayServer/Controllers/ManageController.cs index 8283260d5..4575e628a 100644 --- a/BTCPayServer/Controllers/ManageController.cs +++ b/BTCPayServer/Controllers/ManageController.cs @@ -21,7 +21,7 @@ using Microsoft.Extensions.Logging; namespace BTCPayServer.Controllers { - + [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewProfile)] [Route("[controller]/[action]")] public partial class ManageController : Controller @@ -33,13 +33,13 @@ namespace BTCPayServer.Controllers private readonly UrlEncoder _urlEncoder; private readonly BTCPayServerEnvironment _btcPayServerEnvironment; private readonly APIKeyRepository _apiKeyRepository; - private readonly IAuthorizationService _authorizationService; + private readonly IAuthorizationService _authorizationService; private readonly Fido2Service _fido2Service; private readonly LinkGenerator _linkGenerator; private readonly UserLoginCodeService _userLoginCodeService; private readonly UserService _userService; readonly StoreRepository _StoreRepository; - + public ManageController( UserManager userManager, SignInManager signInManager, @@ -53,7 +53,7 @@ namespace BTCPayServer.Controllers Fido2Service fido2Service, LinkGenerator linkGenerator, UserService userService, - UserLoginCodeService userLoginCodeService + UserLoginCodeService userLoginCodeService ) { _userManager = userManager; @@ -108,7 +108,7 @@ namespace BTCPayServer.Controllers } return RedirectToAction(nameof(Index)); } - + [HttpPost] [ValidateAntiForgeryToken] public async Task Index(IndexViewModel model) diff --git a/BTCPayServer/Controllers/NotificationsController.cs b/BTCPayServer/Controllers/NotificationsController.cs index a586422ef..789cdaba7 100644 --- a/BTCPayServer/Controllers/NotificationsController.cs +++ b/BTCPayServer/Controllers/NotificationsController.cs @@ -47,7 +47,7 @@ namespace BTCPayServer.Controllers { return ViewComponent("NotificationsDropdown"); } - + [HttpGet] public async Task SubscribeUpdates(CancellationToken cancellationToken) { @@ -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,9 +150,10 @@ 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 ?? ""; if (string.IsNullOrEmpty(link)) { @@ -162,7 +165,7 @@ namespace BTCPayServer.Controllers return NotFound(); } - + [HttpPost] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanManageNotificationsForUser)] public async Task MassAction(string command, string[] selectedItems) @@ -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); } diff --git a/BTCPayServer/Controllers/PaymentRequestController.cs b/BTCPayServer/Controllers/PaymentRequestController.cs index 9958f8603..4715ace57 100644 --- a/BTCPayServer/Controllers/PaymentRequestController.cs +++ b/BTCPayServer/Controllers/PaymentRequestController.cs @@ -121,7 +121,7 @@ namespace BTCPayServer.Controllers var data = paymentRequest ?? new PaymentRequestData(); data.StoreDataId = viewModel.StoreId; data.Archived = viewModel.Archived; - + var blob = data.GetBlob(); blob.Title = viewModel.Title; blob.Email = viewModel.Email; @@ -229,7 +229,7 @@ namespace BTCPayServer.Controllers amount = Math.Min(result.AmountDue, amount.Value); else amount = result.AmountDue; - + var pr = await _PaymentRequestRepository.FindPaymentRequest(payReqId, null, cancellationToken); var blob = pr.GetBlob(); var store = pr.StoreData; @@ -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 {PaymentRequestRepository.GetInternalTag(payReqId)}; - var newInvoice = await _InvoiceController.CreateInvoiceCoreRaw(invoiceRequest,store, Request.GetAbsoluteRoot(), additionalTags, cancellationToken); + var additionalTags = new List { 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"); } @@ -343,9 +344,9 @@ namespace BTCPayServer.Controllers } private string GetUserId() => _UserManager.GetUserId(User); - + private StoreData GetCurrentStore() => HttpContext.GetStoreData(); - + private PaymentRequestData GetCurrentPaymentRequest() => HttpContext.GetPaymentRequestData(); } } diff --git a/BTCPayServer/Controllers/PublicLightningNodeInfoController.cs b/BTCPayServer/Controllers/PublicLightningNodeInfoController.cs index cbbd5af20..71ddca35e 100644 --- a/BTCPayServer/Controllers/PublicLightningNodeInfoController.cs +++ b/BTCPayServer/Controllers/PublicLightningNodeInfoController.cs @@ -58,7 +58,7 @@ namespace BTCPayServer.Controllers { return View(new ShowLightningNodeInfoViewModel { - Available = false, + Available = false, CryptoCode = cryptoCode, StoreName = store.StoreName }); diff --git a/BTCPayServer/Controllers/PullPaymentController.cs b/BTCPayServer/Controllers/PullPaymentController.cs index b933b50c0..773f1fa2c 100644 --- a/BTCPayServer/Controllers/PullPaymentController.cs +++ b/BTCPayServer/Controllers/PullPaymentController.cs @@ -42,7 +42,7 @@ namespace BTCPayServer.Controllers _serializerSettings = serializerSettings; _payoutHandlers = payoutHandlers; } - + [Route("pull-payments/{pullPaymentId}")] public async Task ViewPullPayment(string pullPaymentId) { @@ -104,21 +104,21 @@ namespace BTCPayServer.Controllers { ModelState.AddModelError(nameof(pullPaymentId), "This pull payment does not exists"); } - + var ppBlob = pp.GetBlob(); - + 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"); + ModelState.AddModelError(nameof(vm.SelectedPaymentMethod), $"Invalid destination with selected payment method"); return await ViewPullPayment(pullPaymentId); } 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); } diff --git a/BTCPayServer/Controllers/ServerController.Plugins.cs b/BTCPayServer/Controllers/ServerController.Plugins.cs index 885e88ea3..81cb1ec58 100644 --- a/BTCPayServer/Controllers/ServerController.Plugins.cs +++ b/BTCPayServer/Controllers/ServerController.Plugins.cs @@ -83,7 +83,7 @@ namespace BTCPayServer.Controllers [HttpPost("server/plugins/install")] public async Task InstallPlugin( - [FromServices] PluginService pluginService, string plugin , bool update = false) + [FromServices] PluginService pluginService, string plugin, bool update = false) { try { @@ -94,7 +94,7 @@ namespace BTCPayServer.Controllers } else { - + pluginService.InstallPlugin(plugin); } TempData.SetStatusMessageModel(new StatusMessageModel() @@ -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" }); } } } diff --git a/BTCPayServer/Controllers/ServerController.Storage.cs b/BTCPayServer/Controllers/ServerController.Storage.cs index 4b89c7a22..b32139c84 100644 --- a/BTCPayServer/Controllers/ServerController.Storage.cs +++ b/BTCPayServer/Controllers/ServerController.Storage.cs @@ -34,7 +34,7 @@ namespace BTCPayServer.Controllers { var model = new ViewFilesViewModel() { - Files = await _StoredFileRepository.GetFiles(), + Files = await _StoredFileRepository.GetFiles(), DirectUrlByFiles = null, StorageConfigured = (await _SettingsRepository.GetSettingAsync()) != null }; @@ -63,7 +63,7 @@ namespace BTCPayServer.Controllers }); } else - { + { model.DirectUrlByFiles = directUrlByFiles; } } @@ -173,7 +173,7 @@ namespace BTCPayServer.Controllers public bool IsDownload { get; set; } } - + [HttpPost("server/files/upload")] public async Task CreateFiles(List files) { @@ -193,7 +193,7 @@ namespace BTCPayServer.Controllers } StatusMessageModel.StatusSeverity statusMessageSeverity; - string statusMessage; + string statusMessage; if (invalidFileNameCount == 0) { @@ -212,13 +212,13 @@ namespace BTCPayServer.Controllers } this.TempData.SetStatusMessageModel(new StatusMessageModel() - { - Message = statusMessage, - Severity = statusMessageSeverity - }); + { + Message = statusMessage, + Severity = statusMessageSeverity + }); return RedirectToAction(nameof(Files), new - { + { fileIds = fileIds.ToArray(), }); } diff --git a/BTCPayServer/Controllers/ServerController.Users.cs b/BTCPayServer/Controllers/ServerController.Users.cs index 17d9a03b9..c52625526 100644 --- a/BTCPayServer/Controllers/ServerController.Users.cs +++ b/BTCPayServer/Controllers/ServerController.Users.cs @@ -26,7 +26,7 @@ namespace BTCPayServer.Controllers ) { model = this.ParseListQuery(model ?? new UsersViewModel()); - + var usersQuery = _UserManager.Users; if (!string.IsNullOrWhiteSpace(model.SearchTerm)) { @@ -36,7 +36,7 @@ namespace BTCPayServer.Controllers #pragma warning restore CA1307 // Specify StringComparison } - if (sortOrder != null) + if (sortOrder != null) { switch (sortOrder) { @@ -67,7 +67,7 @@ namespace BTCPayServer.Controllers }) .ToListAsync(); model.Total = await usersQuery.CountAsync(); - + return View(model); } @@ -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)) { @@ -149,23 +155,26 @@ namespace BTCPayServer.Controllers { result = await _UserManager.CreateAsync(user); } - + if (result.Succeeded) { if (model.IsAdmin && !(await _UserManager.AddToRoleAsync(user, Roles.ServerAdmin)).Succeeded) model.IsAdmin = false; var tcs = new TaskCompletionSource(); - + _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; if (user.RequiresEmailConfirmation && !user.EmailConfirmed) { - + TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Success, @@ -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.
You may alternatively share this link with them: {callbackUrl}" }); - }else if (!await _UserManager.HasPasswordAsync(user)) + } + else if (!await _UserManager.HasPasswordAsync(user)) { TempData.SetStatusMessageModel(new StatusMessageModel() { @@ -185,7 +195,7 @@ namespace BTCPayServer.Controllers } return RedirectToAction(nameof(ListUsers)); } - + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); @@ -218,7 +228,7 @@ namespace BTCPayServer.Controllers $"The admin {user.Email} will be permanently deleted. This action will also delete all accounts, users and data associated with the server account. Are you sure?", "Delete")); } - + return View("Confirm", new ConfirmModel("Delete user", $"The user {user.Email} will be permanently deleted. Are you sure?", "Delete")); } @@ -257,6 +267,6 @@ namespace BTCPayServer.Controllers public bool IsAdmin { get; set; } [Display(Name = "Email confirmed?")] - public bool EmailConfirmed { get; set; } + public bool EmailConfirmed { get; set; } } } diff --git a/BTCPayServer/Controllers/ServerController.cs b/BTCPayServer/Controllers/ServerController.cs index b51971f94..31e912cd3 100644 --- a/BTCPayServer/Controllers/ServerController.cs +++ b/BTCPayServer/Controllers/ServerController.cs @@ -814,7 +814,7 @@ namespace BTCPayServer.Controllers this.RouteData.Values.Remove(nameof(hostname)); return RedirectToAction(nameof(DynamicDnsServices)); } - + [HttpGet("server/services/dynamic-dns/{hostname}/delete")] public async Task DeleteDynamicDnsService(string hostname) { @@ -826,7 +826,7 @@ namespace BTCPayServer.Controllers new ConfirmModel("Delete dynamic DNS service", $"Deleting the dynamic DNS service for {hostname} means your BTCPay Server will stop updating the associated DNS record periodically.", "Delete")); } - + [HttpPost("server/services/dynamic-dns/{hostname}/delete")] public async Task DeleteDynamicDnsServicePost(string hostname) { @@ -950,12 +950,12 @@ namespace BTCPayServer.Controllers } return RedirectToAction(nameof(SSHService)); } - + if (command is "disable") { return RedirectToAction(nameof(SSHServiceDisable)); } - + return NotFound(); } diff --git a/BTCPayServer/Controllers/StorePullPaymentsController.PullPayments.cs b/BTCPayServer/Controllers/StorePullPaymentsController.PullPayments.cs index b39b071ae..57b78e234 100644 --- a/BTCPayServer/Controllers/StorePullPaymentsController.PullPayments.cs +++ b/BTCPayServer/Controllers/StorePullPaymentsController.PullPayments.cs @@ -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 _payoutHandlers; @@ -44,12 +44,12 @@ namespace BTCPayServer.Controllers return HttpContext.GetStoreData(); } } - public StorePullPaymentsController(BTCPayNetworkProvider btcPayNetworkProvider, - IEnumerable payoutHandlers, - CurrencyNameTable currencyNameTable, + public StorePullPaymentsController(BTCPayNetworkProvider btcPayNetworkProvider, + IEnumerable payoutHandlers, + CurrencyNameTable currencyNameTable, PullPaymentHostedService pullPaymentHostedService, ApplicationDbContextFactory dbContextFactory, - BTCPayNetworkJsonSerializerSettings jsonSerializerSettings) + BTCPayNetworkJsonSerializerSettings jsonSerializerSettings) { _btcPayNetworkProvider = btcPayNetworkProvider; _payoutHandlers = payoutHandlers; @@ -58,12 +58,12 @@ namespace BTCPayServer.Controllers _dbContextFactory = dbContextFactory; _jsonSerializerSettings = jsonSerializerSettings; } - + [HttpGet("new")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public async Task NewPullPayment(string storeId) { - if (CurrentStore is null) + if (CurrentStore is null) return NotFound(); var paymentMethods = await _payoutHandlers.GetSupportedPaymentMethods(CurrentStore); @@ -85,12 +85,12 @@ namespace BTCPayServer.Controllers PaymentMethodItems = paymentMethods.Select(id => new SelectListItem(id.ToPrettyString(), id.ToString(), true)) }); } - + [HttpPost("new")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public async Task NewPullPayment(string storeId, NewPullPaymentModel model) { - if (CurrentStore is null) + if (CurrentStore is null) return NotFound(); var paymentMethodOptions = await _payoutHandlers.GetSupportedPaymentMethods(CurrentStore); @@ -143,9 +143,9 @@ namespace BTCPayServer.Controllers }); return RedirectToAction(nameof(PullPayments), new { storeId = storeId }); } - + [HttpGet("")] - public async Task PullPayments(string storeId, int skip = 0, int count = 50, + public async Task PullPayments(string storeId, int skip = 0, int count = 50, string sortOrder = "desc") { await using var ctx = _dbContextFactory.CreateContext(); @@ -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) @@ -181,12 +183,13 @@ namespace BTCPayServer.Controllers ); foreach (var pp in pps) { - var totalCompleted = pp.Payouts.Where(p => (p.State == PayoutState.Completed || - p.State == PayoutState.InProgress) && p.IsInPeriod(pp, now)) + var totalCompleted = pp.Payouts.Where(p => (p.State == PayoutState.Completed || + p.State == PayoutState.InProgress) && p.IsInPeriod(pp, now)) .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); @@ -225,7 +228,7 @@ namespace BTCPayServer.Controllers { return View("Confirm", new ConfirmModel("Archive pull payment", "Do you really want to archive the pull payment?", "Archive")); } - + [HttpPost("{pullPaymentId}/archive")] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public async Task ArchivePullPaymentPost(string storeId, @@ -247,7 +250,7 @@ namespace BTCPayServer.Controllers { if (vm is null) return NotFound(); - + vm.PaymentMethods = await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData()); var paymentMethodId = PaymentMethodId.Parse(vm.PaymentMethodId); var handler = _payoutHandlers @@ -281,115 +284,120 @@ namespace BTCPayServer.Controllers { case "approve-pay": case "approve": - { - await using var ctx = this._dbContextFactory.CreateContext(); - ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; - var payouts = await GetPayoutsForPaymentMethod(paymentMethodId, ctx, payoutIds, storeId, cancellationToken); - - var failed = false; - for (int i = 0; i < payouts.Count; i++) { - var payout = payouts[i]; - if (payout.State != PayoutState.AwaitingApproval) - continue; - var rateResult = await _pullPaymentService.GetRate(payout, null, cancellationToken); - if (rateResult.BidAsk == null) + await using var ctx = this._dbContextFactory.CreateContext(); + ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + var payouts = await GetPayoutsForPaymentMethod(paymentMethodId, ctx, payoutIds, storeId, cancellationToken); + + var failed = false; + for (int i = 0; i < payouts.Count; i++) { - this.TempData.SetStatusMessageModel(new StatusMessageModel() + var payout = payouts[i]; + if (payout.State != PayoutState.AwaitingApproval) + continue; + var rateResult = await _pullPaymentService.GetRate(payout, null, cancellationToken); + if (rateResult.BidAsk == null) { - Message = $"Rate unavailable: {rateResult.EvaluatedRule}", - Severity = StatusMessageModel.StatusSeverity.Error + this.TempData.SetStatusMessageModel(new StatusMessageModel() + { + Message = $"Rate unavailable: {rateResult.EvaluatedRule}", + Severity = StatusMessageModel.StatusSeverity.Error + }); + failed = true; + break; + } + var approveResult = await _pullPaymentService.Approve(new HostedServices.PullPaymentHostedService.PayoutApproval() + { + PayoutId = payout.Id, + Revision = payout.GetBlob(_jsonSerializerSettings).Revision, + Rate = rateResult.BidAsk.Ask }); - failed = true; + if (approveResult != PullPaymentHostedService.PayoutApproval.Result.Ok) + { + TempData.SetStatusMessageModel(new StatusMessageModel() + { + Message = PullPaymentHostedService.PayoutApproval.GetErrorMessage(approveResult), + Severity = StatusMessageModel.StatusSeverity.Error + }); + failed = true; + break; + } + } + + if (failed) + { break; } - var approveResult = await _pullPaymentService.Approve(new HostedServices.PullPaymentHostedService.PayoutApproval() + if (command == "approve-pay") { - PayoutId = payout.Id, - Revision = payout.GetBlob(_jsonSerializerSettings).Revision, - Rate = rateResult.BidAsk.Ask + goto case "pay"; + } + TempData.SetStatusMessageModel(new StatusMessageModel() + { + Message = "Payouts approved", + Severity = StatusMessageModel.StatusSeverity.Success }); - if (approveResult != PullPaymentHostedService.PayoutApproval.Result.Ok) - { - TempData.SetStatusMessageModel(new StatusMessageModel() - { - Message = PullPaymentHostedService.PayoutApproval.GetErrorMessage(approveResult), - Severity = StatusMessageModel.StatusSeverity.Error - }); - failed = true; - break; - } - } - - if (failed) - { break; } - if (command == "approve-pay") - { - goto case "pay"; - } - TempData.SetStatusMessageModel(new StatusMessageModel() - { - Message = "Payouts approved", Severity = StatusMessageModel.StatusSeverity.Success - }); - break; - } case "pay": - { - 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 - }); - break; - } - - case "mark-paid": - { - await using var ctx = this._dbContextFactory.CreateContext(); - ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; - var payouts = await GetPayoutsForPaymentMethod(paymentMethodId, ctx, payoutIds, storeId, cancellationToken); - for (int i = 0; i < payouts.Count; i++) - { - var payout = payouts[i]; - if (payout.State != PayoutState.AwaitingPayment) - continue; - - var result = await _pullPaymentService.MarkPaid(new PayoutPaidRequest() + if (handler is { }) + return await handler?.InitiatePayment(paymentMethodId, payoutIds); + TempData.SetStatusMessageModel(new StatusMessageModel() { - PayoutId = payout.Id + Message = "Paying via this payment method is not supported", + Severity = StatusMessageModel.StatusSeverity.Error }); - if (result != PayoutPaidRequest.PayoutPaidResult.Ok) - { - TempData.SetStatusMessageModel(new StatusMessageModel() - { - Message = PayoutPaidRequest.GetErrorMessage(result), - Severity = StatusMessageModel.StatusSeverity.Error - }); - return RedirectToAction(nameof(Payouts), new - { - storeId = storeId, - pullPaymentId = vm.PullPaymentId, - paymentMethodId = paymentMethodId.ToString() - }); - } + break; } - TempData.SetStatusMessageModel(new StatusMessageModel() + case "mark-paid": { - Message = "Payouts marked as paid", Severity = StatusMessageModel.StatusSeverity.Success - }); - break; - } + await using var ctx = this._dbContextFactory.CreateContext(); + ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + var payouts = await GetPayoutsForPaymentMethod(paymentMethodId, ctx, payoutIds, storeId, cancellationToken); + for (int i = 0; i < payouts.Count; i++) + { + var payout = payouts[i]; + if (payout.State != PayoutState.AwaitingPayment) + continue; + + var result = await _pullPaymentService.MarkPaid(new PayoutPaidRequest() + { + PayoutId = payout.Id + }); + if (result != PayoutPaidRequest.PayoutPaidResult.Ok) + { + TempData.SetStatusMessageModel(new StatusMessageModel() + { + Message = PayoutPaidRequest.GetErrorMessage(result), + Severity = StatusMessageModel.StatusSeverity.Error + }); + return RedirectToAction(nameof(Payouts), new + { + storeId = storeId, + pullPaymentId = vm.PullPaymentId, + paymentMethodId = paymentMethodId.ToString() + }); + } + } + + TempData.SetStatusMessageModel(new StatusMessageModel() + { + Message = "Payouts marked as paid", + Severity = StatusMessageModel.StatusSeverity.Success + }); + break; + } case "cancel": await _pullPaymentService.Cancel( new PullPaymentHostedService.CancelRequest(payoutIds)); TempData.SetStatusMessageModel(new StatusMessageModel() { - Message = "Payouts archived", Severity = StatusMessageModel.StatusSeverity.Success + Message = "Payouts archived", + Severity = StatusMessageModel.StatusSeverity.Success }); break; } @@ -437,9 +445,9 @@ namespace BTCPayServer.Controllers var vm = this.ParseListQuery(new PayoutsModel { PaymentMethods = paymentMethods, - PaymentMethodId = paymentMethodId??paymentMethods.First().ToString(), - PullPaymentId = pullPaymentId, - PayoutState = payoutState, + PaymentMethodId = paymentMethodId ?? paymentMethods.First().ToString(), + PullPaymentId = pullPaymentId, + PayoutState = payoutState, Skip = skip, Count = count }); @@ -449,21 +457,21 @@ namespace BTCPayServer.Controllers if (pullPaymentId != null) { payoutRequest = payoutRequest.Where(p => p.PullPaymentDataId == vm.PullPaymentId); - vm.PullPaymentName = (await ctx.PullPayments.FindAsync(pullPaymentId)).GetBlob().Name; + vm.PullPaymentName = (await ctx.PullPayments.FindAsync(pullPaymentId)).GetBlob().Name; } - + if (vm.PaymentMethodId != null) { var pmiStr = vm.PaymentMethodId; payoutRequest = payoutRequest.Where(p => p.PaymentMethodId == pmiStr); } - + 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); } @@ -472,9 +480,9 @@ namespace BTCPayServer.Controllers .ToDictionary(pair => pair.Key, pair => pair.Value); payoutRequest = payoutRequest.Where(p => p.State == vm.PayoutState); - vm.Total = await payoutRequest.CountAsync(); + vm.Total = await payoutRequest.CountAsync(); payoutRequest = payoutRequest.Skip(vm.Skip).Take(vm.Count); - + var payouts = await payoutRequest.OrderByDescending(p => p.Date) .Select(o => new { diff --git a/BTCPayServer/Controllers/StoresController.Integrations.cs b/BTCPayServer/Controllers/StoresController.Integrations.cs index d1bc3adeb..a775526b9 100644 --- a/BTCPayServer/Controllers/StoresController.Integrations.cs +++ b/BTCPayServer/Controllers/StoresController.Integrations.cs @@ -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; @@ -15,11 +15,11 @@ namespace BTCPayServer.Controllers { [HttpGet("{storeId}/integrations")] public IActionResult Integrations() - { + { return View("Integrations", new IntegrationsViewModel()); } - - private async Task LastDeliveryForWebhook(string webhookId) + + private async Task LastDeliveryForWebhook(string webhookId) { return (await _Repo.GetWebhookDeliveries(CurrentStore.Id, webhookId, 1)).ToList().FirstOrDefault(); } @@ -29,20 +29,21 @@ 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(); - - return new WebhooksViewModel.WebhookViewModel() - { - Id = w.Id, - Url = w.GetBlob().Url, - LastDeliveryErrorMessage = lastDeliveryBlob?.ErrorMessage, - LastDeliveryTimeStamp = lastDelivery?.Timestamp, - LastDeliverySuccessful = lastDeliveryBlob == null ? true : lastDeliveryBlob.Status == WebhookDeliveryStatus.HttpSuccess, - }; - } + var lastDelivery = await LastDeliveryForWebhook(w.Id); + var lastDeliveryBlob = lastDelivery?.GetBlob(); + + return new WebhooksViewModel.WebhookViewModel() + { + Id = w.Id, + Url = w.GetBlob().Url, + LastDeliveryErrorMessage = lastDeliveryBlob?.ErrorMessage, + LastDeliveryTimeStamp = lastDelivery?.Timestamp, + LastDeliverySuccessful = lastDeliveryBlob == null ? true : lastDeliveryBlob.Status == WebhookDeliveryStatus.HttpSuccess, + }; + } ).Select(t => t.Result).ToArray() }); } @@ -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")}"; } diff --git a/BTCPayServer/Controllers/StoresController.LightningLike.cs b/BTCPayServer/Controllers/StoresController.LightningLike.cs index e442ec29f..2b1423547 100644 --- a/BTCPayServer/Controllers/StoresController.LightningLike.cs +++ b/BTCPayServer/Controllers/StoresController.LightningLike.cs @@ -131,14 +131,14 @@ namespace BTCPayServer.Controllers return View(vm); } } - + [HttpGet("{storeId}/lightning/{cryptoCode}/settings")] public async Task LightningSettings(string storeId, string cryptoCode) { var store = HttpContext.GetStoreData(); if (store == null) return NotFound(); - + var storeBlob = store.GetStoreBlob(); var vm = new LightningSettingsViewModel { @@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers OnChainWithLnInvoiceFallback = storeBlob.OnChainWithLnInvoiceFallback }; await SetExistingValues(store, vm); - + var lightning = GetExistingLightningSupportedPaymentMethod(vm.CryptoCode, store); var lnSet = lightning != null; if (lnSet) @@ -174,7 +174,7 @@ namespace BTCPayServer.Controllers //vm.LNURLEnabled = !lnSet; vm.DisableBolt11PaymentMethod = false; } - + return View(vm); } @@ -191,7 +191,7 @@ namespace BTCPayServer.Controllers ModelState.AddModelError(nameof(vm.CryptoCode), "Invalid network"); return View(vm); } - + var needUpdate = false; var blob = store.GetStoreBlob(); blob.LightningDescriptionTemplate = vm.LightningDescriptionTemplate ?? string.Empty; @@ -209,16 +209,16 @@ namespace BTCPayServer.Controllers lightning.DisableBOLT11PaymentOption = disableBolt11PaymentMethod; store.SetSupportedPaymentMethod(lightning); } - + var lnurl = GetExistingLNURLSupportedPaymentMethod(vm.CryptoCode, store); if (lnurl is null || ( - lnurl.EnableForStandardInvoices != vm.LNURLStandardInvoiceEnabled || - lnurl.UseBech32Scheme != vm.LNURLBech32Mode || + lnurl.EnableForStandardInvoices != vm.LNURLStandardInvoiceEnabled || + lnurl.UseBech32Scheme != vm.LNURLBech32Mode || lnurl.LUD12Enabled != vm.LUD12Enabled)) { needUpdate = true; } - + store.SetSupportedPaymentMethod(new LNURLPaySupportedPaymentMethod { CryptoCode = vm.CryptoCode, @@ -226,12 +226,12 @@ namespace BTCPayServer.Controllers UseBech32Scheme = vm.LNURLBech32Mode, LUD12Enabled = vm.LUD12Enabled }); - + if (store.SetStoreBlob(blob)) { needUpdate = true; } - + if (needUpdate) { await _Repo.UpdateStore(store); diff --git a/BTCPayServer/Controllers/StoresController.Onchain.cs b/BTCPayServer/Controllers/StoresController.Onchain.cs index 4a494a60e..eaa12f1f1 100644 --- a/BTCPayServer/Controllers/StoresController.Onchain.cs +++ b/BTCPayServer/Controllers/StoresController.Onchain.cs @@ -265,7 +265,7 @@ namespace BTCPayServer.Controllers SupportTaproot = network.NBitcoinNetwork.Consensus.SupportTaproot, SupportSegwit = network.NBitcoinNetwork.Consensus.SupportSegwit }; - + if (isImport && string.IsNullOrEmpty(request.ExistingMnemonic)) { ModelState.AddModelError(nameof(request.ExistingMnemonic), "Please provide your existing seed"); @@ -399,7 +399,7 @@ namespace BTCPayServer.Controllers UriScheme = derivation.Network.NBitcoinNetwork.UriScheme, Label = derivation.Label, SelectedSigningKey = derivation.SigningKey.ToString(), - NBXSeedAvailable = derivation.IsHotWallet && + NBXSeedAvailable = derivation.IsHotWallet && canUseHotWallet && !string.IsNullOrEmpty(await client.GetMetadataAsync(derivation.AccountDerivation, WellknownMetadataKeys.MasterHDKey)), @@ -416,22 +416,22 @@ namespace BTCPayServer.Controllers SpeedPolicy = store.SpeedPolicy, ShowRecommendedFee = storeBlob.ShowRecommendedFee, RecommendedFeeBlockTarget = storeBlob.RecommendedFeeBlockTarget, - CanUseHotWallet = canUseHotWallet, - CanUseRPCImport = rpcImport, + CanUseHotWallet = canUseHotWallet, + CanUseRPCImport = rpcImport, CanUsePayJoin = canUseHotWallet && store .GetSupportedPaymentMethods(_NetworkProvider) .OfType() .Any(settings => settings.Network.SupportPayJoin && settings.IsHotWallet), StoreName = store.StoreName, - + }; ViewData["ReplaceDescription"] = WalletReplaceWarning(derivation.IsHotWallet); ViewData["RemoveDescription"] = WalletRemoveWarning(derivation.IsHotWallet, network.CryptoCode); - + return View(vm); } - + [HttpPost("{storeId}/onchain/{cryptoCode}/settings/wallet")] public async Task UpdateWalletSettings(WalletSettingsViewModel vm) { @@ -446,7 +446,7 @@ namespace BTCPayServer.Controllers { return NotFound(); } - + bool needUpdate = false; string errorMessage = null; if (derivation.Label != vm.Label) @@ -454,7 +454,7 @@ namespace BTCPayServer.Controllers needUpdate = true; derivation.Label = vm.Label; } - + var signingKey = string.IsNullOrEmpty(vm.SelectedSigningKey) ? null : new BitcoinExtPubKey(vm.SelectedSigningKey, derivation.Network.NBitcoinNetwork); @@ -463,7 +463,7 @@ namespace BTCPayServer.Controllers needUpdate = true; derivation.SigningKey = signingKey; } - + for (int i = 0; i < derivation.AccountKeySettings.Length; i++) { KeyPath accountKeyPath = null; @@ -474,7 +474,7 @@ namespace BTCPayServer.Controllers accountKeyPath = string.IsNullOrWhiteSpace(vm.AccountKeys[i].AccountKeyPath) ? null : new KeyPath(vm.AccountKeys[i].AccountKeyPath); - + if (accountKeyPath != null && derivation.AccountKeySettings[i].AccountKeyPath != accountKeyPath) { needUpdate = true; @@ -491,7 +491,7 @@ namespace BTCPayServer.Controllers rootFingerprint = string.IsNullOrWhiteSpace(vm.AccountKeys[i].MasterFingerprint) ? (HDFingerprint?)null : new HDFingerprint(Encoders.Hex.DecodeData(vm.AccountKeys[i].MasterFingerprint)); - + if (rootFingerprint != null && derivation.AccountKeySettings[i].RootFingerprint != rootFingerprint) { needUpdate = true; @@ -507,7 +507,7 @@ namespace BTCPayServer.Controllers if (needUpdate) { store.SetSupportedPaymentMethod(derivation); - + await _Repo.UpdateStore(store); if (string.IsNullOrEmpty(errorMessage)) @@ -522,7 +522,7 @@ namespace BTCPayServer.Controllers return RedirectToAction(nameof(WalletSettings), new { vm.StoreId, vm.CryptoCode }); } - + [HttpPost("{storeId}/onchain/{cryptoCode}/settings/payment")] public async Task UpdatePaymentSettings(WalletSettingsViewModel vm) { @@ -537,7 +537,7 @@ namespace BTCPayServer.Controllers { return NotFound(); } - + bool needUpdate = false; if (store.SpeedPolicy != vm.SpeedPolicy) { @@ -551,7 +551,7 @@ namespace BTCPayServer.Controllers blob.ShowRecommendedFee = vm.ShowRecommendedFee; blob.RecommendedFeeBlockTarget = vm.RecommendedFeeBlockTarget; blob.PayJoinEnabled = vm.PayJoinEnabled; - + if (store.SetStoreBlob(blob)) { needUpdate = true; @@ -582,10 +582,10 @@ namespace BTCPayServer.Controllers } } } - + return RedirectToAction(nameof(WalletSettings), new { vm.StoreId, vm.CryptoCode }); } - + [HttpGet("{storeId}/onchain/{cryptoCode}/seed")] public async Task WalletSeed(string storeId, string cryptoCode, CancellationToken cancellationToken = default) { @@ -600,13 +600,13 @@ namespace BTCPayServer.Controllers { return NotFound(); } - + (bool canUseHotWallet, bool _) = await CanUseHotWallet(); if (!canUseHotWallet) { return NotFound(); } - + var client = _ExplorerProvider.GetExplorerClient(network); if (await GetSeed(client, derivation) != null) { @@ -622,7 +622,7 @@ namespace BTCPayServer.Controllers }; return this.RedirectToRecoverySeedBackup(recoveryVm); } - + TempData.SetStatusMessageModel(new StatusMessageModel { Severity = StatusMessageModel.StatusSeverity.Error, @@ -642,7 +642,7 @@ namespace BTCPayServer.Controllers } var derivation = GetExistingDerivationStrategy(cryptoCode, store); - + return View("Confirm", new ConfirmModel { Title = $"Replace {network.CryptoCode} wallet", @@ -794,7 +794,7 @@ namespace BTCPayServer.Controllers .FirstOrDefault(d => d.PaymentId == id); return existing; } - + private async Task GetSeed(ExplorerClient client, DerivationSchemeSettings derivation) { return derivation.IsHotWallet && @@ -827,14 +827,14 @@ namespace BTCPayServer.Controllers $"

Do not proceed if you have not backed up the wallet{additionalText}.

" + $"

This action will erase the current wallet data from the server. {info}

"; } - + private string WalletReplaceWarning(bool isHotWallet) { return WalletWarning(isHotWallet, "The current wallet will be replaced once you finish the setup of the new wallet. " + "If you cancel the setup, the current wallet will stay active."); } - + private string WalletRemoveWarning(bool isHotWallet, string cryptoCode) { return WalletWarning(isHotWallet, diff --git a/BTCPayServer/Controllers/StoresController.cs b/BTCPayServer/Controllers/StoresController.cs index 9c66106ec..18f1722f3 100644 --- a/BTCPayServer/Controllers/StoresController.cs +++ b/BTCPayServer/Controllers/StoresController.cs @@ -379,7 +379,7 @@ namespace BTCPayServer.Controllers }; } }).ToList(); - + vm.RequiresRefundEmail = storeBlob.RequiresRefundEmail; vm.LazyPaymentMethods = storeBlob.LazyPaymentMethods; vm.RedirectAutomatically = storeBlob.RedirectAutomatically; @@ -388,7 +388,7 @@ namespace BTCPayServer.Controllers vm.HtmlTitle = storeBlob.HtmlTitle; vm.AutoDetectLanguage = storeBlob.AutoDetectLanguage; vm.SetLanguages(_LangService, storeBlob.DefaultLang); - + return View(vm); } @@ -415,7 +415,7 @@ namespace BTCPayServer.Controllers vm.PaymentMethods = new SelectList(choices, nameof(chosen.Value), nameof(chosen.Name), chosen?.Value); vm.DefaultPaymentMethod = chosen?.Value; } - + [HttpPost] [Route("{storeId}/checkout")] public async Task CheckoutAppearance(CheckoutAppearanceViewModel model) @@ -504,7 +504,7 @@ namespace BTCPayServer.Controllers }); } - internal void AddPaymentMethods(StoreData store, StoreBlob storeBlob, + internal void AddPaymentMethods(StoreData store, StoreBlob storeBlob, out List derivationSchemes, out List lightningNodes) { var excludeFilters = storeBlob.GetExcludedPaymentMethods(); @@ -544,10 +544,10 @@ namespace BTCPayServer.Controllers #endif }); break; - + case LNURLPayPaymentType lnurlPayPaymentType: break; - + case LightningPaymentType _: var lightning = lightningByCryptoCode.TryGet(paymentMethodId.CryptoCode); var isEnabled = !excludeFilters.Match(paymentMethodId) && lightning != null; @@ -581,13 +581,13 @@ namespace BTCPayServer.Controllers InvoiceExpiration = (int)storeBlob.InvoiceExpiration.TotalMinutes, DefaultCurrency = storeBlob.DefaultCurrency }; - - AddPaymentMethods(store, storeBlob, + + AddPaymentMethods(store, storeBlob, out var derivationSchemes, out var lightningNodes); - + vm.DerivationSchemes = derivationSchemes; vm.LightningNodes = lightningNodes; - + return View(vm); } @@ -601,7 +601,7 @@ namespace BTCPayServer.Controllers blob.PaymentTolerance = model.PaymentTolerance; blob.DefaultCurrency = model.DefaultCurrency; blob.InvoiceExpiration = TimeSpan.FromMinutes(model.InvoiceExpiration); - + if (CurrentStore.SetStoreBlob(blob)) { needUpdate = true; @@ -619,7 +619,7 @@ namespace BTCPayServer.Controllers storeId = CurrentStore.Id }); } - + [HttpGet("{storeId}/settings")] public IActionResult GeneralSettings() { @@ -634,7 +634,7 @@ namespace BTCPayServer.Controllers StoreWebsite = store.StoreWebsite, CanDelete = _Repo.CanDeleteStores() }; - + return View(vm); } @@ -647,7 +647,7 @@ namespace BTCPayServer.Controllers needUpdate = true; CurrentStore.StoreName = model.StoreName; } - + if (CurrentStore.StoreWebsite != model.StoreWebsite) { needUpdate = true; @@ -666,7 +666,7 @@ namespace BTCPayServer.Controllers storeId = CurrentStore.Id }); } - + [HttpGet("{storeId}/delete")] public IActionResult DeleteStore(string storeId) { @@ -737,7 +737,7 @@ namespace BTCPayServer.Controllers model.EncodedApiKey = Encoders.Base64.EncodeData(Encoders.ASCII.DecodeData(model.ApiKey)); return View(model); } - + [HttpGet("{storeId}/tokens/{tokenId}/revoke")] public async Task RevokeToken(string tokenId) { @@ -746,7 +746,7 @@ namespace BTCPayServer.Controllers return NotFound(); return View("Confirm", new ConfirmModel("Revoke the token", $"The access token with the label {token.Label} will be revoked. Do you wish to continue?", "Revoke")); } - + [HttpPost("{storeId}/tokens/{tokenId}/revoke")] public async Task RevokeTokenConfirm(string tokenId) { diff --git a/BTCPayServer/Controllers/UserStoresController.cs b/BTCPayServer/Controllers/UserStoresController.cs index ee55e6b56..48a2b219c 100644 --- a/BTCPayServer/Controllers/UserStoresController.cs +++ b/BTCPayServer/Controllers/UserStoresController.cs @@ -90,9 +90,9 @@ namespace BTCPayServer.Controllers { StoresViewModel result = new StoresViewModel(); var stores = await _repo.GetStoresByUserId(GetUserId()); - if (sortOrder != null && sortOrderColumn != null) + if (sortOrder != null && sortOrderColumn != null) { - stores = stores.OrderByDescending(store => + stores = stores.OrderByDescending(store => { switch (sortOrderColumn) { @@ -124,7 +124,7 @@ namespace BTCPayServer.Controllers result.Stores.Add(new StoresViewModel.StoreViewModel() { Id = store.Id, - + Name = store.StoreName, WebSite = store.StoreWebsite, IsOwner = store.Role == StoreRoles.Owner, diff --git a/BTCPayServer/Controllers/WalletsController.PSBT.cs b/BTCPayServer/Controllers/WalletsController.PSBT.cs index 08d7be6e9..ee12e3c8f 100644 --- a/BTCPayServer/Controllers/WalletsController.PSBT.cs +++ b/BTCPayServer/Controllers/WalletsController.PSBT.cs @@ -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; @@ -86,7 +86,7 @@ namespace BTCPayServer.Controllers if (await vm.GetPSBT(network.NBitcoinNetwork) is PSBT psbt) { vm.PSBT = vm.SigningContext.PSBT = psbt.ToBase64(); - vm.PSBTHex = psbt.ToHex(); + vm.PSBTHex = psbt.ToHex(); vm.Decoded = psbt.ToString(); await FetchTransactionDetails(derivationSchemeSettings, vm, network); return View("WalletPSBTDecoded", vm); @@ -135,7 +135,7 @@ namespace BTCPayServer.Controllers vm.Decoded = psbt.ToString(); await FetchTransactionDetails(derivationSchemeSettings, vm, network); return View("WalletPSBTDecoded", vm); - + case "save-psbt": return FilePSBT(psbt, vm.FileName); @@ -152,7 +152,7 @@ namespace BTCPayServer.Controllers PSBT = psbt.ToBase64(), FileName = vm.FileName }); - + case "combine": ModelState.Remove(nameof(vm.PSBT)); return View(nameof(WalletPSBTCombine), new WalletPSBTCombineViewModel { OtherPSBT = psbt.ToBase64() }); @@ -164,7 +164,7 @@ namespace BTCPayServer.Controllers SigningContext = new SigningContextModel(psbt) }); } - + default: var viewName = string.IsNullOrEmpty(vm.PSBT) ? "WalletPSBT" : "WalletPSBTDecoded"; return View(viewName, vm); @@ -290,7 +290,7 @@ namespace BTCPayServer.Controllers { if (command == null) return await WalletPSBT(walletId, vm); - + PSBT psbt; var network = NetworkProvider.GetNetwork(walletId.CryptoCode); DerivationSchemeSettings derivationSchemeSettings; @@ -300,7 +300,7 @@ namespace BTCPayServer.Controllers derivationSchemeSettings = GetDerivationSchemeSettings(walletId); if (derivationSchemeSettings == null) return NotFound(); - + await FetchTransactionDetails(derivationSchemeSettings, vm, network); } catch diff --git a/BTCPayServer/Controllers/WalletsController.cs b/BTCPayServer/Controllers/WalletsController.cs index 40e24377d..a0404dfad 100644 --- a/BTCPayServer/Controllers/WalletsController.cs +++ b/BTCPayServer/Controllers/WalletsController.cs @@ -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; @@ -112,7 +112,7 @@ namespace BTCPayServer.Controllers } // Borrowed from https://github.com/ManageIQ/guides/blob/master/labels.md - readonly string[] LabelColorScheme = + readonly string[] LabelColorScheme = { "#fbca04", "#0e8a16", @@ -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 @@ -276,9 +277,9 @@ namespace BTCPayServer.Controllers [HttpGet("{walletId}/transactions")] public async Task WalletTransactions( [ModelBinder(typeof(WalletIdModelBinder))] - WalletId walletId, + WalletId walletId, string labelFilter = null, - int skip = 0, + int skip = 0, int count = 50 ) { @@ -454,7 +455,7 @@ namespace BTCPayServer.Controllers { if (!string.IsNullOrEmpty(link)) { - + LoadFromBIP21(model, link, network); } } @@ -492,13 +493,13 @@ 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; else model.ImmatureBalance = Balance.Immature.GetValue(network); - + await Task.WhenAll(recommendedFees); model.RecommendedSatoshiPerByte = recommendedFees.Select(tuple => tuple.Result).Where(option => option != null).ToList(); @@ -697,7 +698,7 @@ namespace BTCPayServer.Controllers } if (!ModelState.IsValid) return View(vm); - + DerivationSchemeSettings derivationScheme = GetDerivationSchemeSettings(walletId); CreatePSBTResponse psbtResponse; try @@ -717,7 +718,7 @@ namespace BTCPayServer.Controllers var psbt = psbtResponse.PSBT; derivationScheme.RebaseKeyPaths(psbt); - + var signingContext = new SigningContextModel { PayJoinBIP21 = vm.PayJoinBIP21, @@ -777,9 +778,9 @@ namespace BTCPayServer.Controllers try { vm.Outputs.Add(new WalletSendModel.TransactionOutput() - { - DestinationAddress = BitcoinAddress.Create(bip21, network.NBitcoinNetwork).ToString() - } + { + DestinationAddress = BitcoinAddress.Create(bip21, network.NBitcoinNetwork).ToString() + } ); } catch @@ -815,7 +816,7 @@ namespace BTCPayServer.Controllers SigningContext = model.SigningContext }); } - + private IActionResult RedirectToWalletPSBTReady(WalletPSBTReadyViewModel vm) { var redirectVm = new PostRedirectViewModel @@ -833,7 +834,7 @@ namespace BTCPayServer.Controllers !string.IsNullOrEmpty(vm.SigningContext.PSBT)) { //if a hw device signed a payjoin, we want it broadcast instantly - redirectVm.Parameters.Add(new KeyValuePair("command", "broadcast")); + redirectVm.Parameters.Add(new KeyValuePair("command", "broadcast")); } return View("PostRedirect", redirectVm); } @@ -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."); @@ -1061,7 +1062,7 @@ namespace BTCPayServer.Controllers return "--"; } } - + [HttpPost("{walletId}/actions")] public async Task WalletActions( [ModelBinder(typeof(WalletIdModelBinder))] @@ -1075,35 +1076,35 @@ namespace BTCPayServer.Controllers switch (command) { case "prune": - { - var result = await ExplorerClientProvider.GetExplorerClient(walletId.CryptoCode).PruneAsync(derivationScheme.AccountDerivation, new PruneRequest(), cancellationToken); - if (result.TotalPruned == 0) { - TempData[WellKnownTempData.SuccessMessage] = "The wallet is already pruned"; - } - else - { - TempData[WellKnownTempData.SuccessMessage] = - $"The wallet has been successfully pruned ({result.TotalPruned} transactions have been removed from the history)"; - } + var result = await ExplorerClientProvider.GetExplorerClient(walletId.CryptoCode).PruneAsync(derivationScheme.AccountDerivation, new PruneRequest(), cancellationToken); + if (result.TotalPruned == 0) + { + TempData[WellKnownTempData.SuccessMessage] = "The wallet is already pruned"; + } + else + { + TempData[WellKnownTempData.SuccessMessage] = + $"The wallet has been successfully pruned ({result.TotalPruned} transactions have been removed from the history)"; + } - return RedirectToAction(nameof(WalletTransactions), new { walletId }); - } + return RedirectToAction(nameof(WalletTransactions), new { walletId }); + } case "clear" when User.IsInRole(Roles.ServerAdmin): - { - if (Version.TryParse(_dashboard.Get(walletId.CryptoCode)?.Status?.Version ?? "0.0.0.0", out var v) && - v < new Version(2, 2, 4)) { - TempData[WellKnownTempData.ErrorMessage] = "This version of NBXplorer doesn't support this operation, please upgrade to 2.2.4 or above"; + if (Version.TryParse(_dashboard.Get(walletId.CryptoCode)?.Status?.Version ?? "0.0.0.0", out var v) && + v < new Version(2, 2, 4)) + { + TempData[WellKnownTempData.ErrorMessage] = "This version of NBXplorer doesn't support this operation, please upgrade to 2.2.4 or above"; + } + else + { + await ExplorerClientProvider.GetExplorerClient(walletId.CryptoCode) + .WipeAsync(derivationScheme.AccountDerivation, cancellationToken); + TempData[WellKnownTempData.SuccessMessage] = "The transactions have been wiped out, to restore your balance, rescan the wallet."; + } + return RedirectToAction(nameof(WalletTransactions), new { walletId }); } - else - { - await ExplorerClientProvider.GetExplorerClient(walletId.CryptoCode) - .WipeAsync(derivationScheme.AccountDerivation, cancellationToken); - TempData[WellKnownTempData.SuccessMessage] = "The transactions have been wiped out, to restore your balance, rescan the wallet."; - } - return RedirectToAction(nameof(WalletTransactions), new { walletId }); - } default: return NotFound(); } diff --git a/BTCPayServer/Data/Payouts/BitcoinLike/AddressClaimDestination.cs b/BTCPayServer/Data/Payouts/BitcoinLike/AddressClaimDestination.cs index c0af94043..98ba1d262 100644 --- a/BTCPayServer/Data/Payouts/BitcoinLike/AddressClaimDestination.cs +++ b/BTCPayServer/Data/Payouts/BitcoinLike/AddressClaimDestination.cs @@ -5,7 +5,7 @@ namespace BTCPayServer.Data { public class AddressClaimDestination : IBitcoinLikeClaimDestination { - public BitcoinAddress _bitcoinAddress; + public BitcoinAddress _bitcoinAddress; public AddressClaimDestination(BitcoinAddress bitcoinAddress) { diff --git a/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs b/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs index 88ac336b9..7af811ab8 100644 --- a/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs +++ b/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs @@ -37,10 +37,10 @@ public class BitcoinLikePayoutHandler : IPayoutHandler private readonly NotificationSender _notificationSender; private readonly Logs Logs; public BitcoinLikePayoutHandler(BTCPayNetworkProvider btcPayNetworkProvider, - ExplorerClientProvider explorerClientProvider, + ExplorerClientProvider explorerClientProvider, BTCPayNetworkJsonSerializerSettings jsonSerializerSettings, - ApplicationDbContextFactory dbContextFactory, - EventAggregator eventAggregator, + ApplicationDbContextFactory dbContextFactory, + EventAggregator eventAggregator, NotificationSender notificationSender, Logs logs) { @@ -97,7 +97,7 @@ public class BitcoinLikePayoutHandler : IPayoutHandler { return null; } - var raw = JObject.Parse(Encoding.UTF8.GetString(payout.Proof)); + var raw = JObject.Parse(Encoding.UTF8.GetString(payout.Proof)); if (raw.TryGetValue("proofType", StringComparison.InvariantCultureIgnoreCase, out var proofType) && proofType.Value() == ManualPayoutProof.Type) { @@ -106,14 +106,15 @@ public class BitcoinLikePayoutHandler : IPayoutHandler var res = raw.ToObject( JsonSerializer.Create(_jsonSerializerSettings.GetSerializer(paymentMethodId.CryptoCode))); var network = _btcPayNetworkProvider.GetNetwork(paymentMethodId.CryptoCode); - if (res == null) return null; + if (res == null) + return null; res.LinkTemplate = network.BlockExplorerLink; return res; } public void StartBackgroundCheck(Action subscribe) { - subscribe(new[] {typeof(NewOnChainTransactionEvent), typeof(NewBlockEvent)}); + subscribe(new[] { typeof(NewOnChainTransactionEvent), typeof(NewBlockEvent) }); } public async Task BackgroundCheck(object o) @@ -170,9 +171,9 @@ public class BitcoinLikePayoutHandler : IPayoutHandler .Where(p => payoutIds.Contains(p.Id)) .Where(p => p.PullPaymentData.StoreId == storeId && !p.PullPaymentData.Archived && p.State == PayoutState.AwaitingPayment) .ToListAsync()).Where(data => - PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) && + 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; @@ -196,10 +197,10 @@ public class BitcoinLikePayoutHandler : IPayoutHandler .Include(p => p.PullPaymentData.StoreData) .Where(p => payoutIds.Contains(p.Id)) .Where(p => p.PullPaymentData.StoreId == storeId && !p.PullPaymentData.Archived && p.State == PayoutState.AwaitingPayment) - .ToListAsync()).Where(data => - PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) && + .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,22 +226,22 @@ public class BitcoinLikePayoutHandler : IPayoutHandler .Where(id => id.PaymentType == BitcoinPaymentType.Instance)); } - public async Task InitiatePayment(PaymentMethodId paymentMethodId ,string[] payoutIds) + public async Task InitiatePayment(PaymentMethodId paymentMethodId, string[] payoutIds) { await using var ctx = this._dbContextFactory.CreateContext(); ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var pmi = paymentMethodId.ToString(); var payouts = await ctx.Payouts.Include(data => data.PullPaymentData) - .Where(data => payoutIds.Contains(data.Id) - && pmi == data.PaymentMethodId + .Where(data => payoutIds.Contains(data.Id) + && pmi == data.PaymentMethodId && data.State == PayoutState.AwaitingPayment) .ToListAsync(); var pullPaymentIds = payouts.Select(data => data.PullPaymentDataId).Distinct().ToArray(); var storeId = payouts.First().PullPaymentData.StoreId; var network = _btcPayNetworkProvider.GetNetwork(paymentMethodId.CryptoCode); - List bip21 = new List(); + List bip21 = new List(); foreach (var payout in payouts) { if (payout.Proof != null) @@ -260,14 +261,14 @@ public class BitcoinLikePayoutHandler : IPayoutHandler case AddressClaimDestination addressClaimDestination: bip21.Add(network.GenerateBIP21(addressClaimDestination.Address.ToString(), new Money(blob.CryptoAmount.Value, MoneyUnit.BTC)).ToString()); 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; diff --git a/BTCPayServer/Data/Payouts/BitcoinLike/PayoutTransactionOnChainBlob.cs b/BTCPayServer/Data/Payouts/BitcoinLike/PayoutTransactionOnChainBlob.cs index ebfd3dd24..ddaa94c9b 100644 --- a/BTCPayServer/Data/Payouts/BitcoinLike/PayoutTransactionOnChainBlob.cs +++ b/BTCPayServer/Data/Payouts/BitcoinLike/PayoutTransactionOnChainBlob.cs @@ -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; } diff --git a/BTCPayServer/Data/Payouts/IPayoutHandler.cs b/BTCPayServer/Data/Payouts/IPayoutHandler.cs index b73c55e58..ab74fa200 100644 --- a/BTCPayServer/Data/Payouts/IPayoutHandler.cs +++ b/BTCPayServer/Data/Payouts/IPayoutHandler.cs @@ -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 diff --git a/BTCPayServer/Data/Payouts/LightningLike/LNURLPayClaimDestinaton.cs b/BTCPayServer/Data/Payouts/LightningLike/LNURLPayClaimDestinaton.cs index 6822ef4b2..0055d92b8 100644 --- a/BTCPayServer/Data/Payouts/LightningLike/LNURLPayClaimDestinaton.cs +++ b/BTCPayServer/Data/Payouts/LightningLike/LNURLPayClaimDestinaton.cs @@ -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) { diff --git a/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutController.cs b/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutController.cs index 56b7f3348..ff01e35d5 100644 --- a/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutController.cs +++ b/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutController.cs @@ -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); @@ -124,9 +127,9 @@ namespace BTCPayServer.Data.Payouts.LightningLike { results.Add(new ResultVM() { - PayoutId = payoutData.Id, + PayoutId = payoutData.Id, Result = PayResult.Error, - Message = $"The BOLT11 invoice amount did not match the payout's amount ({boltAmount} instead of {payoutBlob.CryptoAmount})", + Message = $"The BOLT11 invoice amount did not match the payout's amount ({boltAmount} instead of {payoutBlob.CryptoAmount})", Destination = payoutBlob.Destination }); return; @@ -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,16 +149,18 @@ 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 }); } } - var authorizedForInternalNode = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded; + var authorizedForInternalNode = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded; foreach (var payoutDatas in payouts) { var store = payoutDatas.First().PullPaymentData.StoreData; - + var lightningSupportedPaymentMethod = store.GetSupportedPaymentMethods(_btcPayNetworkProvider) .OfType() .FirstOrDefault(method => method.PaymentId == pmi); @@ -162,7 +169,7 @@ namespace BTCPayServer.Data.Payouts.LightningLike { foreach (PayoutData payoutData in payoutDatas) { - + var blob = payoutData.GetBlob(_btcPayNetworkJsonSerializerSettings); results.Add(new ResultVM() { @@ -176,7 +183,7 @@ namespace BTCPayServer.Data.Payouts.LightningLike continue; } - + var client = lightningSupportedPaymentMethod.CreateLightningClient(network, _options.Value, _lightningClientFactoryService); @@ -213,7 +220,7 @@ namespace BTCPayServer.Data.Payouts.LightningLike { var lnurlPayRequestCallbackResponse = await lnurlInfo.SendRequest(lm, network.NBitcoinNetwork, httpClient); - + await TrypayBolt(client, blob, payoutData, lnurlPayRequestCallbackResponse.GetPaymentRequest(network.NBitcoinNetwork)); } catch (LNUrlException e) @@ -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 }); } } diff --git a/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutHandler.cs b/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutHandler.cs index 4bb9cf9d4..0d1242664 100644 --- a/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutHandler.cs +++ b/BTCPayServer/Data/Payouts/LightningLike/LightningLikePayoutHandler.cs @@ -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, @@ -139,7 +140,7 @@ namespace BTCPayServer.Data.Payouts.LightningLike public async Task> GetSupportedPaymentMethods(StoreData storeData) { var result = new List(); - var methods = storeData.GetEnabledPaymentMethods(_btcPayNetworkProvider).Where(id => id.PaymentId.PaymentType == LightningPaymentType.Instance).OfType(); + var methods = storeData.GetEnabledPaymentMethods(_btcPayNetworkProvider).Where(id => id.PaymentId.PaymentType == LightningPaymentType.Instance).OfType(); foreach (LightningSupportedPaymentMethod supportedPaymentMethod in methods) { if (!supportedPaymentMethod.IsInternalNode) @@ -150,11 +151,12 @@ 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; } - + } return result; diff --git a/BTCPayServer/Data/Payouts/LightningLike/PayoutLightningBlob.cs b/BTCPayServer/Data/Payouts/LightningLike/PayoutLightningBlob.cs index f0fc5294a..243e8260c 100644 --- a/BTCPayServer/Data/Payouts/LightningLike/PayoutLightningBlob.cs +++ b/BTCPayServer/Data/Payouts/LightningLike/PayoutLightningBlob.cs @@ -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; } diff --git a/BTCPayServer/Data/Payouts/PayoutExtensions.cs b/BTCPayServer/Data/Payouts/PayoutExtensions.cs index 474bacc40..7e85604d8 100644 --- a/BTCPayServer/Data/Payouts/PayoutExtensions.cs +++ b/BTCPayServer/Data/Payouts/PayoutExtensions.cs @@ -26,10 +26,10 @@ namespace BTCPayServer.Data return null; return payout; } - + 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 @@ -56,7 +56,7 @@ namespace BTCPayServer.Data this IEnumerable payoutHandlers, StoreData storeData) { return (await Task.WhenAll(payoutHandlers.Select(handler => handler.GetSupportedPaymentMethods(storeData)))).SelectMany(ids => ids).ToList(); - + } } } diff --git a/BTCPayServer/Data/PullPayments/PullPaymentBlob.cs b/BTCPayServer/Data/PullPayments/PullPaymentBlob.cs index afe15dbf4..c92768333 100644 --- a/BTCPayServer/Data/PullPayments/PullPaymentBlob.cs +++ b/BTCPayServer/Data/PullPayments/PullPaymentBlob.cs @@ -21,7 +21,7 @@ namespace BTCPayServer.Data [JsonProperty(ItemConverterType = typeof(PaymentMethodIdJsonConverter))] public PaymentMethodId[] SupportedPaymentMethods { get; set; } - + public class PullPaymentView { public string Title { get; set; } diff --git a/BTCPayServer/Data/PullPayments/PullPaymentsExtensions.cs b/BTCPayServer/Data/PullPayments/PullPaymentsExtensions.cs index 5db09ba97..a4989a90e 100644 --- a/BTCPayServer/Data/PullPayments/PullPaymentsExtensions.cs +++ b/BTCPayServer/Data/PullPayments/PullPaymentsExtensions.cs @@ -7,7 +7,7 @@ namespace BTCPayServer.Data { public static class PullPaymentsExtensions { - + public static PullPaymentBlob GetBlob(this PullPaymentData data) { return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data.Blob)); diff --git a/BTCPayServer/Data/StoreBlob.cs b/BTCPayServer/Data/StoreBlob.cs index 4dabe982b..635dcf0d0 100644 --- a/BTCPayServer/Data/StoreBlob.cs +++ b/BTCPayServer/Data/StoreBlob.cs @@ -41,12 +41,12 @@ namespace BTCPayServer.Data public bool ShowRecommendedFee { get; set; } public int RecommendedFeeBlockTarget { get; set; } string _DefaultCurrency; - public string DefaultCurrency - { - get - { + public string DefaultCurrency + { + get + { return string.IsNullOrEmpty(_DefaultCurrency) ? "USD" : _DefaultCurrency; - } + } set { _DefaultCurrency = value; diff --git a/BTCPayServer/Data/StoreDataExtensions.cs b/BTCPayServer/Data/StoreDataExtensions.cs index 7a146cd91..35a4e320b 100644 --- a/BTCPayServer/Data/StoreDataExtensions.cs +++ b/BTCPayServer/Data/StoreDataExtensions.cs @@ -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 { @@ -25,7 +25,7 @@ namespace BTCPayServer.Data { return GetEnabledPaymentMethods(storeData, networks).Select(method => method.PaymentId).ToArray(); } - + public static ISupportedPaymentMethod[] GetEnabledPaymentMethods(this StoreData storeData, BTCPayNetworkProvider networks) { var excludeFilter = storeData.GetStoreBlob().GetExcludedPaymentMethods(); @@ -147,7 +147,7 @@ namespace BTCPayServer.Data storeData.DerivationStrategies = strategies.ToString(); #pragma warning restore CS0618 } - + public static bool IsLightningEnabled(this StoreData storeData, BTCPayNetworkProvider networks) { var paymentMethods = storeData.GetSupportedPaymentMethods(networks); diff --git a/BTCPayServer/Data/WalletTransactionDataExtensions.cs b/BTCPayServer/Data/WalletTransactionDataExtensions.cs index e2ed6c03b..040fb351e 100644 --- a/BTCPayServer/Data/WalletTransactionDataExtensions.cs +++ b/BTCPayServer/Data/WalletTransactionDataExtensions.cs @@ -49,7 +49,7 @@ namespace BTCPayServer.Data return blobInfo; } static JsonSerializerSettings LabelSerializerSettings = new JsonSerializerSettings() - { + { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.None }; diff --git a/BTCPayServer/Data/WebhookDataExtensions.cs b/BTCPayServer/Data/WebhookDataExtensions.cs index 53de1037a..ffc03c3b1 100644 --- a/BTCPayServer/Data/WebhookDataExtensions.cs +++ b/BTCPayServer/Data/WebhookDataExtensions.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.Data } } - + public class WebhookDeliveryBlob { [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] diff --git a/BTCPayServer/DerivationSchemeParser.cs b/BTCPayServer/DerivationSchemeParser.cs index 32b1f5a2e..f74dfc0e3 100644 --- a/BTCPayServer/DerivationSchemeParser.cs +++ b/BTCPayServer/DerivationSchemeParser.cs @@ -37,16 +37,16 @@ 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(); } } - + 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]"); @@ -82,7 +82,7 @@ namespace BTCPayServer case OutputDescriptor.WSH wsh: if (wsh.Inner is OutputDescriptor.Multi) { - return ParseOutputDescriptor(wsh.Inner.ToString()); + return ParseOutputDescriptor(wsh.Inner.ToString()); } throw new FormatException("wsh descriptors are only supported with multisig"); default: diff --git a/BTCPayServer/EventAggregator.cs b/BTCPayServer/EventAggregator.cs index 92188151d..ad7641346 100644 --- a/BTCPayServer/EventAggregator.cs +++ b/BTCPayServer/EventAggregator.cs @@ -114,8 +114,8 @@ namespace BTCPayServer s.Act = (o) => subscription(s, (T)o); return Subscribe(eventType, s); } - - public IEventAggregatorSubscription Subscribe(Type eventType, Action subscription) + + public IEventAggregatorSubscription Subscribe(Type eventType, Action subscription) { var s = new Subscription(this, eventType); s.Act = (o) => subscription(s, o); diff --git a/BTCPayServer/Events/InvoiceDataChangedEvent.cs b/BTCPayServer/Events/InvoiceDataChangedEvent.cs index ea0fe971f..e8339dbce 100644 --- a/BTCPayServer/Events/InvoiceDataChangedEvent.cs +++ b/BTCPayServer/Events/InvoiceDataChangedEvent.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Services.Invoices; +using BTCPayServer.Services.Invoices; namespace BTCPayServer.Events { diff --git a/BTCPayServer/Events/InvoicePaymentMethodActivated.cs b/BTCPayServer/Events/InvoicePaymentMethodActivated.cs index dbd73e351..af6b46075 100644 --- a/BTCPayServer/Events/InvoicePaymentMethodActivated.cs +++ b/BTCPayServer/Events/InvoicePaymentMethodActivated.cs @@ -14,7 +14,7 @@ namespace BTCPayServer.Events InvoiceEntity = invoiceEntity; } - public string InvoiceId => InvoiceEntity.Id; + public string InvoiceId => InvoiceEntity.Id; public override string ToString() { diff --git a/BTCPayServer/Extensions.cs b/BTCPayServer/Extensions.cs index ccfba0d18..538d38e48 100644 --- a/BTCPayServer/Extensions.cs +++ b/BTCPayServer/Extensions.cs @@ -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; @@ -231,7 +231,7 @@ namespace BTCPayServer return false; } - + public static StatusMessageModel GetStatusMessageModel(this ITempDataDictionary tempData) { @@ -410,7 +410,7 @@ namespace BTCPayServer result = default; return false; } - + public static UserPrefsCookie GetUserPrefsCookie(this HttpContext ctx) { var prefCookie = new UserPrefsCookie(); @@ -441,11 +441,11 @@ namespace BTCPayServer { return ctx.Items.TryGet("BTCPAY.STOREDATA") as StoreData; } - + public static void SetStoreData(this HttpContext ctx, StoreData storeData) { ctx.Items["BTCPAY.STOREDATA"] = storeData; - + SetCurrentStoreId(ctx, storeData.Id); } @@ -453,7 +453,7 @@ namespace BTCPayServer { return ctx.Items.TryGet("BTCPAY.STORESDATA") as StoreData[]; } - + public static void SetStoresData(this HttpContext ctx, StoreData[] storeData) { ctx.Items["BTCPAY.STORESDATA"] = storeData; @@ -463,7 +463,7 @@ namespace BTCPayServer { return ctx.Items.TryGet("BTCPAY.INVOICEDATA") as InvoiceEntity; } - + public static void SetInvoiceData(this HttpContext ctx, InvoiceEntity invoiceEntity) { ctx.Items["BTCPAY.INVOICEDATA"] = invoiceEntity; @@ -473,7 +473,7 @@ namespace BTCPayServer { return ctx.Items.TryGet("BTCPAY.PAYMENTREQUESTDATA") as PaymentRequestData; } - + public static void SetPaymentRequestData(this HttpContext ctx, PaymentRequestData paymentRequestData) { ctx.Items["BTCPAY.PAYMENTREQUESTDATA"] = paymentRequestData; @@ -483,7 +483,7 @@ namespace BTCPayServer { return ctx.Items.TryGet("BTCPAY.APPDATA") as AppData; } - + public static void SetAppData(this HttpContext ctx, AppData appData) { ctx.Items["BTCPAY.APPDATA"] = appData; @@ -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; } diff --git a/BTCPayServer/Extensions/ActionLogicExtensions.cs b/BTCPayServer/Extensions/ActionLogicExtensions.cs index 81585ebed..78f67b759 100644 --- a/BTCPayServer/Extensions/ActionLogicExtensions.cs +++ b/BTCPayServer/Extensions/ActionLogicExtensions.cs @@ -16,7 +16,7 @@ namespace BTCPayServer // It's much better that we extract those common methods then copy paste and maintain same code across codebase internal static class ActionLogicExtensions { - internal static async Task FirstAdminRegistered(this SettingsRepository settingsRepository, PoliciesSettings policies, + internal static async Task FirstAdminRegistered(this SettingsRepository settingsRepository, PoliciesSettings policies, bool updateCheck, bool disableRegistrations, Logs logs) { if (updateCheck) diff --git a/BTCPayServer/Extensions/AuthorizationExtensions.cs b/BTCPayServer/Extensions/AuthorizationExtensions.cs index a9f9f3d2f..821bf6994 100644 --- a/BTCPayServer/Extensions/AuthorizationExtensions.cs +++ b/BTCPayServer/Extensions/AuthorizationExtensions.cs @@ -28,7 +28,7 @@ namespace BTCPayServer isAdmin = user.IsInRole(Roles.ServerAdmin); else if (claimUser.AuthenticationType == GreenFieldConstants.AuthenticationType) isAdmin = (await authorizationService.AuthorizeAsync(user, Policies.CanModifyServerSettings)).Succeeded; - return isAdmin ? (true, true) : + return isAdmin ? (true, true) : (policiesSettings?.AllowHotWalletForAll is true, policiesSettings?.AllowHotWalletRPCImportForAll is true); } } diff --git a/BTCPayServer/Extensions/EmailSenderExtensions.cs b/BTCPayServer/Extensions/EmailSenderExtensions.cs index 205615649..4f69bcc8a 100644 --- a/BTCPayServer/Extensions/EmailSenderExtensions.cs +++ b/BTCPayServer/Extensions/EmailSenderExtensions.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Services private static string CallToAction(string actionName, string actionLink) { string button = $"{BUTTON_HTML}".Replace("{button_description}", actionName, System.StringComparison.InvariantCulture); - button = button.Replace("{button_link}", actionLink, System.StringComparison.InvariantCulture); + button = button.Replace("{button_link}", actionLink, System.StringComparison.InvariantCulture); return button; } @@ -21,7 +21,7 @@ namespace BTCPayServer.Services emailSender.SendEmail(email, "Confirm your email", $"Please confirm your account by clicking this link: link"); } - + public static void SendSetPasswordConfirmation(this IEmailSender emailSender, string email, string link, bool newPassword) { var subject = $"{(newPassword ? "Set" : "Update")} Password"; diff --git a/BTCPayServer/Extensions/EnumExtensions.cs b/BTCPayServer/Extensions/EnumExtensions.cs index 7dfc9e1c9..297a8285f 100644 --- a/BTCPayServer/Extensions/EnumExtensions.cs +++ b/BTCPayServer/Extensions/EnumExtensions.cs @@ -7,7 +7,7 @@ namespace BTCPayServer { public static class EnumExtensions { - public static string DisplayName(this Type enumType, string input) => + public static string DisplayName(this Type enumType, string input) => enumType.GetMember(input).First().GetCustomAttribute()?.Name ?? input; } } diff --git a/BTCPayServer/Extensions/MoneyExtensions.cs b/BTCPayServer/Extensions/MoneyExtensions.cs index fa4bf9ca5..5db82f6b9 100644 --- a/BTCPayServer/Extensions/MoneyExtensions.cs +++ b/BTCPayServer/Extensions/MoneyExtensions.cs @@ -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) { diff --git a/BTCPayServer/Extensions/SettingsRepositoryExtensions.cs b/BTCPayServer/Extensions/SettingsRepositoryExtensions.cs index 0704b2205..957eda39f 100644 --- a/BTCPayServer/Extensions/SettingsRepositoryExtensions.cs +++ b/BTCPayServer/Extensions/SettingsRepositoryExtensions.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using BTCPayServer.Abstractions.Contracts; using BTCPayServer.Services; diff --git a/BTCPayServer/Extensions/StringExtensions.cs b/BTCPayServer/Extensions/StringExtensions.cs index 9ff3ac485..5684e19f5 100644 --- a/BTCPayServer/Extensions/StringExtensions.cs +++ b/BTCPayServer/Extensions/StringExtensions.cs @@ -12,7 +12,8 @@ namespace BTCPayServer { return input.Substring(0, input.Length - suffixToRemove.Length); } - else return input; + else + return input; } } } diff --git a/BTCPayServer/Extensions/UrlHelperExtensions.cs b/BTCPayServer/Extensions/UrlHelperExtensions.cs index 4168fff18..ace01884b 100644 --- a/BTCPayServer/Extensions/UrlHelperExtensions.cs +++ b/BTCPayServer/Extensions/UrlHelperExtensions.cs @@ -15,14 +15,14 @@ namespace Microsoft.AspNetCore.Mvc new { userId, code }, scheme, host, pathbase); } - public static string ResetPasswordCallbackLink(this LinkGenerator urlHelper, string userId, string code, string scheme, HostString host, string pathbase) + public static string ResetPasswordCallbackLink(this LinkGenerator urlHelper, string userId, string code, string scheme, HostString host, string pathbase) { return urlHelper.GetUriByAction( action: nameof(AccountController.SetPassword), controller: "Account", values: new { userId, code }, scheme: scheme, - host:host, + host: host, pathBase: pathbase ); } @@ -36,12 +36,12 @@ namespace Microsoft.AspNetCore.Mvc scheme, host, pathbase); } - public static string AppLink(this LinkGenerator urlHelper, string appId, string scheme, HostString host, string pathbase) + public static string AppLink(this LinkGenerator urlHelper, string appId, string scheme, HostString host, string pathbase) { return urlHelper.GetUriByAction( action: nameof(AppsPublicController.RedirectToApp), controller: "AppsPublic", - values: new { appId }, + values: new { appId }, scheme, host, 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); } } diff --git a/BTCPayServer/Extensions/UserExtensions.cs b/BTCPayServer/Extensions/UserExtensions.cs index aceb8f171..8b652b775 100644 --- a/BTCPayServer/Extensions/UserExtensions.cs +++ b/BTCPayServer/Extensions/UserExtensions.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using BTCPayServer.Data; using BTCPayServer.Services.Invoices; using Newtonsoft.Json.Linq; @@ -7,23 +7,23 @@ namespace BTCPayServer { public static class UserExtensions { - public static UserBlob GetBlob(this ApplicationUser user) + public static UserBlob GetBlob(this ApplicationUser user) + { + var result = user.Blob == null + ? new UserBlob() + : JObject.Parse(ZipUtils.Unzip(user.Blob)).ToObject(); + return result; + } + public static bool SetBlob(this ApplicationUser user, UserBlob blob) + { + var newBytes = InvoiceRepository.ToBytes(blob); + if (user.Blob != null && newBytes.SequenceEqual(user.Blob)) { - var result = user.Blob == null - ? new UserBlob() - : JObject.Parse(ZipUtils.Unzip(user.Blob)).ToObject(); - return result; - } - public static bool SetBlob(this ApplicationUser user, UserBlob blob) - { - var newBytes = InvoiceRepository.ToBytes(blob); - if (user.Blob != null && newBytes.SequenceEqual(user.Blob)) - { - return false; - } - user.Blob = newBytes; - return true; + return false; } + user.Blob = newBytes; + return true; + } } public class UserBlob diff --git a/BTCPayServer/Fido2/Fido2Controller.cs b/BTCPayServer/Fido2/Fido2Controller.cs index bc03ebc3b..657bc60eb 100644 --- a/BTCPayServer/Fido2/Fido2Controller.cs +++ b/BTCPayServer/Fido2/Fido2Controller.cs @@ -19,7 +19,7 @@ namespace BTCPayServer.Fido2 private readonly UserManager _userManager; private readonly Fido2Service _fido2Service; - public Fido2Controller(UserManager userManager, Fido2Service fido2Service) + public Fido2Controller(UserManager userManager, Fido2Service fido2Service) { _userManager = userManager; _fido2Service = fido2Service; @@ -27,7 +27,7 @@ namespace BTCPayServer.Fido2 [HttpGet("{id}/delete")] public IActionResult Remove(string id) - { + { return View("Confirm", new ConfirmModel("Remove security device", "Your account will no longer have this security device as an option for two-factor authentication.", "Remove")); } @@ -41,7 +41,7 @@ namespace BTCPayServer.Fido2 Severity = StatusMessageModel.StatusSeverity.Success, Html = "The security device was removed successfully." }); - + return RedirectToList(); } @@ -56,7 +56,7 @@ namespace BTCPayServer.Fido2 Severity = StatusMessageModel.StatusSeverity.Error, Html = "The security device could not be registered." }); - + return RedirectToList(); } diff --git a/BTCPayServer/Fido2/Fido2Service.cs b/BTCPayServer/Fido2/Fido2Service.cs index 1f7c7d9df..4c48d2745 100644 --- a/BTCPayServer/Fido2/Fido2Service.cs +++ b/BTCPayServer/Fido2/Fido2Service.cs @@ -33,45 +33,47 @@ namespace BTCPayServer.Fido2 public async Task RequestCreation(string userId) { - await using var dbContext = _contextFactory.CreateContext(); - var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials) - .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId); - if (user == null) - { - return null; - } + await using var dbContext = _contextFactory.CreateContext(); + var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials) + .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId); + if (user == null) + { + return null; + } - // 2. Get user existing keys by username - var existingKeys = - user.Fido2Credentials - .Where(credential => credential.Type == Fido2Credential.CredentialType.FIDO2) - .Select(c => c.GetBlob().Descriptor).ToList(); + // 2. Get user existing keys by username + var existingKeys = + user.Fido2Credentials + .Where(credential => credential.Type == Fido2Credential.CredentialType.FIDO2) + .Select(c => c.GetBlob().Descriptor).ToList(); - // 3. Create options - var authenticatorSelection = new AuthenticatorSelection + // 3. Create options + var authenticatorSelection = new AuthenticatorSelection + { + RequireResidentKey = false, + UserVerification = UserVerificationRequirement.Preferred + }; + + var exts = new AuthenticationExtensionsClientInputs() + { + Extensions = true, + UserVerificationIndex = true, + Location = true, + UserVerificationMethod = true, + BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds { - RequireResidentKey = false, UserVerification = UserVerificationRequirement.Preferred - }; + FAR = float.MaxValue, + FRR = float.MaxValue + }, + }; - var exts = new AuthenticationExtensionsClientInputs() - { - Extensions = true, - UserVerificationIndex = true, - Location = true, - UserVerificationMethod = true, - BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds - { - FAR = float.MaxValue, FRR = float.MaxValue - }, - }; + var options = _fido2.RequestNewCredential( + new Fido2User() { DisplayName = user.UserName, Name = user.UserName, Id = user.Id.ToBytesUTF8() }, + existingKeys, authenticatorSelection, AttestationConveyancePreference.None, exts); - var options = _fido2.RequestNewCredential( - 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, ""); - CreationStore.AddOrReplace(userId, options); - return options; + // options.Rp = new PublicKeyCredentialRpEntity(Request.Host.Host, options.Rp.Name, ""); + CreationStore.AddOrReplace(userId, options); + return options; } public async Task CompleteCreation(string userId, string name, string data) @@ -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; @@ -159,16 +161,16 @@ namespace BTCPayServer.Fido2 .Select(c => c.GetBlob().Descriptor) .ToList(); var exts = new AuthenticationExtensionsClientInputs() - { - SimpleTransactionAuthorization = "FIDO", - GenericTransactionAuthorization = new TxAuthGenericArg - { - ContentType = "text/plain", - Content = new byte[] { 0x46, 0x49, 0x44, 0x4F } - }, - UserVerificationIndex = true, - Location = true, - UserVerificationMethod = true , + { + SimpleTransactionAuthorization = "FIDO", + GenericTransactionAuthorization = new TxAuthGenericArg + { + ContentType = "text/plain", + Content = new byte[] { 0x46, 0x49, 0x44, 0x4F } + }, + UserVerificationIndex = true, + Location = true, + UserVerificationMethod = true, Extensions = true, AppID = _fido2Configuration.Origin }; @@ -182,8 +184,9 @@ namespace BTCPayServer.Fido2 LoginStore.AddOrReplace(userId, options); return options; } - - public async Task CompleteLogin(string userId, AuthenticatorAssertionRawResponse response){ + + public async Task 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); @@ -206,7 +209,7 @@ namespace BTCPayServer.Fido2 credential.Item2.SignatureCounter, x => Task.FromResult(true)); // 6. Store the updated counter - credential.Item2.SignatureCounter = res.Counter; + credential.Item2.SignatureCounter = res.Counter; credential.fido2Credential.SetBlob(credential.Item2); await dbContext.SaveChangesAsync(); LoginStore.Remove(userId, out _); diff --git a/BTCPayServer/Fido2/FidoExtensions.cs b/BTCPayServer/Fido2/FidoExtensions.cs index 903d965f8..2d4e26276 100644 --- a/BTCPayServer/Fido2/FidoExtensions.cs +++ b/BTCPayServer/Fido2/FidoExtensions.cs @@ -6,7 +6,7 @@ using Newtonsoft.Json.Linq; namespace BTCPayServer.Fido2 { public static class Fido2Extensions - { + { public static Fido2CredentialBlob GetBlob(this Fido2Credential credential) { var result = credential.Blob == null @@ -25,7 +25,7 @@ namespace BTCPayServer.Fido2 return true; } - - + + } } diff --git a/BTCPayServer/Fido2/UserLoginCodeService.cs b/BTCPayServer/Fido2/UserLoginCodeService.cs index d229e1a84..e84522884 100644 --- a/BTCPayServer/Fido2/UserLoginCodeService.cs +++ b/BTCPayServer/Fido2/UserLoginCodeService.cs @@ -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; diff --git a/BTCPayServer/Filters/CheatModeRouteAttribute.cs b/BTCPayServer/Filters/CheatModeRouteAttribute.cs index 9205b2c4d..cd4889109 100644 --- a/BTCPayServer/Filters/CheatModeRouteAttribute.cs +++ b/BTCPayServer/Filters/CheatModeRouteAttribute.cs @@ -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 { diff --git a/BTCPayServer/Filters/DomainMappingConstraintAttribute.cs b/BTCPayServer/Filters/DomainMappingConstraintAttribute.cs index 1a04712c5..caa43b69e 100644 --- a/BTCPayServer/Filters/DomainMappingConstraintAttribute.cs +++ b/BTCPayServer/Filters/DomainMappingConstraintAttribute.cs @@ -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; diff --git a/BTCPayServer/HostedServices/DbMigrationsHostedService.cs b/BTCPayServer/HostedServices/DbMigrationsHostedService.cs index d363fff97..6b054f696 100644 --- a/BTCPayServer/HostedServices/DbMigrationsHostedService.cs +++ b/BTCPayServer/HostedServices/DbMigrationsHostedService.cs @@ -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 { @@ -30,7 +30,7 @@ namespace BTCPayServer.HostedServices _dbContextFactory = dbContextFactory; _datadirs = datadirs; } - + internal override Task[] InitializeTasks() { @@ -95,8 +95,8 @@ namespace BTCPayServer.HostedServices // textSearch.Add(invoice.RefundMail); // TODO: Are there more things to cache? PaymentData? - InvoiceRepository.AddToTextSearch(ctx, - new InvoiceData { Id = invoice.Id, InvoiceSearchData = new List() }, + InvoiceRepository.AddToTextSearch(ctx, + new InvoiceData { Id = invoice.Id, InvoiceSearchData = new List() }, textSearch.ToArray()); } diff --git a/BTCPayServer/HostedServices/PullPaymentHostedService.cs b/BTCPayServer/HostedServices/PullPaymentHostedService.cs index 240a5150e..7518eef41 100644 --- a/BTCPayServer/HostedServices/PullPaymentHostedService.cs +++ b/BTCPayServer/HostedServices/PullPaymentHostedService.cs @@ -289,7 +289,7 @@ namespace BTCPayServer.HostedServices return; } payout.State = PayoutState.AwaitingPayment; - + if (paymentMethod.CryptoCode == payout.PullPaymentData.GetBlob().Currency) req.Rate = 1.0m; var cryptoAmount = payoutBlob.Amount / req.Rate; @@ -382,7 +382,7 @@ namespace BTCPayServer.HostedServices data.State != PayoutState.Completed && data.State != PayoutState.Cancelled )) { - + req.Completion.TrySetResult(new ClaimRequest.ClaimResponse(ClaimRequest.ClaimResult.Duplicate)); return; } diff --git a/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs b/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs index 9db69e835..d64c1681e 100644 --- a/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs +++ b/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs @@ -59,13 +59,13 @@ namespace BTCPayServer.HostedServices { labels.Add(UpdateTransactionLabel.PaymentRequestLabelTemplate(paymentId)); } - foreach (var appId in AppService.GetAppInternalTags(invoiceEvent.Invoice)) + foreach (var appId in AppService.GetAppInternalTags(invoiceEvent.Invoice)) { labels.Add(UpdateTransactionLabel.AppLabelTemplate(appId)); } - - + + _eventAggregator.Publish(new UpdateTransactionLabel(walletId, transactionId, labels)); } else if (evt is UpdateTransactionLabel updateTransactionLabel) @@ -131,7 +131,7 @@ namespace BTCPayServer.HostedServices public static (string color, Label label) InvoiceLabelTemplate(string invoice) { return ("#cedc21", new ReferenceLabel("invoice", invoice)); - } + } public static (string color, Label label) PaymentRequestLabelTemplate(string paymentRequestId) { return ("#489D77", new ReferenceLabel("payment-request", paymentRequestId)); @@ -146,7 +146,7 @@ namespace BTCPayServer.HostedServices return ("#51b13e", new ReferenceLabel("pj-exposed", invoice)); } - public static (string color, Label label) PayoutTemplate(string payoutId, string pullPaymentId, string walletId) + public static (string color, Label label) PayoutTemplate(string payoutId, string pullPaymentId, string walletId) { return ("#3F88AF", new PayoutLabel() { diff --git a/BTCPayServer/HostedServices/UserEventHostedService.cs b/BTCPayServer/HostedServices/UserEventHostedService.cs index 31578490f..1f7a42c83 100644 --- a/BTCPayServer/HostedServices/UserEventHostedService.cs +++ b/BTCPayServer/HostedServices/UserEventHostedService.cs @@ -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, diff --git a/BTCPayServer/HostedServices/WebhookNotificationManager.cs b/BTCPayServer/HostedServices/WebhookNotificationManager.cs index 6a33e601d..f4d5a8b36 100644 --- a/BTCPayServer/HostedServices/WebhookNotificationManager.cs +++ b/BTCPayServer/HostedServices/WebhookNotificationManager.cs @@ -110,7 +110,7 @@ namespace BTCPayServer.HostedServices return new WebhookDeliveryRequest(webhookDelivery.Webhook.Id, webhookEvent, newDelivery, webhookDelivery.Webhook.GetBlob()); } - private WebhookEvent GetTestWebHook(string storeId, string webhookId, WebhookEventType webhookEventType, Data.WebhookDeliveryData delivery) + private WebhookEvent GetTestWebHook(string storeId, string webhookId, WebhookEventType webhookEventType, Data.WebhookDeliveryData delivery) { var webhookEvent = GetWebhookEvent(webhookEventType); webhookEvent.InvoiceId = "__test__" + Guid.NewGuid().ToString() + "__test__"; @@ -129,12 +129,12 @@ namespace BTCPayServer.HostedServices var delivery = NewDelivery(webhookId); var webhook = (await StoreRepository.GetWebhooks(storeId)).FirstOrDefault(w => w.Id == webhookId); var deliveryRequest = new WebhookDeliveryRequest( - webhookId, - GetTestWebHook(storeId, webhookId, webhookEventType, delivery), - delivery, + webhookId, + GetTestWebHook(storeId, webhookId, webhookEventType, delivery), + delivery, webhook.GetBlob() ); - + return await SendDelivery(deliveryRequest); } @@ -194,7 +194,7 @@ namespace BTCPayServer.HostedServices case WebhookEventType.InvoiceSettled: return new WebhookInvoiceSettledEvent(WebhookEventType.InvoiceSettled); case WebhookEventType.InvoiceInvalid: - return new WebhookInvoiceInvalidEvent(WebhookEventType.InvoiceInvalid); + return new WebhookInvoiceInvalidEvent(WebhookEventType.InvoiceInvalid); default: return new WebhookInvoiceEvent(WebhookEventType.InvoiceCreated); } @@ -352,10 +352,10 @@ namespace BTCPayServer.HostedServices } ctx.Delivery.SetBlob(deliveryBlob); - return new DeliveryResult() - { - Success = deliveryBlob.ErrorMessage is null, - DeliveryId = ctx.Delivery.Id, + return new DeliveryResult() + { + Success = deliveryBlob.ErrorMessage is null, + DeliveryId = ctx.Delivery.Id, ErrorMessage = deliveryBlob.ErrorMessage }; } diff --git a/BTCPayServer/Hosting/BTCPayServerServices.cs b/BTCPayServer/Hosting/BTCPayServerServices.cs index 0db6d0eeb..d63330704 100644 --- a/BTCPayServer/Hosting/BTCPayServerServices.cs +++ b/BTCPayServer/Hosting/BTCPayServerServices.cs @@ -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("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(); services.TryAddSingleton(); services.TryAddSingleton(); - services.AddSingleton( provider => provider.GetService()); + services.AddSingleton(provider => provider.GetService()); services.TryAddSingleton(CurrencyNameTable.Instance); services.TryAddSingleton(o => new NBXplorerFeeProviderFactory(o.GetRequiredService()) { @@ -311,11 +311,11 @@ namespace BTCPayServer.Hosting services.AddSingleton(o => o.GetRequiredService()); services.AddHttpClient(WebhookNotificationManager.OnionNamedClient) .ConfigurePrimaryHttpMessageHandler(); - + services.AddSingleton(); services.AddSingleton(); - + services.AddHttpClient(LightningLikePayoutHandler.LightningLikePayoutHandlerOnionNamedClient) .ConfigurePrimaryHttpMessageHandler(); services.AddSingleton(); @@ -387,7 +387,7 @@ namespace BTCPayServer.Hosting services.AddTransient(); // Add application services. services.AddSingleton(); - + //create a simple client which hooks up to the http scope services.AddScoped(); //also provide a factory that can impersonate user/store id diff --git a/BTCPayServer/Hosting/BTCpayMiddleware.cs b/BTCPayServer/Hosting/BTCpayMiddleware.cs index b138cb265..397b0ce53 100644 --- a/BTCPayServer/Hosting/BTCpayMiddleware.cs +++ b/BTCPayServer/Hosting/BTCpayMiddleware.cs @@ -71,7 +71,7 @@ namespace BTCPayServer.Hosting var isModal = httpContext.Request.Query.TryGetValue("view", out var view) && view.ToString().Equals("modal", StringComparison.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(_Env.OnionUrl) && - !httpContext.Request.IsOnion() && + !httpContext.Request.IsOnion() && isHtml && !isModal) { diff --git a/BTCPayServer/Hosting/MigrationStartupTask.cs b/BTCPayServer/Hosting/MigrationStartupTask.cs index 6f76fe9fe..08ab77445 100644 --- a/BTCPayServer/Hosting/MigrationStartupTask.cs +++ b/BTCPayServer/Hosting/MigrationStartupTask.cs @@ -51,7 +51,7 @@ namespace BTCPayServer.Hosting UserManager userManager, IOptions lightningOptions, SettingsRepository settingsRepository, - AppService appService, + AppService appService, IEnumerable payoutHandlers, BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings, Logs logs) @@ -176,7 +176,7 @@ namespace BTCPayServer.Hosting throw; } } - + private async Task AddInitialUserBlob() { await using var ctx = _DBContextFactory.CreateContext(); @@ -186,25 +186,25 @@ namespace BTCPayServer.Hosting } await ctx.SaveChangesAsync(); } - + private async Task MigratePayoutDestinationId() { await using var ctx = _DBContextFactory.CreateContext(); foreach (var payoutData in await ctx.Payouts.AsQueryable().ToArrayAsync()) { - var pmi = payoutData.GetPaymentMethodId(); - if (pmi is null) - { - continue; - } - var handler = _payoutHandlers - .FindPayoutHandler(pmi); - if (handler is null) - { - continue; - } - var claim = await handler?.ParseClaimDestination(pmi, payoutData.GetBlob(_btcPayNetworkJsonSerializerSettings).Destination, false); - payoutData.Destination = claim.destination?.Id; + var pmi = payoutData.GetPaymentMethodId(); + if (pmi is null) + { + continue; + } + var handler = _payoutHandlers + .FindPayoutHandler(pmi); + if (handler is null) + { + continue; + } + var claim = await handler?.ParseClaimDestination(pmi, payoutData.GetBlob(_btcPayNetworkJsonSerializerSettings).Destination, false); + payoutData.Destination = claim.destination?.Id; } await ctx.SaveChangesAsync(); } @@ -233,9 +233,9 @@ namespace BTCPayServer.Hosting app.SetSettings(settings1); }; break; - + case nameof(AppType.PointOfSale): - + var settings2 = app.GetSettings(); if (string.IsNullOrEmpty(settings2.Currency)) { @@ -288,14 +288,14 @@ namespace BTCPayServer.Hosting fido2.SetBlob(new Fido2CredentialBlob() { SignatureCounter = (uint)u2FDevice.Counter, - PublicKey = CreatePublicKeyFromU2fRegistrationData( u2FDevice.PublicKey).EncodeToBytes() , + PublicKey = CreatePublicKeyFromU2fRegistrationData(u2FDevice.PublicKey).EncodeToBytes(), UserHandle = u2FDevice.KeyHandle, Descriptor = new PublicKeyCredentialDescriptor(u2FDevice.KeyHandle), CredType = "u2f" }); await ctx.AddAsync(fido2); - + ctx.Remove(u2FDevice); } await ctx.SaveChangesAsync(); @@ -536,30 +536,34 @@ retry: CurrencyValue.TryParse(lightningMaxValueJToken.Value(), out lightningMaxValue); blob.AdditionalData.Remove("lightningMaxValue"); } - blob.PaymentMethodCriteria = store.GetEnabledPaymentIds(_NetworkProvider).Select(paymentMethodId=> - { - var matchedFromBlob = - blob.PaymentMethodCriteria?.SingleOrDefault(criteria => criteria.PaymentMethod == paymentMethodId && criteria.Value != null); - return matchedFromBlob switch - { - null when paymentMethodId.PaymentType == LightningPaymentType.Instance && - lightningMaxValue != null => new PaymentMethodCriteria() - { - Above = false, PaymentMethod = paymentMethodId, Value = lightningMaxValue - }, - null when paymentMethodId.PaymentType == BitcoinPaymentType.Instance && - onChainMinValue != null => new PaymentMethodCriteria() - { - Above = true, PaymentMethod = paymentMethodId, Value = onChainMinValue - }, - _ => new PaymentMethodCriteria() - { - PaymentMethod = paymentMethodId, - Above = matchedFromBlob?.Above ?? true, - Value = matchedFromBlob?.Value - } - }; - }).ToList(); + blob.PaymentMethodCriteria = store.GetEnabledPaymentIds(_NetworkProvider).Select(paymentMethodId => + { + var matchedFromBlob = + blob.PaymentMethodCriteria?.SingleOrDefault(criteria => criteria.PaymentMethod == paymentMethodId && criteria.Value != null); + return matchedFromBlob switch + { + null when paymentMethodId.PaymentType == LightningPaymentType.Instance && + lightningMaxValue != null => new PaymentMethodCriteria() + { + Above = false, + PaymentMethod = paymentMethodId, + Value = lightningMaxValue + }, + null when paymentMethodId.PaymentType == BitcoinPaymentType.Instance && + onChainMinValue != null => new PaymentMethodCriteria() + { + Above = true, + PaymentMethod = paymentMethodId, + Value = onChainMinValue + }, + _ => new PaymentMethodCriteria() + { + PaymentMethod = paymentMethodId, + Above = matchedFromBlob?.Above ?? true, + Value = matchedFromBlob?.Value + } + }; + }).ToList(); store.SetStoreBlob(blob); } diff --git a/BTCPayServer/Hosting/Startup.cs b/BTCPayServer/Hosting/Startup.cs index 13bbaee66..d0b960af6 100644 --- a/BTCPayServer/Hosting/Startup.cs +++ b/BTCPayServer/Hosting/Startup.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Net; using BTCPayServer.Configuration; +using BTCPayServer.Controllers.GreenField; using BTCPayServer.Data; using BTCPayServer.Fido2; using BTCPayServer.Filters; @@ -13,15 +14,16 @@ using BTCPayServer.Plugins; using BTCPayServer.Security; using BTCPayServer.Services.Apps; using BTCPayServer.Storage; +using Fido2NetLib; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; -using Fido2NetLib; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -30,8 +32,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; -using Microsoft.AspNetCore.Mvc; -using BTCPayServer.Controllers.GreenField; namespace BTCPayServer.Hosting { @@ -95,7 +95,7 @@ namespace BTCPayServer.Hosting //They'll be used in a "first match wins" way in the order registered config.AddStaticMetadataRepository(); }); - var descriptor =services.Single(descriptor => descriptor.ServiceType == typeof(Fido2Configuration)); + var descriptor = services.Single(descriptor => descriptor.ServiceType == typeof(Fido2Configuration)); services.Remove(descriptor); services.AddScoped(provider => { @@ -109,18 +109,18 @@ namespace BTCPayServer.Hosting }); services.AddScoped(); services.AddSingleton(); - - var mvcBuilder= services.AddMvc(o => - { - o.Filters.Add(new XFrameOptionsAttribute("DENY")); - o.Filters.Add(new XContentTypeOptionsAttribute("nosniff")); - o.Filters.Add(new XXSSProtectionAttribute()); - o.Filters.Add(new ReferrerPolicyAttribute("same-origin")); - o.ModelBinderProviders.Insert(0, new ModelBinders.DefaultModelBinderProvider()); - if (!Configuration.GetOrDefault("nocsp", false)) - o.Filters.Add(new ContentSecurityPolicyAttribute(CSPTemplate.AntiXSS)); - o.Filters.Add(new JsonHttpExceptionFilter()); - }) + + var mvcBuilder = services.AddMvc(o => + { + o.Filters.Add(new XFrameOptionsAttribute("DENY")); + o.Filters.Add(new XContentTypeOptionsAttribute("nosniff")); + o.Filters.Add(new XXSSProtectionAttribute()); + o.Filters.Add(new ReferrerPolicyAttribute("same-origin")); + o.ModelBinderProviders.Insert(0, new ModelBinders.DefaultModelBinderProvider()); + if (!Configuration.GetOrDefault("nocsp", false)) + o.Filters.Add(new ContentSecurityPolicyAttribute(CSPTemplate.AntiXSS)); + o.Filters.Add(new JsonHttpExceptionFilter()); + }) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => diff --git a/BTCPayServer/LNURL/LNURLController.cs b/BTCPayServer/LNURL/LNURLController.cs index 5bb70a548..9de779409 100644 --- a/BTCPayServer/LNURL/LNURLController.cs +++ b/BTCPayServer/LNURL/LNURLController.cs @@ -26,8 +26,8 @@ using BTCPayServer.Services.Stores; using LNURL; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Routing; using NBitcoin; using NBitcoin.Crypto; using Newtonsoft.Json; @@ -155,11 +155,11 @@ namespace BTCPayServer public string StoreId { get; set; } [Display(Name = "Invoice currency")] public string CurrencyCode { get; set; } - + [Display(Name = "Min sats")] [Range(1, double.PositiveInfinity)] public decimal? Min { get; set; } - + [Display(Name = "Max sats")] [Range(1, double.PositiveInfinity)] public decimal? Max { get; set; } @@ -340,7 +340,8 @@ namespace BTCPayServer { return BadRequest(new LNUrlStatusResponse { - Status = "ERROR", Reason = "Amount is out of bounds." + Status = "ERROR", + Reason = "Amount is out of bounds." }); } @@ -404,7 +405,9 @@ namespace BTCPayServer paymentMethodDetails, pmi)); return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse { - Disposable = true, Routes = Array.Empty(), Pr = paymentMethodDetails.BOLT11 + Disposable = true, + Routes = Array.Empty(), + Pr = paymentMethodDetails.BOLT11 }); } @@ -419,7 +422,9 @@ namespace BTCPayServer return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse { - Disposable = true, Routes = Array.Empty(), Pr = paymentMethodDetails.BOLT11 + Disposable = true, + Routes = Array.Empty(), + Pr = paymentMethodDetails.BOLT11 }); } @@ -439,7 +444,8 @@ namespace BTCPayServer return BadRequest(new LNUrlStatusResponse { - Status = "ERROR", Reason = "Invoice not in a valid payable state" + Status = "ERROR", + Reason = "Invoice not in a valid payable state" }); } @@ -458,7 +464,7 @@ namespace BTCPayServer }); return RedirectToAction("PaymentMethods", "Stores", new { storeId }); } - var lightningAddressSettings = await _settingsRepository.GetSettingAsync() ?? + var lightningAddressSettings = await _settingsRepository.GetSettingAsync() ?? new LightningAddressSettings(); if (lightningAddressSettings.StoreToItemMap.TryGetValue(storeId, out var addresses)) { @@ -517,7 +523,7 @@ namespace BTCPayServer { ids = new[] { vm.Add.Username.ToLowerInvariant() }; } - + lightningAddressSettings.StoreToItemMap.AddOrReplace(storeId, ids); vm.Add.StoreId = storeId; lightningAddressSettings.Items.TryAdd(vm.Add.Username.ToLowerInvariant(), vm.Add); diff --git a/BTCPayServer/Logging/InvoiceLog.cs b/BTCPayServer/Logging/InvoiceLog.cs index b217ff7c1..afba62db8 100644 --- a/BTCPayServer/Logging/InvoiceLog.cs +++ b/BTCPayServer/Logging/InvoiceLog.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.Logging { lock (_InvoiceLogs) { - _InvoiceLogs.Add(new InvoiceLog() { Timestamp = DateTimeOffset.UtcNow, Log = data, Severity = eventSeverity}); + _InvoiceLogs.Add(new InvoiceLog() { Timestamp = DateTimeOffset.UtcNow, Log = data, Severity = eventSeverity }); } } diff --git a/BTCPayServer/Models/AppViewModels/CreateAppViewModel.cs b/BTCPayServer/Models/AppViewModels/CreateAppViewModel.cs index 89228988b..a0cdb90e3 100644 --- a/BTCPayServer/Models/AppViewModels/CreateAppViewModel.cs +++ b/BTCPayServer/Models/AppViewModels/CreateAppViewModel.cs @@ -38,7 +38,7 @@ namespace BTCPayServer.Models.AppViewModels var defaultAppType = AppType.PointOfSale.ToString(); var choices = typeof(AppType).GetEnumNames().Select(o => new Format { - Name = typeof(AppType).DisplayName(o), + Name = typeof(AppType).DisplayName(o), Value = o }).ToArray(); var chosen = choices.FirstOrDefault(f => f.Value == defaultAppType) ?? choices.FirstOrDefault(); diff --git a/BTCPayServer/Models/AppViewModels/UpdateCrowdfundViewModel.cs b/BTCPayServer/Models/AppViewModels/UpdateCrowdfundViewModel.cs index a2eb96d2b..d388f4a1e 100644 --- a/BTCPayServer/Models/AppViewModels/UpdateCrowdfundViewModel.cs +++ b/BTCPayServer/Models/AppViewModels/UpdateCrowdfundViewModel.cs @@ -10,7 +10,7 @@ namespace BTCPayServer.Models.AppViewModels { public string StoreId { get; set; } public string StoreName { get; set; } - + [Required] [MaxLength(50)] [MinLength(1)] @@ -50,12 +50,12 @@ namespace BTCPayServer.Models.AppViewModels [Display(Name = "Enable Disqus Comments")] public bool DisqusEnabled { get; set; } = true; - [Display(Name = "Disqus Shortname")] + [Display(Name = "Disqus Shortname")] public string DisqusShortname { get; set; } - + [Display(Name = "Start date")] public DateTime? StartDate { get; set; } - + [Display(Name = "End date")] public DateTime? EndDate { get; set; } @@ -66,14 +66,14 @@ namespace BTCPayServer.Models.AppViewModels [Display(Name = "Set a target amount")] [Range(0, double.PositiveInfinity)] public decimal? TargetAmount { get; set; } - + public IEnumerable ResetEveryValues = Enum.GetNames(typeof(CrowdfundResetEvery)); [Display(Name = "Reset goal every")] public string ResetEvery { get; set; } = nameof(CrowdfundResetEvery.Never); public int ResetEveryAmount { get; set; } = 1; - + [Display(Name = "Do not allow additional contributions after target has been reached")] public bool EnforceTargetAmount { get; set; } @@ -95,16 +95,16 @@ namespace BTCPayServer.Models.AppViewModels [Display(Name = "Sort contribution perks by popularity")] public bool SortPerksByPopularity { get; set; } - + [Display(Name = "Display contribution ranking")] public bool DisplayPerksRanking { get; set; } - + [Display(Name = "Display contribution value")] public bool DisplayPerksValue { get; set; } [Display(Name = "Sounds to play when a payment is made. One sound per line")] public string Sounds { get; set; } - + [Display(Name = "Colors to rotate between with animation when a payment is made. One color per line (any valid css color value).")] public string AnimationColors { get; set; } diff --git a/BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs b/BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs index 1498b659d..4a0d112d3 100644 --- a/BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs +++ b/BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs @@ -10,7 +10,7 @@ namespace BTCPayServer.Models.AppViewModels { public string StoreId { get; set; } public string StoreName { get; set; } - + [Required] [MaxLength(50)] [MinLength(1)] diff --git a/BTCPayServer/Models/AppViewModels/ViewPointOfSaleViewModel.cs b/BTCPayServer/Models/AppViewModels/ViewPointOfSaleViewModel.cs index 12a024348..e8480925f 100644 --- a/BTCPayServer/Models/AppViewModels/ViewPointOfSaleViewModel.cs +++ b/BTCPayServer/Models/AppViewModels/ViewPointOfSaleViewModel.cs @@ -16,7 +16,7 @@ namespace BTCPayServer.Models.AppViewModels Minimum, Fixed } - + public ItemPriceType Type { get; set; } public string Formatted { get; set; } public decimal? Value { get; set; } diff --git a/BTCPayServer/Models/ConfirmModel.cs b/BTCPayServer/Models/ConfirmModel.cs index ffc7c35dd..ff49209d0 100644 --- a/BTCPayServer/Models/ConfirmModel.cs +++ b/BTCPayServer/Models/ConfirmModel.cs @@ -5,8 +5,8 @@ namespace BTCPayServer.Models public class ConfirmModel { private const string ButtonClassDefault = "btn-danger"; - - public ConfirmModel() {} + + public ConfirmModel() { } public ConfirmModel(string title, string desc, string action = null, string buttonClass = ButtonClassDefault, string actionUrl = null) { diff --git a/BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs b/BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs index 8bee6a4a0..a7c01b98e 100644 --- a/BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs +++ b/BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; +using BTCPayServer.Services.Apps; using BTCPayServer.Validation; using Microsoft.AspNetCore.Mvc.Rendering; -using BTCPayServer.Services.Apps; namespace BTCPayServer.Models.InvoicingModels { diff --git a/BTCPayServer/Models/InvoicingModels/InvoiceDetailsModel.cs b/BTCPayServer/Models/InvoicingModels/InvoiceDetailsModel.cs index 878827d69..feee2161e 100644 --- a/BTCPayServer/Models/InvoicingModels/InvoiceDetailsModel.cs +++ b/BTCPayServer/Models/InvoicingModels/InvoiceDetailsModel.cs @@ -106,7 +106,7 @@ namespace BTCPayServer.Models.InvoicingModels get; set; } - + public string NotificationUrl { get; diff --git a/BTCPayServer/Models/InvoicingModels/RefundModel.cs b/BTCPayServer/Models/InvoicingModels/RefundModel.cs index 7cb421a21..006a12755 100644 --- a/BTCPayServer/Models/InvoicingModels/RefundModel.cs +++ b/BTCPayServer/Models/InvoicingModels/RefundModel.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.Models.InvoicingModels public string RateThenText { get; set; } public string FiatText { get; set; } public decimal FiatAmount { get; set; } - + [Display(Name = "Specify the amount and currency for the refund")] public decimal CustomAmount { get; set; } public string CustomCurrency { get; set; } diff --git a/BTCPayServer/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs b/BTCPayServer/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs index 5a1c9dd92..7e1e75458 100644 --- a/BTCPayServer/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs +++ b/BTCPayServer/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs @@ -9,7 +9,7 @@ namespace BTCPayServer.Models.ManageViewModels public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } - + public List Credentials { get; set; } public string LoginCode { get; set; } diff --git a/BTCPayServer/Models/PaymentRequestViewModels/ListPaymentRequestsViewModel.cs b/BTCPayServer/Models/PaymentRequestViewModels/ListPaymentRequestsViewModel.cs index fc6f7a536..ccfec4e58 100644 --- a/BTCPayServer/Models/PaymentRequestViewModels/ListPaymentRequestsViewModel.cs +++ b/BTCPayServer/Models/PaymentRequestViewModels/ListPaymentRequestsViewModel.cs @@ -62,7 +62,7 @@ namespace BTCPayServer.Models.PaymentRequestViewModels [Display(Name = "Store")] public SelectList Stores { get; set; } - + [EmailAddress] public string Email { get; set; } diff --git a/BTCPayServer/Models/ServerViewModels/UsersViewModel.cs b/BTCPayServer/Models/ServerViewModels/UsersViewModel.cs index 77c923439..b0bca100e 100644 --- a/BTCPayServer/Models/ServerViewModels/UsersViewModel.cs +++ b/BTCPayServer/Models/ServerViewModels/UsersViewModel.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace BTCPayServer.Models.ServerViewModels { - public class UsersViewModel: BasePagingViewModel + public class UsersViewModel : BasePagingViewModel { public class UserViewModel { diff --git a/BTCPayServer/Models/StoreViewModels/CheckoutAppearanceViewModel.cs b/BTCPayServer/Models/StoreViewModels/CheckoutAppearanceViewModel.cs index 46d447dd9..4900729de 100644 --- a/BTCPayServer/Models/StoreViewModels/CheckoutAppearanceViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/CheckoutAppearanceViewModel.cs @@ -30,7 +30,7 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Default payment method on checkout")] public string DefaultPaymentMethod { get; set; } - + [Display(Name = "Requires a refund email")] public bool RequiresRefundEmail { get; set; } @@ -39,10 +39,10 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Redirect invoice to redirect url automatically after paid")] public bool RedirectAutomatically { get; set; } - + [Display(Name = "Auto-detect language on checkout")] public bool AutoDetectLanguage { get; set; } - + [Display(Name = "Default language on checkout")] public string DefaultLang { get; set; } @@ -62,7 +62,7 @@ namespace BTCPayServer.Models.StoreViewModels public string PaymentMethod { get; set; } public string Value { get; set; } - public CriteriaType Type { get; set; } + public CriteriaType Type { get; set; } public enum CriteriaType { @@ -81,6 +81,6 @@ namespace BTCPayServer.Models.StoreViewModels throw new ArgumentOutOfRangeException(nameof(type), type, null); } } - + } } diff --git a/BTCPayServer/Models/StoreViewModels/EditWebhookViewModel.cs b/BTCPayServer/Models/StoreViewModels/EditWebhookViewModel.cs index 00cea1001..df5ff47ff 100644 --- a/BTCPayServer/Models/StoreViewModels/EditWebhookViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/EditWebhookViewModel.cs @@ -61,7 +61,7 @@ namespace BTCPayServer.Models.StoreViewModels [MaxLength(64)] public string Secret { get; set; } - public List Deliveries { get; set; } = new List(); + public List Deliveries { get; set; } = new List(); public WebhookBlob CreateBlob() { diff --git a/BTCPayServer/Models/StoreViewModels/GeneralSettingsViewModel.cs b/BTCPayServer/Models/StoreViewModels/GeneralSettingsViewModel.cs index 03da5a361..17d3e82c8 100644 --- a/BTCPayServer/Models/StoreViewModels/GeneralSettingsViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/GeneralSettingsViewModel.cs @@ -5,10 +5,10 @@ namespace BTCPayServer.Models.StoreViewModels { public class GeneralSettingsViewModel { - + [Display(Name = "Store ID")] public string Id { get; set; } - + [Display(Name = "Store Name")] [Required] [MaxLength(50)] @@ -19,7 +19,7 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Store Website")] [MaxLength(500)] public string StoreWebsite { get; set; } - + public bool CanDelete { get; set; } } } diff --git a/BTCPayServer/Models/StoreViewModels/LightningNodeViewModel.cs b/BTCPayServer/Models/StoreViewModels/LightningNodeViewModel.cs index 900006b34..7cbfd1362 100644 --- a/BTCPayServer/Models/StoreViewModels/LightningNodeViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/LightningNodeViewModel.cs @@ -16,7 +16,7 @@ namespace BTCPayServer.Models.StoreViewModels public bool CanUseInternalNode { get; set; } public bool SkipPortTest { get; set; } public bool Enabled { get; set; } = true; - + [Display(Name = "Connection string")] public string ConnectionString { get; set; } } diff --git a/BTCPayServer/Models/StoreViewModels/LightningSettingsViewModel.cs b/BTCPayServer/Models/StoreViewModels/LightningSettingsViewModel.cs index 52b3bfc43..c04d8bb19 100644 --- a/BTCPayServer/Models/StoreViewModels/LightningSettingsViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/LightningSettingsViewModel.cs @@ -16,20 +16,20 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Description template of the lightning invoice")] public string LightningDescriptionTemplate { get; set; } - + // LNURL [Display(Name = "Enable LNURL")] public bool LNURLEnabled { get; set; } - + [Display(Name = "LNURL Classic Mode")] public bool LNURLBech32Mode { get; set; } = true; [Display(Name = "LNURL enabled for standard invoices")] public bool LNURLStandardInvoiceEnabled { get; set; } = true; - + [Display(Name = "Allow payee to pass a comment")] public bool LUD12Enabled { get; set; } - + [Display(Name = "Do not offer BOLT11 for standard invoices")] public bool DisableBolt11PaymentMethod { get; set; } } diff --git a/BTCPayServer/Models/StoreViewModels/PaymentMethodsViewModel.cs b/BTCPayServer/Models/StoreViewModels/PaymentMethodsViewModel.cs index 9fb4581b5..5deaa4485 100644 --- a/BTCPayServer/Models/StoreViewModels/PaymentMethodsViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/PaymentMethodsViewModel.cs @@ -11,7 +11,7 @@ namespace BTCPayServer.Models.StoreViewModels public List LightningNodes { get; set; } public bool HintWallet { get; set; } public bool HintLightning { get; set; } - + [Display(Name = "Allow anyone to create invoice")] public bool AnyoneCanCreateInvoice { get; set; } @@ -25,7 +25,7 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Consider the invoice paid even if the paid amount is ... % less than expected")] [Range(0, 100)] public double PaymentTolerance { get; set; } - + [Display(Name = "Default currency")] [MaxLength(10)] public string DefaultCurrency { get; set; } diff --git a/BTCPayServer/Models/StoreViewModels/WalletSettingsViewModel.cs b/BTCPayServer/Models/StoreViewModels/WalletSettingsViewModel.cs index 3b0853fda..116d80571 100644 --- a/BTCPayServer/Models/StoreViewModels/WalletSettingsViewModel.cs +++ b/BTCPayServer/Models/StoreViewModels/WalletSettingsViewModel.cs @@ -11,7 +11,7 @@ namespace BTCPayServer.Models.StoreViewModels public string StoreId { get; set; } public bool IsHotWallet { get; set; } public bool CanUsePayJoin { get; set; } - + [Display(Name = "Enable Payjoin/P2EP")] public bool PayJoinEnabled { get; set; } @@ -28,9 +28,9 @@ namespace BTCPayServer.Models.StoreViewModels [Display(Name = "Consider the invoice confirmed when the payment transaction …")] public SpeedPolicy SpeedPolicy { get; set; } - + public string Label { get; set; } - + public string DerivationSchemeInput { get; set; } [Display(Name = "Is signing key")] public string SelectedSigningKey { get; set; } diff --git a/BTCPayServer/Models/ViewPullPaymentModel.cs b/BTCPayServer/Models/ViewPullPaymentModel.cs index 7610c7cd2..d684926da 100644 --- a/BTCPayServer/Models/ViewPullPaymentModel.cs +++ b/BTCPayServer/Models/ViewPullPaymentModel.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using BTCPayServer.Abstractions.Extensions; using System.Linq; +using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Client.Models; using BTCPayServer.Data; using BTCPayServer.Payments; diff --git a/BTCPayServer/Models/WalletViewModels/ListWalletsViewModel.cs b/BTCPayServer/Models/WalletViewModels/ListWalletsViewModel.cs index 0a90bd6ab..975c5ce6a 100644 --- a/BTCPayServer/Models/WalletViewModels/ListWalletsViewModel.cs +++ b/BTCPayServer/Models/WalletViewModels/ListWalletsViewModel.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NBitcoin; using BTCPayServer; +using NBitcoin; namespace BTCPayServer.Models.WalletViewModels { diff --git a/BTCPayServer/Models/WalletViewModels/PullPaymentsModel.cs b/BTCPayServer/Models/WalletViewModels/PullPaymentsModel.cs index 8e2faa960..ab6a96fa5 100644 --- a/BTCPayServer/Models/WalletViewModels/PullPaymentsModel.cs +++ b/BTCPayServer/Models/WalletViewModels/PullPaymentsModel.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Mvc.Rendering; namespace BTCPayServer.Models.WalletViewModels { - public class PullPaymentsModel: BasePagingViewModel + public class PullPaymentsModel : BasePagingViewModel { public class PullPaymentModel { diff --git a/BTCPayServer/Models/WalletViewModels/WalletSigningOptionsModel.cs b/BTCPayServer/Models/WalletViewModels/WalletSigningOptionsModel.cs index f3f46d93d..5de74a299 100644 --- a/BTCPayServer/Models/WalletViewModels/WalletSigningOptionsModel.cs +++ b/BTCPayServer/Models/WalletViewModels/WalletSigningOptionsModel.cs @@ -5,7 +5,7 @@ namespace BTCPayServer.Models.WalletViewModels public class WalletSigningOptionsModel { public WalletSigningOptionsModel( - SigningContextModel signingContext, + SigningContextModel signingContext, IDictionary routeDataBack) { SigningContext = signingContext; diff --git a/BTCPayServer/PaymentRequest/PaymentRequestHub.cs b/BTCPayServer/PaymentRequest/PaymentRequestHub.cs index 0b17cb489..cd9e46dac 100644 --- a/BTCPayServer/PaymentRequest/PaymentRequestHub.cs +++ b/BTCPayServer/PaymentRequest/PaymentRequestHub.cs @@ -151,7 +151,7 @@ namespace BTCPayServer.PaymentRequest { foreach (var paymentId in PaymentRequestRepository.GetPaymentIdsFromInternalTags(invoiceEvent.Invoice)) { - if (invoiceEvent.Name == InvoiceEvent.ReceivedPayment || invoiceEvent.Name == InvoiceEvent.MarkedCompleted || invoiceEvent.Name == InvoiceEvent.MarkedInvalid) + if (invoiceEvent.Name == InvoiceEvent.ReceivedPayment || invoiceEvent.Name == InvoiceEvent.MarkedCompleted || invoiceEvent.Name == InvoiceEvent.MarkedInvalid) { await _PaymentRequestService.UpdatePaymentRequestStateIfNeeded(paymentId); var data = invoiceEvent.Payment?.GetCryptoPaymentData(); diff --git a/BTCPayServer/PaymentRequest/PaymentRequestService.cs b/BTCPayServer/PaymentRequest/PaymentRequestService.cs index 2e4bcfb4e..e1083d090 100644 --- a/BTCPayServer/PaymentRequest/PaymentRequestService.cs +++ b/BTCPayServer/PaymentRequest/PaymentRequestService.cs @@ -140,7 +140,7 @@ namespace BTCPayServer.PaymentRequest if (state.Status == InvoiceStatusLegacy.Invalid || state.Status == InvoiceStatusLegacy.Expired && !payments.Any()) return null; - + return new ViewPaymentRequestViewModel.PaymentRequestInvoice { Id = entity.Id, diff --git a/BTCPayServer/Payments/Bitcoin/BitcoinLikeOnChainPaymentMethod.cs b/BTCPayServer/Payments/Bitcoin/BitcoinLikeOnChainPaymentMethod.cs index 28b522d2c..8cc0cae0d 100644 --- a/BTCPayServer/Payments/Bitcoin/BitcoinLikeOnChainPaymentMethod.cs +++ b/BTCPayServer/Payments/Bitcoin/BitcoinLikeOnChainPaymentMethod.cs @@ -55,7 +55,7 @@ namespace BTCPayServer.Payments.Bitcoin [JsonIgnore] public Money NextNetworkFee { get; set; } [JsonIgnore] - public String DepositAddress { get; set; } + public String DepositAddress { get; set; } [JsonConverter(typeof(NBitcoin.JsonConverters.KeyPathJsonConverter))] public KeyPath KeyPath { get; set; } diff --git a/BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentHandler.cs b/BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentHandler.cs index 3f0db280e..47f1aec9a 100644 --- a/BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentHandler.cs +++ b/BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentHandler.cs @@ -43,7 +43,7 @@ namespace BTCPayServer.Payments.Bitcoin network => Encoders.ASCII.EncodeData( network.NBitcoinNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false) .HumanReadablePart)); - + } class Prepare @@ -60,7 +60,7 @@ namespace BTCPayServer.Payments.Bitcoin var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork(model.CryptoCode); model.ShowRecommendedFee = storeBlob.ShowRecommendedFee; - model.FeeRate = ((BitcoinLikeOnChainPaymentMethod) paymentMethod.GetPaymentMethodDetails()).GetFeeRate(); + model.FeeRate = ((BitcoinLikeOnChainPaymentMethod)paymentMethod.GetPaymentMethodDetails()).GetFeeRate(); model.PaymentMethodName = GetPaymentMethodName(network); var lightningFallback = ""; @@ -92,7 +92,7 @@ namespace BTCPayServer.Payments.Bitcoin // .Replace("bitcoin:", "BITCOIN:", StringComparison.OrdinalIgnoreCase) // We're leading the way in Bitcoin community with adding UPPERCASE Bech32 addresses in QR Code - if (network.CryptoCode.Equals("BTC", StringComparison.InvariantCultureIgnoreCase) && _bech32Prefix.TryGetValue(model.CryptoCode, out var prefix) && model.BtcAddress.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + if (network.CryptoCode.Equals("BTC", StringComparison.InvariantCultureIgnoreCase) && _bech32Prefix.TryGetValue(model.CryptoCode, out var prefix) && model.BtcAddress.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrlQR.Replace( $"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress}", $"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress.ToUpperInvariant()}", diff --git a/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs b/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs index b65f2fe1a..82bedd269 100644 --- a/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs +++ b/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs @@ -157,7 +157,7 @@ namespace BTCPayServer.Payments.Bitcoin { var key = output.Item1.ScriptPubKey.Hash + "#" + network.CryptoCode.ToUpperInvariant(); - var invoice = (await _InvoiceRepository.GetInvoicesFromAddresses(new[] {key})) + var invoice = (await _InvoiceRepository.GetInvoicesFromAddresses(new[] { key })) .FirstOrDefault(); if (invoice != null) { @@ -418,7 +418,7 @@ namespace BTCPayServer.Payments.Bitcoin var paymentMethod = invoice.GetPaymentMethod(wallet.Network, PaymentTypes.BTCLike); if (paymentMethod != null && paymentMethod.GetPaymentMethodDetails() is BitcoinLikeOnChainPaymentMethod btc && - btc.Activated && + btc.Activated && btc.GetDepositAddress(wallet.Network.NBitcoinNetwork).ScriptPubKey == paymentData.ScriptPubKey && paymentMethod.Calculate().Due > Money.Zero) { diff --git a/BTCPayServer/Payments/IPaymentMethodDetails.cs b/BTCPayServer/Payments/IPaymentMethodDetails.cs index e1d058e56..3e1f708e4 100644 --- a/BTCPayServer/Payments/IPaymentMethodDetails.cs +++ b/BTCPayServer/Payments/IPaymentMethodDetails.cs @@ -17,7 +17,7 @@ namespace BTCPayServer.Payments /// decimal GetNextNetworkFee(); - bool Activated {get;set;} - virtual string GetAdditionalDataPartialName() => null; + bool Activated { get; set; } + virtual string GetAdditionalDataPartialName() => null; } } diff --git a/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentHandler.cs b/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentHandler.cs index 3c54d078f..80b9ee873 100644 --- a/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentHandler.cs +++ b/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentHandler.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; +using BTCPayServer.Client.Models; using BTCPayServer.Configuration; using BTCPayServer.Data; using BTCPayServer.HostedServices; @@ -12,7 +13,6 @@ using BTCPayServer.Lightning; using BTCPayServer.Logging; using BTCPayServer.Models; using BTCPayServer.Models.InvoicingModels; -using BTCPayServer.Client.Models; using BTCPayServer.Services; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Rates; @@ -67,23 +67,24 @@ namespace BTCPayServer.Payments.Lightning return new LNURLPayPaymentMethodDetails() { - Activated = false, LightningSupportedPaymentMethod = lnSupported + Activated = false, + LightningSupportedPaymentMethod = lnSupported }; } var lnLightningSupportedPaymentMethod = ((LNURLPayPaymentMethodDetails)paymentMethod.GetPaymentMethodDetails()).LightningSupportedPaymentMethod; - + NodeInfo? nodeInfo = null; if (lnLightningSupportedPaymentMethod != null) { nodeInfo = (await _lightningLikePaymentHandler.GetNodeInfo(lnLightningSupportedPaymentMethod, _networkProvider.GetNetwork(supportedPaymentMethod.CryptoCode), logs, paymentMethod.PreferOnion)).FirstOrDefault(); } - + return new LNURLPayPaymentMethodDetails { - Activated = true, + Activated = true, LightningSupportedPaymentMethod = lnLightningSupportedPaymentMethod, BTCPayInvoiceId = paymentMethod.ParentEntity.Id, Bech32Mode = supportedPaymentMethod.UseBech32Scheme, @@ -110,8 +111,8 @@ namespace BTCPayServer.Payments.Lightning model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls?.AdditionalData["LNURLP"].ToObject(); model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrl; model.BtcAddress = model.InvoiceBitcoinUrl; - model.PeerInfo = ((LNURLPayPaymentMethodDetails) paymentMethod.GetPaymentMethodDetails()).NodeInfo; - if ( storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") + model.PeerInfo = ((LNURLPayPaymentMethodDetails)paymentMethod.GetPaymentMethodDetails()).NodeInfo; + if (storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") { var satoshiCulture = new CultureInfo(CultureInfo.InvariantCulture.Name); satoshiCulture.NumberFormat.NumberGroupSeparator = " "; diff --git a/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentMethodDetails.cs b/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentMethodDetails.cs index 52857debc..b4f17ff34 100644 --- a/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentMethodDetails.cs +++ b/BTCPayServer/Payments/LNURLPay/LNURLPayPaymentMethodDetails.cs @@ -1,4 +1,4 @@ -using BTCPayServer.Client.JsonConverters; +using BTCPayServer.Client.JsonConverters; using BTCPayServer.Lightning; using BTCPayServer.Payments.Lightning; using Newtonsoft.Json; @@ -8,7 +8,7 @@ namespace BTCPayServer.Payments public class LNURLPayPaymentMethodDetails : LightningLikePaymentMethodDetails { public LightningSupportedPaymentMethod LightningSupportedPaymentMethod { get; set; } - + [JsonConverter(typeof(LightMoneyJsonConverter))] public LightMoney GeneratedBoltAmount { get; set; } public string BTCPayInvoiceId { get; set; } diff --git a/BTCPayServer/Payments/LNURLPay/PaymentTypes.LNURL.cs b/BTCPayServer/Payments/LNURLPay/PaymentTypes.LNURL.cs index 5e3cc6a78..870be34fb 100644 --- a/BTCPayServer/Payments/LNURLPay/PaymentTypes.LNURL.cs +++ b/BTCPayServer/Payments/LNURLPay/PaymentTypes.LNURL.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Payments { public class LNURLPayPaymentType : LightningPaymentType { - public new static LNURLPayPaymentType Instance { get; } = new LNURLPayPaymentType(); + public new static LNURLPayPaymentType Instance { get; } = new LNURLPayPaymentType(); public override string ToPrettyString() => "LNURL-Pay"; public override string GetId() => "LNURLPAY"; public override string ToStringNormalized() => "LNURLPAY"; diff --git a/BTCPayServer/Payments/Lightning/LightningExtensions.cs b/BTCPayServer/Payments/Lightning/LightningExtensions.cs index bbdcc9389..535174f77 100644 --- a/BTCPayServer/Payments/Lightning/LightningExtensions.cs +++ b/BTCPayServer/Payments/Lightning/LightningExtensions.cs @@ -4,11 +4,11 @@ using BTCPayServer.Services; namespace BTCPayServer.Payments.Lightning { - public static class LightningExtensions + public static class LightningExtensions { - - public static ILightningClient CreateLightningClient(this LightningSupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, LightningNetworkOptions options, LightningClientFactoryService lightningClientFactory) + + public static ILightningClient CreateLightningClient(this LightningSupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, LightningNetworkOptions options, LightningClientFactoryService lightningClientFactory) { var external = supportedPaymentMethod.GetExternalLightningUrl(); if (external != null) diff --git a/BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs b/BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs index c082e51e3..32b371547 100644 --- a/BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs +++ b/BTCPayServer/Payments/Lightning/LightningLikePaymentHandler.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; +using BTCPayServer.Client.Models; using BTCPayServer.Configuration; using BTCPayServer.Data; using BTCPayServer.HostedServices; @@ -12,7 +13,6 @@ using BTCPayServer.Lightning; using BTCPayServer.Logging; using BTCPayServer.Models; using BTCPayServer.Models.InvoicingModels; -using BTCPayServer.Client.Models; using BTCPayServer.Services; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Rates; @@ -34,7 +34,7 @@ namespace BTCPayServer.Payments.Lightning NBXplorerDashboard dashboard, LightningClientFactoryService lightningClientFactory, BTCPayNetworkProvider networkProvider, - SocketFactory socketFactory, + SocketFactory socketFactory, CurrencyNameTable currencyNameTable, IOptions options) { @@ -59,7 +59,8 @@ namespace BTCPayServer.Payments.Lightning { throw new PaymentMethodUnavailableException("BOLT11 payment method is disabled"); } - if (paymentMethod.ParentEntity.Type == InvoiceType.TopUp) { + if (paymentMethod.ParentEntity.Type == InvoiceType.TopUp) + { throw new PaymentMethodUnavailableException("Lightning Network payment method is not available for top-up invoices"); } @@ -72,7 +73,7 @@ namespace BTCPayServer.Payments.Lightning } var storeBlob = store.GetStoreBlob(); var nodeInfo = GetNodeInfo(supportedPaymentMethod, network, logs, paymentMethod.PreferOnion); - + var invoice = paymentMethod.ParentEntity; decimal due = Extensions.RoundUp(invoice.Price / paymentMethod.Rate, network.Divisibility); try @@ -122,7 +123,7 @@ namespace BTCPayServer.Payments.Lightning }; } - public async Task GetNodeInfo(LightningSupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, InvoiceLogs invoiceLogs, bool? preferOnion = null, bool throws=false) + public async Task GetNodeInfo(LightningSupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, InvoiceLogs invoiceLogs, bool? preferOnion = null, bool throws = false) { if (!_Dashboard.IsFullySynched(network.CryptoCode, out var summary)) throw new PaymentMethodUnavailableException("Full node not available"); @@ -143,14 +144,14 @@ namespace BTCPayServer.Payments.Lightning } catch (Exception ex) { - throw new PaymentMethodUnavailableException($"Error while connecting to the API: {ex.Message}" + + throw new PaymentMethodUnavailableException($"Error while connecting to the API: {ex.Message}" + (!string.IsNullOrEmpty(ex.InnerException?.Message) ? $" ({ex.InnerException.Message})" : "")); } var nodeInfo = preferOnion != null && info.NodeInfoList.Any(i => i.IsTor == preferOnion) ? info.NodeInfoList.Where(i => i.IsTor == preferOnion.Value).ToArray() : info.NodeInfoList.Select(i => i).ToArray(); - + // Maybe the user does not have an easily accessible ln node. Node info should be optional. The UI also supports this. // if (!nodeInfo.Any()) // { @@ -166,7 +167,7 @@ namespace BTCPayServer.Payments.Lightning return nodeInfo; } } - catch(Exception e) when (!throws) + catch (Exception e) when (!throws) { invoiceLogs.Write($"NodeInfo failed to be fetched: {e.Message}", InvoiceEventData.EventSeverity.Error); } @@ -226,7 +227,7 @@ namespace BTCPayServer.Payments.Lightning model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls?.BOLT11; model.InvoiceBitcoinUrlQR = $"lightning:{cryptoInfo.PaymentUrls?.BOLT11?.ToUpperInvariant()?.Substring("LIGHTNING:".Length)}"; - model.PeerInfo = ((LightningLikePaymentMethodDetails) paymentMethod.GetPaymentMethodDetails()).NodeInfo; + model.PeerInfo = ((LightningLikePaymentMethodDetails)paymentMethod.GetPaymentMethodDetails()).NodeInfo; if (storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") { var satoshiCulture = new CultureInfo(CultureInfo.InvariantCulture.Name); diff --git a/BTCPayServer/Payments/Lightning/LightningListener.cs b/BTCPayServer/Payments/Lightning/LightningListener.cs index cbc159aac..0a49d5e9c 100644 --- a/BTCPayServer/Payments/Lightning/LightningListener.cs +++ b/BTCPayServer/Payments/Lightning/LightningListener.cs @@ -115,53 +115,53 @@ namespace BTCPayServer.Payments.Lightning } private Task> GetListenedInvoices(string invoiceId) { - return _memoryCache.GetOrCreateAsync( GetCacheKey(invoiceId), async (cacheEntry) => - { - var listenedInvoices = new List(); - var invoice = await _InvoiceRepository.GetInvoice(invoiceId); - foreach (var paymentMethod in invoice.GetPaymentMethods() - .Where(c => new []{PaymentTypes.LightningLike, LNURLPayPaymentType.Instance }.Contains(c.GetId().PaymentType))) - { - LightningLikePaymentMethodDetails lightningMethod; - LightningSupportedPaymentMethod lightningSupportedMethod; - switch (paymentMethod.GetPaymentMethodDetails()) - { - case LNURLPayPaymentMethodDetails lnurlPayPaymentMethodDetails: + return _memoryCache.GetOrCreateAsync(GetCacheKey(invoiceId), async (cacheEntry) => + { + var listenedInvoices = new List(); + var invoice = await _InvoiceRepository.GetInvoice(invoiceId); + foreach (var paymentMethod in invoice.GetPaymentMethods() + .Where(c => new[] { PaymentTypes.LightningLike, LNURLPayPaymentType.Instance }.Contains(c.GetId().PaymentType))) + { + LightningLikePaymentMethodDetails lightningMethod; + LightningSupportedPaymentMethod lightningSupportedMethod; + switch (paymentMethod.GetPaymentMethodDetails()) + { + case LNURLPayPaymentMethodDetails lnurlPayPaymentMethodDetails: - lightningMethod = lnurlPayPaymentMethodDetails; - - lightningSupportedMethod = lnurlPayPaymentMethodDetails.LightningSupportedPaymentMethod; - - break; - case LightningLikePaymentMethodDetails { Activated: true } lightningLikePaymentMethodDetails: - lightningMethod = lightningLikePaymentMethodDetails; - lightningSupportedMethod = invoice.GetSupportedPaymentMethod() - .FirstOrDefault(c => c.CryptoCode == paymentMethod.GetId().CryptoCode); + lightningMethod = lnurlPayPaymentMethodDetails; - break; - default: - continue; - } + lightningSupportedMethod = lnurlPayPaymentMethodDetails.LightningSupportedPaymentMethod; + + break; + case LightningLikePaymentMethodDetails { Activated: true } lightningLikePaymentMethodDetails: + lightningMethod = lightningLikePaymentMethodDetails; + lightningSupportedMethod = invoice.GetSupportedPaymentMethod() + .FirstOrDefault(c => c.CryptoCode == paymentMethod.GetId().CryptoCode); + + break; + default: + continue; + } if (lightningSupportedMethod == null || string.IsNullOrEmpty(lightningMethod.InvoiceId)) - continue; - var network = _NetworkProvider.GetNetwork(paymentMethod.GetId().CryptoCode); + continue; + var network = _NetworkProvider.GetNetwork(paymentMethod.GetId().CryptoCode); - listenedInvoices.Add(new ListenedInvoice() - { - Expiration = invoice.ExpirationTime, - Uri = GetLightningUrl(lightningSupportedMethod).BaseUri.AbsoluteUri, - PaymentMethodDetails = lightningMethod, - SupportedPaymentMethod = lightningSupportedMethod, - PaymentMethod = paymentMethod, - Network = network, - InvoiceId = invoice.Id - }); - } - var expiredIn = DateTimeOffset.UtcNow - invoice.ExpirationTime; - cacheEntry.AbsoluteExpiration = DateTimeOffset.UtcNow + (expiredIn >= TimeSpan.FromMinutes(5.0) ? expiredIn : TimeSpan.FromMinutes(5.0)); - return listenedInvoices; - }); + listenedInvoices.Add(new ListenedInvoice() + { + Expiration = invoice.ExpirationTime, + Uri = GetLightningUrl(lightningSupportedMethod).BaseUri.AbsoluteUri, + PaymentMethodDetails = lightningMethod, + SupportedPaymentMethod = lightningSupportedMethod, + PaymentMethod = paymentMethod, + Network = network, + InvoiceId = invoice.Id + }); + } + var expiredIn = DateTimeOffset.UtcNow - invoice.ExpirationTime; + cacheEntry.AbsoluteExpiration = DateTimeOffset.UtcNow + (expiredIn >= TimeSpan.FromMinutes(5.0) ? expiredIn : TimeSpan.FromMinutes(5.0)); + return listenedInvoices; + }); } readonly ConcurrentDictionary _ListeningInstances = new ConcurrentDictionary(); @@ -192,7 +192,7 @@ namespace BTCPayServer.Payments.Lightning var invoice = await _InvoiceRepository.GetInvoice(inv.InvoiceId); await CreateNewLNInvoiceForBTCPayInvoice(invoice); } - + })); leases.Add(_Aggregator.Subscribe(inv => { @@ -229,7 +229,7 @@ namespace BTCPayServer.Payments.Lightning private async Task CreateNewLNInvoiceForBTCPayInvoice(InvoiceEntity invoice) { var paymentMethods = invoice.GetPaymentMethods() - .Where(method => new []{PaymentTypes.LightningLike, LNURLPayPaymentType.Instance}.Contains(method.GetId().PaymentType)) + .Where(method => new[] { PaymentTypes.LightningLike, LNURLPayPaymentType.Instance }.Contains(method.GetId().PaymentType)) .ToArray(); var store = await _storeRepository.FindStore(invoice.StoreId); if (paymentMethods.Any()) @@ -242,13 +242,13 @@ namespace BTCPayServer.Payments.Lightning { try { - var oldDetails = (LightningLikePaymentMethodDetails) paymentMethod.GetPaymentMethodDetails(); + var oldDetails = (LightningLikePaymentMethodDetails)paymentMethod.GetPaymentMethodDetails(); if (!oldDetails.Activated) { continue; } - + if (oldDetails is LNURLPayPaymentMethodDetails lnurlPayPaymentMethodDetails && !string.IsNullOrEmpty(lnurlPayPaymentMethodDetails.BOLT11)) { try @@ -275,10 +275,10 @@ namespace BTCPayServer.Payments.Lightning }; await _InvoiceRepository.NewPaymentDetails(invoice.Id, lnurlPayPaymentMethodDetails, paymentMethod.Network); - + _Aggregator.Publish(new Events.InvoiceNewPaymentDetailsEvent(invoice.Id, lnurlPayPaymentMethodDetails, paymentMethod.GetId())); - + continue; } @@ -434,7 +434,7 @@ namespace BTCPayServer.Payments.Lightning var client = _lightningClientFactory.Create(ConnectionString, _network); LightningInvoice lightningInvoice = await client.GetInvoice(listenedInvoice.PaymentMethodDetails.InvoiceId, cancellation); if (lightningInvoice?.Status is LightningInvoiceStatus.Paid && - await AddPayment(lightningInvoice, listenedInvoice.InvoiceId,listenedInvoice.PaymentMethod.GetId().PaymentType)) + await AddPayment(lightningInvoice, listenedInvoice.InvoiceId, listenedInvoice.PaymentMethod.GetId().PaymentType)) { Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Payment detected via polling on {listenedInvoice.InvoiceId}"); } diff --git a/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs b/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs index f1265c307..642fb12d3 100644 --- a/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs +++ b/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs @@ -259,7 +259,7 @@ namespace BTCPayServer.Payments.PayJoin { var key = output.ScriptPubKey.Hash + "#" + network.CryptoCode.ToUpperInvariant(); - invoice = (await _invoiceRepository.GetInvoicesFromAddresses(new[] {key})).FirstOrDefault(); + invoice = (await _invoiceRepository.GetInvoicesFromAddresses(new[] { key })).FirstOrDefault(); if (invoice is null) continue; derivationSchemeSettings = invoice @@ -272,10 +272,10 @@ namespace BTCPayServer.Payments.PayJoin var store = await _storeRepository.FindStore(walletReceiveMatch.Item1.StoreId); derivationSchemeSettings = store.GetDerivationSchemeSettings(_btcPayNetworkProvider, walletReceiveMatch.Item1.CryptoCode); - + walletId = walletReceiveMatch.Item1; } - + if (derivationSchemeSettings is null) continue; var receiverInputsType = derivationSchemeSettings.AccountDerivation.ScriptPubKeyType(); @@ -499,10 +499,10 @@ namespace BTCPayServer.Payments.PayJoin return UnprocessableEntity(CreatePayjoinError("already-paid", $"The original transaction has already been accounted")); } - _eventAggregator.Publish(new InvoiceEvent(invoice,InvoiceEvent.ReceivedPayment) { Payment = payment }); + _eventAggregator.Publish(new InvoiceEvent(invoice, InvoiceEvent.ReceivedPayment) { Payment = payment }); } - + await _btcPayWalletProvider.GetWallet(network).SaveOffchainTransactionAsync(ctx.OriginalTransaction); _eventAggregator.Publish(new UpdateTransactionLabel() { diff --git a/BTCPayServer/Payments/PayJoin/PayJoinExtensions.cs b/BTCPayServer/Payments/PayJoin/PayJoinExtensions.cs index 5ff575e52..5e718dee1 100644 --- a/BTCPayServer/Payments/PayJoin/PayJoinExtensions.cs +++ b/BTCPayServer/Payments/PayJoin/PayJoinExtensions.cs @@ -1,9 +1,9 @@ +using BTCPayServer.BIP78.Sender; using BTCPayServer.HostedServices; using BTCPayServer.Payments.PayJoin.Sender; using BTCPayServer.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using BTCPayServer.BIP78.Sender; namespace BTCPayServer.Payments.PayJoin { diff --git a/BTCPayServer/Payments/PaymentTypes.Bitcoin.cs b/BTCPayServer/Payments/PaymentTypes.Bitcoin.cs index aa3887b9c..9711f3c41 100644 --- a/BTCPayServer/Payments/PaymentTypes.Bitcoin.cs +++ b/BTCPayServer/Payments/PaymentTypes.Bitcoin.cs @@ -1,11 +1,11 @@ using System; using System.Globalization; using System.Linq; +using BTCPayServer.BIP78.Sender; +using BTCPayServer.Client.Models; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services.Invoices; using NBitcoin; -using BTCPayServer.BIP78.Sender; -using BTCPayServer.Client.Models; using NBitpayClient; using Newtonsoft.Json.Linq; using InvoiceCryptoInfo = BTCPayServer.Services.Invoices.InvoiceCryptoInfo; @@ -15,7 +15,7 @@ namespace BTCPayServer.Payments public class BitcoinPaymentType : PaymentType { public static BitcoinPaymentType Instance { get; } = new BitcoinPaymentType(); - + private BitcoinPaymentType() { } public override string ToPrettyString() => "On-Chain"; diff --git a/BTCPayServer/Payments/PaymentTypes.cs b/BTCPayServer/Payments/PaymentTypes.cs index cc227b4cb..caf365958 100644 --- a/BTCPayServer/Payments/PaymentTypes.cs +++ b/BTCPayServer/Payments/PaymentTypes.cs @@ -84,7 +84,7 @@ namespace BTCPayServer.Payments public abstract string InvoiceViewPaymentPartialName { get; } public abstract object GetGreenfieldData(ISupportedPaymentMethod supportedPaymentMethod, bool canModifyStore); - + public virtual bool IsPaymentType(string paymentType) { return IsPaymentTypeBase(paymentType); @@ -95,7 +95,7 @@ namespace BTCPayServer.Payments paymentType = paymentType?.ToLowerInvariant(); return new[] { - GetId().Replace("-", "", StringComparison.InvariantCulture), + GetId().Replace("-", "", StringComparison.InvariantCulture), ToStringNormalized() }.Contains( paymentType, diff --git a/BTCPayServer/Plugins/BTCPayServerPlugin.cs b/BTCPayServer/Plugins/BTCPayServerPlugin.cs index ce3b9b815..26a1c4a37 100644 --- a/BTCPayServer/Plugins/BTCPayServerPlugin.cs +++ b/BTCPayServer/Plugins/BTCPayServerPlugin.cs @@ -3,11 +3,11 @@ using BTCPayServer.Models; namespace BTCPayServer.Plugins { - public class BTCPayServerPlugin: BaseBTCPayServerPlugin + public class BTCPayServerPlugin : BaseBTCPayServerPlugin { public override string Identifier { get; } = nameof(BTCPayServer); public override string Name { get; } = "BTCPay Server"; - public override string Description { get; }= "BTCPay Server core system"; - + public override string Description { get; } = "BTCPay Server core system"; + } } diff --git a/BTCPayServer/Plugins/PluginManager.cs b/BTCPayServer/Plugins/PluginManager.cs index 1f0fe4550..d92f22086 100644 --- a/BTCPayServer/Plugins/PluginManager.cs +++ b/BTCPayServer/Plugins/PluginManager.cs @@ -53,7 +53,7 @@ namespace BTCPayServer.Plugins if (!detectedPlugins.Any()) { continue; - + } detectedPlugins = detectedPlugins.Select(plugin => @@ -61,12 +61,12 @@ namespace BTCPayServer.Plugins plugin.SystemPlugin = true; return plugin; }); - - loadedPlugins.Add((null,systemExtension, CreateEmbeddedFileProviderForAssembly(systemExtension))); + + loadedPlugins.Add((null, systemExtension, CreateEmbeddedFileProviderForAssembly(systemExtension))); plugins.AddRange(detectedPlugins); } var orderFilePath = Path.Combine(pluginsFolder, "order"); - + var availableDirs = Directory.GetDirectories(pluginsFolder); var orderedDirs = new List(); if (File.Exists(orderFilePath)) @@ -163,7 +163,7 @@ namespace BTCPayServer.Plugins } var webHostEnvironment = applicationBuilder.ApplicationServices.GetService(); - List providers = new List() {webHostEnvironment.WebRootFileProvider}; + List providers = new List() { webHostEnvironment.WebRootFileProvider }; providers.AddRange(loadedPlugins.Select(tuple => tuple.Item3)); webHostEnvironment.WebRootFileProvider = new CompositeFileProvider(providers); } @@ -214,7 +214,7 @@ namespace BTCPayServer.Plugins ExecuteCommand(("install", command.extension), pluginsFolder, true); break; case "delete": - + ExecuteCommand(("enable", command.extension), pluginsFolder, true); if (Directory.Exists(dirName)) { @@ -228,7 +228,7 @@ namespace BTCPayServer.Plugins } break; - case "install": + case "install": ExecuteCommand(("enable", command.extension), pluginsFolder, true); var fileName = dirName + BTCPayPluginSuffix; if (File.Exists(fileName)) @@ -236,14 +236,14 @@ namespace BTCPayServer.Plugins ZipFile.ExtractToDirectory(fileName, dirName, true); if (!ignoreOrder) { - File.AppendAllLines(Path.Combine(pluginsFolder, "order"), new[] {command.extension}); + File.AppendAllLines(Path.Combine(pluginsFolder, "order"), new[] { command.extension }); } File.Delete(fileName); } break; - + case "disable": if (Directory.Exists(dirName)) { @@ -252,24 +252,24 @@ namespace BTCPayServer.Plugins var disabled = File.ReadAllLines(Path.Combine(pluginsFolder, "disabled")); if (!disabled.Contains(command.extension)) { - File.AppendAllLines(Path.Combine(pluginsFolder, "disabled"), new []{ command.extension}); + File.AppendAllLines(Path.Combine(pluginsFolder, "disabled"), new[] { command.extension }); } } else { - File.AppendAllLines(Path.Combine(pluginsFolder, "disabled"), new []{ command.extension}); + File.AppendAllLines(Path.Combine(pluginsFolder, "disabled"), new[] { command.extension }); } } break; - + case "enable": if (File.Exists(Path.Combine(pluginsFolder, "disabled"))) { var disabled = File.ReadAllLines(Path.Combine(pluginsFolder, "disabled")); if (disabled.Contains(command.extension)) { - File.WriteAllLines(Path.Combine(pluginsFolder, "disabled"), disabled.Where(s=> s!= command.extension)); + File.WriteAllLines(Path.Combine(pluginsFolder, "disabled"), disabled.Where(s => s != command.extension)); } } @@ -289,7 +289,7 @@ namespace BTCPayServer.Plugins }).ToArray(); } - public static void QueueCommands(string pluginsFolder, params ( string action, string plugin)[] commands) + public static void QueueCommands(string pluginsFolder, params (string action, string plugin)[] commands) { File.AppendAllLines(Path.Combine(pluginsFolder, "commands"), commands.Select((tuple) => $"{tuple.action}:{tuple.plugin}")); @@ -306,8 +306,8 @@ namespace BTCPayServer.Plugins public static void DisablePlugin(string pluginDir, string plugin) { - - QueueCommands(pluginDir, ("disable",plugin)); + + QueueCommands(pluginDir, ("disable", plugin)); } public static void Unload() diff --git a/BTCPayServer/Plugins/PluginService.cs b/BTCPayServer/Plugins/PluginService.cs index 228f3ef89..a18fdd2ca 100644 --- a/BTCPayServer/Plugins/PluginService.cs +++ b/BTCPayServer/Plugins/PluginService.cs @@ -133,7 +133,7 @@ namespace BTCPayServer.Plugins return PluginManager.GetPendingCommands(_dataDirectories.Value.PluginDir); } - public void CancelCommands(string plugin) + public void CancelCommands(string plugin) { PluginManager.CancelCommands(_dataDirectories.Value.PluginDir, plugin); } diff --git a/BTCPayServer/Plugins/Shopify/ApiModels/CreateScriptResponse.cs b/BTCPayServer/Plugins/Shopify/ApiModels/CreateScriptResponse.cs index 705c184ad..ce7ccb292 100644 --- a/BTCPayServer/Plugins/Shopify/ApiModels/CreateScriptResponse.cs +++ b/BTCPayServer/Plugins/Shopify/ApiModels/CreateScriptResponse.cs @@ -8,24 +8,25 @@ namespace BTCPayServer.Plugins.Shopify.ApiModels [JsonProperty("script_tag")] public ScriptTag ScriptTag { get; set; } } - - public class ScriptTag { + + public class ScriptTag + { [JsonProperty("id")] - public int Id { get; set; } + public int Id { get; set; } [JsonProperty("src")] - public string Src { get; set; } + public string Src { get; set; } [JsonProperty("event")] - public string Event { get; set; } + public string Event { get; set; } [JsonProperty("created_at")] - public DateTime CreatedAt { get; set; } + public DateTime CreatedAt { get; set; } [JsonProperty("updated_at")] - public DateTime UpdatedAt { get; set; } + public DateTime UpdatedAt { get; set; } [JsonProperty("display_scope")] - public string DisplayScope { get; set; } + public string DisplayScope { get; set; } } } diff --git a/BTCPayServer/Plugins/Shopify/ApiModels/OrdersCountResp.cs b/BTCPayServer/Plugins/Shopify/ApiModels/OrdersCountResp.cs index a20fcec30..a0b85f854 100644 --- a/BTCPayServer/Plugins/Shopify/ApiModels/OrdersCountResp.cs +++ b/BTCPayServer/Plugins/Shopify/ApiModels/OrdersCountResp.cs @@ -4,7 +4,7 @@ namespace BTCPayServer.Plugins.Shopify.ApiModels { public class CountResponse { - [JsonProperty("count")] + [JsonProperty("count")] public long Count { get; set; } } } diff --git a/BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs b/BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs index b700be10d..9f2e0e0e6 100644 --- a/BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs +++ b/BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs @@ -25,7 +25,7 @@ namespace BTCPayServer.Plugins.Shopify.Models { get { - return ShopName?.Contains(".", StringComparison.OrdinalIgnoreCase) is true ? ShopName : $"https://{ShopName}.myshopify.com" ; + return ShopName?.Contains(".", StringComparison.OrdinalIgnoreCase) is true ? ShopName : $"https://{ShopName}.myshopify.com"; } } } diff --git a/BTCPayServer/Plugins/Shopify/OrderTransactionRegisterLogic.cs b/BTCPayServer/Plugins/Shopify/OrderTransactionRegisterLogic.cs index 82ffaf9c9..2e16f5993 100644 --- a/BTCPayServer/Plugins/Shopify/OrderTransactionRegisterLogic.cs +++ b/BTCPayServer/Plugins/Shopify/OrderTransactionRegisterLogic.cs @@ -19,7 +19,7 @@ namespace BTCPayServer.Plugins.Shopify { currency = currency.ToUpperInvariant().Trim(); var existingShopifyOrderTransactions = (await _client.TransactionsList(orderId)).transactions; - + //if there isn't a record for btcpay payment gateway, abort var baseParentTransaction = existingShopifyOrderTransactions.FirstOrDefault(holder => !_keywords.Any(a => holder.gateway.Contains(a, StringComparison.InvariantCultureIgnoreCase))); if (baseParentTransaction is null) diff --git a/BTCPayServer/Plugins/Shopify/ShopifyApiClient.cs b/BTCPayServer/Plugins/Shopify/ShopifyApiClient.cs index f3a524341..ce4425236 100644 --- a/BTCPayServer/Plugins/Shopify/ShopifyApiClient.cs +++ b/BTCPayServer/Plugins/Shopify/ShopifyApiClient.cs @@ -57,7 +57,7 @@ namespace BTCPayServer.Plugins.Shopify public async Task CreateWebhook(string topic, string address, string format = "json") { var req = CreateRequest(_credentials.ShopName, HttpMethod.Post, $"webhooks.json"); - req.Content = new StringContent(JsonConvert.SerializeObject(new {topic, address, format}), Encoding.UTF8, + req.Content = new StringContent(JsonConvert.SerializeObject(new { topic, address, format }), Encoding.UTF8, "application/json"); var strResp = await SendRequest(req); @@ -134,4 +134,4 @@ namespace BTCPayServer.Plugins.Shopify public string ApiKey { get; set; } public string ApiPassword { get; set; } } -} \ No newline at end of file +} diff --git a/BTCPayServer/Plugins/Shopify/ShopifyController.cs b/BTCPayServer/Plugins/Shopify/ShopifyController.cs index 41f5e9c08..c9c8246b5 100644 --- a/BTCPayServer/Plugins/Shopify/ShopifyController.cs +++ b/BTCPayServer/Plugins/Shopify/ShopifyController.cs @@ -28,7 +28,7 @@ using StoreData = BTCPayServer.Data.StoreData; namespace BTCPayServer.Plugins.Shopify { - + [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public class ShopifyController : Controller @@ -77,8 +77,8 @@ namespace BTCPayServer.Plugins.Shopify } string[] fileList = _btcPayServerOptions.Value.BundleJsCss - ? new[] {"bundles/shopify-bundle.min.js"} - : new[] {"modal/btcpay.js", "shopify/btcpay-shopify.js"}; + ? new[] { "bundles/shopify-bundle.min.js" } + : new[] { "modal/btcpay.js", "shopify/btcpay-shopify.js" }; foreach (var file in fileList) @@ -111,7 +111,8 @@ namespace BTCPayServer.Plugins.Shopify var invoiceOrderId = $"{ShopifyOrderMarkerHostedService.SHOPIFY_ORDER_ID_PREFIX}{orderId}"; var matchedExistingInvoices = await _invoiceRepository.GetInvoices(new InvoiceQuery() { - OrderId = new[] {invoiceOrderId}, StoreId = new[] {storeId} + OrderId = new[] { invoiceOrderId }, + StoreId = new[] { storeId } }); matchedExistingInvoices = matchedExistingInvoices.Where(entity => entity.GetInternalTags(ShopifyOrderMarkerHostedService.SHOPIFY_ORDER_ID_PREFIX) @@ -132,7 +133,7 @@ namespace BTCPayServer.Plugins.Shopify var firstInvoiceSettled = matchedExistingInvoices.LastOrDefault(entity => - new[] {InvoiceStatusLegacy.Paid, InvoiceStatusLegacy.Complete, InvoiceStatusLegacy.Confirmed} + new[] { InvoiceStatusLegacy.Paid, InvoiceStatusLegacy.Complete, InvoiceStatusLegacy.Confirmed } .Contains( entity.GetInvoiceState().Status)); @@ -180,7 +181,7 @@ namespace BTCPayServer.Plugins.Shopify if (shopify?.IntegratedAt.HasValue is true) { if (string.IsNullOrEmpty(order?.Id) || - !new[] {"pending", "partially_paid"}.Contains(order.FinancialStatus)) + !new[] { "pending", "partially_paid" }.Contains(order.FinancialStatus)) { return NotFound(); } @@ -191,11 +192,11 @@ namespace BTCPayServer.Plugins.Shopify { Amount = amount < order.TotalOutstanding ? amount : order.TotalOutstanding, Currency = order.PresentmentCurrency, - Metadata = new JObject {["orderId"] = invoiceOrderId} + Metadata = new JObject { ["orderId"] = invoiceOrderId } }, store, - Request.GetAbsoluteRoot(), new List() {invoiceOrderId}); + Request.GetAbsoluteRoot(), new List() { invoiceOrderId }); - return Ok(new {invoiceId = invoice.Id, status = invoice.Status.ToString().ToLowerInvariant()}); + return Ok(new { invoiceId = invoice.Id, status = invoice.Status.ToString().ToLowerInvariant() }); } return NotFound(); @@ -207,7 +208,7 @@ namespace BTCPayServer.Plugins.Shopify { var blob = CurrentStore.GetStoreBlob(); - return View( blob.GetShopifySettings()); + return View(blob.GetShopifySettings()); } @@ -234,72 +235,72 @@ namespace BTCPayServer.Plugins.Shopify catch (Exception) { TempData[WellKnownTempData.ErrorMessage] = "The provided Example Url was invalid."; - return View( vm); + return View(vm); } } switch (command) { case "ShopifySaveCredentials": - { - var shopify = vm; - var validCreds = shopify != null && shopify?.CredentialsPopulated() == true; - if (!validCreds) { - TempData[WellKnownTempData.ErrorMessage] = "Please provide valid Shopify credentials"; - return View(vm); - } + var shopify = vm; + var validCreds = shopify != null && shopify?.CredentialsPopulated() == true; + if (!validCreds) + { + TempData[WellKnownTempData.ErrorMessage] = "Please provide valid Shopify credentials"; + return View(vm); + } - var apiClient = new ShopifyApiClient(_clientFactory, shopify.CreateShopifyApiCredentials()); - try - { - await apiClient.OrdersCount(); - } - catch (ShopifyApiException) - { - TempData[WellKnownTempData.ErrorMessage] = - "Shopify rejected provided credentials, please correct values and try again"; - return View( vm); - } + var apiClient = new ShopifyApiClient(_clientFactory, shopify.CreateShopifyApiCredentials()); + try + { + await apiClient.OrdersCount(); + } + catch (ShopifyApiException) + { + TempData[WellKnownTempData.ErrorMessage] = + "Shopify rejected provided credentials, please correct values and try again"; + return View(vm); + } - var scopesGranted = await apiClient.CheckScopes(); - if (!scopesGranted.Contains("read_orders") || !scopesGranted.Contains("write_orders")) - { - TempData[WellKnownTempData.ErrorMessage] = - "Please grant the private app permissions for read_orders, write_orders"; - return View(vm); + var scopesGranted = await apiClient.CheckScopes(); + if (!scopesGranted.Contains("read_orders") || !scopesGranted.Contains("write_orders")) + { + TempData[WellKnownTempData.ErrorMessage] = + "Please grant the private app permissions for read_orders, write_orders"; + return View(vm); + } + + // everything ready, proceed with saving Shopify integration credentials + shopify.IntegratedAt = DateTimeOffset.Now; + + var blob = CurrentStore.GetStoreBlob(); + blob.SetShopifySettings(shopify); + if (CurrentStore.SetStoreBlob(blob)) + { + await _storeRepository.UpdateStore(CurrentStore); + } + + TempData[WellKnownTempData.SuccessMessage] = "Shopify integration successfully updated"; + break; } - - // everything ready, proceed with saving Shopify integration credentials - shopify.IntegratedAt = DateTimeOffset.Now; - - var blob = CurrentStore.GetStoreBlob(); - blob.SetShopifySettings(shopify); - if (CurrentStore.SetStoreBlob(blob)) - { - await _storeRepository.UpdateStore(CurrentStore); - } - - TempData[WellKnownTempData.SuccessMessage] = "Shopify integration successfully updated"; - break; - } case "ShopifyClearCredentials": - { - var blob = CurrentStore.GetStoreBlob(); - blob.SetShopifySettings(null); - if (CurrentStore.SetStoreBlob(blob)) { - await _storeRepository.UpdateStore(CurrentStore); - } + var blob = CurrentStore.GetStoreBlob(); + blob.SetShopifySettings(null); + if (CurrentStore.SetStoreBlob(blob)) + { + await _storeRepository.UpdateStore(CurrentStore); + } - TempData[WellKnownTempData.SuccessMessage] = "Shopify integration credentials cleared"; - break; - } + TempData[WellKnownTempData.SuccessMessage] = "Shopify integration credentials cleared"; + break; + } } - return RedirectToAction(nameof(EditShopifyIntegration), new {storeId = CurrentStore.Id}); + return RedirectToAction(nameof(EditShopifyIntegration), new { storeId = CurrentStore.Id }); } } - + } diff --git a/BTCPayServer/Plugins/Shopify/ShopifyExtensions.cs b/BTCPayServer/Plugins/Shopify/ShopifyExtensions.cs index 0da5b0ddb..b527029ab 100644 --- a/BTCPayServer/Plugins/Shopify/ShopifyExtensions.cs +++ b/BTCPayServer/Plugins/Shopify/ShopifyExtensions.cs @@ -31,11 +31,11 @@ namespace BTCPayServer.Plugins.Shopify { return new Serializer(null).ToObject(rawObj); } - else if( rawS.Type == JTokenType.String) + else if (rawS.Type == JTokenType.String) { return new Serializer(null).ToObject(rawS.Value()); } - + } return null; diff --git a/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs b/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs index 467aef9f4..c5849b285 100644 --- a/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs +++ b/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs @@ -50,14 +50,14 @@ namespace BTCPayServer.Plugins.Shopify var shopifyOrderId = invoice.GetInternalTags(SHOPIFY_ORDER_ID_PREFIX).FirstOrDefault(); if (shopifyOrderId != null) { - if (new[] {InvoiceStatusLegacy.Invalid, InvoiceStatusLegacy.Expired}.Contains(invoice.GetInvoiceState() + if (new[] { InvoiceStatusLegacy.Invalid, InvoiceStatusLegacy.Expired }.Contains(invoice.GetInvoiceState() .Status) && invoice.ExceptionStatus != InvoiceExceptionStatus.None) { //you have failed us, customer await RegisterTransaction(invoice, shopifyOrderId, false); } - else if (new[] {InvoiceStatusLegacy.Complete, InvoiceStatusLegacy.Confirmed}.Contains( + else if (new[] { InvoiceStatusLegacy.Complete, InvoiceStatusLegacy.Confirmed }.Contains( invoice.Status)) { await RegisterTransaction(invoice, shopifyOrderId, true); diff --git a/BTCPayServer/Program.cs b/BTCPayServer/Program.cs index a83ba57f3..9a31eac50 100644 --- a/BTCPayServer/Program.cs +++ b/BTCPayServer/Program.cs @@ -68,7 +68,7 @@ namespace BTCPayServer if (!string.IsNullOrEmpty(ex.Message)) logs.Configuration.LogError(ex.Message); } - catch(Exception e) when( PluginManager.IsExceptionByPlugin(e)) + catch (Exception e) when (PluginManager.IsExceptionByPlugin(e)) { var pluginDir = new DataDirectories().Configure(conf).PluginDir; PluginManager.DisablePlugin(pluginDir, e.Source); diff --git a/BTCPayServer/Security/CookieAuthorizationHandler.cs b/BTCPayServer/Security/CookieAuthorizationHandler.cs index 420ff7dc5..b74709964 100644 --- a/BTCPayServer/Security/CookieAuthorizationHandler.cs +++ b/BTCPayServer/Security/CookieAuthorizationHandler.cs @@ -43,7 +43,7 @@ namespace BTCPayServer.Security { if (context.User.Identity.AuthenticationType != AuthenticationSchemes.Cookie) return; - + var userId = _userManager.GetUserId(context.User); if (string.IsNullOrEmpty(userId)) return; @@ -110,7 +110,7 @@ namespace BTCPayServer.Security } } } - + // Fall back to user prefs cookie if (storeId == null) { @@ -121,7 +121,7 @@ namespace BTCPayServer.Security { store = await _storeRepository.FindStore(storeId, userId); } - + switch (requirement.Policy) { case Policies.CanModifyServerSettings: @@ -158,15 +158,18 @@ namespace BTCPayServer.Security context.Succeed(requirement); if (!explicitResource) { - + if (store != null) { _httpContext.SetStoreData(store); // cache associated entities if present - if (app != null) _httpContext.SetAppData(app); - if (invoice != null) _httpContext.SetInvoiceData(invoice); - if (paymentRequest != null) _httpContext.SetPaymentRequestData(paymentRequest); + if (app != null) + _httpContext.SetAppData(app); + if (invoice != null) + _httpContext.SetInvoiceData(invoice); + if (paymentRequest != null) + _httpContext.SetPaymentRequestData(paymentRequest); } } } diff --git a/BTCPayServer/Security/GreenField/APIKeysAuthenticationHandler.cs b/BTCPayServer/Security/GreenField/APIKeysAuthenticationHandler.cs index d473a8405..14989736b 100644 --- a/BTCPayServer/Security/GreenField/APIKeysAuthenticationHandler.cs +++ b/BTCPayServer/Security/GreenField/APIKeysAuthenticationHandler.cs @@ -45,7 +45,7 @@ namespace BTCPayServer.Security.GreenField } List claims = new List(); claims.Add(new Claim(_identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, key.UserId)); - + claims.AddRange((await _userManager.GetRolesAsync(key.User)).Select(s => new Claim(_identityOptions.CurrentValue.ClaimsIdentity.RoleClaimType, s))); claims.AddRange(Permission.ToPermissions(key.GetBlob().Permissions).Select(permission => new Claim(GreenFieldConstants.ClaimTypes.Permission, permission.ToString()))); diff --git a/BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs b/BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs index 8f6e9f0a4..b3e6ece17 100644 --- a/BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs +++ b/BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs @@ -66,7 +66,7 @@ namespace BTCPayServer.Security.GreenField .Include(applicationUser => applicationUser.Fido2Credentials) .FirstOrDefaultAsync(applicationUser => applicationUser.NormalizedUserName == _userManager.NormalizeName(username)); - + if (user.Fido2Credentials.Any()) { return AuthenticateResult.Fail("Cannot use Basic authentication with multi-factor is enabled."); diff --git a/BTCPayServer/Security/GreenField/GreenFieldAuthorizationHandler.cs b/BTCPayServer/Security/GreenField/GreenFieldAuthorizationHandler.cs index efd724a71..a074953ad 100644 --- a/BTCPayServer/Security/GreenField/GreenFieldAuthorizationHandler.cs +++ b/BTCPayServer/Security/GreenField/GreenFieldAuthorizationHandler.cs @@ -28,7 +28,7 @@ namespace BTCPayServer.Security.GreenField return Task.CompletedTask; } } - + public class GreenFieldAuthorizationHandler : AuthorizationHandler { diff --git a/BTCPayServer/Security/PermissionTagHelper.cs b/BTCPayServer/Security/PermissionTagHelper.cs index 73b81c876..ad7f70e04 100644 --- a/BTCPayServer/Security/PermissionTagHelper.cs +++ b/BTCPayServer/Security/PermissionTagHelper.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Razor.TagHelpers; @@ -31,7 +31,7 @@ namespace BTCPayServer.Security } var key = $"{Permission}_{PermissionResource}"; - if (!_httpContextAccessor.HttpContext.Items.TryGetValue(key,out var cachedResult)) + if (!_httpContextAccessor.HttpContext.Items.TryGetValue(key, out var cachedResult)) { var result = await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, PermissionResource, @@ -45,7 +45,7 @@ namespace BTCPayServer.Security { output.SuppressOutput(); } - + } } } diff --git a/BTCPayServer/Security/SecurityExtensions.cs b/BTCPayServer/Security/SecurityExtensions.cs index 40dc30e3d..a2cd4fd7d 100644 --- a/BTCPayServer/Security/SecurityExtensions.cs +++ b/BTCPayServer/Security/SecurityExtensions.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Security { return scopes.All(s => context.User.HasClaim(c => c.Type.Equals("scope", StringComparison.InvariantCultureIgnoreCase) && c.Value.Split(' ').Contains(s))); } - + public static string GetImplicitStoreId(this HttpContext httpContext) { // 1. Check in the routeData diff --git a/BTCPayServer/Services/Apps/AppService.cs b/BTCPayServer/Services/Apps/AppService.cs index f45e16539..dba256fda 100644 --- a/BTCPayServer/Services/Apps/AppService.cs +++ b/BTCPayServer/Services/Apps/AppService.cs @@ -56,7 +56,7 @@ namespace BTCPayServer.Services.Apps } return null; } - + private async Task GetInfo(AppData appData) { var settings = appData.GetSettings(); @@ -101,14 +101,14 @@ namespace BTCPayServer.Services.Apps .Where(entity => !string.IsNullOrEmpty(entity.Metadata.ItemCode)) .GroupBy(entity => entity.Metadata.ItemCode) .ToDictionary(entities => entities.Key, entities => entities.Count()); - + Dictionary perkValue = new Dictionary(); if (settings.DisplayPerksValue) { perkValue = paidInvoices .Where(entity => entity.Currency.Equals(settings.TargetCurrency, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(entity.Metadata.ItemCode)) .GroupBy(entity => entity.Metadata.ItemCode) - .ToDictionary(entities => entities.Key, entities => + .ToDictionary(entities => entities.Key, entities => entities.Sum(entity => entity.GetPayments(true).Sum(pay => { var paymentMethodId = pay.GetPaymentMethodId(); @@ -202,7 +202,7 @@ namespace BTCPayServer.Services.Apps }); // Old invoices may have invoices which were not tagged - invoices = invoices.Where(inv => appData.TagAllInvoices || inv.Version < InvoiceEntity.InternalTagSupport_Version || + invoices = invoices.Where(inv => appData.TagAllInvoices || inv.Version < InvoiceEntity.InternalTagSupport_Version || inv.InternalTags.Contains(GetAppInternalTag(appData.Id))).ToArray(); return invoices; } @@ -248,16 +248,16 @@ namespace BTCPayServer.Services.Apps Id = app.Id }) .ToArrayAsync(); - + foreach (ListAppsViewModel.ListAppViewModel app in listApps) { app.ViewStyle = await GetAppViewStyleAsync(app.Id, app.AppType); } - + return listApps; } } - + public async Task GetAppViewStyleAsync(string appId, string appType) { AppType appTypeEnum = Enum.Parse(appType); @@ -325,11 +325,11 @@ namespace BTCPayServer.Services.Apps { var itemNode = new YamlMappingNode(); itemNode.Add("title", new YamlScalarNode(item.Title)); - if(item.Price.Type!= ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup) + if (item.Price.Type != ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup) itemNode.Add("price", new YamlScalarNode(item.Price.Value.ToStringInvariant())); if (!string.IsNullOrEmpty(item.Description)) { - itemNode.Add("description", new YamlScalarNode(item.Description) + itemNode.Add("description", new YamlScalarNode(item.Description) { Style = ScalarStyle.DoubleQuoted }); @@ -352,7 +352,7 @@ namespace BTCPayServer.Services.Apps if (item.PaymentMethods?.Any() is true) { - itemNode.Add("payment_methods", new YamlSequenceNode(item.PaymentMethods.Select(s=> new YamlScalarNode(s)))); + itemNode.Add("payment_methods", new YamlSequenceNode(item.PaymentMethods.Select(s => new YamlScalarNode(s)))); } mappingNode.Add(item.Id, itemNode); } @@ -377,7 +377,7 @@ namespace BTCPayServer.Services.Apps ViewPointOfSaleViewModel.Item.ItemPrice price = new ViewPointOfSaleViewModel.Item.ItemPrice(); var pValue = c.GetDetail("price")?.FirstOrDefault(); - switch (c.GetDetailString("custom")??c.GetDetailString("price_type")?.ToLowerInvariant()) + switch (c.GetDetailString("custom") ?? c.GetDetailString("price_type")?.ToLowerInvariant()) { case "topup": case null when pValue is null: @@ -455,7 +455,7 @@ namespace BTCPayServer.Services.Apps if (p.ExceptionStatus == InvoiceExceptionStatus.Marked && p.Status == InvoiceStatusLegacy.Invalid) return new[] { contribution }; - + // Else, we just sum the payments return payments @@ -512,7 +512,7 @@ namespace BTCPayServer.Services.Apps { return null; } - return sequenceNode.Children.Select(node => (node as YamlScalarNode)?.Value).Where(s => s != null).Select(s=> _htmlSanitizer.Sanitize(s)).ToArray(); + return sequenceNode.Children.Select(node => (node as YamlScalarNode)?.Value).Where(s => s != null).Select(s => _htmlSanitizer.Sanitize(s)).ToArray(); } } private class PosScalar diff --git a/BTCPayServer/Services/Apps/CrowdfundSettings.cs b/BTCPayServer/Services/Apps/CrowdfundSettings.cs index ea366f6fb..30aa7f9f3 100644 --- a/BTCPayServer/Services/Apps/CrowdfundSettings.cs +++ b/BTCPayServer/Services/Apps/CrowdfundSettings.cs @@ -32,7 +32,7 @@ namespace BTCPayServer.Services.Apps public bool DisplayPerksRanking { get; set; } public bool DisplayPerksValue { get; set; } public bool SortPerksByPopularity { get; set; } - public string[] AnimationColors { get; set; } = + public string[] AnimationColors { get; set; } = { "#FF6138", "#FFBE53", "#2980B9", "#282741" }; diff --git a/BTCPayServer/Services/Invoices/InvoiceEntity.cs b/BTCPayServer/Services/Invoices/InvoiceEntity.cs index 81594d1d8..3d842ec67 100644 --- a/BTCPayServer/Services/Invoices/InvoiceEntity.cs +++ b/BTCPayServer/Services/Invoices/InvoiceEntity.cs @@ -39,9 +39,9 @@ namespace BTCPayServer.Services.Invoices seria.ContractResolver = new CamelCasePropertyNamesContractResolver(); MetadataSerializer = seria; } - + [JsonIgnore] - public string OrderId + public string OrderId { get => GetMetadata("orderId"); set => SetMetadata("orderId", value); @@ -53,73 +53,86 @@ namespace BTCPayServer.Services.Invoices set => SetMetadata("orderUrl", value); } [JsonIgnore] - public string PaymentRequestId + public string PaymentRequestId { get => GetMetadata("paymentRequestId"); set => SetMetadata("paymentRequestId", value); } [JsonIgnore] - public string BuyerName{ + public string BuyerName + { get => GetMetadata("buyerName"); set => SetMetadata("buyerName", value); } [JsonIgnore] - public string BuyerEmail { + public string BuyerEmail + { get => GetMetadata("buyerEmail"); set => SetMetadata("buyerEmail", value); } [JsonIgnore] - public string BuyerCountry { + public string BuyerCountry + { get => GetMetadata("buyerCountry"); set => SetMetadata("buyerCountry", value); } [JsonIgnore] - public string BuyerZip { + public string BuyerZip + { get => GetMetadata("buyerZip"); set => SetMetadata("buyerZip", value); } [JsonIgnore] - public string BuyerState{ + public string BuyerState + { get => GetMetadata("buyerState"); set => SetMetadata("buyerState", value); } [JsonIgnore] - public string BuyerCity { + public string BuyerCity + { get => GetMetadata("buyerCity"); set => SetMetadata("buyerCity", value); } [JsonIgnore] - public string BuyerAddress2{ + public string BuyerAddress2 + { get => GetMetadata("buyerAddress2"); set => SetMetadata("buyerAddress2", value); } [JsonIgnore] - public string BuyerAddress1 { + public string BuyerAddress1 + { get => GetMetadata("buyerAddress1"); set => SetMetadata("buyerAddress1", value); } [JsonIgnore] - public string BuyerPhone { + public string BuyerPhone + { get => GetMetadata("buyerPhone"); set => SetMetadata("buyerPhone", value); } [JsonIgnore] - public string ItemDesc { + public string ItemDesc + { get => GetMetadata("itemDesc"); set => SetMetadata("itemDesc", value); } [JsonIgnore] - public string ItemCode{ + public string ItemCode + { get => GetMetadata("itemCode"); set => SetMetadata("itemCode", value); } [JsonIgnore] - public bool? Physical { + public bool? Physical + { get => GetMetadata("physical"); set => SetMetadata("physical", value); } [JsonIgnore] - public decimal? TaxIncluded { + public decimal? TaxIncluded + { get => GetMetadata("taxIncluded"); set => SetMetadata("taxIncluded", value); } @@ -134,7 +147,8 @@ namespace BTCPayServer.Services.Invoices public T GetMetadata(string propName) { - if (AdditionalData == null || !(AdditionalData.TryGetValue(propName, out var jt) is true)) return default; + if (AdditionalData == null || !(AdditionalData.TryGetValue(propName, out var jt) is true)) + return default; if (jt.Type == JTokenType.Null) return default; if (typeof(T) == typeof(string)) @@ -178,16 +192,16 @@ namespace BTCPayServer.Services.Invoices data = JToken.FromObject(value); } } - catch (Exception ) + catch (Exception) { data = JToken.FromObject(value); } - + AdditionalData ??= new Dictionary(); AdditionalData.AddOrReplace(propName, data); } } - + public static InvoiceMetadata FromJObject(JObject jObject) { return jObject.ToObject(MetadataSerializer); @@ -1074,7 +1088,7 @@ namespace BTCPayServer.Services.Invoices private decimal GetTxFee() { - return GetPaymentMethodDetails()?.GetNextNetworkFee()?? 0m; + return GetPaymentMethodDetails()?.GetNextNetworkFee() ?? 0m; } } diff --git a/BTCPayServer/Services/Invoices/InvoiceExtensions.cs b/BTCPayServer/Services/Invoices/InvoiceExtensions.cs index 24b798e88..67bbb2667 100644 --- a/BTCPayServer/Services/Invoices/InvoiceExtensions.cs +++ b/BTCPayServer/Services/Invoices/InvoiceExtensions.cs @@ -13,7 +13,7 @@ namespace BTCPayServer.Services.Invoices public static async Task ActivateInvoicePaymentMethod(this InvoiceRepository invoiceRepository, EventAggregator eventAggregator, BTCPayNetworkProvider btcPayNetworkProvider, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary, - StoreData store,InvoiceEntity invoice, PaymentMethodId paymentMethodId) + StoreData store, InvoiceEntity invoice, PaymentMethodId paymentMethodId) { if (invoice.GetInvoiceState().Status != InvoiceStatusLegacy.New) return false; diff --git a/BTCPayServer/Services/Invoices/InvoiceRepository.cs b/BTCPayServer/Services/Invoices/InvoiceRepository.cs index 846f2f65a..f546277fa 100644 --- a/BTCPayServer/Services/Invoices/InvoiceRepository.cs +++ b/BTCPayServer/Services/Invoices/InvoiceRepository.cs @@ -328,10 +328,10 @@ namespace BTCPayServer.Services.Invoices if (existing.GetPaymentMethodDetails().GetPaymentDestination() != newDetails.GetPaymentDestination() && newDetails.Activated) { await context.AddressInvoices.AddAsync(new AddressInvoiceData() - { - InvoiceDataId = invoiceId, - CreatedTime = DateTimeOffset.UtcNow - } + { + InvoiceDataId = invoiceId, + CreatedTime = DateTimeOffset.UtcNow + } .Set(GetDestination(paymentMethod), paymentMethod.GetId())); await context.HistoricalAddressInvoices.AddAsync(new HistoricalAddressInvoiceData() { @@ -343,7 +343,7 @@ namespace BTCPayServer.Services.Invoices invoice.Blob = ToBytes(invoiceEntity, network); AddToTextSearch(context, invoice, paymentMethod.GetPaymentMethodDetails().GetPaymentDestination()); await context.SaveChangesAsync(); - + } } @@ -545,7 +545,7 @@ namespace BTCPayServer.Services.Invoices { var res = await GetInvoiceRaw(id, context, includeAddressData); return res == null ? null : ToEntity(res); - } + } } public async Task GetInvoices(string[] invoiceIds) { diff --git a/BTCPayServer/Services/Invoices/PaymentService.cs b/BTCPayServer/Services/Invoices/PaymentService.cs index 027cb1c0d..b4aeaec04 100644 --- a/BTCPayServer/Services/Invoices/PaymentService.cs +++ b/BTCPayServer/Services/Invoices/PaymentService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -106,18 +106,18 @@ namespace BTCPayServer.Services.Invoices .Include(data => data.InvoiceData) .Where(data => paymentIds.Contains(data.Id)).ToDictionaryAsync(data => data.Id); var eventsToSend = new List(); - foreach (KeyValuePair payment in paymentsDict) + foreach (KeyValuePair payment in paymentsDict) { var dbPayment = dbPayments[payment.Key]; var invBlob = dbPayment.InvoiceData.GetBlob(_btcPayNetworkProvider); var dbPaymentEntity = dbPayment.GetBlob(_btcPayNetworkProvider); var wasConfirmed = dbPayment.GetBlob(_btcPayNetworkProvider).GetCryptoPaymentData() .PaymentConfirmed(dbPaymentEntity, invBlob.SpeedPolicy); - if (!wasConfirmed && payment.Value.Item2.PaymentConfirmed(payment.Value.entity, invBlob.SpeedPolicy)) + if (!wasConfirmed && payment.Value.Item2.PaymentConfirmed(payment.Value.entity, invBlob.SpeedPolicy)) { eventsToSend.Add(new InvoiceEvent(invBlob, InvoiceEvent.PaymentSettled) { Payment = payment.Value.entity }); } - + dbPayment.Accounted = payment.Value.entity.Accounted; dbPayment.Blob = InvoiceRepository.ToBytes(payment.Value.entity, payment.Value.entity.Network); } diff --git a/BTCPayServer/Services/Labels/Label.cs b/BTCPayServer/Services/Labels/Label.cs index a6765d9a6..216e3c6c2 100644 --- a/BTCPayServer/Services/Labels/Label.cs +++ b/BTCPayServer/Services/Labels/Label.cs @@ -5,8 +5,8 @@ using Newtonsoft.Json.Linq; namespace BTCPayServer.Services.Labels { - - public abstract class Label: LabelData + + public abstract class Label : LabelData { static void FixLegacy(JObject jObj, ReferenceLabel refLabel) { diff --git a/BTCPayServer/Services/LanguageService.cs b/BTCPayServer/Services/LanguageService.cs index 06f8ffc35..d0ab87018 100644 --- a/BTCPayServer/Services/LanguageService.cs +++ b/BTCPayServer/Services/LanguageService.cs @@ -54,13 +54,13 @@ namespace BTCPayServer.Services public IEnumerable GetLanguageSelectListItems() { - IEnumerable items = GetLanguages().Select(l => new SelectListItem - { - Value = l.Code, - Text = l.DisplayName, - Disabled = false - }).OrderBy(lang => lang.Text); - + IEnumerable items = GetLanguages().Select(l => new SelectListItem + { + Value = l.Code, + Text = l.DisplayName, + Disabled = false + }).OrderBy(lang => lang.Text); + return items; } diff --git a/BTCPayServer/Services/Mails/EmailSettings.cs b/BTCPayServer/Services/Mails/EmailSettings.cs index 8c551f65e..b7e211d6d 100644 --- a/BTCPayServer/Services/Mails/EmailSettings.cs +++ b/BTCPayServer/Services/Mails/EmailSettings.cs @@ -1,12 +1,12 @@ using System.ComponentModel.DataAnnotations; using System.Net; -using Newtonsoft.Json; -using MailKit.Net.Smtp; -using MimeKit; -using System.Threading.Tasks; -using System.Threading; using System.Net.Security; using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using MailKit.Net.Smtp; +using MimeKit; +using Newtonsoft.Json; namespace BTCPayServer.Services.Mails { @@ -67,7 +67,7 @@ namespace BTCPayServer.Services.Mails } return new MimeMessage( - from : new[] { new MailboxAddress(From, !string.IsNullOrWhiteSpace(FromDisplay) ? From : FromDisplay) }, + from: new[] { new MailboxAddress(From, !string.IsNullOrWhiteSpace(FromDisplay) ? From : FromDisplay) }, to: new[] { to }, subject, bodyBuilder.ToMessageBody()); diff --git a/BTCPayServer/Services/Mails/StoreEmailSender.cs b/BTCPayServer/Services/Mails/StoreEmailSender.cs index 3e2a87b18..df06f6351 100644 --- a/BTCPayServer/Services/Mails/StoreEmailSender.cs +++ b/BTCPayServer/Services/Mails/StoreEmailSender.cs @@ -32,7 +32,8 @@ namespace BTCPayServer.Services.Mails return emailSettings; } - if (FallbackSender != null) return await FallbackSender?.GetEmailSettings(); + if (FallbackSender != null) + return await FallbackSender?.GetEmailSettings(); return null; } } diff --git a/BTCPayServer/Services/MigrationSettings.cs b/BTCPayServer/Services/MigrationSettings.cs index 38b7b2ecb..fdfbb88de 100644 --- a/BTCPayServer/Services/MigrationSettings.cs +++ b/BTCPayServer/Services/MigrationSettings.cs @@ -6,7 +6,7 @@ namespace BTCPayServer.Services { [JsonProperty("MigrateHotwalletProperty2")] public bool MigrateHotwalletProperty { get; set; } - public bool MigrateU2FToFIDO2{ get; set; } + public bool MigrateU2FToFIDO2 { get; set; } public bool UnreachableStoreCheck { get; set; } public bool DeprecatedLightningConnectionStringCheck { get; set; } public bool ConvertMultiplierToSpread { get; set; } @@ -22,7 +22,7 @@ namespace BTCPayServer.Services { return string.Empty; } - + // Done in DbMigrationsHostedService public int? MigratedInvoiceTextSearchPages { get; set; } public bool MigrateAppCustomOption { get; set; } diff --git a/BTCPayServer/Services/NBXSyncSummaryProvider.cs b/BTCPayServer/Services/NBXSyncSummaryProvider.cs index c54246f46..e40da41e6 100644 --- a/BTCPayServer/Services/NBXSyncSummaryProvider.cs +++ b/BTCPayServer/Services/NBXSyncSummaryProvider.cs @@ -40,12 +40,12 @@ namespace BTCPayServer.Services Available = summary.Status.IsFullySynched }); } - - public class ServerInfoSyncStatusData2: ServerInfoSyncStatusData, ISyncStatus + + public class ServerInfoSyncStatusData2 : ServerInfoSyncStatusData, ISyncStatus { - + } } - - + + } diff --git a/BTCPayServer/Services/Notifications/Blobs/ExternalPayoutTransactionNotification.cs b/BTCPayServer/Services/Notifications/Blobs/ExternalPayoutTransactionNotification.cs index 0e529e4b4..b59a452d9 100644 --- a/BTCPayServer/Services/Notifications/Blobs/ExternalPayoutTransactionNotification.cs +++ b/BTCPayServer/Services/Notifications/Blobs/ExternalPayoutTransactionNotification.cs @@ -28,7 +28,7 @@ namespace BTCPayServer.Services.Notifications.Blobs { get { - return new (string identifier, string name)[] {(TYPE, "External payout approval")}; + return new (string identifier, string name)[] { (TYPE, "External payout approval") }; } } diff --git a/BTCPayServer/Services/Notifications/Blobs/InvoiceEventNotification.cs b/BTCPayServer/Services/Notifications/Blobs/InvoiceEventNotification.cs index d1aea73c2..f97cf0ba5 100644 --- a/BTCPayServer/Services/Notifications/Blobs/InvoiceEventNotification.cs +++ b/BTCPayServer/Services/Notifications/Blobs/InvoiceEventNotification.cs @@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Routing; namespace BTCPayServer.Services.Notifications.Blobs { - internal class InvoiceEventNotification:BaseNotification + internal class InvoiceEventNotification : BaseNotification { private const string TYPE = "invoicestate"; internal class Handler : NotificationHandler @@ -29,7 +29,7 @@ namespace BTCPayServer.Services.Notifications.Blobs { get { - return new (string identifier, string name)[] {(TYPE, "All invoice updates"),} + return new (string identifier, string name)[] { (TYPE, "All invoice updates"), } .Concat(TextMapping.Select(pair => ($"{TYPE}_{pair.Key}", $"Invoice {pair.Value}"))).ToArray(); } } diff --git a/BTCPayServer/Services/Notifications/Blobs/JunkNotification.cs b/BTCPayServer/Services/Notifications/Blobs/JunkNotification.cs index 859cf6d48..3dc894f23 100644 --- a/BTCPayServer/Services/Notifications/Blobs/JunkNotification.cs +++ b/BTCPayServer/Services/Notifications/Blobs/JunkNotification.cs @@ -4,7 +4,7 @@ using BTCPayServer.Abstractions.Contracts; namespace BTCPayServer.Services.Notifications.Blobs { - internal class JunkNotification: BaseNotification + internal class JunkNotification : BaseNotification { private const string TYPE = "junk"; internal class Handler : NotificationHandler @@ -14,7 +14,7 @@ namespace BTCPayServer.Services.Notifications.Blobs { get { - return new (string identifier, string name)[] {(TYPE, "Junk")}; + return new (string identifier, string name)[] { (TYPE, "Junk") }; } } diff --git a/BTCPayServer/Services/Notifications/Blobs/NewVersionNotification.cs b/BTCPayServer/Services/Notifications/Blobs/NewVersionNotification.cs index 1dced7dcc..c6e15539d 100644 --- a/BTCPayServer/Services/Notifications/Blobs/NewVersionNotification.cs +++ b/BTCPayServer/Services/Notifications/Blobs/NewVersionNotification.cs @@ -3,7 +3,7 @@ using BTCPayServer.Models.NotificationViewModels; namespace BTCPayServer.Services.Notifications.Blobs { - internal class NewVersionNotification:BaseNotification + internal class NewVersionNotification : BaseNotification { private const string TYPE = "newversion"; internal class Handler : NotificationHandler @@ -13,7 +13,7 @@ namespace BTCPayServer.Services.Notifications.Blobs { get { - return new (string identifier, string name)[] {(TYPE, "New version")}; + return new (string identifier, string name)[] { (TYPE, "New version") }; } } @@ -32,7 +32,7 @@ namespace BTCPayServer.Services.Notifications.Blobs Version = version; } public string Version { get; set; } - public override string Identifier => TYPE; + public override string Identifier => TYPE; public override string NotificationType => TYPE; } } diff --git a/BTCPayServer/Services/Notifications/Blobs/PayoutNotification.cs b/BTCPayServer/Services/Notifications/Blobs/PayoutNotification.cs index eee394185..33c92d0ca 100644 --- a/BTCPayServer/Services/Notifications/Blobs/PayoutNotification.cs +++ b/BTCPayServer/Services/Notifications/Blobs/PayoutNotification.cs @@ -26,7 +26,7 @@ namespace BTCPayServer.Services.Notifications.Blobs { get { - return new (string identifier, string name)[] {(TYPE, "Payouts")}; + return new (string identifier, string name)[] { (TYPE, "Payouts") }; } } @@ -35,7 +35,7 @@ namespace BTCPayServer.Services.Notifications.Blobs vm.Body = "A new payout is awaiting for approval"; vm.ActionLink = _linkGenerator.GetPathByAction(nameof(StorePullPaymentsController.Payouts), "StorePullPayments", - new {storeId = notification.StoreId, paymentMethodId = notification.PaymentMethod }, _options.RootPath); + new { storeId = notification.StoreId, paymentMethodId = notification.PaymentMethod }, _options.RootPath); } } diff --git a/BTCPayServer/Services/Notifications/NotificationManager.cs b/BTCPayServer/Services/Notifications/NotificationManager.cs index 309a13464..39050e9ee 100644 --- a/BTCPayServer/Services/Notifications/NotificationManager.cs +++ b/BTCPayServer/Services/Notifications/NotificationManager.cs @@ -42,21 +42,24 @@ namespace BTCPayServer.Services.Notifications { var resp = await GetNotifications(new NotificationsQuery() { - Seen = false, Skip = 0, Take = 5, UserId = userId + Seen = false, + Skip = 0, + Take = 5, + UserId = userId }); entry.SetAbsoluteExpiration(TimeSpan.FromMilliseconds(_cacheExpiryMs)); - var res = new NotificationSummaryViewModel() {Last5 = resp.Items, UnseenCount = resp.Count}; + var res = new NotificationSummaryViewModel() { Last5 = resp.Items, UnseenCount = resp.Count }; entry.Value = res; return res; }); } - + public void InvalidateNotificationCache(params string[] userIds) { foreach (var userId in userIds) { _memoryCache.Remove(GetNotificationsCacheId(userId)); - _eventAggregator.Publish(new UserNotificationsUpdatedEvent() {UserId = userId}); + _eventAggregator.Publish(new UserNotificationsUpdatedEvent() { UserId = userId }); } } @@ -75,7 +78,7 @@ namespace BTCPayServer.Services.Notifications Count: await queryables.withoutPaging.CountAsync()); } - private ( IQueryable withoutPaging, IQueryable withPaging) + private (IQueryable withoutPaging, IQueryable withPaging) GetNotificationsQueryable(ApplicationDbContext dbContext, NotificationsQuery query) { var queryable = dbContext.Notifications.AsQueryable(); @@ -147,7 +150,7 @@ namespace BTCPayServer.Services.Notifications if (handler is null) return null; var notification = JsonConvert.DeserializeObject(ZipUtils.Unzip(data.Blob), handler.NotificationBlobType); - var obj = new NotificationViewModel {Id = data.Id, Created = data.Created, Seen = data.Seen}; + var obj = new NotificationViewModel { Id = data.Id, Created = data.Created, Seen = data.Seen }; handler.FillViewModel(notification, obj); return obj; } diff --git a/BTCPayServer/Services/Notifications/NotificationSender.cs b/BTCPayServer/Services/Notifications/NotificationSender.cs index 9aa476b5b..98f492f2b 100644 --- a/BTCPayServer/Services/Notifications/NotificationSender.cs +++ b/BTCPayServer/Services/Notifications/NotificationSender.cs @@ -74,11 +74,11 @@ namespace BTCPayServer.Services.Notifications switch (scope) { case AdminScope _: - { - query = _userManager.GetUsersInRoleAsync(Roles.ServerAdmin).Result.AsQueryable(); + { + query = _userManager.GetUsersInRoleAsync(Roles.ServerAdmin).Result.AsQueryable(); - break; - } + break; + } case StoreScope s: query = ctx.UserStore .Include(store => store.ApplicationUser) @@ -87,12 +87,12 @@ namespace BTCPayServer.Services.Notifications break; case UserScope userScope: query = ctx.Users - .Where(user => user.Id == userScope.UserId); + .Where(user => user.Id == userScope.UserId); break; default: throw new NotSupportedException("Notification scope not supported"); - - + + } query = query.Where(store => store.DisabledNotifications != "all"); foreach (string term in terms) @@ -100,7 +100,7 @@ namespace BTCPayServer.Services.Notifications // Cannot specify StringComparison as EF core does not support it and would attempt client-side evaluation // ReSharper disable once CA1307 #pragma warning disable CA1307 // Specify StringComparison - query = query.Where(user => user.DisabledNotifications == null || !user.DisabledNotifications.Contains(term)); + query = query.Where(user => user.DisabledNotifications == null || !user.DisabledNotifications.Contains(term)); #pragma warning restore CA1307 // Specify StringComparison } diff --git a/BTCPayServer/Services/PoliciesSettings.cs b/BTCPayServer/Services/PoliciesSettings.cs index 4cac58b4d..be90bb253 100644 --- a/BTCPayServer/Services/PoliciesSettings.cs +++ b/BTCPayServer/Services/PoliciesSettings.cs @@ -25,7 +25,7 @@ namespace BTCPayServer.Services [Display(Name = "Allow non-admins to import hot wallets for their stores")] public bool AllowHotWalletRPCImportForAll { get; set; } [Display(Name = "Check releases on GitHub and notify when new BTCPay Server version is available")] - public bool CheckForNewVersions { get; set; } + public bool CheckForNewVersions { get; set; } [Display(Name = "Disable notifications from automatically showing (no websockets)")] public bool DisableInstantNotifications { get; set; } [Display(Name = "Disable stores from using the server's email settings as backup")] @@ -39,10 +39,10 @@ namespace BTCPayServer.Services public string RootAppId { get; set; } public AppType? RootAppType { get; set; } - + [Display(Name = "Override the block explorers used")] public List BlockExplorerLinks { get; set; } = new List(); - + public List DomainToAppMapping { get; set; } = new List(); public class BlockExplorerOverrideItem @@ -50,7 +50,7 @@ namespace BTCPayServer.Services public string CryptoCode { get; set; } public string Link { get; set; } } - + public class DomainToAppMappingItem { [Display(Name = "Domain")] [Required] [HostName] public string Domain { get; set; } diff --git a/BTCPayServer/Services/SettingsRepository.cs b/BTCPayServer/Services/SettingsRepository.cs index 5c689040c..4918f44b7 100644 --- a/BTCPayServer/Services/SettingsRepository.cs +++ b/BTCPayServer/Services/SettingsRepository.cs @@ -49,7 +49,7 @@ namespace BTCPayServer.Services await ctx.SaveChangesAsync(); } } - _memoryCache.Set(GetCacheKey(name),obj); + _memoryCache.Set(GetCacheKey(name), obj); _EventAggregator.Publish(new SettingsChanged() { Settings = obj @@ -60,7 +60,7 @@ namespace BTCPayServer.Services { name ??= obj.GetType().FullName ?? string.Empty; _memoryCache.Remove(GetCacheKey(name)); - var settings = new SettingData {Id = name, Value = Serialize(obj)}; + var settings = new SettingData { Id = name, Value = Serialize(obj) }; ctx.Attach(settings); ctx.Entry(settings).State = EntityState.Modified; return settings; diff --git a/BTCPayServer/Services/Stores/StoreRepository.cs b/BTCPayServer/Services/Stores/StoreRepository.cs index dfbf081f7..da06544d5 100644 --- a/BTCPayServer/Services/Stores/StoreRepository.cs +++ b/BTCPayServer/Services/Stores/StoreRepository.cs @@ -164,7 +164,7 @@ namespace BTCPayServer.Services.Stores } } - private void SetNewStoreHints(ref StoreData storeData) + private void SetNewStoreHints(ref StoreData storeData) { var blob = storeData.GetStoreBlob(); blob.Hints = new Data.StoreBlob.StoreHints @@ -191,14 +191,14 @@ namespace BTCPayServer.Services.Stores ApplicationUserId = ownerId, Role = StoreRoles.Owner, }; - + SetNewStoreHints(ref storeData); ctx.Add(storeData); ctx.Add(userStore); await ctx.SaveChangesAsync(); } - } + } public async Task CreateStore(string ownerId, string name) { diff --git a/BTCPayServer/Services/ThemesSettings.cs b/BTCPayServer/Services/ThemesSettings.cs index d87467823..2c0fbd0af 100644 --- a/BTCPayServer/Services/ThemesSettings.cs +++ b/BTCPayServer/Services/ThemesSettings.cs @@ -7,7 +7,7 @@ namespace BTCPayServer.Services { [Display(Name = "Use custom theme")] public bool CustomTheme { get; set; } - + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] [MaxLength(500)] [Display(Name = "Custom Theme CSS URL")] diff --git a/BTCPayServer/Services/TorServices.cs b/BTCPayServer/Services/TorServices.cs index 18835a393..ab8218c3a 100644 --- a/BTCPayServer/Services/TorServices.cs +++ b/BTCPayServer/Services/TorServices.cs @@ -87,7 +87,7 @@ namespace BTCPayServer.Services private TorService ParseService(string serviceName, string onionHost, int virtualPort) { - var torService = new TorService() {Name = serviceName, OnionHost = onionHost, VirtualPort = virtualPort}; + var torService = new TorService() { Name = serviceName, OnionHost = onionHost, VirtualPort = virtualPort }; if (Enum.TryParse(serviceName, true, out var serviceType)) torService.ServiceType = serviceType; @@ -127,7 +127,7 @@ namespace BTCPayServer.Services { LoadFromConfig(); } - else if(!string.IsNullOrEmpty(_options.Value.TorrcFile)) + else if (!string.IsNullOrEmpty(_options.Value.TorrcFile)) { await Refresh(); await base.StartAsync(cancellationToken); @@ -136,7 +136,7 @@ namespace BTCPayServer.Services internal override Task[] InitializeTasks() { - return new[] {CreateLoopTask(Refresh)}; + return new[] { CreateLoopTask(Refresh) }; } private void LoadFromConfig() diff --git a/BTCPayServer/Services/UserService.cs b/BTCPayServer/Services/UserService.cs index a359a8df3..4ac129c6e 100644 --- a/BTCPayServer/Services/UserService.cs +++ b/BTCPayServer/Services/UserService.cs @@ -3,11 +3,11 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using BTCPayServer.Data; +using BTCPayServer.Services.Stores; +using BTCPayServer.Storage.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; -using BTCPayServer.Data; -using BTCPayServer.Storage.Services; -using BTCPayServer.Services.Stores; namespace BTCPayServer.Services { @@ -33,18 +33,18 @@ namespace BTCPayServer.Services _fileService = fileService; _storeRepository = storeRepository; } - - public async Task IsAdminUser(string userId) + + public async Task IsAdminUser(string userId) { - return IsRoleAdmin(await _userManager.GetRolesAsync(new ApplicationUser(){Id = userId})); + return IsRoleAdmin(await _userManager.GetRolesAsync(new ApplicationUser() { Id = userId })); } - public async Task IsAdminUser(ApplicationUser user) + public async Task IsAdminUser(ApplicationUser user) { return IsRoleAdmin(await _userManager.GetRolesAsync(user)); } - public async Task DeleteUserAndAssociatedData(ApplicationUser user) + public async Task DeleteUserAndAssociatedData(ApplicationUser user) { var userId = user.Id; var files = await _storedFileRepository.GetFiles(new StoredFileRepository.FilesQuery() diff --git a/BTCPayServer/Services/Wallets/BTCPayWallet.cs b/BTCPayServer/Services/Wallets/BTCPayWallet.cs index e94a5e3da..14c797371 100644 --- a/BTCPayServer/Services/Wallets/BTCPayWallet.cs +++ b/BTCPayServer/Services/Wallets/BTCPayWallet.cs @@ -229,7 +229,7 @@ namespace BTCPayServer.Services.Wallets public async Task FetchTransaction(DerivationStrategyBase derivationStrategyBase, uint256 transactionId) { var tx = await _Client.GetTransactionAsync(derivationStrategyBase, transactionId); - if (tx is null || !_Network.FilterValidTransactions(new List() {tx}).Any()) + if (tx is null || !_Network.FilterValidTransactions(new List() { tx }).Any()) { return null; } diff --git a/BTCPayServer/Services/Wallets/WalletReceiveService.cs b/BTCPayServer/Services/Wallets/WalletReceiveService.cs index cd8ebc966..b184aefd5 100644 --- a/BTCPayServer/Services/Wallets/WalletReceiveService.cs +++ b/BTCPayServer/Services/Wallets/WalletReceiveService.cs @@ -51,7 +51,7 @@ namespace BTCPayServer.Services.Wallets return null; } - await explorerClient.CancelReservationAsync(kpi.DerivationStrategy, new[] {kpi.KeyPath}); + await explorerClient.CancelReservationAsync(kpi.DerivationStrategy, new[] { kpi.KeyPath }); Remove(walletId); return kpi.Address.ToString(); } @@ -130,14 +130,14 @@ namespace BTCPayServer.Services.Wallets return Task.CompletedTask; } - public Tuple GetByScriptPubKey(string cryptoCode,Script script) + public Tuple GetByScriptPubKey(string cryptoCode, Script script) { - var match = _walletReceiveState.Where(pair => - pair.Key.CryptoCode.Equals(cryptoCode, StringComparison.InvariantCulture) && - pair.Value.ScriptPubKey == script); + var match = _walletReceiveState.Where(pair => + pair.Key.CryptoCode.Equals(cryptoCode, StringComparison.InvariantCulture) && + pair.Value.ScriptPubKey == script); if (match.Any()) { - var f =match.First(); + var f = match.First(); return new Tuple(f.Key, f.Value); }