Run dotnet format (#3244)

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

View File

@@ -2,11 +2,11 @@ namespace BTCPayServer.Configuration
{ {
public class DataDirectories public class DataDirectories
{ {
public string DataDir { get; set; } public string DataDir { get; set; }
public string PluginDir { get; set; } public string PluginDir { get; set; }
public string TempStorageDir { get; set; } public string TempStorageDir { get; set; }
public string StorageDir { get; set; } public string StorageDir { get; set; }
} }
} }

View File

@@ -9,7 +9,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Operations;
namespace BTCPayServer.Abstractions.Contracts namespace BTCPayServer.Abstractions.Contracts
{ {
public abstract class BaseDbContextFactory<T> where T: DbContext public abstract class BaseDbContextFactory<T> where T : DbContext
{ {
private readonly IOptions<DatabaseOptions> _options; private readonly IOptions<DatabaseOptions> _options;
private readonly string _schemaPrefix; private readonly string _schemaPrefix;
@@ -95,7 +95,7 @@ namespace BTCPayServer.Abstractions.Contracts
builder.UseMySql(_options.Value.ConnectionString, ServerVersion.AutoDetect(_options.Value.ConnectionString), o => builder.UseMySql(_options.Value.ConnectionString, ServerVersion.AutoDetect(_options.Value.ConnectionString), o =>
{ {
o.EnableRetryOnFailure(10); o.EnableRetryOnFailure(10);
if (!string.IsNullOrEmpty(_schemaPrefix)) if (!string.IsNullOrEmpty(_schemaPrefix))
{ {
o.MigrationsHistoryTable(_schemaPrefix); o.MigrationsHistoryTable(_schemaPrefix);
@@ -106,6 +106,6 @@ namespace BTCPayServer.Abstractions.Contracts
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
} }
} }
} }
} }

View File

@@ -28,5 +28,5 @@ namespace BTCPayServer.Abstractions.Contracts
} }
} }
} }
} }

View File

@@ -7,7 +7,7 @@ namespace BTCPayServer.Abstractions.Contracts
public abstract string Identifier { get; } public abstract string Identifier { get; }
public abstract string NotificationType { get; } public abstract string NotificationType { get; }
} }
public interface INotificationHandler public interface INotificationHandler
{ {
string NotificationType { get; } string NotificationType { get; }
@@ -15,7 +15,7 @@ namespace BTCPayServer.Abstractions.Contracts
public (string identifier, string name)[] Meta { get; } public (string identifier, string name)[] Meta { get; }
void FillViewModel(object notification, NotificationViewModel vm); void FillViewModel(object notification, NotificationViewModel vm);
} }
public class NotificationViewModel public class NotificationViewModel
{ {
public string Id { get; set; } public string Id { get; set; }

View File

@@ -5,7 +5,7 @@ namespace BTCPayServer.Abstractions.Contracts
public interface IPluginHookFilter public interface IPluginHookFilter
{ {
public string Hook { get; } public string Hook { get; }
Task<object> Execute(object args); Task<object> Execute(object args);
} }
} }

View File

@@ -3,7 +3,7 @@ namespace BTCPayServer.Abstractions.Contracts
public interface IUIExtension public interface IUIExtension
{ {
string Partial { get; } string Partial { get; }
string Location { get; } string Location { get; }
} }
} }

View File

@@ -14,9 +14,9 @@ namespace BTCPayServer.Abstractions.Extensions
public static void SetActivePage<T>(this ViewDataDictionary viewData, T activePage, string title = null, string activeId = null) public static void SetActivePage<T>(this ViewDataDictionary viewData, T activePage, string title = null, string activeId = null)
where T : IConvertible 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) public static void SetActivePage(this ViewDataDictionary viewData, string activePage, string category, string title = null, string activeId = null)
{ {
// Page Title // Page Title
@@ -57,9 +57,9 @@ namespace BTCPayServer.Abstractions.Extensions
public static string IsActivePage<T>(this ViewDataDictionary viewData, T page, object id = null) public static string IsActivePage<T>(this ViewDataDictionary viewData, T page, object id = null)
where T : IConvertible 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)) if (!viewData.ContainsKey(ACTIVE_PAGE_KEY))
{ {
@@ -68,7 +68,7 @@ namespace BTCPayServer.Abstractions.Extensions
var activeId = viewData[ACTIVE_ID_KEY]; var activeId = viewData[ACTIVE_ID_KEY];
var activePage = viewData[ACTIVE_PAGE_KEY]?.ToString(); var activePage = viewData[ACTIVE_PAGE_KEY]?.ToString();
var activeCategory = viewData[ACTIVE_CATEGORY_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); var idMatch = id == null || activeId == null || id.Equals(activeId);
return categoryAndPageMatch && idMatch ? "active" : null; return categoryAndPageMatch && idMatch ? "active" : null;
} }
@@ -84,11 +84,11 @@ namespace BTCPayServer.Abstractions.Extensions
var displayDate = date.ToString("o", CultureInfo.InvariantCulture); var displayDate = date.ToString("o", CultureInfo.InvariantCulture);
return new HtmlString($"<span class='localizeDate'>{displayDate}</span>"); return new HtmlString($"<span class='localizeDate'>{displayDate}</span>");
} }
public static string ToTimeAgo(this DateTimeOffset date) public static string ToTimeAgo(this DateTimeOffset date)
{ {
var diff = DateTimeOffset.UtcNow - date; var diff = DateTimeOffset.UtcNow - date;
var formatted = diff.Seconds > 0 var formatted = diff.Seconds > 0
? $"{diff.TimeString()} ago" ? $"{diff.TimeString()} ago"
: $"in {diff.Negate().TimeString()}"; : $"in {diff.Negate().TimeString()}";
return formatted; return formatted;

View File

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

View File

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

View File

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

View File

@@ -35,16 +35,18 @@ namespace BTCPayServer.Client
if (textSearch != null) if (textSearch != null)
queryPayload.Add(nameof(textSearch), textSearch); queryPayload.Add(nameof(textSearch), textSearch);
if (status != null) 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); queryPayload.Add(nameof(skip), skip);
} }
if(take != null) { if (take != null)
{
queryPayload.Add(nameof(take), take); queryPayload.Add(nameof(take), take);
} }
var response = var response =
await _httpClient.SendAsync( await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/invoices", CreateHttpRequest($"api/v1/stores/{storeId}/invoices",
@@ -114,7 +116,7 @@ namespace BTCPayServer.Client
public virtual async Task<InvoiceData> UnarchiveInvoice(string storeId, string invoiceId, CancellationToken token = default) public virtual async Task<InvoiceData> UnarchiveInvoice(string storeId, string invoiceId, CancellationToken token = default)
{ {
var response = await _httpClient.SendAsync( 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); method: HttpMethod.Post), token);
return await HandleResponse<InvoiceData>(response); return await HandleResponse<InvoiceData>(response);
} }
@@ -122,7 +124,7 @@ namespace BTCPayServer.Client
public virtual async Task ActivateInvoicePaymentMethod(string storeId, string invoiceId, string paymentMethod, CancellationToken token = default) public virtual async Task ActivateInvoicePaymentMethod(string storeId, string invoiceId, string paymentMethod, CancellationToken token = default)
{ {
var response = await _httpClient.SendAsync( 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); method: HttpMethod.Post), token);
await HandleResponse(response); await HandleResponse(response);
} }

View File

@@ -9,11 +9,11 @@ namespace BTCPayServer.Client
{ {
public partial class BTCPayServerClient public partial class BTCPayServerClient
{ {
public virtual async Task<IEnumerable<NotificationData>> GetNotifications(bool? seen = null, int? skip = null, public virtual async Task<IEnumerable<NotificationData>> GetNotifications(bool? seen = null, int? skip = null,
int? take = null, CancellationToken token = default) int? take = null, CancellationToken token = default)
{ {
Dictionary<string, object> queryPayload = new Dictionary<string, object>(); Dictionary<string, object> queryPayload = new Dictionary<string, object>();
if (seen != null) if (seen != null)
queryPayload.Add(nameof(seen), seen); queryPayload.Add(nameof(seen), seen);
if (skip != null) if (skip != null)
@@ -41,7 +41,7 @@ namespace BTCPayServer.Client
{ {
var response = await _httpClient.SendAsync( var response = await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/users/me/notifications/{notificationId}", CreateHttpRequest($"api/v1/users/me/notifications/{notificationId}",
method: HttpMethod.Put, bodyPayload: new UpdateNotification() {Seen = seen}), token); method: HttpMethod.Put, bodyPayload: new UpdateNotification() { Seen = seen }), token);
return await HandleResponse<NotificationData>(response); return await HandleResponse<NotificationData>(response);
} }

View File

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

View File

@@ -25,14 +25,14 @@ namespace BTCPayServer.Client
Dictionary<string, object> queryParams = new Dictionary<string, object>(); Dictionary<string, object> queryParams = new Dictionary<string, object>();
if (blockTarget != null) if (blockTarget != null)
{ {
queryParams.Add("blockTarget",blockTarget); queryParams.Add("blockTarget", blockTarget);
} }
var response = var response =
await _httpClient.SendAsync( await _httpClient.SendAsync(
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/feeRate", queryParams), token); CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/feeRate", queryParams), token);
return await HandleResponse<OnChainWalletFeeRateData>(response); return await HandleResponse<OnChainWalletFeeRateData>(response);
} }
public virtual async Task<OnChainWalletAddressData> GetOnChainWalletReceiveAddress(string storeId, string cryptoCode, bool forceGenerate = false, public virtual async Task<OnChainWalletAddressData> GetOnChainWalletReceiveAddress(string storeId, string cryptoCode, bool forceGenerate = false,
CancellationToken token = default) CancellationToken token = default)
{ {
@@ -44,16 +44,16 @@ namespace BTCPayServer.Client
}), token); }), token);
return await HandleResponse<OnChainWalletAddressData>(response); return await HandleResponse<OnChainWalletAddressData>(response);
} }
public virtual async Task UnReserveOnChainWalletReceiveAddress(string storeId, string cryptoCode, public virtual async Task UnReserveOnChainWalletReceiveAddress(string storeId, string cryptoCode,
CancellationToken token = default) CancellationToken token = default)
{ {
var response = var response =
await _httpClient.SendAsync( 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); await HandleResponse(response);
} }
public virtual async Task<IEnumerable<OnChainWalletTransactionData>> ShowOnChainWalletTransactions( public virtual async Task<IEnumerable<OnChainWalletTransactionData>> ShowOnChainWalletTransactions(
string storeId, string cryptoCode, TransactionStatus[] statusFilter = null, string storeId, string cryptoCode, TransactionStatus[] statusFilter = null,
CancellationToken token = default) CancellationToken token = default)
@@ -68,7 +68,7 @@ namespace BTCPayServer.Client
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions", query), token); CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions", query), token);
return await HandleResponse<IEnumerable<OnChainWalletTransactionData>>(response); return await HandleResponse<IEnumerable<OnChainWalletTransactionData>>(response);
} }
public virtual async Task<OnChainWalletTransactionData> GetOnChainWalletTransaction( public virtual async Task<OnChainWalletTransactionData> GetOnChainWalletTransaction(
string storeId, string cryptoCode, string transactionId, string storeId, string cryptoCode, string transactionId,
CancellationToken token = default) CancellationToken token = default)
@@ -78,7 +78,7 @@ namespace BTCPayServer.Client
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions/{transactionId}"), token); CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions/{transactionId}"), token);
return await HandleResponse<OnChainWalletTransactionData>(response); return await HandleResponse<OnChainWalletTransactionData>(response);
} }
public virtual async Task<IEnumerable<OnChainWalletUTXOData>> GetOnChainWalletUTXOs(string storeId, public virtual async Task<IEnumerable<OnChainWalletUTXOData>> GetOnChainWalletUTXOs(string storeId,
string cryptoCode, string cryptoCode,
CancellationToken token = default) CancellationToken token = default)
@@ -88,7 +88,7 @@ namespace BTCPayServer.Client
CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/utxos"), token); CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/utxos"), token);
return await HandleResponse<IEnumerable<OnChainWalletUTXOData>>(response); return await HandleResponse<IEnumerable<OnChainWalletUTXOData>>(response);
} }
public virtual async Task<OnChainWalletTransactionData> CreateOnChainTransaction(string storeId, public virtual async Task<OnChainWalletTransactionData> CreateOnChainTransaction(string storeId,
string cryptoCode, CreateOnChainTransactionRequest request, string cryptoCode, CreateOnChainTransactionRequest request,
CancellationToken token = default) 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); CreateHttpRequest($"api/v1/stores/{storeId}/payment-methods/Onchain/{cryptoCode}/wallet/transactions", null, request, HttpMethod.Post), token);
return await HandleResponse<OnChainWalletTransactionData>(response); return await HandleResponse<OnChainWalletTransactionData>(response);
} }
public virtual async Task<Transaction> CreateOnChainTransactionButDoNotBroadcast(string storeId, public virtual async Task<Transaction> CreateOnChainTransactionButDoNotBroadcast(string storeId,
string cryptoCode, CreateOnChainTransactionRequest request, Network network, string cryptoCode, CreateOnChainTransactionRequest request, Network network,
CancellationToken token = default) CancellationToken token = default)

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@@ -21,7 +21,7 @@ public class WordlistJsonConverter : JsonConverter
{"PortugueseBrazil", Wordlist.PortugueseBrazil}, {"PortugueseBrazil", Wordlist.PortugueseBrazil},
{"Czech", Wordlist.Czech} {"Czech", Wordlist.Czech}
}; };
_WordlistsReverse = _Wordlists.ToDictionary(kv => kv.Value, kv => kv.Key); _WordlistsReverse = _Wordlists.ToDictionary(kv => kv.Value, kv => kv.Key);
} }

View File

@@ -4,4 +4,4 @@ namespace BTCPayServer.Client.Models
{ {
public string Email { get; set; } public string Email { get; set; }
} }
} }

View File

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

View File

@@ -1,4 +1,4 @@
using BTCPayServer.Client.JsonConverters; using BTCPayServer.Client.JsonConverters;
using NBitcoin; using NBitcoin;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
@@ -8,7 +8,7 @@ namespace BTCPayServer.Client
public class GenerateOnChainWalletRequest public class GenerateOnChainWalletRequest
{ {
public int AccountNumber { get; set; } = 0; public int AccountNumber { get; set; } = 0;
[JsonConverter(typeof(MnemonicJsonConverter))] [JsonConverter(typeof(MnemonicJsonConverter))]
public Mnemonic ExistingMnemonic { get; set; } public Mnemonic ExistingMnemonic { get; set; }
[JsonConverter(typeof(WordlistJsonConverter))] [JsonConverter(typeof(WordlistJsonConverter))]
public NBitcoin.Wordlist WordList { get; set; } public NBitcoin.Wordlist WordList { get; set; }

View File

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

View File

@@ -12,6 +12,6 @@ namespace BTCPayServer.Client.Models
} }
public string MissingPermission { get; } public string MissingPermission { get; }
} }
} }

View File

@@ -9,4 +9,4 @@ namespace BTCPayServer.Client.Models
Invalid, Invalid,
PaidOver PaidOver
} }
} }

View File

