예제 #1
0
파일: Startup.cs 프로젝트: soma42/blockcore
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            NodeHostSettings hostSettings = fullNode.Services.ServiceProvider.GetService <NodeHostSettings>();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors("CorsPolicy");

            // Register this before MVC and Swagger.
            app.UseMiddleware <NoCacheMiddleware>();

            app.UseEndpoints(endpoints =>
            {
                if (hostSettings.EnableAPI)
                {
                    endpoints.MapControllers();
                }

                if (hostSettings.EnableWS)
                {
                    IHubContext <EventsHub> hubContext = app.ApplicationServices.GetService <IHubContext <EventsHub> >();
                    IEventsSubscriptionService eventsSubscriptionService = fullNode.Services.ServiceProvider.GetService <IEventsSubscriptionService>();
                    eventsSubscriptionService.SetHub(hubContext);

                    endpoints.MapHub <EventsHub>("/ws-events");
                    endpoints.MapHub <NodeHub>("/ws");
                }

                if (hostSettings.EnableUI)
                {
                    endpoints.MapBlazorHub();
                    endpoints.MapFallbackToPage("/_Host");
                }
            });

            if (hostSettings.EnableAPI)
            {
                app.UseSwagger(c =>
                {
                    c.RouteTemplate = "docs/{documentName}/openapi.json";
                });

                app.UseSwaggerUI(c =>
                {
                    c.DefaultModelRendering(ModelRendering.Model);

                    app.UseSwaggerUI(c =>
                    {
                        c.RoutePrefix = "docs";
                        c.SwaggerEndpoint("/docs/node/openapi.json", "Blockcore Node API");
                    });
                });
            }
        }
예제 #2
0
        public NodeHostFeature(
            IFullNodeBuilder fullNodeBuilder,
            FullNode fullNode,
            NodeHostSettings apiSettings,
            ILoggerFactory loggerFactory,
            ICertificateStore certificateStore,
            IEnumerable <IClientEventBroadcaster> eventBroadcasters,
            IEventsSubscriptionService eventsSubscriptionService)
        {
            this.fullNodeBuilder           = fullNodeBuilder;
            this.fullNode                  = fullNode;
            this.settings                  = apiSettings;
            this.certificateStore          = certificateStore;
            this.eventBroadcasters         = eventBroadcasters;
            this.eventsSubscriptionService = eventsSubscriptionService;
            this.logger = loggerFactory.CreateLogger(this.GetType().FullName);

            this.InitializeBeforeBase = true;
        }
