public ServerTester(string scope) { _Directory = scope; if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } NetworkProvider = new BTCPayNetworkProvider(NetworkType.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBitcoinNetwork); ExplorerNode.ScanRPCCapabilities(); ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, TestDatabase = Enum.Parse <TestDatabases>(GetEnvironment("TESTS_DB", TestDatabases.Postgres.ToString()), true), Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver"), MySQL = GetEnvironment("TESTS_MYSQL", "User ID=root;Host=127.0.0.1;Port=33036;Database=btcpayserver") }; PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.InContainer = bool.Parse(GetEnvironment("TESTS_INCONTAINER", "false")); PayTester.SSHPassword = GetEnvironment("TESTS_SSHPASSWORD", "opD3i2282D"); PayTester.SSHKeyFile = GetEnvironment("TESTS_SSHKEYFILE", ""); PayTester.SSHConnection = GetEnvironment("TESTS_SSHCONNECTION", "[email protected]:21622"); }
public void Start() { if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_RPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), Network); ExplorerClient = new ExplorerClient(Network, new Uri(GetEnvironment("TESTS_NBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver") }; PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString())); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.Start(); MerchantEclair = new EclairTester(this, "TEST_ECLAIR1", "http://127.0.0.1:30992/", "eclair1"); CustomerEclair = new EclairTester(this, "TEST_ECLAIR2", "http://127.0.0.1:30993/", "eclair2"); }
protected RpcClientTesting(NodeConfigParameters?config = null) { this.nodeBuilder = NodeBuilderFactory.CreateNodeBuilder(GetType()); try { this.nodeBuilder.ConfigParameters.Add("dandelion", "0"); this.nodeBuilder.ConfigParameters.Add("elysium", "1"); if (config != null) { this.nodeBuilder.ConfigParameters.Import(config, true); } this.Node = this.nodeBuilder.CreateNode(true); this.Client = this.Node.CreateRPCClient(); this.Factory = new RpcClientFactory( this.nodeBuilder.Network, this.Node.RPCUri, RPCCredentialString.Parse(this.Node.GetRPCAuth()), new TransactionSerializer(ElysiumSerializers)); this.subject = new Lazy <T>(CreateSubject); } catch { this.nodeBuilder.Dispose(); throw; } }
public void Start() { if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } NetworkProvider = new BTCPayNetworkProvider(ChainType.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "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(NetworkProvider.GetNetwork("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); LTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork("LTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, LTCNBXplorerUri = LTCExplorerClient.Address, Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver") }; PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.Start(); var btc = NetworkProvider.GetNetwork("BTC").NBitcoinNetwork; CustomerEclair = new EclairTester(this, "TEST_ECLAIR", "http://*****:*****@127.0.0.1:30992/", "eclair", btc); MerchantCharge = new ChargeTester(this, "TEST_CHARGE", "http://*****:*****@127.0.0.1:54938/", "lightning-charged", btc); }
public void ActivateLBTC() { LBTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LBTCRPCCONNECTION", "server=http://127.0.0.1:19332;liquid:liquid")), NetworkProvider.GetNetwork <BTCPayNetwork>("LBTC").NBitcoinNetwork); LBTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork <BTCPayNetwork>("LBTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LBTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester.Chains.Add("LBTC"); PayTester.LBTCNBXplorerUri = LBTCExplorerClient.Address; }
protected RpcClientTesting() { this.nodes = NodeBuilderFactory.CreateNodeBuilder(GetType()); try { this.nodes.ConfigParameters.Add("autocommit", "0"); this.nodes.ConfigParameters.Add("dandelion", "0"); this.nodes.ConfigParameters.Add("exodus", "1"); Node = this.nodes.CreateNode(true); Client = Node.CreateRPCClient(); Factory = new RpcFactory( this.nodes.Network, Node.RPCUri, RPCCredentialString.Parse(Node.GetRPCAuth()), new TransactionEncoder(ExodusEncoders) ); this.subject = new Lazy <RpcClient>(CreateSubject, LazyThreadSafetyMode.ExecutionAndPublication); // lgtm[cs/virtual-call-in-constructor] } catch { this.nodes.Dispose(); throw; } }
public void CanUseMultipleWallets() { using (var builder = NodeBuilder.Create(version: "0.15.0")) { var node = builder.CreateNode(); node.ConfigParameters.Add("wallet", "w1"); //node.ConfigParameters.Add("wallet", "w2"); node.Start(); var rpc = node.CreateRPCClient(); var creds = RPCCredentialString.Parse(rpc.CredentialString.ToString()); creds.Server = rpc.Address.AbsoluteUri; creds.WalletName = "w1"; rpc = new RPCClient(creds, Network.RegTest); rpc.SendCommandAsync(RPCOperations.getwalletinfo).GetAwaiter().GetResult().ThrowIfError(); Assert.NotNull(rpc.GetBalance()); Assert.NotNull(rpc.GetBestBlockHash()); var block = rpc.GetBlock(rpc.Generate(1)[0]); rpc = rpc.PrepareBatch(); var b = rpc.GetBalanceAsync(); var b2 = rpc.GetBestBlockHashAsync(); var a = rpc.SendCommandAsync("gettransaction", block.Transactions.First().GetHash().ToString()); rpc.SendBatch(); b.GetAwaiter().GetResult(); b2.GetAwaiter().GetResult(); a.GetAwaiter().GetResult(); } }
public void CanParseRpcCredentialString() { Assert.True(RPCCredentialString.Parse("default").UseDefault); Assert.Equal("c:/", RPCCredentialString.Parse("cookiefile=c:/").CookieFile); Assert.Equal("abc", RPCCredentialString.Parse("abc:def").UserPassword.UserName); Assert.Equal("def", RPCCredentialString.Parse("abc:def").UserPassword.Password); Assert.Equal("def:def", RPCCredentialString.Parse("abc:def:def").UserPassword.Password); Assert.Equal("abc:def", RPCCredentialString.Parse("abc:def").ToString()); Assert.Equal("server=toto:3030;abc:def", RPCCredentialString.Parse("server=toto:3030;abc:def").ToString()); }
static IRpcFactory CreateRpcFactory(IServiceProvider provider) { var config = provider.GetRequiredService <IConfiguration>().GetZcoinSection(); return(new RpcFactory( provider.GetRequiredService <Network>(), config.Rpc.Address, RPCCredentialString.Parse($"{config.Rpc.UserName}:{config.Rpc.Password}"), provider.GetRequiredService <ITransactionEncoder>())); }
public RPCClient ConfigureRPCClient(Network network) { RPCClient rpcClient = null; var url = Url; var usr = User; var pass = Password; if (url != null && usr != null && pass != null) { rpcClient = new RPCClient(new System.Net.NetworkCredential(usr, pass), url, network); } if (rpcClient == null) { if (url != null && CookieFile != null) { try { rpcClient = new RPCClient(new RPCCredentialString() { CookieFile = CookieFile }, url, network); } catch (IOException) { Logs.Configuration.LogWarning("RPC Cookie file not found at " + CookieFile); } } if (AuthenticationString != null) { rpcClient = new RPCClient(RPCCredentialString.Parse(AuthenticationString), url, network); } if (rpcClient == null) { try { rpcClient = new RPCClient(null as NetworkCredential, url, network); } catch { } if (rpcClient == null) { Logs.Configuration.LogError("RPC connection settings not configured"); throw new ConfigException(); } } } if (NoTest) { return(rpcClient); } TestRPCAsync(network, rpcClient).GetAwaiter().GetResult(); return(rpcClient); }
public RPCClient ConfigureRPCClient(NBXplorerNetwork networkInformation) { var network = networkInformation.NBitcoinNetwork; RPCClient rpcClient = null; var url = Url; var usr = User; var pass = Password; if (url != null && usr != null && pass != null) { rpcClient = new RPCClient(new System.Net.NetworkCredential(usr, pass), url, network); } if (rpcClient == null) { if (CookieFile != null) { try { rpcClient = new RPCClient(new RPCCredentialString() { CookieFile = CookieFile }, url, network); } catch (IOException) { Logs.Configuration.LogWarning($"{networkInformation.CryptoCode}: RPC Cookie file not found at " + (CookieFile ?? RPCClient.GetDefaultCookieFilePath(network))); } } if (AuthenticationString != null) { rpcClient = new RPCClient(RPCCredentialString.Parse(AuthenticationString), url, network); } if (rpcClient == null) { try { rpcClient = new RPCClient(null as NetworkCredential, url, network); } catch { } if (rpcClient == null) { Logs.Configuration.LogError($"{networkInformation.CryptoCode}: RPC connection settings not configured"); throw new ConfigException(); } } } // 10 min of timeout because scantxoutset can take long rpcClient.RequestTimeout = TimeSpan.FromMinutes(10.0); return(rpcClient); }
internal RPCClient ConfigureRPCClient(NRustLightningNetwork nRustLightningNetwork, ILogger logger) { var n = nRustLightningNetwork.NBitcoinNetwork; RPCClient rpcClient = null; if (Url != null && User != null && Password != null) { rpcClient = new RPCClient(new NetworkCredential(User, Password), Url, n); } if (rpcClient is null) { if (CookieFile != null) { try { rpcClient = new RPCClient(new RPCCredentialString { CookieFile = CookieFile }, Url, n); } catch (IOException) { logger.LogWarning($"{nRustLightningNetwork.CryptoCode}: RPC Cookie file not found at " + (CookieFile ?? RPCClient.GetDefaultCookieFilePath(n))); } } if (AuthenticationString != null) { rpcClient = new RPCClient(RPCCredentialString.Parse(AuthenticationString), Url, n); } if (rpcClient is null) { try { rpcClient = new RPCClient(null as NetworkCredential, Url, n); } catch { // ignored } if (rpcClient == null) { logger.LogError($"{nRustLightningNetwork.CryptoCode}: RPC connection settings not configured"); throw new ConfigException(); } } } return(rpcClient); }
public void ConfigureServices(IServiceCollection services) { // Application services. this.RegisterRuntimeConverters(); this.ConfigureApiOptions(services, this.Configuration.GetSection("Api")); services.AddHostedService <DatabaseMigrator>(); // Zsharp services. services.AddServiceExceptionHandler(); services.AddZcoin(Enum.Parse <NetworkType>(this.Configuration["Zcoin:Network"])); services.AddElysiumSerializer(); services.AddZcoinRpcClient(options => { var username = this.Configuration["Zcoin:Daemon:Rpc:Username"]; var password = this.Configuration["Zcoin:Daemon:Rpc:Password"]; options.ServerUrl = new Uri(this.Configuration["Zcoin:Daemon:Rpc:Address"]); options.Credential = RPCCredentialString.Parse($"{username}:{password}"); }); services.AddLightweightIndexer(options => { options.BlockPublisherAddress = this.Configuration["Zcoin:Daemon:ZeroMq:Address"]; }); services.AddLightweightIndexerEntityRepository(); services.AddLightweightIndexerPostgresDbContext(options => { options.ConnectionString = this.Configuration["Database:Blockchain:ConnectionString"]; }); // ASP.NET Core services. services.Configure <RouteOptions>(options => { options.ConstraintMap.Add("uint256", typeof(Constraints.UInt256)); }); services .AddControllers() .AddJsonOptions(options => { this.RegisterJsonConverters(options.JsonSerializerOptions.Converters); }) .ConfigureApiBehaviorOptions(options => { options.SuppressMapClientErrors = true; }); // Swashbuckle services. services.AddSwaggerGen(this.ConfigureSwaggerGenerator); }
public RPCClient ConfigureRPCClient(Network network) { RPCClient rpcClient = null; var url = Url; var usr = User; var pass = Password; if (url != null && usr != null && pass != null) { rpcClient = new RPCClient(new System.Net.NetworkCredential(usr, pass), url, network); } if (rpcClient == null) { if (CookieFile != null) { try { rpcClient = new RPCClient(new RPCCredentialString() { CookieFile = CookieFile }, url, network); } catch (IOException) { Common.Logging.CommonLogs.Configuration.LogWarning($"RPC Cookie file not found at " + (CookieFile ?? RPCClient.GetDefaultCookieFilePath(network))); } } if (AuthenticationString != null) { rpcClient = new RPCClient(RPCCredentialString.Parse(AuthenticationString), url, network); } if (rpcClient == null) { try { rpcClient = new RPCClient(null as NetworkCredential, url, network); } catch { } if (rpcClient == null) { Common.Logging.CommonLogs.Configuration.LogError($"RPC connection settings not configured"); throw new ConfigException(); } } } return(rpcClient); }
public void CanSendCommand() { using (var builder = NodeBuilder.Create()) { var rpc = builder.CreateNode().CreateRPCClient(); builder.StartAll(); var response = rpc.SendCommand(RPCOperations.getinfo); Assert.NotNull(response.Result); var copy = RPCCredentialString.Parse(rpc.CredentialString.ToString()); copy.Server = rpc.Address.AbsoluteUri; rpc = new RPCClient(copy, null as string, Network.RegTest); response = rpc.SendCommand(RPCOperations.getinfo); Assert.NotNull(response.Result); } }
public ServerTester(string scope) { _Directory = scope; if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } NetworkProvider = new BTCPayNetworkProvider(NetworkType.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBitcoinNetwork); ExplorerNode.ScanRPCCapabilities(); LTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LTCRPCCONNECTION", "server=http://127.0.0.1:43783;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork <BTCPayNetwork>("LTC").NBitcoinNetwork); ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); LTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork <BTCPayNetwork>("LTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32838/"))); var btc = NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBitcoinNetwork; CustomerLightningD = LightningClientFactory.CreateClient(GetEnvironment("TEST_CUSTOMERLIGHTNINGD", "type=clightning;server=tcp://127.0.0.1:30992/"), btc); MerchantLightningD = LightningClientFactory.CreateClient(GetEnvironment("TEST_MERCHANTLIGHTNINGD", "type=clightning;server=tcp://127.0.0.1:30993/"), btc); MerchantCharge = new ChargeTester(this, "TEST_MERCHANTCHARGE", "type=charge;server=http://127.0.0.1:54938/;api-token=foiewnccewuify", "merchant_lightningd", btc); MerchantLnd = new LndMockTester(this, "TEST_MERCHANTLND", "https://*****:*****@127.0.0.1:53280/", "merchant_lnd", btc); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, LTCNBXplorerUri = LTCExplorerClient.Address, TestDatabase = Enum.Parse <TestDatabases>(GetEnvironment("TESTS_DB", TestDatabases.Postgres.ToString()), true), Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver"), MySQL = GetEnvironment("TESTS_MYSQL", "User ID=root;Host=127.0.0.1;Port=33036;Database=btcpayserver"), IntegratedLightning = MerchantCharge.Client.Uri }; PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.InContainer = bool.Parse(GetEnvironment("TESTS_INCONTAINER", "false")); PayTester.SSHPassword = GetEnvironment("TESTS_SSHPASSWORD", "opD3i2282D"); PayTester.SSHKeyFile = GetEnvironment("TESTS_SSHKEYFILE", ""); PayTester.SSHConnection = GetEnvironment("TESTS_SSHCONNECTION", "[email protected]:21622"); }
public ServerTester(string scope, bool newDb, ILog testLogs, ILoggerProvider loggerProvider) { LoggerProvider = loggerProvider; this.TestLogs = testLogs; _Directory = scope; if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } NetworkProvider = new BTCPayNetworkProvider(ChainName.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBitcoinNetwork); ExplorerNode.ScanRPCCapabilities(); ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork <BTCPayNetwork>("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester = new BTCPayServerTester(TestLogs, LoggerProvider, Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, TestDatabase = Enum.Parse <TestDatabases>(GetEnvironment("TESTS_DB", TestDatabases.Postgres.ToString()), true), // TODO: The fact that we use same conn string as development database can cause huge problems with tests // since in dev we already can have some users / stores registered, while on CI database is being initalized // for the first time and first registered user gets admin status by default Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Include Error Detail=true;Host=127.0.0.1;Port=39372;Database=btcpayserver"), ExplorerPostgres = GetEnvironment("TESTS_EXPLORER_POSTGRES", "User ID=postgres;Include Error Detail=true;Host=127.0.0.1;Port=39372;Database=nbxplorer"), MySQL = GetEnvironment("TESTS_MYSQL", "User ID=root;Host=127.0.0.1;Port=33036;Database=btcpayserver") }; if (newDb) { var r = RandomUtils.GetUInt32(); PayTester.Postgres = PayTester.Postgres.Replace("btcpayserver", $"btcpayserver{r}"); PayTester.MySQL = PayTester.MySQL.Replace("btcpayserver", $"btcpayserver{r}"); } PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.InContainer = bool.Parse(GetEnvironment("TESTS_INCONTAINER", "false")); PayTester.SSHPassword = GetEnvironment("TESTS_SSHPASSWORD", "opD3i2282D"); PayTester.SSHKeyFile = GetEnvironment("TESTS_SSHKEYFILE", ""); PayTester.SSHConnection = GetEnvironment("TESTS_SSHCONNECTION", "[email protected]:21622"); PayTester.SocksEndpoint = GetEnvironment("TESTS_SOCKSENDPOINT", "localhost:9050"); }
public async Task ExecuteAsync(CancellationToken cancellationToken) { Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); Logger.LogStarting("Wasabi Backend"); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <Config>("Config is successfully initialized."); var roundConfigFilePath = Path.Combine(Global.DataDir, "CcjRoundConfig.json"); var roundConfig = new CcjRoundConfig(roundConfigFilePath); await roundConfig.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <CcjRoundConfig>("RoundConfig is successfully initialized."); var rpc = new RPCClient( credentials: RPCCredentialString.Parse(config.BitcoinRpcConnectionString), network: config.Network); await Global.InitializeAsync(config, roundConfig, rpc); try { Directory.CreateDirectory(UnversionedWebBuilder.UnversionedFolder); UnversionedWebBuilder.CreateDownloadTextWithVersionHtml(); UnversionedWebBuilder.CloneAndUpdateOnionIndexHtml(); if (File.Exists(Global.Coordinator.CoinJoinsFilePath)) { string[] allLines = File.ReadAllLines(Global.Coordinator.CoinJoinsFilePath); Last5CoinJoins = allLines.TakeLast(5).Reverse().ToList(); UnversionedWebBuilder.UpdateCoinJoinsHtml(Last5CoinJoins); } Global.Coordinator.CoinJoinBroadcasted += Coordinator_CoinJoinBroadcasted; } catch (Exception ex) { Logger.LogWarning(ex, nameof(Program)); } }
public RpcFactoryTests() { this.nodes = NodeBuilderFactory.CreateNodeBuilder(GetType()); try { var node = this.nodes.CreateNode(true); this.network = node.Network; this.server = node.RPCUri; this.credential = RPCCredentialString.Parse(node.GetRPCAuth()); this.exodusEncoder = new Mock <ITransactionEncoder>(); this.subject = new RpcFactory(this.network, this.server, this.credential, this.exodusEncoder.Object); } catch { this.nodes.Dispose(); throw; } }
public void Start() { if (Directory.Exists(_Directory)) { Utils.DeleteDirectory(_Directory); } if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } NetworkProvider = new BTCPayNetworkProvider(ChainType.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "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(NetworkProvider.GetNetwork("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); LTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork("LTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32838/"))); var btc = NetworkProvider.GetNetwork("BTC").NBitcoinNetwork; CustomerLightningD = new CLightningRPCClient(new Uri(GetEnvironment("TEST_CUSTOMERLIGHTNINGD", "tcp://127.0.0.1:30992/")), btc); MerchantLightningD = new CLightningRPCClient(new Uri(GetEnvironment("TEST_MERCHANTLIGHTNINGD", "tcp://127.0.0.1:30993/")), btc); MerchantCharge = new ChargeTester(this, "TEST_MERCHANTCHARGE", "http://*****:*****@127.0.0.1:54938/", "merchant_lightningd", btc); PayTester = new BTCPayServerTester(Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, LTCNBXplorerUri = LTCExplorerClient.Address, Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver"), IntegratedLightning = MerchantCharge.Client.Uri }; PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.InContainer = bool.Parse(GetEnvironment("TESTS_INCONTAINER", "false")); PayTester.Start(); }
#pragma warning disable IDE1006 // Naming Styles public static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { try { Logger.InitializeDefaults(Path.Combine(Global.Instance.DataDir, "Logs.txt")); Logger.LogStarting("Wasabi Backend"); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; var configFilePath = Path.Combine(Global.Instance.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <Config>("Config is successfully initialized."); var roundConfigFilePath = Path.Combine(Global.Instance.DataDir, "CcjRoundConfig.json"); var roundConfig = new CcjRoundConfig(roundConfigFilePath); await roundConfig.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <CcjRoundConfig>("RoundConfig is successfully initialized."); var rpc = new RPCClient( credentials: RPCCredentialString.Parse(config.BitcoinRpcConnectionString), network: config.Network); await Global.Instance.InitializeAsync(config, roundConfig, rpc); try { Directory.CreateDirectory(UnversionedWebBuilder.UnversionedFolder); UnversionedWebBuilder.CreateDownloadTextWithVersionHtml(); UnversionedWebBuilder.CloneAndUpdateOnionIndexHtml(); if (File.Exists(Global.Instance.Coordinator.CoinJoinsFilePath)) { string[] allLines = File.ReadAllLines(Global.Instance.Coordinator.CoinJoinsFilePath); Last5CoinJoins = allLines.TakeLast(5).Reverse().ToList(); UnversionedWebBuilder.UpdateCoinJoinsHtml(Last5CoinJoins); } Global.Instance.Coordinator.CoinJoinBroadcasted += Coordinator_CoinJoinBroadcasted; } catch (Exception ex) { Logger.LogWarning(ex, nameof(Program)); } var endPoint = "http://localhost:37127/"; using (var host = WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseUrls(endPoint) .Build()) { await host.RunAsync(); } } catch (Exception ex) { Logger.LogCritical <Program>(ex); } // Note: Don't do finally here. Dispose in Startup.cs. }
public RPCClient ConfigureRPCClient(Network network) { RPCClient rpcClient = null; var url = Url; var usr = User; var pass = Password; if (url != null && usr != null && pass != null) { rpcClient = new RPCClient(new System.Net.NetworkCredential(usr, pass), url, network); } if (rpcClient == null) { if (url != null && CookieFile != null) { try { rpcClient = new RPCClient(new RPCCredentialString() { CookieFile = CookieFile }, url, network); } catch (IOException) { Logs.Configuration.LogWarning("RPC Cookie file not found at " + CookieFile); } } if (AuthenticationString != null) { rpcClient = new RPCClient(RPCCredentialString.Parse(AuthenticationString), url, network); } if (rpcClient == null) { try { rpcClient = new RPCClient(null as NetworkCredential, url, network); } catch { } if (rpcClient == null) { Logs.Configuration.LogError("RPC connection settings not configured"); throw new ConfigException(); } } } Logs.Configuration.LogInformation("Testing RPC connection to " + rpcClient.Address.AbsoluteUri); try { var address = new Key().PubKey.GetAddress(network); var isValid = ((JObject)rpcClient.SendCommand("validateaddress", address.ToString()).Result)["isvalid"].Value <bool>(); if (!isValid) { Logs.Configuration.LogError("The RPC Server is on a different blockchain than the one configured for tumbling"); throw new ConfigException(); } } catch (ConfigException) { throw; } catch (RPCException ex) { Logs.Configuration.LogError("Invalid response from RPC server " + ex.Message); throw new ConfigException(); } catch (Exception ex) { Logs.Configuration.LogError("Error connecting to RPC server " + ex.Message); throw new ConfigException(); } Logs.Configuration.LogInformation("RPC connection successfull"); if (rpcClient.GetBlockHash(0) != network.GenesisHash) { Logs.Configuration.LogError("The RPC server is not using the chain " + network.Name); throw new ConfigException(); } var version = rpcClient.GetVersion(); if (version < MIN_CORE_VERSION) { Logs.Configuration.LogError($"The minimum Bitcoin Core version required is {MIN_CORE_VERSION} (detected: {version})"); throw new ConfigException(); } Logs.Configuration.LogInformation($"Bitcoin Core version detected: {version}"); return(rpcClient); }
private static void executeProcessing() { var uri = new Uri(_zonfig.BitcoindUri); var cred = RPCCredentialString.Parse(_zonfig.BitcoindCred); var rpcClient = new RPCClient(cred, uri, Network.Main); try { var checkConnection = rpcClient.GetBlockCount(); } catch (Exception ex) when( ex is HttpRequestException || (ex is AggregateException && ex.InnerException is HttpRequestException) ) { Console.WriteLine("Bitcoind not running on specified uri..."); return; } var blocks = rpcClient.GetBlockchainInfo(); if (blocks.Headers > blocks.Blocks) { Console.WriteLine("Bitcoind still syncing, please try again later..."); return; } var blocksFilePath = Directory.GetCurrentDirectory() + "\\.blocks"; if (File.Exists(blocksFilePath)) { var executedForBlocks = Convert.ToUInt64(File.ReadAllText(blocksFilePath)); if (executedForBlocks >= blocks.Blocks) { Console.WriteLine($"We already executed Fetched for block {executedForBlocks}"); return; } } // Fetch var resTxoutset = rpcClient.GetTxoutSetInfo(); var res = new TxoutSetInfo { bestblock = resTxoutset.Bestblock.ToString(), hash_serialized_2 = resTxoutset.HashSerialized2, height = resTxoutset.Height, total_amount = resTxoutset.TotalAmount.ToDecimal(MoneyUnit.BTC), transactions = resTxoutset.Transactions, txouts = resTxoutset.Txouts }; var strBody = JsonConvert.SerializeObject(res, Formatting.Indented); //var strBody = "{\"height\":570092,\"bestblock\":\"00000000000000000026960d36e9ffe255e4bde8656a843cea2f32612b1f4b12\",\"transactions\":28714080,\"txouts\":52713092,\"hash_serialized_2\":\"914d9ebf51eac4b5875e87dc2a8ebb0c17fa188dfe4984d3416b20d9a03578fa\",\"total_amount\":17625979.82662823}"; Console.WriteLine($"Sending to publisher:\n{strBody}"); if (_zonfig.PublisherUrl != null) { using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }; using (var client = new HttpClient(httpClientHandler)) { var resp = sendTxoutSetInfo(client, strBody); } } } File.WriteAllText(blocksFilePath, res.height.ToString()); }
public Cheater(BTCPayServerOptions opts, ApplicationDbContextFactory applicationDbContextFactory) { CashCow = new RPCClient(RPCCredentialString.Parse("server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3"), Bitcoin.Instance.GetNetwork(opts.NetworkType)); _applicationDbContextFactory = applicationDbContextFactory; }
#pragma warning disable IDE1006 // Naming Styles public static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { try { Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); Logger.LogStarting("Wasabi Backend"); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <Config>("Config is successfully initialized."); var roundConfigFilePath = Path.Combine(Global.DataDir, "CcjRoundConfig.json"); var roundConfig = new CcjRoundConfig(roundConfigFilePath); await roundConfig.LoadOrCreateDefaultFileAsync(); Logger.LogInfo <CcjRoundConfig>("RoundConfig is successfully initialized."); var rpc = new RPCClient( credentials: RPCCredentialString.Parse(config.BitcoinRpcConnectionString), network: config.Network); await Global.InitializeAsync(config, roundConfig, rpc); try { Directory.CreateDirectory(UnversionedWebBuilder.UnversionedFolder); UnversionedWebBuilder.CreateDownloadTextWithVersionHtml(); UnversionedWebBuilder.CloneAndUpdateOnionIndexHtml(); var getTxTasks = new List <Task <Transaction> >(); var batch = Global.RpcClient.PrepareBatch(); if (File.Exists(Global.Coordinator.CoinJoinsFilePath)) { string[] allLines = File.ReadAllLines(Global.Coordinator.CoinJoinsFilePath); foreach (string txId in allLines) { getTxTasks.Add(batch.GetRawTransactionAsync(uint256.Parse(txId))); } var waiting = Task.WhenAll(getTxTasks); await batch.SendBatchAsync(); await waiting; foreach (var task in getTxTasks) { try { var tx = await task; var volume = tx.GetIndistinguishableOutputs(includeSingle: false).Sum(x => x.count * x.value); TotalVolume += volume; } catch (Exception ex) { Logger.LogWarning(ex, nameof(Program)); } } UnversionedWebBuilder.UpdateMixedTextHtml(TotalVolume); Last5CoinJoins = allLines.TakeLast(5).Reverse().ToList(); UnversionedWebBuilder.UpdateCoinJoinsHtml(Last5CoinJoins); } Global.Coordinator.CoinJoinBroadcasted += Coordinator_CoinJoinBroadcasted; } catch (Exception ex) { Logger.LogWarning(ex, nameof(Program)); } var endPoint = "http://localhost:37127/"; using (var host = WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseUrls(endPoint) .Build()) { await host.RunAsync(); } } catch (Exception ex) { Logger.LogCritical <Program>(ex); } // Note: Don't do finally here. Dispose in Startup.cs. }
public ServerTester(string directory) { nodeDownloadData = bitcoinDownloadData; var networkString = "regtest"; try { var rootTestData = "TestData"; directory = Path.Combine(rootTestData, directory); _Directory = directory; if (!Directory.Exists(rootTestData)) { Directory.CreateDirectory(rootTestData); } NodeBuilder = CreateNodeBuilder(directory); User1 = NodeBuilder.CreateNode(); User2 = NodeBuilder.CreateNode(); Explorer = NodeBuilder.CreateNode(); foreach (var node in NodeBuilder.Nodes) { node.WhiteBind = true; } NodeBuilder.StartAll(); User1.CreateRPCClient().Generate(1); User1.Sync(Explorer, true); Explorer.CreateRPCClient().Generate(1); Explorer.Sync(User2, true); User2.CreateRPCClient().Generate(101); User1.Sync(User2, true); var creds = RPCCredentialString.Parse(Explorer.AuthenticationString).UserPassword; var datadir = Path.Combine(directory, "explorer"); DeleteRecursivelyWithMagicDust(datadir); List <(string key, string value)> keyValues = new List <(string key, string value)>(); keyValues.Add(("conf", Path.Combine(directory, "explorer", "settings.config"))); keyValues.Add(("datadir", datadir)); keyValues.Add(("network", networkString)); keyValues.Add(("verbose", "1")); keyValues.Add(("btcrpcuser", creds.UserName)); keyValues.Add(("btcrpcpassword", creds.Password)); keyValues.Add(("btcrpcurl", Explorer.CreateRPCClient().Address.AbsoluteUri)); keyValues.Add(("cachechain", "0")); keyValues.Add(("rpcnotest", "1")); keyValues.Add(("mingapsize", "2")); keyValues.Add(("maxgapsize", "4")); keyValues.Add(("btcstartheight", Explorer.CreateRPCClient().GetBlockCount().ToString())); keyValues.Add(("btcnodeendpoint", $"{Explorer.Endpoint.Address}:{Explorer.Endpoint.Port}")); var args = keyValues.SelectMany(kv => new[] { $"--{kv.key}", kv.value }).ToArray(); Host = new WebHostBuilder() .UseConfiguration(new DefaultConfiguration().CreateConfiguration(args)) .UseKestrel() .ConfigureLogging(l => { l.SetMinimumLevel(LogLevel.Information) .AddFilter("Microsoft", LogLevel.Error) .AddFilter("Hangfire", LogLevel.Error) .AddFilter("NBXplorer.Authentication.BasicAuthenticationHandler", LogLevel.Critical) .AddProvider(Logs.LogProvider); }) .UseStartup <Startup>() .Build(); string cryptoCode = "BTC"; RPC = ((RPCClientProvider)Host.Services.GetService(typeof(RPCClientProvider))).GetRPCClient(cryptoCode); var nbxnetwork = ((NBXplorerNetworkProvider)Host.Services.GetService(typeof(NBXplorerNetworkProvider))).GetFromCryptoCode(cryptoCode); Network = nbxnetwork.NBitcoinNetwork; var conf = (ExplorerConfiguration)Host.Services.GetService(typeof(ExplorerConfiguration)); Host.Start(); _Client = new ExplorerClient(nbxnetwork, Address); _Client.SetCookieAuth(Path.Combine(conf.DataDir, ".cookie")); } catch { Dispose(); throw; } }
// private void initializeEnvironment() { NetworkProvider = new BTCPayNetworkProvider(NetworkType.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork("BTC").NBitcoinNetwork); }