@@ -52,7 +52,7 @@ namespace BTCPayServer.Client.Models
public PaymentStatus Status { get; set; } public PaymentStatus Status { get; set; }
public string Destination { get; set; } public string Destination { get; set; }
public enum PaymentStatus public enum PaymentStatus
{ {
Invalid, Invalid,

View File

@@ -1,4 +1,4 @@
namespace BTCPayServer.Client.Models namespace BTCPayServer.Client.Models
{ {
public class LNURLPayPaymentMethodBaseData public class LNURLPayPaymentMethodBaseData
{ {
@@ -8,7 +8,7 @@
public LNURLPayPaymentMethodBaseData() public LNURLPayPaymentMethodBaseData()
{ {
} }
} }
} }

View File

@@ -1,6 +1,6 @@
namespace BTCPayServer.Client.Models namespace BTCPayServer.Client.Models
{ {
public class LNURLPayPaymentMethodData: LNURLPayPaymentMethodBaseData public class LNURLPayPaymentMethodData : LNURLPayPaymentMethodBaseData
{ {
/// <summary> /// <summary>
/// Whether the payment method is enabled /// 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; Enabled = enabled;
CryptoCode = cryptoCode; CryptoCode = cryptoCode;

View File

@@ -11,4 +11,4 @@ namespace BTCPayServer.Client.Models
[JsonExtensionData] public Dictionary<string, JToken> AdditionalData { get; set; } [JsonExtensionData] public Dictionary<string, JToken> AdditionalData { get; set; }
} }
} }

View File

@@ -1,4 +1,4 @@
namespace BTCPayServer.Client.Models namespace BTCPayServer.Client.Models
{ {
public class LightningNetworkPaymentMethodBaseData public class LightningNetworkPaymentMethodBaseData
{ {
@@ -7,7 +7,7 @@
public bool DisableBOLT11PaymentOption { get; set; } public bool DisableBOLT11PaymentOption { get; set; }
public LightningNetworkPaymentMethodBaseData() public LightningNetworkPaymentMethodBaseData()
{ {
} }
} }
} }

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ namespace BTCPayServer.Client.Models
public OnChainPaymentMethodDataPreview() public OnChainPaymentMethodDataPreview()
{ {
} }
public OnChainPaymentMethodDataPreview(string cryptoCode, string derivationScheme, string label, RootedKeyPath accountKeyPath) public OnChainPaymentMethodDataPreview(string cryptoCode, string derivationScheme, string label, RootedKeyPath accountKeyPath)
@@ -34,7 +34,7 @@ namespace BTCPayServer.Client.Models
public OnChainPaymentMethodData() public OnChainPaymentMethodData()
{ {
} }
public OnChainPaymentMethodData(string cryptoCode, string derivationScheme, bool enabled, string label, RootedKeyPath accountKeyPath, string paymentMethod) : public OnChainPaymentMethodData(string cryptoCode, string derivationScheme, bool enabled, string label, RootedKeyPath accountKeyPath, string paymentMethod) :

View File

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

View File

@@ -29,14 +29,14 @@ namespace BTCPayServer.Client.Models
/// </summary> /// </summary>
public IEnumerable<SyncStatus> SyncStatus { get; set; } public IEnumerable<SyncStatus> SyncStatus { get; set; }
} }
public class SyncStatus public class SyncStatus
{ {
public string CryptoCode { get; set; } public string CryptoCode { get; set; }
public virtual bool Available { get; set; } public virtual bool Available { get; set; }
} }
public class ServerInfoSyncStatusData: SyncStatus public class ServerInfoSyncStatusData : SyncStatus
{ {
public int ChainHeight { get; set; } public int ChainHeight { get; set; }
public int? SyncHeight { get; set; } public int? SyncHeight { get; set; }

View File

@@ -41,9 +41,9 @@ namespace BTCPayServer.Client.Models
public bool ShowRecommendedFee { get; set; } = true; public bool ShowRecommendedFee { get; set; } = true;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int RecommendedFeeBlockTarget { get; set; } = 1; public int RecommendedFeeBlockTarget { get; set; } = 1;
public string DefaultPaymentMethod { get; set; } public string DefaultPaymentMethod { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string DefaultLang { get; set; } = "en"; public string DefaultLang { get; set; } = "en";

View File

@@ -6,4 +6,4 @@ namespace BTCPayServer.Client.Models
Confirmed, Confirmed,
Replaced Replaced
} }
} }

View File

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

View File

@@ -11,7 +11,7 @@ namespace BTCPayServer.Client.Models
public UpdateOnChainPaymentMethodRequest() public UpdateOnChainPaymentMethodRequest()
{ {
} }
public UpdateOnChainPaymentMethodRequest(bool enabled, string derivationScheme, string label, RootedKeyPath accountKeyPath) public UpdateOnChainPaymentMethodRequest(bool enabled, string derivationScheme, string label, RootedKeyPath accountKeyPath)

View File

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

View File

@@ -8,10 +8,10 @@ namespace BTCPayServer.Data
[MaxLength(50)] [MaxLength(50)]
public string Id { get; set; } public string Id { get; set; }
[MaxLength(50)] [MaxLength(50)]
public string StoreId { get; set; } public string StoreId { get; set; }
[MaxLength(50)] [MaxLength(50)]
public string UserId { get; set; } public string UserId { get; set; }
public APIKeyType Type { get; set; } = APIKeyType.Legacy; public APIKeyType Type { get; set; } = APIKeyType.Legacy;

View File

@@ -19,7 +19,7 @@ namespace BTCPayServer.Data
public List<NotificationData> Notifications { get; set; } public List<NotificationData> Notifications { get; set; }
public List<UserStore> UserStores { get; set; } public List<UserStore> UserStores { get; set; }
public List<Fido2Credential> Fido2Credentials { get; set; } public List<Fido2Credential> Fido2Credentials { get; set; }
public byte[] Blob { get; set; } public byte[] Blob { get; set; }
public List<IdentityUserRole<string>> UserRoles { get; set; } public List<IdentityUserRole<string>> UserRoles { get; set; }

View File

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

View File

@@ -19,8 +19,8 @@ namespace BTCPayServer.Data
public string ApplicationUserId { get; set; } public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; } public ApplicationUser ApplicationUser { get; set; }
internal static void OnModelCreating(ModelBuilder builder) internal static void OnModelCreating(ModelBuilder builder)
{ {
#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete

View File

@@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations
name: "CurrentRefundId", name: "CurrentRefundId",
table: "Invoices", table: "Invoices",
nullable: true, nullable: true,
maxLength: maxLength); maxLength: maxLength);
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Notifications", name: "Notifications",

View File

@@ -1,10 +1,10 @@
using BTCPayServer.Data; using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
namespace BTCPayServer.Migrations namespace BTCPayServer.Migrations
{ {
[DbContext(typeof(ApplicationDbContext))] [DbContext(typeof(ApplicationDbContext))]
[Migration("20200901161733_AddInvoiceEventLogSeverity")] [Migration("20200901161733_AddInvoiceEventLogSeverity")]
public partial class AddInvoiceEventLogSeverity : Migration public partial class AddInvoiceEventLogSeverity : Migration

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations
oldClrType: typeof(string)); oldClrType: typeof(string));
} }
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_Invoices_OrderId", name: "IX_Invoices_OrderId",
table: "Invoices", table: "Invoices",
column: "OrderId"); column: "OrderId");

View File

@@ -20,7 +20,7 @@ namespace BTCPayServer.Migrations
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.Annotation("MySql:ValueGeneratedOnAdd", true) .Annotation("MySql:ValueGeneratedOnAdd", true)
.Annotation("Sqlite:Autoincrement", true), .Annotation("Sqlite:Autoincrement", true),
// eof manually added // eof manually added
InvoiceDataId = table.Column<string>(maxLength: 255, nullable: true), InvoiceDataId = table.Column<string>(maxLength: 255, nullable: true),
Value = table.Column<string>(maxLength: 512, nullable: true) Value = table.Column<string>(maxLength: 512, nullable: true)
}, },

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
@@ -21,8 +21,8 @@ namespace BTCPayServer.PluginPacker
var name = args[1]; var name = args[1];
var outputDir = args[2]; var outputDir = args[2];
var outputFile = Path.Combine(outputDir, name); var outputFile = Path.Combine(outputDir, name);
var rootDLLPath = Path.Combine(directory, name +".dll"); var rootDLLPath = Path.Combine(directory, name + ".dll");
if (!File.Exists(rootDLLPath) ) if (!File.Exists(rootDLLPath))
{ {
throw new Exception($"{rootDLLPath} could not be found"); throw new Exception($"{rootDLLPath} could not be found");
} }
@@ -45,7 +45,7 @@ namespace BTCPayServer.PluginPacker
File.WriteAllText(outputFile + ".btcpay.json", json); File.WriteAllText(outputFile + ".btcpay.json", json);
Console.WriteLine($"Created {outputFile}.btcpay at {directory}"); Console.WriteLine($"Created {outputFile}.btcpay at {directory}");
} }
private static Type[] GetAllExtensionTypesFromAssembly(Assembly assembly) private static Type[] GetAllExtensionTypesFromAssembly(Assembly assembly)
{ {
return assembly.GetTypes().Where(type => return assembly.GetTypes().Where(type =>

View File

@@ -15,7 +15,7 @@ namespace BTCPayServer.Plugins.Test
{ {
_testPluginService = testPluginService; _testPluginService = testPluginService;
} }
// GET // GET
public async Task<IActionResult> Index() public async Task<IActionResult> Index()
{ {
@@ -24,8 +24,8 @@ namespace BTCPayServer.Plugins.Test
Data = await _testPluginService.Get() Data = await _testPluginService.Get()
}); });
} }
} }
public class TestPluginPageViewModel public class TestPluginPageViewModel

View File

@@ -8,7 +8,7 @@ namespace BTCPayServer.Plugins.Test.Data
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; } public string Id { get; set; }
public DateTimeOffset Timestamp { get; set; } public DateTimeOffset Timestamp { get; set; }
} }
} }

View File

@@ -10,7 +10,7 @@ namespace BTCPayServer.Plugins.Test
private readonly bool _designTime; private readonly bool _designTime;
public DbSet<TestPluginData> TestPluginRecords { get; set; } public DbSet<TestPluginData> TestPluginRecords { get; set; }
public TestPluginDbContext(DbContextOptions<TestPluginDbContext> options, bool designTime = false) public TestPluginDbContext(DbContextOptions<TestPluginDbContext> options, bool designTime = false)
: base(options) : base(options)
{ {

View File

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

View File

@@ -6,7 +6,7 @@ using Microsoft.Extensions.Options;
namespace BTCPayServer.Plugins.Test namespace BTCPayServer.Plugins.Test
{ {
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<TestPluginDbContext> public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<TestPluginDbContext>
{ {
public TestPluginDbContext CreateDbContext(string[] args) public TestPluginDbContext CreateDbContext(string[] args)
@@ -31,7 +31,7 @@ namespace BTCPayServer.Plugins.Test
var builder = new DbContextOptionsBuilder<TestPluginDbContext>(); var builder = new DbContextOptionsBuilder<TestPluginDbContext>();
ConfigureBuilder(builder); ConfigureBuilder(builder);
return new TestPluginDbContext(builder.Options); return new TestPluginDbContext(builder.Options);
} }
} }
} }

View File

@@ -19,11 +19,11 @@ namespace BTCPayServer.Plugins.Test.Services
{ {
await using var context = _testPluginDbContextFactory.CreateContext(); 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(); await context.SaveChangesAsync();
} }
public async Task<List<TestPluginData>> Get() public async Task<List<TestPluginData>> Get()
{ {
await using var context = _testPluginDbContextFactory.CreateContext(); await using var context = _testPluginDbContextFactory.CreateContext();

View File

@@ -1,4 +1,4 @@
using System; using System;
using BTCPayServer.Abstractions.Contracts; using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Abstractions.Models; using BTCPayServer.Abstractions.Models;
using BTCPayServer.Abstractions.Services; using BTCPayServer.Abstractions.Services;
@@ -9,11 +9,11 @@ using Microsoft.Extensions.DependencyInjection;
namespace BTCPayServer.Plugins.Test namespace BTCPayServer.Plugins.Test
{ {
public class TestPlugin: BaseBTCPayServerPlugin public class TestPlugin : BaseBTCPayServerPlugin
{ {
public override string Identifier { get; } = "BTCPayServer.Plugins.Test"; public override string Identifier { get; } = "BTCPayServer.Plugins.Test";
public override string Name { get; } = "Test Plugin!"; public override string Name { get; } = "Test Plugin!";
public override string Description { get; } = "This is a description of the loaded test extension!"; public override string Description { get; } = "This is a description of the loaded test extension!";
public override void Execute(IServiceCollection services) public override void Execute(IServiceCollection services)
{ {
@@ -33,7 +33,7 @@ namespace BTCPayServer.Plugins.Test
base.Execute(applicationBuilder, applicationBuilderApplicationServices); base.Execute(applicationBuilder, applicationBuilderApplicationServices);
applicationBuilderApplicationServices.GetService<TestPluginDbContextFactory>().CreateContext().Database.Migrate(); applicationBuilderApplicationServices.GetService<TestPluginDbContextFactory>().CreateContext().Database.Migrate();
applicationBuilderApplicationServices.GetService<TestPluginService>().AddTestDataRecord().GetAwaiter().GetResult(); applicationBuilderApplicationServices.GetService<TestPluginService>().AddTestDataRecord().GetAwaiter().GetResult();
} }
} }
} }

View File

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

View File

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

View File

@@ -142,7 +142,7 @@ namespace BTCPayServer.Tests
(await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions); (await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions);
authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri, 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); s.Driver.Navigate().GoToUrl(authUrl);
Assert.DoesNotContain("kukksappname", s.Driver.PageSource); Assert.DoesNotContain("kukksappname", s.Driver.PageSource);
@@ -169,11 +169,11 @@ namespace BTCPayServer.Tests
s.Driver.Navigate().GoToUrl(authUrl); s.Driver.Navigate().GoToUrl(authUrl);
s.Driver.FindElement(By.Id("continue")).Click(); s.Driver.FindElement(By.Id("continue")).Click();
Assert.Equal(callbackUrl, s.Driver.Url); Assert.Equal(callbackUrl, s.Driver.Url);
//same app but different redirect = nono //same app but different redirect = nono
authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri, authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri,
new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, (appidentifier, new Uri("https://international.local/callback"))).ToString(); new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, (appidentifier, new Uri("https://international.local/callback"))).ToString();
s.Driver.Navigate().GoToUrl(authUrl); s.Driver.Navigate().GoToUrl(authUrl);
Assert.False(s.Driver.Url.StartsWith("https://international.com/callback")); Assert.False(s.Driver.Url.StartsWith("https://international.com/callback"));

View File

@@ -200,7 +200,7 @@ namespace BTCPayServer.Tests
s.Driver.SetCheckbox(By.Id("LightningAmountInSatoshi"), true); s.Driver.SetCheckbox(By.Id("LightningAmountInSatoshi"), true);
s.Driver.FindElement(By.Id("save")).Click(); s.Driver.FindElement(By.Id("save")).Click();
Assert.Contains("BTC Lightning settings successfully updated", s.FindAlertMessage().Text); Assert.Contains("BTC Lightning settings successfully updated", s.FindAlertMessage().Text);
var invoiceId = s.CreateInvoice(storeId, 10, "USD", "a@g.com"); var invoiceId = s.CreateInvoice(storeId, 10, "USD", "a@g.com");
s.GoToInvoiceCheckout(invoiceId); s.GoToInvoiceCheckout(invoiceId);
Assert.Contains("Sats", s.Driver.FindElement(By.ClassName("payment__currencies_noborder")).Text); Assert.Contains("Sats", s.Driver.FindElement(By.ClassName("payment__currencies_noborder")).Text);

View File

