Commit 07459133 authored by Jeremy Bokobza's avatar Jeremy Bokobza

Tabs cleanup

parent 8d101c54
...@@ -6,43 +6,42 @@ using Microsoft.Extensions.Logging; ...@@ -6,43 +6,42 @@ using Microsoft.Extensions.Logging;
using Stratis.Bitcoin; using Stratis.Bitcoin;
using Stratis.Bitcoin.Builder; using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Builder.Feature; using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Logging;
using Stratis.Bitcoin.Utilities; using Stratis.Bitcoin.Utilities;
namespace Breeze.Api namespace Breeze.Api
{ {
/// <summary> /// <summary>
/// Provides an Api to the full node /// Provides an Api to the full node
/// </summary> /// </summary>
public class ApiFeature : FullNodeFeature public class ApiFeature : FullNodeFeature
{ {
private readonly IFullNodeBuilder fullNodeBuilder; private readonly IFullNodeBuilder fullNodeBuilder;
private readonly FullNode fullNode; private readonly FullNode fullNode;
private readonly ApiFeatureOptions apiFeatureOptions; private readonly ApiFeatureOptions apiFeatureOptions;
private readonly IAsyncLoopFactory asyncLoopFactory; private readonly IAsyncLoopFactory asyncLoopFactory;
private readonly ILogger logger; private readonly ILogger logger;
public ApiFeature( public ApiFeature(
IFullNodeBuilder fullNodeBuilder, IFullNodeBuilder fullNodeBuilder,
FullNode fullNode, FullNode fullNode,
ApiFeatureOptions apiFeatureOptions, ApiFeatureOptions apiFeatureOptions,
IAsyncLoopFactory asyncLoopFactory, IAsyncLoopFactory asyncLoopFactory,
ILoggerFactory loggerFactory) ILoggerFactory loggerFactory)
{ {
this.fullNodeBuilder = fullNodeBuilder; this.fullNodeBuilder = fullNodeBuilder;
this.fullNode = fullNode; this.fullNode = fullNode;
this.apiFeatureOptions = apiFeatureOptions; this.apiFeatureOptions = apiFeatureOptions;
this.asyncLoopFactory = asyncLoopFactory; this.asyncLoopFactory = asyncLoopFactory;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
} }
public override void Start() public override void Start()
{ {
this.logger.LogInformation($"Api starting on url {this.fullNode.Settings.ApiUri}"); this.logger.LogInformation($"Api starting on url {this.fullNode.Settings.ApiUri}");
Program.Initialize(this.fullNodeBuilder.Services, this.fullNode); Program.Initialize(this.fullNodeBuilder.Services, this.fullNode);
this.TryStartKeepaliveMonitor(); this.TryStartKeepaliveMonitor();
} }
/// <summary> /// <summary>
/// A KeepaliveMonitor when enabled will shutdown the /// A KeepaliveMonitor when enabled will shutdown the
...@@ -50,26 +49,26 @@ namespace Breeze.Api ...@@ -50,26 +49,26 @@ namespace Breeze.Api
/// during a certain trashold window /// during a certain trashold window
/// </summary> /// </summary>
public void TryStartKeepaliveMonitor() public void TryStartKeepaliveMonitor()
{ {
if (this.apiFeatureOptions.KeepaliveMonitor?.KeepaliveInterval.TotalSeconds > 0) if (this.apiFeatureOptions.KeepaliveMonitor?.KeepaliveInterval.TotalSeconds > 0)
{ {
this.asyncLoopFactory.Run("ApiFeature.KeepaliveMonitor", token => this.asyncLoopFactory.Run("ApiFeature.KeepaliveMonitor", token =>
{ {
// shortened for redability // shortened for redability
var monitor = this.apiFeatureOptions.KeepaliveMonitor; var monitor = this.apiFeatureOptions.KeepaliveMonitor;
// check the trashold to trigger a shutdown // check the trashold to trigger a shutdown
if (monitor.LastBeat.Add(monitor.KeepaliveInterval) < DateTime.UtcNow) if (monitor.LastBeat.Add(monitor.KeepaliveInterval) < DateTime.UtcNow)
this.fullNode.Stop(); this.fullNode.Stop();
return Task.CompletedTask; return Task.CompletedTask;
}, },
this.fullNode.NodeLifetime.ApplicationStopping, this.fullNode.NodeLifetime.ApplicationStopping,
repeatEvery: this.apiFeatureOptions.KeepaliveMonitor?.KeepaliveInterval, repeatEvery: this.apiFeatureOptions.KeepaliveMonitor?.KeepaliveInterval,
startAfter: TimeSpans.Minute); startAfter: TimeSpans.Minute);
} }
} }
} }
public class ApiFeatureOptions public class ApiFeatureOptions
{ {
...@@ -82,25 +81,25 @@ namespace Breeze.Api ...@@ -82,25 +81,25 @@ namespace Breeze.Api
} }
public static class ApiFeatureExtension public static class ApiFeatureExtension
{ {
public static IFullNodeBuilder UseApi(this IFullNodeBuilder fullNodeBuilder, Action<ApiFeatureOptions> optionsAction = null) public static IFullNodeBuilder UseApi(this IFullNodeBuilder fullNodeBuilder, Action<ApiFeatureOptions> optionsAction = null)
{ {
// TODO: move the options in to the feature builder // TODO: move the options in to the feature builder
var options = new ApiFeatureOptions(); var options = new ApiFeatureOptions();
optionsAction?.Invoke(options); optionsAction?.Invoke(options);
fullNodeBuilder.ConfigureFeature(features => fullNodeBuilder.ConfigureFeature(features =>
{ {
features features
.AddFeature<ApiFeature>() .AddFeature<ApiFeature>()
.FeatureServices(services => .FeatureServices(services =>
{ {
services.AddSingleton(fullNodeBuilder); services.AddSingleton(fullNodeBuilder);
services.AddSingleton(options); services.AddSingleton(options);
}); });
}); });
return fullNodeBuilder; return fullNodeBuilder;
} }
} }
} }
using System; using System;
using System.ComponentModel.DataAnnotations;
using Breeze.Api.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using Stratis.Bitcoin.Builder; using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Notifications;
namespace Breeze.Api.Controllers namespace Breeze.Api.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
public class NodeController : Controller public class NodeController : Controller
{ {
private readonly IFullNode fullNode; private readonly IFullNode fullNode;
private readonly ApiFeatureOptions apiFeatureOptions; private readonly ApiFeatureOptions apiFeatureOptions;
public NodeController(IFullNode fullNode, ApiFeatureOptions apiFeatureOptions) public NodeController(IFullNode fullNode, ApiFeatureOptions apiFeatureOptions)
{ {
this.fullNode = fullNode; this.fullNode = fullNode;
this.apiFeatureOptions = apiFeatureOptions; this.apiFeatureOptions = apiFeatureOptions;
} }
/// <summary> /// <summary>
/// Returns some general information about the status of the underlying node. /// Returns some general information about the status of the underlying node.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
[Route("status")] [Route("status")]
public IActionResult Status() public IActionResult Status()
{ {
return this.NotFound(); return this.NotFound();
} }
/// <summary> /// <summary>
/// Trigger a shoutdown of the current running node. /// Trigger a shoutdown of the current running node.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("shutdown")] [Route("shutdown")]
public IActionResult Shutdown() public IActionResult Shutdown()
{ {
// start the node shutdown process // start the node shutdown process
this.fullNode.Stop(); this.fullNode.Stop();
return this.Ok(); return this.Ok();
} }
/// <summary>
/// Set the keepalive flag.
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("keepalive")]
public IActionResult Keepalive()
{
if (this.apiFeatureOptions.KeepaliveMonitor == null)
return new ObjectResult("Keepalive Disabled") {StatusCode = 405}; // (405) Method Not Allowed
this.apiFeatureOptions.KeepaliveMonitor.LastBeat = DateTime.UtcNow; /// <summary>
/// Set the keepalive flag.
return this.Ok(); /// </summary>
} /// <returns></returns>
} [HttpPost]
[Route("keepalive")]
public IActionResult Keepalive()
{
if (this.apiFeatureOptions.KeepaliveMonitor == null)
return new ObjectResult("Keepalive Disabled") {StatusCode = 405}; // (405) Method Not Allowed
this.apiFeatureOptions.KeepaliveMonitor.LastBeat = DateTime.UtcNow;
return this.Ok();
}
}
} }
\ No newline at end of file
...@@ -7,22 +7,22 @@ namespace Breeze.Api ...@@ -7,22 +7,22 @@ namespace Breeze.Api
{ {
public static class MvcBuilderExtensions public static class MvcBuilderExtensions
{ {
/// <summary> /// <summary>
/// Finds all the types that are <see cref="Controller"/> and add them to the Api as services. /// Finds all the types that are <see cref="Controller"/> and add them to the Api as services.
/// </summary> /// </summary>
/// <param name="builder">The builder</param> /// <param name="builder">The builder</param>
/// <param name="services">The services to look into</param> /// <param name="services">The services to look into</param>
/// <returns>The Mvc builder</returns> /// <returns>The Mvc builder</returns>
public static IMvcBuilder AddControllers(this IMvcBuilder builder, IServiceCollection services) public static IMvcBuilder AddControllers(this IMvcBuilder builder, IServiceCollection services)
{ {
var controllerTypes = services.Where(s => s.ServiceType.GetTypeInfo().BaseType == typeof(Controller)); var controllerTypes = services.Where(s => s.ServiceType.GetTypeInfo().BaseType == typeof(Controller));
foreach (var controllerType in controllerTypes) foreach (var controllerType in controllerTypes)
{ {
builder.AddApplicationPart(controllerType.ServiceType.GetTypeInfo().Assembly); builder.AddApplicationPart(controllerType.ServiceType.GetTypeInfo().Assembly);
} }
builder.AddControllersAsServices(); builder.AddControllersAsServices();
return builder; return builder;
} }
} }
} }
...@@ -6,45 +6,45 @@ using Stratis.Bitcoin; ...@@ -6,45 +6,45 @@ using Stratis.Bitcoin;
namespace Breeze.Api namespace Breeze.Api
{ {
public class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
} }
public static void Initialize(IEnumerable<ServiceDescriptor> services, FullNode fullNode) public static void Initialize(IEnumerable<ServiceDescriptor> services, FullNode fullNode)
{ {
var host = new WebHostBuilder() var host = new WebHostBuilder()
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration() .UseIISIntegration()
.UseUrls(fullNode.Settings.ApiUri.ToString()) .UseUrls(fullNode.Settings.ApiUri.ToString())
.ConfigureServices(collection => .ConfigureServices(collection =>
{ {
if (services == null || fullNode == null) if (services == null || fullNode == null)
{ {
return; return;
} }
// copies all the services defined for the full node to the Api.
// also copies over singleton instances already defined
foreach (var service in services)
{
var obj = fullNode.Services.ServiceProvider.GetService(service.ServiceType);
if (obj != null && service.Lifetime == ServiceLifetime.Singleton && service.ImplementationInstance == null)
{
collection.AddSingleton(service.ServiceType, obj);
}
else
{
collection.Add(service);
}
}
})
.UseStartup<Startup>()
.Build();
host.Start(); // copies all the services defined for the full node to the Api.
} // also copies over singleton instances already defined
} foreach (var service in services)
{
var obj = fullNode.Services.ServiceProvider.GetService(service.ServiceType);
if (obj != null && service.Lifetime == ServiceLifetime.Singleton && service.ImplementationInstance == null)
{
collection.AddSingleton(service.ServiceType, obj);
}
else
{
collection.Add(service);
}
}
})
.UseStartup<Startup>()
.Build();
host.Start();
}
}
} }
...@@ -11,83 +11,83 @@ using Swashbuckle.AspNetCore.Swagger; ...@@ -11,83 +11,83 @@ using Swashbuckle.AspNetCore.Swagger;
namespace Breeze.Api namespace Breeze.Api
{ {
public class Startup public class Startup
{ {
public Startup(IHostingEnvironment env) public Startup(IHostingEnvironment env)
{ {
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath) .SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables(); .AddEnvironmentVariables();
Configuration = builder.Build(); Configuration = builder.Build();
} }
public IConfigurationRoot Configuration { get; } public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
// Add service and create Policy to allow Cross-Origin Requests // Add service and create Policy to allow Cross-Origin Requests
services.AddCors services.AddCors
( (
options => options =>
{ {
options.AddPolicy options.AddPolicy
( (
"CorsPolicy", "CorsPolicy",
builder => builder =>
{ {
var allowedDomains = new[]{"http://localhost","http://localhost:4200"}; var allowedDomains = new[] { "http://localhost", "http://localhost:4200" };
builder builder
.WithOrigins(allowedDomains) .WithOrigins(allowedDomains)
.AllowAnyMethod() .AllowAnyMethod()
.AllowAnyHeader() .AllowAnyHeader()
.AllowCredentials(); .AllowCredentials();
} }
); );
}); });
// Add framework services.
services.AddMvc(options => options.Filters.Add(typeof(LoggingActionFilter)))
// add serializers for NBitcoin objects
.AddJsonOptions(options => NBitcoin.JsonConverters.Serializer.RegisterFrontConverters(options.SerializerSettings))
.AddControllers(services);
// Register the Swagger generator, defining one or more Swagger documents // Add framework services.
services.AddSwaggerGen(setup => services.AddMvc(options => options.Filters.Add(typeof(LoggingActionFilter)))
{ // add serializers for NBitcoin objects
setup.SwaggerDoc("v1", new Info { Title = "Breeze.Api", Version = "v1" }); .AddJsonOptions(options => NBitcoin.JsonConverters.Serializer.RegisterFrontConverters(options.SerializerSettings))
.AddControllers(services);
//Set the comments path for the swagger json and ui. // Register the Swagger generator, defining one or more Swagger documents
var basePath = PlatformServices.Default.Application.ApplicationBasePath; services.AddSwaggerGen(setup =>
var apiXmlPath = Path.Combine(basePath, "Breeze.Api.xml"); {
var walletXmlPath = Path.Combine(basePath, "Breeze.Wallet.xml"); setup.SwaggerDoc("v1", new Info { Title = "Breeze.Api", Version = "v1" });
setup.IncludeXmlComments(apiXmlPath);
setup.IncludeXmlComments(walletXmlPath); //Set the comments path for the swagger json and ui.
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var apiXmlPath = Path.Combine(basePath, "Breeze.Api.xml");
var walletXmlPath = Path.Combine(basePath, "Breeze.Wallet.xml");
setup.IncludeXmlComments(apiXmlPath);
setup.IncludeXmlComments(walletXmlPath);
}); });
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ {
loggerFactory.AddConsole(this.Configuration.GetSection("Logging")); loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); loggerFactory.AddDebug();
app.UseCors("CorsPolicy"); app.UseCors("CorsPolicy");
app.UseMvc(); app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint. // Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(); app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint. // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c => app.UseSwaggerUI(c =>
{ {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Breeze.Api V1"); c.SwaggerEndpoint("/swagger/v1/swagger.json", "Breeze.Api V1");
}); });
} }
} }
} }
using System; using System.Threading;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Stratis.Bitcoin.Builder.Feature; using Stratis.Bitcoin.Builder.Feature;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
...@@ -8,7 +7,6 @@ using NBitcoin.Protocol; ...@@ -8,7 +7,6 @@ using NBitcoin.Protocol;
using Stratis.Bitcoin; using Stratis.Bitcoin;
using Stratis.Bitcoin.Builder; using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Consensus.Deployments; using Stratis.Bitcoin.Consensus.Deployments;
using Stratis.Bitcoin.Utilities; using Stratis.Bitcoin.Utilities;
using Stratis.Bitcoin.Wallet; using Stratis.Bitcoin.Wallet;
...@@ -25,9 +23,9 @@ namespace Breeze.Wallet ...@@ -25,9 +23,9 @@ namespace Breeze.Wallet
private readonly ConcurrentChain chain; private readonly ConcurrentChain chain;
private readonly NodeDeployments nodeDeployments; private readonly NodeDeployments nodeDeployments;
private readonly IAsyncLoopFactory asyncLoopFactory; private readonly IAsyncLoopFactory asyncLoopFactory;
private readonly INodeLifetime nodeLifetime; private readonly INodeLifetime nodeLifetime;
public LightWalletFeature(IWalletSyncManager walletSyncManager, IWalletManager walletManager, IConnectionManager connectionManager, public LightWalletFeature(IWalletSyncManager walletSyncManager, IWalletManager walletManager, IConnectionManager connectionManager,
ConcurrentChain chain, NodeDeployments nodeDeployments, IAsyncLoopFactory asyncLoopFactory, INodeLifetime nodeLifetime) ConcurrentChain chain, NodeDeployments nodeDeployments, IAsyncLoopFactory asyncLoopFactory, INodeLifetime nodeLifetime)
{ {
this.walletSyncManager = walletSyncManager; this.walletSyncManager = walletSyncManager;
...@@ -36,7 +34,7 @@ namespace Breeze.Wallet ...@@ -36,7 +34,7 @@ namespace Breeze.Wallet
this.chain = chain; this.chain = chain;
this.nodeDeployments = nodeDeployments; this.nodeDeployments = nodeDeployments;
this.asyncLoopFactory = asyncLoopFactory; this.asyncLoopFactory = asyncLoopFactory;
this.nodeLifetime = nodeLifetime; this.nodeLifetime = nodeLifetime;
} }
public override void Start() public override void Start()
......
using System; using System;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NBitcoin; using NBitcoin;
using NBitcoin.JsonConverters;
using Stratis.Bitcoin; using Stratis.Bitcoin;
using Stratis.Bitcoin.Notifications; using Stratis.Bitcoin.Notifications;
using Stratis.Bitcoin.Utilities; using Stratis.Bitcoin.Utilities;
...@@ -23,20 +21,20 @@ namespace Breeze.Wallet ...@@ -23,20 +21,20 @@ namespace Breeze.Wallet
private readonly ILogger logger; private readonly ILogger logger;
private readonly Signals signals; private readonly Signals signals;
private ChainedBlock walletTip; private ChainedBlock walletTip;
private readonly INodeLifetime nodeLifetime; private readonly INodeLifetime nodeLifetime;
private readonly IAsyncLoopFactory asyncLoopFactory; private readonly IAsyncLoopFactory asyncLoopFactory;
public ChainedBlock WalletTip => this.walletTip; public ChainedBlock WalletTip => this.walletTip;
public LightWalletSyncManager( public LightWalletSyncManager(
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
IWalletManager walletManager, IWalletManager walletManager,
ConcurrentChain chain, ConcurrentChain chain,
Network network, Network network,
BlockNotification blockNotification, BlockNotification blockNotification,
Signals signals, Signals signals,
INodeLifetime nodeLifetime, INodeLifetime nodeLifetime,
IAsyncLoopFactory asyncLoopFactory) IAsyncLoopFactory asyncLoopFactory)
{ {
this.walletManager = walletManager as WalletManager; this.walletManager = walletManager as WalletManager;
this.chain = chain; this.chain = chain;
...@@ -45,7 +43,7 @@ namespace Breeze.Wallet ...@@ -45,7 +43,7 @@ namespace Breeze.Wallet
this.coinType = (CoinType)network.Consensus.CoinType; this.coinType = (CoinType)network.Consensus.CoinType;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.nodeLifetime = nodeLifetime; this.nodeLifetime = nodeLifetime;
this.asyncLoopFactory = asyncLoopFactory; this.asyncLoopFactory = asyncLoopFactory;
} }
/// <inheritdoc /> /// <inheritdoc />
...@@ -183,7 +181,7 @@ namespace Breeze.Wallet ...@@ -183,7 +181,7 @@ namespace Breeze.Wallet
// if the chain is already past the height we want to sync from, we don't wait, even though the chain might not be fully downloaded. // if the chain is already past the height we want to sync from, we don't wait, even though the chain might not be fully downloaded.
if (this.chain.Tip.Height < height) if (this.chain.Tip.Height < height)
{ {
this.asyncLoopFactory.RunUntil("WalletFeature.DownloadChain", this.nodeLifetime.ApplicationStopping, this.asyncLoopFactory.RunUntil("WalletFeature.DownloadChain", this.nodeLifetime.ApplicationStopping,
() => this.chain.Tip.Height >= height, () => this.chain.Tip.Height >= height,
() => this.StartSync(height), () => this.StartSync(height),
(ex) => (ex) =>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment