forked from planetarium/libplanet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Swarm.cs
2222 lines (1968 loc) · 80.2 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 Libplanet.Action;
using Libplanet.Blockchain;
using Libplanet.Blocks;
using Libplanet.Crypto;
using Libplanet.Net.Messages;
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>
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 BlockHashRecvTimeout = TimeSpan.FromSeconds(3);
private static readonly TimeSpan BlockRecvTimeout = TimeSpan.FromSeconds(15);
private static readonly TimeSpan TxRecvTimeout = TimeSpan.FromSeconds(3);
private readonly IDictionary<Peer, DateTimeOffset> _peers;
private readonly IDictionary<Peer, DateTimeOffset> _removedPeers;
private readonly BlockChain<T> _blockChain;
private readonly PrivateKey _privateKey;
private readonly RouterSocket _router;
private readonly IDictionary<Address, DealerSocket> _dealers;
private readonly int _appProtocolVersion;
private readonly TimeSpan _dialTimeout;
private readonly AsyncLock _runningMutex;
private readonly AsyncLock _blockSyncMutex;
private readonly string _host;
private readonly IList<IceServer> _iceServers;
private readonly TimeSpan _linger;
private readonly NetMQQueue<Message> _replyQueue;
private readonly NetMQQueue<Message> _broadcastQueue;
private readonly NetMQPoller _poller;
private readonly ILogger _logger;
private TaskCompletionSource<object> _runningEvent;
private int? _listenPort;
private TurnClient _turnClient;
private CancellationTokenSource _workerCancellationTokenSource;
private CancellationToken _cancellationToken;
private IPAddress _publicIPAddress;
static Swarm()
{
if (!(Type.GetType("Mono.Runtime") is null))
{
ForceDotNet.Force();
}
}
public Swarm(
BlockChain<T> blockChain,
PrivateKey privateKey,
int appProtocolVersion,
int millisecondsDialTimeout = 15000,
int millisecondsLinger = 1000,
string host = null,
int? listenPort = null,
DateTimeOffset? createdAt = null,
IEnumerable<IceServer> iceServers = null,
EventHandler<DifferentProtocolVersionEventArgs>
differentVersionPeerEncountered = null)
: this(
blockChain,
privateKey,
appProtocolVersion,
TimeSpan.FromMilliseconds(millisecondsDialTimeout),
TimeSpan.FromMilliseconds(millisecondsLinger),
host,
listenPort,
createdAt,
iceServers,
differentVersionPeerEncountered)
{
}
public Swarm(
BlockChain<T> blockChain,
PrivateKey privateKey,
int appProtocolVersion,
TimeSpan dialTimeout,
TimeSpan linger,
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));
_privateKey = privateKey ?? throw new ArgumentNullException(nameof(privateKey));
_dialTimeout = dialTimeout;
_peers = new ConcurrentDictionary<Peer, DateTimeOffset>();
_removedPeers = new ConcurrentDictionary<Peer, DateTimeOffset>();
LastSeenTimestamps =
new ConcurrentDictionary<Peer, DateTimeOffset>();
DateTimeOffset now = createdAt.GetValueOrDefault(
DateTimeOffset.UtcNow);
LastDistributed = now;
LastReceived = now;
DeltaDistributed = new AsyncAutoResetEvent();
DeltaReceived = new AsyncAutoResetEvent();
TxReceived = new AsyncAutoResetEvent();
BlockReceived = new AsyncAutoResetEvent();
DifferentVersionPeerEncountered = differentVersionPeerEncountered;
_dealers = new ConcurrentDictionary<Address, DealerSocket>();
_router = new RouterSocket();
_router.Options.RouterHandover = true;
_replyQueue = new NetMQQueue<Message>();
_broadcastQueue = new NetMQQueue<Message>();
_poller = new NetMQPoller { _router, _replyQueue, _broadcastQueue };
_blockSyncMutex = new AsyncLock();
_runningMutex = new AsyncLock();
_host = host;
_listenPort = listenPort;
_appProtocolVersion = appProtocolVersion;
_linger = linger;
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);
_router.ReceiveReady += ReceiveMessage;
_replyQueue.ReceiveReady += DoReply;
_broadcastQueue.ReceiveReady += DoBroadcast;
}
~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" /> called 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 != null
? new Peer(
_privateKey.PublicKey,
EndPoint,
_appProtocolVersion,
_publicIPAddress)
: throw new SwarmException(
"Can't translate unbound Swarm to Peer.");
public AsyncAutoResetEvent DeltaReceived { get; }
public AsyncAutoResetEvent DeltaDistributed { get; }
public AsyncAutoResetEvent TxReceived { get; }
public AsyncAutoResetEvent BlockReceived { get; }
public DateTimeOffset LastReceived { get; private set; }
public DateTimeOffset LastDistributed { 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 => _blockChain;
/// <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 ICollection<Peer> Peers => _peers.Keys;
/// <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 async Task<ISet<Peer>> AddPeersAsync(
IEnumerable<Peer> peers,
DateTimeOffset? timestamp = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (timestamp is null)
{
timestamp = DateTimeOffset.UtcNow;
}
var peersAsArray = peers as Peer[] ?? peers.ToArray();
foreach (Peer peer in peersAsArray)
{
if (_removedPeers.ContainsKey(peer))
{
_removedPeers.Remove(peer);
}
}
PublicKey publicKey = _privateKey.PublicKey;
var addedPeers = new HashSet<Peer>();
foreach (Peer peer in peersAsArray)
{
if (peer.PublicKey.Equals(publicKey))
{
continue;
}
if (!IsUnknownPeer(peer))
{
_logger.Debug($"Peer[{peer}] is already exists, ignored.");
continue;
}
if (Running)
{
try
{
_logger.Debug($"Trying to DialPeerAsync({peer})...");
Pong pong = await DialPeerAsync(peer, cancellationToken);
_logger.Debug($"DialPeerAsync({peer}) is complete.");
Peer peerWithVersion = peer.WithAppProtocolVersion(pong.AppProtocolVersion);
_peers[peerWithVersion] = timestamp.Value;
addedPeers.Add(peerWithVersion);
}
catch (IOException e)
{
_logger.Error(
e,
$"DialPeerAsync({peer}) failed. ignored."
);
}
catch (TimeoutException)
{
_logger.Warning($"DialPeerAsync({peer}) timeout. ignored.");
}
catch (DifferentAppProtocolVersionException e)
{
_logger.Error(
e,
$"DialPeerAsync({peer}) failed. ignored."
);
}
}
else
{
_peers[peer] = timestamp.Value;
}
}
return addedPeers;
}
public async Task StopAsync(
CancellationToken cancellationToken = default(CancellationToken))
{
_workerCancellationTokenSource?.Cancel();
_logger.Debug("Stopping...");
using (await _runningMutex.LockAsync())
{
if (Running)
{
_removedPeers[AsPeer] = DateTimeOffset.UtcNow;
DistributeDelta(false);
await Task.Delay(_linger);
_broadcastQueue.ReceiveReady -= DoBroadcast;
_replyQueue.ReceiveReady -= DoReply;
_router.ReceiveReady -= ReceiveMessage;
if (_poller.IsRunning)
{
_poller.Dispose();
}
_broadcastQueue.Dispose();
_replyQueue.Dispose();
_router.Dispose();
foreach (DealerSocket s in _dealers.Values)
{
s.Dispose();
}
_dealers.Clear();
_turnClient?.Dispose();
Running = false;
}
}
_logger.Debug("Stopped.");
}
public async Task StartAsync(
int millisecondsDistributeInterval = 1500,
int millisecondsBroadcastTxInterval = 5000,
CancellationToken cancellationToken = default(CancellationToken))
{
await StartAsync(
TimeSpan.FromMilliseconds(millisecondsDistributeInterval),
TimeSpan.FromMilliseconds(millisecondsBroadcastTxInterval),
cancellationToken
);
}
/// <summary>
/// Joins to the peer-to-peer network and starts to periodically synchronize
/// the <see cref="BlockChain"/>.
/// </summary>
/// <param name="distributeInterval">The time period of peer exchange.</param>
/// <param name="broadcastTxInterval">The time period of exchange of staged transactions.
/// </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(IProgress{PreloadState}, IImmutableSet{Address}, CancellationToken)"
/// /> method too.</remarks>
public async Task StartAsync(
TimeSpan distributeInterval,
TimeSpan broadcastTxInterval,
CancellationToken cancellationToken = default(CancellationToken))
{
if (Running)
{
throw new SwarmException("Swarm is already running.");
}
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);
}
using (await _runningMutex.LockAsync())
{
await PreloadAsync(render: true, cancellationToken: _cancellationToken);
Running = true;
}
try
{
tasks.Add(RepeatDeltaDistributionAsync(distributeInterval, _cancellationToken));
tasks.Add(BroadcastTxAsync(broadcastTxInterval, _cancellationToken));
tasks.Add(Task.Run(() => _poller.Run(), _cancellationToken));
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 void BroadcastBlocks(IEnumerable<Block<T>> blocks)
{
_logger.Debug("Trying to broadcast blocks...");
var message = new BlockHashes(
Address,
blocks.Select(b => b.Hash)
);
_broadcastQueue.Enqueue(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);
}
/// <summary>
/// Preemptively downloads blocks from registered <see cref="Peer"/>s.
/// </summary>
/// <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="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, CancellationToken)"/> method
/// instead.</remarks>
public Task PreloadAsync(
IProgress<PreloadState> progress = null,
IImmutableSet<Address> trustedStateValidators = null,
CancellationToken cancellationToken = default(CancellationToken)
)
{
return PreloadAsync(
render: false,
progress: progress,
trustedStateValidators: trustedStateValidators,
cancellationToken: cancellationToken
);
}
// FIXME: It is not guaranteed that states will be reported in order. see issue #436, #430
internal async Task PreloadAsync(
bool render,
IProgress<PreloadState> progress = null,
IImmutableSet<Address> trustedStateValidators = null,
CancellationToken cancellationToken = default(CancellationToken)
)
{
if (trustedStateValidators is null)
{
trustedStateValidators = ImmutableHashSet<Address>.Empty;
}
IList<(Peer, long? TipIndex)> peersWithHeight =
await DialToExistingPeers(cancellationToken).Select(pp =>
(pp.Item1, pp.Item2.TipIndex)
).ToListAsync(cancellationToken);
if (!peersWithHeight.Any())
{
_logger.Information("There is no appropriate peer for preloading.");
return;
}
Block<T> initialTip = _blockChain.Tip;
// 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, _blockChain.Store, Guid.NewGuid());
var complete = false;
try
{
await SyncBehindsBlocksFromPeersAsync(
workspace,
peersWithHeight,
progress,
cancellationToken,
render
);
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.
return;
}
long height = workspace.Tip.Index;
IEnumerable<(Peer, 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(),
initialTip?.Hash,
cancellationToken
);
if (!received)
{
long initHeight =
initialTip is null || !workspace[initialTip.Index].Equals(initialTip)
? 0
: initialTip.Index + 1;
int count = 0, totalCount = workspace.Count() - (int)initHeight;
_logger.Debug("Starts to execute actions of {0} blocks.", totalCount);
foreach (HashDigest<SHA256> hash in workspace.BlockHashes.Skip((int)initHeight))
{
cancellationToken.ThrowIfCancellationRequested();
Block<T> block = workspace.Blocks[hash];
if (block.Index < initHeight)
{
continue;
}
workspace.ExecuteActions(block, render: false);
_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
);
workspace.Store.DeleteNamespace(workspace.Id.ToString());
}
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<IEnumerable<HashDigest<SHA256>>>
GetBlockHashesAsync(
Peer peer,
BlockLocator locator,
HashDigest<SHA256>? stop,
CancellationToken token = default(CancellationToken)
)
{
if (!_peers.ContainsKey(peer))
{
throw new PeerNotFoundException(
$"The peer[{peer.Address}] could not be found.");
}
var request = new GetBlockHashes(locator, stop);
using (var socket = new DealerSocket(ToNetMQAddress(peer)))
{
await socket.SendMultipartMessageAsync(
request.ToNetMQMessage(_privateKey),
cancellationToken: token);
NetMQMessage response = await socket.ReceiveMultipartMessageAsync(
timeout: BlockHashRecvTimeout,
cancellationToken: token
);
Message parsedMessage = Message.Parse(response, reply: true);
if (parsedMessage is BlockHashes blockHashes)
{
return blockHashes.Hashes;
}
throw new InvalidMessageException(
$"The response of GetBlockHashes isn't BlockHashes. " +
$"but {parsedMessage}");
}
}
internal IAsyncEnumerable<Block<T>> GetBlocksAsync(
Peer peer,
IEnumerable<HashDigest<SHA256>> blockHashes)
{
if (!_peers.ContainsKey(peer))
{
throw new PeerNotFoundException(
$"The peer[{peer.Address}] could not be found.");
}
return new AsyncEnumerable<Block<T>>(async yield =>
{
CancellationToken yieldToken = yield.CancellationToken;
using (var socket = new DealerSocket(ToNetMQAddress(peer)))
{
var blockHashesAsArray =
blockHashes as HashDigest<SHA256>[] ??
blockHashes.ToArray();
var request = new GetBlocks(blockHashesAsArray);
await socket.SendMultipartMessageAsync(
request.ToNetMQMessage(_privateKey),
cancellationToken: yieldToken);
int hashCount = blockHashesAsArray.Count();
_logger.Debug(
$"Required block count: {hashCount}. {yieldToken}");
while (hashCount > 0 && !yieldToken.IsCancellationRequested)
{
_logger.Debug("Starts to receive blocks from {0}.", peer);
NetMQMessage response = await socket.ReceiveMultipartMessageAsync(
timeout: BlockRecvTimeout,
cancellationToken: yieldToken
);
Message parsedMessage = Message.Parse(response, true);
if (parsedMessage is Messages.Blocks blockMessage)
{
IList<byte[]> payloads = blockMessage.Payloads;
_logger.Debug("Received {0} blocks from {1}.", payloads.Count, peer);
foreach (byte[] payload in payloads)
{
Block<T> block = Block<T>.FromBencodex(payload);
await yield.ReturnAsync(block);
hashCount--;
}
}
else
{
throw new InvalidMessageException(
$"The response of GetData isn't a Block. " +
$"but {parsedMessage}");
}
}
}
});
}
internal IAsyncEnumerable<Transaction<T>> GetTxsAsync(
Peer peer,
IEnumerable<TxId> txIds,
CancellationToken cancellationToken = default(CancellationToken))
{
if (!_peers.ContainsKey(peer))
{
throw new PeerNotFoundException(
$"The peer[{peer.Address}] could not be found.");
}
return new AsyncEnumerable<Transaction<T>>(async yield =>
{
using (var socket = new DealerSocket(ToNetMQAddress(peer)))
{
var txIdsAsArray = txIds as TxId[] ?? txIds.ToArray();
var request = new GetTxs(txIdsAsArray);
await socket.SendMultipartMessageAsync(
request.ToNetMQMessage(_privateKey),
cancellationToken: cancellationToken);
int hashCount = txIdsAsArray.Count();
_logger.Debug($"Required tx count: {hashCount}.");
while (hashCount > 0)
{
_logger.Debug("Receiving tx...");
NetMQMessage response = await socket.ReceiveMultipartMessageAsync(
timeout: TxRecvTimeout,
cancellationToken: cancellationToken
);
Message parsedMessage = Message.Parse(response, true);
if (parsedMessage is Messages.Tx parsed)
{
Transaction<T> tx = Transaction<T>.FromBencodex(
parsed.Payload);
await yield.ReturnAsync(tx);
hashCount--;
}
else
{
throw new InvalidMessageException(
$"The response of getdata isn't block. " +
$"but {parsedMessage}");
}
}
}
});
}
private static IEnumerable<Peer> FilterPeers(
IDictionary<Peer, DateTimeOffset> peers,
DateTimeOffset before,
DateTimeOffset? after = null,
bool remove = false)
{
foreach (KeyValuePair<Peer, DateTimeOffset> kv in peers.ToList())
{
if (after != null && kv.Value <= after)
{
continue;
}
if (kv.Value <= before)
{
if (remove)
{
peers.Remove(kv.Key);
}
yield return kv.Key;
}
}
}
private async Task BindingProxies(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
#pragma warning disable IDE0067 // We'll dispose of `stream` in proxy task.
NetworkStream stream = await _turnClient.AcceptRelayedStreamAsync();
#pragma warning restore IDE0067
// TODO We should expose the interface so that library users
// can limit / manage the task.
#pragma warning disable CS4014
Task.Run(async () =>
{
using (var proxy = new NetworkStreamProxy(stream))
{
Debug.Assert(_listenPort != null, nameof(_listenPort) + " != null");
await proxy.StartAsync(IPAddress.Loopback, _listenPort.Value);
}
}).ContinueWith(_ => stream.Dispose());
#pragma warning restore CS4014
}
catch (Exception e)
{
_logger.Error(e, "An unexpected exception occured. try again...");
}
}
}
private IAsyncEnumerable<(Peer, Pong)> DialToExistingPeers(
CancellationToken cancellationToken)
{
return new AsyncEnumerable<(Peer, Pong)>(async yield =>
{
foreach (Peer peer in _peers.Keys)
{
try
{
await yield.ReturnAsync(
(peer, await DialPeerAsync(peer, cancellationToken))
);
}
catch (TimeoutException e)
{
_logger.Error(
e,
$"TimeoutException occured ({peer})."
);
}
catch (IOException e)
{
_logger.Error(
e,
$"IOException occured ({peer})."
);
}
catch (DifferentAppProtocolVersionException e)
{
_logger.Error(
e,
$"Protocol Version is different ({peer}).");
}
}
});
}
private async Task SyncBehindsBlocksFromPeersAsync(
BlockChain<T> blockChain,
IEnumerable<(Peer, long?)> peersWithHeight,
IProgress<BlockDownloadState> progress,
CancellationToken cancellationToken,
bool render
)
{
// Implement it directly with AggregateAsync()
// because there is no IAsyncEnumerable<T>.MaxAsync().
(Peer, long?)? longestPeerWithLength = peersWithHeight.Aggregate(
default((Peer, long?)?),
(p, c) => p?.Item2 > c.Item2 ? p : c
);
if (longestPeerWithLength != null &&
!(blockChain.Tip?.Index >= longestPeerWithLength?.Item2))
{
long currentTipIndex = blockChain.Tip?.Index ?? -1;
long peerIndex = longestPeerWithLength?.Item2 ?? -1;
long totalBlockCount = peerIndex - currentTipIndex;
BlockChain<T> synced = await SyncPreviousBlocksAsync(
blockChain,
longestPeerWithLength?.Item1,
null,
progress,
totalBlockCount,
evaluateActions: render,
cancellationToken: cancellationToken
);
if (!synced.Id.Equals(blockChain.Id))
{
blockChain.Swap(synced, render);
}
}
}
private async Task<bool> SyncRecentStatesFromTrustedPeersAsync(
BlockChain<T> blockChain,
IProgress<PreloadState> progress,
IReadOnlyList<(Peer, HashDigest<SHA256>)> trustedPeersWithTip,
HashDigest<SHA256>? baseBlockHash,
CancellationToken cancellationToken)
{
_logger.Debug(
"Starts to find a peer to request recent states (candidates: {0} trusted peers).",
trustedPeersWithTip.Count
);
foreach ((Peer peer, var blockHash) in trustedPeersWithTip)
{