Skip to content

Commit

Permalink
Migrate more of network initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
asdacap committed Sep 30, 2024
1 parent dfd0f34 commit 9e4da92
Show file tree
Hide file tree
Showing 37 changed files with 613 additions and 509 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
// SPDX-License-Identifier: LGPL-3.0-only

using System.Threading.Tasks;
using Autofac;

namespace Nethermind.Api.Extensions
{
public interface ISynchronizationPlugin : INethermindPlugin
{
Task InitSynchronization();
void ConfigureSynchronizationBuilder(ContainerBuilder containerBuilder);
Task InitSynchronization(IContainer container);
}
}
8 changes: 5 additions & 3 deletions src/Nethermind/Nethermind.Api/IApiWithBlockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,23 @@ public interface IApiWithBlockchain : IApiWithStores, IBlockchainBridgeFactory

IGasPriceOracle? GasPriceOracle { get; set; }

IEthSyncingInfo? EthSyncingInfo { get; set; }
IEthSyncingInfo? EthSyncingInfo { get; }

CompositePruningTrigger PruningTrigger { get; }

IBlockProductionPolicy? BlockProductionPolicy { get; set; }
INodeStorageFactory NodeStorageFactory { get; set; }
BackgroundTaskScheduler BackgroundTaskScheduler { get; set; }
IBackgroundTaskScheduler BackgroundTaskScheduler { get; set; }
CensorshipDetector CensorshipDetector { get; set; }