예제 #3
0
        public static IWebHost Initialize(IEnumerable <ServiceDescriptor> services, FullNode fullNode,
                                          NodeHostSettings apiSettings, ICertificateStore store, IWebHostBuilder webHostBuilder)
        {
            Guard.NotNull(fullNode, nameof(fullNode));
            Guard.NotNull(webHostBuilder, nameof(webHostBuilder));

            Uri apiUri = apiSettings.ApiUri;

            X509Certificate2 certificate = apiSettings.UseHttps
                ? GetHttpsCertificate(apiSettings.HttpsCertificateFilePath, store)
                : null;

            webHostBuilder
            .UseKestrel(options =>
            {
                if (!apiSettings.UseHttps)
                {
                    return;
                }

                options.AllowSynchronousIO = true;
                Action <ListenOptions> configureListener = listenOptions => { listenOptions.UseHttps(certificate); };
                var ipAddresses = Dns.GetHostAddresses(apiSettings.ApiUri.DnsSafeHost);
                foreach (var ipAddress in ipAddresses)
                {
                    options.Listen(ipAddress, apiSettings.ApiPort, configureListener);
                }
            })
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseUrls(apiUri.ToString())
            .ConfigureServices(collection =>
            {
                if (services == null)
                {
                    return;
                }

                collection.ConfigureOptions(typeof(EditorRCLConfigureOptions));

                // copies all the services defined for the full node to the Api.
                // also copies over singleton instances already defined
                foreach (ServiceDescriptor service in services)
                {
                    // open types can't be singletons
                    if (service.ServiceType.IsGenericType || service.Lifetime == ServiceLifetime.Scoped)
                    {
                        collection.Add(service);
                        continue;
                    }

                    object 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>();

            IWebHost host = webHostBuilder.Build();

            host.Start();

            return(host);
        }
예제 #4
0
 /// <summary>
 /// Get the default configuration.
 /// </summary>
 /// <param name="builder">The string builder to add the settings to.</param>
 /// <param name="network">The network to base the defaults off.</param>
 public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
 {
     NodeHostSettings.BuildDefaultConfigurationFile(builder, network);
 }
예제 #5
0
 /// <summary>
 /// Prints command-line help.
 /// </summary>
 /// <param name="network">The network to extract values from.</param>
 public static void PrintHelp(Network network)
 {
     NodeHostSettings.PrintHelp(network);
 }
예제 #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            NodeHostSettings hostSettings = fullNode.Services.ServiceProvider.GetService <NodeHostSettings>();

            // Make the configuration available to custom features.
            services.AddSingleton(this.Configuration);

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(this.Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });

            services.Configure <BlockcoreSettings>(this.Configuration.GetSection("Blockcore"));

            // Add service and create Policy to allow Cross-Origin Requests
            services.AddCors
            (
                options =>
            {
                options.AddPolicy
                (
                    "CorsPolicy",

                    builder =>
                {
                    var allowedDomains = new[] { "http://localhost", "http://localhost:4200", "http://localhost:8080" };

                    builder
                    .WithOrigins(allowedDomains)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                }
                );
            });

            if (hostSettings.EnableAuth)
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = ApiKeyAuthenticationOptions.DefaultScheme;
                    options.DefaultChallengeScheme    = ApiKeyAuthenticationOptions.DefaultScheme;
                })
                .AddApiKeySupport(options => { });

                services.AddSingleton <IAuthorizationHandler, OnlyUsersAuthorizationHandler>();
                services.AddSingleton <IAuthorizationHandler, OnlyAdminsAuthorizationHandler>();

                services.AddSingleton <IGetApiKeyQuery, AppSettingsGetApiKeyQuery>();
            }

            if (hostSettings.EnableUI)
            {
                services.AddRazorPages();

                services.AddServerSideBlazor();

                services.Configure <RazorPagesOptions>(options =>
                {
                    // The UI elements moved under the UI folder
                    options.RootDirectory = "/UI/Pages";
                });

                services.AddBlazorModal();
            }

            if (hostSettings.EnableWS)
            {
                services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
                {
                    var settings = new JsonSerializerSettings();

                    settings.Error = (sender, args) =>
                    {
                        args.ErrorContext.Handled = true;
                    };

                    Serializer.RegisterFrontConverters(settings);
                    options.PayloadSerializerSettings = settings;
                    options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
            }

            if (hostSettings.EnableAPI)
            {
                services.AddMvc(options =>
                {
                    options.Filters.Add(typeof(LoggingActionFilter));
                })
                // add serializers for NBitcoin objects
                .AddNewtonsoftJson(options =>
                {
                    Serializer.RegisterFrontConverters(options.SerializerSettings);
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                })
                .AddControllers(this.fullNode.Services.Features, services).AddJsonOptions(x => {
                    x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                });

                services.AddSwaggerGen(
                    options =>
                {
                    string assemblyVersion = typeof(Startup).Assembly.GetName().Version.ToString();

                    string description = "Access to the Blockcore Node features.";

                    if (hostSettings.EnableAuth)
                    {
                        description += " Authorization is enabled on this API. You must have API key to perform calls that are not public.";

                        options.AddSecurityDefinition(ApiKeyConstants.HeaderName, new OpenApiSecurityScheme
                        {
                            Description = "API key needed to access the endpoints. Node-Api-Key: YOUR_KEY",
                            In          = ParameterLocation.Header,
                            Name        = ApiKeyConstants.HeaderName,
                            Type        = SecuritySchemeType.ApiKey
                        });

                        options.AddSecurityRequirement(new OpenApiSecurityRequirement
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Name      = ApiKeyConstants.HeaderName,
                                    Type      = SecuritySchemeType.ApiKey,
                                    In        = ParameterLocation.Header,
                                    Reference = new OpenApiReference
                                    {
                                        Type = ReferenceType.SecurityScheme,
                                        Id   = ApiKeyConstants.HeaderName
                                    },
                                },
                                new string[] {}
                            }
                        });
                    }

                    options.SwaggerDoc("node",
                                       new OpenApiInfo
                    {
                        Title       = hostSettings.ApiTitle + " Node API",
                        Version     = assemblyVersion,
                        Description = description,
                        Contact     = new OpenApiContact
                        {
                            Name = "Blockcore",
                            Url  = new Uri("https://www.blockcore.net/")
                        }
                    });

                    SwaggerApiDocumentationScaffolder.Scaffold(options);

//#pragma warning disable CS0618 // Type or member is obsolete
//                    options.DescribeAllEnumsAsStrings();
//#pragma warning restore CS0618 // Type or member is obsolete

                    // options.DescribeStringEnumsInCamelCase();
                });

                services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
            }
        }
