/// <summary> /// Initializes a new instance of the object. /// </summary> /// <param name="fullNode">The full node.</param> /// <param name="loggerFactory">Factory to be used to create logger for the node.</param> /// <param name="rpcSettings">The RPC Settings of the full node.</param> public RPCController(IFullNode fullNode, ILoggerFactory loggerFactory, RpcSettings rpcSettings, IRPCClientFactory rpcClientFactory) { Guard.NotNull(fullNode, nameof(fullNode)); Guard.NotNull(loggerFactory, nameof(loggerFactory)); Guard.NotNull(rpcSettings, nameof(rpcSettings)); Guard.NotNull(rpcClientFactory, nameof(rpcClientFactory)); this.fullNode = fullNode; this.logger = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode"); this.rpcSettings = rpcSettings; this.rpcClientFactory = rpcClientFactory; }
static Program() { _rpcSettings = new RpcSettings { User = "******", Password = "******", Url = "http://*****:*****@127.0.0.1:8332/" }; var options = new UserOptions <RpcSettings>() { Value = _rpcSettings }; _txAdapter = new TransactionAdapter(options); }
/// <summary> /// Initializes a new instance of the object. /// </summary> /// <param name="fullNode">The full node.</param> /// <param name="loggerFactory">Factory to be used to create logger for the node.</param> /// <param name="rpcSettings">The RPC Settings of the full node.</param> public RPCController(IFullNode fullNode, ILoggerFactory loggerFactory, RpcSettings rpcSettings, IRPCClientFactory rpcClientFactory) { Guard.NotNull(fullNode, nameof(fullNode)); Guard.NotNull(loggerFactory, nameof(loggerFactory)); Guard.NotNull(rpcSettings, nameof(rpcSettings)); Guard.NotNull(rpcClientFactory, nameof(rpcClientFactory)); this.fullNode = fullNode; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.rpcSettings = rpcSettings; this.rpcClientFactory = rpcClientFactory; }
public void NodeSettings_CanOverrideOnlyApiPort() { const int apiport = 12345; var nodeSettings = new NodeSettings(new BitcoinRegTest(), args: new[] { $"-apiport={apiport}" }); var apiSettings = new ApiSettings(nodeSettings); var rpcSettings = new RpcSettings(nodeSettings); var configurationManagerSettings = new ConnectionManagerSettings(nodeSettings); Assert.Equal(apiport, apiSettings.ApiPort); Assert.Equal(nodeSettings.Network.DefaultRPCPort, rpcSettings.RPCPort); Assert.Equal(nodeSettings.Network.DefaultPort, configurationManagerSettings.Port); }
/// <summary> /// The expected sequence of arguments is [network-name] [rpc-command] [rpc-params]. /// </summary> static void Main(string[] args) { if (NodeSettings.PrintHelp(args, Network.Main)) { // TODO: add more outputs // Proposal: use reflection to find all settings classes and print out help. RpcSettings.PrintHelp(Network.Main); return; } // hack until static flags are removed string blockchain = "bitcoin"; if (args.Any(a => a.Contains("stratis"))) { blockchain = "stratis"; var s = Network.StratisMain; var st = Network.StratisTest; } // The first argument is the network name var network = Network.GetNetwork(args.First()); NodeSettings nodeSettings = NodeSettings.FromArguments(args, blockchain, network); var rpcSettings = new RpcSettings(); rpcSettings.Load(nodeSettings); // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1. System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0]; // Initilize the RPC client with the configured or passed userid, password and endpoint RPCClient rpc = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", new Uri($"http://{nodeEndPoint}")); try { // Execute the RPC command RPCResponse response = rpc.SendCommand(args.ElementAt(1), args.Skip(2).ToArray()); // Return the result as a string to the console Console.WriteLine(response.ResultString); } catch (Exception err) { // Report any errors to the console Console.WriteLine(err.ToString()); } }
public void GetUrls_NoBindsConfigured_ReturnsEmptyArray() { string dir = CreateTestDir(this); var confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "" }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(Network.TestNet, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(new NodeSettings()); var urls = rpcSettings.GetUrls(); Assert.Empty(urls); }
public void Load_InvalidRpcBindIp_ThrowsConfigurationException() { Assert.Throws <ConfigurationException>(() => { string dir = CreateTestDir(this); string confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "server=true", "rpcbind=0....121.12000.00", }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(this.Network, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(nodeSettings); }); }
public void NodeSettings_CanOverrideAllPorts() { // On MacOS ports below 1024 are privileged, and cannot be bound to by anyone other than root. const int port = 1024 + 123; const int rpcPort = 1024 + 456; const int apiPort = 1024 + 567; var args = new [] { $"-port={port.ToString()}", $"-rpcport={rpcPort.ToString()}", $"-apiport={apiPort.ToString()}" }; var nodeSettings = new NodeSettings(new BitcoinRegTest(), args: args); var apiSettings = new ApiSettings(nodeSettings); var rpcSettings = new RpcSettings(nodeSettings); var configurationManagerSettings = new ConnectionManagerSettings(nodeSettings); Assert.Equal(apiPort, apiSettings.ApiPort); Assert.Equal(rpcPort, rpcSettings.RPCPort); Assert.Equal(port, configurationManagerSettings.Port); }
/// <summary>Creates a new instance of Monero API .NET's RPC manager service.</summary> /// <param name="rpcSettings">IP-related settings to use when communicating through the Monero core assemblies' RPC protocol.</param> /// <param name="timerSettings">Timer settings which can be used to alter data fetching intervals.</param> public MoneroRpcManager(IRpcSettings rpcSettings, ITimerSettings timerSettings) { if (rpcSettings == null) { rpcSettings = new RpcSettings(); } if (timerSettings == null) { timerSettings = new TimerSettings(); } RpcWebClient = new RpcWebClient(rpcSettings, timerSettings); RpcSettings = rpcSettings; TimerSettings = timerSettings; Daemon = new DaemonRpcManager(RpcWebClient); AccountManager = new AccountRpcManager(RpcWebClient); }
public void GetUrls_NoBindsConfigured_NoUserPassword_AllowIp_Configured_Returns_DefaultBindings() { string dir = CreateTestDir(this); string confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "server=true", "rpcallowip=0.0.0.0" }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(this.Network, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(nodeSettings); string[] urls = rpcSettings.GetUrls(); Assert.Equal("http://[::]:18332/", urls[0]); Assert.Equal("http://0.0.0.0:18332/", urls[1]); }
public void Load_InvalidRpcAllowIp_ThrowsConfigurationException() { Assert.Throws <ConfigurationException>(() => { string dir = CreateTestDir(this); var confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "server=true", "rpcallowip=0....121.12000.00", }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(Network.TestNet); nodeSettings.LoadArguments(new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(); rpcSettings.Load(nodeSettings); }); }
/// <summary>Creates a new instance of Monero API .NET's process manager service.</summary> /// <param name="rpcSettings">IP-related settings to use when communicating through the Monero core assemblies' RPC protocol.</param> /// <param name="accountManagerProcessSettings">Path settings for the account manager process.</param> /// <param name="daemonProcessSettings">Path settings for the daemon process.</param> public MoneroProcessManager(IRpcSettings rpcSettings, IAccountManagerProcessSettings accountManagerProcessSettings, IDaemonProcessSettings daemonProcessSettings) { if (rpcSettings == null) { rpcSettings = new RpcSettings(); } if (daemonProcessSettings == null) { daemonProcessSettings = new DaemonProcessSettings(); } if (accountManagerProcessSettings == null) { accountManagerProcessSettings = new AccountManagerProcessSettings(); } RpcSettings = rpcSettings; DaemonProcessSettings = daemonProcessSettings; AccountManagerProcessSettings = accountManagerProcessSettings; Daemon = new DaemonProcessManager(rpcSettings, daemonProcessSettings); AccountManager = new AccountProcessManager(rpcSettings, accountManagerProcessSettings, Daemon); }
public void Load_RpcPasswordWithoutRpcUserName_ThrowsConfigurationException() { Assert.Throws <ConfigurationException>(() => { string dir = CreateTestDir(this); string confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "server=true", "rpcport=1378", "rpcpassword=testpassword", "rpcallowip=0.0.0.0", "rpcbind=127.0.0.1" }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(this.Network, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(nodeSettings); }); }
public void Load_DefaultConfiguration_UsesDefaultNodeSettings() { string dir = CreateTestDir(this); string confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "" }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(this.Network, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(nodeSettings); Assert.False(rpcSettings.Server); Assert.Equal(18332, rpcSettings.RPCPort); Assert.Null(rpcSettings.RpcUser); Assert.Null(rpcSettings.RpcPassword); Assert.Empty(rpcSettings.Bind); Assert.Empty(rpcSettings.DefaultBindings); Assert.Empty(rpcSettings.AllowIp); }
public void GetUrls_BindsConfigured_ReturnsBindUrls() { string dir = CreateTestDir(this); var confFile = Path.Combine(dir, "bitcoin.conf"); var configLines = new List <string>() { "server=true", "rpcport=1378", "rpcuser=testuser", "rpcpassword=testpassword", "rpcallowip=0.0.0.0", "rpcbind=127.0.0.1" }; WriteConfigurationToFile(confFile, configLines); var nodeSettings = new NodeSettings(Network.TestNet, args: new string[] { "-conf=" + confFile }); var rpcSettings = new RpcSettings(nodeSettings); var urls = rpcSettings.GetUrls(); Assert.NotEmpty(urls); Assert.Equal("http://127.0.0.1:1378/", urls[0]); }
public RPCControllerTest() { this.initialBlockSignature = Block.BlockSignature; Block.BlockSignature = false; this.network = Network.TestNet; this.fullNode = new Mock <IFullNode>(); this.fullNode.Setup(f => f.Network) .Returns(this.network); this.rpcHost = new Mock <IWebHost>(); this.rpcSettings = new RpcSettings(); this.serviceProvider = new Mock <IServiceProvider>(); this.rpcClientFactory = new Mock <IRPCClientFactory>(); this.actionDescriptorCollectionProvider = new Mock <IActionDescriptorCollectionProvider>(); this.rpcClient = new Mock <IRPCClient>(); this.rpcSettings.Bind.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0)); this.rpcClientFactory.Setup(r => r.Create($"{this.rpcSettings.RpcUser}:{this.rpcSettings.RpcPassword}", It.Is <Uri>(u => u.ToString() == "http://127.0.0.1:0/"), It.IsAny <Network>())) .Returns(this.rpcClient.Object); this.fullNode.Setup(f => f.RPCHost) .Returns(this.rpcHost.Object); this.rpcHost.Setup(c => c.Services) .Returns(this.serviceProvider.Object); this.serviceProvider.Setup(s => s.GetService(typeof(IActionDescriptorCollectionProvider))) .Returns(this.actionDescriptorCollectionProvider.Object); this.descriptors = new List <ActionDescriptor>(); this.actionDescriptorCollectionProvider.Setup(a => a.ActionDescriptors) .Returns(() => { return(new ActionDescriptorCollection(this.descriptors, 0)); }); this.controller = new RPCController(this.fullNode.Object, this.LoggerFactory.Object, this.rpcSettings, this.rpcClientFactory.Object); }
public static void Main(string[] args) { if (NodeSettings.PrintHelp(args, Network.Main)) { RpcSettings.PrintHelp(Network.Main); return; } NodeSettings nodeSettings = NodeSettings.FromArguments(args); var node = new FullNodeBuilder() .UseNodeSettings(nodeSettings) .UseConsensus() .UseBlockStore() .UseMempool() .AddMining() .AddRPC() .Build(); // start the miner (this is temporary a miner should be started using RPC. Task.Delay(TimeSpan.FromMinutes(1)).ContinueWith((t) => { TryStartMiner(args, node); }); node.Run(); }
/// <summary> /// The expected sequence of arguments: /// <list> /// <item> /// 1, [network-name] [options] [rpc-command] [rpc-params]. /// </item> /// <item> /// 2, [network-name] [options] [api-controller "/" api-command] [api-params]. /// </item> /// </list> /// </summary> public static void Main(string[] args) { try { // Preprocess the command line arguments var argList = new List <string>(args); string networkName = null; if (argList.Any()) { networkName = argList.First(); argList.RemoveAt(0); } var optionList = new List <string>(); while ((argList.Any()) && (argList[0].StartsWith('-'))) { optionList.Add(argList[0]); argList.RemoveAt(0); } string command = string.Empty; if (argList.Any()) { command = argList.First(); argList.RemoveAt(0); } var commandArgList = new List <string>(argList); // Display help if required. if (optionList.Contains("-help") || optionList.Contains("--help") || string.IsNullOrWhiteSpace(command)) { var builder = new StringBuilder(); builder.AppendLine("Usage:"); builder.AppendLine(" dotnet run <Stratis.Bitcoin.Cli/Stratis.Bitcoin.Cli.dll> [network-name] [options] <command> [arguments]"); builder.AppendLine(); builder.AppendLine("Command line arguments:"); builder.AppendLine(); builder.AppendLine("[network-name] Name of the network - e.g. \"stratis\", \"stratismain\", \"stratistest\", \"bitcoinmain\", \"bitcointest\"."); builder.AppendLine("[options] Options for the CLI (optional) - e.g. -help, -rpcuser, see below."); builder.AppendLine("[command] Name of RPC method or API <controller>/<method>."); builder.AppendLine("[arguments] Argument by position (RPC) or Name = Value pairs (API) (optional)."); builder.AppendLine(); builder.AppendLine("Options:"); builder.AppendLine("-help This help message"); builder.AppendLine("-rpcconnect=<ip> Send commands to node running on <ip> (default: 127.0.0.1)"); builder.AppendLine("-rpcport=<port> Connect to JSON-RPC on <port> (default for Stratis: 26174 or default for Bitcoin: 8332)"); builder.AppendLine("-rpcuser=<user> Username for JSON-RPC connections"); builder.AppendLine("-rpcpassword=<pw> Password for JSON-RPC connections"); builder.AppendLine(); builder.AppendLine("Examples:"); builder.AppendLine(); builder.AppendLine("dotnet run stratis Wallet/history WalletName=testwallet - Lists all the historical transactions of the wallet called 'testwallet'."); builder.AppendLine("dotnet run stratis getinfo -rpcuser=stratistestuser -rpcpassword=stratistestpassword -rpcconnect=127.0.0.3 -rpcport=26174 - Displays general information about the Stratis node on the 127.0.0.3:26174, authenticating with the RPC specified user."); builder.AppendLine("dotnet run bitcoin getbalance -rpcuser=btctestuser -rpcpassword=btctestpass - Displays the current balance of the opened wallet on the 127.0.0.1:8332 node, authenticating with the RPC specified user."); Console.WriteLine(builder); return; } // Determine API port. int defaultRestApiPort = 0; Network network = null; if (networkName.Contains("stratis")) { defaultRestApiPort = 37221; network = Network.StratisMain; } else { defaultRestApiPort = 37220; network = Network.Main; } // API calls require both the contoller name and the method name separated by "/". // If this is not an API call then assume it is an RPC call. if (!command.Contains("/")) { // Process RPC call. try { string[] options = optionList.Append("-server").ToArray(); var nodeSettings = new NodeSettings(network, args: options); var rpcSettings = new RpcSettings(nodeSettings); // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1. System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0]; var rpcUri = new Uri($"http://{nodeEndPoint}"); // Process the command line RPC arguments // TODO: this should probably be moved to the NodeSettings.FromArguments if (options.GetValueOf("-rpcbind") != null) { rpcUri = new Uri($"http://{options.GetValueOf("-rpcbind")}"); } if (options.GetValueOf("-rpcconnect") != null || options.GetValueOf("-rpcport") != null) { string rpcAddress = options.GetValueOf("-rpcconnect") ?? "127.0.0.1"; int rpcPort = rpcSettings.RPCPort; int.TryParse(options.GetValueOf("-rpcport"), out rpcPort); rpcUri = new Uri($"http://{rpcAddress}:{rpcPort}"); } rpcSettings.RpcUser = options.GetValueOf("-rpcuser") ?? rpcSettings.RpcUser; rpcSettings.RpcPassword = options.GetValueOf("-rpcpassword") ?? rpcSettings.RpcPassword; Console.WriteLine($"Connecting to the following RPC node: http://{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}@{rpcUri.Authority}..."); // Initialize the RPC client with the configured or passed userid, password and endpoint. var rpcClient = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", rpcUri, network); // Execute the RPC command Console.WriteLine($"Sending RPC command '{command} {string.Join(" ", commandArgList)}' to '{rpcUri}'..."); RPCResponse response = rpcClient.SendCommand(command, commandArgList.ToArray()); // Return the result as a string to the console. Console.WriteLine(response.ResultString); } catch (Exception err) { Console.WriteLine(err.Message); } } else { // Process API call. using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string url = $"http://localhost:{defaultRestApiPort}/api/{command}"; if (commandArgList.Any()) { url += $"?{string.Join("&", commandArgList)}"; } try { // Get the response. Console.WriteLine($"Sending API command to {url}..."); string response = client.GetStringAsync(url).GetAwaiter().GetResult(); // Format and return the result as a string to the console. Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject <object>(response), Formatting.Indented)); } catch (Exception err) { Console.WriteLine(ExceptionToString(err)); } } } } catch (Exception err) { // Report any errors to the console. Console.WriteLine(ExceptionToString(err)); } }
/// <summary> /// The expected sequence of arguments: /// <list> /// <item> /// 1, [network-name] [options] [rpc-command] [rpc-params]. /// </item> /// <item> /// 2, [network-name] [options] [api-controller "/" api-command] [api-params]. /// </item> /// </list> /// </summary> public static void Main(string[] args) { try { // Preprocess the command line arguments var argList = new List <string>(args); string networkName = null; if (argList.Any()) { networkName = argList.First(); argList.RemoveAt(0); } var optionList = new List <string>(); while ((argList.Any()) && (argList[0].StartsWith('-'))) { optionList.Add(argList[0]); argList.RemoveAt(0); } string method = ""; if (argList.Any()) { method = argList.First().ToUpper(); if (method == "GET" || method == "POST" || method == "DELETE") { argList.RemoveAt(0); } else { method = ""; } } string command = string.Empty; if (argList.Any()) { command = argList.First(); argList.RemoveAt(0); } var commandArgList = new List <string>(argList); // Display help if required. if (optionList.Contains("-help") || optionList.Contains("--help") || string.IsNullOrWhiteSpace(command)) { var builder = new StringBuilder(); builder.AppendLine("Usage:"); builder.AppendLine(" dotnet run <Stratis.Bitcoin.Cli/Stratis.Bitcoin.Cli.dll> [network-name] [options] [method] <command> [arguments]"); builder.AppendLine(); builder.AppendLine("Command line arguments:"); builder.AppendLine(); builder.AppendLine("[network-name] Name of the network - e.g. \"strax\" or \"bitcoin\"."); builder.AppendLine("[options] Options for the CLI (optional) - e.g. -help, -rpcuser, see below."); builder.AppendLine("[method] Method to use for API calls - 'GET', 'POST' or 'DELETE'."); builder.AppendLine("[command] Name of RPC method or API <controller>/<method>."); builder.AppendLine("[arguments] Argument by position (RPC) or Name = Value pairs (API) (optional)."); builder.AppendLine(); builder.AppendLine("Options:"); builder.AppendLine("-help This help message"); builder.AppendLine("-rpcconnect=<ip> Send commands to node running on <ip> (default: 127.0.0.1)"); builder.AppendLine("-rpcport=<port> Connect to JSON-RPC on <port> (default for Strax: 18000 (mainnet), 18100 (testnet) or default for Bitcoin: 8332)"); builder.AppendLine("-rpcuser=<user> Username for JSON-RPC connections"); builder.AppendLine("-rpcpassword=<pw> Password for JSON-RPC connections"); builder.AppendLine(); builder.AppendLine("Examples:"); builder.AppendLine(); builder.AppendLine("dotnet run stratis -testnet GET Wallet/history WalletName=testwallet - Lists all the historical transactions of the wallet called 'testwallet' on the stratis test network."); builder.AppendLine("dotnet run stratis -rpcuser=stratistestuser -rpcpassword=stratistestpassword -rpcconnect=127.0.0.3 -rpcport=26174 getinfo - Displays general information about the Stratis node on the 127.0.0.3:26174, authenticating with the RPC specified user."); builder.AppendLine("dotnet run bitcoin -rpcuser=btctestuser -rpcpassword=btctestpass getbalance - Displays the current balance of the opened wallet on the 127.0.0.1:8332 node, authenticating with the RPC specified user."); Console.WriteLine(builder); return; } // Determine API port. NetworksSelector networksSelector = null; if (networkName.Contains("strax")) { networksSelector = Networks.Networks.Strax; } else if (networkName.Contains("stratis")) { networksSelector = Networks.Networks.Stratis; } else { networksSelector = Networks.Networks.Bitcoin; } // API calls require both the controller name and the method name separated by "/". // If this is not an API call then assume it is an RPC call. if (!command.Contains("/")) { // Process RPC call. try { string[] options = optionList.Append("-server").ToArray(); var nodeSettings = new NodeSettings(networksSelector: networksSelector, protocolVersion: ProtocolVersion.PROVEN_HEADER_VERSION, args: options) { MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION }; var rpcSettings = new RpcSettings(nodeSettings); Network network = nodeSettings.Network; // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1. System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0]; var rpcUri = new Uri($"http://{nodeEndPoint}"); // Process the command line RPC arguments // TODO: this should probably be moved to the NodeSettings.FromArguments if (options.GetValueOf("-rpcbind") != null) { rpcUri = new Uri($"http://{options.GetValueOf("-rpcbind")}"); } if (options.GetValueOf("-rpcconnect") != null || options.GetValueOf("-rpcport") != null) { string rpcAddress = options.GetValueOf("-rpcconnect") ?? "127.0.0.1"; int rpcPort = rpcSettings.RPCPort; int.TryParse(options.GetValueOf("-rpcport"), out rpcPort); rpcUri = new Uri($"http://{rpcAddress}:{rpcPort}"); } rpcSettings.RpcUser = options.GetValueOf("-rpcuser") ?? rpcSettings.RpcUser; rpcSettings.RpcPassword = options.GetValueOf("-rpcpassword") ?? rpcSettings.RpcPassword; Console.WriteLine($"Connecting to the following RPC node: http://{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}@{rpcUri.Authority}."); // Initialize the RPC client with the configured or passed userid, password and endpoint. var rpcClient = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", rpcUri, network); // Execute the RPC command Console.WriteLine($"Sending RPC command '{command} {string.Join(" ", commandArgList)}' to '{rpcUri}'."); RPCResponse response = rpcClient.SendCommand(command, commandArgList.ToArray()); // Return the result as a string to the console. Console.WriteLine(response.ResultString); } catch (Exception err) { Console.WriteLine(err.Message); } } else { // Process API call. string[] options = optionList.ToArray(); var nodeSettings = new NodeSettings(networksSelector: networksSelector, protocolVersion: ProtocolVersion.PROVEN_HEADER_VERSION, args: options) { MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION }; var apiSettings = new ApiSettings(nodeSettings); string url = $"http://localhost:{apiSettings.ApiPort}/api".AppendPathSegment(command); object commandArgObj = GetAnonymousObjectFromDictionary(commandArgList .Select(a => a.Split('=')) .ToDictionary(a => a[0], a => a[1])); HttpResponseMessage httpResponse; switch (method) { case "POST": httpResponse = CallApiPost(url, commandArgObj); break; case "DELETE": httpResponse = CallApiDelete(url, commandArgObj); break; default: httpResponse = CallApiGet(url, commandArgObj); break; } var response = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // Format and return the result as a string to the console. Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject <object>(response), Formatting.Indented)); } } catch (Exception err) { // Report any errors to the console. Console.WriteLine(ExceptionToString(err)); } }
/// <summary> /// The expected sequence of arguments: /// 1) [network-name] [rpc-command] [rpc-params]. /// OR /// 2) [network-name] [api-controller "/" api-command] [api-params]. /// </summary> public static void Main(string[] args) { try { // Display help if required. if (args.Length == 0 || args.Contains("-help") || args.Contains("--help")) { var builder = new StringBuilder(); builder.AppendLine("Usage:"); builder.AppendLine(" dotnet run <Stratis.Bitcoin.Cli/Stratis.Bitcoin.Cli.dll> [network-name] [command] [arguments]"); builder.AppendLine(); builder.AppendLine("Command line arguments:"); builder.AppendLine(); builder.AppendLine("[network-name] Name of the network - e.g. \"stratis\"."); builder.AppendLine("[command] Name of RPC method or API <controller>/<method>."); builder.AppendLine("[arguments] Argument by position (RPC) or Name = Value pairs (API)."); Console.WriteLine(builder); return; } // Determine API port. string blockchain = "bitcoin"; int apiPort = 37220; if (args.Any(a => a.Contains("stratis"))) { blockchain = "stratis"; apiPort = 37221; // hack until static flags are removed. Network s = Network.StratisMain; Network st = Network.StratisTest; } // The first argument is the network name. var network = Network.GetNetwork(args.First()); // API calls require both the contoller name and the method name separated by "/". // If this is not an API call then assume it is an RPC call. if (!args.ElementAt(1).Contains("/")) { // Process RPC call. try { NodeSettings nodeSettings = new NodeSettings(blockchain, network).LoadArguments(args); var rpcSettings = new RpcSettings(); rpcSettings.Load(nodeSettings); // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1. System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0]; // Initialize the RPC client with the configured or passed userid, password and endpoint RPCClient rpc = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", new Uri($"http://{nodeEndPoint}")); // Execute the RPC command Console.WriteLine($"Sending RPC command '{string.Join(" ", args.Skip(1))}' to 'http://{nodeEndPoint}'..."); RPCResponse response = rpc.SendCommand(args.ElementAt(1), args.Skip(2).ToArray()); // Return the result as a string to the console. Console.WriteLine(response.ResultString); } catch (Exception err) { Console.WriteLine(err.Message); } } else { // Process API call. using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var url = $"http://localhost:{apiPort}/api/{args.ElementAt(1)}?{string.Join("&", args.Skip(2))}"; try { // Get the response. Console.WriteLine($"Sending API command to {url}..."); var response = client.GetStringAsync(url).GetAwaiter().GetResult(); // Format and return the result as a string to the console. Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject <object>(response), Formatting.Indented)); } catch (Exception err) { Console.WriteLine(ExceptionToString(err)); } } } } catch (Exception err) { // Report any errors to the console. Console.WriteLine(ExceptionToString(err)); } }
/// <summary> /// Initializes a new instance of the object. /// </summary> /// <param name="fullNode">The full node.</param> /// <param name="loggerFactory">Factory to be used to create logger for the node.</param> /// <param name="rpcSettings">The RPC Settings of the full node.</param> public RPCController(IFullNode fullNode, ILoggerFactory loggerFactory, RpcSettings rpcSettings) { this.fullNode = fullNode; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.rpcSettings = rpcSettings; }
public static void Initialize(MainForm mainForm) { MainForm = mainForm; SettingsManager.Initialize(); CultureManager.Initialize(); var defaultFont = new Font(SystemFont.Default); DefaultFontSize = defaultFont.Size; DefaultFontFamily = defaultFont.Family; FontSize1 = (byte)Math.Round(DefaultFontSize * 1.11); FontSize2 = (byte)Math.Round(DefaultFontSize * 1.33); FontSize3 = (byte)Math.Round(DefaultFontSize * 2.22); using (var button = new Button()) { var handler = button.Handler; var fieldInfo = handler.GetType().GetField("MinimumSize"); if (fieldInfo != null) { var size = (Size)(fieldInfo.GetValue(null)); size.Width = 0; fieldInfo.SetValue(null, size); } else { fieldInfo = handler.GetType().GetField("MinimumWidth"); if (fieldInfo != null) { fieldInfo.SetValue(null, 0); } } } var storedPathSettings = SettingsManager.Paths; var daemonProcessSettings = new DaemonProcessSettings { SoftwareDaemon = GetAbsolutePath(storedPathSettings.SoftwareDaemon), DirectoryDaemonData = GetAbsolutePath(storedPathSettings.DirectoryDaemonData), }; var accountManagerProcessSettings = new AccountManagerProcessSettings { SoftwareAccountManager = GetAbsolutePath(storedPathSettings.SoftwareAccountManager), DirectoryAccountBackups = GetAbsolutePath(storedPathSettings.DirectoryAccountBackups), FileAccountData = GetAbsolutePath(storedPathSettings.FileAccountData), }; var storedNetworkSettings = SettingsManager.Network; var rpcSettings = new RpcSettings( storedNetworkSettings.RpcUrlHostDaemon, storedNetworkSettings.RpcUrlPortDaemon, storedNetworkSettings.RpcUrlHostAccountManager, storedNetworkSettings.RpcUrlPortAccountManager ); if (storedNetworkSettings.IsProxyEnabled) { if (!string.IsNullOrEmpty(storedNetworkSettings.ProxyHost)) { rpcSettings.Proxy = new WebProxy(storedNetworkSettings.ProxyHost, storedNetworkSettings.ProxyPort); } } MoneroProcessManager = new MoneroProcessManager(rpcSettings, accountManagerProcessSettings, daemonProcessSettings); MoneroRpcManager = new MoneroRpcManager(rpcSettings); DataSourceAddressBook = new ObservableCollection <SettingsManager.ConfigElementContact>(SettingsManager.AddressBook.Elements); DataSourceAddressBook.CollectionChanged += OnDataSourceAddressBookCollectionChanged; }