public ContainerBuilder ConfigureContainerBuilderFromApiWithBlockchain(ContainerBuilder builder)
{
return ConfigureContainerBuilderFromApiWithStores(builder)
ConfigureContainerBuilderFromApiWithStores(builder)
.AddPropertiesFrom<IApiWithBlockchain>(this)
.AddSingleton<INodeStorage>(NodeStorageFactory.WrapKeyValueStore(DbProvider!.StateDb));
if (TrieStore != null) builder.AddSingleton<IReadOnlyTrieStore>(TrieStore.AsReadOnly());

return builder;
}
}
}
25 changes: 10 additions & 15 deletions src/Nethermind/Nethermind.Api/IApiWithNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,26 @@ public interface IApiWithNetwork : IApiWithBlockchain
{
(IApiWithNetwork GetFromApi, IApiWithNetwork SetInApi) ForNetwork => (this, this);

IDisconnectsAnalyzer? DisconnectsAnalyzer { get; set; }
IDiscoveryApp? DiscoveryApp { get; set; }
IDiscoveryApp? DiscoveryApp { get; }
IGrpcServer? GrpcServer { get; set; }
IIPResolver? IpResolver { get; set; }
IMessageSerializationService MessageSerializationService { get; }
IGossipPolicy GossipPolicy { get; set; }
IMonitoringService MonitoringService { get; set; }
INodeStatsManager? NodeStatsManager { get; set; }
IPeerManager? PeerManager { get; set; }
IPeerPool? PeerPool { get; set; }
IProtocolsManager? ProtocolsManager { get; set; }
IProtocolValidator? ProtocolValidator { get; set; }
INodeStatsManager? NodeStatsManager { get; }
IPeerManager? PeerManager { get; }
IPeerPool? PeerPool { get; }
IList<IPublisher> Publishers { get; }
IRlpxHost? RlpxPeer { get; set; }
IRlpxHost? RlpxPeer { get; }
IRpcModuleProvider? RpcModuleProvider { get; set; }
IJsonRpcLocalStats? JsonRpcLocalStats { get; set; }
ISessionMonitor? SessionMonitor { get; set; }
IStaticNodesManager? StaticNodesManager { get; set; }
ISessionMonitor? SessionMonitor { get; }
IStaticNodesManager? StaticNodesManager { get; }
ISynchronizer? Synchronizer { get; }
ISyncModeSelector SyncModeSelector { get; }
ISyncProgressResolver? SyncProgressResolver { get; }
IPivot? Pivot { get; set; }
ISyncPeerPool? SyncPeerPool { get; set; }
IPeerDifficultyRefreshPool? PeerDifficultyRefreshPool { get; set; }
ISyncServer? SyncServer { get; set; }
ISyncPeerPool? SyncPeerPool { get; }
IPeerDifficultyRefreshPool? PeerDifficultyRefreshPool { get; }
ISyncServer? SyncServer { get; }
IWebSocketsManager WebSocketsManager { get; set; }
ISubscriptionFactory? SubscriptionFactory { get; set; }

Expand Down
9 changes: 5 additions & 4 deletions src/Nethermind/Nethermind.Api/IBasicApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Nethermind.Db;
using Nethermind.KeyStore;
using Nethermind.Logging;
using Nethermind.Network.Config;
using Nethermind.Serialization.Json;
using Nethermind.Specs.ChainSpecStyle;
using Nethermind.Synchronization;
Expand All @@ -43,7 +44,7 @@ public interface IBasicApi
[SkipServiceCollection]
string SealEngineType { get; set; }
ISpecProvider? SpecProvider { get; set; }
IBetterPeerStrategy? BetterPeerStrategy { get; set; }
IBetterPeerStrategy? BetterPeerStrategy { get; }
ITimestamper Timestamper { get; }
ITimerFactory TimerFactory { get; }
IProcessExitSource? ProcessExit { get; set; }
Expand All @@ -61,9 +62,9 @@ public IEnumerable<ISynchronizationPlugin> GetSynchronizationPlugins() =>

public ContainerBuilder ConfigureContainerBuilderFromBasicApi(ContainerBuilder builder)
{
builder
.AddPropertiesFrom<IBasicApi>(this)
.AddSingleton(ConfigProvider.GetConfig<ISyncConfig>());
builder.AddPropertiesFrom<IBasicApi>(this);
builder.Register<IEthereumEcdsa, IEcdsa>(ecdsa => ecdsa);
builder.RegisterSource(new ConfigRegistrationSource());

DbProvider!.ConfigureServiceCollection(builder);

Expand Down
39 changes: 18 additions & 21 deletions src/Nethermind/Nethermind.Api/NethermindApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ public IBlockchainBridge CreateBlockchainBridge()
public ICryptoRandom CryptoRandom { get; }
public IDbProvider? DbProvider { get; set; }
public IDbFactory? DbFactory { get; set; }
public IDisconnectsAnalyzer? DisconnectsAnalyzer { get; set; }
public IDiscoveryApp? DiscoveryApp { get; set; }

public IDiscoveryApp? DiscoveryApp => ApiWithNetworkServiceContainer?.ResolveOptional<IDiscoveryApp>();
public ISigner? EngineSigner { get; set; }
public ISignerStore? EngineSignerStore { get; set; }
public IEnode? Enode { get; set; }
Expand All @@ -153,16 +153,14 @@ public IBlockchainBridge CreateBlockchainBridge()
public IMessageSerializationService MessageSerializationService { get; } = new MessageSerializationService();
public IGossipPolicy GossipPolicy { get; set; } = Policy.FullGossip;
public IMonitoringService MonitoringService { get; set; } = NullMonitoringService.Instance;
public INodeStatsManager? NodeStatsManager { get; set; }
public IPeerManager? PeerManager { get; set; }
public IPeerPool? PeerPool { get; set; }
public IProtocolsManager? ProtocolsManager { get; set; }
public IProtocolValidator? ProtocolValidator { get; set; }
public INodeStatsManager? NodeStatsManager => ApiWithNetworkServiceContainer?.ResolveOptional<INodeStatsManager>();
public IPeerManager? PeerManager => ApiWithNetworkServiceContainer?.ResolveOptional<IPeerManager>();
public IPeerPool? PeerPool => ApiWithNetworkServiceContainer?.ResolveOptional<IPeerPool>();
public IReceiptStorage? ReceiptStorage { get; set; }
public IReceiptFinder? ReceiptFinder { get; set; }
public IReceiptMonitor? ReceiptMonitor { get; set; }
public IRewardCalculatorSource? RewardCalculatorSource { get; set; } = NoBlockRewards.Instance;
public IRlpxHost? RlpxPeer { get; set; }
public IRlpxHost? RlpxPeer => ApiWithNetworkServiceContainer?.ResolveOptional<IRlpxHost>();
public IRpcModuleProvider? RpcModuleProvider { get; set; } = NullModuleProvider.Instance;
public IRpcAuthentication? RpcAuthentication { get; set; }
public IJsonRpcLocalStats? JsonRpcLocalStats { get; set; }
Expand All @@ -183,23 +181,22 @@ public ISealEngine SealEngine
}
}

