-
Notifications
You must be signed in to change notification settings - Fork 393
/
DiscoveryManager.cs
336 lines (294 loc) · 14.8 KB
/
DiscoveryManager.cs
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Config;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Logging;
using Nethermind.Network.Config;
using Nethermind.Network.Discovery.Lifecycle;
using Nethermind.Network.Discovery.Messages;
using Nethermind.Network.Discovery.RoutingTable;
using Nethermind.Stats.Model;
namespace Nethermind.Network.Discovery
{
public class DiscoveryManager : IDiscoveryManager
{
private readonly IDiscoveryConfig _discoveryConfig;
private readonly ILogger _logger;
private readonly INodeLifecycleManagerFactory _nodeLifecycleManagerFactory;
private readonly ConcurrentDictionary<Keccak, INodeLifecycleManager> _nodeLifecycleManagers = new ConcurrentDictionary<Keccak, INodeLifecycleManager>();
private readonly INodeTable _nodeTable;
private readonly INetworkStorage _discoveryStorage;
private readonly IIPResolver _ipResolver;
private readonly ConcurrentDictionary<MessageTypeKey, TaskCompletionSource<DiscoveryMessage>> _waitingEvents = new ConcurrentDictionary<MessageTypeKey, TaskCompletionSource<DiscoveryMessage>>();
private IMessageSender _messageSender;
public DiscoveryManager(
INodeLifecycleManagerFactory nodeLifecycleManagerFactory,
INodeTable nodeTable,
INetworkStorage discoveryStorage,
IDiscoveryConfig discoveryConfig,
ILogManager logManager,
IIPResolver ipResolver)
{
_logger = logManager.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
_discoveryConfig = discoveryConfig ?? throw new ArgumentNullException(nameof(discoveryConfig));
_nodeLifecycleManagerFactory = nodeLifecycleManagerFactory ?? throw new ArgumentNullException(nameof(nodeLifecycleManagerFactory));
_nodeTable = nodeTable ?? throw new ArgumentNullException(nameof(nodeTable));
_discoveryStorage = discoveryStorage ?? throw new ArgumentNullException(nameof(discoveryStorage));
_nodeLifecycleManagerFactory.DiscoveryManager = this;
_ipResolver = ipResolver;
}
public IMessageSender MessageSender
{
set => _messageSender = value;
}
public void OnIncomingMessage(DiscoveryMessage message)
{
try
{
if (_logger.IsTrace) _logger.Trace($"Received msg: {message}");
MessageType msgType = message.MessageType;
Node node = new Node(message.FarPublicKey, message.FarAddress);
INodeLifecycleManager nodeManager = GetNodeLifecycleManager(node);
if (nodeManager == null)
{
return;
}
if (message is PingMessage pingMessage)
{
if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportIncomingMessage(pingMessage.FarAddress.Address.MapToIPv4().ToString(), "MANAGER disc v4", $"Ping {pingMessage.SourceAddress.Address} -> {pingMessage.DestinationAddress.Address}");
}
else
{
if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportIncomingMessage(message.FarAddress.Address.MapToIPv4().ToString(), "MANAGER disc v4", message.MessageType.ToString());
}
switch (msgType)
{
case MessageType.Neighbors:
nodeManager.ProcessNeighborsMessage(message as NeighborsMessage);
break;
case MessageType.Pong:
nodeManager.ProcessPongMessage(message as PongMessage);
break;
case MessageType.Ping:
PingMessage ping = message as PingMessage;
if (ValidatePingAddress(ping))
{
nodeManager.ProcessPingMessage(ping);
}
break;
case MessageType.FindNode:
nodeManager.ProcessFindNodeMessage(message as FindNodeMessage);
break;
default:
_logger.Error($"Unsupported msgType: {msgType}");
return;
}
NotifySubscribersOnMsgReceived(msgType, nodeManager.ManagedNode, message);
CleanUpLifecycleManagers();
}
catch (Exception e)
{
_logger.Error("Error during msg handling", e);
}
}
private int _managersCreated = 0;
public INodeLifecycleManager GetNodeLifecycleManager(Node node, bool isPersisted = false)
{
if (_nodeTable.MasterNode.Equals(node))
{
return null;
}
if (node.Port == 0)
{
if (_logger.IsDebug) _logger.Debug($"Node is not listening - Port 0, blocking add to discovery, id: {node.Id}");
return null;
}
return _nodeLifecycleManagers.GetOrAdd(node.IdHash, x =>
{
Interlocked.Increment(ref _managersCreated);
INodeLifecycleManager manager = _nodeLifecycleManagerFactory.CreateNodeLifecycleManager(node);
if (!isPersisted)
{
_discoveryStorage.UpdateNodes(new[] {new NetworkNode(manager.ManagedNode.Id, manager.ManagedNode.Host, manager.ManagedNode.Port, manager.NodeStats.NewPersistedNodeReputation)});
}
OnNewNode(manager);
return manager;
});
}
public void SendMessage(DiscoveryMessage discoveryMessage)
{
if (_logger.IsTrace) _logger.Trace($"Sending msg: {discoveryMessage}");
try
{
if (discoveryMessage is PingMessage pingMessage)
{
if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportOutgoingMessage(pingMessage.FarAddress.Address.MapToIPv4().ToString(), "HANDLER disc v4", $"Ping {pingMessage.SourceAddress.Address} -> {pingMessage.DestinationAddress.Address}");
}
else
{
if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportOutgoingMessage(discoveryMessage.FarAddress.Address.MapToIPv4().ToString(), "HANDLER disc v4", discoveryMessage.MessageType.ToString());
}
_messageSender.SendMessage(discoveryMessage);
}
catch (Exception e)
{
_logger.Error($"Error during sending message: {discoveryMessage}", e);
}
}
public async Task<bool> WasMessageReceived(Keccak senderIdHash, MessageType messageType, int timeout)
{
TaskCompletionSource<DiscoveryMessage> completionSource = GetCompletionSource(senderIdHash, (int) messageType);
CancellationTokenSource delayCancellation = new CancellationTokenSource();
Task firstTask = await Task.WhenAny(completionSource.Task, Task.Delay(timeout, delayCancellation.Token));
bool result = firstTask == completionSource.Task;
if (result)
{
delayCancellation.Cancel();
}
else
{
RemoveCompletionSource(senderIdHash, (int) messageType);
}
return result;
}
public event EventHandler<NodeEventArgs> NodeDiscovered;
public IReadOnlyCollection<INodeLifecycleManager> GetNodeLifecycleManagers()
{
return _nodeLifecycleManagers.Values.ToArray();
}
public IReadOnlyCollection<INodeLifecycleManager> GetOrAddNodeLifecycleManagers(Func<INodeLifecycleManager, bool> query)
{
return _nodeLifecycleManagers.Values.Where(query.Invoke).ToArray();
}
private bool ValidatePingAddress(PingMessage message)
{
if (message.DestinationAddress == null || message.FarAddress == null)
{
if (_logger.IsDebug) _logger.Debug($"Received a ping message with empty address, message: {message}");
return false;
}
#region
// port will be different as we dynamically open ports for each socket connection
// if (_nodeTable.MasterNode.Port != message.DestinationAddress?.Port)
// {
// throw new NetworkingException($"Received message with incorrect destination port, message: {message}", NetworkExceptionType.Discovery);
// }
// either an old Nethermind or other nodes that make the same mistake
// if (!Bytes.AreEqual(message.FarAddress?.Address.MapToIPv6().GetAddressBytes(), message.SourceAddress?.Address.MapToIPv6().GetAddressBytes()))
// {
// // there is no sense to complain here as nodes sent a lot of garbage as their source addresses
// // if (_logger.IsWarn) _logger.Warn($"Received message with incorrect source address {message.SourceAddress}, message: {message}");
// }
// if (message.FarAddress?.Port != message.SourceAddress?.Port)
// {
// // there is no sense to complain here as nodes sent a lot of garbage as their source addresses
// // if (_logger.IsWarn) _logger.Warn($"TRACE/WARN Received a message with incorrect source port, message: {message}");
// }
#endregion
return true;
}
private void OnNewNode(INodeLifecycleManager manager)
{
NodeDiscovered?.Invoke(this, new NodeEventArgs(manager.ManagedNode));
}
private void NotifySubscribersOnMsgReceived(MessageType msgType, Node node, DiscoveryMessage message)
{
TaskCompletionSource<DiscoveryMessage> completionSource = RemoveCompletionSource(node.IdHash, (int) msgType);
completionSource?.TrySetResult(message);
}
private TaskCompletionSource<DiscoveryMessage> GetCompletionSource(Keccak senderAddressHash, int messageType)
{
MessageTypeKey key = new MessageTypeKey(senderAddressHash, messageType);
TaskCompletionSource<DiscoveryMessage> completionSource = _waitingEvents.GetOrAdd(key, new TaskCompletionSource<DiscoveryMessage>());
return completionSource;
}
private TaskCompletionSource<DiscoveryMessage> RemoveCompletionSource(Keccak senderAddressHash, int messageType)
{
MessageTypeKey key = new MessageTypeKey(senderAddressHash, messageType);
return _waitingEvents.TryRemove(key, out TaskCompletionSource<DiscoveryMessage> completionSource) ? completionSource : null;
}
private void CleanUpLifecycleManagers()
{
if (_nodeLifecycleManagers.Count <= _discoveryConfig.MaxNodeLifecycleManagersCount)
{
return;
}
int cleanupCount = _discoveryConfig.NodeLifecycleManagersCleanupCount;
KeyValuePair<Keccak, INodeLifecycleManager>[] activeExcluded = _nodeLifecycleManagers.Where(x => x.Value.State == NodeLifecycleState.ActiveExcluded).Take(cleanupCount).ToArray();
if (activeExcluded.Length == cleanupCount)
{
int removeCounter = RemoveManagers(activeExcluded, activeExcluded.Length);
if (_logger.IsTrace) _logger.Trace($"Removed: {removeCounter} activeExcluded node lifecycle managers");
return;
}
KeyValuePair<Keccak, INodeLifecycleManager>[] unreachable = _nodeLifecycleManagers.Where(x => x.Value.State == NodeLifecycleState.Unreachable).Take(cleanupCount - activeExcluded.Length).ToArray();
int removeCount = RemoveManagers(activeExcluded, activeExcluded.Length);
removeCount = removeCount + RemoveManagers(unreachable, unreachable.Length);
if (_logger.IsTrace) _logger.Trace($"Removed: {removeCount} unreachable node lifecycle managers");
}
private int RemoveManagers(KeyValuePair<Keccak, INodeLifecycleManager>[] items, int count)
{
int removeCount = 0;
for (int i = 0; i < count; i++)
{
KeyValuePair<Keccak, INodeLifecycleManager> item = items[i];
if (_nodeLifecycleManagers.TryRemove(item.Key, out _))
{
_discoveryStorage.RemoveNodes(new[] {new NetworkNode(item.Value.ManagedNode.Id, item.Value.ManagedNode.Host, item.Value.ManagedNode.Port, item.Value.NodeStats.NewPersistedNodeReputation),});
removeCount++;
}
}
return removeCount;
}
private struct MessageTypeKey : IEquatable<MessageTypeKey>
{
public Keccak SenderAddressHash { get; }
public int MessageType { get; }
public MessageTypeKey(Keccak senderAddressHash, int messageType)
{
SenderAddressHash = senderAddressHash;
MessageType = messageType;
}
public bool Equals(MessageTypeKey other)
{
return SenderAddressHash.Equals(other.SenderAddressHash) && MessageType == other.MessageType;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is MessageTypeKey key && Equals(key);
}
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
unchecked
{
return ((SenderAddressHash != null ? SenderAddressHash.GetHashCode() : 0) * 397) ^ MessageType;
}
}
}
}
}