diff --git a/BTCPayServer.Common/Logging/Logs.cs b/BTCPayServer.Common/Logging/Logs.cs index 81846a910..b93682fd6 100644 --- a/BTCPayServer.Common/Logging/Logs.cs +++ b/BTCPayServer.Common/Logging/Logs.cs @@ -6,11 +6,11 @@ namespace BTCPayServer.Logging { public class Logs { - static Logs() + public Logs() { Configure(new FuncLoggerFactory(n => NullLogger.Instance)); } - public static void Configure(ILoggerFactory factory) + public void Configure(ILoggerFactory factory) { if (factory == null) Configure(new FuncLoggerFactory(n => NullLogger.Instance)); @@ -21,16 +21,16 @@ namespace BTCPayServer.Logging Events = factory.CreateLogger("Events"); } } - public static ILogger Configuration + public ILogger Configuration { get; set; } - public static ILogger PayServer + public ILogger PayServer { get; set; } - public static ILogger Events + public ILogger Events { get; set; } diff --git a/BTCPayServer.Tests/AltcoinTests/AltcoinTests.cs b/BTCPayServer.Tests/AltcoinTests/AltcoinTests.cs index 34f16c491..40d58bd73 100644 --- a/BTCPayServer.Tests/AltcoinTests/AltcoinTests.cs +++ b/BTCPayServer.Tests/AltcoinTests/AltcoinTests.cs @@ -30,13 +30,11 @@ using WalletSettingsViewModel = BTCPayServer.Models.StoreViewModels.WalletSettin namespace BTCPayServer.Tests { - public class AltcoinTests + public class AltcoinTests : UnitTestBase { public const int TestTimeout = 60_000; - public AltcoinTests(ITestOutputHelper helper) + public AltcoinTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] @@ -45,7 +43,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanSetupWallet() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLTC(); tester.ActivateLightning(); @@ -240,7 +238,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanCreateInvoiceWithSpecificPaymentMethods() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); tester.ActivateLTC(); @@ -272,7 +270,7 @@ namespace BTCPayServer.Tests [Trait("Altcoins", "Altcoins")] public async Task CanHaveLTCOnlyStore() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLTC(); await tester.StartAsync(); @@ -343,7 +341,7 @@ namespace BTCPayServer.Tests [Trait("Altcoins", "Altcoins")] public async Task CanCreateRefunds() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLTC(); await s.StartAsync(); @@ -417,7 +415,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUsePaymentMethodDropdown() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLTC(); s.Server.ActivateLightning(); @@ -464,7 +462,7 @@ namespace BTCPayServer.Tests [Trait("Altcoins", "Altcoins")] public async Task CanPayWithTwoCurrencies() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLTC(); await tester.StartAsync(); @@ -532,7 +530,7 @@ namespace BTCPayServer.Tests invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, cashCow.Network); firstPayment = Money.Coins(0.04m); cashCow.SendToAddress(invoiceAddress, firstPayment); - Logs.Tester.LogInformation("First payment sent to " + invoiceAddress); + TestLogs.LogInformation("First payment sent to " + invoiceAddress); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -546,7 +544,7 @@ namespace BTCPayServer.Tests var secondPayment = Money.Coins(decimal.Parse(ltcCryptoInfo.Due, CultureInfo.InvariantCulture)); cashCow.Generate(4); // LTC is not worth a lot, so just to make sure we have money... cashCow.SendToAddress(invoiceAddress, secondPayment); - Logs.Tester.LogInformation("Second payment sent to " + invoiceAddress); + TestLogs.LogInformation("Second payment sent to " + invoiceAddress); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -603,7 +601,7 @@ namespace BTCPayServer.Tests [Trait("Altcoins", "Altcoins")] public async Task CanUsePoSApp() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLTC(); await tester.StartAsync(); @@ -697,7 +695,7 @@ donation: ExpectedThousandSeparator: ",", ExpectedPrefixed: false, ExpectedSymbolSpace: true), }) { - Logs.Tester.LogInformation($"Testing for {test.Code}"); + TestLogs.LogInformation($"Testing for {test.Code}"); vmpos = Assert.IsType(Assert .IsType(apps.UpdatePointOfSale(appId).Result).Model); vmpos.Title = "hello"; diff --git a/BTCPayServer.Tests/AltcoinTests/ElementsTests.cs b/BTCPayServer.Tests/AltcoinTests/ElementsTests.cs index 40a1d5163..39bf31e29 100644 --- a/BTCPayServer.Tests/AltcoinTests/ElementsTests.cs +++ b/BTCPayServer.Tests/AltcoinTests/ElementsTests.cs @@ -18,21 +18,19 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class ElementsTests + public class ElementsTests : UnitTestBase { public const int TestTimeout = 60_000; - public ElementsTests(ITestOutputHelper helper) + public ElementsTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] [Trait("Altcoins", "Altcoins")] public async Task OnlyShowSupportedWallets() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLBTC(); await tester.StartAsync(); @@ -50,7 +48,7 @@ namespace BTCPayServer.Tests [Trait("Altcoins", "Altcoins")] public async Task ElementsAssetsAreHandledCorrectly() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLBTC(); await tester.StartAsync(); diff --git a/BTCPayServer.Tests/AltcoinTests/EthereumTests.cs b/BTCPayServer.Tests/AltcoinTests/EthereumTests.cs index 431b65e5d..d31b01cb6 100644 --- a/BTCPayServer.Tests/AltcoinTests/EthereumTests.cs +++ b/BTCPayServer.Tests/AltcoinTests/EthereumTests.cs @@ -13,21 +13,19 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class EthereumTests + public class EthereumTests : UnitTestBase { public const int TestTimeout = 60_000; - public EthereumTests(ITestOutputHelper helper) + public EthereumTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) {Name = "Tests"}; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] [Trait("Altcoins", "Altcoins")] public async Task CanUseEthereum() { - using var s = SeleniumTester.Create("ETHEREUM", true); + using var s = CreateSeleniumTester("ETHEREUM", true); s.Server.ActivateETH(); await s.StartAsync(); s.RegisterNewUser(true); diff --git a/BTCPayServer.Tests/ApiKeysTests.cs b/BTCPayServer.Tests/ApiKeysTests.cs index 8b981df93..cbdc969a7 100644 --- a/BTCPayServer.Tests/ApiKeysTests.cs +++ b/BTCPayServer.Tests/ApiKeysTests.cs @@ -18,15 +18,13 @@ using StoreData = BTCPayServer.Data.StoreData; namespace BTCPayServer.Tests { - public class ApiKeysTests + public class ApiKeysTests : UnitTestBase { public const int TestTimeout = TestUtils.TestTimeout; public const string TestApiPath = "api/test/apikey"; - public ApiKeysTests(ITestOutputHelper helper) + public ApiKeysTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = TestTimeout)] @@ -37,7 +35,7 @@ namespace BTCPayServer.Tests //as a user through your profile //as an external application requesting an api key from a user - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); var tester = s.Server; diff --git a/BTCPayServer.Tests/BTCPayServerTester.cs b/BTCPayServer.Tests/BTCPayServerTester.cs index 756e95965..4bf2b1082 100644 --- a/BTCPayServer.Tests/BTCPayServerTester.cs +++ b/BTCPayServer.Tests/BTCPayServerTester.cs @@ -40,8 +40,13 @@ namespace BTCPayServer.Tests { private readonly string _Directory; - public BTCPayServerTester(string scope) + public ILoggerProvider LoggerProvider { get; } + + ILog TestLogs; + public BTCPayServerTester(ILog testLogs, ILoggerProvider loggerProvider, string scope) { + this.LoggerProvider = loggerProvider; + this.TestLogs = testLogs; this._Directory = scope ?? throw new ArgumentNullException(nameof(scope)); } @@ -154,7 +159,7 @@ namespace BTCPayServer.Tests HttpClient = new HttpClient(); HttpClient.BaseAddress = ServerUri; Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); - var conf = new DefaultConfiguration() { Logger = Logs.LogProvider.CreateLogger("Console") }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", DisableRegistration ? "true" : "false" }); + var conf = new DefaultConfiguration() { Logger = LoggerProvider.CreateLogger("Console") }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", DisableRegistration ? "true" : "false" }); _Host = new WebHostBuilder() .UseConfiguration(conf) .UseContentRoot(FindBTCPayServerDirectory()) @@ -168,7 +173,7 @@ namespace BTCPayServer.Tests .AddFilter("Microsoft", LogLevel.Error) .AddFilter("Hangfire", LogLevel.Error) .AddFilter("Fido2NetLib.DistributedCacheMetadataService", LogLevel.Error) - .AddProvider(Logs.LogProvider); + .AddProvider(LoggerProvider); }); }) .ConfigureServices(services => @@ -183,9 +188,9 @@ namespace BTCPayServer.Tests var urls = _Host.ServerFeatures.Get().Addresses; foreach (var url in urls) { - Logs.Tester.LogInformation("Listening on " + url); + TestLogs.LogInformation("Listening on " + url); } - Logs.Tester.LogInformation("Server URI " + ServerUri); + TestLogs.LogInformation("Server URI " + ServerUri); InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository)); StoreRepository = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository)); @@ -230,9 +235,9 @@ namespace BTCPayServer.Tests } - Logs.Tester.LogInformation("Waiting site is operational..."); + TestLogs.LogInformation("Waiting site is operational..."); await WaitSiteIsOperational(); - Logs.Tester.LogInformation("Site is now operational"); + TestLogs.LogInformation("Site is now operational"); } MockRateProvider coinAverageMock; private async Task WaitSiteIsOperational() diff --git a/BTCPayServer.Tests/CheckoutUITests.cs b/BTCPayServer.Tests/CheckoutUITests.cs index 4f369a771..6ddc7e1a9 100644 --- a/BTCPayServer.Tests/CheckoutUITests.cs +++ b/BTCPayServer.Tests/CheckoutUITests.cs @@ -11,20 +11,18 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { [Trait("Selenium", "Selenium")] - public class CheckoutUITests + public class CheckoutUITests : UnitTestBase { public const int TestTimeout = TestUtils.TestTimeout; - public CheckoutUITests(ITestOutputHelper helper) + public CheckoutUITests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = TestTimeout)] public async Task CanHandleRefundEmailForm() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.GoToRegister(); @@ -74,7 +72,7 @@ namespace BTCPayServer.Tests public async Task CanHandleRefundEmailForm2() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { // Prepare user account and store await s.StartAsync(); @@ -135,7 +133,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseLanguageDropdown() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.GoToRegister(); @@ -166,7 +164,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanSetDefaultPaymentMethod() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLightning(); await s.StartAsync(); @@ -188,7 +186,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUseLightningSatsFeature() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLightning(); await s.StartAsync(); @@ -211,7 +209,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseJSModal() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.GoToRegister(); diff --git a/BTCPayServer.Tests/CrowdfundTests.cs b/BTCPayServer.Tests/CrowdfundTests.cs index 4ce8a9f07..81af549e9 100644 --- a/BTCPayServer.Tests/CrowdfundTests.cs +++ b/BTCPayServer.Tests/CrowdfundTests.cs @@ -15,19 +15,17 @@ using static BTCPayServer.Tests.UnitTest1; namespace BTCPayServer.Tests { - public class CrowdfundTests + public class CrowdfundTests : UnitTestBase { - public CrowdfundTests(ITestOutputHelper helper) + public CrowdfundTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = LongRunningTestTimeout)] [Trait("Integration", "Integration")] public async Task CanCreateAndDeleteCrowdfundApp() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -67,7 +65,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanContributeOnlyWhenAllowed() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -159,7 +157,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanComputeCrowdfundModel() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -174,7 +172,7 @@ namespace BTCPayServer.Tests var appId = Assert.IsType(Assert.IsType(apps.ListApps().Result).Model) .Apps[0].Id; - Logs.Tester.LogInformation("We create an invoice with a hardcap"); + TestLogs.LogInformation("We create an invoice with a hardcap"); var crowdfundViewModel = Assert.IsType(Assert .IsType(apps.UpdateCrowdfund(appId).Result).Model); crowdfundViewModel.Enabled = true; @@ -201,8 +199,8 @@ namespace BTCPayServer.Tests Assert.Equal(0m, model.Info.ProgressPercentage); - Logs.Tester.LogInformation("Unpaid invoices should show as pending contribution because it is hardcap"); - Logs.Tester.LogInformation("Because UseAllStoreInvoices is true, we can manually create an invoice and it should show as contribution"); + TestLogs.LogInformation("Unpaid invoices should show as pending contribution because it is hardcap"); + TestLogs.LogInformation("Because UseAllStoreInvoices is true, we can manually create an invoice and it should show as contribution"); var invoice = user.BitPay.CreateInvoice(new Invoice() { Buyer = new Buyer() { email = "test@fwf.com" }, @@ -223,7 +221,7 @@ namespace BTCPayServer.Tests Assert.Equal(0m, model.Info.ProgressPercentage); Assert.Equal(1m, model.Info.PendingProgressPercentage); - Logs.Tester.LogInformation("Let's check current amount change once payment is confirmed"); + TestLogs.LogInformation("Let's check current amount change once payment is confirmed"); var invoiceAddress = BitcoinAddress.Create(invoice.CryptoInfo[0].Address, tester.ExplorerNode.Network); tester.ExplorerNode.SendToAddress(invoiceAddress, invoice.BtcDue); tester.ExplorerNode.Generate(1); // By default invoice confirmed at 1 block @@ -235,7 +233,7 @@ namespace BTCPayServer.Tests Assert.Equal(0m, model.Info.CurrentPendingAmount); }); - Logs.Tester.LogInformation("Because UseAllStoreInvoices is true, let's make sure the invoice is tagged"); + TestLogs.LogInformation("Because UseAllStoreInvoices is true, let's make sure the invoice is tagged"); var invoiceEntity = tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id).GetAwaiter().GetResult(); Assert.True(invoiceEntity.Version >= InvoiceEntity.InternalTagSupport_Version); Assert.Contains(AppService.GetAppInternalTag(appId), invoiceEntity.InternalTags); @@ -243,7 +241,7 @@ namespace BTCPayServer.Tests crowdfundViewModel.UseAllStoreInvoices = false; Assert.IsType(apps.UpdateCrowdfund(appId, crowdfundViewModel, "save").Result); - Logs.Tester.LogInformation("Because UseAllStoreInvoices is false, let's make sure the invoice is not tagged"); + TestLogs.LogInformation("Because UseAllStoreInvoices is false, let's make sure the invoice is not tagged"); invoice = user.BitPay.CreateInvoice(new Invoice() { Buyer = new Buyer() { email = "test@fwf.com" }, @@ -257,7 +255,7 @@ namespace BTCPayServer.Tests invoiceEntity = tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id).GetAwaiter().GetResult(); Assert.DoesNotContain(AppService.GetAppInternalTag(appId), invoiceEntity.InternalTags); - Logs.Tester.LogInformation("After turning setting a softcap, let's check that only actual payments are counted"); + TestLogs.LogInformation("After turning setting a softcap, let's check that only actual payments are counted"); crowdfundViewModel.EnforceTargetAmount = false; crowdfundViewModel.UseAllStoreInvoices = true; Assert.IsType(apps.UpdateCrowdfund(appId, crowdfundViewModel, "save").Result); diff --git a/BTCPayServer.Tests/Extensions.cs b/BTCPayServer.Tests/Extensions.cs index d2a7dacc2..90f777505 100644 --- a/BTCPayServer.Tests/Extensions.cs +++ b/BTCPayServer.Tests/Extensions.cs @@ -158,7 +158,6 @@ namespace BTCPayServer.Tests if (value != element.Selected) { - Logs.Tester.LogInformation("SetCheckbox recursion, trying to click again"); driver.SetCheckbox(selector, value); } } diff --git a/BTCPayServer.Tests/FastTests.cs b/BTCPayServer.Tests/FastTests.cs index 5924100cf..fd6787eaf 100644 --- a/BTCPayServer.Tests/FastTests.cs +++ b/BTCPayServer.Tests/FastTests.cs @@ -659,7 +659,7 @@ namespace BTCPayServer.Tests new OptionsWrapper(new BTCPayServerOptions() { TorrcFile = TestUtils.GetTestDataFullPath("Tor/torrc") - })); + }), BTCPayLogs); await tor.Refresh(); Assert.Single(tor.Services.Where(t => t.ServiceType == TorServiceType.BTCPayServer)); @@ -672,7 +672,7 @@ namespace BTCPayServer.Tests { TorrcFile = null, TorServices = "btcpayserver:host.onion:80;btc-p2p:host2.onion:81,BTC-RPC:host3.onion:82,UNKNOWN:host4.onion:83,INVALID:ddd".Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries) - })); + }), BTCPayLogs); await Task.WhenAll(tor.StartAsync(CancellationToken.None)); var btcpayS = Assert.Single(tor.Services.Where(t => t.ServiceType == TorServiceType.BTCPayServer)); @@ -1031,7 +1031,7 @@ namespace BTCPayServer.Tests [Fact] public async Task CanScheduleBackgroundTasks() { - BackgroundJobClient client = new BackgroundJobClient(); + BackgroundJobClient client = new BackgroundJobClient(BTCPayLogs); MockDelay mockDelay = new MockDelay(); client.Delay = mockDelay; bool[] jobs = new bool[4]; @@ -1446,7 +1446,7 @@ namespace BTCPayServer.Tests }) }); - var networkProvider = config.ConfigureNetworkProvider(); + var networkProvider = config.ConfigureNetworkProvider(BTCPayLogs); Assert.NotNull(networkProvider.GetNetwork("ETH")); Assert.NotNull(networkProvider.GetNetwork("USDT20")); Assert.NotNull(networkProvider.GetNetwork("LBTC")); diff --git a/BTCPayServer.Tests/GreenfieldAPITests.cs b/BTCPayServer.Tests/GreenfieldAPITests.cs index eb888d06b..2cc8ffd44 100644 --- a/BTCPayServer.Tests/GreenfieldAPITests.cs +++ b/BTCPayServer.Tests/GreenfieldAPITests.cs @@ -31,20 +31,18 @@ using JsonReader = Newtonsoft.Json.JsonReader; namespace BTCPayServer.Tests { - public class GreenfieldAPITests + public class GreenfieldAPITests : UnitTestBase { public const int TestTimeout = TestUtils.TestTimeout; - public GreenfieldAPITests(ITestOutputHelper helper) + public GreenfieldAPITests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = TestTimeout)] [Trait("Integration", "Integration")] public async Task LocalClientTests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); await tester.StartAsync(); var user = tester.NewAccount(); await user.GrantAccessAsync(); @@ -61,7 +59,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task ApiKeysControllerTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -90,7 +88,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUseMiscAPIs() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -112,7 +110,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task SpecificCanModifyStoreCantCreateNewStore() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -137,7 +135,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCreateAndDeleteAPIKeyViaAPI() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -169,7 +167,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanDeleteUsersViaApi() { - using var tester = ServerTester.Create(newDb: true); + using var tester = CreateServerTester(newDb: true); await tester.StartAsync(); var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri); // Should not be authorized to perform this action @@ -208,7 +206,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCreateUsersViaAPI() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { tester.PayTester.DisableRegistration = true; await tester.StartAsync(); @@ -345,7 +343,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUsePullPaymentViaAPI() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -393,9 +391,9 @@ namespace BTCPayServer.Tests PaymentMethods = new[] { "BTC" } }); - Logs.Tester.LogInformation("Can't archive without knowing the walletId"); + TestLogs.LogInformation("Can't archive without knowing the walletId"); await Assert.ThrowsAsync(async () => await client.ArchivePullPayment("lol", result.Id)); - Logs.Tester.LogInformation("Can't archive without permission"); + TestLogs.LogInformation("Can't archive without permission"); await Assert.ThrowsAsync(async () => await unauthenticated.ArchivePullPayment(storeId, result.Id)); await client.ArchivePullPayment(storeId, result.Id); result = await unauthenticated.GetPullPayment(result.Id); @@ -441,7 +439,7 @@ namespace BTCPayServer.Tests Assert.Equal("BTC", payout2.CryptoCode); Assert.Null(payout.PaymentMethodAmount); - Logs.Tester.LogInformation("Can't overdraft"); + TestLogs.LogInformation("Can't overdraft"); var destination2 = (await tester.ExplorerNode.GetNewAddressAsync()).ToString(); await this.AssertAPIError("overdraft", async () => await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest() @@ -451,14 +449,14 @@ namespace BTCPayServer.Tests PaymentMethod = "BTC" })); - Logs.Tester.LogInformation("Can't create too low payout"); + TestLogs.LogInformation("Can't create too low payout"); await this.AssertAPIError("amount-too-low", async () => await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest() { Destination = destination2, PaymentMethod = "BTC" })); - Logs.Tester.LogInformation("Can archive payout"); + TestLogs.LogInformation("Can archive payout"); await client.CancelPayout(storeId, payout.Id); payouts = await unauthenticated.GetPayouts(pps[0].Id); Assert.Empty(payouts); @@ -467,7 +465,7 @@ namespace BTCPayServer.Tests payout = Assert.Single(payouts); Assert.Equal(PayoutState.Cancelled, payout.State); - Logs.Tester.LogInformation("Can create payout after cancelling"); + TestLogs.LogInformation("Can create payout after cancelling"); payout = await unauthenticated.CreatePayout(pps[0].Id, new CreatePayoutRequest() { Destination = destination, @@ -517,7 +515,7 @@ namespace BTCPayServer.Tests })); - Logs.Tester.LogInformation("Create a pull payment with USD"); + TestLogs.LogInformation("Create a pull payment with USD"); var pp = await client.CreatePullPayment(storeId, new Client.Models.CreatePullPaymentRequest() { Name = "Test USD", @@ -527,7 +525,7 @@ namespace BTCPayServer.Tests }); destination = (await tester.ExplorerNode.GetNewAddressAsync()).ToString(); - Logs.Tester.LogInformation("Try to pay it in BTC"); + TestLogs.LogInformation("Try to pay it in BTC"); payout = await unauthenticated.CreatePayout(pp.Id, new CreatePayoutRequest() { Destination = destination, @@ -594,7 +592,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task StoresControllerTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -670,7 +668,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task UsersControllerTests() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { tester.PayTester.DisableRegistration = true; await tester.StartAsync(); @@ -743,7 +741,7 @@ namespace BTCPayServer.Tests Assert.False(hook.AutomaticRedelivery); Assert.Equal(fakeServer.ServerUri.AbsoluteUri, hook.Url); } - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); using var fakeServer = new FakeServer(); await fakeServer.Start(); await tester.StartAsync(); @@ -803,18 +801,18 @@ namespace BTCPayServer.Tests var jObj = await clientProfile.GetWebhookDeliveryRequest(user.StoreId, hook.Id, newDeliveryId); Assert.NotNull(jObj); - Logs.Tester.LogInformation("Should not be able to access webhook without proper auth"); + TestLogs.LogInformation("Should not be able to access webhook without proper auth"); var unauthorized = await user.CreateClient(Policies.CanCreateInvoice); await AssertHttpError(403, async () => { await unauthorized.GetWebhookDeliveryRequest(user.StoreId, hook.Id, newDeliveryId); }); - Logs.Tester.LogInformation("Can use btcpay.store.canmodifystoresettings to query webhooks"); + TestLogs.LogInformation("Can use btcpay.store.canmodifystoresettings to query webhooks"); clientProfile = await user.CreateClient(Policies.CanModifyStoreSettings, Policies.CanCreateInvoice); await clientProfile.GetWebhookDeliveryRequest(user.StoreId, hook.Id, newDeliveryId); - Logs.Tester.LogInformation("Testing corner cases"); + TestLogs.LogInformation("Testing corner cases"); Assert.Null(await clientProfile.GetWebhookDeliveryRequest(user.StoreId, "lol", newDeliveryId)); Assert.Null(await clientProfile.GetWebhookDeliveryRequest(user.StoreId, hook.Id, "lol")); Assert.Null(await clientProfile.GetWebhookDeliveryRequest(user.StoreId, "lol", "lol")); @@ -832,7 +830,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task HealthControllerTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri); @@ -847,7 +845,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task ServerInfoControllerTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri); @@ -872,7 +870,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task PaymentControllerTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -963,7 +961,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task InvoiceLegacyTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -972,7 +970,7 @@ namespace BTCPayServer.Tests var client = await user.CreateClient(Policies.Unrestricted); var oldBitpay = user.BitPay; - Logs.Tester.LogInformation("Let's create an invoice with bitpay API"); + TestLogs.LogInformation("Let's create an invoice with bitpay API"); var oldInvoice = await oldBitpay.CreateInvoiceAsync(new Invoice() { Currency = "BTC", @@ -990,7 +988,7 @@ namespace BTCPayServer.Tests async Task AssertInvoiceMetadata() { - Logs.Tester.LogInformation("Let's check if we can get invoice in the new format with the metadata"); + TestLogs.LogInformation("Let's check if we can get invoice in the new format with the metadata"); var newInvoice = await client.GetInvoice(user.StoreId, oldInvoice.Id); Assert.Equal("posData", newInvoice.Metadata["posData"].Value()); Assert.Equal("code", newInvoice.Metadata["itemCode"].Value()); @@ -1004,8 +1002,7 @@ namespace BTCPayServer.Tests } await AssertInvoiceMetadata(); - - Logs.Tester.LogInformation("Let's hack the Bitpay created invoice to be just like before this update. (Invoice V1)"); + TestLogs.LogInformation("Let's hack the Bitpay created invoice to be just like before this update. (Invoice V1)"); var invoiceV1 = "{\r\n \"version\": 1,\r\n \"id\": \"" + oldInvoice.Id + "\",\r\n \"storeId\": \"" + user.StoreId + "\",\r\n \"orderId\": \"orderId\",\r\n \"speedPolicy\": 1,\r\n \"rate\": 1.0,\r\n \"invoiceTime\": 1598329634,\r\n \"expirationTime\": 1598330534,\r\n \"depositAddress\": \"mm83rVs8ZnZok1SkRBmXiwQSiPFgTgCKpD\",\r\n \"productInformation\": {\r\n \"itemDesc\": \"desc\",\r\n \"itemCode\": \"code\",\r\n \"physical\": false,\r\n \"price\": 1000.19392922,\r\n \"currency\": \"BTC\"\r\n },\r\n \"buyerInformation\": {\r\n \"buyerName\": null,\r\n \"buyerEmail\": null,\r\n \"buyerCountry\": null,\r\n \"buyerZip\": null,\r\n \"buyerState\": null,\r\n \"buyerCity\": null,\r\n \"buyerAddress2\": \"blah2\",\r\n \"buyerAddress1\": \"blah\",\r\n \"buyerPhone\": null\r\n },\r\n \"posData\": \"posData\",\r\n \"internalTags\": [],\r\n \"derivationStrategy\": null,\r\n \"derivationStrategies\": \"{\\\"BTC\\\":{\\\"signingKey\\\":\\\"tpubDD1AW2ruUxSsDa55NQYtNt7DQw9bqXx4K7r2aScySmjxHtsCZoxFTN3qCMcKLxgsRDMGSwk9qj1fBfi8jqSLenwyYkhDrmgaxQuvuKrTHEf\\\",\\\"source\\\":\\\"NBXplorer\\\",\\\"accountDerivation\\\":\\\"tpubDD1AW2ruUxSsDa55NQYtNt7DQw9bqXx4K7r2aScySmjxHtsCZoxFTN3qCMcKLxgsRDMGSwk9qj1fBfi8jqSLenwyYkhDrmgaxQuvuKrTHEf-[legacy]\\\",\\\"accountOriginal\\\":null,\\\"accountKeySettings\\\":[{\\\"rootFingerprint\\\":\\\"54d5044d\\\",\\\"accountKeyPath\\\":\\\"44'/1'/0'\\\",\\\"accountKey\\\":\\\"tpubDD1AW2ruUxSsDa55NQYtNt7DQw9bqXx4K7r2aScySmjxHtsCZoxFTN3qCMcKLxgsRDMGSwk9qj1fBfi8jqSLenwyYkhDrmgaxQuvuKrTHEf\\\"}],\\\"label\\\":null}}\",\r\n \"status\": \"new\",\r\n \"exceptionStatus\": \"\",\r\n \"payments\": [],\r\n \"refundable\": false,\r\n \"refundMail\": null,\r\n \"redirectURL\": null,\r\n \"redirectAutomatically\": false,\r\n \"txFee\": 0,\r\n \"fullNotifications\": false,\r\n \"notificationEmail\": null,\r\n \"notificationURL\": null,\r\n \"serverUrl\": \"http://127.0.0.1:8001\",\r\n \"cryptoData\": {\r\n \"BTC\": {\r\n \"rate\": 1.0,\r\n \"paymentMethod\": {\r\n \"networkFeeMode\": 0,\r\n \"networkFeeRate\": 100.0,\r\n \"payjoinEnabled\": false\r\n },\r\n \"feeRate\": 100.0,\r\n \"txFee\": 0,\r\n \"depositAddress\": \"mm83rVs8ZnZok1SkRBmXiwQSiPFgTgCKpD\"\r\n }\r\n },\r\n \"monitoringExpiration\": 1598416934,\r\n \"historicalAddresses\": null,\r\n \"availableAddressHashes\": null,\r\n \"extendedNotifications\": false,\r\n \"events\": null,\r\n \"paymentTolerance\": 0.0,\r\n \"archived\": false\r\n}"; var db = tester.PayTester.GetService(); using var ctx = db.CreateContext(); @@ -1014,7 +1011,7 @@ namespace BTCPayServer.Tests await ctx.SaveChangesAsync(); var newInvoice = await AssertInvoiceMetadata(); - Logs.Tester.LogInformation("Now, let's create an invoice with the new API but with the same metadata as Bitpay"); + TestLogs.LogInformation("Now, let's create an invoice with the new API but with the same metadata as Bitpay"); newInvoice.Metadata.Add("lol", "lol"); newInvoice = await client.CreateInvoice(user.StoreId, new CreateInvoiceRequest() { @@ -1032,7 +1029,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanOverpayInvoice() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1064,7 +1061,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task InvoiceTests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1407,7 +1404,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUseLightningAPI() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -1495,7 +1492,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task NotificationAPITests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); await tester.StartAsync(); var user = tester.NewAccount(); await user.GrantAccessAsync(true); @@ -1534,7 +1531,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task OnChainPaymentMethodAPITests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); await tester.StartAsync(); var user = tester.NewAccount(); var user2 = tester.NewAccount(); @@ -1651,7 +1648,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task LightningNetworkPaymentMethodAPITests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); tester.ActivateLightning(); await tester.StartAsync(); await tester.EnsureChannelsSetup(); @@ -1768,7 +1765,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task WalletAPITests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); await tester.StartAsync(); var user = tester.NewAccount(); @@ -1989,7 +1986,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task StorePaymentMethodsAPITests() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); tester.ActivateLightning(); await tester.StartAsync(); await tester.EnsureChannelsSetup(); diff --git a/BTCPayServer.Tests/LanguageServiceTests.cs b/BTCPayServer.Tests/LanguageServiceTests.cs index cf1ba2f75..3f48bd450 100644 --- a/BTCPayServer.Tests/LanguageServiceTests.cs +++ b/BTCPayServer.Tests/LanguageServiceTests.cs @@ -6,20 +6,18 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class LanguageServiceTests + public class LanguageServiceTests : UnitTestBase { public const int TestTimeout = TestUtils.TestTimeout; - public LanguageServiceTests(ITestOutputHelper helper) + public LanguageServiceTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = TestTimeout)] [Trait("Integration", "Integration")] public async Task CanAutoDetectLanguage() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var languageService = tester.PayTester.GetService(); diff --git a/BTCPayServer.Tests/Logging/Logs.cs b/BTCPayServer.Tests/Logging/Logs.cs index 109ef28c6..0357e4407 100644 --- a/BTCPayServer.Tests/Logging/Logs.cs +++ b/BTCPayServer.Tests/Logging/Logs.cs @@ -77,16 +77,4 @@ namespace BTCPayServer.Tests.Logging catch { } } } - public class Logs - { - public static ILog Tester - { - get; set; - } - public static XUnitLogProvider LogProvider - { - get; - set; - } - } } diff --git a/BTCPayServer.Tests/POSTests.cs b/BTCPayServer.Tests/POSTests.cs index 1c319b70e..a31b09fd5 100644 --- a/BTCPayServer.Tests/POSTests.cs +++ b/BTCPayServer.Tests/POSTests.cs @@ -10,19 +10,17 @@ using static BTCPayServer.Tests.UnitTest1; namespace BTCPayServer.Tests { - public class POSTests + public class POSTests : UnitTestBase { - public POSTests(ITestOutputHelper helper) + public POSTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = LongRunningTestTimeout)] [Trait("Integration", "Integration")] public async Task CanUsePoSApp1() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); diff --git a/BTCPayServer.Tests/PSBTTests.cs b/BTCPayServer.Tests/PSBTTests.cs index 50397ebe4..c802be885 100644 --- a/BTCPayServer.Tests/PSBTTests.cs +++ b/BTCPayServer.Tests/PSBTTests.cs @@ -13,18 +13,16 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class PSBTTests + public class PSBTTests : UnitTestBase { - public PSBTTests(ITestOutputHelper helper) + public PSBTTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] [Trait("Integration", "Integration")] public async Task CanPlayWithPSBT() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); diff --git a/BTCPayServer.Tests/PayJoinTests.cs b/BTCPayServer.Tests/PayJoinTests.cs index bba3d05b0..ba99b29ee 100644 --- a/BTCPayServer.Tests/PayJoinTests.cs +++ b/BTCPayServer.Tests/PayJoinTests.cs @@ -33,21 +33,19 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class PayJoinTests + public class PayJoinTests : UnitTestBase { public const int TestTimeout = 60_000; - public PayJoinTests(ITestOutputHelper helper) + public PayJoinTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] [Trait("Integration", "Integration")] public async Task CanUseTheDelayedBroadcaster() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var network = tester.NetworkProvider.GetNetwork("BTC"); @@ -68,7 +66,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUsePayjoinRepository() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var network = tester.NetworkProvider.GetNetwork("BTC"); @@ -108,7 +106,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task ChooseBestUTXOsForPayjoin() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var network = tester.NetworkProvider.GetNetwork("BTC"); @@ -169,7 +167,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanOnlyUseCorrectAddressFormatsForPayjoin() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var broadcaster = tester.PayTester.GetService(); @@ -197,7 +195,7 @@ namespace BTCPayServer.Tests continue; var senderCoin = await senderUser.ReceiveUTXO(Money.Satoshis(100000), network); - Logs.Tester.LogInformation($"Testing payjoin with sender: {senderAddressType} receiver: {receiverAddressType}"); + TestLogs.LogInformation($"Testing payjoin with sender: {senderAddressType} receiver: {receiverAddressType}"); var receiverUser = tester.NewAccount(); receiverUser.GrantAccess(true); receiverUser.RegisterDerivationScheme("BTC", receiverAddressType, true); @@ -231,7 +229,7 @@ namespace BTCPayServer.Tests [Trait("Selenium", "Selenium")] public async Task CanUsePayjoinForTopUp() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -282,7 +280,7 @@ namespace BTCPayServer.Tests [Trait("Selenium", "Selenium")] public async Task CanUsePayjoinViaUI() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); var invoiceRepository = s.Server.PayTester.GetService(); @@ -416,7 +414,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUsePayjoin2() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var pjClient = tester.PayTester.GetService(); @@ -481,7 +479,7 @@ namespace BTCPayServer.Tests Assert.Equal(changeIndex.ToString(), request.Request.Query["additionalfeeoutputindex"][0]); Assert.Equal("1146", request.Request.Query["maxadditionalfeecontribution"][0]); - Logs.Tester.LogInformation("The payjoin receiver tries to make us pay lots of fee"); + TestLogs.LogInformation("The payjoin receiver tries to make us pay lots of fee"); var originalPSBT = await ParsePSBT(request); var proposalTx = originalPSBT.GetGlobalTransaction(); proposalTx.Outputs[changeIndex].Value -= Money.Satoshis(1147); @@ -490,7 +488,7 @@ namespace BTCPayServer.Tests var ex = await Assert.ThrowsAsync(async () => await requesting); Assert.Contains("contribution is more than maxadditionalfeecontribution", ex.Message); - Logs.Tester.LogInformation("The payjoin receiver tries to change one of our output"); + TestLogs.LogInformation("The payjoin receiver tries to change one of our output"); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); originalPSBT = await ParsePSBT(request); @@ -500,7 +498,7 @@ namespace BTCPayServer.Tests fakeServer.Done(); ex = await Assert.ThrowsAsync(async () => await requesting); Assert.Contains("The receiver decreased the value of one", ex.Message); - Logs.Tester.LogInformation("The payjoin receiver tries to pocket the fee"); + TestLogs.LogInformation("The payjoin receiver tries to pocket the fee"); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); originalPSBT = await ParsePSBT(request); @@ -511,7 +509,7 @@ namespace BTCPayServer.Tests ex = await Assert.ThrowsAsync(async () => await requesting); Assert.Contains("The receiver decreased absolute fee", ex.Message); - Logs.Tester.LogInformation("The payjoin receiver tries to remove one of our output"); + TestLogs.LogInformation("The payjoin receiver tries to remove one of our output"); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); originalPSBT = await ParsePSBT(request); @@ -523,7 +521,7 @@ namespace BTCPayServer.Tests ex = await Assert.ThrowsAsync(async () => await requesting); Assert.Contains("Some of our outputs are not included in the proposal", ex.Message); - Logs.Tester.LogInformation("The payjoin receiver tries to change their own output"); + TestLogs.LogInformation("The payjoin receiver tries to change their own output"); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); originalPSBT = await ParsePSBT(request); @@ -534,7 +532,7 @@ namespace BTCPayServer.Tests await requesting; - Logs.Tester.LogInformation("The payjoin receiver tries to send money to himself"); + TestLogs.LogInformation("The payjoin receiver tries to send money to himself"); pjClient.MaxFeeBumpContribution = Money.Satoshis(1); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); @@ -547,7 +545,7 @@ namespace BTCPayServer.Tests ex = await Assert.ThrowsAsync(async () => await requesting); Assert.Contains("is not only paying fee", ex.Message); pjClient.MaxFeeBumpContribution = null; - Logs.Tester.LogInformation("The payjoin receiver can't use additional fee without adding inputs"); + TestLogs.LogInformation("The payjoin receiver can't use additional fee without adding inputs"); pjClient.MinimumFeeRate = new FeeRate(50m); requesting = pjClient.RequestPayjoin(bip21, new PayjoinWallet(derivationSchemeSettings), psbt, default); request = await fakeServer.GetNextRequest(); @@ -560,7 +558,7 @@ namespace BTCPayServer.Tests Assert.Contains("is not only paying for additional inputs", ex.Message); pjClient.MinimumFeeRate = null; - Logs.Tester.LogInformation("Make sure the receiver implementation do not take more fee than allowed"); + TestLogs.LogInformation("Make sure the receiver implementation do not take more fee than allowed"); var bob = tester.NewAccount(); await bob.GrantAccessAsync(); await bob.RegisterDerivationSchemeAsync("BTC", ScriptPubKeyType.Segwit, true); @@ -603,7 +601,7 @@ namespace BTCPayServer.Tests await tester.ExplorerNode.SendRawTransactionAsync(proposal.ExtractTransaction()); await notifications.NextEventAsync(); - Logs.Tester.LogInformation("Abusing minFeeRate should give not enough money error"); + TestLogs.LogInformation("Abusing minFeeRate should give not enough money error"); invoice = bob.BitPay.CreateInvoice( new Invoice() { Price = 0.1m, Currency = "BTC", FullNotifications = true }); invoiceBIP21 = new BitcoinUrlBuilder(invoice.CryptoInfo.First().PaymentUrls.BIP21, @@ -642,7 +640,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUsePayjoinFeeCornerCase() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var broadcaster = tester.PayTester.GetService(); @@ -733,17 +731,17 @@ namespace BTCPayServer.Tests } } - Logs.Tester.LogInformation("Here we send exactly the right amount. This should fails as\n" + + TestLogs.LogInformation("Here we send exactly the right amount. This should fails as\n" + "there is not enough to pay the additional payjoin input. (going below the min relay fee" + "However, the original tx has been broadcasted!"); vector = (SpentCoin: Money.Satoshis(810), InvoiceAmount: Money.Satoshis(700), Paid: Money.Satoshis(700), Fee: Money.Satoshis(110), InvoicePaid: true, ExpectedError: "not-enough-money", OriginalTxBroadcasted: true); await RunVector(); - Logs.Tester.LogInformation("We don't pay enough"); + TestLogs.LogInformation("We don't pay enough"); vector = (SpentCoin: Money.Satoshis(810), InvoiceAmount: Money.Satoshis(700), Paid: Money.Satoshis(690), Fee: Money.Satoshis(110), InvoicePaid: false, ExpectedError: "invoice-not-fully-paid", OriginalTxBroadcasted: true); await RunVector(); - Logs.Tester.LogInformation("We pay correctly"); + TestLogs.LogInformation("We pay correctly"); vector = (SpentCoin: Money.Satoshis(810), InvoiceAmount: Money.Satoshis(500), Paid: Money.Satoshis(500), Fee: Money.Satoshis(110), InvoicePaid: true, ExpectedError: null as string, OriginalTxBroadcasted: false); await RunVector(); @@ -751,7 +749,7 @@ namespace BTCPayServer.Tests var outputCountReceived = new bool[2]; do { - Logs.Tester.LogInformation("We pay a little bit more the invoice with enough fees to support additional input\n" + + TestLogs.LogInformation("We pay a little bit more the invoice with enough fees to support additional input\n" + "The receiver should have added a fake output"); vector = (SpentCoin: Money.Satoshis(910), InvoiceAmount: Money.Satoshis(500), Paid: Money.Satoshis(700), Fee: Money.Satoshis(110), InvoicePaid: true, ExpectedError: null as string, OriginalTxBroadcasted: false); proposedPSBT = await RunVector(); @@ -760,7 +758,7 @@ namespace BTCPayServer.Tests cashCow.Generate(1); } while (outputCountReceived.All(o => o)); - Logs.Tester.LogInformation("We pay correctly, but no utxo\n" + + TestLogs.LogInformation("We pay correctly, but no utxo\n" + "However, this has the side effect of having the receiver broadcasting the original tx"); await payjoinRepository.TryLock(receiverCoin.Outpoint); vector = (SpentCoin: Money.Satoshis(810), InvoiceAmount: Money.Satoshis(500), Paid: Money.Satoshis(500), Fee: Money.Satoshis(110), InvoicePaid: true, ExpectedError: "unavailable|any UTXO available", OriginalTxBroadcasted: true); @@ -773,7 +771,7 @@ retry: // We paid 510, the receiver pay 10 sat // The send pay remaining 86 sat from his pocket // So total paid by sender should be 86 + 510 + 200 so we should get 1090 - (86 + 510 + 200) == 294 back) - Logs.Tester.LogInformation($"Check if we can take fee on overpaid utxo{(senderUser == receiverUser ? " (to self)" : "")}"); + TestLogs.LogInformation($"Check if we can take fee on overpaid utxo{(senderUser == receiverUser ? " (to self)" : "")}"); vector = (SpentCoin: Money.Satoshis(1090), InvoiceAmount: Money.Satoshis(500), Paid: Money.Satoshis(510), Fee: Money.Satoshis(200), InvoicePaid: true, ExpectedError: null as string, OriginalTxBroadcasted: false); proposedPSBT = await RunVector(); Assert.Equal(2, proposedPSBT.Outputs.Count); @@ -784,8 +782,8 @@ retry: var explorerClient = tester.PayTester.GetService().GetExplorerClient(proposedPSBT.Network.NetworkSet.CryptoCode); var result = await explorerClient.BroadcastAsync(proposedPSBT.ExtractTransaction()); Assert.True(result.Success); - Logs.Tester.LogInformation($"We broadcasted the payjoin {proposedPSBT.ExtractTransaction().GetHash()}"); - Logs.Tester.LogInformation($"Let's make sure that the coinjoin is not over paying, since the 10 overpaid sats have gone to fee"); + TestLogs.LogInformation($"We broadcasted the payjoin {proposedPSBT.ExtractTransaction().GetHash()}"); + TestLogs.LogInformation($"Let's make sure that the coinjoin is not over paying, since the 10 overpaid sats have gone to fee"); await TestUtils.EventuallyAsync(async () => { var invoice = await tester.PayTester.GetService().GetInvoice(lastInvoiceId); @@ -800,7 +798,7 @@ retry: await LockAllButReceiverCoin(); if (senderUser != receiverUser) { - Logs.Tester.LogInformation("Let's do the same, this time paying to ourselves"); + TestLogs.LogInformation("Let's do the same, this time paying to ourselves"); senderUser = receiverUser; goto retry; } @@ -832,7 +830,7 @@ retry: [Trait("Integration", "Integration")] public async Task CanUsePayjoin() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); diff --git a/BTCPayServer.Tests/PaymentRequestTests.cs b/BTCPayServer.Tests/PaymentRequestTests.cs index 907a8261c..5ca5d114e 100644 --- a/BTCPayServer.Tests/PaymentRequestTests.cs +++ b/BTCPayServer.Tests/PaymentRequestTests.cs @@ -17,19 +17,17 @@ using Xunit.Abstractions; namespace BTCPayServer.Tests { - public class PaymentRequestTests + public class PaymentRequestTests : UnitTestBase { - public PaymentRequestTests(ITestOutputHelper helper) + public PaymentRequestTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) {Name = "Tests"}; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact] [Trait("Integration", "Integration")] public async Task CanCreateViewUpdateAndDeletePaymentRequest() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -100,7 +98,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanPayPaymentRequestWhenPossible() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -166,7 +164,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCancelPaymentWhenPossible() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); diff --git a/BTCPayServer.Tests/SeleniumTester.cs b/BTCPayServer.Tests/SeleniumTester.cs index 4f525596c..0dd2f92d3 100644 --- a/BTCPayServer.Tests/SeleniumTester.cs +++ b/BTCPayServer.Tests/SeleniumTester.cs @@ -31,9 +31,6 @@ namespace BTCPayServer.Tests public string StoreId { get; set; } - public static SeleniumTester Create([CallerMemberNameAttribute] string scope = null, bool newDb = false) => - new SeleniumTester { Server = ServerTester.Create(scope, newDb) }; - public static readonly TimeSpan ImplicitWait = TimeSpan.FromSeconds(5); public async Task StartAsync() @@ -65,7 +62,7 @@ namespace BTCPayServer.Tests Driver = new OpenQA.Selenium.Remote.RemoteWebDriver(new Uri("http://selenium:4444/wd/hub"), new RemoteSessionSettings(options)); var containerIp = File.ReadAllText("/etc/hosts").Split('\n', StringSplitOptions.RemoveEmptyEntries).Last() .Split('\t', StringSplitOptions.RemoveEmptyEntries)[0].Trim(); - Logs.Tester.LogInformation($"Selenium: Container's IP {containerIp}"); + TestLogs.LogInformation($"Selenium: Container's IP {containerIp}"); ServerUri = new Uri(Server.PayTester.ServerUri.AbsoluteUri.Replace($"http://{Server.PayTester.HostName}", $"http://{containerIp}", StringComparison.OrdinalIgnoreCase), UriKind.Absolute); } else @@ -82,9 +79,9 @@ namespace BTCPayServer.Tests } Driver.Manage().Window.Maximize(); - Logs.Tester.LogInformation($"Selenium: Using {Driver.GetType()}"); - Logs.Tester.LogInformation($"Selenium: Browsing to {ServerUri}"); - Logs.Tester.LogInformation($"Selenium: Resolution {Driver.Manage().Window.Size}"); + TestLogs.LogInformation($"Selenium: Using {Driver.GetType()}"); + TestLogs.LogInformation($"Selenium: Browsing to {ServerUri}"); + TestLogs.LogInformation($"Selenium: Resolution {Driver.Manage().Window.Size}"); GoToRegister(); Driver.AssertNoError(); } @@ -120,7 +117,7 @@ namespace BTCPayServer.Tests public string RegisterNewUser(bool isAdmin = false) { var usr = RandomUtils.GetUInt256().ToString().Substring(64 - 20) + "@a.com"; - Logs.Tester.LogInformation($"User: {usr} with password 123456"); + TestLogs.LogInformation($"User: {usr} with password 123456"); Driver.FindElement(By.Id("Email")).SendKeys(usr); Driver.FindElement(By.Id("Password")).SendKeys("123456"); Driver.FindElement(By.Id("ConfirmPassword")).SendKeys("123456"); @@ -162,7 +159,7 @@ namespace BTCPayServer.Tests if (isImport) { - Logs.Tester.LogInformation("Progressing with existing seed"); + TestLogs.LogInformation("Progressing with existing seed"); Driver.FindElement(By.Id("ImportWalletOptionsLink")).Click(); Driver.FindElement(By.Id("ImportSeedLink")).Click(); Driver.FindElement(By.Id("ExistingMnemonic")).SendKeys(seed); @@ -171,7 +168,7 @@ namespace BTCPayServer.Tests else { var option = privkeys ? "Hotwallet" : "Watchonly"; - Logs.Tester.LogInformation($"Generating new seed ({option})"); + TestLogs.LogInformation($"Generating new seed ({option})"); Driver.FindElement(By.Id("GenerateWalletLink")).Click(); Driver.FindElement(By.Id($"Generate{option}Link")).Click(); } @@ -265,13 +262,14 @@ namespace BTCPayServer.Tests } } + public Logging.ILog TestLogs => Server.TestLogs; public void ClickOnAllSideMenus() { var links = Driver.FindElements(By.CssSelector(".nav .nav-link")).Select(c => c.GetAttribute("href")).ToList(); Driver.AssertNoError(); foreach (var l in links) { - Logs.Tester.LogInformation($"Checking no error on {l}"); + TestLogs.LogInformation($"Checking no error on {l}"); Driver.Navigate().GoToUrl(l); Driver.AssertNoError(); } @@ -451,7 +449,7 @@ namespace BTCPayServer.Tests // // if (jsErrors.Any()) // { - // Logs.Tester.LogInformation("JavaScript error(s):" + Environment.NewLine + jsErrors.Aggregate("", (s, entry) => s + entry.Message + Environment.NewLine)); + // TestLogs.LogInformation("JavaScript error(s):" + Environment.NewLine + jsErrors.Aggregate("", (s, entry) => s + entry.Message + Environment.NewLine)); // } // Assert.Empty(jsErrors); diff --git a/BTCPayServer.Tests/SeleniumTests.cs b/BTCPayServer.Tests/SeleniumTests.cs index c46f507c7..b9d72d607 100644 --- a/BTCPayServer.Tests/SeleniumTests.cs +++ b/BTCPayServer.Tests/SeleniumTests.cs @@ -43,20 +43,18 @@ using CreateInvoiceRequest = BTCPayServer.Lightning.Charge.CreateInvoiceRequest; namespace BTCPayServer.Tests { [Trait("Selenium", "Selenium")] - public class ChromeTests + public class ChromeTests : UnitTestBase { private const int TestTimeout = TestUtils.TestTimeout; - public ChromeTests(ITestOutputHelper helper) + public ChromeTests(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } [Fact(Timeout = TestTimeout)] public async Task CanNavigateServerSettings() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -65,7 +63,7 @@ namespace BTCPayServer.Tests s.ClickOnAllSideMenus(); s.Driver.FindElement(By.LinkText("Services")).Click(); - Logs.Tester.LogInformation("Let's check if we can access the logs"); + TestLogs.LogInformation("Let's check if we can access the logs"); s.Driver.FindElement(By.LinkText("Logs")).Click(); s.Driver.FindElement(By.PartialLinkText(".log")).Click(); Assert.Contains("Starting listening NBXplorer", s.Driver.PageSource); @@ -77,7 +75,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUseLndSeedBackup() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLightning(); await s.StartAsync(); @@ -86,7 +84,7 @@ namespace BTCPayServer.Tests s.Driver.AssertNoError(); s.Driver.FindElement(By.LinkText("Services")).Click(); - Logs.Tester.LogInformation("Let's if we can access LND's seed"); + TestLogs.LogInformation("Let's if we can access LND's seed"); Assert.Contains("server/services/lndseedbackup/BTC", s.Driver.PageSource); s.Driver.Navigate().GoToUrl(s.Link("/server/services/lndseedbackup/BTC")); s.Driver.FindElement(By.Id("details")).Click(); @@ -109,7 +107,7 @@ namespace BTCPayServer.Tests [Trait("Selenium", "Selenium")] public async Task CanChangeUserMail() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); @@ -147,7 +145,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task NewUserLogin() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); //Register & Log Out @@ -232,7 +230,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseSSHService() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); var settings = s.Server.PayTester.GetService(); @@ -289,7 +287,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanSetupEmailServer() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(isAdmin: true); @@ -310,7 +308,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseDynamicDns() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(isAdmin: true); @@ -362,7 +360,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanCreateStores() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { s.Server.ActivateLightning(); await s.StartAsync(); @@ -470,7 +468,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUsePairing() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.Driver.Navigate().GoToUrl(s.Link("/api-access-request")); @@ -515,7 +513,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanCreateAppPoS() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(); @@ -555,7 +553,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanCreateCrowdfundingApp() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(); @@ -582,7 +580,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanCreatePayRequest() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(); @@ -624,7 +622,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseCoinSelection() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -686,14 +684,14 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanUseWebhooks() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); var (storeName, storeId) = s.CreateNewStore(); s.GoToStore(storeId, StoreNavPages.Webhooks); - Logs.Tester.LogInformation("Let's create two webhooks"); + TestLogs.LogInformation("Let's create two webhooks"); for (var i = 0; i < 2; i++) { s.Driver.FindElement(By.Id("CreateWebhook")).Click(); @@ -704,7 +702,7 @@ namespace BTCPayServer.Tests s.Driver.FindElement(By.Name("add")).Click(); } - Logs.Tester.LogInformation("Let's delete one of them"); + TestLogs.LogInformation("Let's delete one of them"); var deletes = s.Driver.FindElements(By.LinkText("Delete")); Assert.Equal(2, deletes.Count); deletes[0].Click(); @@ -714,7 +712,7 @@ namespace BTCPayServer.Tests Assert.Single(deletes); s.FindAlertMessage(); - Logs.Tester.LogInformation("Let's try to update one of them"); + TestLogs.LogInformation("Let's try to update one of them"); s.Driver.FindElement(By.LinkText("Modify")).Click(); using FakeServer server = new FakeServer(); @@ -744,7 +742,7 @@ namespace BTCPayServer.Tests s.FindAlertMessage(); Assert.Contains(server.ServerUri.AbsoluteUri, s.Driver.PageSource); - Logs.Tester.LogInformation("Let's see if we can generate an event"); + TestLogs.LogInformation("Let's see if we can generate an event"); s.GoToStore(storeId); s.AddDerivationScheme(); s.CreateInvoice(storeName); @@ -758,7 +756,7 @@ namespace BTCPayServer.Tests request.Response.StatusCode = 200; server.Done(); - Logs.Tester.LogInformation("Let's make a failed event"); + TestLogs.LogInformation("Let's make a failed event"); s.CreateInvoice(storeName); request = await server.GetNextRequest(); request.Response.StatusCode = 404; @@ -779,7 +777,7 @@ namespace BTCPayServer.Tests request.Response.StatusCode = 404; server.Done(); - Logs.Tester.LogInformation("Can we browse the json content?"); + TestLogs.LogInformation("Can we browse the json content?"); CanBrowseContent(s); s.GoToInvoices(); @@ -793,7 +791,7 @@ namespace BTCPayServer.Tests request.Response.StatusCode = 404; server.Done(); - Logs.Tester.LogInformation("Let's see if we can delete store with some webhooks inside"); + TestLogs.LogInformation("Let's see if we can delete store with some webhooks inside"); s.GoToStore(storeId, StoreNavPages.GeneralSettings); s.Driver.FindElement(By.Id("delete-store")).Click(); s.Driver.WaitForElement(By.Id("ConfirmContinue")).Click(); @@ -804,7 +802,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanImportMnemonic() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -825,7 +823,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanManageWallet() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -992,7 +990,7 @@ namespace BTCPayServer.Tests [Fact(Timeout = TestTimeout)] public async Task CanImportWallet() { - using (var s = SeleniumTester.Create()) + using (var s = CreateSeleniumTester()) { await s.StartAsync(); s.RegisterNewUser(true); @@ -1014,7 +1012,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUsePullPaymentsViaUI() { - using var s = SeleniumTester.Create(); + using var s = CreateSeleniumTester(); s.Server.ActivateLightning(); await s.StartAsync(); s.RegisterNewUser(true); @@ -1258,7 +1256,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUsePOSPrint() { - using var s = SeleniumTester.Create(); + using var s = CreateSeleniumTester(); s.Server.ActivateLightning(); await s.StartAsync(); @@ -1302,7 +1300,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUseLNURL() { - using var s = SeleniumTester.Create(); + using var s = CreateSeleniumTester(); s.Server.ActivateLightning(); await s.StartAsync(); await s.Server.EnsureChannelsSetup(); @@ -1493,7 +1491,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanUseLNAddress() { - using var s = SeleniumTester.Create(); + using var s = CreateSeleniumTester(); s.Server.ActivateLightning(); await s.StartAsync(); await s.Server.EnsureChannelsSetup(); diff --git a/BTCPayServer.Tests/ServerTester.cs b/BTCPayServer.Tests/ServerTester.cs index efeaad981..1896f15c4 100644 --- a/BTCPayServer.Tests/ServerTester.cs +++ b/BTCPayServer.Tests/ServerTester.cs @@ -11,6 +11,7 @@ using BTCPayServer.Lightning.CLightning; using BTCPayServer.Payments.Lightning; using BTCPayServer.Tests.Lnd; using BTCPayServer.Tests.Logging; +using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.RPC; using NBitpayClient; @@ -20,15 +21,16 @@ namespace BTCPayServer.Tests { public class ServerTester : IDisposable { - public static ServerTester Create([CallerMemberNameAttribute] string scope = null, bool newDb = false) - { - return new ServerTester(scope, newDb); - } - public List Resources = new List(); readonly string _Directory; - public ServerTester(string scope, bool newDb) + + public ILoggerProvider LoggerProvider { get; } + + internal ILog TestLogs; + public ServerTester(string scope, bool newDb, ILog testLogs, ILoggerProvider loggerProvider) { + LoggerProvider = loggerProvider; + this.TestLogs = testLogs; _Directory = scope; if (Directory.Exists(_Directory)) Utils.DeleteDirectory(_Directory); @@ -41,7 +43,7 @@ namespace BTCPayServer.Tests ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); - PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) + PayTester = new BTCPayServerTester(TestLogs, LoggerProvider, Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, TestDatabase = Enum.Parse(GetEnvironment("TESTS_DB", TestDatabases.Postgres.ToString()), true), @@ -150,10 +152,10 @@ namespace BTCPayServer.Tests /// public async Task EnsureChannelsSetup() { - Logs.Tester.LogInformation("Connecting channels"); - BTCPayServer.Lightning.Tests.ConnectChannels.Logs = Logs.LogProvider.CreateLogger("Connect channels"); + TestLogs.LogInformation("Connecting channels"); + BTCPayServer.Lightning.Tests.ConnectChannels.Logs = LoggerProvider.CreateLogger("Connect channels"); await BTCPayServer.Lightning.Tests.ConnectChannels.ConnectAll(ExplorerNode, GetLightningSenderClients(), GetLightningDestClients()).ConfigureAwait(false); - Logs.Tester.LogInformation("Channels connected"); + TestLogs.LogInformation("Channels connected"); } private IEnumerable GetLightningSenderClients() @@ -248,14 +250,14 @@ namespace BTCPayServer.Tests { foreach (var r in this.Resources) r.Dispose(); - Logs.Tester.LogInformation("Disposing the BTCPayTester..."); + TestLogs.LogInformation("Disposing the BTCPayTester..."); foreach (var store in Stores) { Xunit.Assert.True(PayTester.StoreRepository.DeleteStore(store).GetAwaiter().GetResult()); } if (PayTester != null) PayTester.Dispose(); - Logs.Tester.LogInformation("BTCPayTester disposed"); + TestLogs.LogInformation("BTCPayTester disposed"); } } } diff --git a/BTCPayServer.Tests/TestAccount.cs b/BTCPayServer.Tests/TestAccount.cs index 0362a9c45..b4c06688b 100644 --- a/BTCPayServer.Tests/TestAccount.cs +++ b/BTCPayServer.Tests/TestAccount.cs @@ -331,7 +331,7 @@ namespace BTCPayServer.Tests return psbt.SignAll(this.DerivationScheme, GenerateWalletResponseV.AccountHDKey, GenerateWalletResponseV.AccountKeyPath); } - + Logging.ILog TestLogs => this.parent.TestLogs; public async Task SubmitPayjoin(Invoice invoice, PSBT psbt, string expectedError = null, bool senderError = false) { var endpoint = GetPayjoinBitcoinUrl(invoice, psbt.Network); @@ -344,11 +344,11 @@ namespace BTCPayServer.Tests var store = await storeRepository.FindStore(StoreId); var settings = store.GetSupportedPaymentMethods(parent.NetworkProvider).OfType() .First(); - Logs.Tester.LogInformation($"Proposing {psbt.GetGlobalTransaction().GetHash()}"); + TestLogs.LogInformation($"Proposing {psbt.GetGlobalTransaction().GetHash()}"); if (expectedError is null && !senderError) { var proposed = await pjClient.RequestPayjoin(endpoint, new PayjoinWallet(settings), psbt, default); - Logs.Tester.LogInformation($"Proposed payjoin is {proposed.GetGlobalTransaction().GetHash()}"); + TestLogs.LogInformation($"Proposed payjoin is {proposed.GetGlobalTransaction().GetHash()}"); Assert.NotNull(proposed); return proposed; } diff --git a/BTCPayServer.Tests/ThirdPartyTests.cs b/BTCPayServer.Tests/ThirdPartyTests.cs index 5d4240a38..62ab3a5d9 100644 --- a/BTCPayServer.Tests/ThirdPartyTests.cs +++ b/BTCPayServer.Tests/ThirdPartyTests.cs @@ -37,7 +37,7 @@ namespace BTCPayServer.Tests [FactWithSecret("AzureBlobStorageConnectionString")] public async Task CanUseAzureBlobStorage() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -339,7 +339,7 @@ namespace BTCPayServer.Tests [Fact] public async Task CanUseExchangeSpecificRate() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.PayTester.MockRates = false; await tester.StartAsync(); diff --git a/BTCPayServer.Tests/UnitTest1.cs b/BTCPayServer.Tests/UnitTest1.cs index ee479660c..bdd9352c8 100644 --- a/BTCPayServer.Tests/UnitTest1.cs +++ b/BTCPayServer.Tests/UnitTest1.cs @@ -74,14 +74,12 @@ using RatesViewModel = BTCPayServer.Models.StoreViewModels.RatesViewModel; namespace BTCPayServer.Tests { - public class UnitTest1 + public class UnitTest1 : UnitTestBase { public const int LongRunningTestTimeout = 60_000; // 60s - public UnitTest1(ITestOutputHelper helper) + public UnitTest1(ITestOutputHelper helper) : base(helper) { - Logs.Tester = new XUnitLog(helper) { Name = "Tests" }; - Logs.LogProvider = new XUnitLogProvider(helper); } class DockerImage @@ -134,7 +132,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CheckSwaggerIsConformToSchema() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -164,7 +162,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task EnsureSwaggerPermissionsDocumented() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -188,7 +186,7 @@ namespace BTCPayServer.Tests string.Join("\n", serverPolicies.Select(pair => $"* `{pair.Key}`: {pair.Value.Title}"))) .Replace("#STOREPERMISSIONS#", string.Join("\n", storePolicies.Select(pair => $"* `{pair.Key}`: {pair.Value.Title}"))); - Logs.Tester.LogInformation(description); + TestLogs.LogInformation(description); var sresp = Assert .IsType(await tester.PayTester.GetController(acc.UserId, acc.StoreId) @@ -200,7 +198,7 @@ namespace BTCPayServer.Tests } } - private static async Task CheckDeadLinks(Regex regex, HttpClient httpClient, string file) + private async Task CheckDeadLinks(Regex regex, HttpClient httpClient, string file) { List checkLinks = new List(); var text = await File.ReadAllTextAsync(file); @@ -224,7 +222,7 @@ namespace BTCPayServer.Tests await Task.WhenAll(checkLinks); } - private static async Task AssertLinkNotDead(HttpClient httpClient, string url, string file) + private async Task AssertLinkNotDead(HttpClient httpClient, string url, string file) { var uri = new Uri(url); @@ -238,7 +236,7 @@ namespace BTCPayServer.Tests var response = await httpClient.SendAsync(request); if (response.StatusCode == HttpStatusCode.ServiceUnavailable) // Temporary issue { - Logs.Tester.LogInformation($"Unavailable: {url} ({file})"); + TestLogs.LogInformation($"Unavailable: {url} ({file})"); return; } Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -249,19 +247,19 @@ namespace BTCPayServer.Tests Assert.Matches($"id=\"{fragment}\"", contents); } - Logs.Tester.LogInformation($"OK: {url} ({file})"); + TestLogs.LogInformation($"OK: {url} ({file})"); } catch (Exception ex) when (ex is MatchesException) { var details = ex.Message; - Logs.Tester.LogInformation($"FAILED: {url} ({file}) – anchor not found: {uri.Fragment}"); + TestLogs.LogInformation($"FAILED: {url} ({file}) – anchor not found: {uri.Fragment}"); throw; } catch (Exception ex) { var details = ex is EqualException ? (ex as EqualException).Actual : ex.Message; - Logs.Tester.LogInformation($"FAILED: {url} ({file}) {details}"); + TestLogs.LogInformation($"FAILED: {url} ({file}) {details}"); throw; } @@ -271,7 +269,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanAcceptInvoiceWithTolerance2() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -315,7 +313,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanThrowBitpay404Error() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -356,7 +354,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task EnsureNewLightningInvoiceOnPartialPayment() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); tester.ActivateLightning(); await tester.StartAsync(); await tester.EnsureChannelsSetup(); @@ -385,7 +383,7 @@ namespace BTCPayServer.Tests BOLT11PaymentRequest.Parse(newBolt11, Network.RegTest).MinimumAmount.ToDecimal(LightMoneyUnit.BTC)); }, 40000); - Logs.Tester.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(async () => { await tester.SendLightningPaymentAsync(newInvoice); @@ -396,14 +394,14 @@ namespace BTCPayServer.Tests Assert.Equal(InvoiceExceptionStatus.None, fetchedInvoice.ExceptionStatus); //BTCPay will attempt to cancel previous bolt11 invoices so that there are less weird edge case scenarios - Logs.Tester.LogInformation($"Attempting to pay invoice {invoice.Id} original full amount bolt11 invoice "); + TestLogs.LogInformation($"Attempting to pay invoice {invoice.Id} original full amount bolt11 invoice "); await Assert.ThrowsAsync(async () => { await tester.SendLightningPaymentAsync(invoice); }); //NOTE: Eclair does not support cancelling invoice so the below test case would make sense for it - // Logs.Tester.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(async () => // { // await tester.SendLightningPaymentAsync(invoice); @@ -418,7 +416,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanSetLightningServer() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -487,7 +485,7 @@ namespace BTCPayServer.Tests // For easier debugging and testing // LightningLikePaymentHandler.LIGHTNING_TIMEOUT = int.MaxValue; - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -515,9 +513,9 @@ namespace BTCPayServer.Tests ItemDesc = "Some description" }); await Task.Delay(TimeSpan.FromMilliseconds(1000)); // Give time to listen the new invoices - Logs.Tester.LogInformation($"Trying to send Lightning payment to {invoice.Id}"); + TestLogs.LogInformation($"Trying to send Lightning payment to {invoice.Id}"); await tester.SendLightningPaymentAsync(invoice); - Logs.Tester.LogInformation($"Lightning payment to {invoice.Id} is sent"); + TestLogs.LogInformation($"Lightning payment to {invoice.Id} is sent"); await TestUtils.EventuallyAsync(async () => { var localInvoice = await user.BitPay.GetInvoiceAsync(invoice.Id); @@ -531,7 +529,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUseServerInitiatedPairingCode() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -560,7 +558,7 @@ namespace BTCPayServer.Tests { using (var callbackServer = new CustomServer()) { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -629,7 +627,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CantPairTwiceWithSamePubkey() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -653,7 +651,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUseTorClient() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var proxy = tester.PayTester.GetService(); @@ -690,12 +688,12 @@ namespace BTCPayServer.Tests response.EnsureSuccessStatusCode(); AssertConnectionDropped(); - Logs.Tester.LogInformation("Querying an onion address which can't be found should send http 500"); + TestLogs.LogInformation("Querying an onion address which can't be found should send http 500"); response = await client.GetAsync("http://dwoduwoi.onion/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); AssertConnectionDropped(); - Logs.Tester.LogInformation("Querying valid onion but unreachable should send error 502"); + TestLogs.LogInformation("Querying valid onion but unreachable should send error 502"); using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(20))) { try @@ -706,7 +704,7 @@ namespace BTCPayServer.Tests } catch when (cts.Token.IsCancellationRequested) { - Logs.Tester.LogInformation("Skipping this test, it timed out"); + TestLogs.LogInformation("Skipping this test, it timed out"); } } } @@ -716,7 +714,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanRescanWallet() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -818,7 +816,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanListInvoices() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -869,7 +867,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanListNotifications() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -902,7 +900,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanGetRates() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var acc = tester.NewAccount(); @@ -970,7 +968,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanRBFPayment() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -989,12 +987,12 @@ namespace BTCPayServer.Tests false, //subtractfeefromamount true, //replaceable }).ResultString); - Logs.Tester.LogInformation( + TestLogs.LogInformation( $"Let's send a first payment of {payment1} for the {invoice.BtcDue} invoice ({tx1})"); var invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork); - Logs.Tester.LogInformation($"The invoice should be paidOver"); + TestLogs.LogInformation($"The invoice should be paidOver"); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -1022,13 +1020,13 @@ namespace BTCPayServer.Tests var replaced = tester.ExplorerNode.SignRawTransaction(tx); Thread.Sleep(1000); // Make sure the replacement has a different timestamp var tx2 = tester.ExplorerNode.SendRawTransaction(replaced); - Logs.Tester.LogInformation( + TestLogs.LogInformation( $"Let's RBF with a payment of {payment2} ({tx2}), waiting for NBXplorer to pick it up"); Assert.Equal(tx2, ((NewTransactionEvent)listener.NextEvent(cts.Token)).TransactionData.TransactionHash); } - Logs.Tester.LogInformation($"The invoice should now not be paidOver anymore"); + TestLogs.LogInformation($"The invoice should now not be paidOver anymore"); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -1037,7 +1035,7 @@ namespace BTCPayServer.Tests }); - Logs.Tester.LogInformation( + TestLogs.LogInformation( $"Let's test out rbf payments where the payment gets sent elsehwere instead"); var invoice2 = user.BitPay.CreateInvoice(new Invoice() { Price = 0.01m, Currency = "BTC" }, Facade.Merchant); @@ -1078,7 +1076,7 @@ namespace BTCPayServer.Tests Assert.False(i.GetPayments(false).First().Accounted); }); - Logs.Tester.LogInformation("Let's test if we can RBF a normal payment without adding fees to the invoice"); + TestLogs.LogInformation("Let's test if we can RBF a normal payment without adding fees to the invoice"); await user.SetNetworkFeeMode(NetworkFeeMode.MultiplePaymentsOnly); invoice = user.BitPay.CreateInvoice(new Invoice { Price = 5000.0m, Currency = "USD" }, Facade.Merchant); payment1 = invoice.BtcDue; @@ -1089,7 +1087,7 @@ namespace BTCPayServer.Tests false, //subtractfeefromamount true, //replaceable }).ResultString); - Logs.Tester.LogInformation($"Paid {tx1}"); + TestLogs.LogInformation($"Paid {tx1}"); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -1102,7 +1100,7 @@ namespace BTCPayServer.Tests { tx1.ToString(), }).Result["txid"].Value()); - Logs.Tester.LogInformation($"Bumped with {tx1Bump}"); + TestLogs.LogInformation($"Bumped with {tx1Bump}"); await TestUtils.EventuallyAsync(async () => { var invoiceEntity = await tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id); @@ -1127,7 +1125,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanSaveKeyPathForOnChainPayments() { - using var tester = ServerTester.Create(); + using var tester = CreateServerTester(); await tester.StartAsync(); var user = tester.NewAccount(); await user.GrantAccessAsync(); @@ -1155,7 +1153,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async void CheckCORSSetOnBitpayAPI() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); foreach (var req in new[] { "invoices/", "invoices", "rates", "tokens" }.Select(async path => @@ -1190,7 +1188,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task TestAccessBitpayAPI() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1269,14 +1267,14 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUseAnyoneCanCreateInvoice() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); user.GrantAccess(); user.RegisterDerivationScheme("BTC"); - Logs.Tester.LogInformation("StoreId without anyone can create invoice = 403"); + TestLogs.LogInformation("StoreId without anyone can create invoice = 403"); var response = await tester.PayTester.HttpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, $"invoices?storeId={user.StoreId}") { @@ -1285,7 +1283,7 @@ namespace BTCPayServer.Tests }); Assert.Equal(403, (int)response.StatusCode); - Logs.Tester.LogInformation( + TestLogs.LogInformation( "No store without anyone can create invoice = 404 because the bitpay API can't know the storeid"); response = await tester.PayTester.HttpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, $"invoices") @@ -1297,7 +1295,7 @@ namespace BTCPayServer.Tests await user.ModifyPayment(p => p.AnyoneCanCreateInvoice = true); - Logs.Tester.LogInformation("Bad store with anyone can create invoice = 403"); + TestLogs.LogInformation("Bad store with anyone can create invoice = 403"); response = await tester.PayTester.HttpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, $"invoices?storeId=badid") { @@ -1306,7 +1304,7 @@ namespace BTCPayServer.Tests }); Assert.Equal(403, (int)response.StatusCode); - Logs.Tester.LogInformation("Good store with anyone can create invoice = 200"); + TestLogs.LogInformation("Good store with anyone can create invoice = 200"); response = await tester.PayTester.HttpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, $"invoices?storeId={user.StoreId}") { @@ -1321,7 +1319,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanTweakRate() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1369,7 +1367,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCreateTopupInvoices() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1379,7 +1377,7 @@ namespace BTCPayServer.Tests var rng = new Random(); var seed = rng.Next(); rng = new Random(seed); - Logs.Tester.LogInformation("Seed: " + seed); + TestLogs.LogInformation("Seed: " + seed); foreach (var networkFeeMode in Enum.GetValues(typeof(NetworkFeeMode)).Cast()) { await user.SetNetworkFeeMode(networkFeeMode); @@ -1452,7 +1450,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanModifyRates() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1519,7 +1517,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanUseDefaultCurrency() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1560,7 +1558,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanSetPaymentMethodLimits() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -1638,7 +1636,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanSetUnifiedQrCode() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -1700,7 +1698,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanSetPaymentMethodLimitsLightning() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -1761,7 +1759,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task PosDataParser_ParsesCorrectly_Slower() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1818,7 +1816,7 @@ namespace BTCPayServer.Tests return decimal.Parse(match.Groups[1].Value.Trim(), CultureInfo.InvariantCulture); } - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -1890,7 +1888,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanChangeNetworkFeeMode() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { var btc = new PaymentMethodId("BTC", PaymentTypes.BTCLike); await tester.StartAsync(); @@ -1899,7 +1897,7 @@ namespace BTCPayServer.Tests user.RegisterDerivationScheme("BTC"); foreach (var networkFeeMode in Enum.GetValues(typeof(NetworkFeeMode)).Cast()) { - Logs.Tester.LogInformation($"Trying with {nameof(networkFeeMode)}={networkFeeMode}"); + TestLogs.LogInformation($"Trying with {nameof(networkFeeMode)}={networkFeeMode}"); await user.SetNetworkFeeMode(networkFeeMode); var invoice = user.BitPay.CreateInvoice( new Invoice @@ -1934,7 +1932,7 @@ namespace BTCPayServer.Tests var due = Money.Parse(invoice.CryptoInfo[0].Due); var productPartDue = (invoice.Price / invoice.Rate); - Logs.Tester.LogInformation( + TestLogs.LogInformation( $"Product part due is {productPartDue} and due {due} with network fee {nextNetworkFee}"); Assert.Equal(productPartDue + nextNetworkFee, due.ToDecimal(MoneyUnit.BTC)); var firstPayment = productPartDue - missingMoney; @@ -1944,7 +1942,7 @@ namespace BTCPayServer.Tests { invoice = user.BitPay.GetInvoice(invoice.Id); due = Money.Parse(invoice.CryptoInfo[0].Due); - Logs.Tester.LogInformation($"Remaining due after first payment: {due}"); + TestLogs.LogInformation($"Remaining due after first payment: {due}"); Assert.Equal(Money.Coins(firstPayment), Money.Parse(invoice.CryptoInfo[0].Paid)); nextNetworkFee = (await tester.PayTester.InvoiceRepository.GetInvoice(invoice.Id)) .GetPaymentMethods()[btc] @@ -1967,7 +1965,7 @@ namespace BTCPayServer.Tests Money.Parse(invoice.CryptoInfo[0].TotalDue).ToDecimal(MoneyUnit.BTC)); }); cashCow.SendToAddress(invoiceAddress, due); - Logs.Tester.LogInformation($"After payment of {due}, the invoice should be paid"); + TestLogs.LogInformation($"After payment of {due}, the invoice should be paid"); TestUtils.Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); @@ -1981,7 +1979,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanExportInvoicesCsv() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2023,7 +2021,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCreateAndDeleteApps() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2062,7 +2060,7 @@ namespace BTCPayServer.Tests [Trait("Lightning", "Lightning")] public async Task CanCreateStrangeInvoice() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { tester.ActivateLightning(); await tester.StartAsync(); @@ -2156,7 +2154,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task InvoiceFlowThroughDifferentStatesCorrectly() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2360,7 +2358,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CheckLogsRoute() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2377,7 +2375,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanLoginWithNoSecondaryAuthSystemsOrRequestItWhenAdded() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2452,7 +2450,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async void CheckOnionlocationForNonOnionHtmlRequests() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var url = tester.PayTester.ServerUri.AbsoluteUri; @@ -2498,7 +2496,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanCheckForNewVersion() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { await tester.StartAsync(); @@ -2511,7 +2509,7 @@ namespace BTCPayServer.Tests var mockEnv = tester.PayTester.GetService(); var mockSender = tester.PayTester.GetService(); - var svc = new NewVersionCheckerHostedService(settings, mockEnv, mockSender, new MockVersionFetcher()); + var svc = new NewVersionCheckerHostedService(settings, mockEnv, mockSender, new MockVersionFetcher(), BTCPayLogs); await svc.ProcessVersionCheck(); // since last version present in database was null, it should've been updated with version mock returned @@ -2544,7 +2542,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanDoLightningInternalNodeMigration() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { tester.ActivateLightning(LightningConnectionType.CLightning); await tester.StartAsync(); @@ -2623,7 +2621,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanDoInvoiceMigrations() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { await tester.StartAsync(); @@ -2704,7 +2702,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task EmailSenderTests() { - using (var tester = ServerTester.Create(newDb: true)) + using (var tester = CreateServerTester(newDb: true)) { await tester.StartAsync(); @@ -2754,7 +2752,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async Task CanConfigureStorage() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); @@ -2837,7 +2835,7 @@ namespace BTCPayServer.Tests [Trait("Integration", "Integration")] public async void CanUseLocalProviderFiles() { - using (var tester = ServerTester.Create()) + using (var tester = CreateServerTester()) { await tester.StartAsync(); var user = tester.NewAccount(); diff --git a/BTCPayServer.Tests/UnitTestBase.cs b/BTCPayServer.Tests/UnitTestBase.cs index 09fd20140..4b68023bd 100644 --- a/BTCPayServer.Tests/UnitTestBase.cs +++ b/BTCPayServer.Tests/UnitTestBase.cs @@ -14,8 +14,8 @@ namespace BTCPayServer.Tests { TestLogs = new XUnitLog(helper) { Name = "Tests" }; TestLogProvider = new XUnitLogProvider(helper); - Logs.Tester = TestLogs; - Logs.LogProvider = TestLogProvider; + BTCPayLogs = new BTCPayServer.Logging.Logs(); + BTCPayLogs.Configure(new BTCPayServer.Logging.FuncLoggerFactory((n) => new XUnitLog(helper) { Name = n })); } public ILog TestLogs { @@ -25,14 +25,15 @@ namespace BTCPayServer.Tests { get; } + public BTCPayServer.Logging.Logs BTCPayLogs { get; } public ServerTester CreateServerTester([CallerMemberNameAttribute] string scope = null, bool newDb = false) { - return new ServerTester(scope, newDb); + return new ServerTester(scope, newDb, TestLogs, TestLogProvider); } public SeleniumTester CreateSeleniumTester([CallerMemberNameAttribute] string scope = null, bool newDb = false) { - return new SeleniumTester() { Server = new ServerTester(scope, newDb) }; + return new SeleniumTester() { Server = new ServerTester(scope, newDb, TestLogs, TestLogProvider) }; } } } diff --git a/BTCPayServer/Configuration/BTCPayServerOptions.cs b/BTCPayServer/Configuration/BTCPayServerOptions.cs index 9a2a33a9b..8a3bcf51f 100644 --- a/BTCPayServer/Configuration/BTCPayServerOptions.cs +++ b/BTCPayServer/Configuration/BTCPayServerOptions.cs @@ -56,7 +56,7 @@ namespace BTCPayServer.Configuration return (LogEventLevel)Enum.Parse(typeof(LogEventLevel), raw, true); } - public void LoadArgs(IConfiguration conf) + public void LoadArgs(IConfiguration conf, Logs Logs) { NetworkType = DefaultConfiguration.GetNetworkType(conf); diff --git a/BTCPayServer/Controllers/AccountController.cs b/BTCPayServer/Controllers/AccountController.cs index e739166dc..6825b058b 100644 --- a/BTCPayServer/Controllers/AccountController.cs +++ b/BTCPayServer/Controllers/AccountController.cs @@ -36,6 +36,8 @@ namespace BTCPayServer.Controllers private readonly EventAggregator _eventAggregator; readonly ILogger _logger; + public Logs Logs { get; } + public AccountController( UserManager userManager, RoleManager roleManager, @@ -44,7 +46,8 @@ namespace BTCPayServer.Controllers Configuration.BTCPayServerOptions options, BTCPayServerEnvironment btcPayServerEnvironment, EventAggregator eventAggregator, - Fido2Service fido2Service) + Fido2Service fido2Service, + Logs logs) { _userManager = userManager; _signInManager = signInManager; @@ -54,7 +57,8 @@ namespace BTCPayServer.Controllers _btcPayServerEnvironment = btcPayServerEnvironment; _fido2Service = fido2Service; _eventAggregator = eventAggregator; - _logger = Logs.PayServer; + _logger = logs.PayServer; + Logs = logs; } [TempData] @@ -447,7 +451,7 @@ namespace BTCPayServer.Controllers settings.FirstRun = false; await _SettingsRepository.UpdateSetting(settings); - await _SettingsRepository.FirstAdminRegistered(policies, _Options.UpdateUrl != null, _Options.DisableRegistration); + await _SettingsRepository.FirstAdminRegistered(policies, _Options.UpdateUrl != null, _Options.DisableRegistration, Logs); RegisteredAdmin = true; } diff --git a/BTCPayServer/Controllers/GreenField/UsersController.cs b/BTCPayServer/Controllers/GreenField/UsersController.cs index f8f60751b..22e2d1860 100644 --- a/BTCPayServer/Controllers/GreenField/UsersController.cs +++ b/BTCPayServer/Controllers/GreenField/UsersController.cs @@ -20,6 +20,7 @@ using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using NicolasDorier.RateLimits; +using BTCPayServer.Logging; namespace BTCPayServer.Controllers.GreenField { @@ -28,6 +29,8 @@ namespace BTCPayServer.Controllers.GreenField [EnableCors(CorsPolicies.All)] public class UsersController : ControllerBase { + public Logs Logs { get; } + private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly SettingsRepository _settingsRepository; @@ -46,8 +49,10 @@ namespace BTCPayServer.Controllers.GreenField RateLimitService throttleService, BTCPayServerOptions options, IAuthorizationService authorizationService, - UserService userService) + UserService userService, + Logs logs) { + this.Logs = logs; _userManager = userManager; _roleManager = roleManager; _settingsRepository = settingsRepository; @@ -168,7 +173,7 @@ namespace BTCPayServer.Controllers.GreenField await _settingsRepository.UpdateSetting(settings); } - await _settingsRepository.FirstAdminRegistered(policies, _options.UpdateUrl != null, _options.DisableRegistration); + await _settingsRepository.FirstAdminRegistered(policies, _options.UpdateUrl != null, _options.DisableRegistration, Logs); } } _eventAggregator.Publish(new UserRegisteredEvent() { RequestUri = Request.GetAbsoluteRootUri(), User = user, Admin = request.IsAdministrator is true }); diff --git a/BTCPayServer/Controllers/ServerController.cs b/BTCPayServer/Controllers/ServerController.cs index 9567e07c3..e87db9518 100644 --- a/BTCPayServer/Controllers/ServerController.cs +++ b/BTCPayServer/Controllers/ServerController.cs @@ -55,6 +55,7 @@ namespace BTCPayServer.Controllers private readonly CheckConfigurationHostedService _sshState; private readonly EventAggregator _eventAggregator; private readonly IOptions _externalServiceOptions; + private readonly Logs Logs; private readonly StoredFileRepository _StoredFileRepository; private readonly FileService _FileService; private readonly IEnumerable _StorageProviderServices; @@ -75,7 +76,8 @@ namespace BTCPayServer.Controllers AppService appService, CheckConfigurationHostedService sshState, EventAggregator eventAggregator, - IOptions externalServiceOptions) + IOptions externalServiceOptions, + Logs logs) { _Options = options; _StoredFileRepository = storedFileRepository; @@ -93,6 +95,7 @@ namespace BTCPayServer.Controllers _sshState = sshState; _eventAggregator = eventAggregator; _externalServiceOptions = externalServiceOptions; + Logs = logs; } [Route("server/maintenance")] @@ -250,7 +253,7 @@ namespace BTCPayServer.Controllers return null; } - private static async Task RunSSHCore(SshClient sshClient, string ssh) + private async Task RunSSHCore(SshClient sshClient, string ssh) { try { diff --git a/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs b/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs index a840af0ca..88ac336b9 100644 --- a/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs +++ b/BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs @@ -35,13 +35,14 @@ public class BitcoinLikePayoutHandler : IPayoutHandler private readonly ApplicationDbContextFactory _dbContextFactory; private readonly EventAggregator _eventAggregator; private readonly NotificationSender _notificationSender; - + private readonly Logs Logs; public BitcoinLikePayoutHandler(BTCPayNetworkProvider btcPayNetworkProvider, ExplorerClientProvider explorerClientProvider, BTCPayNetworkJsonSerializerSettings jsonSerializerSettings, ApplicationDbContextFactory dbContextFactory, EventAggregator eventAggregator, - NotificationSender notificationSender) + NotificationSender notificationSender, + Logs logs) { _btcPayNetworkProvider = btcPayNetworkProvider; _explorerClientProvider = explorerClientProvider; @@ -49,8 +50,10 @@ public class BitcoinLikePayoutHandler : IPayoutHandler _dbContextFactory = dbContextFactory; _eventAggregator = eventAggregator; _notificationSender = notificationSender; + this.Logs = logs; } + public bool CanHandle(PaymentMethodId paymentMethod) { return paymentMethod?.PaymentType == BitcoinPaymentType.Instance && diff --git a/BTCPayServer/EventAggregator.cs b/BTCPayServer/EventAggregator.cs index d15f7cbb3..e1674ea51 100644 --- a/BTCPayServer/EventAggregator.cs +++ b/BTCPayServer/EventAggregator.cs @@ -15,6 +15,10 @@ namespace BTCPayServer } public class EventAggregator : IDisposable { + public EventAggregator(Logs logs) + { + Logs = logs; + } class Subscription : IEventAggregatorSubscription { private readonly EventAggregator aggregator; @@ -135,6 +139,8 @@ namespace BTCPayServer readonly Dictionary>> _Subscriptions = new Dictionary>>(); + public Logs Logs { get; } + public IEventAggregatorSubscription Subscribe(Func subscription) { return Subscribe(new Action((t) => subscription(t))); diff --git a/BTCPayServer/ExplorerClientProvider.cs b/BTCPayServer/ExplorerClientProvider.cs index 027abdf32..6b54cd206 100644 --- a/BTCPayServer/ExplorerClientProvider.cs +++ b/BTCPayServer/ExplorerClientProvider.cs @@ -18,14 +18,18 @@ namespace BTCPayServer public BTCPayNetworkProvider NetworkProviders => _NetworkProviders; + public Logs Logs { get; } + readonly NBXplorerDashboard _Dashboard; public ExplorerClientProvider( IHttpClientFactory httpClientFactory, BTCPayNetworkProvider networkProviders, IOptions nbXplorerOptions, - NBXplorerDashboard dashboard) + NBXplorerDashboard dashboard, + Logs logs) { + Logs = logs; _Dashboard = dashboard; _NetworkProviders = networkProviders; @@ -46,7 +50,7 @@ namespace BTCPayServer } } - private static ExplorerClient CreateExplorerClient(HttpClient httpClient, BTCPayNetwork n, Uri uri, + private ExplorerClient CreateExplorerClient(HttpClient httpClient, BTCPayNetwork n, Uri uri, string cookieFile) { var explorer = n.NBXplorerNetwork.CreateExplorerClient(uri); diff --git a/BTCPayServer/Extensions.cs b/BTCPayServer/Extensions.cs index 62d5769cd..cac419a7b 100644 --- a/BTCPayServer/Extensions.cs +++ b/BTCPayServer/Extensions.cs @@ -462,7 +462,7 @@ namespace BTCPayServer return sql; } - public static BTCPayNetworkProvider ConfigureNetworkProvider(this IConfiguration configuration) + public static BTCPayNetworkProvider ConfigureNetworkProvider(this IConfiguration configuration, Logs logs) { var _networkType = DefaultConfiguration.GetNetworkType(configuration); var supportedChains = configuration.GetOrDefault("chains", "btc") @@ -487,7 +487,7 @@ namespace BTCPayServer throw new ConfigException($"Invalid chains \"{chain}\""); } - Logs.Configuration.LogInformation( + logs.Configuration.LogInformation( "Supported chains: " + String.Join(',', supportedChains.ToArray())); return result; } diff --git a/BTCPayServer/Extensions/ActionLogicExtensions.cs b/BTCPayServer/Extensions/ActionLogicExtensions.cs index 9e5d247f2..81585ebed 100644 --- a/BTCPayServer/Extensions/ActionLogicExtensions.cs +++ b/BTCPayServer/Extensions/ActionLogicExtensions.cs @@ -17,18 +17,18 @@ namespace BTCPayServer internal static class ActionLogicExtensions { internal static async Task FirstAdminRegistered(this SettingsRepository settingsRepository, PoliciesSettings policies, - bool updateCheck, bool disableRegistrations) + bool updateCheck, bool disableRegistrations, Logs logs) { if (updateCheck) { - Logs.PayServer.LogInformation("First admin created, enabling checks for new versions"); + logs.PayServer.LogInformation("First admin created, enabling checks for new versions"); policies.CheckForNewVersions = updateCheck; } if (disableRegistrations) { // Once the admin user has been created lock subsequent user registrations (needs to be disabled for unit tests that require multiple users). - Logs.PayServer.LogInformation("First admin created, disabling subscription (disable-registration is set to true)"); + logs.PayServer.LogInformation("First admin created, disabling subscription (disable-registration is set to true)"); policies.LockSubscription = true; } diff --git a/BTCPayServer/HostedServices/AppInventoryUpdaterHostedService.cs b/BTCPayServer/HostedServices/AppInventoryUpdaterHostedService.cs index 49e9e2515..4bfaf235d 100644 --- a/BTCPayServer/HostedServices/AppInventoryUpdaterHostedService.cs +++ b/BTCPayServer/HostedServices/AppInventoryUpdaterHostedService.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using BTCPayServer.Controllers; using BTCPayServer.Events; +using BTCPayServer.Logging; using BTCPayServer.Services.Apps; namespace BTCPayServer.HostedServices @@ -20,8 +21,7 @@ namespace BTCPayServer.HostedServices Subscribe(); } - public AppInventoryUpdaterHostedService(EventAggregator eventAggregator, AppService appService) : base( - eventAggregator) + public AppInventoryUpdaterHostedService(EventAggregator eventAggregator, AppService appService, Logs logs) : base(eventAggregator, logs) { _eventAggregator = eventAggregator; _appService = appService; diff --git a/BTCPayServer/HostedServices/BackgroundJobSchedulerHostedService.cs b/BTCPayServer/HostedServices/BackgroundJobSchedulerHostedService.cs index 4c836e038..c11939667 100644 --- a/BTCPayServer/HostedServices/BackgroundJobSchedulerHostedService.cs +++ b/BTCPayServer/HostedServices/BackgroundJobSchedulerHostedService.cs @@ -14,12 +14,14 @@ namespace BTCPayServer.HostedServices { public class BackgroundJobSchedulerHostedService : IHostedService { - public BackgroundJobSchedulerHostedService(IBackgroundJobClient backgroundJobClient) + public BackgroundJobSchedulerHostedService(IBackgroundJobClient backgroundJobClient, Logs logs) { BackgroundJobClient = (BackgroundJobClient)backgroundJobClient; + Logs = logs; } public BackgroundJobClient BackgroundJobClient { get; } + public Logs Logs { get; } Task _Loop; @@ -77,6 +79,12 @@ namespace BTCPayServer.HostedServices } } + public BackgroundJobClient(Logs logs) + { + Logs = logs; + } + Logs Logs; + public IDelay Delay { get; set; } = TaskDelay.Instance; public int GetExecutingCount() { diff --git a/BTCPayServer/HostedServices/BaseAsyncService.cs b/BTCPayServer/HostedServices/BaseAsyncService.cs index 0c501aac6..54cbe2ee4 100644 --- a/BTCPayServer/HostedServices/BaseAsyncService.cs +++ b/BTCPayServer/HostedServices/BaseAsyncService.cs @@ -12,6 +12,11 @@ namespace BTCPayServer.HostedServices { private CancellationTokenSource _Cts = new CancellationTokenSource(); protected Task[] _Tasks; + public readonly Logs Logs; + public BaseAsyncService(Logs logs) + { + Logs = logs; + } public virtual Task StartAsync(CancellationToken cancellationToken) { diff --git a/BTCPayServer/HostedServices/CheckConfigurationHostedService.cs b/BTCPayServer/HostedServices/CheckConfigurationHostedService.cs index 2c7110d56..f8469ab5c 100644 --- a/BTCPayServer/HostedServices/CheckConfigurationHostedService.cs +++ b/BTCPayServer/HostedServices/CheckConfigurationHostedService.cs @@ -10,12 +10,15 @@ namespace BTCPayServer.HostedServices { public class CheckConfigurationHostedService : IHostedService { + public Logs Logs { get; } + private readonly BTCPayServerOptions _options; Task _testingConnection; readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); - public CheckConfigurationHostedService(BTCPayServerOptions options) + public CheckConfigurationHostedService(BTCPayServerOptions options, Logs logs) { + Logs = logs; _options = options; } diff --git a/BTCPayServer/HostedServices/DbMigrationsHostedService.cs b/BTCPayServer/HostedServices/DbMigrationsHostedService.cs index 82d47e1dc..d363fff97 100644 --- a/BTCPayServer/HostedServices/DbMigrationsHostedService.cs +++ b/BTCPayServer/HostedServices/DbMigrationsHostedService.cs @@ -23,7 +23,7 @@ namespace BTCPayServer.HostedServices private readonly ApplicationDbContextFactory _dbContextFactory; private readonly IOptions _datadirs; - public DbMigrationsHostedService(InvoiceRepository invoiceRepository, SettingsRepository settingsRepository, ApplicationDbContextFactory dbContextFactory, IOptions datadirs) + public DbMigrationsHostedService(InvoiceRepository invoiceRepository, SettingsRepository settingsRepository, ApplicationDbContextFactory dbContextFactory, IOptions datadirs, Logs logs) : base(logs) { _invoiceRepository = invoiceRepository; _settingsRepository = settingsRepository; diff --git a/BTCPayServer/HostedServices/DelayedTransactionBroadcasterHostedService.cs b/BTCPayServer/HostedServices/DelayedTransactionBroadcasterHostedService.cs index aaa206a2c..ae1654817 100644 --- a/BTCPayServer/HostedServices/DelayedTransactionBroadcasterHostedService.cs +++ b/BTCPayServer/HostedServices/DelayedTransactionBroadcasterHostedService.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using BTCPayServer.Logging; using BTCPayServer.Services; namespace BTCPayServer.HostedServices @@ -8,7 +9,7 @@ namespace BTCPayServer.HostedServices { private readonly DelayedTransactionBroadcaster _transactionBroadcaster; - public DelayedTransactionBroadcasterHostedService(DelayedTransactionBroadcaster transactionBroadcaster) + public DelayedTransactionBroadcasterHostedService(DelayedTransactionBroadcaster transactionBroadcaster, Logs logs) : base(logs) { _transactionBroadcaster = transactionBroadcaster; } diff --git a/BTCPayServer/HostedServices/DynamicDnsHostedService.cs b/BTCPayServer/HostedServices/DynamicDnsHostedService.cs index 859e205ad..1ca4869b3 100644 --- a/BTCPayServer/HostedServices/DynamicDnsHostedService.cs +++ b/BTCPayServer/HostedServices/DynamicDnsHostedService.cs @@ -10,7 +10,7 @@ namespace BTCPayServer.HostedServices { public class DynamicDnsHostedService : BaseAsyncService { - public DynamicDnsHostedService(IHttpClientFactory httpClientFactory, SettingsRepository settingsRepository) + public DynamicDnsHostedService(IHttpClientFactory httpClientFactory, SettingsRepository settingsRepository, Logs logs) : base(logs) { HttpClientFactory = httpClientFactory; SettingsRepository = settingsRepository; diff --git a/BTCPayServer/HostedServices/EventHostedServiceBase.cs b/BTCPayServer/HostedServices/EventHostedServiceBase.cs index b1de13f80..5b75a0003 100644 --- a/BTCPayServer/HostedServices/EventHostedServiceBase.cs +++ b/BTCPayServer/HostedServices/EventHostedServiceBase.cs @@ -12,14 +12,18 @@ namespace BTCPayServer.HostedServices public class EventHostedServiceBase : IHostedService { private readonly EventAggregator _EventAggregator; + + public Logs Logs { get; } + public EventAggregator EventAggregator => _EventAggregator; private List _Subscriptions; private CancellationTokenSource _Cts; public CancellationToken CancellationToken => _Cts.Token; - public EventHostedServiceBase(EventAggregator eventAggregator) + public EventHostedServiceBase(EventAggregator eventAggregator, Logs logs) { _EventAggregator = eventAggregator; + Logs = logs; } readonly Channel _Events = Channel.CreateUnbounded(); diff --git a/BTCPayServer/HostedServices/InvoiceEventSaverService.cs b/BTCPayServer/HostedServices/InvoiceEventSaverService.cs index 3e6a0c528..e7a2415b3 100644 --- a/BTCPayServer/HostedServices/InvoiceEventSaverService.cs +++ b/BTCPayServer/HostedServices/InvoiceEventSaverService.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using BTCPayServer.Data; using BTCPayServer.Events; +using BTCPayServer.Logging; using BTCPayServer.Services.Invoices; using NBXplorer; @@ -13,8 +14,8 @@ namespace BTCPayServer.HostedServices public class InvoiceEventSaverService : EventHostedServiceBase { private readonly InvoiceRepository _invoiceRepository; - public InvoiceEventSaverService(EventAggregator eventAggregator, InvoiceRepository invoiceRepository) : base( - eventAggregator) + public InvoiceEventSaverService(EventAggregator eventAggregator, InvoiceRepository invoiceRepository, Logs logs) : base( + eventAggregator, logs) { _invoiceRepository = invoiceRepository; } diff --git a/BTCPayServer/HostedServices/InvoiceWatcher.cs b/BTCPayServer/HostedServices/InvoiceWatcher.cs index 4c8e3fb94..1d795f54b 100644 --- a/BTCPayServer/HostedServices/InvoiceWatcher.cs +++ b/BTCPayServer/HostedServices/InvoiceWatcher.cs @@ -57,19 +57,22 @@ namespace BTCPayServer.HostedServices readonly ExplorerClientProvider _explorerClientProvider; private readonly NotificationSender _notificationSender; private readonly PaymentService _paymentService; + public Logs Logs { get; } public InvoiceWatcher( InvoiceRepository invoiceRepository, EventAggregator eventAggregator, ExplorerClientProvider explorerClientProvider, NotificationSender notificationSender, - PaymentService paymentService) + PaymentService paymentService, + Logs logs) { _invoiceRepository = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository)); _eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator)); _explorerClientProvider = explorerClientProvider; _notificationSender = notificationSender; _paymentService = paymentService; + this.Logs = logs; } readonly CompositeDisposable leases = new CompositeDisposable(); diff --git a/BTCPayServer/HostedServices/NBXplorerWaiter.cs b/BTCPayServer/HostedServices/NBXplorerWaiter.cs index 58b719b4f..799b7a0b4 100644 --- a/BTCPayServer/HostedServices/NBXplorerWaiter.cs +++ b/BTCPayServer/HostedServices/NBXplorerWaiter.cs @@ -61,11 +61,11 @@ namespace BTCPayServer.HostedServices public class NBXplorerWaiters : IHostedService { readonly List _Waiters = new List(); - public NBXplorerWaiters(NBXplorerDashboard dashboard, ExplorerClientProvider explorerClientProvider, EventAggregator eventAggregator) + public NBXplorerWaiters(NBXplorerDashboard dashboard, ExplorerClientProvider explorerClientProvider, EventAggregator eventAggregator, Logs logs) { foreach (var explorer in explorerClientProvider.GetAll()) { - _Waiters.Add(new NBXplorerWaiter(dashboard, explorer.Item1, explorer.Item2, eventAggregator)); + _Waiters.Add(new NBXplorerWaiter(dashboard, explorer.Item1, explorer.Item2, eventAggregator, logs)); } } public Task StartAsync(CancellationToken cancellationToken) @@ -82,8 +82,9 @@ namespace BTCPayServer.HostedServices public class NBXplorerWaiter : IHostedService { - public NBXplorerWaiter(NBXplorerDashboard dashboard, BTCPayNetwork network, ExplorerClient client, EventAggregator aggregator) + public NBXplorerWaiter(NBXplorerDashboard dashboard, BTCPayNetwork network, ExplorerClient client, EventAggregator aggregator, Logs logs) { + this.Logs = logs; _Network = network; _Client = client; _Aggregator = aggregator; @@ -92,6 +93,9 @@ namespace BTCPayServer.HostedServices } readonly NBXplorerDashboard _Dashboard; + + public Logs Logs { get; } + readonly BTCPayNetwork _Network; readonly EventAggregator _Aggregator; readonly ExplorerClient _Client; diff --git a/BTCPayServer/HostedServices/NewVersionCheckerHostedService.cs b/BTCPayServer/HostedServices/NewVersionCheckerHostedService.cs index d98848c33..2e88c0e66 100644 --- a/BTCPayServer/HostedServices/NewVersionCheckerHostedService.cs +++ b/BTCPayServer/HostedServices/NewVersionCheckerHostedService.cs @@ -21,7 +21,7 @@ namespace BTCPayServer.HostedServices private readonly IVersionFetcher _versionFetcher; public NewVersionCheckerHostedService(SettingsRepository settingsRepository, BTCPayServerEnvironment env, - NotificationSender notificationSender, IVersionFetcher versionFetcher) + NotificationSender notificationSender, IVersionFetcher versionFetcher, Logs logs) : base(logs) { _settingsRepository = settingsRepository; _env = env; @@ -80,10 +80,13 @@ namespace BTCPayServer.HostedServices public class GithubVersionFetcher : IVersionFetcher { + public Logs Logs { get; } + private readonly HttpClient _httpClient; private readonly Uri _updateurl; - public GithubVersionFetcher(IHttpClientFactory httpClientFactory, BTCPayServerOptions options) + public GithubVersionFetcher(IHttpClientFactory httpClientFactory, BTCPayServerOptions options, Logs logs) { + Logs = logs; _httpClient = httpClientFactory.CreateClient(nameof(GithubVersionFetcher)); _httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); _httpClient.DefaultRequestHeaders.Add("User-Agent", "BTCPayServer/NewVersionChecker"); diff --git a/BTCPayServer/HostedServices/PullPaymentHostedService.cs b/BTCPayServer/HostedServices/PullPaymentHostedService.cs index cc15689b0..820af15ed 100644 --- a/BTCPayServer/HostedServices/PullPaymentHostedService.cs +++ b/BTCPayServer/HostedServices/PullPaymentHostedService.cs @@ -6,6 +6,7 @@ using System.Threading.Channels; using System.Threading.Tasks; using BTCPayServer.Client.Models; using BTCPayServer.Data; +using BTCPayServer.Logging; using BTCPayServer.Payments; using BTCPayServer.Services; using BTCPayServer.Services.Notifications; @@ -154,7 +155,8 @@ namespace BTCPayServer.HostedServices NotificationSender notificationSender, RateFetcher rateFetcher, IEnumerable payoutHandlers, - ILogger logger) + ILogger logger, + Logs logs) : base(logs) { _dbContextFactory = dbContextFactory; _jsonSerializerSettings = jsonSerializerSettings; diff --git a/BTCPayServer/HostedServices/RatesHostedService.cs b/BTCPayServer/HostedServices/RatesHostedService.cs index 2b389ab2d..7d65797a5 100644 --- a/BTCPayServer/HostedServices/RatesHostedService.cs +++ b/BTCPayServer/HostedServices/RatesHostedService.cs @@ -26,8 +26,10 @@ namespace BTCPayServer.HostedServices } private readonly SettingsRepository _SettingsRepository; readonly RateProviderFactory _RateProviderFactory; + public RatesHostedService(SettingsRepository repo, - RateProviderFactory rateProviderFactory) + RateProviderFactory rateProviderFactory, + Logs logs) : base(logs) { this._SettingsRepository = repo; _RateProviderFactory = rateProviderFactory; diff --git a/BTCPayServer/HostedServices/Socks5HttpProxyServer.cs b/BTCPayServer/HostedServices/Socks5HttpProxyServer.cs index 575a083e4..3d6462e8d 100644 --- a/BTCPayServer/HostedServices/Socks5HttpProxyServer.cs +++ b/BTCPayServer/HostedServices/Socks5HttpProxyServer.cs @@ -47,10 +47,14 @@ namespace BTCPayServer.HostedServices public CancellationToken CancellationToken; public int ConnectionCount; } + + public Logs Logs { get; } + private readonly BTCPayServerOptions _opts; - public Socks5HttpProxyServer(Configuration.BTCPayServerOptions opts) + public Socks5HttpProxyServer(Configuration.BTCPayServerOptions opts, Logs logs) { + this.Logs = logs; _opts = opts; } private ServerContext _ServerContext; diff --git a/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs b/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs index d71286625..7f84e24be 100644 --- a/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs +++ b/BTCPayServer/HostedServices/TransactionLabelMarkerHostedService.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using BTCPayServer.Data; using BTCPayServer.Events; +using BTCPayServer.Logging; using BTCPayServer.Payments; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services; @@ -21,8 +22,8 @@ namespace BTCPayServer.HostedServices private readonly EventAggregator _eventAggregator; private readonly WalletRepository _walletRepository; - public TransactionLabelMarkerHostedService(EventAggregator eventAggregator, WalletRepository walletRepository) : - base(eventAggregator) + public TransactionLabelMarkerHostedService(EventAggregator eventAggregator, WalletRepository walletRepository, Logs logs) : + base(eventAggregator, logs) { _eventAggregator = eventAggregator; _walletRepository = walletRepository; diff --git a/BTCPayServer/HostedServices/UserEventHostedService.cs b/BTCPayServer/HostedServices/UserEventHostedService.cs index 67e07f3ed..31578490f 100644 --- a/BTCPayServer/HostedServices/UserEventHostedService.cs +++ b/BTCPayServer/HostedServices/UserEventHostedService.cs @@ -20,8 +20,9 @@ namespace BTCPayServer.HostedServices private readonly EmailSenderFactory _emailSenderFactory; private readonly LinkGenerator _generator; + public UserEventHostedService(EventAggregator eventAggregator, UserManager userManager, - EmailSenderFactory emailSenderFactory, LinkGenerator generator) : base(eventAggregator) + EmailSenderFactory emailSenderFactory, LinkGenerator generator, Logs logs) : base(eventAggregator, logs) { _userManager = userManager; _emailSenderFactory = emailSenderFactory; diff --git a/BTCPayServer/HostedServices/WebhookNotificationManager.cs b/BTCPayServer/HostedServices/WebhookNotificationManager.cs index 75b2d6382..6a33e601d 100644 --- a/BTCPayServer/HostedServices/WebhookNotificationManager.cs +++ b/BTCPayServer/HostedServices/WebhookNotificationManager.cs @@ -61,7 +61,8 @@ namespace BTCPayServer.HostedServices public WebhookNotificationManager(EventAggregator eventAggregator, StoreRepository storeRepository, - IHttpClientFactory httpClientFactory) : base(eventAggregator) + IHttpClientFactory httpClientFactory, + Logs logs) : base(eventAggregator, logs) { StoreRepository = storeRepository; HttpClientFactory = httpClientFactory; diff --git a/BTCPayServer/Hosting/BTCPayServerServices.cs b/BTCPayServer/Hosting/BTCPayServerServices.cs index 0cf5528d6..6fd93490e 100644 --- a/BTCPayServer/Hosting/BTCPayServerServices.cs +++ b/BTCPayServer/Hosting/BTCPayServerServices.cs @@ -70,7 +70,7 @@ namespace BTCPayServer.Hosting services.AddSingleton((s) => new JsonConverterRegistration(create)); return services; } - public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration, Logs logs) { services.AddSingleton(o => o.GetRequiredService>().Value); services.AddDbContext((provider, o) => @@ -84,6 +84,7 @@ namespace BTCPayServer.Hosting httpClient.Timeout = Timeout.InfiniteTimeSpan; }); + services.AddSingleton(logs); services.AddSingleton(); services.AddPayJoinServices(); @@ -117,7 +118,7 @@ namespace BTCPayServer.Hosting services.AddOptions().Configure( (options) => { - options.LoadArgs(configuration); + options.LoadArgs(configuration, logs); }); services.AddOptions().Configure( (options) => @@ -185,7 +186,7 @@ namespace BTCPayServer.Hosting if (!LightningConnectionString.TryParse(lightning, true, out var connectionString, out var error)) { - Logs.Configuration.LogWarning($"Invalid setting {net.CryptoCode}.lightning, " + + logs.Configuration.LogWarning($"Invalid setting {net.CryptoCode}.lightning, " + Environment.NewLine + $"If you have a c-lightning server use: 'type=clightning;server=/root/.lightning/lightning-rpc', " + Environment.NewLine + @@ -206,7 +207,7 @@ namespace BTCPayServer.Hosting { if (connectionString.IsLegacy) { - Logs.Configuration.LogWarning( + logs.Configuration.LogWarning( $"Setting {net.CryptoCode}.lightning is a deprecated format, it will work now, but please replace it for future versions with '{connectionString.ToString()}'"); } options.InternalLightningByCryptoCode.Add(net.CryptoCode, connectionString); @@ -238,7 +239,7 @@ namespace BTCPayServer.Hosting } } }); - services.TryAddSingleton(o => configuration.ConfigureNetworkProvider()); + services.TryAddSingleton(o => configuration.ConfigureNetworkProvider(logs)); services.TryAddSingleton(); services.AddSingleton(); diff --git a/BTCPayServer/Hosting/BTCpayMiddleware.cs b/BTCPayServer/Hosting/BTCpayMiddleware.cs index 07560e4ab..b138cb265 100644 --- a/BTCPayServer/Hosting/BTCpayMiddleware.cs +++ b/BTCPayServer/Hosting/BTCpayMiddleware.cs @@ -19,15 +19,20 @@ namespace BTCPayServer.Hosting { readonly RequestDelegate _Next; readonly BTCPayServerOptions _Options; + + public Logs Logs { get; } + readonly BTCPayServerEnvironment _Env; public BTCPayMiddleware(RequestDelegate next, BTCPayServerOptions options, - BTCPayServerEnvironment env) + BTCPayServerEnvironment env, + Logs logs) { _Env = env ?? throw new ArgumentNullException(nameof(env)); _Next = next ?? throw new ArgumentNullException(nameof(next)); _Options = options ?? throw new ArgumentNullException(nameof(options)); + Logs = logs; } diff --git a/BTCPayServer/Hosting/MigrationStartupTask.cs b/BTCPayServer/Hosting/MigrationStartupTask.cs index bc83253c3..37aaed634 100644 --- a/BTCPayServer/Hosting/MigrationStartupTask.cs +++ b/BTCPayServer/Hosting/MigrationStartupTask.cs @@ -31,6 +31,8 @@ namespace BTCPayServer.Hosting { public class MigrationStartupTask : IStartupTask { + public Logs Logs { get; } + private readonly ApplicationDbContextFactory _DBContextFactory; private readonly StoreRepository _StoreRepository; private readonly BTCPayNetworkProvider _NetworkProvider; @@ -51,8 +53,10 @@ namespace BTCPayServer.Hosting SettingsRepository settingsRepository, AppService appService, IEnumerable payoutHandlers, - BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings) + BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings, + Logs logs) { + Logs = logs; _DBContextFactory = dbContextFactory; _StoreRepository = storeRepository; _NetworkProvider = networkProvider; diff --git a/BTCPayServer/Hosting/Startup.cs b/BTCPayServer/Hosting/Startup.cs index abc83a801..2e185b1af 100644 --- a/BTCPayServer/Hosting/Startup.cs +++ b/BTCPayServer/Hosting/Startup.cs @@ -42,6 +42,8 @@ namespace BTCPayServer.Hosting Configuration = conf; _Env = env; LoggerFactory = loggerFactory; + Logs = new Logs(); + Logs.Configure(loggerFactory); } readonly IWebHostEnvironment _Env; @@ -50,10 +52,10 @@ namespace BTCPayServer.Hosting get; set; } public ILoggerFactory LoggerFactory { get; } + public Logs Logs { get; } public void ConfigureServices(IServiceCollection services) { - Logs.Configure(LoggerFactory); services.AddMemoryCache(); services.AddDataProtection() .SetApplicationName("BTCPay Server") @@ -80,7 +82,7 @@ namespace BTCPayServer.Hosting opts.ValidationInterval = TimeSpan.FromMinutes(5.0); }); - services.AddBTCPayServer(Configuration); + services.AddBTCPayServer(Configuration, Logs); services.AddProviderStorage(); services.AddSession(); services.AddSignalR(); @@ -199,22 +201,22 @@ namespace BTCPayServer.Hosting IOptions dataDirectories, ILoggerFactory loggerFactory) { + Logs.Configure(loggerFactory); Logs.Configuration.LogInformation($"Root Path: {options.RootPath}"); if (options.RootPath.Equals("/", StringComparison.OrdinalIgnoreCase)) { - ConfigureCore(app, env, prov, loggerFactory, dataDirectories); + ConfigureCore(app, env, prov, dataDirectories); } else { app.Map(options.RootPath, appChild => { - ConfigureCore(appChild, env, prov, loggerFactory, dataDirectories); + ConfigureCore(appChild, env, prov, dataDirectories); }); } } - private static void ConfigureCore(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider prov, ILoggerFactory loggerFactory, IOptions dataDirectories) + private void ConfigureCore(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider prov, IOptions dataDirectories) { - Logs.Configure(loggerFactory); app.UsePlugins(); if (env.IsDevelopment()) { diff --git a/BTCPayServer/PaymentRequest/PaymentRequestHub.cs b/BTCPayServer/PaymentRequest/PaymentRequestHub.cs index feaeac064..2b15e5bde 100644 --- a/BTCPayServer/PaymentRequest/PaymentRequestHub.cs +++ b/BTCPayServer/PaymentRequest/PaymentRequestHub.cs @@ -103,7 +103,8 @@ namespace BTCPayServer.PaymentRequest public PaymentRequestStreamer(EventAggregator eventAggregator, IHubContext hubContext, PaymentRequestRepository paymentRequestRepository, - PaymentRequestService paymentRequestService) : base(eventAggregator) + PaymentRequestService paymentRequestService, + Logs logs) : base(eventAggregator, logs) { _HubContext = hubContext; _PaymentRequestRepository = paymentRequestRepository; diff --git a/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs b/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs index 07aa86e93..b65f2fe1a 100644 --- a/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs +++ b/BTCPayServer/Payments/Bitcoin/NBXplorerListener.cs @@ -39,8 +39,10 @@ namespace BTCPayServer.Payments.Bitcoin InvoiceRepository invoiceRepository, EventAggregator aggregator, PayJoinRepository payjoinRepository, - PaymentService paymentService) + PaymentService paymentService, + Logs logs) { + this.Logs = logs; PollInterval = TimeSpan.FromMinutes(1.0); _Wallets = wallets; _InvoiceRepository = invoiceRepository; @@ -55,6 +57,9 @@ namespace BTCPayServer.Payments.Bitcoin private Timer _ListenPoller; TimeSpan _PollInterval; + + public Logs Logs { get; } + public TimeSpan PollInterval { get diff --git a/BTCPayServer/Payments/Lightning/LightningListener.cs b/BTCPayServer/Payments/Lightning/LightningListener.cs index b8eeb64f1..810565999 100644 --- a/BTCPayServer/Payments/Lightning/LightningListener.cs +++ b/BTCPayServer/Payments/Lightning/LightningListener.cs @@ -24,6 +24,8 @@ namespace BTCPayServer.Payments.Lightning { public class LightningListener : IHostedService { + public Logs Logs { get; } + readonly EventAggregator _Aggregator; readonly InvoiceRepository _InvoiceRepository; private readonly IMemoryCache _memoryCache; @@ -44,8 +46,10 @@ namespace BTCPayServer.Payments.Lightning LightningLikePaymentHandler lightningLikePaymentHandler, StoreRepository storeRepository, IOptions options, - PaymentService paymentService) + PaymentService paymentService, + Logs logs) { + Logs = logs; _Aggregator = aggregator; _InvoiceRepository = invoiceRepository; _memoryCache = memoryCache; @@ -70,7 +74,7 @@ namespace BTCPayServer.Payments.Lightning if (!_InstanceListeners.TryGetValue(instanceListenerKey, out var instanceListener) || !instanceListener.IsListening) { - instanceListener ??= new LightningInstanceListener(_InvoiceRepository, _Aggregator, lightningClientFactory, listenedInvoice.Network, GetLightningUrl(listenedInvoice.SupportedPaymentMethod), _paymentService); + instanceListener ??= new LightningInstanceListener(_InvoiceRepository, _Aggregator, lightningClientFactory, listenedInvoice.Network, GetLightningUrl(listenedInvoice.SupportedPaymentMethod), _paymentService, Logs); var status = await instanceListener.PollPayment(listenedInvoice, cancellation); if (status is null || status is LightningInvoiceStatus.Paid || @@ -393,6 +397,8 @@ namespace BTCPayServer.Payments.Lightning public class LightningInstanceListener { + public Logs Logs { get; } + private readonly InvoiceRepository _invoiceRepository; private readonly EventAggregator _eventAggregator; private readonly BTCPayNetwork _network; @@ -406,10 +412,12 @@ namespace BTCPayServer.Payments.Lightning LightningClientFactoryService lightningClientFactory, BTCPayNetwork network, LightningConnectionString connectionString, - PaymentService paymentService) + PaymentService paymentService, + Logs logs) { if (connectionString == null) throw new ArgumentNullException(nameof(connectionString)); + Logs = logs; this._invoiceRepository = invoiceRepository; _eventAggregator = eventAggregator; this._network = network; diff --git a/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs b/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs index 808edeb87..a4e90850c 100644 --- a/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs +++ b/BTCPayServer/Payments/PayJoin/PayJoinEndpointController.cs @@ -10,6 +10,7 @@ using BTCPayServer.Data; using BTCPayServer.Events; using BTCPayServer.Filters; using BTCPayServer.HostedServices; +using BTCPayServer.Logging; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services; using BTCPayServer.Services.Invoices; @@ -93,6 +94,8 @@ namespace BTCPayServer.Payments.PayJoin private readonly StoreRepository _storeRepository; private readonly PaymentService _paymentService; + public Logs Logs { get; } + public PayJoinEndpointController(BTCPayNetworkProvider btcPayNetworkProvider, InvoiceRepository invoiceRepository, ExplorerClientProvider explorerClientProvider, BTCPayWalletProvider btcPayWalletProvider, @@ -103,7 +106,8 @@ namespace BTCPayServer.Payments.PayJoin BTCPayServerEnvironment env, WalletReceiveService walletReceiveService, StoreRepository storeRepository, - PaymentService paymentService) + PaymentService paymentService, + Logs logs) { _btcPayNetworkProvider = btcPayNetworkProvider; _invoiceRepository = invoiceRepository; @@ -117,6 +121,7 @@ namespace BTCPayServer.Payments.PayJoin _walletReceiveService = walletReceiveService; _storeRepository = storeRepository; _paymentService = paymentService; + Logs = logs; } [HttpPost("")] @@ -145,7 +150,7 @@ namespace BTCPayServer.Payments.PayJoin }); } - await using var ctx = new PayjoinReceiverContext(_invoiceRepository, _explorerClientProvider.GetExplorerClient(network), _payJoinRepository); + await using var ctx = new PayjoinReceiverContext(_invoiceRepository, _explorerClientProvider.GetExplorerClient(network), _payJoinRepository, Logs); ObjectResult CreatePayjoinErrorAndLog(int httpCode, PayjoinReceiverWellknownErrors err, string debug) { ctx.Logs.Write($"Payjoin error: {debug}", InvoiceEventData.EventSeverity.Error); diff --git a/BTCPayServer/Payments/PayJoin/PayjoinReceiverContext.cs b/BTCPayServer/Payments/PayJoin/PayjoinReceiverContext.cs index 130bc4307..a5278737e 100644 --- a/BTCPayServer/Payments/PayJoin/PayjoinReceiverContext.cs +++ b/BTCPayServer/Payments/PayJoin/PayjoinReceiverContext.cs @@ -15,9 +15,10 @@ namespace BTCPayServer.Payments.PayJoin private readonly InvoiceRepository _invoiceRepository; private readonly ExplorerClient _explorerClient; private readonly PayJoinRepository _payJoinRepository; - - public PayjoinReceiverContext(InvoiceRepository invoiceRepository, ExplorerClient explorerClient, PayJoinRepository payJoinRepository) + private readonly BTCPayServer.Logging.Logs BTCPayLogs; + public PayjoinReceiverContext(InvoiceRepository invoiceRepository, ExplorerClient explorerClient, PayJoinRepository payJoinRepository, BTCPayServer.Logging.Logs logs) { + this.BTCPayLogs = logs; _invoiceRepository = invoiceRepository; _explorerClient = explorerClient; _payJoinRepository = payJoinRepository; @@ -47,7 +48,7 @@ namespace BTCPayServer.Payments.PayJoin } catch (Exception ex) { - BTCPayServer.Logging.Logs.PayServer.LogWarning(ex, "Error while disposing the PayjoinReceiverContext"); + BTCPayLogs.PayServer.LogWarning(ex, "Error while disposing the PayjoinReceiverContext"); } } diff --git a/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs b/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs index a96a68fcc..467aef9f4 100644 --- a/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs +++ b/BTCPayServer/Plugins/Shopify/ShopifyOrderMarkerHostedService.cs @@ -23,7 +23,8 @@ namespace BTCPayServer.Plugins.Shopify public ShopifyOrderMarkerHostedService(EventAggregator eventAggregator, StoreRepository storeRepository, - IHttpClientFactory httpClientFactory) : base(eventAggregator) + IHttpClientFactory httpClientFactory, + Logs logs) : base(eventAggregator, logs) { _storeRepository = storeRepository; _httpClientFactory = httpClientFactory; diff --git a/BTCPayServer/Program.cs b/BTCPayServer/Program.cs index 2f1a66f14..a83ba57f3 100644 --- a/BTCPayServer/Program.cs +++ b/BTCPayServer/Program.cs @@ -25,6 +25,7 @@ namespace BTCPayServer using var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); + Logs logs = new Logs(); IConfiguration conf = null; try { @@ -32,9 +33,9 @@ namespace BTCPayServer conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) return; - Logs.Configure(loggerFactory); - new BTCPayServerOptions().LoadArgs(conf); - Logs.Configure(null); + logs.Configure(loggerFactory); + new BTCPayServerOptions().LoadArgs(conf, logs); + logs.Configure(null); ///// host = new WebHostBuilder() @@ -65,7 +66,7 @@ namespace BTCPayServer catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) - Logs.Configuration.LogError(ex.Message); + logs.Configuration.LogError(ex.Message); } catch(Exception e) when( PluginManager.IsExceptionByPlugin(e)) { @@ -76,7 +77,7 @@ namespace BTCPayServer { processor.Dispose(); if (host == null) - Logs.Configuration.LogError("Configuration error"); + logs.Configuration.LogError("Configuration error"); if (host != null) host.Dispose(); Serilog.Log.CloseAndFlush(); diff --git a/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumService.cs b/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumService.cs index ac90b9404..0e4cca423 100644 --- a/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumService.cs +++ b/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumService.cs @@ -43,8 +43,8 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services SettingsRepository settingsRepository, InvoiceRepository invoiceRepository, IConfiguration configuration, - PaymentService paymentService) : base( - eventAggregator) + PaymentService paymentService, + Logs logs) : base(eventAggregator, logs) { _httpClientFactory = httpClientFactory; _eventAggregator = eventAggregator; @@ -189,7 +189,7 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services _chainHostedServiceCancellationTokenSources.AddOrReplace(ethereumLikeConfiguration.ChainId, cts); _chainHostedServices.AddOrReplace(ethereumLikeConfiguration.ChainId, new EthereumWatcher(ethereumLikeConfiguration.ChainId, ethereumLikeConfiguration, - _btcPayNetworkProvider, _eventAggregator, _invoiceRepository, _paymentService)); + _btcPayNetworkProvider, _eventAggregator, _invoiceRepository, _paymentService, Logs)); await _chainHostedServices[ethereumLikeConfiguration.ChainId].StartAsync(CancellationTokenSource .CreateLinkedTokenSource(cancellationToken, cts.Token).Token); } diff --git a/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumWatcher.cs b/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumWatcher.cs index 5e97d2850..14ed1244d 100644 --- a/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumWatcher.cs +++ b/BTCPayServer/Services/Altcoins/Ethereum/Services/EthereumWatcher.cs @@ -34,7 +34,7 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services public override async Task StartAsync(CancellationToken cancellationToken) { - Logs.NodeServer.LogInformation($"Starting EthereumWatcher for chain {ChainId}"); + Logs.PayServer.LogInformation($"Starting EthereumWatcher for chain {ChainId}"); var result = await Web3.Eth.ChainId.SendRequestAsync(); if (result.Value != ChainId) { @@ -203,7 +203,7 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services public override Task StopAsync(CancellationToken cancellationToken) { - Logs.NodeServer.LogInformation($"Stopping EthereumWatcher for chain {ChainId}"); + Logs.PayServer.LogInformation($"Stopping EthereumWatcher for chain {ChainId}"); return base.StopAsync(cancellationToken); } @@ -257,7 +257,7 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services var tasks = new List(); if (existingPaymentData.Any() && currentBlock.Value != LastBlock) { - Logs.NodeServer.LogInformation( + Logs.PayServer.LogInformation( $"Checking {existingPaymentData.Count} existing payments on {expandedInvoices.Count} invoices on {network.CryptoCode}"); var blockParameter = new BlockParameter(currentBlock); @@ -282,7 +282,7 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services if (noAccountedPaymentInvoices.Any()) { - Logs.NodeServer.LogInformation( + Logs.PayServer.LogInformation( $"Checking {noAccountedPaymentInvoices.Count} addresses for new payments on {network.CryptoCode}"); var blockParameter = BlockParameter.CreatePending(); tasks.AddRange(noAccountedPaymentInvoices.Select(async tuple => @@ -346,8 +346,9 @@ namespace BTCPayServer.Services.Altcoins.Ethereum.Services public EthereumWatcher(int chainId, EthereumLikeConfiguration config, BTCPayNetworkProvider btcPayNetworkProvider, - EventAggregator eventAggregator, InvoiceRepository invoiceRepository, PaymentService paymentService) : - base(eventAggregator) + EventAggregator eventAggregator, InvoiceRepository invoiceRepository, PaymentService paymentService, + BTCPayServer.Logging.Logs logs) : + base(eventAggregator, logs) { _eventAggregator = eventAggregator; _invoiceRepository = invoiceRepository; diff --git a/BTCPayServer/Services/Altcoins/Monero/Services/MoneroLikeSummaryUpdaterHostedService.cs b/BTCPayServer/Services/Altcoins/Monero/Services/MoneroLikeSummaryUpdaterHostedService.cs index 91c9210d4..f0cc18fbf 100644 --- a/BTCPayServer/Services/Altcoins/Monero/Services/MoneroLikeSummaryUpdaterHostedService.cs +++ b/BTCPayServer/Services/Altcoins/Monero/Services/MoneroLikeSummaryUpdaterHostedService.cs @@ -13,11 +13,15 @@ namespace BTCPayServer.Services.Altcoins.Monero.Services { private readonly MoneroRPCProvider _MoneroRpcProvider; private readonly MoneroLikeConfiguration _moneroLikeConfiguration; + + public Logs Logs { get; } + private CancellationTokenSource _Cts; - public MoneroLikeSummaryUpdaterHostedService(MoneroRPCProvider moneroRpcProvider, MoneroLikeConfiguration moneroLikeConfiguration) + public MoneroLikeSummaryUpdaterHostedService(MoneroRPCProvider moneroRpcProvider, MoneroLikeConfiguration moneroLikeConfiguration, Logs logs) { _MoneroRpcProvider = moneroRpcProvider; _moneroLikeConfiguration = moneroLikeConfiguration; + Logs = logs; } public Task StartAsync(CancellationToken cancellationToken) { diff --git a/BTCPayServer/Services/Apps/AppHubStreamer.cs b/BTCPayServer/Services/Apps/AppHubStreamer.cs index ee43a8255..041c30018 100644 --- a/BTCPayServer/Services/Apps/AppHubStreamer.cs +++ b/BTCPayServer/Services/Apps/AppHubStreamer.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using BTCPayServer.Controllers; using BTCPayServer.Events; using BTCPayServer.HostedServices; +using BTCPayServer.Logging; using Microsoft.AspNetCore.SignalR; namespace BTCPayServer.Services.Apps @@ -14,7 +15,8 @@ namespace BTCPayServer.Services.Apps public AppHubStreamer(EventAggregator eventAggregator, IHubContext hubContext, - AppService appService) : base(eventAggregator) + AppService appService, + Logs logs) : base(eventAggregator, logs) { _appService = appService; _HubContext = hubContext; diff --git a/BTCPayServer/Services/DelayedTransactionBroadcaster.cs b/BTCPayServer/Services/DelayedTransactionBroadcaster.cs index 4471a0a47..7ede267c9 100644 --- a/BTCPayServer/Services/DelayedTransactionBroadcaster.cs +++ b/BTCPayServer/Services/DelayedTransactionBroadcaster.cs @@ -25,16 +25,20 @@ namespace BTCPayServer.Services private readonly ExplorerClientProvider _explorerClientProvider; private readonly ApplicationDbContextFactory _dbContextFactory; + public Logs Logs { get; } + public DelayedTransactionBroadcaster( BTCPayNetworkProvider networkProvider, ExplorerClientProvider explorerClientProvider, - Data.ApplicationDbContextFactory dbContextFactory) + Data.ApplicationDbContextFactory dbContextFactory, + Logs logs) { if (explorerClientProvider == null) throw new ArgumentNullException(nameof(explorerClientProvider)); _networkProvider = networkProvider; _explorerClientProvider = explorerClientProvider; _dbContextFactory = dbContextFactory; + this.Logs = logs; } public async Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network) diff --git a/BTCPayServer/Services/Invoices/InvoiceRepository.cs b/BTCPayServer/Services/Invoices/InvoiceRepository.cs index 75074c6f8..ea4624999 100644 --- a/BTCPayServer/Services/Invoices/InvoiceRepository.cs +++ b/BTCPayServer/Services/Invoices/InvoiceRepository.cs @@ -29,13 +29,16 @@ namespace BTCPayServer.Services.Invoices NBitcoin.JsonConverters.Serializer.RegisterFrontConverters(DefaultSerializerSettings); } + public Logs Logs { get; } + private readonly ApplicationDbContextFactory _applicationDbContextFactory; private readonly EventAggregator _eventAggregator; private readonly BTCPayNetworkProvider _btcPayNetworkProvider; public InvoiceRepository(ApplicationDbContextFactory contextFactory, - BTCPayNetworkProvider networks, EventAggregator eventAggregator) + BTCPayNetworkProvider networks, EventAggregator eventAggregator, Logs logs) { + Logs = logs; _applicationDbContextFactory = contextFactory; _btcPayNetworkProvider = networks; _eventAggregator = eventAggregator; diff --git a/BTCPayServer/Services/Mails/EmailSender.cs b/BTCPayServer/Services/Mails/EmailSender.cs index c158db4d0..abe011bd8 100644 --- a/BTCPayServer/Services/Mails/EmailSender.cs +++ b/BTCPayServer/Services/Mails/EmailSender.cs @@ -9,10 +9,13 @@ namespace BTCPayServer.Services.Mails { public abstract class EmailSender : IEmailSender { + public Logs Logs { get; } + readonly IBackgroundJobClient _JobClient; - public EmailSender(IBackgroundJobClient jobClient) + public EmailSender(IBackgroundJobClient jobClient, Logs logs) { + Logs = logs; _JobClient = jobClient ?? throw new ArgumentNullException(nameof(jobClient)); } diff --git a/BTCPayServer/Services/Mails/EmailSenderFactory.cs b/BTCPayServer/Services/Mails/EmailSenderFactory.cs index 35cddd255..e0473ff13 100644 --- a/BTCPayServer/Services/Mails/EmailSenderFactory.cs +++ b/BTCPayServer/Services/Mails/EmailSenderFactory.cs @@ -1,19 +1,24 @@ using System.Threading.Tasks; using BTCPayServer.HostedServices; +using BTCPayServer.Logging; using BTCPayServer.Services.Stores; namespace BTCPayServer.Services.Mails { public class EmailSenderFactory { + public Logs Logs { get; } + private readonly IBackgroundJobClient _jobClient; private readonly SettingsRepository _settingsRepository; private readonly StoreRepository _storeRepository; public EmailSenderFactory(IBackgroundJobClient jobClient, SettingsRepository settingsSettingsRepository, - StoreRepository storeRepository) + StoreRepository storeRepository, + Logs logs) { + Logs = logs; _jobClient = jobClient; _settingsRepository = settingsSettingsRepository; _storeRepository = storeRepository; @@ -21,12 +26,12 @@ namespace BTCPayServer.Services.Mails public async Task GetEmailSender(string storeId = null) { - var serverSender = new ServerEmailSender(_settingsRepository, _jobClient); + var serverSender = new ServerEmailSender(_settingsRepository, _jobClient, Logs); if (string.IsNullOrEmpty(storeId)) return serverSender; return new StoreEmailSender(_storeRepository, !(await _settingsRepository.GetPolicies()).DisableStoresToUseServerEmailSettings ? serverSender : null, _jobClient, - storeId); + storeId, Logs); } } } diff --git a/BTCPayServer/Services/Mails/ServerEmailSender.cs b/BTCPayServer/Services/Mails/ServerEmailSender.cs index e80329195..42256f8f3 100644 --- a/BTCPayServer/Services/Mails/ServerEmailSender.cs +++ b/BTCPayServer/Services/Mails/ServerEmailSender.cs @@ -1,12 +1,14 @@ using System; using System.Threading.Tasks; +using BTCPayServer.Logging; namespace BTCPayServer.Services.Mails { class ServerEmailSender : EmailSender { public ServerEmailSender(SettingsRepository settingsRepository, - IBackgroundJobClient backgroundJobClient) : base(backgroundJobClient) + IBackgroundJobClient backgroundJobClient, + Logs logs) : base(backgroundJobClient, logs) { if (settingsRepository == null) throw new ArgumentNullException(nameof(settingsRepository)); diff --git a/BTCPayServer/Services/Mails/StoreEmailSender.cs b/BTCPayServer/Services/Mails/StoreEmailSender.cs index 9c65d94f8..3e2a87b18 100644 --- a/BTCPayServer/Services/Mails/StoreEmailSender.cs +++ b/BTCPayServer/Services/Mails/StoreEmailSender.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using BTCPayServer.Data; +using BTCPayServer.Logging; using BTCPayServer.Services.Stores; namespace BTCPayServer.Services.Mails @@ -10,7 +11,8 @@ namespace BTCPayServer.Services.Mails public StoreEmailSender(StoreRepository storeRepository, EmailSender fallback, IBackgroundJobClient backgroundJobClient, - string storeId) : base(backgroundJobClient) + string storeId, + Logs logs) : base(backgroundJobClient, logs) { StoreId = storeId ?? throw new ArgumentNullException(nameof(storeId)); StoreRepository = storeRepository; diff --git a/BTCPayServer/Services/TorServices.cs b/BTCPayServer/Services/TorServices.cs index e1f2047e1..18835a393 100644 --- a/BTCPayServer/Services/TorServices.cs +++ b/BTCPayServer/Services/TorServices.cs @@ -17,7 +17,8 @@ namespace BTCPayServer.Services private readonly BTCPayNetworkProvider _btcPayNetworkProvider; private readonly IOptions _options; - public TorServices(BTCPayNetworkProvider btcPayNetworkProvider, IOptions options) + + public TorServices(BTCPayNetworkProvider btcPayNetworkProvider, IOptions options, Logs logs) : base(logs) { _btcPayNetworkProvider = btcPayNetworkProvider; _options = options; diff --git a/BTCPayServer/Services/Wallets/BTCPayWallet.cs b/BTCPayServer/Services/Wallets/BTCPayWallet.cs index 75e357898..960e6f17b 100644 --- a/BTCPayServer/Services/Wallets/BTCPayWallet.cs +++ b/BTCPayServer/Services/Wallets/BTCPayWallet.cs @@ -39,15 +39,18 @@ namespace BTCPayServer.Services.Wallets } public class BTCPayWallet { + public Logs Logs { get; } + private readonly ExplorerClient _Client; private readonly IMemoryCache _MemoryCache; public BTCPayWallet(ExplorerClient client, IMemoryCache memoryCache, BTCPayNetwork network, - ApplicationDbContextFactory dbContextFactory) + ApplicationDbContextFactory dbContextFactory, Logs logs) { if (client == null) throw new ArgumentNullException(nameof(client)); if (memoryCache == null) throw new ArgumentNullException(nameof(memoryCache)); + Logs = logs; _Client = client; _Network = network; _dbContextFactory = dbContextFactory; diff --git a/BTCPayServer/Services/Wallets/BTCPayWalletProvider.cs b/BTCPayServer/Services/Wallets/BTCPayWalletProvider.cs index a1b2b4561..38bfe84ce 100644 --- a/BTCPayServer/Services/Wallets/BTCPayWalletProvider.cs +++ b/BTCPayServer/Services/Wallets/BTCPayWalletProvider.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using BTCPayServer.Logging; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; @@ -8,16 +9,20 @@ namespace BTCPayServer.Services.Wallets { public class BTCPayWalletProvider { + public Logs Logs { get; } + private readonly ExplorerClientProvider _Client; readonly BTCPayNetworkProvider _NetworkProvider; readonly IOptions _Options; public BTCPayWalletProvider(ExplorerClientProvider client, IOptions memoryCacheOption, Data.ApplicationDbContextFactory dbContextFactory, - BTCPayNetworkProvider networkProvider) + BTCPayNetworkProvider networkProvider, + Logs logs) { if (client == null) throw new ArgumentNullException(nameof(client)); + this.Logs = logs; _Client = client; _NetworkProvider = networkProvider; _Options = memoryCacheOption; @@ -27,7 +32,7 @@ namespace BTCPayServer.Services.Wallets var explorerClient = _Client.GetExplorerClient(network.CryptoCode); if (explorerClient == null) continue; - _Wallets.Add(network.CryptoCode.ToUpperInvariant(), new BTCPayWallet(explorerClient, new MemoryCache(_Options), network, dbContextFactory)); + _Wallets.Add(network.CryptoCode.ToUpperInvariant(), new BTCPayWallet(explorerClient, new MemoryCache(_Options), network, dbContextFactory, Logs)); } }