@@ -92,7 +92,7 @@ namespace BTCPayServer.Tests
var anonAppPubsController = tester.PayTester.GetController<AppsPublicController>(); var anonAppPubsController = tester.PayTester.GetController<AppsPublicController>();
var publicApps = user.GetController<AppsPublicController>(); var publicApps = user.GetController<AppsPublicController>();
Assert.IsType<NotFoundObjectResult>(await anonAppPubsController.ContributeToCrowdfund(app.Id, new ContributeToCrowdfund() Assert.IsType<NotFoundObjectResult>(await anonAppPubsController.ContributeToCrowdfund(app.Id, new ContributeToCrowdfund()
{ {
Amount = new decimal(0.01) Amount = new decimal(0.01)
@@ -187,7 +187,7 @@ namespace BTCPayServer.Tests
var model = Assert.IsType<ViewCrowdfundViewModel>(Assert var model = Assert.IsType<ViewCrowdfundViewModel>(Assert
.IsType<ViewResult>(publicApps.ViewCrowdfund(app.Id, String.Empty).Result).Model); .IsType<ViewResult>(publicApps.ViewCrowdfund(app.Id, String.Empty).Result).Model);
Assert.Equal(crowdfundViewModel.TargetAmount, model.TargetAmount); Assert.Equal(crowdfundViewModel.TargetAmount, model.TargetAmount);
Assert.Equal(crowdfundViewModel.EndDate, model.EndDate); Assert.Equal(crowdfundViewModel.EndDate, model.EndDate);
Assert.Equal(crowdfundViewModel.StartDate, model.StartDate); Assert.Equal(crowdfundViewModel.StartDate, model.StartDate);
@@ -195,7 +195,7 @@ namespace BTCPayServer.Tests
Assert.Equal(0m, model.Info.CurrentAmount); Assert.Equal(0m, model.Info.CurrentAmount);
Assert.Equal(0m, model.Info.CurrentPendingAmount); Assert.Equal(0m, model.Info.CurrentPendingAmount);
Assert.Equal(0m, model.Info.ProgressPercentage); Assert.Equal(0m, model.Info.ProgressPercentage);
TestLogs.LogInformation("Unpaid invoices should show as pending contribution because it is hardcap"); 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"); 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 var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice
@@ -208,7 +208,7 @@ namespace BTCPayServer.Tests
TransactionSpeed = "high", TransactionSpeed = "high",
FullNotifications = true FullNotifications = true
}, Facade.Merchant); }, Facade.Merchant);
model = Assert.IsType<ViewCrowdfundViewModel>(Assert model = Assert.IsType<ViewCrowdfundViewModel>(Assert
.IsType<ViewResult>(publicApps.ViewCrowdfund(app.Id, string.Empty).Result).Model); .IsType<ViewResult>(publicApps.ViewCrowdfund(app.Id, string.Empty).Result).Model);

View File

@@ -28,11 +28,12 @@ namespace BTCPayServer.Tests
public static void AssertNoError(this IWebDriver driver) 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"))) 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}"); Assert.False(dangerAlert.Displayed, $"No alert should be displayed, but found this on {driver.Url}: {dangerAlert.Text}");
} }
public static T AssertViewModel<T>(this IActionResult result) public static T AssertViewModel<T>(this IActionResult result)
{ {
Assert.NotNull(result); Assert.NotNull(result);
@@ -50,7 +51,7 @@ namespace BTCPayServer.Tests
// Sometimes, selenium is flaky... // Sometimes, selenium is flaky...
public static IWebElement FindElementUntilNotStaled(this IWebDriver driver, By by, Action<IWebElement> act) public static IWebElement FindElementUntilNotStaled(this IWebDriver driver, By by, Action<IWebElement> act)
{ {
retry: retry:
try try
{ {
var el = driver.FindElement(by); var el = driver.FindElement(by);
@@ -91,18 +92,18 @@ namespace BTCPayServer.Tests
public static void UntilJsIsReady(this WebDriverWait wait) 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 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 typeof(jQuery) === 'undefined' || jQuery.active === 0").Equals(true));
} }
// Open collapse via JS, because if we click the link it triggers the toggle animation. // 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. // 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) public static void ToggleCollapse(this IWebDriver driver, string collapseId)
{ {
driver.ExecuteJavaScript($"document.getElementById('{collapseId}').classList.add('show')"); driver.ExecuteJavaScript($"document.getElementById('{collapseId}').classList.add('show')");
} }
public static void SetAttribute(this IWebDriver driver, string element, string attribute, string value) public static void SetAttribute(this IWebDriver driver, string element, string attribute, string value)
{ {
@@ -135,7 +136,7 @@ namespace BTCPayServer.Tests
wait.UntilJsIsReady(); wait.UntilJsIsReady();
int retriesLeft = 4; int retriesLeft = 4;
retry: retry:
try try
{ {
var el = driver.FindElement(selector); var el = driver.FindElement(selector);

View File

@@ -460,7 +460,7 @@ namespace BTCPayServer.Tests
Assert.Null(payout.PaymentMethodAmount); Assert.Null(payout.PaymentMethodAmount);
TestLogs.LogInformation("Can't overdraft"); TestLogs.LogInformation("Can't overdraft");
var destination2 = (await tester.ExplorerNode.GetNewAddressAsync()).ToString(); var destination2 = (await tester.ExplorerNode.GetNewAddressAsync()).ToString();
await this.AssertAPIError("overdraft", async () => await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest() await this.AssertAPIError("overdraft", async () => await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest()
{ {
@@ -1142,25 +1142,25 @@ namespace BTCPayServer.Tests
Assert.Empty(invoices); Assert.Empty(invoices);
//list Filtered //list Filtered
var invoicesFiltered = await viewOnly.GetInvoices(user.StoreId, var invoicesFiltered = await viewOnly.GetInvoices(user.StoreId,
orderId: null, status: null, startDate: DateTimeOffset.Now.AddHours(-1), orderId: null, status: null, startDate: DateTimeOffset.Now.AddHours(-1),
endDate: DateTimeOffset.Now.AddHours(1)); endDate: DateTimeOffset.Now.AddHours(1));
Assert.NotNull(invoicesFiltered); Assert.NotNull(invoicesFiltered);
Assert.Single(invoicesFiltered); Assert.Single(invoicesFiltered);
Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id);
Assert.NotNull(invoicesFiltered); Assert.NotNull(invoicesFiltered);
Assert.Single(invoicesFiltered); Assert.Single(invoicesFiltered);
Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id);
//list Yesterday //list Yesterday
var invoicesYesterday = await viewOnly.GetInvoices(user.StoreId, var invoicesYesterday = await viewOnly.GetInvoices(user.StoreId,
orderId: null, status: null, startDate: DateTimeOffset.Now.AddDays(-2), orderId: null, status: null, startDate: DateTimeOffset.Now.AddDays(-2),
endDate: DateTimeOffset.Now.AddDays(-1)); endDate: DateTimeOffset.Now.AddDays(-1));
Assert.NotNull(invoicesYesterday); Assert.NotNull(invoicesYesterday);
Assert.Empty(invoicesYesterday); Assert.Empty(invoicesYesterday);
// Error, startDate and endDate inverted // Error, startDate and endDate inverted
await AssertValidationError(new[] { "startDate", "endDate" }, await AssertValidationError(new[] { "startDate", "endDate" },
@@ -1177,31 +1177,31 @@ namespace BTCPayServer.Tests
//list Existing OrderId //list Existing OrderId
var invoicesExistingOrderId = var invoicesExistingOrderId =
await viewOnly.GetInvoices(user.StoreId, orderId: new []{newInvoice.Metadata["orderId"].ToString()}); await viewOnly.GetInvoices(user.StoreId, orderId: new[] { newInvoice.Metadata["orderId"].ToString() });
Assert.NotNull(invoicesExistingOrderId); Assert.NotNull(invoicesExistingOrderId);
Assert.Single(invoicesFiltered); Assert.Single(invoicesFiltered);
Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id); Assert.Equal(newInvoice.Id, invoicesFiltered.First().Id);
//list NonExisting OrderId //list NonExisting OrderId
var invoicesNonExistingOrderId = var invoicesNonExistingOrderId =
await viewOnly.GetInvoices(user.StoreId, orderId: new []{"NonExistingOrderId"}); await viewOnly.GetInvoices(user.StoreId, orderId: new[] { "NonExistingOrderId" });
Assert.NotNull(invoicesNonExistingOrderId); Assert.NotNull(invoicesNonExistingOrderId);
Assert.Empty(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 //get
var invoice = await viewOnly.GetInvoice(user.StoreId, newInvoice.Id); var invoice = await viewOnly.GetInvoice(user.StoreId, newInvoice.Id);
Assert.Equal(newInvoice.Metadata, invoice.Metadata); Assert.Equal(newInvoice.Metadata, invoice.Metadata);
@@ -1216,14 +1216,14 @@ namespace BTCPayServer.Tests
//update //update
newInvoice = await client.CreateInvoice(user.StoreId, newInvoice = await client.CreateInvoice(user.StoreId,
new CreateInvoiceRequest() { Currency = "USD", Amount = 1 }); new CreateInvoiceRequest() { Currency = "USD", Amount = 1 });
Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking);
Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
await client.MarkInvoiceStatus(user.StoreId, newInvoice.Id, new MarkInvoiceStatusRequest() await client.MarkInvoiceStatus(user.StoreId, newInvoice.Id, new MarkInvoiceStatusRequest()
{ {
Status = InvoiceStatus.Settled Status = InvoiceStatus.Settled
}); });
newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id); newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id);
Assert.DoesNotContain(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); Assert.DoesNotContain(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking);
Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); Assert.Contains(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
newInvoice = await client.CreateInvoice(user.StoreId, newInvoice = await client.CreateInvoice(user.StoreId,
@@ -1234,7 +1234,7 @@ namespace BTCPayServer.Tests
}); });
newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id); newInvoice = await client.GetInvoice(user.StoreId, newInvoice.Id);
Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking); Assert.Contains(InvoiceStatus.Settled, newInvoice.AvailableStatusesForManualMarking);
Assert.DoesNotContain(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking); Assert.DoesNotContain(InvoiceStatus.Invalid, newInvoice.AvailableStatusesForManualMarking);
await AssertHttpError(403, async () => await AssertHttpError(403, async () =>
@@ -1369,7 +1369,7 @@ namespace BTCPayServer.Tests
Checkout = new CreateInvoiceRequest.CheckoutOptions() Checkout = new CreateInvoiceRequest.CheckoutOptions()
{ {
PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" }, PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" },
DefaultPaymentMethod = "BTC_LightningLike" DefaultPaymentMethod = "BTC_LightningLike"
} }
}); });
Assert.Equal("BTC_LightningLike", invoiceWithdefaultPaymentMethodLN.Checkout.DefaultPaymentMethod); Assert.Equal("BTC_LightningLike", invoiceWithdefaultPaymentMethodLN.Checkout.DefaultPaymentMethod);
@@ -1382,17 +1382,17 @@ namespace BTCPayServer.Tests
Checkout = new CreateInvoiceRequest.CheckoutOptions() Checkout = new CreateInvoiceRequest.CheckoutOptions()
{ {
PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" }, PaymentMethods = new[] { "BTC", "BTC-LightningNetwork" },
DefaultPaymentMethod = "BTC" DefaultPaymentMethod = "BTC"
} }
}); });
Assert.Equal("BTC", invoiceWithdefaultPaymentMethodOnChain.Checkout.DefaultPaymentMethod); Assert.Equal("BTC", invoiceWithdefaultPaymentMethodOnChain.Checkout.DefaultPaymentMethod);
store = await client.GetStore(user.StoreId); store = await client.GetStore(user.StoreId);
store.LazyPaymentMethods = false; store.LazyPaymentMethods = false;
store = await client.UpdateStore(store.Id, store = await client.UpdateStore(store.Id,
JObject.FromObject(store).ToObject<UpdateStoreRequest>()); JObject.FromObject(store).ToObject<UpdateStoreRequest>());
//let's see the overdue amount //let's see the overdue amount
invoice = await client.CreateInvoice(user.StoreId, invoice = await client.CreateInvoice(user.StoreId,
new CreateInvoiceRequest() new CreateInvoiceRequest()
@@ -1402,24 +1402,24 @@ namespace BTCPayServer.Tests
Checkout = new CreateInvoiceRequest.CheckoutOptions() Checkout = new CreateInvoiceRequest.CheckoutOptions()
{ {
PaymentMethods = new[] { "BTC" }, PaymentMethods = new[] { "BTC" },
DefaultPaymentMethod = "BTC" DefaultPaymentMethod = "BTC"
} }
}); });
var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id)); var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id));
Assert.Equal(0.0001m, pm.Due); Assert.Equal(0.0001m, pm.Due);
await tester.WaitForEvent<NewOnChainTransactionEvent>(async () => await tester.WaitForEvent<NewOnChainTransactionEvent>(async () =>
{ {
await tester.ExplorerNode.SendToAddressAsync( await tester.ExplorerNode.SendToAddressAsync(
BitcoinAddress.Create(pm.Destination, tester.ExplorerClient.Network.NBitcoinNetwork), BitcoinAddress.Create(pm.Destination, tester.ExplorerClient.Network.NBitcoinNetwork),
new Money(0.0002m, MoneyUnit.BTC)); new Money(0.0002m, MoneyUnit.BTC));
}); });
await TestUtils.EventuallyAsync(async () => await TestUtils.EventuallyAsync(async () =>
{ {
var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id)); var pm = Assert.Single(await client.GetInvoicePaymentMethods(user.StoreId, invoice.Id));
Assert.Single(pm.Payments); Assert.Single(pm.Payments);
Assert.Equal(-0.0001m, pm.Due); Assert.Equal(-0.0001m, pm.Due);
}); });
} }
} }
@@ -1567,7 +1567,7 @@ namespace BTCPayServer.Tests
var user2 = tester.NewAccount(); var user2 = tester.NewAccount();
await user.GrantAccessAsync(true); await user.GrantAccessAsync(true);
await user2.GrantAccessAsync(false); await user2.GrantAccessAsync(false);
var client = await user.CreateClient(Policies.CanModifyStoreSettings); var client = await user.CreateClient(Policies.CanModifyStoreSettings);
var client2 = await user2.CreateClient(Policies.CanModifyStoreSettings); var client2 = await user2.CreateClient(Policies.CanModifyStoreSettings);
var viewOnlyClient = await user.CreateClient(Policies.CanViewStoreSettings); var viewOnlyClient = await user.CreateClient(Policies.CanViewStoreSettings);
@@ -1578,8 +1578,8 @@ namespace BTCPayServer.Tests
await AssertHttpError(403, async () => await AssertHttpError(403, async () =>
{ {
await viewOnlyClient.UpdateStoreOnChainPaymentMethod(store.Id, "BTC", new UpdateOnChainPaymentMethodRequest() { }); 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() var xpriv = new Mnemonic("all all all all all all all all all all all all").DeriveExtKey()
.Derive(KeyPath.Parse("m/84'/1'/0'")); .Derive(KeyPath.Parse("m/84'/1'/0'"));
var xpub = xpriv.Neuter().ToString(Network.RegTest); var xpub = xpriv.Neuter().ToString(Network.RegTest);
@@ -1617,59 +1617,59 @@ namespace BTCPayServer.Tests
{ {
await client.GetStoreOnChainPaymentMethod(store.Id, "BTC"); await client.GetStoreOnChainPaymentMethod(store.Id, "BTC");
}); });
await AssertHttpError(403, async () => await AssertHttpError(403, async () =>
{ {
await viewOnlyClient.GenerateOnChainWallet(store.Id, "BTC", new GenerateOnChainWalletRequest() { }); 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"); var allMnemonic = new Mnemonic("all all all all all all all all all all all all");
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC"); await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
var generateResponse = await client.GenerateOnChainWallet(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.Mnemonic.ToString(), allMnemonic.ToString());
Assert.Equal(generateResponse.DerivationScheme, xpub); Assert.Equal(generateResponse.DerivationScheme, xpub);
await AssertAPIError("already-configured", async () => await AssertAPIError("already-configured", async () =>
{ {
await client.GenerateOnChainWallet(store.Id, "BTC", await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() {ExistingMnemonic = allMnemonic,}); new GenerateOnChainWalletRequest() { ExistingMnemonic = allMnemonic, });
}); });
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC"); await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC", generateResponse = await client.GenerateOnChainWallet(store.Id, "BTC",
new GenerateOnChainWalletRequest() {}); new GenerateOnChainWalletRequest() { });
Assert.NotEqual(generateResponse.Mnemonic.ToString(), allMnemonic.ToString()); 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); Assert.Equal(generateResponse.Mnemonic.DeriveExtKey().Derive(KeyPath.Parse("m/84'/1'/0'")).Neuter().ToString(Network.RegTest), generateResponse.DerivationScheme);
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC"); await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(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(generateResponse.Mnemonic.ToString(), allMnemonic.ToString());
Assert.Equal(new Mnemonic("all all all all all all all all all all all all").DeriveExtKey() 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); .Derive(KeyPath.Parse("m/84'/1'/1'")).Neuter().ToString(Network.RegTest), generateResponse.DerivationScheme);
await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC"); await client.RemoveStoreOnChainPaymentMethod(store.Id, "BTC");
generateResponse = await client.GenerateOnChainWallet(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(24, generateResponse.Mnemonic.Words.Length);
Assert.Equal(Wordlist.Japanese,generateResponse.Mnemonic.WordList); Assert.Equal(Wordlist.Japanese, generateResponse.Mnemonic.WordList);
} }
@@ -1784,7 +1784,7 @@ namespace BTCPayServer.Tests
settings.AllowLightningInternalNodeForAll = true; settings.AllowLightningInternalNodeForAll = true;
await tester.PayTester.GetService<SettingsRepository>().UpdateSetting(settings); await tester.PayTester.GetService<SettingsRepository>().UpdateSetting(settings);
await nonAdminUserClient.UpdateStoreLightningNetworkPaymentMethod(nonAdminUser.StoreId, "BTC", new UpdateLightningNetworkPaymentMethodRequest() await nonAdminUserClient.UpdateStoreLightningNetworkPaymentMethod(nonAdminUser.StoreId, "BTC", new UpdateLightningNetworkPaymentMethodRequest()
{ {
Enabled = method.Enabled, Enabled = method.Enabled,
ConnectionString = method.ConnectionString ConnectionString = method.ConnectionString
@@ -2010,7 +2010,7 @@ namespace BTCPayServer.Tests
new[] { TransactionStatus.Confirmed }), data => data.TransactionHash == txdata.TransactionHash); new[] { TransactionStatus.Confirmed }), data => data.TransactionHash == txdata.TransactionHash);
} }
[Fact(Timeout = 60 * 2 * 1000)] [Fact(Timeout = 60 * 2 * 1000)]
[Trait("Lightning", "Lightning")] [Trait("Lightning", "Lightning")]
[Trait("Integration", "Integration")] [Trait("Integration", "Integration")]
@@ -2040,7 +2040,7 @@ namespace BTCPayServer.Tests
var methods = await adminClient.GetStorePaymentMethods(store.Id); var methods = await adminClient.GetStorePaymentMethods(store.Id);
Assert.Single(methods); Assert.Single(methods);
VerifyLightning(methods); VerifyLightning(methods);
var randK = new Mnemonic(Wordlist.English, WordCount.Twelve).DeriveExtKey().Neuter().ToString(Network.RegTest); var randK = new Mnemonic(Wordlist.English, WordCount.Twelve).DeriveExtKey().Neuter().ToString(Network.RegTest);
await adminClient.UpdateStoreOnChainPaymentMethod(admin.StoreId, "BTC", await adminClient.UpdateStoreOnChainPaymentMethod(admin.StoreId, "BTC",
new UpdateOnChainPaymentMethodRequest(true, randK, "testing", null)); new UpdateOnChainPaymentMethodRequest(true, randK, "testing", null));
@@ -2051,35 +2051,35 @@ namespace BTCPayServer.Tests
var paymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<OnChainPaymentMethodBaseData>(); var paymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<OnChainPaymentMethodBaseData>();
Assert.Equal(randK, paymentMethodBaseData.DerivationScheme); Assert.Equal(randK, paymentMethodBaseData.DerivationScheme);
} }
methods = await adminClient.GetStorePaymentMethods(store.Id); methods = await adminClient.GetStorePaymentMethods(store.Id);
Assert.Equal(2, methods.Count); Assert.Equal(2, methods.Count);
VerifyLightning(methods); VerifyLightning(methods);
VerifyOnChain(methods); VerifyOnChain(methods);
methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id); methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id);
VerifyLightning(methods); VerifyLightning(methods);
await adminClient.UpdateStoreLightningNetworkPaymentMethod(store.Id, "BTC", await adminClient.UpdateStoreLightningNetworkPaymentMethod(store.Id, "BTC",
new UpdateLightningNetworkPaymentMethodRequest( new UpdateLightningNetworkPaymentMethodRequest(
tester.GetLightningConnectionString(LightningConnectionType.CLightning, true), true)); tester.GetLightningConnectionString(LightningConnectionType.CLightning, true), true));
methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id); methods = await viewerOnlyClient.GetStorePaymentMethods(store.Id);
Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out var item)); Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out var item));
var lightningNetworkPaymentMethodBaseData =Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>(); var lightningNetworkPaymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
Assert.Equal("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString); Assert.Equal("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString);
methods = await adminClient.GetStorePaymentMethods(store.Id); methods = await adminClient.GetStorePaymentMethods(store.Id);
Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out item)); Assert.True(methods.TryGetValue(new PaymentMethodId("BTC", PaymentTypes.LightningLike).ToStringNormalized(), out item));
lightningNetworkPaymentMethodBaseData =Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>(); lightningNetworkPaymentMethodBaseData = Assert.IsType<JObject>(item.Data).ToObject<LightningNetworkPaymentMethodBaseData>();
Assert.NotEqual("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString); Assert.NotEqual("*NEED CanModifyStoreSettings PERMISSION TO VIEW*", lightningNetworkPaymentMethodBaseData.ConnectionString);
} }
} }

