-
Notifications
You must be signed in to change notification settings - Fork 250
/
ForkChoice.java
854 lines (772 loc) · 37.8 KB
/
ForkChoice.java
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
/*
* Copyright Consensys Software Inc., 2022
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.statetransition.forkchoice;
import static com.google.common.base.Preconditions.checkArgument;
import static tech.pegasys.teku.infrastructure.logging.P2PLogger.P2P_LOG;
import static tech.pegasys.teku.infrastructure.time.TimeUtilities.secondsToMillis;
import static tech.pegasys.teku.spec.constants.NetworkConstants.INTERVALS_PER_SLOT;
import static tech.pegasys.teku.statetransition.forkchoice.StateRootCollector.addParentStateRoots;
import com.google.common.base.Throwables;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes32;
import org.hyperledger.besu.plugin.services.MetricsSystem;
import tech.pegasys.teku.infrastructure.async.ExceptionThrowingRunnable;
import tech.pegasys.teku.infrastructure.async.ExceptionThrowingSupplier;
import tech.pegasys.teku.infrastructure.async.SafeFuture;
import tech.pegasys.teku.infrastructure.async.eventthread.EventThread;
import tech.pegasys.teku.infrastructure.exceptions.ExceptionUtil;
import tech.pegasys.teku.infrastructure.exceptions.FatalServiceFailureException;
import tech.pegasys.teku.infrastructure.subscribers.Subscribers;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
import tech.pegasys.teku.spec.Spec;
import tech.pegasys.teku.spec.SpecVersion;
import tech.pegasys.teku.spec.cache.CapturingIndexedAttestationCache;
import tech.pegasys.teku.spec.cache.IndexedAttestationCache;
import tech.pegasys.teku.spec.datastructures.attestation.ValidatableAttestation;
import tech.pegasys.teku.spec.datastructures.blobs.versions.deneb.BlobSidecar;
import tech.pegasys.teku.spec.datastructures.blocks.BeaconBlock;
import tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock;
import tech.pegasys.teku.spec.datastructures.blocks.SlotAndBlockRoot;
import tech.pegasys.teku.spec.datastructures.forkchoice.InvalidCheckpointException;
import tech.pegasys.teku.spec.datastructures.forkchoice.ReadOnlyForkChoiceStrategy;
import tech.pegasys.teku.spec.datastructures.forkchoice.ReadOnlyStore;
import tech.pegasys.teku.spec.datastructures.forkchoice.VoteTracker;
import tech.pegasys.teku.spec.datastructures.forkchoice.VoteUpdater;
import tech.pegasys.teku.spec.datastructures.operations.AttesterSlashing;
import tech.pegasys.teku.spec.datastructures.operations.IndexedAttestation;
import tech.pegasys.teku.spec.datastructures.state.Checkpoint;
import tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState;
import tech.pegasys.teku.spec.datastructures.util.AttestationProcessingResult;
import tech.pegasys.teku.spec.datastructures.util.AttestationProcessingResult.Status;
import tech.pegasys.teku.spec.executionlayer.ExecutionLayerChannel;
import tech.pegasys.teku.spec.executionlayer.ForkChoiceState;
import tech.pegasys.teku.spec.executionlayer.PayloadStatus;
import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.StateTransitionException;
import tech.pegasys.teku.spec.logic.common.statetransition.results.BlockImportResult;
import tech.pegasys.teku.spec.logic.common.statetransition.results.BlockImportResult.FailureReason;
import tech.pegasys.teku.spec.logic.common.util.ForkChoiceUtil;
import tech.pegasys.teku.spec.logic.versions.deneb.blobs.BlobSidecarsAndValidationResult;
import tech.pegasys.teku.spec.logic.versions.deneb.blobs.BlobSidecarsAvailabilityChecker;
import tech.pegasys.teku.statetransition.attestation.DeferredAttestations;
import tech.pegasys.teku.statetransition.blobs.BlobSidecarManager;
import tech.pegasys.teku.statetransition.block.BlockImportPerformance;
import tech.pegasys.teku.statetransition.validation.AttestationStateSelector;
import tech.pegasys.teku.statetransition.validation.InternalValidationResult;
import tech.pegasys.teku.storage.client.RecentChainData;
import tech.pegasys.teku.storage.protoarray.DeferredVotes;
import tech.pegasys.teku.storage.protoarray.ForkChoiceStrategy;
import tech.pegasys.teku.storage.store.UpdatableStore;
import tech.pegasys.teku.storage.store.UpdatableStore.StoreTransaction;
public class ForkChoice implements ForkChoiceUpdatedResultSubscriber {
public static final int BLOCK_CREATION_TOLERANCE_MS = 500;
private static final Logger LOG = LogManager.getLogger();
private final Spec spec;
private final EventThread forkChoiceExecutor;
private final ForkChoiceStateProvider forkChoiceStateProvider;
private final RecentChainData recentChainData;
@SuppressWarnings("unused")
private final BlobSidecarManager blobSidecarManager;
private final ForkChoiceNotifier forkChoiceNotifier;
private final MergeTransitionBlockValidator transitionBlockValidator;
private final boolean forkChoiceUpdateHeadOnBlockImportEnabled;
private final AttestationStateSelector attestationStateSelector;
private final DeferredAttestations deferredAttestations = new DeferredAttestations();
private final Subscribers<OptimisticHeadSubscriber> optimisticSyncSubscribers =
Subscribers.create(true);
private final TickProcessor tickProcessor;
private Optional<Boolean> optimisticSyncing = Optional.empty();
public ForkChoice(
final Spec spec,
final EventThread forkChoiceExecutor,
final RecentChainData recentChainData,
final BlobSidecarManager blobSidecarManager,
final ForkChoiceNotifier forkChoiceNotifier,
final ForkChoiceStateProvider forkChoiceStateProvider,
final TickProcessor tickProcessor,
final MergeTransitionBlockValidator transitionBlockValidator,
final boolean forkChoiceUpdateHeadOnBlockImportEnabled,
final MetricsSystem metricsSystem) {
this.spec = spec;
this.forkChoiceExecutor = forkChoiceExecutor;
this.blobSidecarManager = blobSidecarManager;
this.forkChoiceStateProvider = forkChoiceStateProvider;
this.recentChainData = recentChainData;
this.forkChoiceNotifier = forkChoiceNotifier;
this.transitionBlockValidator = transitionBlockValidator;
this.attestationStateSelector =
new AttestationStateSelector(spec, recentChainData, metricsSystem);
this.tickProcessor = tickProcessor;
this.forkChoiceUpdateHeadOnBlockImportEnabled = forkChoiceUpdateHeadOnBlockImportEnabled;
recentChainData.subscribeStoreInitialized(this::initializeProtoArrayForkChoice);
forkChoiceNotifier.subscribeToForkChoiceUpdatedResult(this);
}
/**
* @deprecated Provided only to avoid having to hard code forkChoiceUpdateHeadOnBlockImportEnabled
* in lots of tests. Will be removed when the feature toggle is removed.
*/
@Deprecated
public ForkChoice(
final Spec spec,
final EventThread forkChoiceExecutor,
final RecentChainData recentChainData,
final BlobSidecarManager blobSidecarManager,
final ForkChoiceNotifier forkChoiceNotifier,
final MergeTransitionBlockValidator transitionBlockValidator,
final MetricsSystem metricsSystem) {
this(
spec,
forkChoiceExecutor,
recentChainData,
blobSidecarManager,
forkChoiceNotifier,
new ForkChoiceStateProvider(forkChoiceExecutor, recentChainData),
new TickProcessor(spec, recentChainData),
transitionBlockValidator,
true,
metricsSystem);
}
@Override
public void onForkChoiceUpdatedResult(
final ForkChoiceUpdatedResultNotification forkChoiceUpdatedResultNotification) {
forkChoiceUpdatedResultNotification
.getForkChoiceUpdatedResult()
.thenAccept(
maybeForkChoiceUpdatedResult ->
maybeForkChoiceUpdatedResult.ifPresent(
forkChoiceUpdatedResult -> {
if (forkChoiceUpdatedResultNotification.isTerminalBlockCall()
&& forkChoiceUpdatedResult.getPayloadStatus().hasInvalidStatus()) {
LOG.error(
"Execution engine considers INVALID recently provided terminal block {}",
forkChoiceUpdatedResultNotification
.getForkChoiceState()
.getHeadExecutionBlockHash());
return;
}
onExecutionPayloadResult(
forkChoiceUpdatedResultNotification
.getForkChoiceState()
.getHeadBlockRoot(),
forkChoiceUpdatedResult.getPayloadStatus());
}))
.finish(error -> LOG.error("Failed to update fork choice", error));
}
public SafeFuture<Boolean> processHead() {
return processHead(Optional.empty(), false);
}
/** Import a block to the store. */
public SafeFuture<BlockImportResult> onBlock(
final SignedBeaconBlock block,
final Optional<BlockImportPerformance> blockImportPerformance,
final ExecutionLayerChannel executionLayer) {
return recentChainData
.retrieveStateAtSlot(new SlotAndBlockRoot(block.getSlot(), block.getParentRoot()))
.thenPeek(__ -> blockImportPerformance.ifPresent(BlockImportPerformance::preStateRetrieved))
.thenCompose(
blockSlotState ->
onBlock(block, blockSlotState, blockImportPerformance, executionLayer));
}
public SafeFuture<AttestationProcessingResult> onAttestation(
final ValidatableAttestation attestation) {
return attestationStateSelector
.getStateToValidate(attestation.getData())
.thenCompose(
maybeState -> {
final UpdatableStore store = recentChainData.getStore();
final AttestationProcessingResult validationResult =
spec.validateAttestation(store, attestation, maybeState);
if (!validationResult.isSuccessful()) {
if (validationResult.getStatus() == Status.DEFER_FORK_CHOICE_PROCESSING) {
deferredAttestations.addAttestation(getIndexedAttestation(attestation));
}
return SafeFuture.completedFuture(validationResult);
}
return onForkChoiceThread(
() -> {
final VoteUpdater transaction = recentChainData.startVoteUpdate();
getForkChoiceStrategy()
.onAttestation(transaction, getIndexedAttestation(attestation));
transaction.commit();
})
.thenApply(__ -> validationResult);
})
.exceptionallyCompose(
error -> {
final Throwable rootCause = Throwables.getRootCause(error);
if (rootCause instanceof InvalidCheckpointException) {
return SafeFuture.completedFuture(
AttestationProcessingResult.invalid(rootCause.getMessage()));
}
return SafeFuture.failedFuture(error);
});
}
public void applyIndexedAttestations(final List<ValidatableAttestation> attestations) {
onForkChoiceThread(
() -> {
final VoteUpdater transaction = recentChainData.startVoteUpdate();
final ForkChoiceStrategy forkChoiceStrategy = getForkChoiceStrategy();
attestations.stream()
.map(this::getIndexedAttestation)
.forEach(
attestation -> forkChoiceStrategy.onAttestation(transaction, attestation));
transaction.commit();
})
.ifExceptionGetsHereRaiseABug();
}
public void onAttesterSlashing(
final AttesterSlashing slashing,
InternalValidationResult validationStatus,
boolean fromNetwork) {
if (!validationStatus.isAccept()) {
return;
}
onForkChoiceThread(
() -> {
final VoteUpdater transaction = recentChainData.startVoteUpdate();
storeEquivocatingIndices(slashing, transaction);
transaction.commit();
})
.ifExceptionGetsHereRaiseABug();
}
public void subscribeToOptimisticHeadChangesAndUpdate(OptimisticHeadSubscriber subscriber) {
optimisticSyncSubscribers.subscribe(subscriber);
getOptimisticSyncing().ifPresent(subscriber::onOptimisticHeadChanged);
}
public void onTick(
final UInt64 currentTimeMillis, final Optional<TickProcessingPerformance> performanceRecord) {
final UpdatableStore store = recentChainData.getStore();
final UInt64 slotAtStartOfTick = spec.getCurrentSlot(store);
tickProcessor.onTick(currentTimeMillis).join();
performanceRecord.ifPresent(TickProcessingPerformance::tickProcessorComplete);
final UInt64 currentSlot = spec.getCurrentSlot(store);
if (currentSlot.isGreaterThan(slotAtStartOfTick)) {
applyDeferredAttestations(currentSlot).ifExceptionGetsHereRaiseABug();
}
performanceRecord.ifPresent(TickProcessingPerformance::deferredAttestationsApplied);
}
private void initializeProtoArrayForkChoice() {
processHead().join();
}
SafeFuture<Boolean> processHead(final UInt64 nodeSlot) {
return processHead(Optional.of(nodeSlot), false);
}
private SafeFuture<Boolean> processHead(
final Optional<UInt64> nodeSlot, final boolean isPreProposal) {
final Checkpoint retrievedJustifiedCheckpoint =
recentChainData.getStore().getJustifiedCheckpoint();
return recentChainData
.retrieveCheckpointState(retrievedJustifiedCheckpoint)
.thenCompose(
maybeJustifiedCheckpointState ->
onForkChoiceThread(
() -> {
final Checkpoint finalizedCheckpoint =
recentChainData.getStore().getFinalizedCheckpoint();
final Checkpoint justifiedCheckpoint =
recentChainData.getStore().getJustifiedCheckpoint();
if (!justifiedCheckpoint.equals(retrievedJustifiedCheckpoint)) {
LOG.debug(
"Skipping head block update as justified checkpoint was updated while loading checkpoint state. Was {} ({}) but now {} ({})",
retrievedJustifiedCheckpoint::getEpoch,
retrievedJustifiedCheckpoint::getRoot,
justifiedCheckpoint::getEpoch,
justifiedCheckpoint::getRoot);
return false;
}
if (maybeJustifiedCheckpointState.isEmpty()) {
LOG.debug(
"Retrieved justified checkpoint state for {} was empty, cannot update head given current information.",
justifiedCheckpoint::getRoot);
return false;
}
updateHeadTransaction(
nodeSlot,
maybeJustifiedCheckpointState.orElseThrow(),
finalizedCheckpoint,
justifiedCheckpoint);
notifyForkChoiceUpdatedAndOptimisticSyncingChanged(
isPreProposal ? nodeSlot : Optional.empty());
return true;
}));
}
private void updateHeadTransaction(
final Optional<UInt64> nodeSlot,
final BeaconState justifiedState,
final Checkpoint finalizedCheckpoint,
final Checkpoint justifiedCheckpoint) {
final VoteUpdater transaction = recentChainData.startVoteUpdate();
final ReadOnlyForkChoiceStrategy forkChoiceStrategy = getForkChoiceStrategy();
final List<UInt64> justifiedEffectiveBalances =
spec.getBeaconStateUtil(justifiedState.getSlot())
.getEffectiveActiveUnslashedBalances(justifiedState);
final Bytes32 headBlockRoot =
transaction.applyForkChoiceScoreChanges(
recentChainData.getCurrentEpoch().orElseThrow(),
finalizedCheckpoint,
justifiedCheckpoint,
justifiedEffectiveBalances,
recentChainData.getStore().getProposerBoostRoot(),
spec.getProposerBoostAmount(justifiedState));
recentChainData.updateHead(
headBlockRoot,
nodeSlot.orElse(
forkChoiceStrategy
.blockSlot(headBlockRoot)
.orElseThrow(
() ->
new IllegalStateException(
"Unable to retrieve the slot of fork choice head: " + headBlockRoot))));
transaction.commit();
}
/**
* Import a block to the store. The supplied blockSlotState must already have empty slots
* processed to the same slot as the block.
*/
private SafeFuture<BlockImportResult> onBlock(
final SignedBeaconBlock block,
final Optional<BeaconState> blockSlotState,
final Optional<BlockImportPerformance> blockImportPerformance,
final ExecutionLayerChannel executionLayer) {
if (blockSlotState.isEmpty()) {
return SafeFuture.completedFuture(BlockImportResult.FAILED_UNKNOWN_PARENT);
}
checkArgument(
block.getSlot().equals(blockSlotState.get().getSlot()),
"State must have processed slots up to the block slot. Block slot %s, state slot %s",
block.getSlot(),
blockSlotState.get().getSlot());
final SpecVersion specVersion = spec.atSlot(block.getSlot());
final ForkChoicePayloadExecutor payloadExecutor =
ForkChoicePayloadExecutor.create(spec, recentChainData, block, executionLayer);
final ForkChoiceUtil forkChoiceUtil = specVersion.getForkChoiceUtil();
final BlockImportResult preconditionCheckResult =
forkChoiceUtil.checkOnBlockConditions(
block, blockSlotState.get(), recentChainData.getStore());
if (!preconditionCheckResult.isSuccessful()) {
reportInvalidBlock(block, preconditionCheckResult);
return SafeFuture.completedFuture(preconditionCheckResult);
}
final CapturingIndexedAttestationCache indexedAttestationCache =
IndexedAttestationCache.capturing();
final BlobSidecarsAvailabilityChecker blobSidecarsAvailabilityChecker =
blobSidecarManager.createAvailabilityChecker(block);
blobSidecarsAvailabilityChecker.initiateDataAvailabilityCheck();
final BeaconState postState;
try {
postState =
spec.getBlockProcessor(block.getSlot())
.processAndValidateBlock(
block,
blockSlotState.get(),
indexedAttestationCache,
Optional.of(payloadExecutor));
} catch (final StateTransitionException e) {
final BlockImportResult result = BlockImportResult.failedStateTransition(e);
reportInvalidBlock(block, result);
return SafeFuture.completedFuture(result);
}
blockImportPerformance.ifPresent(BlockImportPerformance::postStateCreated);
return payloadExecutor
.getExecutionResult()
.thenPeek(
__ -> blockImportPerformance.ifPresent(BlockImportPerformance::executionResultReceived))
.thenCombineAsync(
blobSidecarsAvailabilityChecker.getAvailabilityCheckResult(),
(payloadResult, blobSidecarsAndValidationResult) ->
importBlockAndState(
block,
blockSlotState.get(),
blockImportPerformance,
forkChoiceUtil,
indexedAttestationCache,
postState,
payloadResult,
blobSidecarsAndValidationResult),
forkChoiceExecutor);
}
private BlockImportResult importBlockAndState(
final SignedBeaconBlock block,
final BeaconState blockSlotState,
final Optional<BlockImportPerformance> blockImportPerformance,
final ForkChoiceUtil forkChoiceUtil,
final CapturingIndexedAttestationCache indexedAttestationCache,
final BeaconState postState,
final PayloadValidationResult payloadValidationResult,
final BlobSidecarsAndValidationResult blobSidecarsAndValidationResult) {
blockImportPerformance.ifPresent(BlockImportPerformance::beginImporting);
final PayloadStatus payloadResult = payloadValidationResult.getStatus();
if (payloadResult.hasInvalidStatus()) {
final BlockImportResult result =
BlockImportResult.failedStateTransition(
new IllegalStateException(
"Invalid ExecutionPayload: "
+ payloadResult.getValidationError().orElse("No reason provided")));
reportInvalidBlock(block, result);
payloadValidationResult
.getInvalidTransitionBlockRoot()
.ifPresentOrElse(
invalidTransitionBlockRoot ->
getForkChoiceStrategy()
.onExecutionPayloadResult(invalidTransitionBlockRoot, payloadResult, true),
() ->
getForkChoiceStrategy()
.onExecutionPayloadResult(block.getParentRoot(), payloadResult, false));
return result;
}
if (payloadResult.hasNotValidatedStatus()
&& !spec.atSlot(block.getSlot())
.getForkChoiceUtil()
.canOptimisticallyImport(recentChainData.getStore(), block)) {
return BlockImportResult.FAILED_EXECUTION_PAYLOAD_EXECUTION_SYNCING;
}
if (payloadResult.hasFailedExecution()) {
return BlockImportResult.failedExecutionPayloadExecution(
payloadResult.getFailureCause().orElseThrow());
}
switch (blobSidecarsAndValidationResult.getValidationResult()) {
case VALID:
case NOT_REQUIRED:
LOG.debug(
"blobSidecars validation result: {}", blobSidecarsAndValidationResult::toLogString);
break;
case NOT_AVAILABLE:
LOG.warn(
"blobSidecars validation result: {}", blobSidecarsAndValidationResult::toLogString);
return BlockImportResult.failedDataAvailabilityCheckNotAvailable(
blobSidecarsAndValidationResult.getCause());
case INVALID:
LOG.error(
"blobSidecars validation result: {}", blobSidecarsAndValidationResult::toLogString);
return BlockImportResult.failedDataAvailabilityCheckInvalid(
blobSidecarsAndValidationResult.getCause());
}
final ForkChoiceStrategy forkChoiceStrategy = getForkChoiceStrategy();
// Now that we're on the fork choice thread, make sure the block still descends from finalized
// (which may have changed while we were processing the block)
if (!forkChoiceUtil.blockDescendsFromLatestFinalizedBlock(
block, recentChainData.getStore(), forkChoiceStrategy)) {
return BlockImportResult.FAILED_INVALID_ANCESTRY;
}
final StoreTransaction transaction = recentChainData.startStoreTransaction();
addParentStateRoots(spec, blockSlotState, transaction);
final List<BlobSidecar> blobSidecars;
if (blobSidecarsAndValidationResult.isNotRequired()) {
// Outside availability window or pre-Deneb
blobSidecars = Collections.emptyList();
} else if (blobSidecarsAndValidationResult.isValid()) {
blobSidecars = blobSidecarsAndValidationResult.getBlobSidecars();
} else {
throw new IllegalStateException(
String.format(
"Unexpected attempt to store invalid blob sidecars (%s) for block: %s",
blobSidecarsAndValidationResult.getBlobSidecars().size(), block.toLogString()));
}
final Optional<UInt64> earliestBlobSidecarsSlot =
computeEarliestBlobSidecarsSlot(
recentChainData.getStore(), blobSidecarsAndValidationResult, block.getMessage());
forkChoiceUtil.applyBlockToStore(
transaction,
block,
postState,
payloadResult.hasNotValidatedStatus(),
blobSidecars,
earliestBlobSidecarsSlot);
if (spec.getCurrentSlot(transaction).equals(block.getSlot())) {
final UInt64 millisPerSlot = spec.getMillisPerSlot(block.getSlot());
final UInt64 timeIntoSlotMillis = getMillisIntoSlot(transaction, millisPerSlot);
if (isBeforeAttestingInterval(millisPerSlot, timeIntoSlotMillis)) {
transaction.setProposerBoostRoot(block.getRoot());
}
}
blockImportPerformance.ifPresent(BlockImportPerformance::transactionReady);
// Note: not using thenRun here because we want to ensure each step is on the event thread
transaction.commit().join();
blockImportPerformance.ifPresent(BlockImportPerformance::transactionCommitted);
forkChoiceStrategy.onExecutionPayloadResult(block.getRoot(), payloadResult, true);
final UInt64 currentEpoch = spec.computeEpochAtSlot(spec.getCurrentSlot(transaction));
// We only need to apply attestations from the current or previous epoch. If the block is from
// before that, none of the attestations will be applicable so just skip the whole step.
if (spec.computeEpochAtSlot(block.getSlot())
.isGreaterThanOrEqualTo(currentEpoch.minusMinZero(1))) {
final VoteUpdater voteUpdater = recentChainData.startVoteUpdate();
// We also need to handle recent AttesterSlashings to update equivocating validator indices
// We don't need any epochs older than previous as it doesn't affect ForkChoice
applyAttesterSlashingsFromBlock(block, voteUpdater);
applyVotesFromBlock(forkChoiceStrategy, currentEpoch, indexedAttestationCache, voteUpdater);
voteUpdater.commit();
}
final BlockImportResult result;
if (payloadResult.hasValidStatus()) {
result = BlockImportResult.successful(block);
} else {
result = BlockImportResult.optimisticallySuccessful(block);
}
updateForkChoiceForImportedBlock(block, result, forkChoiceStrategy);
notifyForkChoiceUpdatedAndOptimisticSyncingChanged(Optional.empty());
return result;
}
/**
* In order to keep track of DataAvailability Window, we need to compute the earliest slot we can
* consider data available for the given block. It needs to take in account possible empty slots
* so the actual slot should be parent block slot + 1. Moreover, we need to manage the case in
* which the calculated slot is before Deneb activation, so it should never be before the first
* deneb slot.
*
* @param store requires for data availability window calculation
* @param blobSidecarsAndValidationResult If it's not required or invalid, we could skip
* calculation
* @param block Beacon block
* @return the slot we could mark as earliestBlobSidecarsSlot if any, otherwise Optional.empty()
*/
private Optional<UInt64> computeEarliestBlobSidecarsSlot(
final ReadOnlyStore store,
final BlobSidecarsAndValidationResult blobSidecarsAndValidationResult,
final BeaconBlock block) {
if (!blobSidecarsAndValidationResult.isValid()) {
return Optional.empty();
}
final UInt64 earliestAffectedSlot =
recentChainData
.getSlotForBlockRoot(block.getParentRoot())
.map(UInt64::increment)
.orElse(block.getSlot());
final Optional<UInt64> maybeEarliestAvailabilityWindowSlotBeforeBlock =
spec.atSlot(block.getSlot())
.getForkChoiceUtil()
.getEarliestAvailabilityWindowSlotBeforeBlock(spec, store, block.getSlot());
return maybeEarliestAvailabilityWindowSlotBeforeBlock.map(
earliestAvailabilityWindowSlotBeforeBlock ->
earliestAvailabilityWindowSlotBeforeBlock.max(earliestAffectedSlot));
}
private UInt64 getMillisIntoSlot(StoreTransaction transaction, UInt64 millisPerSlot) {
return transaction
.getTimeMillis()
.minus(secondsToMillis(transaction.getGenesisTime()))
.mod(millisPerSlot);
}
private boolean isBeforeAttestingInterval(
final UInt64 millisPerSlot, final UInt64 timeIntoSlotMillis) {
UInt64 oneThirdSlot = millisPerSlot.dividedBy(INTERVALS_PER_SLOT);
return timeIntoSlotMillis.isLessThan(oneThirdSlot);
}
private void onExecutionPayloadResult(
final Bytes32 blockRoot, final PayloadStatus payloadResult) {
final SafeFuture<PayloadValidationResult> transitionValidatedStatus;
if (payloadResult.hasValidStatus()) {
transitionValidatedStatus = transitionBlockValidator.verifyAncestorTransitionBlock(blockRoot);
} else {
transitionValidatedStatus =
SafeFuture.completedFuture(new PayloadValidationResult(payloadResult));
}
transitionValidatedStatus.finishAsync(
result -> {
final PayloadStatus resultStatus = result.getStatus();
final Bytes32 validatedBlockRoot =
result.getInvalidTransitionBlockRoot().orElse(blockRoot);
getForkChoiceStrategy().onExecutionPayloadResult(validatedBlockRoot, resultStatus, true);
if (resultStatus.hasInvalidStatus()) {
LOG.warn("Will run fork choice because head block {} was invalid", validatedBlockRoot);
processHead().finish(error -> LOG.error("Fork choice updating head failed", error));
}
},
error -> {
// Pass FatalServiceFailureException up to the uncaught exception handler.
// This will cause teku to exit because the error is unrecoverable.
// We specifically do this here because a FatalServiceFailureException will be thrown if
// a justified or finalized block is found to be invalid.
if (ExceptionUtil.hasCause(error, FatalServiceFailureException.class)) {
Thread.currentThread()
.getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(), error);
} else {
LOG.error("Failed to apply payload result for block {}", blockRoot, error);
}
},
forkChoiceExecutor);
}
private void updateForkChoiceForImportedBlock(
final SignedBeaconBlock block,
final BlockImportResult result,
final ForkChoiceStrategy forkChoiceStrategy) {
final SlotAndBlockRoot bestHeadBlock = findNewChainHead(block, forkChoiceStrategy);
if (!bestHeadBlock.getBlockRoot().equals(recentChainData.getBestBlockRoot().orElseThrow())) {
recentChainData.updateHead(bestHeadBlock.getBlockRoot(), bestHeadBlock.getSlot());
if (bestHeadBlock.getBlockRoot().equals(block.getRoot())) {
result.markAsCanonical();
}
}
}
private SlotAndBlockRoot findNewChainHead(
final SignedBeaconBlock block, final ForkChoiceStrategy forkChoiceStrategy) {
// If the new block builds on our current chain head it must be the new chain head.
// Since fork choice works by walking down the tree selecting the child block with
// the greatest weight, when a block has only one child it will automatically become
// a better choice than the block itself. So the first block we receive that is a
// child of our current chain head, must be the new chain head. If we'd had any other
// child of the current chain head we'd have already selected it as head.
if (forkChoiceUpdateHeadOnBlockImportEnabled
&& recentChainData
.getBestBlockRoot()
.map(chainHeadRoot -> chainHeadRoot.equals(block.getParentRoot()))
.orElse(false)) {
// NOTE: disabled by --Xfork-choice-update-head-on-block-import-enabled=false,
// this check avoids running fork choice on blocks that arrive if they descend from head,
// but we're far better off just running fork choice and applying the normal rules
return new SlotAndBlockRoot(block.getSlot(), block.getRoot());
}
// Otherwise, use fork choice to find the new chain head as if this block is on time the
// proposer weighting may cause us to reorg.
// During sync, this may be noticeably slower than just comparing the chain head due to the way
// ProtoArray skips updating all ancestors when adding a new block but it's cheap when in sync.
final Checkpoint justifiedCheckpoint = recentChainData.getJustifiedCheckpoint().orElseThrow();
final Checkpoint finalizedCheckpoint = recentChainData.getFinalizedCheckpoint().orElseThrow();
return forkChoiceStrategy.findHead(
recentChainData.getCurrentEpoch().orElseThrow(), justifiedCheckpoint, finalizedCheckpoint);
}
private void reportInvalidBlock(final SignedBeaconBlock block, final BlockImportResult result) {
if (result.getFailureReason() == FailureReason.BLOCK_IS_FROM_FUTURE) {
return;
}
P2P_LOG.onInvalidBlock(
block.getSlot(),
block.getRoot(),
block.sszSerialize(),
result.getFailureReason().name(),
result.getFailureCause());
}
private void notifyForkChoiceUpdatedAndOptimisticSyncingChanged(
final Optional<UInt64> proposingSlot) {
final ForkChoiceState forkChoiceState = forkChoiceStateProvider.getForkChoiceStateSync();
forkChoiceNotifier.onForkChoiceUpdated(forkChoiceState, proposingSlot);
if (optimisticSyncing
.map(oldValue -> !oldValue.equals(forkChoiceState.isHeadOptimistic()))
.orElse(true)) {
optimisticSyncing = Optional.of(forkChoiceState.isHeadOptimistic());
optimisticSyncSubscribers.deliver(
OptimisticHeadSubscriber::onOptimisticHeadChanged, forkChoiceState.isHeadOptimistic());
}
}
private void applyVotesFromBlock(
final ForkChoiceStrategy forkChoiceStrategy,
final UInt64 currentEpoch,
final CapturingIndexedAttestationCache indexedAttestationProvider,
final VoteUpdater voteUpdater) {
indexedAttestationProvider.getIndexedAttestations().stream()
.filter(
attestation -> validateBlockAttestation(forkChoiceStrategy, currentEpoch, attestation))
.forEach(attestation -> forkChoiceStrategy.onAttestation(voteUpdater, attestation));
}
private boolean validateBlockAttestation(
final ForkChoiceStrategy forkChoiceStrategy,
final UInt64 currentEpoch,
final IndexedAttestation attestation) {
return spec.atSlot(attestation.getData().getSlot())
.getForkChoiceUtil()
.validateOnAttestation(forkChoiceStrategy, currentEpoch, attestation.getData())
.isSuccessful();
}
private SafeFuture<Void> applyDeferredAttestations(
final Collection<DeferredVotes> deferredVoteUpdates) {
return onForkChoiceThread(
() -> {
final VoteUpdater transaction = recentChainData.startVoteUpdate();
final ForkChoiceStrategy forkChoiceStrategy = getForkChoiceStrategy();
deferredVoteUpdates.forEach(
update -> forkChoiceStrategy.applyDeferredAttestations(transaction, update));
transaction.commit();
});
}
private void applyAttesterSlashingsFromBlock(
final SignedBeaconBlock signedBeaconBlock, final VoteUpdater voteUpdater) {
signedBeaconBlock
.getMessage()
.getBody()
.getAttesterSlashings()
.forEach(attesterSlashing -> storeEquivocatingIndices(attesterSlashing, voteUpdater));
}
private void storeEquivocatingIndices(
final AttesterSlashing attesterSlashing, final VoteUpdater transaction) {
attesterSlashing
.getIntersectingValidatorIndices()
.forEach(
validatorIndex -> {
final VoteTracker voteTracker = transaction.getVote(validatorIndex);
transaction.putVote(validatorIndex, voteTracker.createNextEquivocating());
});
}
SafeFuture<Void> prepareForBlockProduction(final UInt64 slot) {
final UInt64 slotStartTimeMillis =
spec.getSlotStartTimeMillis(slot, recentChainData.getGenesisTimeMillis());
final UInt64 currentTime = recentChainData.getStore().getTimeMillis();
// We haven't yet transitioned into this slot but will do very soon, so make it happen now
if (!currentTime
.plus(BLOCK_CREATION_TOLERANCE_MS)
.isGreaterThanOrEqualTo(slotStartTimeMillis)) {
// Creating a block too far before the slot start, don't run fork choice at all.
LOG.warn(
"Block creation requested more than {}ms before the start of slot {}",
BLOCK_CREATION_TOLERANCE_MS,
slot);
return SafeFuture.COMPLETE;
}
return SafeFuture.allOf(
tickProcessor.onTick(slotStartTimeMillis), applyDeferredAttestations(slot))
.thenCompose(__ -> processHead(Optional.of(slot), true))
.toVoid();
}
private SafeFuture<Void> applyDeferredAttestations(final UInt64 slot) {
final Collection<DeferredVotes> deferredVoteUpdates = deferredAttestations.prune(slot);
if (deferredVoteUpdates.isEmpty()) {
return SafeFuture.COMPLETE;
}
return applyDeferredAttestations(deferredVoteUpdates);
}
private ForkChoiceStrategy getForkChoiceStrategy() {
forkChoiceExecutor.checkOnEventThread();
return recentChainData
.getUpdatableForkChoiceStrategy()
.orElseThrow(
() ->
new IllegalStateException(
"Attempting to perform fork choice operations before store has been initialized"));
}
private IndexedAttestation getIndexedAttestation(final ValidatableAttestation attestation) {
return attestation
.getIndexedAttestation()
.orElseThrow(
() ->
new UnsupportedOperationException(
"ValidateableAttestation does not have an IndexedAttestation."));
}
private SafeFuture<Void> onForkChoiceThread(final ExceptionThrowingRunnable task) {
return onForkChoiceThread(
() -> {
task.run();
return null;
});
}
private <T> SafeFuture<T> onForkChoiceThread(final ExceptionThrowingSupplier<T> task) {
return forkChoiceExecutor.execute(task);
}
private Optional<Boolean> getOptimisticSyncing() {
return optimisticSyncing;
}
public interface OptimisticHeadSubscriber {
void onOptimisticHeadChanged(boolean isHeadOptimistic);
}
}