forked from NethermindEth/nethermind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockTree.Initializer.cs
More file actions
394 lines (344 loc) · 14.8 KB
/
BlockTree.Initializer.cs
File metadata and controls
394 lines (344 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// SPDX-FileCopyrightText: 2025 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.IO;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Db;
using Nethermind.Serialization.Rlp;
namespace Nethermind.Blockchain;
public partial class BlockTree
{
private bool _tryToRecoverFromHeaderBelowBodyCorruption = false;
public void RecalculateTreeLevels()
{
LoadLowestInsertedHeader();
LoadLowestInsertedBeaconHeader();
LoadBestKnown();
LoadBeaconBestKnown();
LoadForkChoiceInfo();
}
public static long? BinarySearchBlockNumber(long left, long right, Func<long, bool, bool> isBlockFound,
BinarySearchDirection direction = BinarySearchDirection.Up, bool findBeacon = false)
{
if (left > right)
{
return null;
}
long? result = null;
while (left != right)
{
long index = direction == BinarySearchDirection.Up
? left + (right - left) / 2
: right - (right - left) / 2;
if (isBlockFound(index, findBeacon))
{
result = index;
if (direction == BinarySearchDirection.Up)
{
left = index + 1;
}
else
{
right = index - 1;
}
}
else
{
if (direction == BinarySearchDirection.Up)
{
right = index;
}
else
{
left = index;
}
}
}
if (isBlockFound(left, findBeacon))
{
result = direction == BinarySearchDirection.Up ? left : right;
}
return result;
}
private void AttemptToFixCorruptionByMovingHeadBackwards()
{
if (_tryToRecoverFromHeaderBelowBodyCorruption && BestSuggestedHeader is not null)
{
long blockNumber = BestPersistedState ?? BestSuggestedHeader.Number;
ChainLevelInfo chainLevelInfo = LoadLevel(blockNumber);
BlockInfo? canonicalBlock = chainLevelInfo?.MainChainBlock;
if (canonicalBlock is not null && canonicalBlock.WasProcessed)
{
SetHeadBlock(canonicalBlock.BlockHash!);
}
else
{
Logger.Error("Failed attempt to fix 'header < body' corruption caused by an unexpected shutdown.");
}
}
}
private bool LevelExists(long blockNumber, bool findBeacon = false)
{
ChainLevelInfo? level = LoadLevel(blockNumber);
if (findBeacon)
{
return level is not null && level.HasBeaconBlocks;
}
return level is not null && level.HasNonBeaconBlocks;
}
private bool HeaderExists(long blockNumber, bool findBeacon = false)
{
ChainLevelInfo level = LoadLevel(blockNumber);
if (level is null)
{
return false;
}
foreach (BlockInfo blockInfo in level.BlockInfos)
{
BlockHeader? header = FindHeader(blockInfo.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded | BlockTreeLookupOptions.DoNotCreateLevelIfMissing);
if (header is not null)
{
if (findBeacon && blockInfo.IsBeaconHeader)
{
return true;
}
if (!findBeacon && !blockInfo.IsBeaconHeader)
{
return true;
}
}
}
return false;
}
private bool BodyExists(long blockNumber, bool findBeacon = false)
{
ChainLevelInfo level = LoadLevel(blockNumber);
if (level is null)
{
return false;
}
foreach (BlockInfo blockInfo in level.BlockInfos)
{
Block? block = FindBlock(blockInfo.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded | BlockTreeLookupOptions.DoNotCreateLevelIfMissing);
if (block is not null)
{
if (findBeacon && blockInfo.IsBeaconBody)
{
return true;
}
if (!findBeacon && !blockInfo.IsBeaconBody)
{
return true;
}
}
}
return false;
}
private void LoadForkChoiceInfo()
{
Logger.Info("Loading fork choice info");
FinalizedHash ??= _metadataDb.Get(MetadataDbKeys.FinalizedBlockHash)?.AsRlpStream().DecodeKeccak();
SafeHash ??= _metadataDb.Get(MetadataDbKeys.SafeBlockHash)?.AsRlpStream().DecodeKeccak();
}
private void LoadLowestInsertedBeaconHeader()
{
if (_metadataDb.KeyExists(MetadataDbKeys.LowestInsertedBeaconHeaderHash))
{
Hash256? lowestBeaconHeaderHash = _metadataDb.Get(MetadataDbKeys.LowestInsertedBeaconHeaderHash)?
.AsRlpStream().DecodeKeccak();
_lowestInsertedBeaconHeader = FindHeader(lowestBeaconHeaderHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
}
}
private void LoadLowestInsertedHeader()
{
if (_metadataDb.KeyExists(MetadataDbKeys.LowestInsertedFastHeaderHash))
{
Hash256? headerHash = _metadataDb.Get(MetadataDbKeys.LowestInsertedFastHeaderHash)?
.AsRlpStream().DecodeKeccak();
_lowestInsertedHeader = FindHeader(headerHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
}
else
{
// Old style binary search.
long left = 1L;
long right = SyncPivot.BlockNumber;
LowestInsertedHeader = BinarySearchBlockHeader(left, right, LevelExists, BinarySearchDirection.Down);
}
if (Logger.IsDebug) Logger.Debug($"Lowest inserted header set to {LowestInsertedHeader?.Number.ToString() ?? "null"}");
}
private void LoadBestKnown()
{
long left = (Head?.Number ?? 0) == 0
? Math.Max(SyncPivot.BlockNumber, LowestInsertedHeader?.Number ?? 0) - 1
: Head.Number;
long right = Math.Max(0, left) + BestKnownSearchLimit;
long bestKnownNumberFound = BinarySearchBlockNumber(left, right, LevelExists) ?? 0;
long bestSuggestedHeaderNumber = BinarySearchBlockNumber(left, right, HeaderExists) ?? 0;
long bestSuggestedBodyNumber = BinarySearchBlockNumber(left, right, BodyExists) ?? 0;
if (Logger.IsInfo)
Logger.Info("Numbers resolved, " +
$"level = {bestKnownNumberFound}, " +
$"header = {bestSuggestedHeaderNumber}, " +
$"body = {bestSuggestedBodyNumber}");
if (bestKnownNumberFound < 0 ||
bestSuggestedHeaderNumber < 0 ||
bestSuggestedBodyNumber < 0 ||
bestSuggestedHeaderNumber < bestSuggestedBodyNumber)
{
if (Logger.IsWarn)
Logger.Warn(
$"Detected corrupted block tree data ({bestSuggestedHeaderNumber} < {bestSuggestedBodyNumber}) (possibly due to an unexpected shutdown). Attempting to fix by moving head backwards. This may fail and you may need to resync the node.");
if (bestSuggestedHeaderNumber < bestSuggestedBodyNumber)
{
bestSuggestedBodyNumber = bestSuggestedHeaderNumber;
_tryToRecoverFromHeaderBelowBodyCorruption = true;
}
else
{
throw new InvalidDataException("Invalid initial block tree state loaded - " +
$"best known: {bestKnownNumberFound}|" +
$"best header: {bestSuggestedHeaderNumber}|" +
$"best body: {bestSuggestedBodyNumber}|");
}
}
BestKnownNumber = bestKnownNumberFound;
BestSuggestedHeader = FindHeader(bestSuggestedHeaderNumber, BlockTreeLookupOptions.None);
BlockHeader? bestSuggestedBodyHeader = FindHeader(bestSuggestedBodyNumber, BlockTreeLookupOptions.None);
BestSuggestedBody = bestSuggestedBodyHeader is null
? null
: FindBlock(bestSuggestedBodyHeader.Hash, BlockTreeLookupOptions.None);
}
private void LoadBeaconBestKnown()
{
long left = Math.Max(Head?.Number ?? 0, LowestInsertedBeaconHeader?.Number ?? 0) - 1;
long right = Math.Max(0, left) + BestKnownSearchLimit;
long bestKnownNumberFound = BinarySearchBlockNumber(left, right, LevelExists, findBeacon: true) ?? 0;
left = Math.Max(
Math.Max(
Head?.Number ?? 0,
LowestInsertedBeaconHeader?.Number ?? 0),
BestSuggestedHeader?.Number ?? 0
) - 1;
right = Math.Max(0, left) + BestKnownSearchLimit;
long bestBeaconHeaderNumber = BinarySearchBlockNumber(left, right, HeaderExists, findBeacon: true) ?? 0;
long? beaconPivotNumber = _metadataDb.Get(MetadataDbKeys.BeaconSyncPivotNumber)?.AsRlpValueContext().DecodeLong();
left = Math.Max(Head?.Number ?? 0, beaconPivotNumber ?? 0) - 1;
right = Math.Max(0, left) + BestKnownSearchLimit;
long bestBeaconBodyNumber = BinarySearchBlockNumber(left, right, BodyExists, findBeacon: true) ?? 0;
if (Logger.IsInfo)
Logger.Info("Beacon Numbers resolved, " +
$"level = {bestKnownNumberFound}, " +
$"header = {bestBeaconHeaderNumber}, " +
$"body = {bestBeaconBodyNumber}");
if (bestKnownNumberFound < 0 ||
bestBeaconHeaderNumber < 0 ||
bestBeaconBodyNumber < 0 ||
bestBeaconHeaderNumber < bestBeaconBodyNumber)
{
if (Logger.IsWarn)
Logger.Warn(
$"Detected corrupted block tree data ({bestBeaconHeaderNumber} < {bestBeaconBodyNumber}) (possibly due to an unexpected shutdown). Attempting to fix by moving head backwards. This may fail and you may need to resync the node.");
if (bestBeaconHeaderNumber < bestBeaconBodyNumber)
{
bestBeaconBodyNumber = bestBeaconHeaderNumber;
_tryToRecoverFromHeaderBelowBodyCorruption = true;
}
else
{
throw new InvalidDataException("Invalid initial block tree state loaded - " +
$"best known: {bestKnownNumberFound}|" +
$"best header: {bestBeaconHeaderNumber}|" +
$"best body: {bestBeaconBodyNumber}|");
}
}
BestKnownBeaconNumber = bestKnownNumberFound;
BestSuggestedBeaconHeader = FindHeader(bestBeaconHeaderNumber, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
BlockHeader? bestBeaconBodyHeader = FindHeader(bestBeaconBodyNumber, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
BestSuggestedBeaconBody = bestBeaconBodyHeader is null
? null
: FindBlock(bestBeaconBodyHeader.Hash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
}
public enum BinarySearchDirection
{
Up,
Down
}
private BlockHeader? BinarySearchBlockHeader(long left, long right, Func<long, bool, bool> isBlockFound,
BinarySearchDirection direction = BinarySearchDirection.Up)
{
long? blockNumber = BinarySearchBlockNumber(left, right, isBlockFound, direction);
if (blockNumber.HasValue)
{
ChainLevelInfo? level = LoadLevel(blockNumber.Value) ?? throw new InvalidDataException(
$"Missing chain level at number {blockNumber.Value}");
BlockInfo blockInfo = level.BlockInfos[0];
return FindHeader(blockInfo.BlockHash, BlockTreeLookupOptions.None);
}
return null;
}
private void LoadStartBlock()
{
Block? startBlock = null;
byte[] persistedNumberData = _blockInfoDb.Get(StateHeadHashDbEntryAddress);
BestPersistedState = persistedNumberData is null ? null : new RlpStream(persistedNumberData).DecodeLong();
long? persistedNumber = BestPersistedState;
if (persistedNumber is not null)
{
startBlock = FindBlock(persistedNumber.Value, BlockTreeLookupOptions.None);
if (Logger.IsInfo) Logger.Info(
$"Start block loaded from reorg boundary - {persistedNumber} - {startBlock?.ToString(Block.Format.Short)}");
}
else
{
byte[] data = _blockInfoDb.Get(HeadAddressInDb);
if (data is not null)
{
startBlock = FindBlock(new Hash256(data), BlockTreeLookupOptions.None);
if (Logger.IsInfo) Logger.Info($"Start block loaded from HEAD - {startBlock?.ToString(Block.Format.Short)}");
}
}
if (startBlock is not null)
{
if (startBlock.Hash is null)
{
throw new InvalidDataException("The start block hash is null.");
}
SetHeadBlock(startBlock.Hash);
}
}
private void SetHeadBlock(Hash256 headHash)
{
Block? headBlock = FindBlock(headHash, BlockTreeLookupOptions.None) ?? throw new InvalidOperationException(
"An attempt to set a head block that has not been stored in the DB.");
ChainLevelInfo? level = LoadLevel(headBlock.Number);
int? index = level?.FindIndex(headHash);
if (!index.HasValue)
{
throw new InvalidDataException("Head block data missing from chain info");
}
headBlock.Header.TotalDifficulty = level.BlockInfos[index.Value].TotalDifficulty;
Head = headBlock;
}
private void LoadSyncPivot()
{
byte[]? pivotFromDb = _metadataDb.Get(MetadataDbKeys.UpdatedPivotData);
if (pivotFromDb is null)
{
_syncPivot = (_syncConfig.PivotNumber, _syncConfig.PivotHash is null ? null : new Hash256(Bytes.FromHexString(_syncConfig.PivotHash)));
return;
}
RlpStream pivotStream = new(pivotFromDb!);
long updatedPivotBlockNumber = pivotStream.DecodeLong();
Hash256 updatedPivotBlockHash = pivotStream.DecodeKeccak()!;
if (updatedPivotBlockHash.IsZero)
{
_syncPivot = (_syncConfig.PivotNumber, _syncConfig.PivotHash is null ? null : new Hash256(Bytes.FromHexString(_syncConfig.PivotHash)));
return;
}
SyncPivot = (updatedPivotBlockNumber, updatedPivotBlockHash);
_syncConfig.MaxAttemptsToUpdatePivot = 0; // Disable pivot updater
if (Logger.IsInfo) Logger.Info($"Pivot block has been set based on data from db. Pivot block number: {updatedPivotBlockNumber}, hash: {updatedPivotBlockHash}");
}
}