View File

@@ -22,7 +22,7 @@ namespace BTCPayServer.Tests
{ {
await tester.StartAsync(); await tester.StartAsync();
var languageService = tester.PayTester.GetService<LanguageService>(); var languageService = tester.PayTester.GetService<LanguageService>();
// Most common format. First option does not have a quality score. Others do in descending order. // 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) // 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"); var lang1 = languageService.FindLanguageInAcceptLanguageHeader("nl,fr;q=0.7,en;q=0.5");

View File

@@ -95,7 +95,7 @@ namespace BTCPayServer.Tests
Assert.Equal(2 + 1, psbtReady.Destinations.Count); // The fee is a destination 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.Destination == sendDestination && !d.Positive);
Assert.Contains(psbtReady.Destinations, d => d.Positive); Assert.Contains(psbtReady.Destinations, d => d.Positive);
vmPSBT.PSBT = unsignedPSBT.ToBase64(); vmPSBT.PSBT = unsignedPSBT.ToBase64();
var combineVM = await walletController.WalletPSBT(walletId, vmPSBT, "combine").AssertViewModelAsync<WalletPSBTCombineViewModel>(); var combineVM = await walletController.WalletPSBT(walletId, vmPSBT, "combine").AssertViewModelAsync<WalletPSBTCombineViewModel>();
Assert.Equal(vmPSBT.PSBT, combineVM.OtherPSBT); Assert.Equal(vmPSBT.PSBT, combineVM.OtherPSBT);

View File

@@ -4,6 +4,7 @@ using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models; using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client.Models; using BTCPayServer.Client.Models;
using BTCPayServer.Controllers; using BTCPayServer.Controllers;
using BTCPayServer.Data; using BTCPayServer.Data;
@@ -16,11 +17,10 @@ using BTCPayServer.Services;
using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Wallets; using BTCPayServer.Services.Wallets;
using BTCPayServer.Tests.Logging; using BTCPayServer.Tests.Logging;
using BTCPayServer.Views.Stores;
using BTCPayServer.Views.Wallets; using BTCPayServer.Views.Wallets;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using NBitcoin; using NBitcoin;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Views.Stores;
using NBitcoin.Payment; using NBitcoin.Payment;
using NBitpayClient; using NBitpayClient;
using NBXplorer.DerivationStrategy; using NBXplorer.DerivationStrategy;
@@ -179,7 +179,7 @@ namespace BTCPayServer.Tests
var cashCow = tester.ExplorerNode; var cashCow = tester.ExplorerNode;
cashCow.Generate(2); // get some money in case 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))) foreach (ScriptPubKeyType senderAddressType in Enum.GetValues(typeof(ScriptPubKeyType)))
@@ -287,7 +287,7 @@ namespace BTCPayServer.Tests
var invoiceRepository = s.Server.PayTester.GetService<InvoiceRepository>(); var invoiceRepository = s.Server.PayTester.GetService<InvoiceRepository>();
s.RegisterNewUser(true); 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 cryptoCode = "BTC";
var receiver = s.CreateNewStore(); var receiver = s.CreateNewStore();
@@ -300,7 +300,7 @@ namespace BTCPayServer.Tests
var bip21 = s.Driver.FindElement(By.ClassName("payment__details__instruction__open-wallet__btn")) var bip21 = s.Driver.FindElement(By.ClassName("payment__details__instruction__open-wallet__btn"))
.GetAttribute("href"); .GetAttribute("href");
Assert.Contains($"{PayjoinClient.BIP21EndpointKey}=", bip21); Assert.Contains($"{PayjoinClient.BIP21EndpointKey}=", bip21);
s.GoToWalletSettings(receiver.storeId, cryptoCode); s.GoToWalletSettings(receiver.storeId, cryptoCode);
Assert.True(s.Driver.FindElement(By.Id("PayJoinEnabled")).Selected); Assert.True(s.Driver.FindElement(By.Id("PayJoinEnabled")).Selected);
@@ -867,7 +867,7 @@ retry:
//give the cow some cash //give the cow some cash
await cashCow.GenerateAsync(1); await cashCow.GenerateAsync(1);
//let's get some more utxos first //let's get some more utxos first
foreach (var m in new [] foreach (var m in new[]
{ {
Money.Coins(0.011m), Money.Coins(0.011m),
Money.Coins(0.012m), Money.Coins(0.012m),
@@ -940,7 +940,7 @@ retry:
coin5 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.025m); coin5 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.025m);
coin6 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.026m); coin6 = Assert.Single(senderCoins, coin => coin.Value.GetValue(btcPayNetwork) == 0.026m);
}); });
var signingKeySettings = derivationSchemeSettings.GetSigningAccountKeySettings(); var signingKeySettings = derivationSchemeSettings.GetSigningAccountKeySettings();
signingKeySettings.RootFingerprint = signingKeySettings.RootFingerprint =

View File

