-
Notifications
You must be signed in to change notification settings - Fork 711
Expand file tree
/
Copy pathInitializeNetwork.cs
More file actions
296 lines (250 loc) · 10.5 KB
/
Copy pathInitializeNetwork.cs
File metadata and controls
296 lines (250 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// SPDX-FileCopyrightText: 2025 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Threading;
using System.Threading.Tasks;
using Autofac.Features.AttributeFilters;
using Nethermind.Api;
using Nethermind.Api.Extensions;
using Nethermind.Api.Steps;
using Nethermind.Blockchain.Synchronization;
using Nethermind.Core;
using Nethermind.Core.Exceptions;
using Nethermind.Db;
using Nethermind.Logging;
using Nethermind.Network;
using Nethermind.Network.Config;
using Nethermind.Network.Contract.P2P;
using Nethermind.Network.Discovery;
using Nethermind.Network.P2P.ProtocolHandlers;
using Nethermind.Stats;
using Nethermind.Stats.Model;
using Nethermind.Synchronization;
using Nethermind.Synchronization.Peers;
namespace Nethermind.Init.Steps;
public static class NettyMemoryEstimator
{
private const uint PageSize = 8192;
public static void SetPageSize() =>
// For some reason needs to be half page size to get page size
Environment.SetEnvironmentVariable("io.netty.allocator.pageSize", (PageSize / 2).ToString((IFormatProvider?)null));
public static long Estimate(uint arenaCount, int arenaOrder) => arenaCount * (1L << arenaOrder) * PageSize;
}
[RunnerStepDependencies(
typeof(LoadGenesisBlock),
typeof(SetupKeyStore),
typeof(InitializePlugins),
typeof(InitializeBlockchain))]
#pragma warning disable IDE0290 // Primary constructor would shadow discard `_` used in fire-and-forget patterns
public class InitializeNetwork : IStep
{
protected readonly IApiWithNetwork _api;
protected readonly INodeStatsManager NodeStatsManager;
protected readonly ISynchronizer _synchronizer;
protected readonly ISyncPeerPool _syncPeerPool;
protected readonly IDiscoveryApp _discoveryApp;
protected readonly Lazy<IPeerPool> _peerPool;
protected readonly INetworkStorage _peerStorage;
protected readonly INetworkConfig _networkConfig;
private readonly NodeSourceToDiscV4Feeder _enrDiscoveryAppFeeder;
private readonly ISyncConfig _syncConfig;
private readonly IInitConfig _initConfig;
protected readonly IProtocolHandlerFactory[] _protocolHandlerFactories;
private readonly ILogger _logger;
public InitializeNetwork(
INethermindApi api,
INodeStatsManager nodeStatsManager,
ISyncServer _, // Need to be resolved at least once
ISynchronizer synchronizer,
ISyncPeerPool syncPeerPool,
NodeSourceToDiscV4Feeder enrDiscoveryAppFeeder,
IDiscoveryApp discoveryApp,
Lazy<IPeerPool> peerPool, // Require IRlpxPeer to be created first, hence, lazy.
[KeyFilter(DbNames.PeersDb)] INetworkStorage peerStorage,
IProtocolHandlerFactory[] protocolHandlerFactories,
INetworkConfig networkConfig,
ISyncConfig syncConfig,
IInitConfig initConfig,
ILogManager logManager
)
{
_api = api;
NodeStatsManager = nodeStatsManager;
_synchronizer = synchronizer;
_syncPeerPool = syncPeerPool;
_enrDiscoveryAppFeeder = enrDiscoveryAppFeeder;
_discoveryApp = discoveryApp;
_peerPool = peerPool;
_peerStorage = peerStorage;
_protocolHandlerFactories = protocolHandlerFactories;
_networkConfig = networkConfig;
_syncConfig = syncConfig;
_initConfig = initConfig;
_logger = logManager.GetClassLogger<InitializeNetwork>();
}
public virtual Task Execute(CancellationToken cancellationToken) => Initialize(cancellationToken);
private async Task Initialize(CancellationToken cancellationToken)
{
if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree));
if (_syncConfig.StaticSnapPivot)
{
if (!_syncConfig.SnapSync)
throw new InvalidConfigurationException("Sync.StaticSnapPivot requires Sync.SnapSync to be enabled.", -1);
if (_syncConfig.PivotNumber <= 0 || string.IsNullOrWhiteSpace(_syncConfig.PivotHash))
throw new InvalidConfigurationException("Sync.StaticSnapPivot requires Sync.PivotNumber and Sync.PivotHash to be set to the target (frozen) pivot block.", -1);
}
if (_networkConfig.DiagTracerEnabled)
{
NetworkDiagTracer.IsEnabled = true;
}
if (NetworkDiagTracer.IsEnabled)
{
NetworkDiagTracer.Start(_api.LogManager);
}
int maxPeersCount = _networkConfig.ActivePeersMaxCount;
Network.Metrics.PeerLimit = maxPeersCount;
if (cancellationToken.IsCancellationRequested)
{
return;
}
await InitPeer().ContinueWith(initPeerTask =>
{
if (initPeerTask.IsFaulted)
{
_logger.Error("Unable to init the peer manager.", initPeerTask.Exception);
}
});
if (_syncConfig.SnapSync && _syncConfig.SnapServingEnabled != true)
{
SnapCapabilitySwitcher snapCapabilitySwitcher =
new(_api.ProtocolsManager, _api.SyncModeSelector, _api.LogManager);
_api.DisposeStack.Push(snapCapabilitySwitcher);
snapCapabilitySwitcher.EnableSnapCapabilityUntilSynced();
}
else if (_logger.IsDebug) _logger.Debug("Skipped enabling snap capability");
if (cancellationToken.IsCancellationRequested)
{
return;
}
await StartSync().ContinueWith(initNetTask =>
{
if (initNetTask.IsFaulted)
{
_logger.Error("Unable to start the synchronizer.", initNetTask.Exception);
}
});
if (cancellationToken.IsCancellationRequested)
{
return;
}
await StartDiscovery().ContinueWith(initDiscoveryTask =>
{
if (initDiscoveryTask.IsFaulted)
{
_logger.Error("Unable to start the discovery protocol.", initDiscoveryTask.Exception);
}
});
try
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
StartPeer();
}
catch (Exception e)
{
_logger.Error("Unable to start the peer manager.", e);
}
if (_api.Enode is null)
{
throw new InvalidOperationException("Cannot initialize network without knowing own enode");
}
ProductInfo.InitializePublicClientId(_networkConfig.PublicClientIdFormat);
ThisNodeInfo.AddInfo("Ethereum :", $"tcp://{_api.Enode.HostIp}:{_api.Enode.Port} ");
ThisNodeInfo.AddInfo("Client id :", ProductInfo.ClientId);
ThisNodeInfo.AddInfo("Public id :", ProductInfo.PublicClientId);
ThisNodeInfo.AddInfo("This node :", $"{_api.Enode.Info} ");
ThisNodeInfo.AddInfo("Node address :", $"{_api.Enode.Address} (do not use as an account)");
}
private Task StartDiscovery()
{
if (!_initConfig.DiscoveryEnabled)
{
if (_logger.IsWarn) _logger.Warn($"Skipping discovery init due to {nameof(IInitConfig.DiscoveryEnabled)} set to false");
return Task.CompletedTask;
}
if (_logger.IsDebug) _logger.Debug("Starting discovery process.");
_ = _discoveryApp.StartAsync();
if (_logger.IsDebug) _logger.Debug("Discovery process started.");
return Task.CompletedTask;
}
private void StartPeer()
{
if (_api.PeerManager is null) throw new StepDependencyException(nameof(_api.PeerManager));
if (_api.SessionMonitor is null) throw new StepDependencyException(nameof(_api.SessionMonitor));
if (!_api.Config<IInitConfig>().PeerManagerEnabled)
{
if (_logger.IsWarn) _logger.Warn($"Skipping peer manager init due to {nameof(IInitConfig.PeerManagerEnabled)} set to false");
}
if (_logger.IsDebug) _logger.Debug("Initializing peer manager");
_peerPool.Value.Start();
_api.PeerManager.Start();
_api.SessionMonitor.Start();
if (_logger.IsDebug) _logger.Debug("Peer manager initialization completed");
}
private Task StartSync()
{
if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree));
if (_syncConfig.NetworkingEnabled)
{
_syncPeerPool.Start();
if (_syncConfig.SynchronizationEnabled)
{
if (_logger.IsDebug) _logger.Debug($"Starting synchronization from block {_api.BlockTree.Head?.Header.ToString(BlockHeader.Format.Short)}.");
_synchronizer.Start();
}
else
{
if (_logger.IsWarn) _logger.Warn($"Skipping blockchain synchronization init due to {nameof(ISyncConfig.SynchronizationEnabled)} set to false");
}
}
else if (_logger.IsWarn) _logger.Warn($"Skipping connecting to peers due to {nameof(ISyncConfig.NetworkingEnabled)} set to false");
return Task.CompletedTask;
}
protected virtual async Task InitPeer()
{
if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree));
if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider));
if (_api.TxPool is null) throw new StepDependencyException(nameof(_api.TxPool));
_api.ProtocolsManager = CreateProtocolManager();
if (_syncConfig.SnapServingEnabled == true)
{
_api.ProtocolsManager!.AddSupportedCapability(new Capability(Protocol.Snap, 1));
}
if (!_networkConfig.DisableDiscV4DnsFeeder)
{
// Feed some nodes into discoveryApp in case all bootnodes is faulty.
_ = _enrDiscoveryAppFeeder.Run();
}
foreach (INethermindPlugin plugin in _api.Plugins)
{
await plugin.InitNetworkProtocol();
}
// Capabilities must be finalized before the RLPx listener accepts peers. Otherwise
// early sessions can negotiate only the default ETH version and never upgrade.
await _api.RlpxPeer.Init();
await _api.StaticNodesManager.InitAsync();
await _api.TrustedNodesManager.InitAsync();
}
protected virtual IProtocolsManager CreateProtocolManager() => new ProtocolsManager(
_api.SyncPeerPool!,
_api.TxPool!,
_discoveryApp,
_api.RlpxPeer,
NodeStatsManager,
_api.ProtocolValidator,
_peerStorage,
_protocolHandlerFactories,
_api.LogManager);
}