diff --git a/BTCPayServer.Tests/BTCPayServerTester.cs b/BTCPayServer.Tests/BTCPayServerTester.cs index 237bd882c..3879d471b 100644 --- a/BTCPayServer.Tests/BTCPayServerTester.cs +++ b/BTCPayServer.Tests/BTCPayServerTester.cs @@ -45,21 +45,13 @@ namespace BTCPayServer.Tests } public Uri LTCNBXplorerUri { get; set; } - public string CookieFile - { - get; set; - } + public Uri ServerUri { get; set; } - public ExtKey HDPrivateKey - { - get; set; - } - public string Postgres { get; set; @@ -76,15 +68,17 @@ namespace BTCPayServer.Tests if (!Directory.Exists(_Directory)) Directory.CreateDirectory(_Directory); - HDPrivateKey = new ExtKey(); StringBuilder config = new StringBuilder(); config.AppendLine($"regtest=1"); config.AppendLine($"port={Port}"); - config.AppendLine($"explorer.url={NBXplorerUri.AbsoluteUri}"); + config.AppendLine($"chains=btc,ltc"); + + config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}"); + config.AppendLine($"btc.explorer.cookiefile=0"); + config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}"); - config.AppendLine($"explorer.cookiefile={CookieFile}"); - config.AppendLine($"ltc.explorer.cookiefile={CookieFile}"); - config.AppendLine($"hdpubkey={HDPrivateKey.Neuter().ToString(Network.RegTest)}"); + config.AppendLine($"ltc.explorer.cookiefile=0"); + if (Postgres != null) config.AppendLine($"postgres=" + Postgres); File.WriteAllText(Path.Combine(_Directory, "settings.config"), config.ToString()); diff --git a/BTCPayServer.Tests/EclairTester.cs b/BTCPayServer.Tests/EclairTester.cs index 6454f3230..32d7e4655 100644 --- a/BTCPayServer.Tests/EclairTester.cs +++ b/BTCPayServer.Tests/EclairTester.cs @@ -12,7 +12,7 @@ namespace BTCPayServer.Tests public EclairTester(ServerTester parent, string environmentName, string defaultRPC, string defaultHost) { this.parent = parent; - RPC = new EclairRPCClient(new Uri(parent.GetEnvironment(environmentName, defaultRPC)), parent.Network); + //RPC = new EclairRPCClient(new Uri(parent.GetEnvironment(environmentName, defaultRPC)), parent.Network); P2PHost = parent.GetEnvironment(environmentName + "_HOST", defaultHost); } diff --git a/BTCPayServer.Tests/ServerTester.cs b/BTCPayServer.Tests/ServerTester.cs index 0345b3fa1..8065c1fcc 100644 --- a/BTCPayServer.Tests/ServerTester.cs +++ b/BTCPayServer.Tests/ServerTester.cs @@ -47,12 +47,12 @@ namespace BTCPayServer.Tests Directory.CreateDirectory(_Directory); - var network = new BTCPayNetworkProvider(Network); - ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_RPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), network.GetNetwork("BTC").NBitcoinNetwork); - LTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LTCRPCCONNECTION", "server=http://127.0.0.1:43783;ceiwHEbqWI83:DwubwWsoo3")), network.GetNetwork("LTC").NBitcoinNetwork); + NetworkProvider = new BTCPayNetworkProvider(ChainType.Regtest); + ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_RPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork("BTC").NBitcoinNetwork); + LTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LTCRPCCONNECTION", "server=http://127.0.0.1:43783;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork("LTC").NBitcoinNetwork); - ExplorerClient = new ExplorerClient(Network, new Uri(GetEnvironment("TESTS_NBXPLORERURL", "http://127.0.0.1:32838/"))); - LTCExplorerClient = new ExplorerClient(Network, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32839/"))); + ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork("BTC").NBitcoinNetwork, new Uri(GetEnvironment("TESTS_NBXPLORERURL", "http://127.0.0.1:32838/"))); + LTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork("LTC").NBitcoinNetwork, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32839/"))); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { @@ -108,6 +108,8 @@ namespace BTCPayServer.Tests { return new TestAccount(this); } + + public BTCPayNetworkProvider NetworkProvider { get; private set; } public RPCClient ExplorerNode { get; set; @@ -224,12 +226,6 @@ namespace BTCPayServer.Tests get; set; } - public Network Network - { - get; - set; - } = Network.RegTest; - public void Dispose() { if (PayTester != null) diff --git a/BTCPayServer.Tests/TestAccount.cs b/BTCPayServer.Tests/TestAccount.cs index a0d07d671..21a75deaa 100644 --- a/BTCPayServer.Tests/TestAccount.cs +++ b/BTCPayServer.Tests/TestAccount.cs @@ -46,17 +46,18 @@ namespace BTCPayServer.Tests Assert.IsType(await store.RequestPairing(pairingCode.ToString())); await store.Pair(pairingCode.ToString(), StoreId); } - public StoresController CreateStore() + public StoresController CreateStore(string cryptoCode = "BTC") { - return CreateStoreAsync().GetAwaiter().GetResult(); + return CreateStoreAsync(cryptoCode).GetAwaiter().GetResult(); } - public async Task CreateStoreAsync() + public async Task CreateStoreAsync(string cryptoCode = "BTC") { - ExtKey = new ExtKey().GetWif(parent.Network); + SupportedNetwork = parent.NetworkProvider.GetNetwork(cryptoCode); + ExtKey = new ExtKey().GetWif(SupportedNetwork.NBitcoinNetwork); var store = parent.PayTester.GetController(UserId); await store.CreateStore(new CreateStoreViewModel() { Name = "Test Store" }); StoreId = store.CreatedStoreId; - DerivationScheme = new DerivationStrategyFactory(parent.Network).Parse(ExtKey.Neuter().ToString() + "-[legacy]"); + DerivationScheme = new DerivationStrategyFactory(SupportedNetwork.NBitcoinNetwork).Parse(ExtKey.Neuter().ToString() + "-[legacy]"); await store.UpdateStore(StoreId, new StoreViewModel() { SpeedPolicy = SpeedPolicy.MediumSpeed @@ -71,6 +72,8 @@ namespace BTCPayServer.Tests return store; } + public BTCPayNetwork SupportedNetwork { get; set; } + public void RegisterDerivationScheme(string crytoCode) { RegisterDerivationSchemeAsync(crytoCode).GetAwaiter().GetResult(); diff --git a/BTCPayServer.Tests/UnitTest1.cs b/BTCPayServer.Tests/UnitTest1.cs index 3aa84efa2..5da4bc4c1 100644 --- a/BTCPayServer.Tests/UnitTest1.cs +++ b/BTCPayServer.Tests/UnitTest1.cs @@ -330,13 +330,13 @@ namespace BTCPayServer.Tests false, //subtractfeefromamount true, //replaceable }).ResultString); - var invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, tester.Network); + var invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork); Eventually(() => { invoice = user.BitPay.GetInvoice(invoice.Id); Assert.Equal(payment1, invoice.BtcPaid); - invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, tester.Network); + invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork); }); var tx = tester.ExplorerNode.GetRawTransaction(new uint256(tx1)); diff --git a/BTCPayServer.Tests/docker-compose.yml b/BTCPayServer.Tests/docker-compose.yml index c0e1f3703..343f6f52f 100644 --- a/BTCPayServer.Tests/docker-compose.yml +++ b/BTCPayServer.Tests/docker-compose.yml @@ -39,7 +39,7 @@ services: - postgres bitcoin-nbxplorer: - image: nicolasdorier/nbxplorer:1.0.0.47 + image: nicolasdorier/nbxplorer:1.0.0.48 ports: - "32838:32838" expose: @@ -57,7 +57,7 @@ services: - bitcoind litecoin-nbxplorer: - image: nicolasdorier/nbxplorer:1.0.0.47 + image: nicolasdorier/nbxplorer:1.0.0.48 ports: - "32839:32839" expose: diff --git a/BTCPayServer/BTCPayNetwork.cs b/BTCPayServer/BTCPayNetwork.cs index af5a1cb32..23906355f 100644 --- a/BTCPayServer/BTCPayNetwork.cs +++ b/BTCPayServer/BTCPayNetwork.cs @@ -1,12 +1,54 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Services.Rates; using NBitcoin; +using NBXplorer.Configuration; namespace BTCPayServer { + public enum ChainType + { + Regtest, + Main, + Test + } + public class BTCPayDefaultSettings + { + static BTCPayDefaultSettings() + { + _Settings = new Dictionary(); + foreach (var chainType in new[] { ChainType.Main, ChainType.Test, ChainType.Regtest }) + { + var btcNetwork = (chainType == ChainType.Main ? Network.Main : + chainType == ChainType.Regtest ? Network.RegTest : + chainType == ChainType.Test ? Network.TestNet : throw new NotSupportedException(chainType.ToString())); + + var settings = new BTCPayDefaultSettings(); + _Settings.Add(chainType, settings); + settings.ChainType = chainType; + settings.DefaultDataDirectory = StandardConfiguration.DefaultDataDirectory.GetDirectory("BTCPayServer", btcNetwork.Name); + settings.DefaultConfigurationFile = Path.Combine(settings.DefaultDataDirectory, "settings.config"); + settings.DefaultPort = (chainType == ChainType.Main ? 23000 : + chainType == ChainType.Regtest ? 23002 : + chainType == ChainType.Test ? 23001 : throw new NotSupportedException(chainType.ToString())); + } + } + + static Dictionary _Settings; + + public static BTCPayDefaultSettings GetDefaultSettings(ChainType chainType) + { + return _Settings[chainType]; + } + + public string DefaultDataDirectory { get; set; } + public string DefaultConfigurationFile { get; set; } + public ChainType ChainType { get; internal set; } + public int DefaultPort { get; set; } + } public class BTCPayNetwork { public Network NBitcoinNetwork { get; set; } @@ -25,6 +67,10 @@ namespace BTCPayServer } public string CryptoImagePath { get; set; } + public NetworkInformation NBXplorerNetwork { get; set; } + + + public BTCPayDefaultSettings DefaultSettings { get; set; } public override string ToString() { return CryptoCode; diff --git a/BTCPayServer/BTCPayNetworkProvider.cs b/BTCPayServer/BTCPayNetworkProvider.cs index fe6c37456..a37dc2f26 100644 --- a/BTCPayServer/BTCPayNetworkProvider.cs +++ b/BTCPayServer/BTCPayNetworkProvider.cs @@ -1,11 +1,13 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Services.Rates; using Microsoft.Extensions.Caching.Memory; using NBitcoin; using NBitpayClient; +using NBXplorer.Configuration; namespace BTCPayServer { @@ -16,14 +18,14 @@ namespace BTCPayServer NBXplorer.Altcoins.Litecoin.Networks.EnsureRegistered(); } Dictionary _Networks = new Dictionary(); - public BTCPayNetworkProvider(Network network) + public BTCPayNetworkProvider(ChainType chainType) { var coinaverage = new CoinAverageRateProvider("BTC"); var bitpay = new BitpayRateProvider(new Bitpay(new Key(), new Uri("https://bitpay.com/"))); var btcRate = new FallbackRateProvider(new IRateProvider[] { coinaverage, bitpay }); var ltcRate = new CoinAverageRateProvider("LTC"); - if (network == Network.Main) + if (chainType == ChainType.Main) { Add(new BTCPayNetwork() { @@ -45,7 +47,7 @@ namespace BTCPayServer }); } - if (network == Network.TestNet) + if (chainType == ChainType.Test) { Add(new BTCPayNetwork() { @@ -67,7 +69,7 @@ namespace BTCPayServer }); } - if (network == Network.RegTest) + if (chainType == ChainType.Regtest) { Add(new BTCPayNetwork() { @@ -85,9 +87,15 @@ namespace BTCPayServer NBitcoinNetwork = NBXplorer.Altcoins.Litecoin.Networks.Regtest, UriScheme = "litecoin", DefaultRateProvider = ltcRate, - CryptoImagePath = "imlegacy/litecoin-symbol.svg" + CryptoImagePath = "imlegacy/litecoin-symbol.svg", }); } + + foreach(var n in _Networks) + { + n.Value.NBXplorerNetwork = NetworkInformation.GetNetworkByName(n.Value.NBitcoinNetwork.Name); + n.Value.DefaultSettings = BTCPayDefaultSettings.GetDefaultSettings(chainType); + } } [Obsolete("To use only for legacy stuff")] diff --git a/BTCPayServer/BTCPayServer.csproj b/BTCPayServer/BTCPayServer.csproj index a741f33c4..c0e34a4a6 100644 --- a/BTCPayServer/BTCPayServer.csproj +++ b/BTCPayServer/BTCPayServer.csproj @@ -2,7 +2,7 @@ Exe netcoreapp2.0 - 1.0.0.65 + 1.0.0.66 diff --git a/BTCPayServer/Configuration/BTCPayServerOptions.cs b/BTCPayServer/Configuration/BTCPayServerOptions.cs index 506632006..98bd77f0d 100644 --- a/BTCPayServer/Configuration/BTCPayServerOptions.cs +++ b/BTCPayServer/Configuration/BTCPayServerOptions.cs @@ -15,7 +15,7 @@ namespace BTCPayServer.Configuration { public class BTCPayServerOptions { - public Network Network + public ChainType ChainType { get; set; } @@ -37,41 +37,35 @@ namespace BTCPayServer.Configuration public void LoadArgs(IConfiguration conf) { - var networkInfo = DefaultConfiguration.GetNetwork(conf); - Network = networkInfo?.Network; - if (Network == null) - throw new ConfigException("Invalid network"); + ChainType = DefaultConfiguration.GetChainType(conf); + var defaultSettings = BTCPayDefaultSettings.GetDefaultSettings(ChainType); + DataDir = conf.GetOrDefault("datadir", defaultSettings.DefaultDataDirectory); + Logs.Configuration.LogInformation("Network: " + ChainType.ToString()); - DataDir = conf.GetOrDefault("datadir", networkInfo.DefaultDataDirectory); - Logs.Configuration.LogInformation("Network: " + Network); - - - bool btcHandled = false; - foreach (var net in new BTCPayNetworkProvider(Network).GetAll()) + var supportedChains = conf.GetOrDefault("chains", "btc") + .Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(t => t.ToLowerInvariant()); + var validChains = new List(); + foreach (var net in new BTCPayNetworkProvider(ChainType).GetAll()) { - var nbxplorer = NBXplorer.Configuration.NetworkInformation.GetNetworkByName(net.NBitcoinNetwork.Name); - var explorer = conf.GetOrDefault($"{net.CryptoCode}.explorer.url", null); - var cookieFile = conf.GetOrDefault($"{net.CryptoCode}.explorer.cookiefile", nbxplorer.GetDefaultCookieFile()); - if (explorer != null) + if (supportedChains.Contains(net.CryptoCode.ToLowerInvariant())) { -#pragma warning disable CS0618 - if (net.IsBTC) - btcHandled = true; -#pragma warning restore CS0618 - ExplorerFactories.Add(net.CryptoCode, (n) => CreateExplorerClient(n, explorer, cookieFile)); + validChains.Add(net.CryptoCode.ToLowerInvariant()); + var explorer = conf.GetOrDefault($"{net.CryptoCode}.explorer.url", new Uri(net.NBXplorerNetwork.GetDefaultExplorerUrl())); + var cookieFile = conf.GetOrDefault($"{net.CryptoCode}.explorer.cookiefile", net.NBXplorerNetwork.GetDefaultCookieFile()); + if (cookieFile.Trim() == "0") + cookieFile = null; + if (explorer != null) + { + ExplorerFactories.Add(net.CryptoCode, (n) => CreateExplorerClient(n, explorer, cookieFile)); + } } } + var invalidChains = String.Join(',', supportedChains.Where(s => !validChains.Contains(s)).ToArray()); + if(!string.IsNullOrEmpty(invalidChains)) + throw new ConfigException($"Invalid chains {invalidChains}"); - // Handle legacy explorer.url and explorer.cookiefile - if (!btcHandled) - { - var nbxplorer = NBXplorer.Configuration.NetworkInformation.GetNetworkByName(Network.Name); // Will get BTC info - var explorer = conf.GetOrDefault($"explorer.url", new Uri(nbxplorer.GetDefaultExplorerUrl(), UriKind.Absolute)); - var cookieFile = conf.GetOrDefault($"explorer.cookiefile", nbxplorer.GetDefaultCookieFile()); - ExplorerFactories.Add("BTC", (n) => CreateExplorerClient(n, explorer, cookieFile)); - } - ////// - + Logs.Configuration.LogInformation("Supported chains: " + String.Join(';', supportedChains.ToArray())); PostgresConnectionString = conf.GetOrDefault("postgres", null); ExternalUrl = conf.GetOrDefault("externalurl", null); } @@ -79,7 +73,7 @@ namespace BTCPayServer.Configuration private static ExplorerClient CreateExplorerClient(BTCPayNetwork n, Uri uri, string cookieFile) { var explorer = new ExplorerClient(n.NBitcoinNetwork, uri); - if (!explorer.SetCookieAuth(cookieFile)) + if (cookieFile == null || !explorer.SetCookieAuth(cookieFile)) explorer.SetNoAuth(); return explorer; } diff --git a/BTCPayServer/Configuration/DefaultConfiguration.cs b/BTCPayServer/Configuration/DefaultConfiguration.cs index 1dfec91b3..1aefd32ae 100644 --- a/BTCPayServer/Configuration/DefaultConfiguration.cs +++ b/BTCPayServer/Configuration/DefaultConfiguration.cs @@ -17,20 +17,23 @@ namespace BTCPayServer.Configuration { protected override CommandLineApplication CreateCommandLineApplicationCore() { + var provider = new BTCPayNetworkProvider(ChainType.Main); + var chains = string.Join(",", provider.GetAll().Select(n=>n.CryptoCode.ToLowerInvariant()).ToArray()); CommandLineApplication app = new CommandLineApplication(true) { FullName = "BTCPay\r\nOpen source, self-hosted payment processor.", Name = "BTCPay" }; app.HelpOption("-? | -h | --help"); - app.Option("-n | --network", $"Set the network among ({NetworkInformation.ToStringAll()}) (default: {Network.Main.ToString()})", CommandOptionType.SingleValue); - app.Option("--testnet | -testnet", $"Use testnet", CommandOptionType.BoolValue); - app.Option("--regtest | -regtest", $"Use regtest", CommandOptionType.BoolValue); + app.Option("-n | --network", $"Set the network among (mainnet,testnet,regtest) (default: mainnet)", CommandOptionType.SingleValue); + app.Option("--testnet | -testnet", $"Use testnet (Deprecated, use --network instead)", CommandOptionType.BoolValue); + app.Option("--regtest | -regtest", $"Use regtest (Deprecated, use --network instead)", CommandOptionType.BoolValue); + app.Option("--chains | -c", $"Chains to support comma separated (default: btc, available: {chains})", CommandOptionType.SingleValue); app.Option("--postgres", $"Connection string to postgres database (default: sqlite is used)", CommandOptionType.SingleValue); - foreach (var network in new BTCPayNetworkProvider(Network.Main).GetAll()) + foreach (var network in provider.GetAll()) { - app.Option($"--{network.CryptoCode}explorerurl", $"Url of the NBxplorer for {network.CryptoCode} (default: If no explorer is specified, the default for Bitcoin will be selected)", CommandOptionType.SingleValue); - app.Option($"--{network.CryptoCode}explorercookiefile", $"Path to the cookie file (default: Default setting of NBXplorer for the network)", CommandOptionType.SingleValue); + app.Option($"--{network.CryptoCode}explorerurl", $"Url of the NBxplorer for {network.CryptoCode} (default: {network.NBXplorerNetwork.GetDefaultExplorerUrl()})", CommandOptionType.SingleValue); + app.Option($"--{network.CryptoCode}explorercookiefile", $"Path to the cookie file (default: {network.NBXplorerNetwork.GetDefaultCookieFile()})", CommandOptionType.SingleValue); } app.Option("--externalurl", $"The expected external url of this service, to use if BTCPay is behind a reverse proxy (default: empty, use the incoming HTTP request to figure out)", CommandOptionType.SingleValue); return app; @@ -40,12 +43,12 @@ namespace BTCPayServer.Configuration protected override string GetDefaultDataDir(IConfiguration conf) { - return GetNetwork(conf).DefaultDataDirectory; + return BTCPayDefaultSettings.GetDefaultSettings(GetChainType(conf)).DefaultDataDirectory; } protected override string GetDefaultConfigurationFile(IConfiguration conf) { - var network = GetNetwork(conf); + var network = BTCPayDefaultSettings.GetDefaultSettings(GetChainType(conf)); var dataDir = conf["datadir"]; if (dataDir == null) return network.DefaultConfigurationFile; @@ -53,44 +56,44 @@ namespace BTCPayServer.Configuration return Path.Combine(dataDir, fileName); } - public static NetworkInformation GetNetwork(IConfiguration conf) + public static ChainType GetChainType(IConfiguration conf) { var network = conf.GetOrDefault("network", null); if (network != null) { - var info = NetworkInformation.GetNetworkByName(network); - if (info == null) - throw new ConfigException($"Invalid network name {network}"); - return info; + var n = Network.GetNetwork(network); + if (n == Network.Main) + return ChainType.Main; + if (n == Network.TestNet) + return ChainType.Test; + if (n == Network.RegTest) + return ChainType.Regtest; } + var net = conf.GetOrDefault("regtest", false) ? ChainType.Regtest: + conf.GetOrDefault("testnet", false) ? ChainType.Test : ChainType.Main; - var net = conf.GetOrDefault("regtest", false) ? Network.RegTest : - conf.GetOrDefault("testnet", false) ? Network.TestNet : Network.Main; - - return NetworkInformation.GetNetworkByName(net.Name); + return net; } protected override string GetDefaultConfigurationFileTemplate(IConfiguration conf) { - var network = GetNetwork(conf); + var defaultSettings = BTCPayDefaultSettings.GetDefaultSettings(GetChainType(conf)); StringBuilder builder = new StringBuilder(); builder.AppendLine("### Global settings ###"); - builder.AppendLine("#testnet=0"); - builder.AppendLine("#regtest=0"); + builder.AppendLine("#network=mainnet"); builder.AppendLine(); builder.AppendLine("### Server settings ###"); - builder.AppendLine("#port=" + network.DefaultPort); + builder.AppendLine("#port=" + defaultSettings.DefaultPort); builder.AppendLine("#bind=127.0.0.1"); builder.AppendLine(); builder.AppendLine("### Database ###"); builder.AppendLine("#postgres=User ID=root;Password=myPassword;Host=localhost;Port=5432;Database=myDataBase;"); builder.AppendLine(); builder.AppendLine("### NBXplorer settings ###"); - foreach (var n in new BTCPayNetworkProvider(network.Network).GetAll()) + foreach (var n in new BTCPayNetworkProvider(defaultSettings.ChainType).GetAll()) { - var nbxplorer = NBXplorer.Configuration.NetworkInformation.GetNetworkByName(n.NBitcoinNetwork.ToString()); - builder.AppendLine($"#{n.CryptoCode}.explorer.url={nbxplorer.GetDefaultExplorerUrl()}"); - builder.AppendLine($"#{n.CryptoCode}.explorer.cookiefile={ nbxplorer.GetDefaultCookieFile()}"); + builder.AppendLine($"#{n.CryptoCode}.explorer.url={n.NBXplorerNetwork.GetDefaultExplorerUrl()}"); + builder.AppendLine($"#{n.CryptoCode}.explorer.cookiefile={ n.NBXplorerNetwork.GetDefaultCookieFile()}"); } return builder.ToString(); } @@ -99,7 +102,7 @@ namespace BTCPayServer.Configuration protected override IPEndPoint GetDefaultEndpoint(IConfiguration conf) { - return new IPEndPoint(IPAddress.Parse("127.0.0.1"), GetNetwork(conf).DefaultPort); + return new IPEndPoint(IPAddress.Parse("127.0.0.1"), BTCPayDefaultSettings.GetDefaultSettings(GetChainType(conf)).DefaultPort); } } } diff --git a/BTCPayServer/Configuration/NetworkInformation.cs b/BTCPayServer/Configuration/NetworkInformation.cs deleted file mode 100644 index 8f99a3912..000000000 --- a/BTCPayServer/Configuration/NetworkInformation.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Microsoft.Extensions.Configuration; -using NBitcoin; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; - -namespace BTCPayServer.Configuration -{ - public class NetworkInformation - { - static NetworkInformation() - { - _Networks = new Dictionary(); - foreach (var network in new[] { Network.Main, Network.TestNet, Network.RegTest }) - { - NetworkInformation info = new NetworkInformation(); - info.DefaultDataDirectory = StandardConfiguration.DefaultDataDirectory.GetDirectory("BTCPayServer", network.Name); - info.DefaultConfigurationFile = Path.Combine(info.DefaultDataDirectory, "settings.config"); - info.Network = network; - info.DefaultPort = 23002; - _Networks.Add(network.Name, info); - if (network == Network.Main) - { - info.DefaultPort = 23000; - } - if (network == Network.TestNet) - { - info.DefaultPort = 23001; - } - } - } - - static Dictionary _Networks; - public static NetworkInformation GetNetworkByName(string name) - { - var value = _Networks.TryGet(name); - if (value != null) - return value; - - //Maybe alias ? - var network = Network.GetNetwork(name); - if (network != null) - { - value = _Networks.TryGet(network.Name); - if (value != null) - return value; - } - return null; - } - - public Network Network - { - get; set; - } - public string DefaultConfigurationFile - { - get; - set; - } - public string DefaultDataDirectory - { - get; - set; - } - public int DefaultPort - { - get; - private set; - } - - public override string ToString() - { - return Network.ToString(); - } - - public static string ToStringAll() - { - return string.Join(", ", _Networks.Select(n => n.Key).ToArray()); - } - } -} diff --git a/BTCPayServer/Controllers/InvoiceController.PaymentProtocol.cs b/BTCPayServer/Controllers/InvoiceController.PaymentProtocol.cs index a5e0ad0ce..f084c9a13 100644 --- a/BTCPayServer/Controllers/InvoiceController.PaymentProtocol.cs +++ b/BTCPayServer/Controllers/InvoiceController.PaymentProtocol.cs @@ -77,7 +77,7 @@ namespace BTCPayServer.Controllers return NotFound(); var payment = PaymentMessage.Load(Request.Body); var unused = wallet.BroadcastTransactionsAsync(payment.Transactions); - await _InvoiceRepository.AddRefundsAsync(invoiceId, payment.RefundTo.Select(p => new TxOut(p.Amount, p.Script)).ToArray()); + await _InvoiceRepository.AddRefundsAsync(invoiceId, payment.RefundTo.Select(p => new TxOut(p.Amount, p.Script)).ToArray(), network.NBitcoinNetwork); return new PaymentAckActionResult(payment.CreateACK(invoiceId + " is currently processing, thanks for your purchase...")); } } diff --git a/BTCPayServer/Hosting/BTCPayServerServices.cs b/BTCPayServer/Hosting/BTCPayServerServices.cs index 698ca93f9..7ea398465 100644 --- a/BTCPayServer/Hosting/BTCPayServerServices.cs +++ b/BTCPayServer/Hosting/BTCPayServerServices.cs @@ -103,7 +103,7 @@ namespace BTCPayServer.Hosting var dbpath = Path.Combine(opts.DataDir, "InvoiceDB"); if (!Directory.Exists(dbpath)) Directory.CreateDirectory(dbpath); - return new InvoiceRepository(dbContext, dbpath, opts.Network); + return new InvoiceRepository(dbContext, dbpath); }); services.AddSingleton(); services.TryAddSingleton(); @@ -129,7 +129,7 @@ namespace BTCPayServer.Hosting services.TryAddSingleton(o => { var opts = o.GetRequiredService(); - return new BTCPayNetworkProvider(opts.Network); + return new BTCPayNetworkProvider(opts.ChainType); }); services.TryAddSingleton(); @@ -152,7 +152,7 @@ namespace BTCPayServer.Hosting services.TryAddSingleton(); services.TryAddSingleton(o => { - if (o.GetRequiredService().Network == Network.Main) + if (o.GetRequiredService().ChainType == ChainType.Main) return new Bitpay(new Key(), new Uri("https://bitpay.com/")); else return new Bitpay(new Key(), new Uri("https://test.bitpay.com/")); diff --git a/BTCPayServer/Services/Invoices/InvoiceRepository.cs b/BTCPayServer/Services/Invoices/InvoiceRepository.cs index 917e237d0..57b2b8f4a 100644 --- a/BTCPayServer/Services/Invoices/InvoiceRepository.cs +++ b/BTCPayServer/Services/Invoices/InvoiceRepository.cs @@ -32,27 +32,12 @@ namespace BTCPayServer.Services.Invoices } } - - Network _Network; - public Network Network - { - get - { - return _Network; - } - set - { - _Network = value; - } - } - private ApplicationDbContextFactory _ContextFactory; private CustomThreadPool _IndexerThread; - public InvoiceRepository(ApplicationDbContextFactory contextFactory, string dbreezePath, Network network) + public InvoiceRepository(ApplicationDbContextFactory contextFactory, string dbreezePath) { _Engine = new DBreezeEngine(dbreezePath); _IndexerThread = new CustomThreadPool(1, "Invoice Indexer"); - _Network = network; _ContextFactory = contextFactory; } @@ -105,7 +90,7 @@ namespace BTCPayServer.Services.Invoices public async Task CreateInvoiceAsync(string storeId, InvoiceEntity invoice, BTCPayNetworkProvider networkProvider) { List textSearch = new List(); - invoice = Clone(invoice); + invoice = Clone(invoice, null); invoice.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); #pragma warning disable CS0618 invoice.Payments = new List(); @@ -118,7 +103,7 @@ namespace BTCPayServer.Services.Invoices StoreDataId = storeId, Id = invoice.Id, Created = invoice.InvoiceTime, - Blob = ToBytes(invoice), + Blob = ToBytes(invoice, null), OrderId = invoice.OrderId, Status = invoice.Status, ItemCode = invoice.ProductInformation.ItemCode, @@ -150,8 +135,8 @@ namespace BTCPayServer.Services.Invoices textSearch.Add(invoice.InvoiceTime.ToString(CultureInfo.InvariantCulture)); textSearch.Add(invoice.ProductInformation.Price.ToString(CultureInfo.InvariantCulture)); textSearch.Add(invoice.OrderId); - textSearch.Add(ToString(invoice.BuyerInformation)); - textSearch.Add(ToString(invoice.ProductInformation)); + textSearch.Add(ToString(invoice.BuyerInformation, null)); + textSearch.Add(ToString(invoice.ProductInformation, null)); textSearch.Add(invoice.StoreId); AddToTextSearch(invoice.Id, textSearch.ToArray()); @@ -167,7 +152,7 @@ namespace BTCPayServer.Services.Invoices if (invoice == null) return false; - var invoiceEntity = ToObject(invoice.Blob); + var invoiceEntity = ToObject(invoice.Blob, network.NBitcoinNetwork); var currencyData = invoiceEntity.GetCryptoData(network, null); if (currencyData == null) return false; @@ -186,7 +171,7 @@ namespace BTCPayServer.Services.Invoices } #pragma warning restore CS0618 invoiceEntity.SetCryptoData(currencyData); - invoice.Blob = ToBytes(invoiceEntity); + invoice.Blob = ToBytes(invoiceEntity, network.NBitcoinNetwork); context.AddressInvoices.Add(new AddressInvoiceData() { InvoiceDataId = invoiceId, CreatedTime = DateTimeOffset.UtcNow } @@ -225,7 +210,7 @@ namespace BTCPayServer.Services.Invoices var invoiceData = await context.FindAsync(invoiceId).ConfigureAwait(false); if (invoiceData == null) return; - var invoiceEntity = ToObject(invoiceData.Blob); + var invoiceEntity = ToObject(invoiceData.Blob, null); MarkUnassigned(invoiceId, invoiceEntity, context, null); try { @@ -308,11 +293,11 @@ namespace BTCPayServer.Services.Invoices private InvoiceEntity ToEntity(InvoiceData invoice) { - var entity = ToObject(invoice.Blob); + var entity = ToObject(invoice.Blob, null); #pragma warning disable CS0618 entity.Payments = invoice.Payments.Select(p => { - var paymentEntity = ToObject(p.Blob); + var paymentEntity = ToObject(p.Blob, null); paymentEntity.Accounted = p.Accounted; return paymentEntity; }).ToList(); @@ -396,7 +381,7 @@ namespace BTCPayServer.Services.Invoices } - public async Task AddRefundsAsync(string invoiceId, TxOut[] outputs) + public async Task AddRefundsAsync(string invoiceId, TxOut[] outputs, Network network) { if (outputs.Length == 0) return; @@ -410,14 +395,14 @@ namespace BTCPayServer.Services.Invoices { Id = invoiceId + "-" + i, InvoiceDataId = invoiceId, - Blob = ToBytes(output) + Blob = ToBytes(output, network) }); i++; } await context.SaveChangesAsync().ConfigureAwait(false); } - var addresses = outputs.Select(o => o.ScriptPubKey.GetDestinationAddress(_Network)).Where(a => a != null).ToArray(); + var addresses = outputs.Select(o => o.ScriptPubKey.GetDestinationAddress(network)).Where(a => a != null).ToArray(); AddToTextSearch(invoiceId, addresses.Select(a => a.ToString()).ToArray()); } @@ -438,7 +423,7 @@ namespace BTCPayServer.Services.Invoices PaymentData data = new PaymentData { Id = receivedCoin.Outpoint.ToString(), - Blob = ToBytes(entity), + Blob = ToBytes(entity, null), InvoiceDataId = invoiceId }; @@ -468,24 +453,24 @@ namespace BTCPayServer.Services.Invoices } } - private T ToObject(byte[] value) + private T ToObject(byte[] value, Network network) { - return NBitcoin.JsonConverters.Serializer.ToObject(ZipUtils.Unzip(value), Network); + return NBitcoin.JsonConverters.Serializer.ToObject(ZipUtils.Unzip(value), network); } - private byte[] ToBytes(T obj) + private byte[] ToBytes(T obj, Network network) { - return ZipUtils.Zip(NBitcoin.JsonConverters.Serializer.ToString(obj)); + return ZipUtils.Zip(NBitcoin.JsonConverters.Serializer.ToString(obj, network)); } - private T Clone(T invoice) + private T Clone(T invoice, Network network) { - return NBitcoin.JsonConverters.Serializer.ToObject(ToString(invoice), Network); + return NBitcoin.JsonConverters.Serializer.ToObject(ToString(invoice, network), network); } - private string ToString(T data) + private string ToString(T data, Network network) { - return NBitcoin.JsonConverters.Serializer.ToString(data, Network); + return NBitcoin.JsonConverters.Serializer.ToString(data, network); } public void Dispose()