@@ -32,7 +32,7 @@ namespace BTCPayServer.Tests
user.RegisterDerivationScheme("BTC"); user.RegisterDerivationScheme("BTC");
var user2 = tester.NewAccount(); var user2 = tester.NewAccount();
await user2.GrantAccessAsync(); await user2.GrantAccessAsync();
var paymentRequestController = user.GetController<PaymentRequestController>(); var paymentRequestController = user.GetController<PaymentRequestController>();
@@ -51,7 +51,7 @@ namespace BTCPayServer.Tests
.RouteValues.Values.Last().ToString(); .RouteValues.Values.Last().ToString();
paymentRequestController.HttpContext.SetPaymentRequestData(new PaymentRequestData { Id = id, StoreDataId = request.StoreId }); paymentRequestController.HttpContext.SetPaymentRequestData(new PaymentRequestData { Id = id, StoreDataId = request.StoreId });
// Permission guard for guests editing // Permission guard for guests editing
Assert Assert
.IsType<NotFoundResult>(guestpaymentRequestController.EditPaymentRequest(user.StoreId, id)); .IsType<NotFoundResult>(guestpaymentRequestController.EditPaymentRequest(user.StoreId, id));
@@ -78,7 +78,7 @@ namespace BTCPayServer.Tests
Assert.Empty(Assert Assert.Empty(Assert
.IsType<ListPaymentRequestsViewModel>(Assert .IsType<ListPaymentRequestsViewModel>(Assert
.IsType<ViewResult>(await paymentRequestController.GetPaymentRequests(user.StoreId)).Model).Items); .IsType<ViewResult>(await paymentRequestController.GetPaymentRequests(user.StoreId)).Model).Items);
// Unarchive // Unarchive
Assert Assert
.IsType<RedirectToActionResult>(await paymentRequestController.TogglePaymentRequestArchival(id)); .IsType<RedirectToActionResult>(await paymentRequestController.TogglePaymentRequestArchival(id));

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models; using BTCPayServer.Abstractions.Models;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Lightning; using BTCPayServer.Lightning;
using BTCPayServer.Lightning.CLightning; using BTCPayServer.Lightning.CLightning;
using BTCPayServer.Views.Manage; using BTCPayServer.Views.Manage;
@@ -12,11 +13,10 @@ using BTCPayServer.Views.Stores;
using BTCPayServer.Views.Wallets; using BTCPayServer.Views.Wallets;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using NBitcoin; using NBitcoin;
using BTCPayServer.BIP78.Sender;
using OpenQA.Selenium; using OpenQA.Selenium;
using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Chrome;
using Xunit;
using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Support.UI;
using Xunit;
namespace BTCPayServer.Tests namespace BTCPayServer.Tests
{ {
@@ -82,7 +82,7 @@ namespace BTCPayServer.Tests
GoToRegister(); GoToRegister();
Driver.AssertNoError(); Driver.AssertNoError();
} }
/// <summary> /// <summary>
/// Use this ServerUri when trying to browse with selenium /// Use this ServerUri when trying to browse with selenium
/// Because for some reason, the selenium container can't resolve the tests container domain name /// 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; public Uri ServerUri;
internal IWebElement FindAlertMessage(StatusMessageModel.StatusSeverity severity = StatusMessageModel.StatusSeverity.Success) internal IWebElement FindAlertMessage(StatusMessageModel.StatusSeverity severity = StatusMessageModel.StatusSeverity.Success)
{ {
return FindAlertMessage(new[] {severity}); return FindAlertMessage(new[] { severity });
} }
internal IWebElement FindAlertMessage(params StatusMessageModel.StatusSeverity[] severity) internal IWebElement FindAlertMessage(params StatusMessageModel.StatusSeverity[] severity)
{ {
@@ -187,7 +187,7 @@ namespace BTCPayServer.Tests
Driver.FindElement(By.Id("ScriptPubKeyType")).Click(); Driver.FindElement(By.Id("ScriptPubKeyType")).Click();
Driver.FindElement(By.CssSelector($"#ScriptPubKeyType option[value={format}]")).Click(); Driver.FindElement(By.CssSelector($"#ScriptPubKeyType option[value={format}]")).Click();
Driver.ToggleCollapse("AdvancedSettings"); Driver.ToggleCollapse("AdvancedSettings");
Driver.SetCheckbox(By.Id("ImportKeysToRPC"), importkeys); Driver.SetCheckbox(By.Id("ImportKeysToRPC"), importkeys);
Driver.FindElement(By.Id("Continue")).Click(); Driver.FindElement(By.Id("Continue")).Click();
@@ -210,7 +210,7 @@ namespace BTCPayServer.Tests
Driver.FindElement(By.Id("confirm")).Click(); Driver.FindElement(By.Id("confirm")).Click();
Driver.FindElement(By.Id("submit")).Click(); Driver.FindElement(By.Id("submit")).Click();
} }
WalletId = new WalletId(StoreId, cryptoCode); WalletId = new WalletId(StoreId, cryptoCode);
return new Mnemonic(seed); return new Mnemonic(seed);
} }
@@ -240,7 +240,7 @@ namespace BTCPayServer.Tests
LightningConnectionType.Charge => LightningConnectionType.Charge =>
$"type=charge;server={Server.MerchantCharge.Client.Uri.AbsoluteUri};allowinsecure=true", $"type=charge;server={Server.MerchantCharge.Client.Uri.AbsoluteUri};allowinsecure=true",
LightningConnectionType.CLightning => LightningConnectionType.CLightning =>
$"type=clightning;server={((CLightningClient) Server.MerchantLightningD).Address.AbsoluteUri}", $"type=clightning;server={((CLightningClient)Server.MerchantLightningD).Address.AbsoluteUri}",
LightningConnectionType.LndREST => LightningConnectionType.LndREST =>
$"type=lnd-rest;server={Server.MerchantLnd.Swagger.BaseUrl};allowinsecure=true", $"type=lnd-rest;server={Server.MerchantLnd.Swagger.BaseUrl};allowinsecure=true",
_ => null _ => null
@@ -402,9 +402,9 @@ namespace BTCPayServer.Tests
} }
public string CreateInvoice( public string CreateInvoice(
string storeId, string storeId,
decimal? amount = 100, decimal? amount = 100,
string currency = "USD", string currency = "USD",
string refundEmail = "", string refundEmail = "",
string defaultPaymentMethod = null, string defaultPaymentMethod = null,
bool? requiresRefundEmail = null, bool? requiresRefundEmail = null,

View File

@@ -122,7 +122,7 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("Email")).SendKeys(u2.RegisterDetails.Email); s.Driver.FindElement(By.Id("Email")).SendKeys(u2.RegisterDetails.Email);
s.Driver.FindElement(By.Id("save")).Click(); 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.FindAlertMessage(StatusMessageModel.StatusSeverity.Error).Text);
s.GoToProfile(); s.GoToProfile();
@@ -402,11 +402,11 @@ namespace BTCPayServer.Tests
Assert.DoesNotContain("Archived", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text); Assert.DoesNotContain("Archived", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text);
s.Driver.FindElement(By.Id("btn-archive-toggle")).Click(); s.Driver.FindElement(By.Id("btn-archive-toggle")).Click();
Assert.Contains("Unarchive", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text); Assert.Contains("Unarchive", s.Driver.FindElement(By.Id("btn-archive-toggle")).Text);
//check that it no longer appears in list //check that it no longer appears in list
s.GoToInvoices(storeId); s.GoToInvoices(storeId);
Assert.DoesNotContain(invoiceId, s.Driver.PageSource); Assert.DoesNotContain(invoiceId, s.Driver.PageSource);
//ok, let's unarchive and see that it shows again //ok, let's unarchive and see that it shows again
s.Driver.Navigate().GoToUrl(invoiceUrl); s.Driver.Navigate().GoToUrl(invoiceUrl);
s.Driver.FindElement(By.Id("btn-archive-toggle")).Click(); s.Driver.FindElement(By.Id("btn-archive-toggle")).Click();
@@ -422,7 +422,7 @@ namespace BTCPayServer.Tests
s.Driver.Navigate().GoToUrl(invoiceUrl); s.Driver.Navigate().GoToUrl(invoiceUrl);
Assert.Contains("ReturnUrl", s.Driver.Url); Assert.Contains("ReturnUrl", s.Driver.Url);
s.GoToRegister(); s.GoToRegister();
// When logged in as different user we should not be able to access store and invoice details // When logged in as different user we should not be able to access store and invoice details
var bob = s.RegisterNewUser(); var bob = s.RegisterNewUser();
s.Driver.Navigate().GoToUrl(storeUrl); s.Driver.Navigate().GoToUrl(storeUrl);
@@ -900,13 +900,13 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("AccountKeys_0__MasterFingerprint")).GetAttribute("value")); s.Driver.FindElement(By.Id("AccountKeys_0__MasterFingerprint")).GetAttribute("value"));
Assert.Contains("m/84'/1'/0'", Assert.Contains("m/84'/1'/0'",
s.Driver.FindElement(By.Id("AccountKeys_0__AccountKeyPath")).GetAttribute("value")); s.Driver.FindElement(By.Id("AccountKeys_0__AccountKeyPath")).GetAttribute("value"));
s.Driver.FindElement(By.Id($"StoreNav-Wallet{cryptoCode}")).Click(); s.Driver.FindElement(By.Id($"StoreNav-Wallet{cryptoCode}")).Click();
// Make sure we can rescan, because we are admin! // Make sure we can rescan, because we are admin!
s.Driver.FindElement(By.Id("SectionNav-Rescan")).Click(); s.Driver.FindElement(By.Id("SectionNav-Rescan")).Click();
Assert.Contains("The batch size make sure", s.Driver.PageSource); Assert.Contains("The batch size make sure", s.Driver.PageSource);
// Check the tx sent earlier arrived // Check the tx sent earlier arrived
s.Driver.FindElement(By.Id("SectionNav-Transactions")).Click(); s.Driver.FindElement(By.Id("SectionNav-Transactions")).Click();
@@ -1110,7 +1110,7 @@ namespace BTCPayServer.Tests
//offline/external payout test //offline/external payout test
s.Driver.FindElement(By.Id("NotificationsHandle")).Click(); s.Driver.FindElement(By.Id("NotificationsHandle")).Click();
s.Driver.FindElement(By.CssSelector("#notificationsForm button")).Click(); s.Driver.FindElement(By.CssSelector("#notificationsForm button")).Click();
var newStore = s.CreateNewStore(); var newStore = s.CreateNewStore();
s.GenerateWallet("BTC", "", true, true); s.GenerateWallet("BTC", "", true, true);
var newWalletId = new WalletId(newStore.storeId, "BTC"); var newWalletId = new WalletId(newStore.storeId, "BTC");
@@ -1170,7 +1170,7 @@ namespace BTCPayServer.Tests
var paymentMethodOptions = s.Driver.FindElements(By.CssSelector("input[name='PaymentMethods']")); var paymentMethodOptions = s.Driver.FindElements(By.CssSelector("input[name='PaymentMethods']"));
Assert.Equal(2, paymentMethodOptions.Count); Assert.Equal(2, paymentMethodOptions.Count);
s.Driver.FindElement(By.Id("Name")).SendKeys("Lightning Test"); s.Driver.FindElement(By.Id("Name")).SendKeys("Lightning Test");
s.Driver.FindElement(By.Id("Amount")).Clear(); s.Driver.FindElement(By.Id("Amount")).Clear();
s.Driver.FindElement(By.Id("Amount")).SendKeys(payoutAmount.ToString()); 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")); Assert.DoesNotContain("show", s.Driver.FindElement(By.Id("LNURLSettings")).GetAttribute("class"));
s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true); s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true);
SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode); SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode);
// Topup Invoice test // Topup Invoice test
var i = s.CreateInvoice(storeId, null, cryptoCode); var i = s.CreateInvoice(storeId, null, cryptoCode);
s.GoToInvoiceCheckout(i); s.GoToInvoiceCheckout(i);
@@ -1331,7 +1331,7 @@ namespace BTCPayServer.Tests
// Initial bolt was cancelled // Initial bolt was cancelled
await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr); await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr);
}); });
await s.Server.CustomerLightningD.Pay(lnurlResponse2.Pr); await s.Server.CustomerLightningD.Pay(lnurlResponse2.Pr);
await TestUtils.EventuallyAsync(async () => await TestUtils.EventuallyAsync(async () =>
{ {
@@ -1374,7 +1374,7 @@ namespace BTCPayServer.Tests
await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr); await s.Server.CustomerLightningD.Pay(lnurlResponse.Pr);
Assert.Equal(new LightMoney(0.0000001m, LightMoneyUnit.BTC), Assert.Equal(new LightMoney(0.0000001m, LightMoneyUnit.BTC),
lnurlResponse2.GetPaymentRequest(network).MinimumAmount); lnurlResponse2.GetPaymentRequest(network).MinimumAmount);
s.GoToLightningSettings(s.StoreId, cryptoCode); s.GoToLightningSettings(s.StoreId, cryptoCode);
// LNURL is enabled and settings are expanded // LNURL is enabled and settings are expanded
Assert.True(s.Driver.FindElement(By.Id("LNURLEnabled")).Selected); 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.SetCheckbox(By.Id("LNURLStandardInvoiceEnabled"), false);
s.Driver.FindElement(By.Id("save")).Click(); s.Driver.FindElement(By.Id("save")).Click();
Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text); Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text);
i = s.CreateInvoice(storeId, 0.000001m, cryptoCode); i = s.CreateInvoice(storeId, 0.000001m, cryptoCode);
s.GoToInvoiceCheckout(i); s.GoToInvoiceCheckout(i);
s.Driver.FindElement(By.ClassName("payment__currencies_noborder")); s.Driver.FindElement(By.ClassName("payment__currencies_noborder"));
@@ -1398,7 +1398,7 @@ namespace BTCPayServer.Tests
s.Driver.SetCheckbox(By.Id("DisableBolt11PaymentMethod"), true); s.Driver.SetCheckbox(By.Id("DisableBolt11PaymentMethod"), true);
s.Driver.FindElement(By.Id("save")).Click(); s.Driver.FindElement(By.Id("save")).Click();
Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text); Assert.Contains($"{cryptoCode} Lightning settings successfully updated", s.FindAlertMessage().Text);
// Ensure the toggles are set correctly // Ensure the toggles are set correctly
s.GoToLightningSettings(s.StoreId, cryptoCode); 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 // 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("LNURLBech32Mode")).Selected);
Assert.False(s.Driver.FindElement(By.Id("LNURLStandardInvoiceEnabled")).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! //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); 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 // 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); i = s.CreateInvoice(storeId, null, cryptoCode);
s.GoToInvoiceCheckout(i); s.GoToInvoiceCheckout(i);
@@ -1419,7 +1419,7 @@ namespace BTCPayServer.Tests
lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value"); lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value");
Assert.StartsWith("lnurlp", lnurl); Assert.StartsWith("lnurlp", lnurl);
LNURL.LNURL.Parse(lnurl, out tag); LNURL.LNURL.Parse(lnurl, out tag);
s.GoToHome(); s.GoToHome();
var newStore = s.CreateNewStore(false); var newStore = s.CreateNewStore(false);
s.AddLightningNode(cryptoCode, LightningConnectionType.LndREST, false); s.AddLightningNode(cryptoCode, LightningConnectionType.LndREST, false);
@@ -1433,11 +1433,11 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("copy-tab")).Click(); s.Driver.FindElement(By.Id("copy-tab")).Click();
lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value"); lnurl = s.Driver.FindElement(By.CssSelector("input.checkoutTextbox")).GetAttribute("value");
parsed = LNURL.LNURL.Parse(lnurl, out tag); parsed = LNURL.LNURL.Parse(lnurl, out tag);
// Check that pull payment has lightning option // Check that pull payment has lightning option
s.GoToStore(s.StoreId, StoreNavPages.PullPayments); s.GoToStore(s.StoreId, StoreNavPages.PullPayments);
s.Driver.FindElement(By.Id("NewPullPayment")).Click(); 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("Name")).SendKeys("PP1");
s.Driver.FindElement(By.Id("Amount")).Clear(); s.Driver.FindElement(By.Id("Amount")).Clear();
s.Driver.FindElement(By.Id("Amount")).SendKeys("0.0000001"); 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")).Clear();
s.Driver.FindElement(By.Id("ClaimedAmount")).SendKeys("0.0000001" + Keys.Enter); s.Driver.FindElement(By.Id("ClaimedAmount")).SendKeys("0.0000001" + Keys.Enter);
s.FindAlertMessage(); s.FindAlertMessage();
s.GoToStore(s.StoreId, StoreNavPages.PullPayments); s.GoToStore(s.StoreId, StoreNavPages.PullPayments);
var payouts = s.Driver.FindElements(By.ClassName("pp-payout")); var payouts = s.Driver.FindElements(By.ClassName("pp-payout"));
payouts[0].Click(); payouts[0].Click();
@@ -1494,11 +1494,11 @@ namespace BTCPayServer.Tests
s.AddLightningNode("BTC", LightningConnectionType.LndREST, false); s.AddLightningNode("BTC", LightningConnectionType.LndREST, false);
//ensure ln address is not available as lnurl is not configured //ensure ln address is not available as lnurl is not configured
s.Driver.AssertElementNotFound(By.Id("StoreNav-LightningAddress")); s.Driver.AssertElementNotFound(By.Id("StoreNav-LightningAddress"));
s.GoToLightningSettings(s.StoreId, cryptoCode); s.GoToLightningSettings(s.StoreId, cryptoCode);
s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true); s.Driver.SetCheckbox(By.Id("LNURLEnabled"), true);
SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode); SudoForceSaveLightningSettingsRightNowAndFast(s, cryptoCode);
s.Driver.FindElement(By.Id("StoreNav-LightningAddress")).Click(); s.Driver.FindElement(By.Id("StoreNav-LightningAddress")).Click();
s.Driver.ToggleCollapse("AddAddress"); s.Driver.ToggleCollapse("AddAddress");
@@ -1534,8 +1534,8 @@ namespace BTCPayServer.Tests
var lnurl = new Uri(LNURL.LNURL.ExtractUriFromInternetIdentifier(value).ToString() var lnurl = new Uri(LNURL.LNURL.ExtractUriFromInternetIdentifier(value).ToString()
.Replace("https", "http")); .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) switch (value)
{ {
case { } v when v.StartsWith(lnaddress2): case { } v when v.StartsWith(lnaddress2):
@@ -1562,20 +1562,20 @@ namespace BTCPayServer.Tests
var code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value"); var code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value");
s.Driver.FindElement(By.Id("regeneratecode")).Click(); s.Driver.FindElement(By.Id("regeneratecode")).Click();
Assert.NotEqual(code, s.Driver.FindElement(By.Id("logincode")).GetAttribute("value")); Assert.NotEqual(code, s.Driver.FindElement(By.Id("logincode")).GetAttribute("value"));
code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value"); code = s.Driver.FindElement(By.Id("logincode")).GetAttribute("value");
s.Logout(); s.Logout();
s.GoToLogin(); s.GoToLogin();
s.Driver.SetAttribute("LoginCode", "value", "bad code"); s.Driver.SetAttribute("LoginCode", "value", "bad code");
s.Driver.InvokeJSFunction("logincode-form", "submit"); s.Driver.InvokeJSFunction("logincode-form", "submit");
s.Driver.SetAttribute("LoginCode", "value", code); s.Driver.SetAttribute("LoginCode", "value", code);
s.Driver.InvokeJSFunction("logincode-form", "submit"); s.Driver.InvokeJSFunction("logincode-form", "submit");
s.GoToProfile(); s.GoToProfile();
Assert.Contains(user, s.Driver.PageSource); Assert.Contains(user, s.Driver.PageSource);
} }
// For god know why, selenium have problems clicking on the save button, resulting in ultimate hacks // For god know why, selenium have problems clicking on the save button, resulting in ultimate hacks
// to make it works. // to make it works.

View File

