-
Notifications
You must be signed in to change notification settings - Fork 258
Expand file tree
/
Copy pathNetworkService.cs
More file actions
430 lines (358 loc) · 14.3 KB
/
NetworkService.cs
File metadata and controls
430 lines (358 loc) · 14.3 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AElf.Kernel;
using AElf.Kernel.Consensus.Application;
using AElf.OS.Network.Helpers;
using AElf.OS.Network.Infrastructure;
using AElf.OS.Network.Types;
using AElf.Types;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.DependencyInjection;
namespace AElf.OS.Network.Application;
/// <summary>
/// Exposes networking functionality to the application handlers.
/// </summary>
public class NetworkService : INetworkService, ISingletonDependency
{
private readonly IBlackListedPeerProvider _blackListedPeerProvider;
private readonly IBroadcastPrivilegedPubkeyListProvider _broadcastPrivilegedPubkeyListProvider;
private readonly IAElfNetworkServer _networkServer;
private readonly IPeerPool _peerPool;
private readonly ITaskQueueManager _taskQueueManager;
public NetworkService(IPeerPool peerPool, ITaskQueueManager taskQueueManager, IAElfNetworkServer networkServer,
IBlackListedPeerProvider blackListedPeerProvider,
IBroadcastPrivilegedPubkeyListProvider broadcastPrivilegedPubkeyListProvider)
{
_peerPool = peerPool;
_taskQueueManager = taskQueueManager;
_networkServer = networkServer;
_broadcastPrivilegedPubkeyListProvider = broadcastPrivilegedPubkeyListProvider;
_blackListedPeerProvider = blackListedPeerProvider;
Logger = NullLogger<NetworkService>.Instance;
}
public ILogger<NetworkService> Logger { get; set; }
public async Task<bool> AddPeerAsync(string endpoint)
{
return await TryAddPeerAsync(endpoint, false);
}
/// <summary>
/// Add trusted peer, will remove the host from blacklist first.
/// </summary>
/// <param name="endpoint"></param>
/// <returns></returns>
public async Task<bool> AddTrustedPeerAsync(string endpoint)
{
return await TryAddPeerAsync(endpoint, true);
}
public async Task<bool> RemovePeerByEndpointAsync(string endpoint,
int removalSeconds = NetworkConstants.DefaultPeerRemovalSeconds)
{
if (!AElfPeerEndpointHelper.TryParse(endpoint, out var aelfPeerEndpoint))
return false;
var peer = _peerPool.FindPeerByEndpoint(aelfPeerEndpoint);
if (!await TryRemovePeerAsync(peer, removalSeconds))
{
Logger.LogWarning($"Remove peer failed. Peer address: {endpoint}");
return false;
}
return true;
}
public async Task<bool> RemovePeerByPubkeyAsync(string peerPubkey,
int removalSeconds = NetworkConstants.DefaultPeerRemovalSeconds)
{
var peer = _peerPool.FindPeerByPublicKey(peerPubkey);
if (!await TryRemovePeerAsync(peer, removalSeconds))
{
Logger.LogWarning($"Remove peer failed. Peer pubkey: {peerPubkey}");
return false;
}
return true;
}
public List<PeerInfo> GetPeers(bool includeFailing = true)
{
return _peerPool.GetPeers(includeFailing).Select(PeerInfoHelper.FromNetworkPeer).ToList();
}
public PeerInfo GetPeerByPubkey(string peerPubkey)
{
var peer = _peerPool.FindPeerByPublicKey(peerPubkey);
return peer == null ? null : PeerInfoHelper.FromNetworkPeer(peer);
}
public async Task BroadcastBlockWithTransactionsAsync(BlockWithTransactions blockWithTransactions)
{
if (IsOldBlock(blockWithTransactions.Header))
return;
var nextMinerPubkey = await GetNextMinerPubkey(blockWithTransactions.Header);
var nextPeer = _peerPool.FindPeerByPublicKey(nextMinerPubkey);
if (nextPeer != null)
EnqueueBlock(nextPeer, blockWithTransactions);
foreach (var peer in _peerPool.GetPeers())
{
if (nextPeer != null && peer.Info.Pubkey == nextPeer.Info.Pubkey)
continue;
EnqueueBlock(peer, blockWithTransactions);
}
}
public Task BroadcastAnnounceAsync(BlockHeader blockHeader)
{
var blockHash = blockHeader.GetHash();
if (IsOldBlock(blockHeader))
return Task.CompletedTask;
var blockAnnouncement = new BlockAnnouncement
{
BlockHash = blockHash,
BlockHeight = blockHeader.Height
};
foreach (var peer in _peerPool.GetPeers())
try
{
if (peer.KnowsBlock(blockHash))
continue; // block already known to this peer
peer.EnqueueAnnouncement(blockAnnouncement, async ex =>
{
peer.TryAddKnownBlock(blockHash);
if (ex != null)
{
Logger.LogInformation(ex, $"Could not broadcast announcement to {peer} " +
$"- status {peer.ConnectionStatus}.");
await HandleNetworkExceptionAsync(peer, ex);
}
});
}
catch (NetworkException ex)
{
Logger.LogWarning(ex, $"Could not enqueue announcement to {peer} " +
$"- status {peer.ConnectionStatus}.");
}
return Task.CompletedTask;
}
public Task BroadcastTransactionAsync(Transaction transaction)
{
var txHash = transaction.GetHash();
foreach (var peer in _peerPool.GetPeers())
try
{
if (peer.KnowsTransaction(txHash))
continue; // transaction already known to this peer
peer.EnqueueTransaction(transaction, async ex =>
{
if (ex != null)
{
Logger.LogWarning(ex, $"Could not broadcast transaction to {peer} " +
$"- status {peer.ConnectionStatus}.");
await HandleNetworkExceptionAsync(peer, ex);
}
});
}
catch (NetworkException ex)
{
Logger.LogWarning(ex, $"Could not enqueue transaction to {peer} - " +
$"status {peer.ConnectionStatus}.");
}
return Task.CompletedTask;
}
public Task BroadcastLibAnnounceAsync(Hash libHash, long libHeight)
{
var announce = new LibAnnouncement
{
LibHash = libHash,
LibHeight = libHeight
};
foreach (var peer in _peerPool.GetPeers())
try
{
peer.EnqueueLibAnnouncement(announce, async ex =>
{
if (ex != null)
{
Logger.LogWarning(ex, $"Could not broadcast lib announcement to {peer} " +
$"- status {peer.ConnectionStatus}.");
await HandleNetworkExceptionAsync(peer, ex);
}
});
}
catch (NetworkException ex)
{
Logger.LogWarning(ex, $"Could not enqueue lib announcement to {peer} " +
$"- status {peer.ConnectionStatus}.");
}
return Task.CompletedTask;
}
public async Task CheckPeersHealthAsync()
{
foreach (var peer in _peerPool.GetPeers(true))
{
Logger.LogDebug($"Health checking: {peer}");
if (peer.IsInvalid)
{
_peerPool.RemovePeer(peer.Info.Pubkey);
await peer.DisconnectAsync(false);
Logger.LogInformation($"Remove invalid peer: {peer}");
continue;
}
try
{
await peer.CheckHealthAsync();
}
catch (NetworkException ex)
{
if (ex.ExceptionType == NetworkExceptionType.Unrecoverable
|| ex.ExceptionType == NetworkExceptionType.PeerUnstable)
{
Logger.LogInformation(ex, $"Removing unhealthy peer {peer}.");
await _networkServer.TrySchedulePeerReconnectionAsync(peer);
}
}
}
}
public void CheckNtpDrift()
{
_networkServer.CheckNtpDrift();
}
public async Task<Response<List<BlockWithTransactions>>> GetBlocksAsync(Hash previousBlock, int count,
string peerPubkey)
{
var peer = _peerPool.FindPeerByPublicKey(peerPubkey);
if (peer == null)
throw new InvalidOperationException($"Could not find peer {peerPubkey}.");
var response = await Request(peer, p => p.GetBlocksAsync(previousBlock, count));
if (response.Success && response.Payload != null
&& (response.Payload.Count == 0 || response.Payload.Count != count))
Logger.LogDebug($"Requested blocks from {peer} - count miss match, " +
$"asked for {count} but got {response.Payload.Count} (from {previousBlock})");
return response;
}
public async Task<Response<BlockWithTransactions>> GetBlockByHashAsync(Hash hash, string peerPubkey)
{
var peer = _peerPool.FindPeerByPublicKey(peerPubkey);
if (peer == null)
throw new InvalidOperationException($"Could not find peer {peerPubkey}.");
Logger.LogDebug($"Getting block by hash, hash: {hash} from {peer}.");
return await Request(peer, p => p.GetBlockByHashAsync(hash));
}
public bool IsPeerPoolFull()
{
return _peerPool.IsFull();
}
private async Task<bool> TryAddPeerAsync(string endpoint, bool isTrusted)
{
if (!AElfPeerEndpointHelper.TryParse(endpoint, out var aelfPeerEndpoint))
{
Logger.LogDebug($"Could not parse endpoint {endpoint}.");
return false;
}
if (isTrusted)
_blackListedPeerProvider.RemoveHostFromBlackList(aelfPeerEndpoint.Host);
return await _networkServer.ConnectAsync(aelfPeerEndpoint);
}
/// <summary>
/// Try remove the peer, put the peer to blacklist, and disconnect.
/// </summary>
/// <param name="peer"></param>
/// <param name="removalSeconds"></param>
/// <returns>If the peer is null, return false.</returns>
private async Task<bool> TryRemovePeerAsync(IPeer peer, int removalSeconds)
{
if (peer == null) return false;
_blackListedPeerProvider.AddHostToBlackList(peer.RemoteEndpoint.Host, removalSeconds);
Logger.LogDebug($"Blacklisted {peer.RemoteEndpoint.Host} ({peer.Info.Pubkey})");
await _networkServer.DisconnectAsync(peer);
return true;
}
private bool IsOldBlock(BlockHeader header)
{
var limit = TimestampHelper.GetUtcNow()
- TimestampHelper.DurationFromMinutes(NetworkConstants.DefaultMaxBlockAgeToBroadcastInMinutes);
if (header.Time < limit)
return true;
return false;
}
private void EnqueueBlock(IPeer peer, BlockWithTransactions blockWithTransactions)
{
try
{
var blockHash = blockWithTransactions.GetHash();
if (peer.KnowsBlock(blockHash))
return; // block already known to this peer
peer.EnqueueBlock(blockWithTransactions, async ex =>
{
peer.TryAddKnownBlock(blockHash);
if (ex != null)
{
Logger.LogWarning(ex, $"Could not broadcast block to {peer} - status {peer.ConnectionStatus}.");
await HandleNetworkExceptionAsync(peer, ex);
}
});
}
catch (NetworkException ex)
{
Logger.LogWarning(ex, $"Could not enqueue block to {peer} - status {peer.ConnectionStatus}.");
}
}
private async Task<string> GetNextMinerPubkey(BlockHeader blockHeader)
{
var broadcastList = await _broadcastPrivilegedPubkeyListProvider.GetPubkeyList(blockHeader);
return broadcastList.IsNullOrEmpty() ? null : broadcastList[0];
}
private async Task<Response<T>> Request<T>(IPeer peer, Func<IPeer, Task<T>> func) where T : class
{
try
{
return new Response<T>(await func(peer));
}
catch (NetworkException ex)
{
Logger.LogWarning(ex, $"Request failed from {peer.RemoteEndpoint}.");
if (ex.ExceptionType == NetworkExceptionType.HandlerException)
return new Response<T>(default);
await HandleNetworkExceptionAsync(peer, ex);
}
return new Response<T>();
}
public async Task<List<NodeInfo>> GetNodesAsync(IPeer peer)
{
try
{
var nodeList = await peer.GetNodesAsync();
if (nodeList?.Nodes == null)
return new List<NodeInfo>();
Logger.LogDebug("get nodes: {nodeList} from peer: {peer}.", nodeList, peer);
return nodeList.Nodes.ToList();
}
catch (Exception e)
{
if (e is NetworkException exception) await HandleNetworkExceptionAsync(peer, exception);
Logger.LogWarning(e, "get nodes failed. peer={peer}", peer);
return new List<NodeInfo>();
}
}
private async Task HandleNetworkExceptionAsync(IPeer peer, NetworkException exception)
{
if (exception.ExceptionType == NetworkExceptionType.Unrecoverable)
{
Logger.LogInformation(exception, $"Removing unrecoverable {peer}.");
await _networkServer.TrySchedulePeerReconnectionAsync(peer);
}
else if (exception.ExceptionType == NetworkExceptionType.PeerUnstable)
{
Logger.LogDebug(exception, $"Queuing peer for reconnection {peer.RemoteEndpoint}.");
QueueNetworkTask(async () => await RecoverPeerAsync(peer));
}
}
private async Task RecoverPeerAsync(IPeer peer)
{
if (peer.IsReady) // peer recovered already
return;
var success = await peer.TryRecoverAsync();
if (success)
await _networkServer.BuildStreamForPeerAsync(peer);
else
await _networkServer.TrySchedulePeerReconnectionAsync(peer);
}
private void QueueNetworkTask(Func<Task> task)
{
_taskQueueManager.Enqueue(task, NetworkConstants.PeerReconnectionQueueName);
}
}