public ISessionMonitor? SessionMonitor { get; set; }
public ISessionMonitor? SessionMonitor => ApiWithNetworkServiceContainer?.ResolveOptional<ISessionMonitor>();
public ISpecProvider? SpecProvider { get; set; }
public IPoSSwitcher PoSSwitcher { get; set; } = NoPoS.Instance;
public ISyncModeSelector SyncModeSelector => ApiWithNetworkServiceContainer?.Resolve<ISyncModeSelector>()!;

public ISyncProgressResolver? SyncProgressResolver => ApiWithNetworkServiceContainer?.Resolve<ISyncProgressResolver>();
public IBetterPeerStrategy? BetterPeerStrategy { get; set; }
public IPivot? Pivot { get; set; }
public ISyncPeerPool? SyncPeerPool { get; set; }
public IPeerDifficultyRefreshPool? PeerDifficultyRefreshPool { get; set; }
public ISynchronizer? Synchronizer => ApiWithNetworkServiceContainer?.Resolve<ISynchronizer>();
public ISyncServer? SyncServer { get; set; }
public ISyncModeSelector SyncModeSelector => ApiWithNetworkServiceContainer?.ResolveOptional<ISyncModeSelector>()!;
public IBetterPeerStrategy? BetterPeerStrategy => ApiWithNetworkServiceContainer?.ResolveOptional<IBetterPeerStrategy>();
public ISyncPeerPool? SyncPeerPool => ApiWithNetworkServiceContainer?.ResolveOptional<ISyncPeerPool>();
public IPeerDifficultyRefreshPool? PeerDifficultyRefreshPool => ApiWithNetworkServiceContainer?.ResolveOptional<IPeerDifficultyRefreshPool>();
public ISynchronizer? Synchronizer => ApiWithNetworkServiceContainer?.ResolveOptional<ISynchronizer>();
public ISyncServer? SyncServer => ApiWithNetworkServiceContainer?.ResolveOptional<ISyncServer>();

[SkipServiceCollection]
public IWorldState? WorldState { get; set; }
public IReadOnlyStateProvider? ChainHeadStateProvider { get; set; }
public IWorldStateManager? WorldStateManager { get; set; }
public IStateReader? StateReader { get; set; }
public IStaticNodesManager? StaticNodesManager { get; set; }
public IStaticNodesManager? StaticNodesManager => ApiWithNetworkServiceContainer?.ResolveOptional<IStaticNodesManager>();
public ITimestamper Timestamper { get; } = Core.Timestamper.Default;
public ITimerFactory TimerFactory { get; } = Core.Timers.TimerFactory.Default;
public ITransactionProcessor? TransactionProcessor { get; set; }
Expand All @@ -217,10 +214,10 @@ public ISealEngine SealEngine
public IBlockProducerEnvFactory? BlockProducerEnvFactory { get; set; }
public IGasPriceOracle? GasPriceOracle { get; set; }

public IEthSyncingInfo? EthSyncingInfo { get; set; }
public IEthSyncingInfo? EthSyncingInfo => ApiWithNetworkServiceContainer?.ResolveOptional<IEthSyncingInfo>();
public IBlockProductionPolicy? BlockProductionPolicy { get; set; }
public INodeStorageFactory NodeStorageFactory { get; set; } = null!;
public BackgroundTaskScheduler BackgroundTaskScheduler { get; set; } = null!;
public IBackgroundTaskScheduler BackgroundTaskScheduler { get; set; } = null!;
public CensorshipDetector CensorshipDetector { get; set; } = null!;
public IWallet? Wallet { get; set; }
public IBlockStore? BadBlocksStore { get; set; }
Expand Down
51 changes: 51 additions & 0 deletions src/Nethermind/Nethermind.Config/ConfigRegistrationSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Delegate;
using Autofac.Core.Lifetime;
using Autofac.Core.Registration;