@@ -5,6 +5,7 @@ using System.Net.Http;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Client; using BTCPayServer.Client;
using BTCPayServer.Client.Models; using BTCPayServer.Client.Models;
using BTCPayServer.Controllers; using BTCPayServer.Controllers;
@@ -14,6 +15,7 @@ using BTCPayServer.Lightning;
using BTCPayServer.Lightning.CLightning; using BTCPayServer.Lightning.CLightning;
using BTCPayServer.Models.AccountViewModels; using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Models.StoreViewModels; using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Payments.PayJoin.Sender; using BTCPayServer.Payments.PayJoin.Sender;
using BTCPayServer.Services; using BTCPayServer.Services;
using BTCPayServer.Services.Stores; using BTCPayServer.Services.Stores;
@@ -23,8 +25,6 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Operations;
using NBitcoin; using NBitcoin;
using BTCPayServer.BIP78.Sender;
using BTCPayServer.Payments.Lightning;
using NBitcoin.Payment; using NBitcoin.Payment;
using NBitpayClient; using NBitpayClient;
using NBXplorer.DerivationStrategy; using NBXplorer.DerivationStrategy;
@@ -141,7 +141,7 @@ namespace BTCPayServer.Tests
modify(paymentMethods); modify(paymentMethods);
await storeController.PaymentMethods(paymentMethods); await storeController.PaymentMethods(paymentMethods);
} }
public async Task ModifyWalletSettings(Action<WalletSettingsViewModel> modify) public async Task ModifyWalletSettings(Action<WalletSettingsViewModel> modify)
{ {
var storeController = GetController<StoresController>(); var storeController = GetController<StoresController>();
@@ -150,7 +150,7 @@ namespace BTCPayServer.Tests
modify(walletSettings); modify(walletSettings);
storeController.UpdateWalletSettings(walletSettings).GetAwaiter().GetResult(); storeController.UpdateWalletSettings(walletSettings).GetAwaiter().GetResult();
} }
public async Task ModifyOnchainPaymentSettings(Action<WalletSettingsViewModel> modify) public async Task ModifyOnchainPaymentSettings(Action<WalletSettingsViewModel> modify)
{ {
var storeController = GetController<StoresController>(); var storeController = GetController<StoresController>();
@@ -227,7 +227,7 @@ namespace BTCPayServer.Tests
//this addresses an obscure issue where LockSubscription is unintentionally set to "true", //this addresses an obscure issue where LockSubscription is unintentionally set to "true",
//resulting in a large number of tests failing. //resulting in a large number of tests failing.
if (account.RegisteredUserId == null) if (account.RegisteredUserId == null)
{ {
var settings = parent.PayTester.GetService<SettingsRepository>(); var settings = parent.PayTester.GetService<SettingsRepository>();
var policies = await settings.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings(); var policies = await settings.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings();
@@ -470,7 +470,7 @@ namespace BTCPayServer.Tests
public TEvent AssertHasWebhookEvent<TEvent>(WebhookEventType eventType, Action<TEvent> assert) where TEvent : class public TEvent AssertHasWebhookEvent<TEvent>(WebhookEventType eventType, Action<TEvent> assert) where TEvent : class
{ {
int retry = 0; int retry = 0;
retry: retry:
foreach (var evt in WebhookEvents) foreach (var evt in WebhookEvents)
{ {
if (evt.Type == eventType) if (evt.Type == eventType)

View File

@@ -159,7 +159,7 @@ namespace BTCPayServer.Tests
Assert.True(valid); Assert.True(valid);
} }
} }
[Fact] [Fact]
[Trait("Integration", "Integration")] [Trait("Integration", "Integration")]
public async Task EnsureSwaggerPermissionsDocumented() public async Task EnsureSwaggerPermissionsDocumented()
@@ -171,7 +171,7 @@ namespace BTCPayServer.Tests
var description = 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"; "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 = var storePolicies =
ManageController.AddApiKeyViewModel.PermissionValueItem.PermissionDescriptions.Where(pair => ManageController.AddApiKeyViewModel.PermissionValueItem.PermissionDescriptions.Where(pair =>
Policies.IsStorePolicy(pair.Key) && !pair.Key.EndsWith(":", StringComparison.InvariantCulture)); Policies.IsStorePolicy(pair.Key) && !pair.Key.EndsWith(":", StringComparison.InvariantCulture));
@@ -189,7 +189,7 @@ namespace BTCPayServer.Tests
.Replace("#STOREPERMISSIONS#", .Replace("#STOREPERMISSIONS#",
string.Join("\n", storePolicies.Select(pair => $"* `{pair.Key}`: {pair.Value.Title}"))); string.Join("\n", storePolicies.Select(pair => $"* `{pair.Key}`: {pair.Value.Title}")));
TestLogs.LogInformation(description); TestLogs.LogInformation(description);
var sresp = Assert var sresp = Assert
.IsType<JsonResult>(await tester.PayTester.GetController<HomeController>(acc.UserId, acc.StoreId) .IsType<JsonResult>(await tester.PayTester.GetController<HomeController>(acc.UserId, acc.StoreId)
.Swagger()).Value.ToJson(); .Swagger()).Value.ToJson();
@@ -350,7 +350,7 @@ namespace BTCPayServer.Tests
Assert.Equal(0, result.Content.Headers.ContentLength.Value); Assert.Equal(0, result.Content.Headers.ContentLength.Value);
} }
} }
[Fact(Timeout = 60 * 2 * 1000)] [Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")] [Trait("Integration", "Integration")]
[Trait("Lightning", "Lightning")] [Trait("Lightning", "Lightning")]
@@ -371,7 +371,7 @@ namespace BTCPayServer.Tests
{ {
await tester.ExplorerNode.SendToAddressAsync( await tester.ExplorerNode.SendToAddressAsync(
BitcoinAddress.Create(invoice.BitcoinAddress, Network.RegTest), Money.Coins(0.00005m)); 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); await tester.ExplorerNode.GenerateAsync(1);
Invoice newInvoice = null; Invoice newInvoice = null;
await TestUtils.EventuallyAsync(async () => await TestUtils.EventuallyAsync(async () =>
@@ -384,7 +384,7 @@ namespace BTCPayServer.Tests
Assert.Equal(newInvoice.BtcDue.GetValue(), Assert.Equal(newInvoice.BtcDue.GetValue(),
BOLT11PaymentRequest.Parse(newBolt11, Network.RegTest).MinimumAmount.ToDecimal(LightMoneyUnit.BTC)); BOLT11PaymentRequest.Parse(newBolt11, Network.RegTest).MinimumAmount.ToDecimal(LightMoneyUnit.BTC));
}, 40000); }, 40000);
TestLogs.LogInformation($"Paying invoice {newInvoice.Id} remaining due amount {newInvoice.BtcDue.GetValue()} via lightning"); TestLogs.LogInformation($"Paying invoice {newInvoice.Id} remaining due amount {newInvoice.BtcDue.GetValue()} via lightning");
var evt = await tester.WaitForEvent<InvoiceDataChangedEvent>(async () => var evt = await tester.WaitForEvent<InvoiceDataChangedEvent>(async () =>
{ {
@@ -401,7 +401,7 @@ namespace BTCPayServer.Tests
{ {
await tester.SendLightningPaymentAsync(invoice); await tester.SendLightningPaymentAsync(invoice);
}); });
//NOTE: Eclair does not support cancelling invoice so the below test case would make sense for it //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 "); // TestLogs.LogInformation($"Paying invoice {invoice.Id} original full amount bolt11 invoice ");
// evt = await tester.WaitForEvent<InvoiceDataChangedEvent>(async () => // evt = await tester.WaitForEvent<InvoiceDataChangedEvent>(async () =>
@@ -1354,7 +1354,7 @@ namespace BTCPayServer.Tests
rng = new Random(seed); rng = new Random(seed);
TestLogs.LogInformation("Seed: " + seed); TestLogs.LogInformation("Seed: " + seed);
foreach (var networkFeeMode in Enum.GetValues(typeof(NetworkFeeMode)).Cast<NetworkFeeMode>()) foreach (var networkFeeMode in Enum.GetValues(typeof(NetworkFeeMode)).Cast<NetworkFeeMode>())
{ {
await user.SetNetworkFeeMode(networkFeeMode); await user.SetNetworkFeeMode(networkFeeMode);
await AssertTopUpBtcPrice(tester, user, Money.Coins(1.0m), 5000.0m, 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); 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); Assert.True($"bitcoin:{paymentMethodSecond.BtcAddress.ToUpperInvariant()}" == split);
// Fallback lightning invoice should be uppercase inside the QR code. // 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); Assert.True(lightningFallback.ToUpperInvariant() == lightningFallback);
} }
} }
@@ -1990,7 +1990,7 @@ namespace BTCPayServer.Tests
}); });
} }
} }
[Fact(Timeout = LongRunningTestTimeout)] [Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")] [Trait("Integration", "Integration")]
public async Task CanCreateAndDeleteApps() public async Task CanCreateAndDeleteApps()
@@ -2043,7 +2043,7 @@ namespace BTCPayServer.Tests
var user = tester.NewAccount(); var user = tester.NewAccount();
user.GrantAccess(true); user.GrantAccess(true);
user.RegisterDerivationScheme("BTC"); user.RegisterDerivationScheme("BTC");
DateTimeOffset expiration = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(21); DateTimeOffset expiration = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(21);
// This should fail, the amount is too low to be above the dust limit of bitcoin // 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() var zeroInvoice = await greenfield.CreateInvoice(user.StoreId, new CreateInvoiceRequest()
{ {
Amount = 0m, Amount = 0m,
Currency = "USD" Currency = "USD"
}); });
Assert.Equal(InvoiceStatus.New, zeroInvoice.Status); Assert.Equal(InvoiceStatus.New, zeroInvoice.Status);
await TestUtils.EventuallyAsync(async () => await TestUtils.EventuallyAsync(async () =>
@@ -2312,20 +2312,20 @@ namespace BTCPayServer.Tests
c => c =>
{ {
Assert.False(c.AfterExpiration); 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.NotNull(c.Payment);
Assert.Equal(invoice.BitcoinAddress, c.Payment.Destination); Assert.Equal(invoice.BitcoinAddress, c.Payment.Destination);
Assert.StartsWith(txId.ToString(), c.Payment.Id); Assert.StartsWith(txId.ToString(), c.Payment.Id);
}); });
user.AssertHasWebhookEvent<WebhookInvoicePaymentSettledEvent>(WebhookEventType.InvoicePaymentSettled, user.AssertHasWebhookEvent<WebhookInvoicePaymentSettledEvent>(WebhookEventType.InvoicePaymentSettled,
c => c =>
{ {
Assert.False(c.AfterExpiration); 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.NotNull(c.Payment);
Assert.Equal(invoice.BitcoinAddress, c.Payment.Destination); 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(); var acc = tester.NewAccount();
await acc.GrantAccessAsync(true); await acc.GrantAccessAsync(true);
await acc.CreateStoreAsync(); await acc.CreateStoreAsync();
// Test if legacy DerivationStrategy column is converted to DerivationStrategies // Test if legacy DerivationStrategy column is converted to DerivationStrategies
var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId); var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav"; var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav";
@@ -2540,7 +2540,7 @@ namespace BTCPayServer.Tests
Assert.Equal(derivation, v.AccountOriginal.ToString()); Assert.Equal(derivation, v.AccountOriginal.ToString());
Assert.Equal(xpub, v.SigningKey.ToString()); Assert.Equal(xpub, v.SigningKey.ToString());
Assert.Equal(xpub, v.GetSigningAccountKeySettings().AccountKey.ToString()); Assert.Equal(xpub, v.GetSigningAccountKeySettings().AccountKey.ToString());
await acc.RegisterLightningNodeAsync("BTC", LightningConnectionType.CLightning, true); await acc.RegisterLightningNodeAsync("BTC", LightningConnectionType.CLightning, true);
store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId); store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
var lnMethod = store.GetSupportedPaymentMethods(tester.NetworkProvider).OfType<LightningSupportedPaymentMethod>().First(); var lnMethod = store.GetSupportedPaymentMethods(tester.NetworkProvider).OfType<LightningSupportedPaymentMethod>().First();
@@ -2687,37 +2687,37 @@ namespace BTCPayServer.Tests
var settings = tester.PayTester.GetService<SettingsRepository>(); var settings = tester.PayTester.GetService<SettingsRepository>();
var emailSenderFactory = tester.PayTester.GetService<EmailSenderFactory>(); var emailSenderFactory = tester.PayTester.GetService<EmailSenderFactory>();
Assert.Null(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()); Assert.Null(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings());
Assert.Null(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()); Assert.Null(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings());
await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = false }); await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = false });
await settings.UpdateSetting(new EmailSettings() await settings.UpdateSetting(new EmailSettings()
{ {
From = "admin@admin.com", From = "admin@admin.com",
Login = "admin@admin.com", Login = "admin@admin.com",
Password = "admin@admin.com", Password = "admin@admin.com",
Port = 1234, Port = 1234,
Server = "admin.com", Server = "admin.com",
}); });
Assert.Equal("admin@admin.com",(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); Assert.Equal("admin@admin.com", (await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Equal("admin@admin.com",(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); Assert.Equal("admin@admin.com", (await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = true }); await settings.UpdateSetting(new PoliciesSettings() { DisableStoresToUseServerEmailSettings = true });
Assert.Equal("admin@admin.com",(await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login); Assert.Equal("admin@admin.com", (await Assert.IsType<ServerEmailSender>(await emailSenderFactory.GetEmailSender()).GetEmailSettings()).Login);
Assert.Null(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()); Assert.Null(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings());
Assert.IsType<RedirectToActionResult>(await acc.GetController<StoresController>().Emails(acc.StoreId, new EmailsViewModel(new EmailSettings() Assert.IsType<RedirectToActionResult>(await acc.GetController<StoresController>().Emails(acc.StoreId, new EmailsViewModel(new EmailSettings()
{ {
From = "store@store.com", From = "store@store.com",
Login = "store@store.com", Login = "store@store.com",
Password = "store@store.com", Password = "store@store.com",
Port = 1234, Port = 1234,
Server = "store.com" Server = "store.com"
}), "")); }), ""));
Assert.Equal("store@store.com",(await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login); Assert.Equal("store@store.com", (await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
} }
} }

View File

@@ -31,7 +31,7 @@ namespace BTCPayServer.Components.MainNav
AppService appService, AppService appService,
StoreRepository storeRepo, StoreRepository storeRepo,
StoresController storesController, StoresController storesController,
BTCPayNetworkProvider networkProvider, BTCPayNetworkProvider networkProvider,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
PaymentMethodHandlerDictionary paymentMethodHandlerDictionary) PaymentMethodHandlerDictionary paymentMethodHandlerDictionary)
{ {
@@ -53,13 +53,13 @@ namespace BTCPayServer.Components.MainNav
if (store != null) if (store != null)
{ {
var storeBlob = store.GetStoreBlob(); var storeBlob = store.GetStoreBlob();
// Wallets // Wallets
_storesController.AddPaymentMethods(store, storeBlob, _storesController.AddPaymentMethods(store, storeBlob,
out var derivationSchemes, out var lightningNodes); out var derivationSchemes, out var lightningNodes);
vm.DerivationSchemes = derivationSchemes; vm.DerivationSchemes = derivationSchemes;
vm.LightningNodes = lightningNodes; vm.LightningNodes = lightningNodes;
// Apps // Apps
var apps = await _appService.GetAllApps(UserId, false, store.Id); var apps = await _appService.GetAllApps(UserId, false, store.Id);
vm.Apps = apps.Select(a => new StoreApp vm.Apps = apps.Select(a => new StoreApp
@@ -70,7 +70,7 @@ namespace BTCPayServer.Components.MainNav
IsOwner = a.IsOwner IsOwner = a.IsOwner
}).ToList(); }).ToList();
} }
return View(vm); return View(vm);
} }

View File

@@ -12,7 +12,7 @@ namespace BTCPayServer.Components.MainNav
public List<StoreApp> Apps { get; set; } public List<StoreApp> Apps { get; set; }
public bool AltcoinsBuild { get; set; } public bool AltcoinsBuild { get; set; }
} }
public class StoreApp public class StoreApp
{ {
public string Id { get; set; } public string Id { get; set; }

View File

@@ -15,7 +15,7 @@ namespace BTCPayServer.Components.StoreSelector
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
public StoreSelector( public StoreSelector(
StoreRepository storeRepo, StoreRepository storeRepo,
BTCPayNetworkProvider networkProvider, BTCPayNetworkProvider networkProvider,
UserManager<ApplicationUser> userManager) UserManager<ApplicationUser> userManager)
{ {
@@ -47,14 +47,14 @@ namespace BTCPayServer.Components.StoreSelector
}; };
}) })
.ToList(); .ToList();
var vm = new StoreSelectorViewModel var vm = new StoreSelectorViewModel
{ {
Options = options, Options = options,
CurrentStoreId = currentStore?.Id, CurrentStoreId = currentStore?.Id,
CurrentDisplayName = currentStore?.StoreName CurrentDisplayName = currentStore?.StoreName
}; };
return View(vm); return View(vm);
} }
} }

View File

@@ -8,7 +8,7 @@ namespace BTCPayServer.Components.StoreSelector
public string CurrentStoreId { get; set; } public string CurrentStoreId { get; set; }
public string CurrentDisplayName { get; set; } public string CurrentDisplayName { get; set; }
} }
public class StoreSelectorOption public class StoreSelectorOption
{ {
public bool Selected { get; set; } public bool Selected { get; set; }

View File

@@ -1,8 +1,8 @@
using System; using System;
using BTCPayServer.Configuration;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using BTCPayServer.Configuration;
using BTCPayServer.Logging; using BTCPayServer.Logging;
using BTCPayServer.SSH; using BTCPayServer.SSH;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -59,20 +59,20 @@ namespace BTCPayServer.Configuration
public void LoadArgs(IConfiguration conf, Logs Logs) public void LoadArgs(IConfiguration conf, Logs Logs)
{ {
NetworkType = DefaultConfiguration.GetNetworkType(conf); NetworkType = DefaultConfiguration.GetNetworkType(conf);
Logs.Configuration.LogInformation("Network: " + NetworkType.ToString()); Logs.Configuration.LogInformation("Network: " + NetworkType.ToString());
if (conf.GetOrDefault<bool>("launchsettings", false) && NetworkType != ChainName.Regtest) if (conf.GetOrDefault<bool>("launchsettings", false) && NetworkType != ChainName.Regtest)
throw new ConfigException($"You need to run BTCPayServer with the run.sh or run.ps1 script"); throw new ConfigException($"You need to run BTCPayServer with the run.sh or run.ps1 script");
BundleJsCss = conf.GetOrDefault<bool>("bundlejscss", true); BundleJsCss = conf.GetOrDefault<bool>("bundlejscss", true);
DockerDeployment = conf.GetOrDefault<bool>("dockerdeployment", true); DockerDeployment = conf.GetOrDefault<bool>("dockerdeployment", true);
TorrcFile = conf.GetOrDefault<string>("torrcfile", null); TorrcFile = conf.GetOrDefault<string>("torrcfile", null);
TorServices = conf.GetOrDefault<string>("torservices", null) TorServices = conf.GetOrDefault<string>("torservices", null)
?.Split(new[] {';', ','}, StringSplitOptions.RemoveEmptyEntries); ?.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (!string.IsNullOrEmpty(TorrcFile) && TorServices != null) if (!string.IsNullOrEmpty(TorrcFile) && TorServices != null)
throw new ConfigException($"torrcfile or torservices should be provided, but not both"); throw new ConfigException($"torrcfile or torservices should be provided, but not both");
@@ -145,7 +145,7 @@ namespace BTCPayServer.Configuration
DisableRegistration = conf.GetOrDefault<bool>("disable-registration", true); DisableRegistration = conf.GetOrDefault<bool>("disable-registration", true);
PluginRemote = conf.GetOrDefault("plugin-remote", "btcpayserver/btcpayserver-plugins"); 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); CheatMode = conf.GetOrDefault("cheatmode", false);
if (CheatMode && this.NetworkType == ChainName.Mainnet) if (CheatMode && this.NetworkType == ChainName.Mainnet)
throw new ConfigException($"cheatmode can't be used on mainnet"); throw new ConfigException($"cheatmode can't be used on mainnet");

View File

@@ -8,4 +8,4 @@ namespace BTCPayServer.Configuration
public Uri ExplorerUri { get; internal set; } public Uri ExplorerUri { get; internal set; }
public string CookieFile { get; internal set; } public string CookieFile { get; internal set; }
} }
} }

View File

@@ -108,8 +108,8 @@ namespace BTCPayServer.Controllers
ModelState.AddModelError(string.Empty, ModelState.AddModelError(string.Empty,
"Login code was invalid"); "Login code was invalid");
return await Login(returnUrl, null); 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); _logger.LogInformation("User with ID {UserId} logged in with a login code.", user.Id);
await _signInManager.SignInAsync(user, false, "LoginCode"); await _signInManager.SignInAsync(user, false, "LoginCode");
@@ -150,9 +150,9 @@ namespace BTCPayServer.Controllers
ModelState.AddModelError(string.Empty, "Invalid login attempt."); ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model); return View(model);
} }
var fido2Devices = await _fido2Service.HasCredentials(user.Id); 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)) if (await _userManager.CheckPasswordAsync(user, model.Password))
{ {
@@ -171,7 +171,7 @@ namespace BTCPayServer.Controllers
return View("SecondaryLogin", new SecondaryLoginViewModel() return View("SecondaryLogin", new SecondaryLoginViewModel()
{ {
LoginWith2FaViewModel = twoFModel, LoginWith2FaViewModel = twoFModel,
LoginWithFido2ViewModel = fido2Devices? await BuildFido2ViewModel(model.RememberMe, user): null, LoginWithFido2ViewModel = fido2Devices ? await BuildFido2ViewModel(model.RememberMe, user) : null,
}); });
} }
else else
@@ -464,8 +464,13 @@ namespace BTCPayServer.Controllers
return RedirectToAction(nameof(HomeController.Index), "Home"); return RedirectToAction(nameof(HomeController.Index), "Home");
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, RequiresEmailConfirmation = policies.RequiresConfirmedEmail, var user = new ApplicationUser
Created = DateTimeOffset.UtcNow }; {
UserName = model.Email,
Email = model.Email,
RequiresEmailConfirmation = policies.RequiresConfirmedEmail,
Created = DateTimeOffset.UtcNow
};
var result = await _userManager.CreateAsync(user, model.Password); var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded) if (result.Succeeded)
{ {
@@ -534,17 +539,17 @@ namespace BTCPayServer.Controllers
{ {
throw new ApplicationException($"Unable to load user with ID '{userId}'."); throw new ApplicationException($"Unable to load user with ID '{userId}'.");
} }
var result = await _userManager.ConfirmEmailAsync(user, code); var result = await _userManager.ConfirmEmailAsync(user, code);
if (!await _userManager.HasPasswordAsync(user)) if (!await _userManager.HasPasswordAsync(user))
{ {
TempData.SetStatusMessageModel(new StatusMessageModel() TempData.SetStatusMessageModel(new StatusMessageModel()
{ {
Severity = StatusMessageModel.StatusSeverity.Info, Severity = StatusMessageModel.StatusSeverity.Info,
Message = "Your email has been confirmed but you still need to set your password." 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) if (result.Succeeded)
@@ -554,7 +559,7 @@ namespace BTCPayServer.Controllers
Severity = StatusMessageModel.StatusSeverity.Success, Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Your email has been confirmed." Message = "Your email has been confirmed."
}); });
return RedirectToAction("Login", new {email = user.Email}); return RedirectToAction("Login", new { email = user.Email });
} }
return View("Error"); return View("Error");
@@ -583,7 +588,8 @@ namespace BTCPayServer.Controllers
} }
_eventAggregator.Publish(new UserPasswordResetRequestedEvent() _eventAggregator.Publish(new UserPasswordResetRequestedEvent()
{ {
User = user, RequestUri = Request.GetAbsoluteRootUri() User = user,
RequestUri = Request.GetAbsoluteRootUri()
}); });
return RedirectToAction(nameof(ForgotPasswordConfirmation)); return RedirectToAction(nameof(ForgotPasswordConfirmation));
} }
@@ -614,7 +620,7 @@ namespace BTCPayServer.Controllers
email = user?.Email; 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); return View(model);
} }
@@ -639,7 +645,8 @@ namespace BTCPayServer.Controllers
{ {
TempData.SetStatusMessageModel(new StatusMessageModel() TempData.SetStatusMessageModel(new StatusMessageModel()
{ {
Severity = StatusMessageModel.StatusSeverity.Success, Message = "Password successfully set." Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Password successfully set."
}); });
return RedirectToAction(nameof(Login)); return RedirectToAction(nameof(Login));
} }

