-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathBlockTree.cs
1715 lines (1431 loc) · 70.3 KB
/
BlockTree.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
// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autofac.Features.AttributeFilters;
using Nethermind.Blockchain.Blocks;
using Nethermind.Blockchain.Find;
using Nethermind.Blockchain.Headers;
using Nethermind.Blockchain.Synchronization;
using Nethermind.Core;
using Nethermind.Core.Attributes;
using Nethermind.Core.Caching;
using Nethermind.Core.Collections;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Crypto;
using Nethermind.Db;
using Nethermind.Int256;
using Nethermind.Logging;
using Nethermind.Serialization.Rlp;
using Nethermind.State.Repositories;
using Nethermind.Db.Blooms;
using Nethermind.Serialization.Json;
namespace Nethermind.Blockchain
{
[Todo(Improve.Refactor, "After the fast sync work there are some duplicated code parts for the 'by header' and 'by block' approaches.")]
public partial class BlockTree : IBlockTree
{
// there is not much logic in the addressing here
private static readonly byte[] StateHeadHashDbEntryAddress = new byte[16];
internal static Hash256 DeletePointerAddressInDb = new(new BitArray(32 * 8, true).ToBytes());
internal static Hash256 HeadAddressInDb = Keccak.Zero;
private const int BestKnownSearchLimit = 256_000_000;
private readonly IBlockStore _blockStore;
private readonly IHeaderStore _headerStore;
private readonly IDb _blockInfoDb;
private readonly IDb _metadataDb;
private readonly IBadBlockStore _badBlockStore;
private readonly LruCache<ValueHash256, Block> _invalidBlocks =
new(128, 128, "invalid blocks");
private readonly ILogger _logger;
private readonly ISpecProvider _specProvider;
private readonly IBloomStorage _bloomStorage;
private readonly ISyncConfig _syncConfig;
private readonly IChainLevelInfoRepository _chainLevelInfoRepository;
public BlockHeader? Genesis { get; private set; }
public Block? Head { get; private set; }
public BlockHeader? BestSuggestedHeader { get; private set; }
public Block? BestSuggestedBody { get; private set; }
public BlockHeader? LowestInsertedHeader
{
get => _lowestInsertedHeader;
set
{
_lowestInsertedHeader = value;
_metadataDb.Set(MetadataDbKeys.LowestInsertedFastHeaderHash, Rlp.Encode(value?.Hash ?? value?.CalculateHash()).Bytes);
}
}
private BlockHeader? _lowestInsertedHeader;
public BlockHeader? BestSuggestedBeaconHeader { get; private set; }
public Block? BestSuggestedBeaconBody { get; private set; }
public BlockHeader? LowestInsertedBeaconHeader
{
get => _lowestInsertedBeaconHeader;
set
{
_lowestInsertedBeaconHeader = value;
_metadataDb.Set(MetadataDbKeys.LowestInsertedBeaconHeaderHash, Rlp.Encode(value?.Hash ?? value?.CalculateHash()).Bytes);
}
}
private BlockHeader? _lowestInsertedBeaconHeader;
private long? _highestPersistedState;
public long BestKnownNumber { get; private set; }
public long BestKnownBeaconNumber { get; private set; }
public ulong NetworkId => _specProvider.NetworkId;
public ulong ChainId => _specProvider.ChainId;
private int _canAcceptNewBlocksCounter;
public bool CanAcceptNewBlocks => _canAcceptNewBlocksCounter == 0;
private TaskCompletionSource<bool>? _taskCompletionSource;
public BlockTree(
IBlockStore? blockStore,
IHeaderStore? headerDb,
[KeyFilter(DbNames.BlockInfos)] IDb? blockInfoDb,
[KeyFilter(DbNames.Metadata)] IDb? metadataDb,
IBadBlockStore? badBlockStore,
IChainLevelInfoRepository? chainLevelInfoRepository,
ISpecProvider? specProvider,
IBloomStorage? bloomStorage,
ISyncConfig? syncConfig,
ILogManager? logManager)
{
_logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
_blockStore = blockStore ?? throw new ArgumentNullException(nameof(blockStore));
_headerStore = headerDb ?? throw new ArgumentNullException(nameof(headerDb));
_blockInfoDb = blockInfoDb ?? throw new ArgumentNullException(nameof(blockInfoDb));
_metadataDb = metadataDb ?? throw new ArgumentNullException(nameof(metadataDb));
_badBlockStore = badBlockStore ?? throw new ArgumentNullException(nameof(badBlockStore));
_specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
_bloomStorage = bloomStorage ?? throw new ArgumentNullException(nameof(bloomStorage));
_syncConfig = syncConfig ?? throw new ArgumentNullException(nameof(syncConfig));
_chainLevelInfoRepository = chainLevelInfoRepository ??
throw new ArgumentNullException(nameof(chainLevelInfoRepository));
LoadSyncPivot();
byte[]? deletePointer = _blockInfoDb.Get(DeletePointerAddressInDb);
if (deletePointer is not null)
{
DeleteBlocks(new Hash256(deletePointer));
}
// Need to be here because it still need to run even if there are no genesis to store the null entry.
LoadLowestInsertedHeader();
ChainLevelInfo? genesisLevel = LoadLevel(0);
if (genesisLevel is not null)
{
BlockInfo genesisBlockInfo = genesisLevel.BlockInfos[0];
if (genesisLevel.BlockInfos.Length != 1)
{
// just for corrupted test bases
genesisLevel.BlockInfos = new[] { genesisBlockInfo };
_chainLevelInfoRepository.PersistLevel(0, genesisLevel);
//throw new InvalidOperationException($"Genesis level in DB has {genesisLevel.BlockInfos.Length} blocks");
}
if (genesisBlockInfo.WasProcessed)
{
BlockHeader genesisHeader = FindHeader(genesisBlockInfo.BlockHash, BlockTreeLookupOptions.None);
Genesis = genesisHeader;
LoadStartBlock();
Head ??= FindBlock(genesisBlockInfo.BlockHash, BlockTreeLookupOptions.None);
}
RecalculateTreeLevels();
AttemptToFixCorruptionByMovingHeadBackwards();
}
if (_logger.IsInfo)
_logger.Info($"Block tree initialized, " +
$"last processed is {Head?.Header.ToString(BlockHeader.Format.Short) ?? "0"}, " +
$"best queued is {BestSuggestedHeader?.Number.ToString() ?? "0"}, " +
$"best known is {BestKnownNumber}, " +
$"lowest inserted header {LowestInsertedHeader?.Number}, " +
$"lowest sync inserted block number {LowestInsertedBeaconHeader?.Number}");
ProductInfo.Network = $"{(ChainId == NetworkId ? BlockchainIds.GetBlockchainName(NetworkId) : ChainId)}";
ThisNodeInfo.AddInfo("Chain ID :", ProductInfo.Network);
ThisNodeInfo.AddInfo("Chain head :", $"{Head?.Header.ToString(BlockHeader.Format.Short) ?? "0"}");
if (ChainId != NetworkId)
{
ThisNodeInfo.AddInfo("Network ID :", $"{NetworkId}");
}
}
public AddBlockResult Insert(BlockHeader header, BlockTreeInsertHeaderOptions headerOptions = BlockTreeInsertHeaderOptions.None)
{
if (!CanAcceptNewBlocks)
{
return AddBlockResult.CannotAccept;
}
if (header.Hash is null)
{
throw new InvalidOperationException("An attempt to insert a block header without a known hash.");
}
if (header.Bloom is null)
{
throw new InvalidOperationException("An attempt to insert a block header without a known bloom.");
}
if (header.Number == 0)
{
throw new InvalidOperationException("Genesis block should not be inserted.");
}
bool totalDifficultyNeeded = (headerOptions & BlockTreeInsertHeaderOptions.TotalDifficultyNotNeeded) == 0;
if (header.TotalDifficulty is null && totalDifficultyNeeded)
{
SetTotalDifficulty(header);
}
_bloomStorage.Store(header.Number, header.Bloom);
_headerStore.Insert(header);
bool isOnMainChain = (headerOptions & BlockTreeInsertHeaderOptions.NotOnMainChain) == 0;
BlockInfo blockInfo = new(header.Hash, header.TotalDifficulty ?? 0);
bool beaconInsert = (headerOptions & BlockTreeInsertHeaderOptions.BeaconHeaderMetadata) != 0;
if (!beaconInsert)
{
if (header.Number > BestKnownNumber)
{
BestKnownNumber = header.Number;
}
if (header.Number > (BestSuggestedHeader?.Number ?? 0))
{
BestSuggestedHeader = header;
}
}
if (beaconInsert)
{
if (header.Number > BestKnownBeaconNumber)
{
BestKnownBeaconNumber = header.Number;
}
if (header.Number > (BestSuggestedBeaconHeader?.Number ?? 0))
{
BestSuggestedBeaconHeader = header;
}
if (header.Number < (LowestInsertedBeaconHeader?.Number ?? long.MaxValue))
{
if (_logger.IsTrace)
_logger.Trace(
$"LowestInsertedBeaconHeader changed, old: {LowestInsertedBeaconHeader?.Number}, new: {header?.Number}");
LowestInsertedBeaconHeader = header;
}
}
bool addBeaconHeaderMetadata = (headerOptions & BlockTreeInsertHeaderOptions.BeaconHeaderMetadata) != 0;
bool addBeaconBodyMetadata = (headerOptions & BlockTreeInsertHeaderOptions.BeaconBodyMetadata) != 0;
bool moveToBeaconMainChain = (headerOptions & BlockTreeInsertHeaderOptions.MoveToBeaconMainChain) != 0;
if (addBeaconHeaderMetadata)
{
blockInfo.Metadata |= BlockMetadata.BeaconHeader;
}
if (addBeaconBodyMetadata)
{
blockInfo.Metadata |= BlockMetadata.BeaconBody;
}
if (moveToBeaconMainChain)
{
blockInfo.Metadata |= BlockMetadata.BeaconMainChain;
}
UpdateOrCreateLevel(header.Number, blockInfo, isOnMainChain);
return AddBlockResult.Added;
}
public void BulkInsertHeader(IReadOnlyList<BlockHeader> headers,
BlockTreeInsertHeaderOptions headerOptions = BlockTreeInsertHeaderOptions.None)
{
if (!CanAcceptNewBlocks)
{
throw new InvalidOperationException("Cannot accept new blocks at the moment.");
}
using ArrayPoolList<(long, Bloom)> bloomToStore = new ArrayPoolList<(long, Bloom)>(headers.Count);
foreach (var header in headers)
{
if (header.Hash is null)
{
throw new InvalidOperationException("An attempt to insert a block header without a known hash.");
}
if (header.Bloom is null)
{
throw new InvalidOperationException("An attempt to insert a block header without a known bloom.");
}
if (header.Number == 0)
{
throw new InvalidOperationException("Genesis block should not be inserted.");
}
bool totalDifficultyNeeded = (headerOptions & BlockTreeInsertHeaderOptions.TotalDifficultyNotNeeded) == 0;
if (header.TotalDifficulty is null && totalDifficultyNeeded)
{
SetTotalDifficulty(header);
}
bloomToStore.Add((header.Number, header.Bloom));
}
Task bloomStoreTask = Task.Run(() =>
{
_bloomStorage.Store(bloomToStore);
});
_headerStore.BulkInsert(headers);
bool isOnMainChain = (headerOptions & BlockTreeInsertHeaderOptions.NotOnMainChain) == 0;
bool beaconInsert = (headerOptions & BlockTreeInsertHeaderOptions.BeaconHeaderMetadata) != 0;
using ArrayPoolList<(long, BlockInfo)> blockInfos = new ArrayPoolList<(long, BlockInfo)>(headers.Count);
foreach (var header in headers)
{
BlockInfo blockInfo = new(header.Hash, header.TotalDifficulty ?? 0);
if (!beaconInsert)
{
if (header.Number > BestKnownNumber)
{
BestKnownNumber = header.Number;
}
if (header.Number > (BestSuggestedHeader?.Number ?? 0))
{
BestSuggestedHeader = header;
}
}
if (beaconInsert)
{
if (header.Number > BestKnownBeaconNumber)
{
BestKnownBeaconNumber = header.Number;
}
if (header.Number > (BestSuggestedBeaconHeader?.Number ?? 0))
{
BestSuggestedBeaconHeader = header;
}
if (header.Number < (LowestInsertedBeaconHeader?.Number ?? long.MaxValue))
{
if (_logger.IsTrace)
_logger.Trace(
$"LowestInsertedBeaconHeader changed, old: {LowestInsertedBeaconHeader?.Number}, new: {header?.Number}");
LowestInsertedBeaconHeader = header;
}
}
bool addBeaconHeaderMetadata = (headerOptions & BlockTreeInsertHeaderOptions.BeaconHeaderMetadata) != 0;
bool addBeaconBodyMetadata = (headerOptions & BlockTreeInsertHeaderOptions.BeaconBodyMetadata) != 0;
bool moveToBeaconMainChain = (headerOptions & BlockTreeInsertHeaderOptions.MoveToBeaconMainChain) != 0;
if (addBeaconHeaderMetadata)
{
blockInfo.Metadata |= BlockMetadata.BeaconHeader;
}
if (addBeaconBodyMetadata)
{
blockInfo.Metadata |= BlockMetadata.BeaconBody;
}
if (moveToBeaconMainChain)
{
blockInfo.Metadata |= BlockMetadata.BeaconMainChain;
}
blockInfos.Add((header.Number, blockInfo));
}
UpdateOrCreateLevel(blockInfos, isOnMainChain);
bloomStoreTask.Wait();
}
public AddBlockResult Insert(Block block, BlockTreeInsertBlockOptions insertBlockOptions = BlockTreeInsertBlockOptions.None,
BlockTreeInsertHeaderOptions insertHeaderOptions = BlockTreeInsertHeaderOptions.None, WriteFlags blockWriteFlags = WriteFlags.None)
{
bool skipCanAcceptNewBlocks = (insertBlockOptions & BlockTreeInsertBlockOptions.SkipCanAcceptNewBlocks) != 0;
if (!CanAcceptNewBlocks)
{
if (_logger.IsTrace) _logger.Trace($"Block tree in cannot accept new blocks mode. SkipCanAcceptNewBlocks: {skipCanAcceptNewBlocks}, Block {block}");
}
if (!CanAcceptNewBlocks && !skipCanAcceptNewBlocks)
{
return AddBlockResult.CannotAccept;
}
if (block.Number == 0)
{
throw new InvalidOperationException("Genesis block should not be inserted.");
}
_blockStore.Insert(block, writeFlags: blockWriteFlags);
_headerStore.InsertBlockNumber(block.Hash, block.Number);
bool saveHeader = (insertBlockOptions & BlockTreeInsertBlockOptions.SaveHeader) != 0;
if (saveHeader)
{
Insert(block.Header, insertHeaderOptions);
}
return AddBlockResult.Added;
}
private AddBlockResult Suggest(Block? block, BlockHeader header, BlockTreeSuggestOptions options = BlockTreeSuggestOptions.ShouldProcess)
{
bool shouldProcess = options.ContainsFlag(BlockTreeSuggestOptions.ShouldProcess);
bool fillBeaconBlock = options.ContainsFlag(BlockTreeSuggestOptions.FillBeaconBlock);
bool setAsMain = options.ContainsFlag(BlockTreeSuggestOptions.ForceSetAsMain) ||
!options.ContainsFlag(BlockTreeSuggestOptions.ForceDontSetAsMain) && !shouldProcess;
if (_logger.IsTrace) _logger.Trace($"Suggesting a new block. BestSuggestedBlock {BestSuggestedBody}, BestSuggestedBlock TD {BestSuggestedBody?.TotalDifficulty}, Block TD {block?.TotalDifficulty}, Head: {Head}, Head TD: {Head?.TotalDifficulty}, Block {block?.ToString(Block.Format.FullHashAndNumber)}. ShouldProcess: {shouldProcess}, TryProcessKnownBlock: {fillBeaconBlock}, SetAsMain {setAsMain}");
#if DEBUG
/* this is just to make sure that we do not fall into this trap when creating tests */
if (header.StateRoot is null && !header.IsGenesis)
{
throw new InvalidDataException($"State root is null in {header.ToString(BlockHeader.Format.Short)}");
}
#endif
if (header.Hash is null)
{
throw new InvalidOperationException("An attempt to suggest a header with a null hash.");
}
if (!CanAcceptNewBlocks)
{
return AddBlockResult.CannotAccept;
}
if (_invalidBlocks.Contains(header.Hash))
{
return AddBlockResult.InvalidBlock;
}
bool isKnown = IsKnownBlock(header.Number, header.Hash);
if (isKnown && (BestSuggestedHeader?.Number ?? 0) >= header.Number)
{
if (_logger.IsTrace) _logger.Trace($"Block {header.ToString(BlockHeader.Format.FullHashAndNumber)} already known.");
return AddBlockResult.AlreadyKnown;
}
bool parentExists = IsKnownBlock(header.Number - 1, header.ParentHash!) ||
IsKnownBeaconBlock(header.Number - 1, header.ParentHash!);
if (!header.IsGenesis && !parentExists)
{
if (_logger.IsTrace) _logger.Trace($"Could not find parent ({header.ParentHash}) of block {header.Hash}");
return AddBlockResult.UnknownParent;
}
SetTotalDifficulty(header);
if (block is not null)
{
if (block.Hash is null)
{
throw new InvalidOperationException("An attempt to suggest block with a null hash.");
}
_blockStore.Insert(block);
}
if (!isKnown)
{
_headerStore.Insert(header);
}
if (!isKnown || fillBeaconBlock)
{
BlockInfo blockInfo = new(header.Hash, header.TotalDifficulty ?? 0);
UpdateOrCreateLevel(header.Number, blockInfo, setAsMain);
NewSuggestedBlock?.Invoke(this, new BlockEventArgs(block!));
}
if (header.IsGenesis)
{
Genesis = header;
BestSuggestedHeader = header;
}
if (block is not null)
{
bool bestSuggestedImprovementSatisfied = BestSuggestedImprovementRequirementsSatisfied(header);
if (bestSuggestedImprovementSatisfied)
{
if (_logger.IsTrace)
_logger.Trace(
$"New best suggested block. PreviousBestSuggestedBlock {BestSuggestedBody}, BestSuggestedBlock TD {BestSuggestedBody?.TotalDifficulty}, Block TD {block?.TotalDifficulty}, Head: {Head}, Head: {Head?.TotalDifficulty}, Block {block?.ToString(Block.Format.FullHashAndNumber)}");
BestSuggestedHeader = block.Header;
if (block.IsPostMerge)
{
BestSuggestedBody = block;
}
}
if (shouldProcess && (bestSuggestedImprovementSatisfied || header.IsGenesis || fillBeaconBlock))
{
BestSuggestedBody = block;
NewBestSuggestedBlock?.Invoke(this, new BlockEventArgs(block));
}
}
return AddBlockResult.Added;
}
public AddBlockResult SuggestHeader(BlockHeader header)
{
return Suggest(null, header);
}
public async ValueTask<AddBlockResult> SuggestBlockAsync(Block block, BlockTreeSuggestOptions suggestOptions = BlockTreeSuggestOptions.ShouldProcess)
{
if (!WaitForReadinessToAcceptNewBlock.IsCompleted)
{
await WaitForReadinessToAcceptNewBlock;
}
return SuggestBlock(block, suggestOptions);
}
public AddBlockResult SuggestBlock(Block block, BlockTreeSuggestOptions options = BlockTreeSuggestOptions.ShouldProcess)
{
if (Genesis is null && !block.IsGenesis)
{
throw new InvalidOperationException("Block tree should be initialized with genesis before suggesting other blocks.");
}
return Suggest(block, block.Header, options);
}
public BlockHeader? FindHeader(long number, BlockTreeLookupOptions options)
{
Hash256 blockHash = GetBlockHashOnMainOrBestDifficultyHash(number);
return blockHash is null ? null : FindHeader(blockHash, options, blockNumber: number);
}
public Hash256? FindBlockHash(long blockNumber) => GetBlockHashOnMainOrBestDifficultyHash(blockNumber);
public bool HasBlock(long blockNumber, Hash256 blockHash) => _blockStore.HasBlock(blockNumber, blockHash);
public BlockHeader? FindHeader(Hash256? blockHash, BlockTreeLookupOptions options, long? blockNumber = null)
{
if (blockHash is null || blockHash == Keccak.Zero)
{
// TODO: would be great to check why this is still needed (maybe it is something archaic)
return null;
}
BlockHeader? header = _headerStore.Get(blockHash, shouldCache: false, blockNumber: blockNumber);
if (header is null)
{
bool allowInvalid = (options & BlockTreeLookupOptions.AllowInvalid) == BlockTreeLookupOptions.AllowInvalid;
if (allowInvalid && _invalidBlocks.TryGet(blockHash, out Block block))
{
header = block.Header;
}
return header;
}
header.Hash ??= blockHash;
bool totalDifficultyNeeded = (options & BlockTreeLookupOptions.TotalDifficultyNotNeeded) == BlockTreeLookupOptions.None;
bool createLevelIfMissing = (options & BlockTreeLookupOptions.DoNotCreateLevelIfMissing) == BlockTreeLookupOptions.None;
bool requiresCanonical = (options & BlockTreeLookupOptions.RequireCanonical) == BlockTreeLookupOptions.RequireCanonical;
if ((totalDifficultyNeeded && header.TotalDifficulty is null) || requiresCanonical)
{
(BlockInfo blockInfo, ChainLevelInfo level) = LoadInfo(header.Number, header.Hash, true);
if (level is null || blockInfo is null)
{
// TODO: this is here because storing block data is not transactional
// TODO: would be great to remove it, he?
// TODO: we should remove it - readonly method modifies DB
bool isSearchingForBeaconBlock = (BestKnownBeaconNumber > BestKnownNumber && header.Number > BestKnownNumber); // if we're searching for beacon block we don't want to create level. We're creating it in different place with beacon metadata
if (createLevelIfMissing == false || isSearchingForBeaconBlock)
{
if (_logger.IsInfo) _logger.Info($"Missing block info - ignoring creation of the level in {nameof(FindHeader)} scope when head is {Head?.ToString(Block.Format.Short)}. BlockHeader {header.ToString(BlockHeader.Format.FullHashAndNumber)}, CreateLevelIfMissing: {createLevelIfMissing}. BestKnownBeaconNumber: {BestKnownBeaconNumber}, BestKnownNumber: {BestKnownNumber}");
}
else
{
if (_logger.IsInfo) _logger.Info($"Missing block info - creating level in {nameof(FindHeader)} scope when head is {Head?.ToString(Block.Format.Short)}. BlockHeader {header.ToString(BlockHeader.Format.FullHashAndNumber)}, CreateLevelIfMissing: {createLevelIfMissing}. BestKnownBeaconNumber: {BestKnownBeaconNumber}, BestKnownNumber: {BestKnownNumber}");
SetTotalDifficulty(header);
blockInfo = new BlockInfo(header.Hash, header.TotalDifficulty ?? UInt256.Zero);
level = UpdateOrCreateLevel(header.Number, blockInfo);
}
}
else
{
SetTotalDifficultyFromBlockInfo(header, blockInfo);
}
if (requiresCanonical)
{
bool isMain = level.MainChainBlock?.BlockHash?.Equals(blockHash) == true;
header = isMain ? header : null;
}
}
if (header is not null && ShouldCache(header.Number))
{
_headerStore.Cache(header);
}
return header;
}
/// <returns>
/// If level has a block on the main chain then returns the block info,otherwise <value>null</value>
/// </returns>
public BlockInfo? FindCanonicalBlockInfo(long blockNumber)
{
ChainLevelInfo level = LoadLevel(blockNumber);
if (level is null)
{
return null;
}
if (level.HasBlockOnMainChain)
{
BlockInfo blockInfo = level.BlockInfos[0];
blockInfo.BlockNumber = blockNumber;
return blockInfo;
}
return null;
}
public Hash256? FindHash(long number)
{
return GetBlockHashOnMainOrBestDifficultyHash(number);
}
public IOwnedReadOnlyList<BlockHeader> FindHeaders(Hash256? blockHash, int numberOfBlocks, int skip, bool reverse)
{
if (numberOfBlocks == 0)
{
return ArrayPoolList<BlockHeader>.Empty();
}
if (blockHash is null)
{
return new ArrayPoolList<BlockHeader>(numberOfBlocks, numberOfBlocks);
}
BlockHeader startHeader = FindHeader(blockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (startHeader is null)
{
return new ArrayPoolList<BlockHeader>(numberOfBlocks, numberOfBlocks);
}
if (numberOfBlocks == 1)
{
return new ArrayPoolList<BlockHeader>(1) { startHeader };
}
if (skip == 0)
{
static ArrayPoolList<BlockHeader> FindHeadersReversedFast(BlockTree tree, BlockHeader startHeader, int numberOfBlocks, bool reverse = false)
{
ArgumentNullException.ThrowIfNull(startHeader);
if (numberOfBlocks == 1)
{
return new ArrayPoolList<BlockHeader>(1) { startHeader };
}
ArrayPoolList<BlockHeader> result = new ArrayPoolList<BlockHeader>(numberOfBlocks, numberOfBlocks);
BlockHeader current = startHeader;
int responseIndex = reverse ? 0 : numberOfBlocks - 1;
int step = reverse ? 1 : -1;
do
{
result[responseIndex] = current;
responseIndex += step;
if (responseIndex < 0)
{
break;
}
current = tree.FindParentHeader(current, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
} while (current is not null && responseIndex < numberOfBlocks);
return result;
}
/* if we do not skip and we have the last block then we can assume that all the blocks are there
and we can use the fact that we can use parent hash and that searching by hash is much faster
as it does not require the step of resolving number -> hash */
if (reverse)
{
return FindHeadersReversedFast(this, startHeader, numberOfBlocks, true);
}
else
{
BlockHeader endHeader = FindHeader(startHeader.Number + numberOfBlocks - 1, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (endHeader is not null)
{
return FindHeadersReversedFast(this, endHeader, numberOfBlocks);
}
}
}
ArrayPoolList<BlockHeader> result = new ArrayPoolList<BlockHeader>(numberOfBlocks, numberOfBlocks);
BlockHeader current = startHeader;
int directionMultiplier = reverse ? -1 : 1;
int responseIndex = 0;
do
{
result[responseIndex] = current;
responseIndex++;
long nextNumber = startHeader.Number + directionMultiplier * (responseIndex * skip + responseIndex);
if (nextNumber < 0)
{
break;
}
current = FindHeader(nextNumber, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
} while (current is not null && responseIndex < numberOfBlocks);
return result;
}
private BlockHeader? GetAncestorAtNumber(BlockHeader header, long number)
{
BlockHeader? result = header;
while (result is not null && result.Number < number)
{
result = this.FindParentHeader(result, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
}
return header;
}
private Hash256? GetBlockHashOnMainOrBestDifficultyHash(long blockNumber)
{
if (blockNumber < 0)
{
throw new ArgumentOutOfRangeException(nameof(blockNumber), $"Value must be greater or equal to zero but is {blockNumber}");
}
ChainLevelInfo level = LoadLevel(blockNumber);
if (level is null)
{
return null;
}
if (level.HasBlockOnMainChain)
{
return level.BlockInfos[0].BlockHash;
}
UInt256 bestDifficultySoFar = UInt256.Zero;
Hash256 bestHash = null;
for (int i = 0; i < level.BlockInfos.Length; i++)
{
BlockInfo current = level.BlockInfos[i];
if (level.BlockInfos[i].TotalDifficulty >= bestDifficultySoFar)
{
bestDifficultySoFar = current.TotalDifficulty;
bestHash = current.BlockHash;
}
}
return bestHash;
}
public Block? FindBlock(long blockNumber, BlockTreeLookupOptions options)
{
Hash256 hash = GetBlockHashOnMainOrBestDifficultyHash(blockNumber);
return FindBlock(hash, options, blockNumber: blockNumber);
}
public void DeleteInvalidBlock(Block invalidBlock)
{
if (invalidBlock.Hash is null)
{
if (_logger.IsWarn) _logger.Warn($"{nameof(DeleteInvalidBlock)} call has been made for a block without a null hash.");
return;
}
if (_logger.IsDebug) _logger.Debug($"Deleting invalid block {invalidBlock.ToString(Block.Format.FullHashAndNumber)}");
_invalidBlocks.Set(invalidBlock.Hash, invalidBlock);
_badBlockStore.Insert(invalidBlock);
BestSuggestedHeader = Head?.Header;
BestSuggestedBody = Head;
BlockAcceptingNewBlocks();
try
{
DeleteBlocks(invalidBlock.Hash!);
}
finally
{
ReleaseAcceptingNewBlocks();
}
}
private void DeleteBlocks(Hash256 deletePointer)
{
BlockHeader? deleteHeader = FindHeader(deletePointer, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (deleteHeader is null)
{
if (_logger.IsWarn) _logger.Warn($"Cannot delete invalid block {deletePointer} - block has not been added to the database or has already been deleted.");
return;
}
if (deleteHeader.Hash is null)
{
if (_logger.IsWarn) _logger.Warn($"Cannot delete invalid block {deletePointer} - black has a null hash.");
return;
}
long currentNumber = deleteHeader.Number;
Hash256 currentHash = deleteHeader.Hash;
Hash256? nextHash = null;
ChainLevelInfo? nextLevel = null;
using BatchWrite batch = _chainLevelInfoRepository.StartBatch();
while (true)
{
ChainLevelInfo? currentLevel = nextLevel ?? LoadLevel(currentNumber);
nextLevel = LoadLevel(currentNumber + 1);
bool shouldRemoveLevel = false;
if (currentLevel is not null) // preparing update of the level (removal of the invalid branch block)
{
if (currentLevel.BlockInfos.Length == 1)
{
shouldRemoveLevel = true;
}
else
{
currentLevel.BlockInfos = currentLevel.BlockInfos.Where(bi => bi.BlockHash != currentHash).ToArray();
}
}
// just finding what the next descendant will be
if (nextLevel is not null)
{
nextHash = FindChild(nextLevel, currentHash);
}
UpdateDeletePointer(nextHash);
if (shouldRemoveLevel)
{
BestKnownNumber = Math.Min(BestKnownNumber, currentNumber - 1);
_chainLevelInfoRepository.Delete(currentNumber, batch);
}
else if (currentLevel is not null)
{
_chainLevelInfoRepository.PersistLevel(currentNumber, currentLevel, batch);
}
if (_logger.IsInfo) _logger.Info($"Deleting invalid block {currentHash} at level {currentNumber}");
_blockStore.Delete(currentNumber, currentHash);
_headerStore.Delete(currentHash);
if (nextHash is null)
{
break;
}
currentNumber++;
currentHash = nextHash;
nextHash = null;
}
}
private Hash256? FindChild(ChainLevelInfo level, Hash256 parentHash)
{
Hash256 childHash = null;
for (int i = 0; i < level.BlockInfos.Length; i++)
{
Hash256 potentialChildHash = level.BlockInfos[i].BlockHash;
BlockHeader? potentialChild = FindHeader(potentialChildHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (potentialChild is null)
{
if (_logger.IsWarn) _logger.Warn($"Block with hash {potentialChildHash} has been found on chain level but its header is missing from the DB.");
return null;
}
if (potentialChild.ParentHash == parentHash)
{
childHash = potentialChildHash;
break;
}
}
return childHash;
}
public bool IsMainChain(BlockHeader blockHeader) =>
LoadLevel(blockHeader.Number)?.MainChainBlock?.BlockHash.Equals(blockHeader.Hash) == true;
public bool IsMainChain(Hash256 blockHash, bool throwOnMissingHash = true)
{
BlockHeader? header = FindHeader(blockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
return header is not null
? IsMainChain(header)
: throwOnMissingHash
? throw new InvalidOperationException($"Not able to retrieve block number for an unknown block {blockHash}")
: false;
}
public BlockHeader? FindBestSuggestedHeader() => BestSuggestedHeader;
public bool WasProcessed(long number, Hash256 blockHash)
{
ChainLevelInfo? levelInfo = LoadLevel(number) ?? throw new InvalidOperationException($"Not able to find block {blockHash} from an unknown level {number}");
int? index = levelInfo.FindIndex(blockHash) ?? throw new InvalidOperationException($"Not able to find block {blockHash} index on the chain level");
return levelInfo.BlockInfos[index.Value].WasProcessed;
}
public void MarkChainAsProcessed(IReadOnlyList<Block> blocks)
{
if (blocks.Count == 0)
{
return;
}
using BatchWrite batch = _chainLevelInfoRepository.StartBatch();
for (int i = 0; i < blocks.Count; i++)
{
Block block = blocks[i];
if (ShouldCache(block.Number))
{
_blockStore.Cache(block);
_headerStore.Cache(block.Header);
}
ChainLevelInfo? level = LoadLevel(block.Number);
int? index = (level?.FindIndex(block.Hash)) ?? throw new InvalidOperationException($"Cannot mark unknown block {block.ToString(Block.Format.FullHashAndNumber)} as processed");
BlockInfo info = level.BlockInfos[index.Value];
info.WasProcessed = true;
_chainLevelInfoRepository.PersistLevel(block.Number, level, batch);
}
}
public void UpdateMainChain(IReadOnlyList<Block> blocks, bool wereProcessed, bool forceUpdateHeadBlock = false)
{
if (blocks.Count == 0)
{
return;
}
bool ascendingOrder = true;
if (blocks.Count > 1)
{
if (blocks[^1].Number < blocks[0].Number)
{
ascendingOrder = false;
}
}
#if DEBUG
for (int i = 0; i < blocks.Count; i++)
{
if (i != 0)
{
if (ascendingOrder && blocks[i].Number != blocks[i - 1].Number + 1)
{
throw new InvalidOperationException("Update main chain invoked with gaps");
}
if (!ascendingOrder && blocks[i - 1].Number != blocks[i].Number + 1)
{
throw new InvalidOperationException("Update main chain invoked with gaps");
}
}
}
#endif
long lastNumber = ascendingOrder ? blocks[^1].Number : blocks[0].Number;
long previousHeadNumber = Head?.Number ?? 0L;
using BatchWrite batch = _chainLevelInfoRepository.StartBatch();
if (previousHeadNumber > lastNumber)
{
for (long i = 0; i < previousHeadNumber - lastNumber; i++)