forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 8
/
stage_headers.go
1177 lines (1063 loc) · 36.3 KB
/
stage_headers.go
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
package stagedsync
import (
"context"
"encoding/binary"
"fmt"
"math/big"
"runtime"
"time"
"github.com/c2h5oh/datasize"
"github.com/ledgerwatch/erigon-lib/chain"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/dbg"
"github.com/ledgerwatch/erigon-lib/common/hexutility"
"github.com/ledgerwatch/erigon-lib/etl"
"github.com/ledgerwatch/erigon-lib/gointerfaces/remote"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/log/v3"
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/math"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/ethdb/privateapi"
"github.com/ledgerwatch/erigon/rlp"
"github.com/ledgerwatch/erigon/turbo/engineapi"
"github.com/ledgerwatch/erigon/turbo/services"
"github.com/ledgerwatch/erigon/turbo/shards"
"github.com/ledgerwatch/erigon/turbo/snapshotsync"
"github.com/ledgerwatch/erigon/turbo/stages/bodydownload"
"github.com/ledgerwatch/erigon/turbo/stages/headerdownload"
)
// The number of blocks we should be able to re-org sub-second on commodity hardware.
// See https://hackmd.io/TdJtNs0dS56q-In8h-ShSg
const ShortPoSReorgThresholdBlocks = 10
type HeadersCfg struct {
db kv.RwDB
hd *headerdownload.HeaderDownload
bodyDownload *bodydownload.BodyDownload
chainConfig chain.Config
headerReqSend func(context.Context, *headerdownload.HeaderRequest) ([64]byte, bool)
announceNewHashes func(context.Context, []headerdownload.Announce)
penalize func(context.Context, []headerdownload.PenaltyItem)
batchSize datasize.ByteSize
noP2PDiscovery bool
tmpdir string
snapshots *snapshotsync.RoSnapshots
blockReader services.FullBlockReader
forkValidator *engineapi.ForkValidator
notifications *shards.Notifications
}
func StageHeadersCfg(
db kv.RwDB,
headerDownload *headerdownload.HeaderDownload,
bodyDownload *bodydownload.BodyDownload,
chainConfig chain.Config,
headerReqSend func(context.Context, *headerdownload.HeaderRequest) ([64]byte, bool),
announceNewHashes func(context.Context, []headerdownload.Announce),
penalize func(context.Context, []headerdownload.PenaltyItem),
batchSize datasize.ByteSize,
noP2PDiscovery bool,
snapshots *snapshotsync.RoSnapshots,
blockReader services.FullBlockReader,
tmpdir string,
notifications *shards.Notifications,
forkValidator *engineapi.ForkValidator) HeadersCfg {
return HeadersCfg{
db: db,
hd: headerDownload,
bodyDownload: bodyDownload,
chainConfig: chainConfig,
headerReqSend: headerReqSend,
announceNewHashes: announceNewHashes,
penalize: penalize,
batchSize: batchSize,
tmpdir: tmpdir,
noP2PDiscovery: noP2PDiscovery,
snapshots: snapshots,
blockReader: blockReader,
forkValidator: forkValidator,
notifications: notifications,
}
}
func SpawnStageHeaders(
s *StageState,
u Unwinder,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
initialCycle bool,
test bool, // Set to true in tests, allows the stage to fail rather than wait indefinitely
) error {
useExternalTx := tx != nil
if !useExternalTx {
var err error
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
if initialCycle && cfg.snapshots != nil && cfg.snapshots.Cfg().Enabled {
if err := cfg.hd.AddHeadersFromSnapshot(tx, cfg.snapshots.BlocksAvailable(), cfg.blockReader); err != nil {
return err
}
}
var preProgress uint64
if s == nil {
preProgress = 0
} else {
preProgress = s.BlockNumber
}
notBorAndParlia := cfg.chainConfig.Bor == nil && cfg.chainConfig.Parlia == nil
unsettledForkChoice, headHeight := cfg.hd.GetUnsettledForkChoice()
if notBorAndParlia && unsettledForkChoice != nil { // some work left to do after unwind
return finishHandlingForkChoice(unsettledForkChoice, headHeight, s, tx, cfg, useExternalTx)
}
transitionedToPoS := cfg.chainConfig.TerminalTotalDifficultyPassed
if notBorAndParlia && !transitionedToPoS {
var err error
transitionedToPoS, err = rawdb.Transitioned(tx, preProgress, cfg.chainConfig.TerminalTotalDifficulty)
if err != nil {
return err
}
if transitionedToPoS {
cfg.hd.SetFirstPoSHeight(preProgress)
}
}
if transitionedToPoS {
libcommon.SafeClose(cfg.hd.QuitPoWMining)
return HeadersPOS(s, u, ctx, tx, cfg, initialCycle, test, useExternalTx, preProgress)
} else {
return HeadersPOW(s, u, ctx, tx, cfg, initialCycle, test, useExternalTx)
}
}
// HeadersPOS processes Proof-of-Stake requests (newPayload, forkchoiceUpdated).
// It also saves PoS headers downloaded by (*HeaderDownload)StartPoSDownloader into the DB.
func HeadersPOS(
s *StageState,
u Unwinder,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
initialCycle bool,
test bool,
useExternalTx bool,
preProgress uint64,
) error {
/*
if initialCycle {
// Let execution and other stages to finish before waiting for CL, but only if other stages aren't ahead
if execProgress, err := stages.GetStageProgress(tx, stages.Execution); err != nil {
return err
} else if s.BlockNumber >= execProgress {
return nil
}
}
*/
cfg.hd.SetPOSSync(true)
syncing := cfg.hd.PosStatus() != headerdownload.Idle
if !syncing {
log.Info(fmt.Sprintf("[%s] Waiting for Consensus Layer...", s.LogPrefix()))
}
interrupt, requestId, requestWithStatus := cfg.hd.BeaconRequestList.WaitForRequest(syncing, test)
cfg.hd.SetHeaderReader(&ChainReaderImpl{config: &cfg.chainConfig, tx: tx, blockReader: cfg.blockReader})
headerInserter := headerdownload.NewHeaderInserter(s.LogPrefix(), nil, s.BlockNumber, cfg.blockReader)
interrupted, err := handleInterrupt(interrupt, cfg, tx, headerInserter, useExternalTx)
if err != nil {
return err
}
if interrupted {
return nil
}
if requestWithStatus == nil {
log.Warn(fmt.Sprintf("[%s] Nil beacon request. Should only happen in tests", s.LogPrefix()))
return nil
}
request := requestWithStatus.Message
requestStatus := requestWithStatus.Status
// Decide what kind of action we need to take place
forkChoiceMessage, forkChoiceInsteadOfNewPayload := request.(*engineapi.ForkChoiceMessage)
cfg.hd.ClearPendingPayloadHash()
cfg.hd.SetPendingPayloadStatus(nil)
var payloadStatus *engineapi.PayloadStatus
if forkChoiceInsteadOfNewPayload {
payloadStatus, err = startHandlingForkChoice(forkChoiceMessage, requestStatus, requestId, s, u, ctx, tx, cfg, test, headerInserter, preProgress)
} else {
payloadMessage := request.(*types.Block)
payloadStatus, err = handleNewPayload(payloadMessage, requestStatus, requestId, s, ctx, tx, cfg, test, headerInserter)
}
if err != nil {
if requestStatus == engineapi.New {
cfg.hd.PayloadStatusCh <- engineapi.PayloadStatus{CriticalError: err}
}
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
if requestStatus == engineapi.New && payloadStatus != nil {
if payloadStatus.Status == remote.EngineStatus_SYNCING || payloadStatus.Status == remote.EngineStatus_ACCEPTED || !useExternalTx {
cfg.hd.PayloadStatusCh <- *payloadStatus
} else {
// Let the stage loop run to the end so that the transaction is committed prior to replying to CL
cfg.hd.SetPendingPayloadStatus(payloadStatus)
}
}
return nil
}
func writeForkChoiceHashes(
forkChoice *engineapi.ForkChoiceMessage,
s *StageState,
tx kv.RwTx,
cfg HeadersCfg,
) (bool, error) {
if forkChoice.SafeBlockHash != (libcommon.Hash{}) {
safeIsCanonical, err := rawdb.IsCanonicalHash(tx, forkChoice.SafeBlockHash)
if err != nil {
return false, err
}
if !safeIsCanonical {
log.Warn(fmt.Sprintf("[%s] Non-canonical SafeBlockHash", s.LogPrefix()), "forkChoice", forkChoice)
return false, nil
}
}
if forkChoice.FinalizedBlockHash != (libcommon.Hash{}) {
finalizedIsCanonical, err := rawdb.IsCanonicalHash(tx, forkChoice.FinalizedBlockHash)
if err != nil {
return false, err
}
if !finalizedIsCanonical {
log.Warn(fmt.Sprintf("[%s] Non-canonical FinalizedBlockHash", s.LogPrefix()), "forkChoice", forkChoice)
return false, nil
}
}
rawdb.WriteForkchoiceHead(tx, forkChoice.HeadBlockHash)
if forkChoice.SafeBlockHash != (libcommon.Hash{}) {
rawdb.WriteForkchoiceSafe(tx, forkChoice.SafeBlockHash)
}
if forkChoice.FinalizedBlockHash != (libcommon.Hash{}) {
rawdb.WriteForkchoiceFinalized(tx, forkChoice.FinalizedBlockHash)
}
return true, nil
}
func startHandlingForkChoice(
forkChoice *engineapi.ForkChoiceMessage,
requestStatus engineapi.RequestStatus,
requestId int,
s *StageState,
u Unwinder,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
test bool,
headerInserter *headerdownload.HeaderInserter,
preProgress uint64,
) (*engineapi.PayloadStatus, error) {
defer cfg.forkValidator.ClearWithUnwind(tx, cfg.notifications.Accumulator, cfg.notifications.StateChangesConsumer)
headerHash := forkChoice.HeadBlockHash
log.Debug(fmt.Sprintf("[%s] Handling fork choice", s.LogPrefix()), "headerHash", headerHash)
currentHeadHash := rawdb.ReadHeadHeaderHash(tx)
if currentHeadHash == headerHash { // no-op
log.Debug(fmt.Sprintf("[%s] Fork choice no-op", s.LogPrefix()))
cfg.hd.BeaconRequestList.Remove(requestId)
canonical, err := writeForkChoiceHashes(forkChoice, s, tx, cfg)
if err != nil {
log.Warn(fmt.Sprintf("[%s] Fork choice err", s.LogPrefix()), "err", err)
return nil, err
}
if canonical {
return &engineapi.PayloadStatus{
Status: remote.EngineStatus_VALID,
LatestValidHash: currentHeadHash,
}, nil
} else {
return &engineapi.PayloadStatus{
CriticalError: &privateapi.InvalidForkchoiceStateErr,
}, nil
}
}
// Header itself may already be in the snapshots, if CL starts off at much earlier state than Erigon
header, err := cfg.blockReader.HeaderByHash(ctx, tx, headerHash)
if err != nil {
log.Warn(fmt.Sprintf("[%s] Fork choice err (reading header by hash %x)", s.LogPrefix(), headerHash), "err", err)
cfg.hd.BeaconRequestList.Remove(requestId)
return nil, err
}
if header == nil {
log.Debug(fmt.Sprintf("[%s] Fork choice: need to download header with hash %x", s.LogPrefix(), headerHash))
if test {
cfg.hd.BeaconRequestList.Remove(requestId)
} else {
schedulePoSDownload(requestId, headerHash, 0 /* header height is unknown, setting to 0 */, headerHash, s, cfg)
}
return &engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}, nil
}
cfg.hd.BeaconRequestList.Remove(requestId)
headerNumber := header.Number.Uint64()
if headerHash == cfg.forkValidator.ExtendingForkHeadHash() {
log.Info(fmt.Sprintf("[%s] Fork choice update: flushing in-memory state (built by previous newPayload)", s.LogPrefix()))
if err := cfg.forkValidator.FlushExtendingFork(tx, cfg.notifications.Accumulator); err != nil {
return nil, err
}
cfg.hd.BeaconRequestList.Remove(requestId)
canonical, err := writeForkChoiceHashes(forkChoice, s, tx, cfg)
if err != nil {
log.Warn(fmt.Sprintf("[%s] Fork choice err", s.LogPrefix()), "err", err)
return nil, err
}
if canonical {
cfg.hd.SetPendingPayloadHash(headerHash)
return nil, nil
} else {
return &engineapi.PayloadStatus{
CriticalError: &privateapi.InvalidForkchoiceStateErr,
}, nil
}
}
forkingPoint, err := forkingPoint(ctx, tx, headerInserter, cfg.blockReader, header)
if err != nil {
return nil, err
}
if forkingPoint < preProgress {
log.Info(fmt.Sprintf("[%s] Fork choice: re-org", s.LogPrefix()), "goal", headerNumber, "from", preProgress, "unwind to", forkingPoint)
if requestStatus == engineapi.New {
if headerNumber-forkingPoint <= ShortPoSReorgThresholdBlocks {
// TODO(yperbasis): what if some bodies are missing and we have to download them?
cfg.hd.SetPendingPayloadHash(headerHash)
} else {
cfg.hd.PayloadStatusCh <- engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}
}
}
u.UnwindTo(forkingPoint, libcommon.Hash{})
cfg.hd.SetUnsettledForkChoice(forkChoice, headerNumber)
} else {
// Extend canonical chain by the new header
log.Info(fmt.Sprintf("[%s] Fork choice: chain extension", s.LogPrefix()), "from", preProgress, "to", headerNumber)
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
if err = fixCanonicalChain(s.LogPrefix(), logEvery, headerNumber, headerHash, tx, cfg.blockReader); err != nil {
return nil, err
}
if err = rawdb.WriteHeadHeaderHash(tx, forkChoice.HeadBlockHash); err != nil {
return nil, err
}
canonical, err := writeForkChoiceHashes(forkChoice, s, tx, cfg)
if err != nil {
return nil, err
}
if err := s.Update(tx, headerNumber); err != nil {
return nil, err
}
// Referesh currentHeadHash
currentHeadHash = rawdb.ReadHeadHeaderHash(tx)
if canonical {
return &engineapi.PayloadStatus{
Status: remote.EngineStatus_VALID,
LatestValidHash: currentHeadHash,
}, nil
} else {
return &engineapi.PayloadStatus{
CriticalError: &privateapi.InvalidForkchoiceStateErr,
}, nil
}
}
return nil, nil
}
func finishHandlingForkChoice(
forkChoice *engineapi.ForkChoiceMessage,
headHeight uint64,
s *StageState,
tx kv.RwTx,
cfg HeadersCfg,
useExternalTx bool,
) error {
log.Info(fmt.Sprintf("[%s] Unsettled forkchoice after unwind", s.LogPrefix()), "height", headHeight, "forkchoice", forkChoice)
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
if err := fixCanonicalChain(s.LogPrefix(), logEvery, headHeight, forkChoice.HeadBlockHash, tx, cfg.blockReader); err != nil {
return err
}
if err := rawdb.WriteHeadHeaderHash(tx, forkChoice.HeadBlockHash); err != nil {
return err
}
canonical, err := writeForkChoiceHashes(forkChoice, s, tx, cfg)
if err != nil {
return err
}
if err := s.Update(tx, headHeight); err != nil {
return err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
if !canonical {
if cfg.hd.GetPendingPayloadHash() != (libcommon.Hash{}) {
cfg.hd.PayloadStatusCh <- engineapi.PayloadStatus{
CriticalError: &privateapi.InvalidForkchoiceStateErr,
}
}
cfg.hd.ClearPendingPayloadHash()
}
cfg.hd.ClearUnsettledForkChoice()
return nil
}
func handleNewPayload(
block *types.Block,
requestStatus engineapi.RequestStatus,
requestId int,
s *StageState,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
test bool,
headerInserter *headerdownload.HeaderInserter,
) (*engineapi.PayloadStatus, error) {
header := block.Header()
headerNumber := header.Number.Uint64()
headerHash := block.Hash()
log.Info(fmt.Sprintf("[%s] Handling new payload", s.LogPrefix()), "height", headerNumber, "hash", headerHash)
parent, err := cfg.blockReader.HeaderByHash(ctx, tx, header.ParentHash)
if err != nil {
return nil, err
}
if parent == nil {
log.Debug(fmt.Sprintf("[%s] New payload: need to download parent", s.LogPrefix()), "height", headerNumber, "hash", headerHash, "parentHash", header.ParentHash)
if test {
cfg.hd.BeaconRequestList.Remove(requestId)
return &engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}, nil
}
if !schedulePoSDownload(requestId, header.ParentHash, headerNumber-1, headerHash /* downloaderTip */, s, cfg) {
return &engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}, nil
}
currentHeadNumber := rawdb.ReadCurrentBlockNumber(tx)
if currentHeadNumber != nil && math.AbsoluteDifference(*currentHeadNumber, headerNumber) < 32 {
// We try waiting until we finish downloading the PoS blocks if the distance from the head is enough,
// so that we will perform full validation.
success := false
for i := 0; i < 10; i++ {
time.Sleep(10 * time.Millisecond)
if cfg.hd.PosStatus() == headerdownload.Synced {
success = true
break
}
}
if success {
// If we downloaded the headers in time, then save them and proceed with the new header
saveDownloadedPoSHeaders(tx, cfg, headerInserter, true /* validate */)
} else {
return &engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}, nil
}
} else {
return &engineapi.PayloadStatus{Status: remote.EngineStatus_SYNCING}, nil
}
}
cfg.hd.BeaconRequestList.Remove(requestId)
log.Debug(fmt.Sprintf("[%s] New payload begin verification", s.LogPrefix()))
response, success, err := verifyAndSaveNewPoSHeader(requestStatus, s, ctx, tx, cfg, block, headerInserter)
log.Debug(fmt.Sprintf("[%s] New payload verification ended", s.LogPrefix()), "success", success, "err", err)
if err != nil || !success {
return response, err
}
if cfg.bodyDownload != nil {
cfg.bodyDownload.AddToPrefetch(header, block.RawBody())
}
return response, nil
}
func verifyAndSaveNewPoSHeader(
requestStatus engineapi.RequestStatus,
s *StageState,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
block *types.Block,
headerInserter *headerdownload.HeaderInserter,
) (response *engineapi.PayloadStatus, success bool, err error) {
header := block.Header()
headerNumber := header.Number.Uint64()
headerHash := block.Hash()
bad, lastValidHash := cfg.hd.IsBadHeaderPoS(headerHash)
if bad {
return &engineapi.PayloadStatus{Status: remote.EngineStatus_INVALID, LatestValidHash: lastValidHash}, false, nil
}
if verificationErr := cfg.hd.VerifyHeader(header); verificationErr != nil {
log.Warn("Verification failed for header", "hash", headerHash, "height", headerNumber, "err", verificationErr)
cfg.hd.ReportBadHeaderPoS(headerHash, header.ParentHash)
return &engineapi.PayloadStatus{
Status: remote.EngineStatus_INVALID,
LatestValidHash: header.ParentHash,
ValidationError: verificationErr,
}, false, nil
}
currentHeadHash := rawdb.ReadHeadHeaderHash(tx)
extendingHash := cfg.forkValidator.ExtendingForkHeadHash()
extendCanonical := (extendingHash == libcommon.Hash{} && header.ParentHash == currentHeadHash) || extendingHash == header.ParentHash
status, latestValidHash, validationError, criticalError := cfg.forkValidator.ValidatePayload(tx, header, block.RawBody(), extendCanonical)
if criticalError != nil {
return nil, false, criticalError
}
success = validationError == nil
if !success {
log.Warn("Validation failed for header", "hash", headerHash, "height", headerNumber, "err", validationError)
cfg.hd.ReportBadHeaderPoS(headerHash, latestValidHash)
} else if err := headerInserter.FeedHeaderPoS(tx, header, headerHash); err != nil {
return nil, false, err
}
return &engineapi.PayloadStatus{
Status: status,
LatestValidHash: latestValidHash,
ValidationError: validationError,
}, success, nil
}
func schedulePoSDownload(
requestId int,
hashToDownload libcommon.Hash,
heightToDownload uint64,
downloaderTip libcommon.Hash,
s *StageState,
cfg HeadersCfg,
) bool {
cfg.hd.BeaconRequestList.SetStatus(requestId, engineapi.DataWasMissing)
if cfg.hd.PosStatus() != headerdownload.Idle {
log.Info(fmt.Sprintf("[%s] Postponing PoS download since another one is in progress", s.LogPrefix()), "height", heightToDownload, "hash", hashToDownload)
return false
}
if heightToDownload == 0 {
log.Info(fmt.Sprintf("[%s] Downloading PoS headers...", s.LogPrefix()), "height", "unknown", "hash", hashToDownload, "requestId", requestId)
} else {
log.Info(fmt.Sprintf("[%s] Downloading PoS headers...", s.LogPrefix()), "height", heightToDownload, "hash", hashToDownload, "requestId", requestId)
}
cfg.hd.SetRequestId(requestId)
cfg.hd.SetPoSDownloaderTip(downloaderTip)
cfg.hd.SetHeaderToDownloadPoS(hashToDownload, heightToDownload)
cfg.hd.SetPOSSync(true) // This needs to be called after SetHeaderToDownloadPOS because SetHeaderToDownloadPOS sets `posAnchor` member field which is used by ProcessHeadersPOS
//nolint
headerCollector := etl.NewCollector(s.LogPrefix(), cfg.tmpdir, etl.NewSortableBuffer(etl.BufferOptimalSize))
// headerCollector is closed in saveDownloadedPoSHeaders, thus nolint
cfg.hd.SetHeadersCollector(headerCollector)
cfg.hd.SetPosStatus(headerdownload.Syncing)
return true
}
func saveDownloadedPoSHeaders(tx kv.RwTx, cfg HeadersCfg, headerInserter *headerdownload.HeaderInserter, validate bool) {
var lastValidHash libcommon.Hash
var badChainError error
var foundPow bool
headerLoadFunc := func(key, value []byte, _ etl.CurrentTableReader, _ etl.LoadNextFunc) error {
var h types.Header
// no header to process
if value == nil {
return nil
}
if err := rlp.DecodeBytes(value, &h); err != nil {
return err
}
if badChainError != nil {
cfg.hd.ReportBadHeaderPoS(h.Hash(), lastValidHash)
return nil
}
lastValidHash = h.ParentHash
if err := cfg.hd.VerifyHeader(&h); err != nil {
log.Warn("Verification failed for header", "hash", h.Hash(), "height", h.Number.Uint64(), "err", err)
badChainError = err
cfg.hd.ReportBadHeaderPoS(h.Hash(), lastValidHash)
return nil
}
// If we are in PoW range then block validation is not required anymore.
if foundPow {
return headerInserter.FeedHeaderPoS(tx, &h, h.Hash())
}
foundPow = h.Difficulty.Cmp(common.Big0) != 0
if foundPow {
return headerInserter.FeedHeaderPoS(tx, &h, h.Hash())
}
// Validate state if possible (bodies will be retrieved through body download)
if validate {
_, _, validationError, criticalError := cfg.forkValidator.ValidatePayload(tx, &h, nil, false)
if criticalError != nil {
return criticalError
}
if validationError != nil {
badChainError = validationError
cfg.hd.ReportBadHeaderPoS(h.Hash(), lastValidHash)
return nil
}
}
return headerInserter.FeedHeaderPoS(tx, &h, h.Hash())
}
err := cfg.hd.HeadersCollector().Load(tx, kv.Headers, headerLoadFunc, etl.TransformArgs{
LogDetailsLoad: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"block", binary.BigEndian.Uint64(k)}
},
})
if err != nil || badChainError != nil {
if err == nil {
err = badChainError
}
log.Warn("Removing beacon request due to", "err", err, "requestId", cfg.hd.RequestId())
cfg.hd.BeaconRequestList.Remove(cfg.hd.RequestId())
cfg.hd.ReportBadHeaderPoS(cfg.hd.PoSDownloaderTip(), lastValidHash)
} else {
log.Info("PoS headers verified and saved", "requestId", cfg.hd.RequestId(), "fork head", lastValidHash)
}
cfg.hd.HeadersCollector().Close()
cfg.hd.SetHeadersCollector(nil)
cfg.hd.SetPosStatus(headerdownload.Idle)
}
func forkingPoint(
ctx context.Context,
tx kv.RwTx,
headerInserter *headerdownload.HeaderInserter,
headerReader services.HeaderReader,
header *types.Header,
) (uint64, error) {
headerNumber := header.Number.Uint64()
if headerNumber == 0 {
return 0, nil
}
parent, err := headerReader.Header(ctx, tx, header.ParentHash, headerNumber-1)
if err != nil {
return 0, err
}
return headerInserter.ForkingPoint(tx, header, parent)
}
func handleInterrupt(interrupt engineapi.Interrupt, cfg HeadersCfg, tx kv.RwTx, headerInserter *headerdownload.HeaderInserter, useExternalTx bool) (bool, error) {
if interrupt != engineapi.None {
if interrupt == engineapi.Stopping {
close(cfg.hd.ShutdownCh)
return false, fmt.Errorf("server is stopping")
}
if interrupt == engineapi.Synced && cfg.hd.HeadersCollector() != nil {
saveDownloadedPoSHeaders(tx, cfg, headerInserter, false /* validate */)
}
if !useExternalTx {
return true, tx.Commit()
}
return true, nil
}
return false, nil
}
// HeadersPOW progresses Headers stage for Proof-of-Work headers
func HeadersPOW(
s *StageState,
u Unwinder,
ctx context.Context,
tx kv.RwTx,
cfg HeadersCfg,
initialCycle bool,
test bool, // Set to true in tests, allows the stage to fail rather than wait indefinitely
useExternalTx bool,
) error {
var headerProgress uint64
var err error
if err = cfg.hd.ReadProgressFromDb(tx); err != nil {
return err
}
cfg.hd.SetPOSSync(false)
cfg.hd.SetFetchingNew(true)
defer cfg.hd.SetFetchingNew(false)
headerProgress = cfg.hd.Progress()
logPrefix := s.LogPrefix()
// Check if this is called straight after the unwinds, which means we need to create new canonical markings
hash, err := rawdb.ReadCanonicalHash(tx, headerProgress)
if err != nil {
return err
}
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
if hash == (libcommon.Hash{}) {
headHash := rawdb.ReadHeadHeaderHash(tx)
if err = fixCanonicalChain(logPrefix, logEvery, headerProgress, headHash, tx, cfg.blockReader); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
// Allow other stages to run 1 cycle if no network available
if initialCycle && cfg.noP2PDiscovery {
return nil
}
log.Info(fmt.Sprintf("[%s] Waiting for headers...", logPrefix), "from", headerProgress)
localTd, err := rawdb.ReadTd(tx, hash, headerProgress)
if err != nil {
return err
}
if localTd == nil {
return fmt.Errorf("localTD is nil: %d, %x", headerProgress, hash)
}
headerInserter := headerdownload.NewHeaderInserter(logPrefix, localTd, headerProgress, cfg.blockReader)
cfg.hd.SetHeaderReader(&ChainReaderImpl{config: &cfg.chainConfig, tx: tx, blockReader: cfg.blockReader})
var sentToPeer bool
stopped := false
prevProgress := headerProgress
var noProgressCounter int
var wasProgress bool
var lastSkeletonTime time.Time
Loop:
for !stopped {
transitionedToPoS, err := rawdb.Transitioned(tx, headerProgress, cfg.chainConfig.TerminalTotalDifficulty)
if err != nil {
return err
}
if transitionedToPoS {
if err := s.Update(tx, headerProgress); err != nil {
return err
}
break
}
currentTime := time.Now()
req, penalties := cfg.hd.RequestMoreHeaders(currentTime)
if req != nil {
_, sentToPeer = cfg.headerReqSend(ctx, req)
if sentToPeer {
cfg.hd.UpdateStats(req, false /* skeleton */)
}
// Regardless of whether request was actually sent to a peer, we update retry time to be 5 seconds in the future
cfg.hd.UpdateRetryTime(req, currentTime, 5*time.Second /* timeout */)
}
if len(penalties) > 0 {
cfg.penalize(ctx, penalties)
}
maxRequests := 64 // Limit number of requests sent per round to let some headers to be inserted into the database
for req != nil && sentToPeer && maxRequests > 0 {
req, penalties = cfg.hd.RequestMoreHeaders(currentTime)
if req != nil {
_, sentToPeer = cfg.headerReqSend(ctx, req)
if sentToPeer {
cfg.hd.UpdateStats(req, false /* skeleton */)
}
// Regardless of whether request was actually sent to a peer, we update retry time to be 5 seconds in the future
cfg.hd.UpdateRetryTime(req, currentTime, 5*time.Second /* timeout */)
}
if len(penalties) > 0 {
cfg.penalize(ctx, penalties)
}
maxRequests--
}
// Send skeleton request if required
if time.Since(lastSkeletonTime) > 1*time.Second {
req = cfg.hd.RequestSkeleton()
if req != nil {
_, sentToPeer = cfg.headerReqSend(ctx, req)
if sentToPeer {
cfg.hd.UpdateStats(req, true /* skeleton */)
lastSkeletonTime = time.Now()
}
}
}
// Load headers into the database
var inSync bool
if inSync, err = cfg.hd.InsertHeaders(headerInserter.NewFeedHeaderFunc(tx, cfg.blockReader), cfg.chainConfig.TerminalTotalDifficulty, logPrefix, logEvery.C); err != nil {
return err
}
if test {
announces := cfg.hd.GrabAnnounces()
if len(announces) > 0 {
cfg.announceNewHashes(ctx, announces)
}
}
if headerInserter.BestHeaderChanged() { // We do not break unless there best header changed
noProgressCounter = 0
wasProgress = true
if !initialCycle {
// if this is not an initial cycle, we need to react quickly when new headers are coming in
break
}
// if this is initial cycle, we want to make sure we insert all known headers (inSync)
if inSync {
break
}
}
if test {
break
}
timer := time.NewTimer(1 * time.Second)
select {
case <-ctx.Done():
stopped = true
case <-logEvery.C:
progress := cfg.hd.Progress()
logProgressHeaders(logPrefix, prevProgress, progress)
stats := cfg.hd.ExtractStats()
if prevProgress == progress {
noProgressCounter++
if noProgressCounter >= 5 {
log.Info("Req/resp stats", "req", stats.Requests, "reqMin", stats.ReqMinBlock, "reqMax", stats.ReqMaxBlock,
"skel", stats.SkeletonRequests, "skelMin", stats.SkeletonReqMinBlock, "skelMax", stats.SkeletonReqMaxBlock,
"resp", stats.Responses, "respMin", stats.RespMinBlock, "respMax", stats.RespMaxBlock, "dups", stats.Duplicates)
cfg.hd.LogAnchorState()
if wasProgress {
log.Warn("Looks like chain is not progressing, moving to the next stage")
break Loop
}
}
}
prevProgress = progress
case <-timer.C:
log.Trace("RequestQueueTime (header) ticked")
case <-cfg.hd.DeliveryNotify:
log.Trace("headerLoop woken up by the incoming request")
}
timer.Stop()
}
if headerInserter.Unwind() {
u.UnwindTo(headerInserter.UnwindPoint(), libcommon.Hash{})
}
if headerInserter.GetHighest() != 0 {
if !headerInserter.Unwind() {
if err := fixCanonicalChain(logPrefix, logEvery, headerInserter.GetHighest(), headerInserter.GetHighestHash(), tx, cfg.blockReader); err != nil {
return fmt.Errorf("fix canonical chain: %w", err)
}
}
if err = rawdb.WriteHeadHeaderHash(tx, headerInserter.GetHighestHash()); err != nil {
return fmt.Errorf("[%s] marking head header hash as %x: %w", logPrefix, headerInserter.GetHighestHash(), err)
}
if err = s.Update(tx, headerInserter.GetHighest()); err != nil {
return fmt.Errorf("[%s] saving Headers progress: %w", logPrefix, err)
}
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
if stopped {
return libcommon.ErrStopped
}
// We do not print the following line if the stage was interrupted
log.Info(fmt.Sprintf("[%s] Processed", logPrefix), "highest inserted", headerInserter.GetHighest(), "age", common.PrettyAge(time.Unix(int64(headerInserter.GetHighestTimestamp()), 0)))
return nil
}
func fixCanonicalChain(logPrefix string, logEvery *time.Ticker, height uint64, hash libcommon.Hash, tx kv.StatelessRwTx, headerReader services.FullBlockReader) error {
if height == 0 {
return nil
}
ancestorHash := hash
ancestorHeight := height
var ch libcommon.Hash
var err error
for ch, err = headerReader.CanonicalHash(context.Background(), tx, ancestorHeight); err == nil && ch != ancestorHash; ch, err = headerReader.CanonicalHash(context.Background(), tx, ancestorHeight) {
if err = rawdb.WriteCanonicalHash(tx, ancestorHash, ancestorHeight); err != nil {
return fmt.Errorf("marking canonical header %d %x: %w", ancestorHeight, ancestorHash, err)
}
ancestor, err := headerReader.Header(context.Background(), tx, ancestorHash, ancestorHeight)
if err != nil {
return err
}
if ancestor == nil {
return fmt.Errorf("ancestor is nil. height %d, hash %x", ancestorHeight, ancestorHash)
}
select {
case <-logEvery.C:
log.Info(fmt.Sprintf("[%s] write canonical markers", logPrefix), "ancestor", ancestorHeight, "hash", ancestorHash)
default:
}
ancestorHash = ancestor.ParentHash
ancestorHeight--
}
if err != nil {
return fmt.Errorf("reading canonical hash for %d: %w", ancestorHeight, err)
}
return nil
}
func HeadersUnwind(u *UnwindState, s *StageState, tx kv.RwTx, cfg HeadersCfg, test bool) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
defer tx.Rollback()
}
// Delete canonical hashes that are being unwound
badBlock := u.BadBlock != (libcommon.Hash{})
if badBlock {
cfg.hd.ReportBadHeader(u.BadBlock)
// Mark all descendants of bad block as bad too
headerCursor, cErr := tx.Cursor(kv.Headers)
if cErr != nil {
return cErr
}
defer headerCursor.Close()
var k, v []byte
for k, v, err = headerCursor.Seek(hexutility.EncodeTs(u.UnwindPoint + 1)); err == nil && k != nil; k, v, err = headerCursor.Next() {
var h types.Header
if err = rlp.DecodeBytes(v, &h); err != nil {
return err
}
if cfg.hd.IsBadHeader(h.ParentHash) {
cfg.hd.ReportBadHeader(h.Hash())
}
}
if err != nil {