View File

@@ -30,7 +30,7 @@ namespace BTCPayServer.Controllers
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
var settings = app.GetSettings<CrowdfundSettings>(); var settings = app.GetSettings<CrowdfundSettings>();
var vm = new UpdateCrowdfundViewModel var vm = new UpdateCrowdfundViewModel
{ {
@@ -68,14 +68,14 @@ namespace BTCPayServer.Controllers
}; };
return View(vm); return View(vm);
} }
[HttpPost("{appId}/settings/crowdfund")] [HttpPost("{appId}/settings/crowdfund")]
public async Task<IActionResult> UpdateCrowdfund(string appId, UpdateCrowdfundViewModel vm, string command) public async Task<IActionResult> UpdateCrowdfund(string appId, UpdateCrowdfundViewModel vm, string command)
{ {
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
vm.TargetCurrency = await GetStoreDefaultCurrentIfEmpty(app.StoreDataId, vm.TargetCurrency); vm.TargetCurrency = await GetStoreDefaultCurrentIfEmpty(app.StoreDataId, vm.TargetCurrency);
if (_currencies.GetCurrencyData(vm.TargetCurrency, false) == null) if (_currencies.GetCurrencyData(vm.TargetCurrency, false) == null)
ModelState.AddModelError(nameof(vm.TargetCurrency), "Invalid currency"); ModelState.AddModelError(nameof(vm.TargetCurrency), "Invalid currency");

View File

@@ -76,7 +76,7 @@ namespace BTCPayServer.Controllers
public string CustomTipText { get; set; } = CUSTOM_TIP_TEXT_DEF; public string CustomTipText { get; set; } = CUSTOM_TIP_TEXT_DEF;
public static readonly int[] CUSTOM_TIP_PERCENTAGES_DEF = new int[] { 15, 18, 20 }; public static readonly int[] CUSTOM_TIP_PERCENTAGES_DEF = new int[] { 15, 18, 20 };
public int[] CustomTipPercentages { get; set; } = CUSTOM_TIP_PERCENTAGES_DEF; public int[] CustomTipPercentages { get; set; } = CUSTOM_TIP_PERCENTAGES_DEF;
public string CustomCSSLink { get; set; } public string CustomCSSLink { get; set; }
public string EmbeddedCSS { get; set; } public string EmbeddedCSS { get; set; }
@@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
var settings = app.GetSettings<PointOfSaleSettings>(); var settings = app.GetSettings<PointOfSaleSettings>();
settings.DefaultView = settings.EnableShoppingCart ? PosViewType.Cart : settings.DefaultView; settings.DefaultView = settings.EnableShoppingCart ? PosViewType.Cart : settings.DefaultView;
settings.EnableShoppingCart = false; settings.EnableShoppingCart = false;
@@ -167,7 +167,7 @@ namespace BTCPayServer.Controllers
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return View(vm); return View(vm);
@@ -213,14 +213,14 @@ namespace BTCPayServer.Controllers
TempData[WellKnownTempData.SuccessMessage] = "App updated"; TempData[WellKnownTempData.SuccessMessage] = "App updated";
return RedirectToAction(nameof(UpdatePointOfSale), new { appId }); return RedirectToAction(nameof(UpdatePointOfSale), new { appId });
} }
private int[] ListSplit(string list, string separator = ",") private int[] ListSplit(string list, string separator = ",")
{ {
if (string.IsNullOrEmpty(list)) if (string.IsNullOrEmpty(list))
{ {
return Array.Empty<int>(); return Array.Empty<int>();
} }
// Remove all characters except numeric and comma // Remove all characters except numeric and comma
Regex charsToDestroy = new Regex(@"[^\d|\" + separator + "]"); Regex charsToDestroy = new Regex(@"[^\d|\" + separator + "]");
list = charsToDestroy.Replace(list, ""); list = charsToDestroy.Replace(list, "");

View File

@@ -1,9 +1,9 @@
using System; using System;
using BTCPayServer.Data;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants; using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Client; using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Models; using BTCPayServer.Models;
using BTCPayServer.Models.AppViewModels; using BTCPayServer.Models.AppViewModels;
using BTCPayServer.Services.Apps; using BTCPayServer.Services.Apps;
@@ -41,10 +41,10 @@ namespace BTCPayServer.Controllers
private readonly AppService _appService; private readonly AppService _appService;
public string CreatedAppId { get; set; } public string CreatedAppId { get; set; }
[HttpGet("/stores/{storeId}/apps")] [HttpGet("/stores/{storeId}/apps")]
public async Task<IActionResult> ListApps( public async Task<IActionResult> ListApps(
string storeId, string storeId,
string sortOrder = null, string sortOrder = null,
string sortOrderColumn = null string sortOrderColumn = null
) )
@@ -52,9 +52,9 @@ namespace BTCPayServer.Controllers
var store = GetCurrentStore(); var store = GetCurrentStore();
var apps = await _appService.GetAllApps(GetUserId(), false, store.Id); 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) switch (sortOrderColumn)
{ {
@@ -80,7 +80,7 @@ namespace BTCPayServer.Controllers
break; break;
} }
} }
return View(new ListAppsViewModel return View(new ListAppsViewModel
{ {
Apps = apps Apps = apps
@@ -151,7 +151,7 @@ namespace BTCPayServer.Controllers
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
return View("Confirm", new ConfirmModel("Delete app", $"The app <strong>{app.Name}</strong> and its settings will be permanently deleted. Are you sure?", "Delete")); return View("Confirm", new ConfirmModel("Delete app", $"The app <strong>{app.Name}</strong> and its settings will be permanently deleted. Are you sure?", "Delete"));
} }
@@ -161,10 +161,10 @@ namespace BTCPayServer.Controllers
var app = GetCurrentApp(); var app = GetCurrentApp();
if (app == null) if (app == null)
return NotFound(); return NotFound();
if (await _appService.DeleteApp(app)) if (await _appService.DeleteApp(app))
TempData[WellKnownTempData.SuccessMessage] = "App deleted successfully."; TempData[WellKnownTempData.SuccessMessage] = "App deleted successfully.";
return RedirectToAction(nameof(ListApps), new { storeId = app.StoreDataId }); return RedirectToAction(nameof(ListApps), new { storeId = app.StoreDataId });
} }
@@ -180,7 +180,7 @@ namespace BTCPayServer.Controllers
private string GetUserId() => _userManager.GetUserId(User); private string GetUserId() => _userManager.GetUserId(User);
private StoreData GetCurrentStore() => HttpContext.GetStoreData(); private StoreData GetCurrentStore() => HttpContext.GetStoreData();
private AppData GetCurrentApp() => HttpContext.GetAppData(); private AppData GetCurrentApp() => HttpContext.GetAppData();
} }
} }

View File

