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() { 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; } }
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 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); } 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; }
public RpcFactory( Network network, Uri server, RPCCredentialString credential, ITransactionEncoder exodusEncoder) { if (network == null) { throw new ArgumentNullException(nameof(network)); } if (server == null) { throw new ArgumentNullException(nameof(server)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } if (exodusEncoder == null) { throw new ArgumentNullException(nameof(exodusEncoder)); } Network = network; this.serverUri = server; this.credential = credential; ExodusEncoder = exodusEncoder; GenesisTransactions = new HashSet <uint256>(Network.GetGenesis().Transactions.Select(t => t.GetHash())); }
static async Task Main(string[] args) { Logger.InitializeDefaults(); ParseArgs(args, out NetworkCredential rpcCred); var rpcConf = new RPCCredentialString { UserPassword = rpcCred }; var client = new RPCClient(rpcConf, Network.Main); using (BenchmarkLogger.Measure(operationName: "Parsing The Blockchain")) { var cjIndexer = new CoinJoinIndexer(client); var days = await cjIndexer.GetDailyStatsAsync(); foreach (var month in days.GroupBy(x => new DateTimeOffset(x.BlockTimeDay.Year, x.BlockTimeDay.Month, 1, 0, 0, 0, TimeSpan.Zero)).OrderBy(x => x.Key)) { Console.WriteLine($"{month.Key.Year}-{month.Key.Month}\tFresh bitcoins: {(int)Money.Satoshis(month.Sum(x => x.NonMixedInputSum)).ToDecimal(MoneyUnit.BTC)},\tNonremixed change: {(int)Money.Satoshis(month.Sum(x => x.NonRemixedChangeSum)).ToDecimal(MoneyUnit.BTC)}\t\tNonremixed <2 anons: {(int)Money.Satoshis(month.Sum(x => x.NonRemixed2AnonSum)).ToDecimal(MoneyUnit.BTC)}\t\tNonremixed <5 anons: {(int)Money.Satoshis(month.Sum(x => x.NonRemixed5AnonSum)).ToDecimal(MoneyUnit.BTC)}\t\tNonremixed <10 anons: {(int)Money.Satoshis(month.Sum(x => x.NonRemixed10AnonSum)).ToDecimal(MoneyUnit.BTC)}"); } await File.WriteAllLinesAsync("DailyStats.txt", days.Select(x => x.ToString())); } Console.WriteLine(); Console.WriteLine("Press a button to exit..."); Console.ReadKey(); }
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 async Task <IActionResult> Post([FromBody] OrderViewModel model) { try { if (ModelState.IsValid) { var newOrder = mapper.Map <OrderViewModel, Order>(model); if (newOrder.OrderDate == DateTime.MinValue) { newOrder.OrderDate = DateTime.Now; } var currentUser = await userManager.FindByNameAsync(User.Identity.Name); newOrder.User = currentUser; if (newOrder.BitcoinPrice == 0) { logger.LogError($"BtcPrice is not correctly set modelPrice: {model.BtcPrice} newOrderPrice: {newOrder.BitcoinPrice}"); throw new Exception($"BtcPrice is not correctly set modelPrice: {model.BtcPrice} newOrderPrice: {newOrder.BitcoinPrice}"); } var subtotal = newOrder.Items.Sum(i => i.Quantity * i.UnitPrice); newOrder.OrderTotalInUSD = subtotal; newOrder.OrderTotalInBitcoin = Math.Round(subtotal / newOrder.BitcoinPrice, 8); RPCCredentialString cred = new RPCCredentialString(); cred.UserPassword = new NetworkCredential(config["NodeCredentials:RPCUser"], config["NodeCredentials:RPCPassword"]); RPCClient client = new RPCClient(cred, Network.TestNet); var address = await client.GetNewAddressAsync(); newOrder.BitcoinAddress = address.ToString(); repo.AddOrder(newOrder); if (repo.SaveAll()) { logger.LogInformation("New order created"); return(Created($"/api/orders/{newOrder.Id}", mapper.Map <Order, OrderViewModel>(newOrder))); } } else { logger.LogInformation("Order creation failed"); return(BadRequest(ModelState)); } } catch (Exception ex) { logger.LogError($"Failed to save new order: {ex}"); return(BadRequest($"Failed to save new order prvi")); } return(BadRequest("Failed to save new order drugi")); }
private void CreateClient(NetworkParameters networkParameters) { var credentialString = new RPCCredentialString(); var uri = $"http://{_configuration.RpcIpAddress}:{_configuration.RpcPort}"; var network = NBitcoin.Network.GetNetwork(networkParameters.Name); credentialString.UserPassword = new NetworkCredential(_configuration.RpcUser, _configuration.RpcPassword); _client = new RPCClient(credentialString, uri, network); }
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 RpcClientFactory( Network network, Uri server, RPCCredentialString credential, ITransactionSerializer elysiumSerializer) { this.network = network; this.serverUrl = server; this.credential = credential; this.ElysiumSerializer = elysiumSerializer; this.GenesisTransactions = new HashSet <uint256>(network.GetGenesis().Transactions.Select(t => t.GetHash())); }
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); }
public async Task GetAsync(string id) //id is blockId { logger.LogInformation("New block has been mined"); RPCCredentialString cred = new RPCCredentialString(); cred.UserPassword = new NetworkCredential(config["NodeCredentials:RPCUser"], config["NodeCredentials:RPCPassword"]); RPCClient client = new RPCClient(cred, Network.TestNet); var unspent = client.ListUnspent(); foreach (var order in repo.GetAllOrders()) { if (order.DisregardOrder || order.OrderTransactionsConfirmed) { continue; } if (order.OrderDate.AddMinutes(15) < DateTime.Now && order.ReceivedValue < order.OrderTotalInBitcoin) //15 minutes or more has passed since order has been placed and payment did not met the requirements { order.DisregardOrder = true; } if (!order.OrderTransactionsConfirmed && order.ReceivedValue > 0) // if there are unconfirmed txes { bool confirmed = true; foreach (var unspentOutput in unspent.Where(tx => tx.Address.ToString() == order.BitcoinAddress)) { if (unspentOutput.Confirmations < 6) // one of transactions of order has less than 6 confirmations { confirmed = false; // transactions for this order have not been confirmed break; } } if (confirmed == true) // all transactions are confirmed and there has been at least some payment { order.OrderTransactionsConfirmed = true; await mailService.SendEmailAsync( order.User.Email, "Your Transactions have been confirmed!", $"Accordion Fair is pleased to inform you that your transactions for order {order.OrderNumber} have been confirmed." ); repo.SaveAll(); } } } }
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 RegTestFixture() { BackendNodeBuilder = NodeBuilder.CreateAsync(nameof(RegTestFixture)).GetAwaiter().GetResult(); BackendNodeBuilder.CreateNodeAsync().GetAwaiter().GetResult(); BackendNodeBuilder.StartAllAsync().GetAwaiter().GetResult(); BackendRegTestNode = BackendNodeBuilder.Nodes[0]; var rpc = BackendRegTestNode.CreateRpcClient(); var connectionString = new RPCCredentialString() { Server = rpc.Address.AbsoluteUri, UserPassword = BackendRegTestNode.Creds }.ToString(); var testnetBackendDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests", "Backend")); IoHelpers.DeleteRecursivelyWithMagicDustAsync(testnetBackendDir).GetAwaiter().GetResult(); Thread.Sleep(100); Directory.CreateDirectory(testnetBackendDir); Thread.Sleep(100); var config = new Config(BackendNodeBuilder.Network, connectionString, IPAddress.Loopback.ToString(), IPAddress.Loopback.ToString(), BackendRegTestNode.Endpoint.Address.ToString(), Network.Main.DefaultPort, Network.TestNet.DefaultPort, BackendRegTestNode.Endpoint.Port); var configFilePath = Path.Combine(testnetBackendDir, "Config.json"); config.SetFilePath(configFilePath); config.ToFileAsync().GetAwaiter().GetResult(); var roundConfig = CreateRoundConfig(Money.Coins(0.1m), Constants.OneDayConfirmationTarget, 0.7, 0.1m, 100, 120, 60, 60, 60, 1, 24, true, 11); var roundConfigFilePath = Path.Combine(testnetBackendDir, "CcjRoundConfig.json"); roundConfig.SetFilePath(roundConfigFilePath); roundConfig.ToFileAsync().GetAwaiter().GetResult(); var conf = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("datadir", testnetBackendDir) }) .Build(); BackendEndPoint = $"http://localhost:{new Random().Next(37130, 38000)}/"; BackendHost = WebHost.CreateDefaultBuilder() .UseStartup <Startup>() .UseConfiguration(conf) .UseWebRoot("../../../../WalletWasabi.Backend/wwwroot") .UseUrls(BackendEndPoint) .Build(); Global = (Backend.Global)BackendHost.Services.GetService(typeof(Backend.Global)); var hostInitializationTask = BackendHost.RunWithTasksAsync(); Logger.LogInfo($"Started Backend webhost: {BackendEndPoint}", nameof(Global)); var delayTask = Task.Delay(3000); Task.WaitAny(delayTask, hostInitializationTask); // Wait for server to initialize (Without this OSX CI will fail) }
private static RPCClient GetRpcClient() { // Run your Dash Core locally like this: dash-qt.exe -server -testnet -rpcuser=user -rpcpassword=pass -rpcport=19998 Uri uri = new Uri("http://127.0.0.1:19998"); string rpcUser = "******"; string rpcPass = "******"; RPCCredentialString credentials = new RPCCredentialString(); credentials.UserPassword = new System.Net.NetworkCredential(rpcUser, rpcPass); RPCClient client = new RPCClient(credentials, uri, _network); return(client); }
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, 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 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 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 async Task <decimal> GetBalance(string address) { //var client = new QBitNinjaClient(Network.Main); //var balance = await client //Console.WriteLine(string.Format("TransId:{0}", transactionResponse.TransactionId)); //Console.WriteLine(string.Format("Conformations:{0}", transactionResponse.Block.Confirmations)); var targetAddr = new BitcoinWitPubKeyAddress(address); RPCCredentialString creds = new RPCCredentialString(); RPCClient client = new RPCClient(Network.Main); client.ImportAddress(targetAddr); var bal = client.GetBalance(); Console.WriteLine(bal); return(decimal.Parse(bal.ToString())); }
public BitcoinService( ILogger <BitcoinService> logger, IOptions <BitcoinSettings> options, IServiceScopeFactory scopeFactory) { _logger = logger; _options = options.Value; _scopeFactory = scopeFactory; _masterKey = new BitcoinExtKey(_options.MasterKey, Network.Main); var credentialString = new RPCCredentialString { Server = _options.Server, UserPassword = new NetworkCredential { UserName = _options.Username, Password = _options.Password } }; _client = new RPCClient(credentialString, Network.Main); }
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(); }