예제 #7
0
파일: Startup.cs 프로젝트: soma42/blockcore
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            NodeHostSettings hostSettings = fullNode.Services.ServiceProvider.GetService <NodeHostSettings>();

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(this.Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });

            // Add service and create Policy to allow Cross-Origin Requests
            services.AddCors
            (
                options =>
            {
                options.AddPolicy
                (
                    "CorsPolicy",

                    builder =>
                {
                    var allowedDomains = new[] { "http://localhost", "http://localhost:4200", "http://localhost:8080" };

                    builder
                    .WithOrigins(allowedDomains)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                }
                );
            });

            if (hostSettings.EnableUI)
            {
                services.AddRazorPages();

                services.AddServerSideBlazor();

                services.Configure <RazorPagesOptions>(options =>
                {
                    // The UI elements moved under the UI folder
                    options.RootDirectory = "/UI/Pages";
                });

                services.AddBlazorModal();
            }

            if (hostSettings.EnableWS)
            {
                services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
                {
                    var settings = new JsonSerializerSettings();

                    settings.Error = (sender, args) =>
                    {
                        args.ErrorContext.Handled = true;
                    };

                    Serializer.RegisterFrontConverters(settings);
                    options.PayloadSerializerSettings = settings;
                    options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
            }

            if (hostSettings.EnableAPI)
            {
                services.AddMvc(options =>
                {
                    options.Filters.Add(typeof(LoggingActionFilter));
                })
                // add serializers for NBitcoin objects
                .AddNewtonsoftJson(options => {
                    Serializer.RegisterFrontConverters(options.SerializerSettings);
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                })
                .AddControllers(this.fullNode.Services.Features, services);

                services.AddSwaggerGen(
                    options =>
                {
                    string assemblyVersion = typeof(Startup).Assembly.GetName().Version.ToString();

                    options.SwaggerDoc("node",
                                       new OpenApiInfo
                    {
                        Title       = "Blockcore Node API",
                        Version     = assemblyVersion,
                        Description = "Access to the Blockcore Node features.",
                        Contact     = new OpenApiContact
                        {
                            Name = "Blockcore",
                            Url  = new Uri("https://www.blockcore.net/")
                        }
                    });

                    SwaggerApiDocumentationScaffolder.Scaffold(options);

#pragma warning disable CS0618 // Type or member is obsolete
                    options.DescribeAllEnumsAsStrings();
#pragma warning restore CS0618 // Type or member is obsolete

                    // options.DescribeStringEnumsInCamelCase();
                });

                services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
            }
        }