Skip to content

Commit 4d308a9

Browse files
authored
Refactor ApiSettings (stratisproject#993)
* Refactor ApiSettings * Add comment * Fix comment * Fix test * Fix tests * Simplify
1 parent bd4664a commit 4d308a9

File tree

4 files changed

+32
-94
lines changed

4 files changed

+32
-94
lines changed

src/Stratis.Bitcoin.Features.Api/ApiFeature.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using NBitcoin;
88
using Stratis.Bitcoin.Builder;
99
using Stratis.Bitcoin.Builder.Feature;
10+
using Stratis.Bitcoin.Configuration.Settings;
1011

1112
namespace Stratis.Bitcoin.Features.Api
1213
{
@@ -83,7 +84,7 @@ public override Task InitializeAsync()
8384
/// <param name="network">The network to extract values from.</param>
8485
public static void PrintHelp(Network network)
8586
{
86-
ApiSettings.PrintHelp(network);
87+
BaseSettings.PrintHelp(typeof(ApiSettings), network);
8788
}
8889

8990
/// <summary>
@@ -93,7 +94,7 @@ public static void PrintHelp(Network network)
9394
/// <param name="network">The network to base the defaults off.</param>
9495
public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
9596
{
96-
ApiSettings.BuildDefaultConfigurationFile(builder, network);
97+
BaseSettings.BuildDefaultConfigurationFile(typeof(ApiSettings), builder, network);
9798
}
9899

99100
/// <inheritdoc />
Lines changed: 22 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,35 @@
11
using System;
2-
using System.Text;
32
using System.Timers;
4-
using Microsoft.Extensions.Logging;
5-
using NBitcoin;
63
using Stratis.Bitcoin.Configuration;
7-
using Stratis.Bitcoin.Utilities;
4+
using Stratis.Bitcoin.Configuration.Settings;
85

96
namespace Stratis.Bitcoin.Features.Api
107
{
118
/// <summary>
129
/// Configuration related to the API interface.
1310
/// </summary>
14-
public class ApiSettings
11+
public class ApiSettings : BaseSettings
1512
{
1613
/// <summary>The default port used by the API when the node runs on the Stratis network.</summary>
1714
public const string DefaultApiHost = "http://localhost";
1815

19-
/// <summary>Instance logger.</summary>
20-
private readonly ILogger logger;
21-
2216
/// <summary>URI to node's API interface.</summary>
23-
public Uri ApiUri { get; set; }
17+
[CommandLineOption("apiuri", "URI to node's API interface.")]
18+
private string ApiHost { get { return this.UseHttps ? this.apiHost.Replace(@"http://", @"https://") : this.apiHost; } set { this.apiHost = value; } }
19+
private string apiHost = DefaultApiHost;
20+
21+
// If a port is set in the -apiuri, it takes precedence over the default port or the port passed in -apiport.
22+
public Uri ApiUri { get { Uri uri = new Uri(this.ApiHost); return uri.IsDefaultPort ? new Uri($"{this.ApiHost}:{this.apiPort ?? this.nodeSettings.Network.DefaultAPIPort}") : uri; } }
2423

2524
/// <summary>Port of node's API interface.</summary>
26-
public int ApiPort { get; set; }
25+
[CommandLineOption("apiport", "Port of node's API interface.")]
26+
public int ApiPort { get { return this.ApiUri.Port; } set { this.apiPort = value; } }
27+
private int? apiPort = null;
28+
29+
/// <summary>Sets the keepalive interval (set in seconds).</summary>
30+
[CommandLineOption("keepalive", "Keep Alive interval (set in seconds).")]
31+
private int KeepAlive { get; set; } = 0;
2732

28-
/// <summary>URI to node's API interface.</summary>
2933
public Timer KeepaliveTimer { get; private set; }
3034

3135
/// <summary>
@@ -35,99 +39,31 @@ public class ApiSettings
3539
/// Password protected certificates are not supported. On MacOs, only p12 certificates can be used without password.
3640
/// Please refer to .Net Core documentation for usage: <seealso cref="https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.-ctor?view=netcore-2.1#System_Security_Cryptography_X509Certificates_X509Certificate2__ctor_System_Byte___" />.
3741
/// </remarks>
38-
public string HttpsCertificateFilePath { get; set; }
42+
[CommandLineOption("certificatefilepath", "Path to the certificate used for https traffic encryption. Password protected files are not supported. On MacOs, only p12 certificates can be used without password.", false)]
43+
public string HttpsCertificateFilePath { get; set; } = null;
3944

4045
/// <summary>Use HTTPS or not.</summary>
41-
public bool UseHttps { get; set; }
46+
[CommandLineOption("usehttps", "Use https protocol on the API.")]
47+
public bool UseHttps { get; set; } = false;
4248

4349
/// <summary>
4450
/// Initializes an instance of the object from the node configuration.
4551
/// </summary>
4652
/// <param name="nodeSettings">The node configuration.</param>
47-
public ApiSettings(NodeSettings nodeSettings)
53+
public ApiSettings(NodeSettings nodeSettings) : base(nodeSettings)
4854
{
49-
Guard.NotNull(nodeSettings, nameof(nodeSettings));
50-
51-
this.logger = nodeSettings.LoggerFactory.CreateLogger(typeof(ApiSettings).FullName);
52-
53-
TextFileConfiguration config = nodeSettings.ConfigReader;
54-
55-
this.UseHttps = config.GetOrDefault("usehttps", false);
56-
this.HttpsCertificateFilePath = config.GetOrDefault("certificatefilepath", (string)null);
57-
5855
if (this.UseHttps && string.IsNullOrWhiteSpace(this.HttpsCertificateFilePath))
5956
throw new ConfigurationException("The path to a certificate needs to be provided when using https. Please use the argument 'certificatefilepath' to provide it.");
6057

61-
var defaultApiHost = this.UseHttps
62-
? DefaultApiHost.Replace(@"http://", @"https://")
63-
: DefaultApiHost;
64-
65-
string apiHost = config.GetOrDefault("apiuri", defaultApiHost, this.logger);
66-
var apiUri = new Uri(apiHost);
67-
68-
// Find out which port should be used for the API.
69-
int apiPort = config.GetOrDefault("apiport", nodeSettings.Network.DefaultAPIPort, this.logger);
70-
71-
// If no port is set in the API URI.
72-
if (apiUri.IsDefaultPort)
73-
{
74-
this.ApiUri = new Uri($"{apiHost}:{apiPort}");
75-
this.ApiPort = apiPort;
76-
}
77-
// If a port is set in the -apiuri, it takes precedence over the default port or the port passed in -apiport.
78-
else
79-
{
80-
this.ApiUri = apiUri;
81-
this.ApiPort = apiUri.Port;
82-
}
83-
8458
// Set the keepalive interval (set in seconds).
85-
int keepAlive = config.GetOrDefault("keepalive", 0, this.logger);
86-
if (keepAlive > 0)
59+
if (this.KeepAlive > 0)
8760
{
8861
this.KeepaliveTimer = new Timer
8962
{
9063
AutoReset = false,
91-
Interval = keepAlive * 1000
64+
Interval = this.KeepAlive * 1000
9265
};
9366
}
9467
}
95-
96-
/// <summary>Prints the help information on how to configure the API settings to the logger.</summary>
97-
/// <param name="network">The network to use.</param>
98-
public static void PrintHelp(Network network)
99-
{
100-
var builder = new StringBuilder();
101-
102-
builder.AppendLine($"-apiuri=<string> URI to node's API interface. Defaults to '{ DefaultApiHost }'.");
103-
builder.AppendLine($"-apiport=<0-65535> Port of node's API interface. Defaults to { network.DefaultAPIPort }.");
104-
builder.AppendLine($"-keepalive=<seconds> Keep Alive interval (set in seconds). Default: 0 (no keep alive).");
105-
builder.AppendLine($"-usehttps=<bool> Use https protocol on the API. Defaults to false.");
106-
builder.AppendLine($"-certificatefilepath=<string> Path to the certificate used for https traffic encryption. Defaults to <null>. Password protected files are not supported. On MacOs, only p12 certificates can be used without password.");
107-
108-
var logger = NodeSettings.Default(network).LoggerFactory.CreateLogger(typeof(ApiSettings).FullName);
109-
logger.LogInformation(builder.ToString());
110-
}
111-
112-
/// <summary>
113-
/// Get the default configuration.
114-
/// </summary>
115-
/// <param name="builder">The string builder to add the settings to.</param>
116-
/// <param name="network">The network to base the defaults off.</param>
117-
public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
118-
{
119-
builder.AppendLine("####API Settings####");
120-
builder.AppendLine($"#URI to node's API interface. Defaults to '{ DefaultApiHost }'.");
121-
builder.AppendLine($"#apiuri={ DefaultApiHost }");
122-
builder.AppendLine($"#Port of node's API interface. Defaults to { network.DefaultAPIPort }.");
123-
builder.AppendLine($"#apiport={ network.DefaultAPIPort }");
124-
builder.AppendLine($"#Keep Alive interval (set in seconds). Default: 0 (no keep alive).");
125-
builder.AppendLine($"#keepalive=0");
126-
builder.AppendLine($"#Use HTTPS protocol on the API. Default is false.");
127-
builder.AppendLine($"#usehttps=false");
128-
builder.AppendLine($"#Path to the file containing the certificate to use for https traffic encryption. Password protected files are not supported. On MacOs, only p12 certificates can be used without password.");
129-
builder.AppendLine(@"#Please refer to .Net Core documentation for usage: 'https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.-ctor?view=netcore-2.1#System_Security_Cryptography_X509Certificates_X509Certificate2__ctor_System_Byte___'.");
130-
builder.AppendLine($"#certificatefilepath=");
131-
}
13268
}
13369
}

src/Stratis.Bitcoin/Configuration/Settings/BaseSettings.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ private static string DefaultValue(object value, bool raw = false)
5656

5757
private static Dictionary<Type, MethodInfo> typeGetter = new Dictionary<Type, MethodInfo>();
5858

59+
private static BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
60+
5961
public BaseSettings(NodeSettings nodeSettings)
6062
{
6163
Guard.NotNull(nodeSettings, nameof(nodeSettings));
@@ -66,8 +68,6 @@ public BaseSettings(NodeSettings nodeSettings)
6668

6769
TextFileConfiguration config = nodeSettings.ConfigReader;
6870

69-
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
70-
7171
foreach (PropertyInfo pi in this.GetType().GetProperties(bindingFlags))
7272
{
7373
CommandLineOptionAttribute attr = Attribute.GetCustomAttributes(pi).OfType<CommandLineOptionAttribute>().FirstOrDefault();
@@ -100,7 +100,7 @@ public static void PrintHelp(Type settingsType, Network network)
100100
var builder = new StringBuilder();
101101
var defaultValues = Activator.CreateInstance(settingsType, new object[] { defaultSettings });
102102

103-
foreach (PropertyInfo pi in settingsType.GetProperties())
103+
foreach (PropertyInfo pi in settingsType.GetProperties(bindingFlags))
104104
{
105105
CommandLineOptionAttribute attr = Attribute.GetCustomAttributes(pi).OfType<CommandLineOptionAttribute>().FirstOrDefault();
106106
if (attr == null)
@@ -130,7 +130,7 @@ public static void BuildDefaultConfigurationFile(Type settingsType, StringBuilde
130130
NodeSettings defaultSettings = NodeSettings.Default(network);
131131
var defaultValues = Activator.CreateInstance(settingsType, new object[] { defaultSettings });
132132

133-
foreach (PropertyInfo pi in settingsType.GetProperties())
133+
foreach (PropertyInfo pi in settingsType.GetProperties(bindingFlags))
134134
{
135135
CommandLineOptionAttribute attr = Attribute.GetCustomAttributes(pi).OfType<CommandLineOptionAttribute>().FirstOrDefault();
136136
if (attr == null)

src/Stratis.Features.Unity3dApi/Unity3dApiFeature.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Stratis.Bitcoin;
99
using Stratis.Bitcoin.Builder;
1010
using Stratis.Bitcoin.Builder.Feature;
11+
using Stratis.Bitcoin.Configuration.Settings;
1112
using Stratis.Bitcoin.Features.Api;
1213
using Stratis.Bitcoin.Features.Wallet.Controllers;
1314
using Stratis.Features.Unity3dApi.Controllers;
@@ -95,7 +96,7 @@ public override Task InitializeAsync()
9596
/// <param name="network">The network to extract values from.</param>
9697
public static void PrintHelp(Network network)
9798
{
98-
ApiSettings.PrintHelp(network);
99+
BaseSettings.PrintHelp(typeof(ApiSettings), network);
99100
}
100101

101102
/// <summary>
@@ -105,7 +106,7 @@ public static void PrintHelp(Network network)
105106
/// <param name="network">The network to base the defaults off.</param>
106107
public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
107108
{
108-
ApiSettings.BuildDefaultConfigurationFile(builder, network);
109+
BaseSettings.BuildDefaultConfigurationFile(typeof(ApiSettings), builder, network);
109110
}
110111

111112
/// <inheritdoc />

0 commit comments

Comments
 (0)