/
BlockChain.cs
1506 lines (1368 loc) · 62.6 KB
/
BlockChain.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
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Threading;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Assets;
using Libplanet.Blockchain.Policies;
using Libplanet.Blockchain.Renderers;
using Libplanet.Blocks;
using Libplanet.Crypto;
using Libplanet.Store;
using Libplanet.Store.Trie;
using Libplanet.Tx;
using Serilog;
using static Libplanet.Blockchain.KeyConverters;
namespace Libplanet.Blockchain
{
/// <summary>
/// A class have <see cref="Block{T}"/>s, <see cref="Transaction{T}"/>s, and the chain
/// information.
/// <para>In order to watch its state changes, implement <see cref="IRenderer{T}"/>
/// interface and pass it to the <see cref="BlockChain{T}(IBlockPolicy{T}, IStagePolicy{T},
/// IStore, IStateStore, Block{T}, IEnumerable{IRenderer{T}})"/> constructor.</para>
/// </summary>
/// <remarks>This object is guaranteed that it has at least one block, since it takes a genesis
/// block when it's instantiated.</remarks>
/// <typeparam name="T">An <see cref="IAction"/> type. It should match
/// to <see cref="Block{T}"/>'s type parameter.</typeparam>
public partial class BlockChain<T> : IBlockChainStates<T>
where T : IAction, new()
{
// FIXME: The _rwlock field should be private.
[SuppressMessage(
"StyleCop.CSharp.OrderingRules",
"SA1401:FieldsMustBePrivate",
Justification = "Temporary visibility.")]
internal readonly ReaderWriterLockSlim _rwlock;
private readonly object _txLock;
private readonly ILogger _logger;
/// <summary>
/// All <see cref="Block{T}"/>s in the <see cref="BlockChain{T}"/>
/// storage, including orphan <see cref="Block{T}"/>s.
/// Keys are <see cref="Block{T}.Hash"/>es and values are
/// their corresponding <see cref="Block{T}"/>s.
/// </summary>
private IDictionary<BlockHash, Block<T>> _blocks;
/// <summary>
/// Cached genesis block.
/// </summary>
private Block<T> _genesis;
/// <summary>
/// Initializes a new instance of the <see cref="BlockChain{T}"/> class.
/// </summary>
/// <param name="policy"><see cref="IBlockPolicy{T}"/> to use in the
/// <see cref="BlockChain{T}"/>.</param>
/// <param name="stagePolicy">The staging policy to follow.</param>
/// <param name="store"><see cref="IStore"/> to store <see cref="Block{T}"/>s,
/// <see cref="Transaction{T}"/>s, and <see cref="BlockChain{T}"/> information.</param>
/// <param name="genesisBlock">The genesis <see cref="Block{T}"/> of
/// the <see cref="BlockChain{T}"/>, which is a part of the consensus.
/// If the given <paramref name="store"/> already contains the genesis block
/// it checks if the existing genesis block and this argument is the same.
/// If the <paramref name="store"/> has no genesis block yet this argument will
/// be used for that.</param>
/// <param name="renderers">Listens state changes on the created chain. Listens nothing
/// by default or if it is <c>null</c>. Note that action renderers receive events made
/// by unsuccessful transactions too; see also <see cref="AtomicActionRenderer{T}"/> for
/// workaround.</param>
/// <param name="stateStore"><see cref="IStateStore"/> to store states.</param>
/// <exception cref="InvalidGenesisBlockException">Thrown when the <paramref name="store"/>
/// has a genesis block and it does not match to what the network expects
/// (i.e., <paramref name="genesisBlock"/>).</exception>
public BlockChain(
IBlockPolicy<T> policy,
IStagePolicy<T> stagePolicy,
IStore store,
IStateStore stateStore,
Block<T> genesisBlock,
IEnumerable<IRenderer<T>> renderers = null
)
: this(
policy,
stagePolicy,
store,
stateStore,
store.GetCanonicalChainId() ?? Guid.NewGuid(),
genesisBlock,
renderers
)
{
}
internal BlockChain(
IBlockPolicy<T> policy,
IStagePolicy<T> stagePolicy,
IStore store,
IStateStore stateStore,
Guid id,
Block<T> genesisBlock,
IEnumerable<IRenderer<T>> renderers
)
: this(
policy,
stagePolicy,
store,
stateStore,
id,
genesisBlock,
false,
renderers
)
{
}
private BlockChain(
IBlockPolicy<T> policy,
IStagePolicy<T> stagePolicy,
IStore store,
IStateStore stateStore,
Guid id,
Block<T> genesisBlock,
bool inFork,
IEnumerable<IRenderer<T>> renderers
)
{
Id = id;
Policy = policy;
StagePolicy = stagePolicy;
Store = store;
// It expects store is DefaultStore or RocksDBStore.
StateStore = stateStore ?? store as IStateStore;
if (StateStore is null)
{
throw new ArgumentNullException(nameof(stateStore));
}
_blocks = new BlockSet<T>(store);
Renderers = renderers is IEnumerable<IRenderer<T>> r
? r.ToImmutableArray()
: ImmutableArray<IRenderer<T>>.Empty;
ActionRenderers = Renderers.OfType<IActionRenderer<T>>().ToImmutableArray();
_rwlock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
_txLock = new object();
if (Store.GetCanonicalChainId() is null)
{
Store.SetCanonicalChainId(Id);
}
_logger = Log
.ForContext<BlockChain<T>>()
.ForContext("Source", nameof(BlockChain<T>))
.ForContext("CanonicalChainId", Id);
ActionEvaluator = new ActionEvaluator<T>(
Policy.BlockAction,
blockChainStates: this,
trieGetter: hash => StateStore.GetStateRoot(_blocks[hash].StateRootHash),
genesisHash: genesisBlock.Hash,
nativeTokenPredicate: Policy.NativeTokens.Contains
);
if (Count == 0)
{
if (inFork)
{
Store.AppendIndex(Id, genesisBlock.Hash);
}
else
{
Append(
genesisBlock,
renderBlocks: !inFork,
renderActions: !inFork,
evaluateActions: !inFork
);
}
}
else if (!Genesis.Equals(genesisBlock))
{
string msg =
$"The genesis block that the given {nameof(IStore)} contains does not match " +
"to the genesis block that the network expects. You might pass the wrong " +
"store which is incompatible with this chain. Or your network might " +
"restarted the chain with a new genesis block so that it is incompatible " +
"with your existing chain in the local store.";
throw new InvalidGenesisBlockException(
message: msg,
networkExpected: genesisBlock.Hash,
stored: Genesis.Hash
);
}
}
~BlockChain()
{
_rwlock?.Dispose();
}
/// <summary>
/// An event which is invoked when <see cref="Tip"/> is changed.
/// </summary>
// FIXME: This should be completely replaced by IRenderer<T>.RenderBlock() or any other
// alternatives.
internal event EventHandler<(Block<T> OldTip, Block<T> NewTip)> TipChanged;
/// <summary>
/// The list of registered renderers listening the state changes.
/// </summary>
/// <remarks>
/// Since this value is immutable, renderers cannot be registered after once a <see
/// cref="BlockChain{T}"/> object is instantiated; use <c>renderers</c> option of <see cref=
/// "BlockChain{T}(IBlockPolicy{T}, IStagePolicy{T}, IStore, IStateStore, Block{T},
/// IEnumerable{IRenderer{T}})"/>
/// constructor instead.
/// </remarks>
public IImmutableList<IRenderer<T>> Renderers { get; }
/// <summary>
/// A filtered list, from <see cref="Renderers"/>, which contains only <see
/// cref="IActionRenderer{T}"/> instances.
/// </summary>
public IImmutableList<IActionRenderer<T>> ActionRenderers { get; }
/// <summary>
/// The block and blockchain policy.
/// </summary>
public IBlockPolicy<T> Policy { get; }
/// <summary>
/// The staging policy.
/// </summary>
public IStagePolicy<T> StagePolicy { get; set; }
/// <summary>
/// The topmost <see cref="Block{T}"/> of the current blockchain.
/// </summary>
public Block<T> Tip => this[-1];
/// <summary>
/// The first <see cref="Block{T}"/> in the <see cref="BlockChain{T}"/>.
/// </summary>
public Block<T> Genesis => _genesis ??= this[0];
public Guid Id { get; private set; }
/// <summary>
/// All <see cref="Block{T}.Hash"/>es in the current index. The genesis block's hash goes
/// first, and the tip goes last.
/// Returns a <see cref="long"/> integer that represents the number of elements in the
/// <see cref="BlockChain{T}"/>.
/// </summary>
public IEnumerable<BlockHash> BlockHashes => IterateBlockHashes();
/// <summary>
/// Returns a <see cref="long"/> integer that represents the number of elements in the
/// <see cref="BlockChain{T}"/>.
/// </summary>
/// <returns>A number that represents how many elements in the <see cref="BlockChain{T}"/>.
/// </returns>
public long Count => Store.CountIndex(Id);
internal IStore Store { get; }
internal IStateStore StateStore { get; }
internal ActionEvaluator<T> ActionEvaluator { get; }
/// <summary>
/// Whether the instance is canonical or not.
/// </summary>
internal bool IsCanonical => Store.GetCanonicalChainId() is Guid guid && Id == guid;
/// <summary>
/// Gets the block corresponding to the <paramref name="index"/>.
/// </summary>
/// <param name="index">A number of index of <see cref="Block{T}"/>.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given index of
/// <see cref="Block{T}"/> does not exist.</exception>
public Block<T> this[int index] => this[(long)index];
/// <summary>
/// Gets the block corresponding to the <paramref name="index"/>.
/// </summary>
/// <param name="index">A number of index of <see cref="Block{T}"/>.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given index of
/// <see cref="Block{T}"/> does not exist.</exception>
public Block<T> this[long index]
{
get
{
_rwlock.EnterReadLock();
try
{
BlockHash? blockHash = Store.IndexBlockHash(Id, index);
return blockHash is { } bh
? _blocks[bh]
: throw new ArgumentOutOfRangeException();
}
finally
{
_rwlock.ExitReadLock();
}
}
}
/// <summary>
/// Gets the block corresponding to the <paramref name="blockHash"/>.
/// </summary>
/// <param name="blockHash">A <see cref="Block{T}.Hash"/> of the <see cref="Block{T}"/> to
/// get. </param>
/// <exception cref="KeyNotFoundException">Thrown when there is no <see cref="Block{T}"/>
/// with a given <paramref name="blockHash"/>.</exception>
public Block<T> this[in BlockHash blockHash]
{
get
{
if (!ContainsBlock(blockHash))
{
throw new KeyNotFoundException(
$"The given hash[{blockHash}] was not found in this chain."
);
}
_rwlock.EnterReadLock();
try
{
return _blocks[blockHash];
}
finally
{
_rwlock.ExitReadLock();
}
}
}
/// <summary>
/// Mine the genesis block of the blockchain.
/// </summary>
/// <param name="actions">List of actions will be included in the genesis block.
/// If it's null, it will be replaced with <see cref="ImmutableArray{T}.Empty"/>
/// as default.</param>
/// <param name="privateKey">A private key to sign the transaction and the genesis block.
/// If it's null, it will use new private key as default.</param>
/// <param name="timestamp">The timestamp of the genesis block. If it's null, it will
/// use <see cref="DateTimeOffset.UtcNow"/> as default.</param>
/// <param name="blockAction">A block action to execute and be rendered for every block.
/// It must match to <see cref="BlockPolicy{T}.BlockAction"/> of <see cref="Policy"/>.
/// </param>
/// <param name="nativeTokenPredicate">A predicate function to determine whether
/// the specified <see cref="Currency"/> is a native token defined by chain's
/// <see cref="Libplanet.Blockchain.Policies.IBlockPolicy{T}.NativeTokens"/> or not.
/// Treat no <see cref="Currency"/> as native token if the argument omitted.</param>
/// <returns>The genesis block mined with parameters.</returns>
public static Block<T> MakeGenesisBlock(
IEnumerable<T> actions = null,
PrivateKey privateKey = null,
DateTimeOffset? timestamp = null,
IAction blockAction = null,
Predicate<Currency> nativeTokenPredicate = null)
{
privateKey ??= new PrivateKey();
actions ??= ImmutableArray<T>.Empty;
Transaction<T>[] transactions =
{
Transaction<T>.Create(0, privateKey, null, actions, timestamp: timestamp),
};
BlockContent<T> content = new BlockContent<T>
{
PublicKey = privateKey.PublicKey,
Timestamp = timestamp ?? DateTimeOffset.UtcNow,
Transactions = transactions,
};
PreEvaluationBlock<T> preEval = content.Mine();
return preEval.Evaluate(
privateKey,
blockAction,
nativeTokenPredicate,
new TrieStateStore(new DefaultKeyValueStore(null))
);
}
/// <summary>
/// Determines whether the <see cref="BlockChain{T}"/> contains <see cref="Block{T}"/>
/// the specified <paramref name="blockHash"/>.
/// </summary>
/// <param name="blockHash">The <see cref="HashDigest{T}"/> of the <see cref="Block{T}"/> to
/// check if it is in the <see cref="BlockChain{T}"/>.</param>
/// <returns>
/// <c>true</c> if the <see cref="BlockChain{T}"/> contains <see cref="Block{T}"/> with
/// the specified <paramref name="blockHash"/>; otherwise, <c>false</c>.
/// </returns>
public bool ContainsBlock(BlockHash blockHash)
{
_rwlock.EnterReadLock();
try
{
return
_blocks.ContainsKey(blockHash) &&
Store.GetBlockIndex(blockHash) is { } branchPointIndex &&
branchPointIndex <= Tip.Index &&
Store.IndexBlockHash(Id, branchPointIndex).Equals(blockHash);
}
finally
{
_rwlock.ExitReadLock();
}
}
/// <summary>
/// Gets the transaction corresponding to the <paramref name="txId"/>.
/// </summary>
/// <param name="txId">A <see cref="TxId"/> of the <see cref="Transaction{T}"/> to get.
/// </param>
/// <returns><see cref="Transaction{T}"/> with <paramref name="txId"/>.</returns>
/// <exception cref="KeyNotFoundException">Thrown when there is no
/// <see cref="Transaction{T}"/> with a given <paramref name="txId"/>.</exception>
public Transaction<T> GetTransaction(TxId txId)
{
if (StagePolicy.Get(this, txId) is { } tx)
{
return tx;
}
_rwlock.EnterReadLock();
try
{
if (Store.GetTransaction<T>(txId) is { } transaction)
{
transaction.Validate();
return transaction;
}
throw new KeyNotFoundException($"No such transaction: {txId}");
}
finally
{
_rwlock.ExitReadLock();
}
}
/// <summary>
/// Gets the state of the given <paramref name="address"/> in the
/// <see cref="BlockChain{T}"/> from <paramref name="offset"/>.
/// </summary>
/// <param name="address">An <see cref="Address"/> to get the states of.</param>
/// <param name="offset">The <see cref="HashDigest{T}"/> of the block to start finding
/// the state. It will be The tip of the <see cref="BlockChain{T}"/> if it is <c>null</c>.
/// </param>
/// <param name="stateCompleter">When the <see cref="BlockChain{T}"/> instance does not
/// contain states dirty of the block which lastly updated states of a requested address,
/// this delegate is called and its return value is used instead.
/// <para><see cref="StateCompleters{T}.Recalculate"/> makes the incomplete states
/// recalculated and filled on the fly.</para>
/// <para><see cref="StateCompleters{T}.Reject"/> (which is default) makes the incomplete
/// states (if needed) to cause <see cref="IncompleteBlockStatesException"/> instead.</para>
/// </param>
/// <returns>The current state of given <paramref name="address"/>. This can be <c>null</c>
/// if <paramref name="address"/> has no value.</returns>
public IValue GetState(
Address address,
BlockHash? offset = null,
StateCompleter<T> stateCompleter = null
) =>
Count > 0
? GetStates(
new[] { address },
offset ?? Tip.Hash,
stateCompleter ?? StateCompleters<T>.Reject
)[0]
: null;
/// <summary>
/// Gets multiple states associated to the specified <paramref name="addresses"/>.
/// </summary>
/// <param name="addresses">Addresses of states to query.</param>
/// <param name="offset">The <see cref="HashDigest{T}"/> of the block to start finding
/// the states. <see cref="Tip"/> by default.</param>
/// <param name="stateCompleter">When the <see cref="BlockChain{T}"/> instance does not
/// contain states of the block, this delegate is called and its return values are used
/// instead.
/// <para><see cref="StateCompleters{T}.Recalculate"/> makes the incomplete states
/// recalculated and filled on the fly.</para>
/// <para><see cref="StateCompleters{T}.Reject"/> (which is default) makes the incomplete
/// states (if needed) to cause <see cref="IncompleteBlockStatesException"/> instead.</para>
/// </param>
/// <returns>The states associated to the specified <paramref name="addresses"/>.
/// Associated values are ordered in the same way to the corresponding
/// <paramref name="addresses"/>. Absent states are represented as <see langword="null"/>.
/// </returns>
public IReadOnlyList<IValue> GetStates(
IReadOnlyList<Address> addresses,
BlockHash? offset = null,
StateCompleter<T> stateCompleter = null
) =>
Count > 0
? GetStates(
addresses,
offset ?? Tip.Hash,
stateCompleter ?? StateCompleters<T>.Reject
)
: new IValue[addresses.Count];
public IReadOnlyList<IValue> GetStates(
IReadOnlyList<Address> addresses,
BlockHash offset,
StateCompleter<T> stateCompleter
)
{
if (Count < 1)
{
return new IValue[addresses.Count];
}
HashDigest<SHA256>? stateRootHash = Store.GetStateRootHash(offset);
if (stateRootHash is { } h && StateStore.ContainsStateRoot(h))
{
string[] rawKeys = addresses.Select(ToStateKey).ToArray();
return StateStore.GetStates(stateRootHash, rawKeys);
}
return stateCompleter(this, offset, addresses);
}
/// <summary>
/// Queries <paramref name="address"/>'s balance of the <paramref name="currency"/> in the
/// <see cref="BlockChain{T}"/> from <paramref name="offset"/>.
/// </summary>
/// <param name="address">The owner <see cref="Address"/> to query.</param>
/// <param name="currency">The currency type to query.</param>
/// <param name="offset">The <see cref="HashDigest{T}"/> of the block to
/// start finding the state. It will be the tip of the
/// <see cref="BlockChain{T}"/> if it is <c>null</c>.</param>
/// <param name="stateCompleter">When the <see cref="BlockChain{T}"/> instance does not
/// contain states dirty of the block which lastly updated states of a requested address,
/// this delegate is called and its return value is used instead.
/// <para><see cref="FungibleAssetStateCompleters{T}.Recalculate"/> makes the incomplete
/// states recalculated and filled on the fly.</para>
/// <para><see cref="FungibleAssetStateCompleters{T}.Reject"/> (which is default) makes
/// the incomplete states (if needed) to cause <see cref="IncompleteBlockStatesException"/>
/// instead.</para></param>
/// <returns>The <paramref name="address"/>'s current balance (or balance as of the given
/// <paramref name="offset"/>) of the <paramref name="currency"/>.
/// </returns>
public FungibleAssetValue GetBalance(
Address address,
Currency currency,
BlockHash? offset = null,
FungibleAssetStateCompleter<T> stateCompleter = null
) =>
GetBalance(
address,
currency,
offset ?? Tip.Hash,
stateCompleter ?? FungibleAssetStateCompleters<T>.Reject
);
/// <inheritdoc cref="IBlockChainStates{T}.GetBalance"/>
public FungibleAssetValue GetBalance(
Address address,
Currency currency,
BlockHash offset,
FungibleAssetStateCompleter<T> stateCompleter
)
{
if (Count < 1)
{
return currency * 0;
}
HashDigest<SHA256>? stateRootHash = Store.GetStateRootHash(offset);
if (stateRootHash is { } h && StateStore.ContainsStateRoot(h))
{
string rawKey = ToFungibleAssetKey(address, currency);
IReadOnlyList<IValue> values =
StateStore.GetStates(stateRootHash, new[] { rawKey });
return values.Count > 0 && values[0] is Bencodex.Types.Integer i
? FungibleAssetValue.FromRawValue(currency, i)
: currency * 0;
}
return stateCompleter(this, offset, address, currency);
}
/// <summary>
/// Gets the total supply of a <paramref name="currency"/> in the
/// <see cref="BlockChain{T}"/> from <paramref name="offset"/>, and if not found, derive
/// from the sum of all balances.
/// </summary>
/// <param name="currency">The currency type to query.</param>
/// <param name="offset">The <see cref="HashDigest{T}"/> of the block to
/// start finding the state.</param>
/// <param name="stateCompleter">When the <see cref="BlockChain{T}"/> instance does not
/// contain states of the block, this delegate is called and its return values are used
/// instead.
/// <para><see cref="FungibleAssetStateCompleters{T}.Recalculate"/> makes the incomplete
/// states recalculated and filled on the fly.</para>
/// <para><see cref="FungibleAssetStateCompleters{T}.Reject"/> makes the incomplete states
/// (if needed) to cause <see cref="IncompleteBlockStatesException"/> instead.</para>
/// </param>
/// <returns>The total supply value of <paramref name="currency"/> at
/// <paramref name="offset"/> in <see cref="FungibleAssetValue"/>.</returns>
public FungibleAssetValue GetTotalSupply(
Currency currency,
BlockHash? offset = null,
TotalSupplyStateCompleter<T> stateCompleter = null
) =>
GetTotalSupply(
currency,
offset ?? Tip.Hash,
stateCompleter ?? TotalSupplyStateCompleters<T>.Reject
);
/// <inheritdoc cref="IBlockChainStates{T}.GetTotalSupply"/>
public FungibleAssetValue GetTotalSupply(
Currency currency,
BlockHash offset,
TotalSupplyStateCompleter<T> stateCompleter
)
{
if (!currency.TotalSupplyTrackable)
{
throw TotalSupplyNotTrackableException.WithDefaultMessage(currency);
}
if (Count < 1)
{
return currency * 0;
}
HashDigest<SHA256>? stateRootHash = Store.GetStateRootHash(offset);
if (stateRootHash is { } h && StateStore.ContainsStateRoot(h))
{
string rawKey = ToTotalSupplyKey(currency);
IReadOnlyList<IValue> values =
StateStore.GetStates(stateRootHash, new[] { rawKey });
return values.Count > 0 && values[0] is Bencodex.Types.Integer i
? FungibleAssetValue.FromRawValue(currency, i)
: currency * 0;
}
return stateCompleter(this, offset, currency);
}
/// <summary>
/// Queries the recorded <see cref="TxExecution"/> for a successful or failed
/// <see cref="Transaction{T}"/> within a <see cref="Block{T}"/>.
/// </summary>
/// <param name="blockHash">The <see cref="Block{T}.Hash"/> of the <see cref="Block{T}"/>
/// that the <see cref="Transaction{T}"/> is executed within.</param>
/// <param name="txid">The executed <see cref="Transaction{T}"/>'s
/// <see cref="Transaction{T}.Id"/>.</param>
/// <returns>The recorded <see cref="TxExecution"/>. If the transaction has never been
/// executed within the block, it returns <c>null</c> instead.</returns>
public TxExecution GetTxExecution(BlockHash blockHash, TxId txid) =>
Store.GetTxExecution(blockHash, txid);
/// <summary>
/// Adds a <paramref name="block"/> to the end of this chain.
/// <para><see cref="Block{T}.Transactions"/> in the <paramref name="block"/> updates
/// states and balances in the blockchain, and <see cref="TxExecution"/>s for
/// transactions are recorded.</para>
/// <para>Note that <see cref="Renderers"/> receive events right after the <paramref
/// name="block"/> is confirmed (and thus all states reflect changes in the <paramref
/// name="block"/>).</para>
/// </summary>
/// <param name="block">A next <see cref="Block{T}"/>, which is mined,
/// to add.</param>
/// <param name="stateCompleters">The strategy to complement incomplete block states which
/// are required for action execution and rendering.
/// <see cref="StateCompleterSet{T}.Recalculate"/> by default.
/// </param>
/// <exception cref="BlockPolicyViolationException">Thrown when given
/// <paramref name="block"/> does not satisfy any of the constraints
/// validated by <see cref="IBlockPolicy{T}.ValidateNextBlock"/> of <see cref="Policy"/>.
/// </exception>
/// <exception cref="InvalidBlockException">Thrown when the given <paramref name="block"/>
/// is invalid, in itself or according to the <see cref="Policy"/>.</exception>
/// <exception cref="InvalidTxNonceException">Thrown when the
/// <see cref="Transaction{T}.Nonce"/> is different from
/// <see cref="GetNextTxNonce"/> result of the
/// <see cref="Transaction{T}.Signer"/>.</exception>
public void Append(
Block<T> block,
StateCompleterSet<T>? stateCompleters = null
) =>
Append(
block,
evaluateActions: true,
renderBlocks: true,
renderActions: true,
stateCompleters: stateCompleters
);
/// <summary>
/// Adds <paramref name="transaction"/> to the pending list so that a next
/// <see cref="Block{T}"/> to be mined may contain given <paramref name="transaction"/>.
/// </summary>
/// <param name="transaction"><see cref="Transaction{T}"/> to add to the pending list.
/// </param>
/// <returns><c>true</c> if staging was successful, <c>false</c> otherwise.</returns>
/// <exception cref="InvalidTxGenesisHashException">Thrown when given
/// <paramref name="transaction"/> has invalid <see cref="Transaction{T}.GenesisHash"/>.
/// </exception>
public bool StageTransaction(Transaction<T> transaction)
{
if (!transaction.GenesisHash.Equals(Genesis.Hash))
{
var msg = "GenesisHash of the transaction is not compatible " +
"with the BlockChain<T>.Genesis.Hash.";
throw new InvalidTxGenesisHashException(
msg,
transaction.Id,
Genesis.Hash,
transaction.GenesisHash);
}
return StagePolicy.Stage(this, transaction);
}
/// <summary>
/// Removes a <paramref name="transaction"/> from the pending list.
/// </summary>
/// <param name="transaction">A <see cref="Transaction{T}"/>
/// to remove from the pending list.</param>
/// <returns><c>true</c> if unstaging was successful, <c>false</c> otherwise.</returns>
/// <seealso cref="StageTransaction"/>
public bool UnstageTransaction(Transaction<T> transaction) =>
StagePolicy.Unstage(this, transaction.Id);
/// <summary>
/// Gets next <see cref="Transaction{T}.Nonce"/> of the address.
/// </summary>
/// <param name="address">The <see cref="Address"/> from which to obtain the
/// <see cref="Transaction{T}.Nonce"/> value.</param>
/// <returns>The next <see cref="Transaction{T}.Nonce"/> value of the
/// <paramref name="address"/>.</returns>
public long GetNextTxNonce(Address address)
=> StagePolicy.GetNextTxNonce(this, address);
/// <summary>
/// Records and queries the <paramref name="perceivedTime"/> of the given
/// <paramref name="blockExcerpt"/>.
/// <para>Although blocks have their own <see cref="Block{T}.Timestamp"/>, but these values
/// are untrustworthy as they are arbitrarily determined by their miners.</para>
/// <para>On the other hand, this method returns the subjective time according to the local
/// node's perception.</para>
/// <para>If the local node has never perceived the <paramref name="blockExcerpt"/> yet,
/// it is perceived at that moment and the current time is returned instead. (However, you
/// can replace the current time with the <paramref name="perceivedTime"/> option.)
/// In other words, this method is idempotent.</para>
/// </summary>
/// <param name="blockExcerpt">The perceived block.</param>
/// <param name="perceivedTime">The time the local node perceived the given <paramref
/// name="blockExcerpt"/>. The current time by default.</param>
/// <returns>A pair of a block and the time it was perceived.</returns>
public BlockPerception PerceiveBlock(
IBlockExcerpt blockExcerpt,
DateTimeOffset? perceivedTime = null
)
{
if (!(Store.GetBlockPerceivedTime(blockExcerpt.Hash) is { } time))
{
time = perceivedTime ?? DateTimeOffset.FromUnixTimeMilliseconds(
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
Store.SetBlockPerceivedTime(blockExcerpt.Hash, time);
}
return new BlockPerception(blockExcerpt, time);
}
/// <summary>
/// Creates a new <see cref="Transaction{T}"/> and stage the transaction.
/// Cannot create new transaction if the genesis block does not exist.
/// </summary>
/// <param name="privateKey">A <see cref="PrivateKey"/> of the account who creates and
/// signs a new transaction.</param>
/// <param name="actions">A list of <see cref="IAction"/>s to include to a new transaction.
/// </param>
/// <param name="updatedAddresses"><see cref="Address"/>es whose states affected by
/// <paramref name="actions"/>.</param>
/// <param name="timestamp">The time this <see cref="Transaction{T}"/> is created and
/// signed.</param>
/// <returns>A created new <see cref="Transaction{T}"/> signed by the given
/// <paramref name="privateKey"/>.</returns>
public Transaction<T> MakeTransaction(
PrivateKey privateKey,
IEnumerable<T> actions,
IImmutableSet<Address> updatedAddresses = null,
DateTimeOffset? timestamp = null)
{
timestamp = timestamp ?? DateTimeOffset.UtcNow;
lock (_txLock)
{
// FIXME: Exception should be documented when the genesis block does not exist.
Transaction<T> tx = Transaction<T>.Create(
GetNextTxNonce(privateKey.ToAddress()),
privateKey,
Genesis.Hash,
actions,
updatedAddresses,
timestamp);
StageTransaction(tx);
return tx;
}
}
/// <summary>
/// Lists all staged <see cref="TxId"/>s.
/// </summary>
/// <returns><see cref="IImmutableSet{TxId}"/> of staged transactions.</returns>
public IImmutableSet<TxId> GetStagedTransactionIds()
{
// FIXME: How about turning this method to the StagedTransactions property?
return StagePolicy.Iterate(this).Select(tx => tx.Id).ToImmutableHashSet();
}
/// <summary>
/// Evaluates actions in the given <paramref name="block"/> and fills states with the
/// results.
/// </summary>
/// <param name="block">A block to execute.</param>
/// <param name="stateCompleters">The strategy to complement incomplete previous block
/// states. <see cref="StateCompleterSet{T}.Recalculate"/> by default.
/// </param>
/// <returns>The result of action evaluations of the given <paramref name="block"/>.
/// </returns>
/// <remarks>This method is idempotent (except for rendering). If the given
/// <paramref name="block"/> has executed before, it does not execute it nor mutate states.
/// Exposed as public for benchmarking.
/// </remarks>
public IReadOnlyList<ActionEvaluation> ExecuteActions(
Block<T> block,
StateCompleterSet<T>? stateCompleters = null
)
{
IReadOnlyList<ActionEvaluation> evaluations = ActionEvaluator.Evaluate(
block,
stateCompleters ?? StateCompleterSet<T>.Recalculate
);
_rwlock.EnterWriteLock();
try
{
// Update states
DateTimeOffset setStatesStarted = DateTimeOffset.Now;
var totalDelta =
evaluations.GetTotalDelta(ToStateKey, ToFungibleAssetKey, ToTotalSupplyKey);
const string deltaMsg =
"Summarized the states delta with {KeyCount} key changes " +
"made by block #{BlockIndex} {BlockHash}.";
_logger.Debug(deltaMsg, totalDelta.Count, block.Index, block.Hash);
HashDigest<SHA256>? prevStateRootHash = Store.GetStateRootHash(block.PreviousHash);
ITrie stateRoot = StateStore.Commit(prevStateRootHash, totalDelta);
HashDigest<SHA256> rootHash = stateRoot.Hash;
const string rootHashMsg =
"Calculated the root hash of the states made by block #{BlockIndex} " +
"{BlockHash} for " + nameof(TrieStateStore) + ": {StateRootHash}.";
_logger.Debug(rootHashMsg, block.Index, block.Hash, rootHash);
if (!rootHash.Equals(block.StateRootHash))
{
var message = $"Block #{block.Index} {block.Hash}'s state root hash " +
$"is {block.StateRootHash}, but the execution result is {rootHash}.";
throw new InvalidBlockStateRootHashException(
message,
block.StateRootHash,
rootHash);
}
TimeSpan setStatesDuration = DateTimeOffset.Now - setStatesStarted;
_logger
.ForContext("Tag", "Metric")
.ForContext("Subtag", "StateUpdateDuration")
.Debug(
"Finished updating the states with {KeyCount} key changes affected by " +
"block #{BlockIndex} {BlockHash} in {DurationMs:F0}ms.",
totalDelta.Count,
block.Index,
block.Hash,
setStatesDuration.TotalMilliseconds);
IEnumerable<TxExecution> txExecutions = MakeTxExecutions(block, evaluations);
UpdateTxExecutions(txExecutions);
}
finally
{
_rwlock.ExitWriteLock();
}
return evaluations;
}
/// <summary>
/// Find the branching point between this blockchain and <paramref name="locator"/>, and
/// the hashes of subsequent blocks from the point.</summary>
/// <param name="locator">The <see cref="BlockLocator"/> to find the branching point
/// from.</param>
/// <param name="stop">A block hash to stop looking for subsequent blocks once encountered.
/// </param>
/// <param name="count">Maximum number of block hashes to return.</param>
/// <returns>A tuple of the index of the branching point and block hashes.</returns>
public Tuple<long?, IReadOnlyList<BlockHash>> FindNextHashes(
BlockLocator locator,
BlockHash? stop = null,
int count = 500)
{
DateTimeOffset startTime = DateTimeOffset.Now;
// FIXME Theoretically, we don't accept empty chain. so `tip` can't be null on this
// assumption. but during some test case(e.g. GetDemandBlockHashesDuringReorg),
// it had been occurred.
// We should find a reason for that and fix it before remote this early return.
BlockHash? tip = Store.IndexBlockHash(Id, -1);
if (tip is null)
{
return new Tuple<long?, IReadOnlyList<BlockHash>>(null, new BlockHash[0]);
}
BlockHash? branchpoint = FindBranchpoint(locator);
var branchpointIndex = branchpoint is { } h ? (int)Store.GetBlockIndex(h)! : 0;
// FIXME: Currently, increasing count by one to satisfy
// the number defined by FindNextHashesChunkSize variable
// when branchPointIndex didn't indicate genesis block.
// Since branchPointIndex is same as the latest block of
// requesting peer.
if (branchpointIndex > 0)
{
count++;
}
var result = new List<BlockHash>();
foreach (BlockHash hash in Store.IterateIndexes(Id, branchpointIndex, count))
{
if (count == 0)
{
break;
}
result.Add(hash);
if (hash.Equals(stop))
{
break;
}
count--;
}
TimeSpan duration = DateTimeOffset.Now - startTime;
_logger
.ForContext("Tag", "Metric")
.ForContext("Subtag", "FindHashesDuration")
.Debug(
"Found {HashCount} hashes from storage with {ChainIdCount} chain ids " +
"in {DurationMs:F0}ms.",
result.Count,
Store.ListChainIds().Count(),
duration.TotalMilliseconds);
return new Tuple<long?, IReadOnlyList<BlockHash>>(branchpointIndex, result);
}
/// <summary>
/// Forks the chain at <paramref name="point"/> and returns the newly forked chain.
/// </summary>
/// <param name="point">The hash in which to fork from.</param>
/// <param name="inheritRenderers">Whether to inherit the renderers from the existing chain.
/// </param>
/// <returns>An instance of the newly forked chain.</returns>
/// <exception cref="ArgumentException">Throws when the provided <paramref name="point"/>
/// does not exist in the current chain.</exception>
public BlockChain<T> Fork(BlockHash point, bool inheritRenderers = true)
{
if (!ContainsBlock(point))
{
throw new ArgumentException(
$"The block [{point}] doesn't exist.",
nameof(point));
}
Block<T> pointBlock = this[point];
if (!point.Equals(this[pointBlock.Index].Hash))
{