-
Notifications
You must be signed in to change notification settings - Fork 138
/
Swarm.cs
2537 lines (2266 loc) · 93.8 KB
/
Swarm.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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Async;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using AsyncIO;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Blockchain;
using Libplanet.Blocks;
using Libplanet.Crypto;
using Libplanet.Net.Messages;
using Libplanet.Net.Protocols;
using Libplanet.Store;
using Libplanet.Stun;
using Libplanet.Tx;
using NetMQ;
using NetMQ.Sockets;
using Nito.AsyncEx;
using Serilog;
using Serilog.Events;
namespace Libplanet.Net
{
public class Swarm<T> : ISwarm, IDisposable
where T : IAction, new()
{
private static readonly TimeSpan TurnAllocationLifetime =
TimeSpan.FromSeconds(777);
// TURN Permission lifetime was defined in RFC 5766
// see also https://tools.ietf.org/html/rfc5766#section-8
private static readonly TimeSpan TurnPermissionLifetime =
TimeSpan.FromMinutes(5);
private static readonly TimeSpan MaxTimeout = TimeSpan.FromSeconds(150);
private static readonly TimeSpan BlockRecvTimeout = TimeSpan.FromSeconds(15);
private static readonly TimeSpan TxRecvTimeout = TimeSpan.FromSeconds(3);
private static readonly TimeSpan RecentStateRecvTimeout = TimeSpan.FromSeconds(150);
private readonly PrivateKey _privateKey;
private readonly int _appProtocolVersion;
private readonly AsyncLock _runningMutex;
private readonly AsyncLock _blockSyncMutex;
private readonly string _host;
private readonly IList<IceServer> _iceServers;
private readonly ILogger _logger;
private RouterSocket _router;
private NetMQQueue<Message> _replyQueue;
private NetMQQueue<Message> _broadcastQueue;
private AsyncCollection<MessageRequest> _requests;
private NetMQPoller _poller;
private TaskCompletionSource<object> _runningEvent;
private int? _listenPort;
private TurnClient _turnClient;
private CancellationTokenSource _workerCancellationTokenSource;
private CancellationTokenSource _runtimeCancellationTokenSource;
private CancellationToken _cancellationToken;
private IPAddress _publicIPAddress;
private Task _runtimeProcessor;
private IStore _store;
static Swarm()
{
if (!(Type.GetType("Mono.Runtime") is null))
{
ForceDotNet.Force();
}
}
public Swarm(
BlockChain<T> blockChain,
PrivateKey privateKey,
int appProtocolVersion,
int workers = 5,
string host = null,
int? listenPort = null,
DateTimeOffset? createdAt = null,
IEnumerable<IceServer> iceServers = null,
EventHandler<DifferentProtocolVersionEventArgs>
differentVersionPeerEncountered = null)
: this(
blockChain,
privateKey,
appProtocolVersion,
null,
null,
workers,
host,
listenPort,
createdAt,
iceServers,
differentVersionPeerEncountered)
{
}
internal Swarm(
BlockChain<T> blockChain,
PrivateKey privateKey,
int appProtocolVersion,
int? tableSize,
int? bucketSize,
int workers = 5,
string host = null,
int? listenPort = null,
DateTimeOffset? createdAt = null,
IEnumerable<IceServer> iceServers = null,
EventHandler<DifferentProtocolVersionEventArgs> differentVersionPeerEncountered = null)
{
Running = false;
BlockChain = blockChain ?? throw new ArgumentNullException(nameof(blockChain));
_store = BlockChain.Store;
_privateKey = privateKey ?? throw new ArgumentNullException(nameof(privateKey));
LastSeenTimestamps =
new ConcurrentDictionary<Peer, DateTimeOffset>();
DateTimeOffset now = createdAt.GetValueOrDefault(
DateTimeOffset.UtcNow);
LastReceived = now;
TxReceived = new AsyncAutoResetEvent();
BlockAppended = new AsyncAutoResetEvent();
BlockReceived = new AsyncAutoResetEvent();
DifferentVersionPeerEncountered = differentVersionPeerEncountered;
_blockSyncMutex = new AsyncLock();
_runningMutex = new AsyncLock();
_host = host;
_listenPort = listenPort;
_appProtocolVersion = appProtocolVersion;
if (_host != null && _listenPort is int listenPortAsInt)
{
EndPoint = new DnsEndPoint(_host, listenPortAsInt);
}
_iceServers = iceServers?.ToList();
if (_host == null && (_iceServers == null || !_iceServers.Any()))
{
throw new ArgumentException(
$"Swarm requires either {nameof(host)} or " +
$"{nameof(iceServers)}."
);
}
string loggerId = _privateKey.PublicKey.ToAddress().ToHex();
_logger = Log.ForContext<Swarm<T>>()
.ForContext("SwarmId", loggerId);
Protocol = new KademliaProtocol(
this,
_privateKey.PublicKey.ToAddress(),
_appProtocolVersion,
_logger,
tableSize,
bucketSize);
_requests = new AsyncCollection<MessageRequest>();
_runtimeCancellationTokenSource = new CancellationTokenSource();
_runtimeProcessor = Task.Run(() =>
{
// Ignore NetMQ related exceptions during NetMQRuntime.Dispose() to stabilize tests
try
{
using (var runtime = new NetMQRuntime())
{
Task[] workerTasks = new Task[workers];
for (int i = 0; i < workers; i++)
{
workerTasks[i] = ProcessRuntime(_runtimeCancellationTokenSource.Token);
}
runtime.Run(workerTasks);
}
}
catch (NetMQException)
{
}
catch (ObjectDisposedException)
{
}
});
}
~Swarm()
{
// FIXME If possible, we should stop Swarm appropriately here.
if (Running)
{
_logger.Warning(
"Swarm is scheduled to destruct, but it's still running.");
}
}
/// <summary>
/// The <see cref="EventHandler" /> triggered when the different version of
/// <see cref="Peer" /> is discovered.
/// </summary>
public event EventHandler<DifferentProtocolVersionEventArgs>
DifferentVersionPeerEncountered;
public DnsEndPoint EndPoint { get; private set; }
public Address Address => _privateKey.PublicKey.ToAddress();
public Peer AsPeer => EndPoint is null
? new Peer(
_privateKey.PublicKey,
_appProtocolVersion,
_publicIPAddress)
: new BoundPeer(
_privateKey.PublicKey,
EndPoint,
_appProtocolVersion,
_publicIPAddress);
public DateTimeOffset LastReceived { get; private set; }
public IDictionary<Peer, DateTimeOffset> LastSeenTimestamps
{
get;
private set;
}
/// <summary>
/// The <see cref="BlockChain{T}"/> instance this <see cref="Swarm{T}"/> instance
/// synchronizes with.
/// </summary>
public BlockChain<T> BlockChain { get; private set; }
/// <summary>
/// Whether this <see cref="Swarm{T}"/> instance is running.
/// </summary>
public bool Running
{
get => _runningEvent.Task.Status == TaskStatus.RanToCompletion;
private set
{
if (value)
{
_runningEvent.TrySetResult(null);
}
else
{
_runningEvent = new TaskCompletionSource<object>();
}
}
}
internal AsyncAutoResetEvent TxReceived { get; }
internal AsyncAutoResetEvent BlockReceived { get; }
// FIXME: Should have a unit test.
internal AsyncAutoResetEvent BlockAppended { get; }
internal TimeSpan BlockHashRecvTimeout { get; set; } = TimeSpan.FromSeconds(30);
internal IEnumerable<BoundPeer> Peers => Protocol.Peers;
internal IProtocol Protocol { get; private set; }
// FIXME: We need some sort of configuration method for it.
internal int FindNextHashesChunkSize { get; set; } = 500;
internal int FindNextStatesChunkSize { get; set; } = 1000;
internal AsyncAutoResetEvent PreloadStarted { get; } = new AsyncAutoResetEvent();
internal AsyncAutoResetEvent FillBlocksAsyncStarted { get; } = new AsyncAutoResetEvent();
internal AsyncAutoResetEvent FillBlocksAsyncFailed { get; } = new AsyncAutoResetEvent();
/// <summary>
/// Waits until this <see cref="Swarm{T}"/> instance gets started to run.
/// </summary>
/// <returns>A <see cref="Task"/> completed when <see cref="Running"/>
/// property becomes <c>true</c>.</returns>
public Task WaitForRunningAsync() => _runningEvent.Task;
public void Dispose()
{
_runtimeCancellationTokenSource.Cancel();
_runtimeProcessor.Wait();
}
public async Task StopAsync(
CancellationToken cancellationToken = default(CancellationToken)
)
{
await StopAsync(TimeSpan.FromSeconds(1), cancellationToken);
}
public async Task StopAsync(
TimeSpan waitFor,
CancellationToken cancellationToken = default(CancellationToken)
)
{
_workerCancellationTokenSource?.Cancel();
_logger.Debug("Stopping...");
using (await _runningMutex.LockAsync())
{
if (Running)
{
await Task.Delay(waitFor, cancellationToken);
_broadcastQueue.ReceiveReady -= DoBroadcast;
_replyQueue.ReceiveReady -= DoReply;
_router.ReceiveReady -= ReceiveMessage;
if (_poller.IsRunning)
{
_poller.Dispose();
}
_broadcastQueue.Dispose();
_replyQueue.Dispose();
_router.Dispose();
_turnClient?.Dispose();
Running = false;
}
}
_logger.Debug("Stopped.");
}
public async Task StartAsync(
int millisecondsDialTimeout = 15000,
int millisecondsBroadcastTxInterval = 5000,
EventHandler<PreloadBlockDownloadFailEventArgs> preloadBlockDownloadFailed = null,
CancellationToken cancellationToken = default(CancellationToken))
{
await StartAsync(
TimeSpan.FromMilliseconds(millisecondsDialTimeout),
TimeSpan.FromMilliseconds(millisecondsBroadcastTxInterval),
preloadBlockDownloadFailed: preloadBlockDownloadFailed,
cancellationToken
);
}
/// <summary>
/// Starts to periodically synchronize the <see cref="BlockChain"/>.
/// </summary>
/// <param name="dialTimeout">
/// A timeout value for dialing.
/// </param>
/// <param name="broadcastTxInterval">The time period of exchange of staged transactions.
/// </param>
/// <param name="preloadBlockDownloadFailed">
/// The <see cref="EventHandler" /> triggered when
/// <see cref="PreloadAsync(TimeSpan?, IProgress{PreloadState}, IImmutableSet{Address},
/// EventHandler{PreloadBlockDownloadFailEventArgs}, CancellationToken)" />
/// fails to download blocks.
/// </param>
/// /// <param name="cancellationToken">
/// A cancellation token used to propagate notification that this
/// operation should be canceled.
/// </param>
/// <returns>An awaitable task without value.</returns>
/// <exception cref="SwarmException">Thrown when this <see cref="Swarm{T}"/> instance is
/// already <see cref="Running"/>.</exception>
/// <remarks>If the <see cref="BlockChain"/> has no blocks at all or there are long behind
/// blocks to caught in the network this method could lead to unexpected behaviors, because
/// this tries to <see cref="IAction.Render"/> <em>all</em> actions in the behind blocks
/// so that there are a lot of calls to <see cref="IAction.Render"/> method in a short
/// period of time. This can lead a game startup slow. If you want to omit rendering of
/// these actions in the behind blocks use <see cref=
/// "PreloadAsync(TimeSpan?, IProgress{PreloadState}, IImmutableSet{Address},
/// EventHandler{PreloadBlockDownloadFailEventArgs}, CancellationToken)"
/// /> method too.</remarks>
public async Task StartAsync(
TimeSpan dialTimeout,
TimeSpan broadcastTxInterval,
EventHandler<PreloadBlockDownloadFailEventArgs> preloadBlockDownloadFailed = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (Running)
{
throw new SwarmException("Swarm is already running.");
}
_router = new RouterSocket();
_router.Options.RouterHandover = true;
if (_host is null && !(_iceServers is null))
{
_turnClient = await IceServer.CreateTurnClient(_iceServers);
}
if (_listenPort == null)
{
_listenPort = _router.BindRandomPort("tcp://*");
}
else
{
_router.Bind($"tcp://*:{_listenPort}");
}
_logger.Information($"Listen on {_listenPort}");
_workerCancellationTokenSource = new CancellationTokenSource();
CancellationToken workerCancellationToken =
CancellationTokenSource.CreateLinkedTokenSource(
_workerCancellationTokenSource.Token, cancellationToken
).Token;
_cancellationToken = workerCancellationToken;
var tasks = new List<Task>();
var behindNAT = false;
if (!(_turnClient is null))
{
_publicIPAddress = (await _turnClient.GetMappedAddressAsync()).Address;
if (await _turnClient.IsBehindNAT())
{
behindNAT = true;
}
}
if (behindNAT)
{
IPEndPoint turnEp = await _turnClient.AllocateRequestAsync(
TurnAllocationLifetime
);
EndPoint = new DnsEndPoint(turnEp.Address.ToString(), turnEp.Port);
tasks.Add(BindingProxies(_cancellationToken));
tasks.Add(RefreshAllocate(_cancellationToken));
tasks.Add(RefreshPermissions(_cancellationToken));
}
else
{
EndPoint = new DnsEndPoint(_host, _listenPort.Value);
}
_replyQueue = new NetMQQueue<Message>();
_broadcastQueue = new NetMQQueue<Message>();
_poller = new NetMQPoller { _router, _replyQueue, _broadcastQueue };
_router.ReceiveReady += ReceiveMessage;
_replyQueue.ReceiveReady += DoReply;
_broadcastQueue.ReceiveReady += DoBroadcast;
_logger.Debug("Starting swarm...");
_logger.Debug("Peer information : {Peer}", AsPeer);
using (await _runningMutex.LockAsync())
{
await PreloadAsync(
dialTimeout: dialTimeout,
render: true,
cancellationToken: _cancellationToken
);
Running = true;
}
try
{
tasks.Add(BroadcastTxAsync(broadcastTxInterval, _cancellationToken));
tasks.Add(
RefreshTableAsync(
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(10),
_cancellationToken));
tasks.Add(RebuildConnectionAsync(TimeSpan.FromMinutes(30), _cancellationToken));
tasks.Add(
Task.Run(() =>
{
// Ignore NetMQ related exceptions during NetMQPoller.Run() to stabilize
// tests.
try
{
_poller.Run();
}
catch (TerminatingException)
{
_logger.Error($"TerminatingException occurred in {nameof(_poller)}");
}
catch (ObjectDisposedException)
{
_logger.Error($"ObjectDisposedException occurred in {nameof(_poller)}");
}
}));
_logger.Debug("Swarm started.");
await await Task.WhenAny(tasks);
}
catch (OperationCanceledException e)
{
_logger.Warning(e, $"{nameof(StartAsync)}() is canceled.");
throw;
}
catch (Exception e)
{
_logger.Error(
e,
$"An unexpected exception occurred during {nameof(StartAsync)}(): {e}"
);
throw;
}
}
public async Task BootstrapAsync(
IEnumerable<Peer> seedPeers,
double pingSeedTimeout,
double findPeerTimeout,
int depth = Kademlia.MaxDepth,
CancellationToken cancellationToken = default(CancellationToken))
{
await BootstrapAsync(
seedPeers,
TimeSpan.FromMilliseconds(pingSeedTimeout),
TimeSpan.FromMilliseconds(findPeerTimeout),
depth,
cancellationToken);
}
/// <summary>
/// Join to the peer-to-peer network using seed peers.
/// </summary>
/// <param name="seedPeers">List of seed peers.</param>
/// <param name="pingSeedTimeout">Timeout for connecting to seed peers.</param>
/// <param name="findNeighborsTimeout">Timeout for requesting neighbors.</param>
/// <param name="depth">Depth to find neighbors of current <see cref="Peer"/>
/// from seed peers.</param>
/// <param name="cancellationToken">A cancellation token used to propagate notification
/// that this operation should be canceled.</param>
/// <returns>An awaitable task without value.</returns>
/// <exception cref="SwarmException">Thrown when this <see cref="Swarm{T}"/> instance is
/// not <see cref="Running"/>.</exception>
public async Task BootstrapAsync(
IEnumerable<Peer> seedPeers,
TimeSpan? pingSeedTimeout,
TimeSpan? findNeighborsTimeout,
int depth = Kademlia.MaxDepth,
CancellationToken cancellationToken = default(CancellationToken))
{
if (seedPeers is null)
{
throw new ArgumentNullException(nameof(seedPeers));
}
IEnumerable<BoundPeer> peers = seedPeers.OfType<BoundPeer>();
await Protocol.BootstrapAsync(
peers.ToImmutableList(),
pingSeedTimeout,
findNeighborsTimeout,
depth,
cancellationToken);
}
public void BroadcastBlocks(IEnumerable<Block<T>> blocks)
{
_logger.Debug("Trying to broadcast blocks...");
var message = new BlockHashes(
Address,
blocks.Select(b => b.Hash)
);
BroadcastMessage(message);
_logger.Debug("Block broadcasting complete.");
}
public void BroadcastTxs(IEnumerable<Transaction<T>> txs)
{
_logger.Debug("Broadcast Txs.");
List<TxId> txIds = txs.Select(tx => tx.Id).ToList();
BroadcastTxIds(txIds);
}
public string TraceTable()
{
return Protocol is null ? string.Empty : Protocol.Trace();
}
async Task<Message> ISwarm.SendMessageWithReplyAsync(
BoundPeer peer,
Message message,
TimeSpan? timeout,
CancellationToken cancellationToken)
{
IEnumerable<Message> replies =
await SendMessageWithReplyAsync(peer, message, timeout, 1, cancellationToken);
Message reply = replies.First();
ValidateSender(reply.Remote);
return reply;
}
void ISwarm.ReplyMessage(Message message)
{
_replyQueue.Enqueue(message);
}
#pragma warning disable MEN002 // Line is too long
/// <summary>
/// Preemptively downloads blocks from registered <see cref="Peer"/>s.
/// </summary>
/// <param name="dialTimeout">
/// A timeout value for dialing.
/// </param>
/// <param name="progress">
/// An instance that receives progress updates for block downloads.
/// </param>
/// <param name="trustedStateValidators">
/// If any peer in this set is reachable and there are no built-up
/// blocks in a current node, <see cref="Swarm{T}"/> receives the latest
/// states of the major blockchain from that trusted peer,
/// which is also calculated by that peer, instead of autonomously
/// calculating the states from scratch. Note that this option is
/// intended to be exposed to end users through a feasible user
/// interface so that they can decide whom to trust for themselves.
/// </param>
/// <param name="blockDownloadFailed">
/// The <see cref="EventHandler" /> triggered when block downloading fails.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token used to propagate notification that this
/// operation should be canceled.
/// </param>
/// <returns>
/// A task without value.
/// You only can <c>await</c> until the method is completed.
/// </returns>
/// <remarks>This does not render downloaded <see cref="IAction"/>s, but fills states only.
/// If you want to render all <see cref="IAction"/>s from the genesis block to the recent
/// blocks use
/// <see cref="StartAsync(TimeSpan, TimeSpan, EventHandler{PreloadBlockDownloadFailEventArgs}, CancellationToken)"/>
/// method instead.</remarks>
/// <exception cref="AggregateException">Thrown when the given the block downloading is
/// failed and if <paramref name="blockDownloadFailed "/> is <c>null</c>.</exception>
#pragma warning restore MEN002 // Line is too long
public Task PreloadAsync(
TimeSpan? dialTimeout = null,
IProgress<PreloadState> progress = null,
IImmutableSet<Address> trustedStateValidators = null,
EventHandler<PreloadBlockDownloadFailEventArgs> blockDownloadFailed = null,
CancellationToken cancellationToken = default(CancellationToken)
)
{
return PreloadAsync(
render: false,
dialTimeout: dialTimeout,
progress: progress,
trustedStateValidators: trustedStateValidators,
blockDownloadFailed: blockDownloadFailed,
cancellationToken: cancellationToken
);
}
// FIXME: It is not guaranteed that states will be reported in order. see issue #436, #430
internal async Task PreloadAsync(
bool render,
TimeSpan? dialTimeout = null,
IProgress<PreloadState> progress = null,
IImmutableSet<Address> trustedStateValidators = null,
EventHandler<PreloadBlockDownloadFailEventArgs> blockDownloadFailed = null,
CancellationToken cancellationToken = default(CancellationToken)
)
{
trustedStateValidators = trustedStateValidators ?? ImmutableHashSet<Address>.Empty;
Block<T> initialTip = BlockChain.Tip;
BlockLocator initialLocator = BlockChain.GetBlockLocator();
_logger.Debug($"initialTip? : {BlockChain.Tip}");
IList<(BoundPeer, long?)> peersWithHeight =
await DialToExistingPeers(dialTimeout, cancellationToken)
.Where(pp => pp.Item2.TipIndex > (initialTip?.Index ?? -1))
.Select(pp => (pp.Item1, pp.Item2.TipIndex))
.ToListAsync(cancellationToken);
if (!peersWithHeight.Any())
{
_logger.Information("There is no appropriate peer for preloading.");
return;
}
PreloadStarted.Set();
// As preloading takes long, the blockchain data can corrupt if a program suddenly
// terminates during preloading is going on. In order to make preloading done
// all or nothing (i.e., atomic), we first fork the chain and stack up preloaded data
// upon that forked workspace, and then if preloading ends replace the existing
// blockchain with it.
BlockChain<T> workspace = initialTip is Block<T> tip
? BlockChain.Fork(tip.Hash)
: new BlockChain<T>(BlockChain.Policy, _store, Guid.NewGuid(), BlockChain.Genesis);
var complete = false;
try
{
var exceptions = new List<Exception>();
var blockDownloadComplete = false;
foreach ((BoundPeer Peer, long? Height) peerWithHeight in peersWithHeight)
{
try
{
_logger.Information(
"Try to download blocks from {EndPoint}@{Address}.",
peerWithHeight.Peer.EndPoint,
peerWithHeight.Peer.Address.ToHex());
await SyncBehindsBlocksFromPeerAsync(
workspace,
peerWithHeight,
progress,
cancellationToken,
render
);
}
catch (Exception e)
{
_logger.Error(
"Exception was thrown during downloading blocks from "
+ "{EndPoint}@{Address}.\n{Exception}",
peerWithHeight.Peer.EndPoint,
peerWithHeight.Peer.Address.ToHex(),
e);
exceptions.Add(e);
continue;
}
_logger.Information(
"Finished to download blocks from {EndPoint}@{Address}.",
peerWithHeight.Peer.EndPoint,
peerWithHeight.Peer.Address.ToHex());
blockDownloadComplete = true;
break;
}
if (!blockDownloadComplete)
{
if (blockDownloadFailed is null)
{
throw new AggregateException(
"Failed to download blocks from peers.",
exceptions);
}
else
{
blockDownloadFailed.Invoke(
this,
new PreloadBlockDownloadFailEventArgs { InnerExceptions = exceptions });
}
}
if (workspace.Tip is null)
{
// If there is no blocks in the network (or no consensus at least)
// it doesn't need to receive states from other peers at all.
return;
}
else if (render)
{
// If it's already rendered by SyncBehindsBlocksFromPeersAsync() method
// it means states are already calculated so that it does not need to receive
// calculated states from trusted peers.
complete = true;
return;
}
long height = workspace.Tip.Index;
IEnumerable<(BoundPeer, HashDigest<SHA256> Hash)> trustedPeersWithTip =
peersWithHeight.Where(pair =>
trustedStateValidators.Contains(pair.Item1.Address) &&
!(pair.Item2 is null) &&
pair.Item2 <= height)
.OrderByDescending(pair => pair.Item2)
.Select(pair => (pair.Item1, workspace[pair.Item2.Value].Hash));
bool received = await SyncRecentStatesFromTrustedPeersAsync(
workspace,
progress,
trustedPeersWithTip.ToImmutableList(),
initialLocator,
cancellationToken
);
if (!received)
{
long initHeight =
initialTip is null || !workspace[initialTip.Index].Equals(initialTip)
? 0
: initialTip.Index + 1;
int count = 0, totalCount = (int)(workspace.Count - initHeight);
_logger.Debug("Starts to execute actions of {0} blocks.", totalCount);
var blockHashes = workspace.IterateBlockHashes((int)initHeight);
foreach (HashDigest<SHA256> hash in blockHashes)
{
cancellationToken.ThrowIfCancellationRequested();
Block<T> block = workspace[hash];
if (block.Index < initHeight)
{
continue;
}
workspace.ExecuteActions(block);
_logger.Debug("Executed actions in the block {0}.", block.Hash);
progress?.Report(new ActionExecutionState()
{
TotalBlockCount = totalCount,
ExecutedBlockCount = ++count,
ExecutedBlockHash = block.Hash,
});
}
_logger.Debug("Finished to execute actions.");
}
complete = true;
}
finally
{
if (cancellationToken.IsCancellationRequested)
{
_logger.Information($"{nameof(PreloadAsync)}() is canceled.");
}
if (!complete
|| workspace.Tip == BlockChain.Tip
|| cancellationToken.IsCancellationRequested)
{
_logger.Debug(
"Preloading is aborted; delete the temporary working chain ({0}: {1}), " +
"and make the existing chain ({2}: {3}) remains.",
workspace.Id,
workspace.Tip,
BlockChain.Id,
BlockChain.Tip
);
_store.DeleteChainId(workspace.Id);
}
else
{
_logger.Debug(
"Preloading finished; replace the existing chain ({0}: {1}) with " +
"the working chain ({2}: {3}).",
BlockChain.Id,
BlockChain.Tip,
workspace.Id,
workspace.Tip
);
BlockChain.Swap(workspace, render: false);
}
cancellationToken.ThrowIfCancellationRequested();
}
}
internal async Task AddPeersAsync(
IEnumerable<Peer> peers,
TimeSpan? timeout,
CancellationToken cancellationToken = default(CancellationToken))
{
if (Protocol is null)
{
throw new ArgumentNullException(nameof(Protocol));
}
if (cancellationToken == default(CancellationToken))
{
cancellationToken = _cancellationToken;
}
try
{
KademliaProtocol kp = (KademliaProtocol)Protocol;
var tasks = new List<Task>();
foreach (Peer peer in peers)
{
if (peer is BoundPeer boundPeer)
{
tasks.Add(kp.PingAsync(
boundPeer,
timeout: timeout,
cancellationToken: cancellationToken));
}
}
_logger.Verbose("Trying to ping all {PeersNumber} peers.", tasks.Count);
await Task.WhenAll(tasks);
_logger.Verbose("Update complete.");
}
catch (DifferentAppProtocolVersionException)
{
_logger.Debug("Different version encountered during AddPeersAsync().");
}
catch (TimeoutException)
{
_logger.Debug(
$"Timeout occurred during {nameof(AddPeersAsync)}() after {timeout}.");
throw;
}
catch (TaskCanceledException)
{
_logger.Debug($"Task is cancelled during {nameof(AddPeersAsync)}().");
}
catch (Exception e)
{
_logger.Error(
e,
$"Unexpected exception occurred during {nameof(AddPeersAsync)}().");
throw;
}
}
internal async Task SendMessageAsync(BoundPeer peer, Message message)
{
await SendMessageWithReplyAsync(peer, message, TimeSpan.FromSeconds(3), 0);
}
internal virtual async Task<IEnumerable<Message>> SendMessageWithReplyAsync(
BoundPeer peer,
Message message,
TimeSpan? timeout,
int expectedResponses,
CancellationToken cancellationToken = default(CancellationToken)
)
{
if (!(_turnClient is null))
{
await CreatePermission(peer);
}
Guid reqId = Guid.NewGuid();
try
{
_logger.Verbose(
"Enqueue a request {RequestId} to {PeerAddress}: {Message}.",
reqId,
peer.Address,
message
);
var tcs = new TaskCompletionSource<IEnumerable<Message>>();
await _requests.AddAsync(
new MessageRequest(reqId, message, peer, timeout, expectedResponses, tcs)
);
_logger.Verbose(
"Enqueued a request {RequestId} to {PeerAddress}: {Message}.",
reqId,
peer.Address,
message
);
var reply = (await tcs.Task).ToList();
const string logMsg =
"Received {ReplyMessageCount} reply messages to {RequestId} " +
"from {PeerAddress}: {ReplyMessages}.";
_logger.Debug(logMsg, reply.Count, reqId, peer.Address, reply);
return reply;
}
catch (DifferentAppProtocolVersionException e)
{
const string logMsg =
"{PeerAddress} sent a reply to {RequestId} with " +
"a different app protocol version; " +
"expected: {ExpectedVersion}; actual: {ActualVersion}.";
_logger.Error(e, logMsg, peer.Address, reqId, e.ExpectedVersion, e.ActualVersion);
throw;
}
catch (TimeoutException)
{
_logger.Debug(
$"{nameof(Swarm<T>)}.{nameof(SendMessageWithReplyAsync)}() timed out " +
"after {Timeout} of waiting a reply to {RequestId} from {PeerAddress}.",
timeout,
reqId,
peer.Address
);
throw;
}
catch (TaskCanceledException)
{
_logger.Debug(
$"{nameof(Swarm<T>)}.{nameof(SendMessageWithReplyAsync)}() was cancelled to " +
"wait a reply to {RequestId} from {PeerAddress}.",
reqId,
peer.Address