using System; using System.IO; using System.Threading; using BTCPayServer.Configuration; using BTCPayServer.Contracts; using BTCPayServer.Controllers; using BTCPayServer.Data; using BTCPayServer.HostedServices; using BTCPayServer.Logging; using BTCPayServer.PaymentRequest; using BTCPayServer.Payments; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Payments.Lightning; using BTCPayServer.Payments.PayJoin; using BTCPayServer.Plugins; using BTCPayServer.Security; using BTCPayServer.Security.Bitpay; using BTCPayServer.Security.GreenField; using BTCPayServer.Services; using BTCPayServer.Services.Apps; using BTCPayServer.Services.Fees; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Labels; using BTCPayServer.Services.Mails; using BTCPayServer.Services.Notifications; using BTCPayServer.Services.Notifications.Blobs; using BTCPayServer.Services.PaymentRequests; using BTCPayServer.Services.Rates; using BTCPayServer.Services.Shopify; using BTCPayServer.Services.Stores; using BTCPayServer.Services.Wallets; using BTCPayServer.U2F; using BundlerMinifier.TagHelpers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NBitcoin; using NBitpayClient; using NBXplorer.DerivationStrategy; using Newtonsoft.Json; using NicolasDorier.RateLimits; using Serilog; #if ALTCOINS using BTCPayServer.Services.Altcoins.Monero; using BTCPayServer.Services.Altcoins.Ethereum; #endif namespace BTCPayServer.Hosting { public static class BTCPayServerServices { public static IServiceCollection RegisterJsonConverter(this IServiceCollection services, Func create) { services.AddSingleton((s) => new JsonConverterRegistration(create)); return services; } public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton(o => o.GetRequiredService>().Value); services.AddDbContext((provider, o) => { var factory = provider.GetRequiredService(); factory.ConfigureBuilder(o); }); services.AddHttpClient(); services.AddHttpClient(nameof(ExplorerClientProvider), httpClient => { httpClient.Timeout = Timeout.InfiniteTimeSpan; }); services.AddSingleton(); services.RegisterJsonConverter(n => new ClaimDestinationJsonConverter(n)); services.AddPayJoinServices(); #if ALTCOINS services.AddMoneroLike(); services.AddEthereumLike(); #endif services.TryAddSingleton(); services.TryAddSingleton(provider => provider.GetService()); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(o => o.GetRequiredService>().Value); services.AddStartupTask(); services.AddStartupTask(); services.TryAddSingleton(o => { var opts = o.GetRequiredService(); var dbContext = o.GetRequiredService(); var dbpath = Path.Combine(opts.DataDir, "InvoiceDB"); if (!Directory.Exists(dbpath)) Directory.CreateDirectory(dbpath); return new InvoiceRepository(dbContext, dbpath, o.GetRequiredService(), o.GetService()); }); services.AddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(o => { var opts = o.GetRequiredService(); ApplicationDbContextFactory dbContext = null; if (!string.IsNullOrEmpty(opts.PostgresConnectionString)) { Logs.Configuration.LogInformation($"Postgres DB used"); dbContext = new ApplicationDbContextFactory(DatabaseType.Postgres, opts.PostgresConnectionString); } else if (!string.IsNullOrEmpty(opts.MySQLConnectionString)) { Logs.Configuration.LogInformation($"MySQL DB used"); Logs.Configuration.LogWarning("MySQL is not widely tested and should be considered experimental, we advise you to use postgres instead."); dbContext = new ApplicationDbContextFactory(DatabaseType.MySQL, opts.MySQLConnectionString); } else if (!string.IsNullOrEmpty(opts.SQLiteFileName)) { var connStr = "Data Source=" +(Path.IsPathRooted(opts.SQLiteFileName) ? opts.SQLiteFileName : Path.Combine(opts.DataDir, opts.SQLiteFileName)); Logs.Configuration.LogInformation($"SQLite DB used"); Logs.Configuration.LogWarning("SQLite is not widely tested and should be considered experimental, we advise you to use postgres instead."); dbContext = new ApplicationDbContextFactory(DatabaseType.Sqlite, connStr); } else { throw new ConfigException("No database option was configured."); } return dbContext; }); services.TryAddSingleton(o => { var opts = o.GetRequiredService(); return opts.NetworkProvider; }); services.TryAddSingleton(); services.AddSingleton(); services.TryAddTransient(); services.TryAddSingleton(o => { var htmlSanitizer = new Ganss.XSS.HtmlSanitizer(); htmlSanitizer.RemovingAtRule += (sender, args) => { }; htmlSanitizer.RemovingTag += (sender, args) => { if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase)) { if (!args.Tag.ClassList.Contains("img-fluid")) { args.Tag.ClassList.Add("img-fluid"); } args.Cancel = true; } }; htmlSanitizer.RemovingAttribute += (sender, args) => { if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase) && args.Attribute.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase) && args.Reason == Ganss.XSS.RemoveReason.NotAllowedUrlValue) { args.Cancel = true; } }; htmlSanitizer.RemovingStyle += (sender, args) => { args.Cancel = true; }; htmlSanitizer.AllowedAttributes.Add("class"); htmlSanitizer.AllowedTags.Add("iframe"); htmlSanitizer.AllowedTags.Add("style"); htmlSanitizer.AllowedTags.Remove("img"); htmlSanitizer.AllowedAttributes.Add("webkitallowfullscreen"); htmlSanitizer.AllowedAttributes.Add("allowfullscreen"); return htmlSanitizer; }); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(CurrencyNameTable.Instance); services.TryAddSingleton(o => new NBXplorerFeeProviderFactory(o.GetRequiredService()) { Fallback = new FeeRate(100L, 1) }); services.AddSingleton(); services.Configure((o) => { o.Filters.Add(new ContentSecurityPolicyCssThemeManager()); o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(WalletId))); o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(DerivationStrategyBase))); }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(o => o.GetRequiredService()); services.AddSingleton(); services.AddSingleton(o => o.GetRequiredService()); services.AddSingleton(); services.AddSingleton(provider => provider.GetService()); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(provider => provider.GetService()); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddShopify(); #if DEBUG services.AddSingleton(); #endif services.TryAddSingleton(); services.TryAddSingleton(o => { if (o.GetRequiredService().NetworkType == NetworkType.Mainnet) return new Bitpay(new Key(), new Uri("https://bitpay.com/")); else return new Bitpay(new Key(), new Uri("https://test.bitpay.com/")); }); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddScoped(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); // Add application services. services.AddSingleton(); services.AddAPIKeyAuthentication(); services.AddBtcPayServerAuthenticationSchemes(); services.AddAuthorization(o => o.AddBTCPayPolicies()); // bundling services.AddSingleton(); services.AddTransient(provider => { var opts = provider.GetRequiredService(); var bundle = new BundleOptions(); bundle.UseBundles = opts.BundleJsCss; bundle.AppendVersion = true; return bundle; }); services.AddCors(options => { options.AddPolicy(CorsPolicies.All, p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); }); services.AddSingleton(provider => { var btcPayEnv = provider.GetService(); var rateLimits = new RateLimitService(); if (btcPayEnv.IsDeveloping) { rateLimits.SetZone($"zone={ZoneLimits.Login} rate=1000r/min burst=100 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.Register} rate=1000r/min burst=100 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.PayJoin} rate=1000r/min burst=100 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.Shopify} rate=1000r/min burst=100 nodelay"); } else { rateLimits.SetZone($"zone={ZoneLimits.Login} rate=5r/min burst=3 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.Register} rate=2r/min burst=2 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.PayJoin} rate=5r/min burst=3 nodelay"); rateLimits.SetZone($"zone={ZoneLimits.Shopify} rate=20r/min burst=3 nodelay"); } return rateLimits; }); services.AddLogging(logBuilder => { var debugLogFile = BTCPayServerOptions.GetDebugLog(configuration); if (!string.IsNullOrEmpty(debugLogFile)) { Serilog.Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(configuration)) .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1) .CreateLogger(); logBuilder.AddProvider(new Serilog.Extensions.Logging.SerilogLoggerProvider(Log.Logger)); } }); return services; } private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB. private static void AddBtcPayServerAuthenticationSchemes(this IServiceCollection services) { services.AddAuthentication() .AddCookie() .AddBitpayAuthentication() .AddAPIKeyAuthentication(); } public static IApplicationBuilder UsePayServer(this IApplicationBuilder app) { app.UseMiddleware(); return app; } public static IApplicationBuilder UseHeadersOverride(this IApplicationBuilder app) { app.UseMiddleware(); return app; } } }