namespace Nethermind.Config;

/// <summary>
/// Dynamically resolve IConfig<T>
/// </summary>
public class ConfigRegistrationSource : IRegistrationSource
{
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<ServiceRegistration>> registrationAccessor)
{
IServiceWithType swt = service as IServiceWithType;
if (swt == null || !typeof(IConfig).IsAssignableFrom(swt.ServiceType))
{
// It's not a request for the base handler type, so skip it.
return Enumerable.Empty<IComponentRegistration>();
}

// Dynamically resolve IConfig
ComponentRegistration registration = new ComponentRegistration(
Guid.NewGuid(),
new DelegateActivator(swt.ServiceType, (c, p) =>
{
IConfigProvider configProvider = c.Resolve<IConfigProvider>();
object config = typeof(IConfigProvider)
.GetMethod("GetConfig")
.MakeGenericMethod(swt.ServiceType)
.Invoke(configProvider, new object[] { });
return config;
}),
new RootScopeLifetime(),
InstanceSharing.Shared,
InstanceOwnership.OwnedByLifetimeScope,
new[] { service },
new Dictionary<string, object>());

return new IComponentRegistration[] { registration };
}

public bool IsAdapterForIndividualComponents => false;
}
9 changes: 7 additions & 2 deletions src/Nethermind/Nethermind.Consensus.AuRa/AuRaPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Autofac;
using Nethermind.Api;
using Nethermind.Api.Extensions;
using Nethermind.Config;
Expand All @@ -12,6 +13,7 @@
using Nethermind.Logging;
using Nethermind.Serialization.Json;
using Nethermind.Specs.ChainSpecStyle;
using Nethermind.Synchronization;

[assembly: InternalsVisibleTo("Nethermind.Merge.AuRa")]

Expand Down Expand Up @@ -49,13 +51,16 @@ public Task Init(INethermindApi nethermindApi)
return Task.CompletedTask;
}

public Task InitSynchronization()
public void ConfigureSynchronizationBuilder(ContainerBuilder containerBuilder)
{
if (_nethermindApi is not null)
{
_nethermindApi.BetterPeerStrategy = new AuRaBetterPeerStrategy(_nethermindApi.BetterPeerStrategy!, _nethermindApi.LogManager);
containerBuilder.RegisterDecorator<AuRaBetterPeerStrategy, IBetterPeerStrategy>();
}
}

public Task InitSynchronization(IContainer container)
{
return Task.CompletedTask;
}

Expand Down
12 changes: 12 additions & 0 deletions src/Nethermind/Nethermind.Core/ContainerBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ public static ContainerBuilder RegisterNamedComponentInItsOwnLifetime<T>(this Co

return builder;
}

/// <summary>
/// Shorthand for registering a constructor that resolve TImpl as TAs.
/// This is useful for clarity or for conditional registration where TImpl is declared somewhere else.
/// </summary>
public static ContainerBuilder Bind<TImpl, TAs>(this ContainerBuilder builder) where TImpl : notnull where TAs : notnull
{
builder.Register(ctx => ctx.Resolve<TImpl>())
.As<TAs>();

return builder;
}
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions src/Nethermind/Nethermind.Db/IDbProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ void ConfigureServiceCollection(ContainerBuilder sc)
var db = GetDb<IDb>(dbName);
sc.AddKeyedSingleton<IDb>(dbName, db);
sc.AddKeyedSingleton<IDbMeta>(dbName, db);
sc.AddKeyedSingleton<IReadOnlyKeyValueStore>(dbName, db);
if (db is ITunableDb tunableDb)
{
sc.AddKeyedSingleton<ITunableDb>(dbName, tunableDb);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class EthStatsPluginTests
[SetUp]
public void Setup()
{
_context = Build.ContextWithMocks();
_context = Build.ContextWithMocksWithTestContainer();
_plugin = new EthStatsPlugin();
}

Expand Down
Loading

0 comments on commit 9e4da92

Please sign in to comment.