@@ -43,19 +43,19 @@ namespace BTCPayServer.Controllers
[HttpGet("/apps/{appId}")] [HttpGet("/apps/{appId}")]
public async Task<IActionResult> RedirectToApp(string appId) public async Task<IActionResult> RedirectToApp(string appId)
{ {
switch ((await _AppService.GetApp(appId, null)).AppType) switch ((await _AppService.GetApp(appId, null)).AppType)
{ {
case nameof(AppType.Crowdfund): case nameof(AppType.Crowdfund):
return RedirectToAction("ViewCrowdfund", new {appId}); return RedirectToAction("ViewCrowdfund", new { appId });
case nameof(AppType.PointOfSale): case nameof(AppType.PointOfSale):
return RedirectToAction("ViewPointOfSale", new {appId}); return RedirectToAction("ViewPointOfSale", new { appId });
} }
return NotFound(); return NotFound();
} }
[HttpGet] [HttpGet]
[Route("/")] [Route("/")]
[Route("/apps/{appId}/pos/{viewType?}")] [Route("/apps/{appId}/pos/{viewType?}")]
@@ -122,7 +122,7 @@ namespace BTCPayServer.Controllers
string notificationUrl, string notificationUrl,
string redirectUrl, string redirectUrl,
string choiceKey, string choiceKey,
string posData = null, string posData = null,
RequiresRefundEmail requiresRefundEmail = RequiresRefundEmail.InheritFromStore, RequiresRefundEmail requiresRefundEmail = RequiresRefundEmail.InheritFromStore,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
@@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers
if (choice == null) if (choice == null)
return NotFound(); return NotFound();
title = choice.Title; title = choice.Title;
if (choice.Price.Type == ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup) if (choice.Price.Type == ViewPointOfSaleViewModel.Item.ItemPrice.ItemPriceType.Topup)
{ {
price = null; price = null;
} }
@@ -160,7 +160,7 @@ namespace BTCPayServer.Controllers
if (amount > price) if (amount > price)
price = amount; price = amount;
} }
if (choice.Inventory.HasValue) if (choice.Inventory.HasValue)
{ {
@@ -230,7 +230,7 @@ namespace BTCPayServer.Controllers
PosData = string.IsNullOrEmpty(posData) ? null : posData, PosData = string.IsNullOrEmpty(posData) ? null : posData,
RedirectAutomatically = settings.RedirectAutomatically, RedirectAutomatically = settings.RedirectAutomatically,
SupportedTransactionCurrencies = paymentMethods, SupportedTransactionCurrencies = paymentMethods,
RequiresRefundEmail = requiresRefundEmail == RequiresRefundEmail.InheritFromStore RequiresRefundEmail = requiresRefundEmail == RequiresRefundEmail.InheritFromStore
? store.GetStoreBlob().RequiresRefundEmail ? store.GetStoreBlob().RequiresRefundEmail
: requiresRefundEmail == RequiresRefundEmail.On, : requiresRefundEmail == RequiresRefundEmail.On,
}, store, HttpContext.Request.GetAbsoluteRoot(), }, 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."); return NotFound("A Target Currency must be set for this app in order to be loadable.");
} }
var appInfo = await GetAppInfo(appId); var appInfo = await GetAppInfo(appId);
if (settings.Enabled) if (settings.Enabled)
return View(appInfo); return View(appInfo);
if (!isAdmin) if (!isAdmin)
@@ -292,7 +292,7 @@ namespace BTCPayServer.Controllers
[DomainMappingConstraintAttribute(AppType.Crowdfund)] [DomainMappingConstraintAttribute(AppType.Crowdfund)]
public async Task<IActionResult> ContributeToCrowdfund(string appId, ContributeToCrowdfund request, CancellationToken cancellationToken) public async Task<IActionResult> ContributeToCrowdfund(string appId, ContributeToCrowdfund request, CancellationToken cancellationToken)
{ {
var app = await _AppService.GetApp(appId, AppType.Crowdfund, true); var app = await _AppService.GetApp(appId, AppType.Crowdfund, true);
if (app == null) if (app == null)

View File

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

View File

@@ -53,7 +53,7 @@ namespace BTCPayServer.Controllers.GreenField
[FromQuery] [FromQuery]
[ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))] [ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))]
DateTimeOffset? startDate = null, DateTimeOffset? startDate = null,
[FromQuery] [FromQuery]
[ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))] [ModelBinder(typeof(ModelBinders.DateTimeOffsetModelBinder))]
DateTimeOffset? endDate = null, DateTimeOffset? endDate = null,
[FromQuery] string? textSearch = null, [FromQuery] string? textSearch = null,
@@ -82,7 +82,7 @@ namespace BTCPayServer.Controllers.GreenField
{ {
Skip = skip, Skip = skip,
Take = take, Take = take,
StoreId = new[] {store.Id}, StoreId = new[] { store.Id },
IncludeArchived = includeArchived, IncludeArchived = includeArchived,
StartDate = startDate, StartDate = startDate,
EndDate = endDate, EndDate = endDate,
@@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers.GreenField
return Ok(invoices.Select(ToModel)); return Ok(invoices.Select(ToModel));
} }
[Authorize(Policy = Policies.CanViewInvoices, [Authorize(Policy = Policies.CanViewInvoices,
AuthenticationSchemes = AuthenticationSchemes.Greenfield)] AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}")] [HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}")]
@@ -283,7 +283,7 @@ namespace BTCPayServer.Controllers.GreenField
await _invoiceRepository.ToggleInvoiceArchival(invoiceId, false, storeId); await _invoiceRepository.ToggleInvoiceArchival(invoiceId, false, storeId);
return await GetInvoice(storeId, invoiceId); return await GetInvoice(storeId, invoiceId);
} }
[Authorize(Policy = Policies.CanViewInvoices, [Authorize(Policy = Policies.CanViewInvoices,
AuthenticationSchemes = AuthenticationSchemes.Greenfield)] AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}/payment-methods")] [HttpGet("~/api/v1/stores/{storeId}/invoices/{invoiceId}/payment-methods")]
@@ -369,7 +369,7 @@ namespace BTCPayServer.Controllers.GreenField
}; };
}).ToArray(); }).ToArray();
} }
public static InvoicePaymentMethodDataModel.Payment ToPaymentModel(InvoiceEntity entity, PaymentEntity paymentEntity) public static InvoicePaymentMethodDataModel.Payment ToPaymentModel(InvoiceEntity entity, PaymentEntity paymentEntity)
{ {
var data = paymentEntity.GetCryptoPaymentData(); var data = paymentEntity.GetCryptoPaymentData();

View File

@@ -27,7 +27,7 @@ namespace BTCPayServer.Controllers.GreenField
public InternalLightningNodeApiController( public InternalLightningNodeApiController(
BTCPayNetworkProvider btcPayNetworkProvider, ISettingsRepository settingsRepository, LightningClientFactoryService lightningClientFactory, BTCPayNetworkProvider btcPayNetworkProvider, ISettingsRepository settingsRepository, LightningClientFactoryService lightningClientFactory,
IOptions<LightningNetworkOptions> lightningNetworkOptions, IOptions<LightningNetworkOptions> lightningNetworkOptions,
IAuthorizationService authorizationService) : base( IAuthorizationService authorizationService) : base(
btcPayNetworkProvider, settingsRepository, authorizationService) btcPayNetworkProvider, settingsRepository, authorizationService)

View File

@@ -105,7 +105,7 @@ namespace BTCPayServer.Controllers.GreenField
protected override Task<ILightningClient> GetLightningClient(string cryptoCode, protected override Task<ILightningClient> GetLightningClient(string cryptoCode,
bool doingAdminThings) bool doingAdminThings)
{ {
var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(cryptoCode); var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(cryptoCode);
var store = HttpContext.GetStoreData(); var store = HttpContext.GetStoreData();
if (store == null || network == null) if (store == null || network == null)

View File

@@ -267,7 +267,7 @@ namespace BTCPayServer.Controllers.GreenField
protected async Task<bool> CanUseInternalLightning(bool doingAdminThings) protected async Task<bool> CanUseInternalLightning(bool doingAdminThings)
{ {
return (!doingAdminThings && (await _settingsRepository.GetPolicies()).AllowLightningInternalNodeForAll) || return (!doingAdminThings && (await _settingsRepository.GetPolicies()).AllowLightningInternalNodeForAll) ||
(await _authorizationService.AuthorizeAsync(User, null, (await _authorizationService.AuthorizeAsync(User, null,
new PolicyRequirement(Policies.CanUseInternalLightningNode))).Succeeded; new PolicyRequirement(Policies.CanUseInternalLightningNode))).Succeeded;

View File

@@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers.GreenField
_greenfieldPullPaymentController, _greenfieldPullPaymentController,
_homeController, _homeController,
_storePaymentMethodsController, _storePaymentMethodsController,
new HttpContextAccessor() {HttpContext = context} new HttpContextAccessor() { HttpContext = context }
); );
} }
} }
@@ -471,8 +471,8 @@ namespace BTCPayServer.Controllers.GreenField
switch (result) switch (result)
{ {
case JsonResult jsonResult: case JsonResult jsonResult:
return (T) jsonResult.Value; return (T)jsonResult.Value;
case OkObjectResult {Value: T res}: case OkObjectResult { Value: T res }:
return res; return res;
default: default:
return default; return default;
@@ -483,9 +483,9 @@ namespace BTCPayServer.Controllers.GreenField
{ {
switch (result) switch (result)
{ {
case UnprocessableEntityObjectResult {Value: List<GreenfieldValidationError> validationErrors}: case UnprocessableEntityObjectResult { Value: List<GreenfieldValidationError> validationErrors }:
throw new GreenFieldValidationException(validationErrors.ToArray()); throw new GreenFieldValidationException(validationErrors.ToArray());
case BadRequestObjectResult {Value: GreenfieldAPIError error}: case BadRequestObjectResult { Value: GreenfieldAPIError error }:
throw new GreenFieldAPIException(400, error); throw new GreenFieldAPIException(400, error);
case NotFoundResult _: case NotFoundResult _:
throw new GreenFieldAPIException(404, new GreenfieldAPIError("not-found", "")); throw new GreenFieldAPIException(404, new GreenfieldAPIError("not-found", ""));
@@ -612,8 +612,8 @@ namespace BTCPayServer.Controllers.GreenField
{ {
HandleActionResult(await _apiKeysController.RevokeKey(apikey)); HandleActionResult(await _apiKeysController.RevokeKey(apikey));
} }
public override async Task<IEnumerable<NotificationData>> GetNotifications(bool? seen = null, public override async Task<IEnumerable<NotificationData>> GetNotifications(bool? seen = null,
int? skip = null, int? take = null, CancellationToken token = default) int? skip = null, int? take = null, CancellationToken token = default)
{ {
return GetFromActionResult<IEnumerable<NotificationData>>( return GetFromActionResult<IEnumerable<NotificationData>>(
@@ -632,7 +632,7 @@ namespace BTCPayServer.Controllers.GreenField
{ {
return GetFromActionResult<NotificationData>( return GetFromActionResult<NotificationData>(
await _notificationsController.UpdateNotification(notificationId, await _notificationsController.UpdateNotification(notificationId,
new UpdateNotification() {Seen = seen})); new UpdateNotification() { Seen = seen }));
} }
public override async Task RemoveNotification(string notificationId, CancellationToken token = default) public override async Task RemoveNotification(string notificationId, CancellationToken token = default)
@@ -752,7 +752,7 @@ namespace BTCPayServer.Controllers.GreenField
{ {
return GetFromActionResult<StoreData>(await _storesController.UpdateStore(storeId, request)); return GetFromActionResult<StoreData>(await _storesController.UpdateStore(storeId, request));
} }
public override Task<IEnumerable<LNURLPayPaymentMethodData>> public override Task<IEnumerable<LNURLPayPaymentMethodData>>
GetStoreLNURLPayPaymentMethods(string storeId, bool? enabled, GetStoreLNURLPayPaymentMethods(string storeId, bool? enabled,
CancellationToken token = default) CancellationToken token = default)
@@ -784,7 +784,7 @@ namespace BTCPayServer.Controllers.GreenField
_storeLnurlPayPaymentMethodsController.UpdateLNURLPayPaymentMethod(storeId, cryptoCode, _storeLnurlPayPaymentMethodsController.UpdateLNURLPayPaymentMethod(storeId, cryptoCode,
paymentMethod)); paymentMethod));
} }
public override Task<IEnumerable<LightningNetworkPaymentMethodData>> public override Task<IEnumerable<LightningNetworkPaymentMethodData>>
GetStoreLightningNetworkPaymentMethods(string storeId, bool? enabled, GetStoreLightningNetworkPaymentMethods(string storeId, bool? enabled,
CancellationToken token = default) CancellationToken token = default)
@@ -826,13 +826,13 @@ namespace BTCPayServer.Controllers.GreenField
int? skip = null, int? skip = null,
int? take = null, int? take = null,
CancellationToken token = default CancellationToken token = default
) )
{ {
return GetFromActionResult<IEnumerable<InvoiceData>>( return GetFromActionResult<IEnumerable<InvoiceData>>(
await _greenFieldInvoiceController.GetInvoices(storeId, orderId, await _greenFieldInvoiceController.GetInvoices(storeId, orderId,
status?.Select(invoiceStatus => invoiceStatus.ToString())?.ToArray(), startDate, status?.Select(invoiceStatus => invoiceStatus.ToString())?.ToArray(), startDate,
endDate, textSearch, includeArchived,skip,take)); endDate, textSearch, includeArchived, skip, take));
} }
public override async Task<InvoiceData> GetInvoice(string storeId, string invoiceId, public override async Task<InvoiceData> GetInvoice(string storeId, string invoiceId,
@@ -928,7 +928,7 @@ namespace BTCPayServer.Controllers.GreenField
public override async Task<OnChainPaymentMethodDataWithSensitiveData> GenerateOnChainWallet(string storeId, string cryptoCode, GenerateOnChainWalletRequest request, public override async Task<OnChainPaymentMethodDataWithSensitiveData> GenerateOnChainWallet(string storeId, string cryptoCode, GenerateOnChainWalletRequest request,
CancellationToken token = default) CancellationToken token = default)
{ {
return GetFromActionResult<OnChainPaymentMethodDataWithSensitiveData>(await _chainPaymentMethodsController.GenerateOnChainWallet(storeId, cryptoCode, new GenerateWalletRequest() return GetFromActionResult<OnChainPaymentMethodDataWithSensitiveData>(await _chainPaymentMethodsController.GenerateOnChainWallet(storeId, cryptoCode, new GenerateWalletRequest()
{ {
Passphrase = request.Passphrase, Passphrase = request.Passphrase,
AccountNumber = request.AccountNumber, AccountNumber = request.AccountNumber,

View File

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

View File

@@ -164,7 +164,7 @@ namespace BTCPayServer.Controllers.GreenField
CustomCSSLink = blob.CustomCSSLink CustomCSSLink = blob.CustomCSSLink
}; };
} }
private IActionResult PaymentRequestNotFound() private IActionResult PaymentRequestNotFound()
{ {
return this.CreateAPIError(404, "payment-request-not-found", "The payment request was not found"); return this.CreateAPIError(404, "payment-request-not-found", "The payment request was not found");

View File

@@ -107,14 +107,14 @@ namespace BTCPayServer.Controllers.GreenField
PaymentMethodId.TryParse(s, out var pmi); PaymentMethodId.TryParse(s, out var pmi);
return pmi; return pmi;
}).ToArray(); }).ToArray();
var supported = (await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData())).ToArray(); var supported = (await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData())).ToArray();
for (int i = 0; i < paymentMethods.Length; i++) for (int i = 0; i < paymentMethods.Length; i++)
{ {
if (!supported.Contains(paymentMethods[i])) if (!supported.Contains(paymentMethods[i]))
{ {
request.AddModelError(paymentRequest => paymentRequest.PaymentMethods[i], "Invalid or unsupported payment method", this); request.AddModelError(paymentRequest => paymentRequest.PaymentMethods[i], "Invalid or unsupported payment method", this);
} }
} }
} }
else else
{ {
@@ -181,7 +181,7 @@ namespace BTCPayServer.Controllers.GreenField
var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, true); var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, true);
if (pp is null) if (pp is null)
return PullPaymentNotFound(); 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); var cd = _currencyNameTable.GetCurrencyData(pp.GetBlob().Currency, false);
return base.Ok(payouts return base.Ok(payouts
.Select(p => ToModel(p, cd)).ToList()); .Select(p => ToModel(p, cd)).ToList());
@@ -198,7 +198,7 @@ namespace BTCPayServer.Controllers.GreenField
if (pp is null) if (pp is null)
return PullPaymentNotFound(); return PullPaymentNotFound();
var payout = pp.Payouts.FirstOrDefault(p => p.Id == payoutId); var payout = pp.Payouts.FirstOrDefault(p => p.Id == payoutId);
if(payout is null ) if (payout is null)
return PayoutNotFound(); return PayoutNotFound();
var cd = _currencyNameTable.GetCurrencyData(payout.PullPaymentData.GetBlob().Currency, false); var cd = _currencyNameTable.GetCurrencyData(payout.PullPaymentData.GetBlob().Currency, false);
return base.Ok(ToModel(payout, cd)); return base.Ok(ToModel(payout, cd));
@@ -232,7 +232,7 @@ namespace BTCPayServer.Controllers.GreenField
ModelState.AddModelError(nameof(request.PaymentMethod), "Invalid payment method"); ModelState.AddModelError(nameof(request.PaymentMethod), "Invalid payment method");
return this.CreateValidationError(ModelState); return this.CreateValidationError(ModelState);
} }
var payoutHandler = _payoutHandlers.FindPayoutHandler(paymentMethodId); var payoutHandler = _payoutHandlers.FindPayoutHandler(paymentMethodId);
if (payoutHandler is null) if (payoutHandler is null)
{ {
@@ -248,7 +248,7 @@ namespace BTCPayServer.Controllers.GreenField
var destination = await payoutHandler.ParseClaimDestination(paymentMethodId, request!.Destination, true); var destination = await payoutHandler.ParseClaimDestination(paymentMethodId, request!.Destination, true);
if (destination.destination is null) 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); return this.CreateValidationError(ModelState);
} }
@@ -404,7 +404,7 @@ namespace BTCPayServer.Controllers.GreenField
throw new NotSupportedException(); throw new NotSupportedException();
} }
} }
private IActionResult PayoutNotFound() private IActionResult PayoutNotFound()
{ {
return this.CreateAPIError(404, "payout-not-found", "The payout was not found"); return this.CreateAPIError(404, "payout-not-found", "The payout was not found");

View File

@@ -23,7 +23,7 @@ namespace BTCPayServer.Controllers.GreenField
public GreenFieldServerInfoController( public GreenFieldServerInfoController(
BTCPayServerEnvironment env, BTCPayServerEnvironment env,
PaymentMethodHandlerDictionary paymentMethodHandlerDictionary, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary,
IEnumerable<ISyncSummaryProvider>summaryProviders) IEnumerable<ISyncSummaryProvider> summaryProviders)
{ {
_env = env; _env = env;
_paymentMethodHandlerDictionary = paymentMethodHandlerDictionary; _paymentMethodHandlerDictionary = paymentMethodHandlerDictionary;
@@ -37,7 +37,7 @@ namespace BTCPayServer.Controllers.GreenField
var supportedPaymentMethods = _paymentMethodHandlerDictionary var supportedPaymentMethods = _paymentMethodHandlerDictionary
.SelectMany(handler => handler.GetSupportedPaymentMethods().Select(id => id.ToString())) .SelectMany(handler => handler.GetSupportedPaymentMethods().Select(id => id.ToString()))
.Distinct(); .Distinct();
ServerInfoData model = new ServerInfoData2 ServerInfoData model = new ServerInfoData2
{ {
FullySynched = _summaryProviders.All(provider => provider.AllAvailable()), FullySynched = _summaryProviders.All(provider => provider.AllAvailable()),
@@ -48,7 +48,7 @@ namespace BTCPayServer.Controllers.GreenField
}; };
return Ok(model); return Ok(model);
} }
public class ServerInfoData2 : ServerInfoData public class ServerInfoData2 : ServerInfoData
{ {
public new IEnumerable<ISyncStatus> SyncStatus { get; set; } public new IEnumerable<ISyncStatus> SyncStatus { get; set; }

View File

@@ -93,7 +93,7 @@ namespace BTCPayServer.Controllers.GreenField
string storeId, string storeId,
string cryptoCode) string cryptoCode)
{ {
AssertCryptoCodeWallet(cryptoCode, out _); AssertCryptoCodeWallet(cryptoCode, out _);
var id = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay); var id = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay);
@@ -109,7 +109,7 @@ namespace BTCPayServer.Controllers.GreenField
[FromBody] LNURLPayPaymentMethodData paymentMethodData) [FromBody] LNURLPayPaymentMethodData paymentMethodData)
{ {
var paymentMethodId = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay); var paymentMethodId = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay);
AssertCryptoCodeWallet(cryptoCode, out _); AssertCryptoCodeWallet(cryptoCode, out _);
var lnMethod = StoreLightningNetworkPaymentMethodsController.GetExistingLightningLikePaymentMethod(_btcPayNetworkProvider, var lnMethod = StoreLightningNetworkPaymentMethodsController.GetExistingLightningLikePaymentMethod(_btcPayNetworkProvider,
@@ -130,7 +130,7 @@ namespace BTCPayServer.Controllers.GreenField
UseBech32Scheme = paymentMethodData.UseBech32Scheme, UseBech32Scheme = paymentMethodData.UseBech32Scheme,
EnableForStandardInvoices = paymentMethodData.EnableForStandardInvoices EnableForStandardInvoices = paymentMethodData.EnableForStandardInvoices
}; };
var store = Store; var store = Store;
var storeBlob = store.GetStoreBlob(); var storeBlob = store.GetStoreBlob();
store.SetSupportedPaymentMethod(paymentMethodId, paymentMethod); store.SetSupportedPaymentMethod(paymentMethodId, paymentMethod);
@@ -166,6 +166,6 @@ namespace BTCPayServer.Controllers.GreenField
if (network is null) if (network is null)
throw new JsonHttpException(this.CreateAPIError(404, "unknown-cryptocode", "This crypto code isn't set up in this BTCPay Server instance")); throw new JsonHttpException(this.CreateAPIError(404, "unknown-cryptocode", "This crypto code isn't set up in this BTCPay Server instance"));
} }
} }
} }

View File

@@ -201,7 +201,7 @@ namespace BTCPayServer.Controllers.GreenField
return paymentMethod is null return paymentMethod is null
? null ? null
: new LightningNetworkPaymentMethodData(paymentMethod.PaymentId.CryptoCode, : new LightningNetworkPaymentMethodData(paymentMethod.PaymentId.CryptoCode,
paymentMethod.GetDisplayableConnectionString(), !excluded, paymentMethod.GetDisplayableConnectionString(), !excluded,
paymentMethod.PaymentId.ToStringNormalized(), paymentMethod.DisableBOLT11PaymentOption); paymentMethod.PaymentId.ToStringNormalized(), paymentMethod.DisableBOLT11PaymentOption);
} }

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants; using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Client; using BTCPayServer.Client;
@@ -18,7 +18,7 @@ namespace BTCPayServer.Controllers.GreenField
public async Task<IActionResult> GenerateOnChainWallet(string storeId, string cryptoCode, public async Task<IActionResult> GenerateOnChainWallet(string storeId, string cryptoCode,
GenerateWalletRequest request) GenerateWalletRequest request)
{ {
AssertCryptoCodeWallet(cryptoCode, out var network, out var wallet); AssertCryptoCodeWallet(cryptoCode, out var network, out var wallet);
if (!_walletProvider.IsAvailable(network)) if (!_walletProvider.IsAvailable(network))
@@ -26,7 +26,7 @@ namespace BTCPayServer.Controllers.GreenField
return this.CreateAPIError("not-available", return this.CreateAPIError("not-available",
$"{cryptoCode} services are not currently available"); $"{cryptoCode} services are not currently available");
} }
var method = GetExistingBtcLikePaymentMethod(cryptoCode); var method = GetExistingBtcLikePaymentMethod(cryptoCode);
if (method != null) if (method != null)
{ {
@@ -91,7 +91,7 @@ namespace BTCPayServer.Controllers.GreenField
rawResult.Enabled, rawResult.Label, rawResult.AccountKeyPath, response.GetMnemonic(), derivationSchemeSettings.PaymentId.ToStringNormalized()); rawResult.Enabled, rawResult.Label, rawResult.AccountKeyPath, response.GetMnemonic(), derivationSchemeSettings.PaymentId.ToStringNormalized());
return Ok(result); return Ok(result);
} }
private async Task<(bool HotWallet, bool RPCImport)> CanUseHotWallet() private async Task<(bool HotWallet, bool RPCImport)> CanUseHotWallet()
{ {
return await _authorizationService.CanUseHotWallet(await _settingsRepository.GetPolicies(), User); return await _authorizationService.CanUseHotWallet(await _settingsRepository.GetPolicies(), User);

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