-
Notifications
You must be signed in to change notification settings - Fork 475
/
Copy pathscenarios.go
1980 lines (1796 loc) · 68.1 KB
/
scenarios.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 main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/hive/hivesim"
"github.com/ethereum/hive/simulators/eth2/engine/setup"
"github.com/protolambda/eth2api"
"github.com/protolambda/eth2api/client/beaconapi"
"github.com/protolambda/zrnt/eth2/beacon/bellatrix"
beacon "github.com/protolambda/zrnt/eth2/beacon/common"
"github.com/rauljordan/engine-proxy/proxy"
)
var (
DEFAULT_VALIDATOR_COUNT uint64 = 60
DEFAULT_SLOT_TIME uint64 = 6
DEFAULT_TERMINAL_TOTAL_DIFFICULTY uint64 = 100
EPOCHS_TO_FINALITY uint64 = 4
// Default config used for all tests unless a client specific config exists
DEFAULT_CONFIG = &Config{
ValidatorCount: big.NewInt(int64(DEFAULT_VALIDATOR_COUNT)),
SlotTime: big.NewInt(int64(DEFAULT_SLOT_TIME)),
TerminalTotalDifficulty: big.NewInt(int64(DEFAULT_TERMINAL_TOTAL_DIFFICULTY)),
AltairForkEpoch: common.Big0,
MergeForkEpoch: common.Big0,
Eth1Consensus: &setup.Eth1CliqueConsensus{},
}
// Clients that do not support starting on epoch 0 with all forks enabled.
// Tests take longer for these clients.
INCREMENTAL_FORKS_CONFIG = &Config{
TerminalTotalDifficulty: big.NewInt(int64(DEFAULT_TERMINAL_TOTAL_DIFFICULTY) * 5),
AltairForkEpoch: common.Big1,
MergeForkEpoch: common.Big2,
}
INCREMENTAL_FORKS_CLIENTS = map[string]bool{
"nimbus": true,
"prysm": true,
}
SAFE_SLOTS_TO_IMPORT_OPTIMISTICALLY_CLIENT_OVERRIDE = map[string]*big.Int{}
)
func getClientConfig(n node) *Config {
config := DEFAULT_CONFIG
if INCREMENTAL_FORKS_CLIENTS[n.ConsensusClient] == true {
config = config.join(INCREMENTAL_FORKS_CONFIG)
}
return config
}
func TransitionTestnet(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: []node{
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
finalized, err := testnet.WaitForFinality(ctx, testnet.spec.SLOTS_PER_EPOCH*beacon.Slot(EPOCHS_TO_FINALITY+1))
if err != nil {
t.Fatalf("FAIL: Waiting for finality: %v", err)
}
if err := VerifyParticipation(testnet, ctx, FirstSlotAfterCheckpoint{&finalized}, 0.95); err != nil {
t.Fatalf("FAIL: Verifying participation: %v", err)
}
if err := VerifyExecutionPayloadIsCanonical(testnet, ctx, LastSlotAtCheckpoint{&finalized}); err != nil {
t.Fatalf("FAIL: Verifying execution payload is canonical: %v", err)
}
if err := VerifyProposers(testnet, ctx, LastSlotAtCheckpoint{&finalized}, false); err != nil {
t.Fatalf("FAIL: Verifying proposers: %v", err)
}
}
func TestRPCError(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: []node{
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
finalized, err := testnet.WaitForFinality(ctx, testnet.spec.SLOTS_PER_EPOCH*beacon.Slot(EPOCHS_TO_FINALITY+1))
if err != nil {
t.Fatalf("FAIL: Waiting for finality: %v", err)
}
if err := VerifyParticipation(testnet, ctx, FirstSlotAfterCheckpoint{&finalized}, 0.95); err != nil {
t.Fatalf("FAIL: Verifying participation: %v", err)
}
if err := VerifyExecutionPayloadIsCanonical(testnet, ctx, LastSlotAtCheckpoint{&finalized}); err != nil {
t.Fatalf("FAIL: Verifying execution payload is canonical: %v", err)
}
if err := VerifyProposers(testnet, ctx, LastSlotAtCheckpoint{&finalized}, true); err != nil {
t.Fatalf("FAIL: Verifying proposers: %v", err)
}
if err := VerifyELHeads(testnet, ctx); err != nil {
t.Fatalf("FAIL: Verifying EL Heads: %v", err)
}
fields := make(map[string]interface{})
fields["headBlockHash"] = "weird error"
spoof := &proxy.Spoof{
Method: EngineForkchoiceUpdatedV1,
Fields: fields,
}
testnet.Proxies().Running()[0].AddRequest(spoof)
time.Sleep(24 * time.Second)
if err := VerifyParticipation(testnet, ctx, FirstSlotAfterCheckpoint{&finalized}, 0.95); err != nil {
t.Fatalf("FAIL: %v", err)
}
if err := VerifyELHeads(testnet, ctx); err == nil {
t.Fatalf("FAIL: Expected different heads after spoof %v", err)
}
}
// Test `latest`, `safe`, `finalized` block labels on the post-merge testnet.
func BlockLatestSafeFinalized(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: []node{
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := testnet.WaitForExecutionFinality(ctx, testnet.spec.SLOTS_PER_EPOCH*beacon.Slot(EPOCHS_TO_FINALITY+2))
if err != nil {
t.Fatalf("FAIL: Waiting for execution finality: %v", err)
}
if err := VerifyELBlockLabels(testnet, ctx); err != nil {
t.Fatalf("FAIL: Verifying EL block labels: %v", err)
}
}
// Generate a testnet where the transition payload contains an unknown PoW parent.
// Verify that the testnet can finalize after this.
func UnknownPoWParent(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: Nodes{
n,
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
var (
getPayloadLock sync.Mutex
getPayloadCount int
invalidPayloadHash common.Hash
/*
invalidPayloadNewParent common.Hash
invalidPayloadOldParent common.Hash
*/
invalidPayloadNodeID int
)
// The EL mock will intercept an engine_getPayloadV1 call and set a random parent block in the response
getPayloadCallbackGen := func(node int) func([]byte, []byte) *proxy.Spoof {
return func(res []byte, req []byte) *proxy.Spoof {
getPayloadLock.Lock()
defer getPayloadLock.Unlock()
getPayloadCount++
// Invalidate the transition payload
if getPayloadCount == 1 {
var (
payload ExecutableDataV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCResponse(res, &payload)
if err != nil {
panic(err)
}
t.Logf("INFO (%v): Generating payload with unknown PoW parent: %s", t.TestID, res)
invalidPayloadHash, spoof, err = generateInvalidPayloadSpoof(EngineGetPayloadV1, &payload, InvalidParentHash)
if err != nil {
panic(err)
}
t.Logf("INFO (%v): Invalidated payload hash: %v", t.TestID, invalidPayloadHash)
invalidPayloadNodeID = node
return spoof
}
return nil
}
}
// The EL mock will intercept an engine_newPayloadV1 on the node that generated the invalid hash in order to validate it and broadcast it.
newPayloadCallbackGen := func(node int) func([]byte, []byte) *proxy.Spoof {
return func(res []byte, req []byte) *proxy.Spoof {
var (
payload ExecutableDataV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCRequest(req, &payload)
if err != nil {
panic(err)
}
// Validate the new payload in the node that produced it
if invalidPayloadNodeID == node && payload.BlockHash == invalidPayloadHash {
t.Logf("INFO (%v): Validating new payload: %s", t.TestID, payload.BlockHash)
spoof, err = payloadStatusSpoof(EngineNewPayloadV1, &PayloadStatusV1{
Status: Valid,
LatestValidHash: &payload.BlockHash,
ValidationError: nil,
})
if err != nil {
panic(err)
}
return spoof
}
return nil
}
}
// The EL mock will intercept an engine_forkchoiceUpdatedV1 on the node that generated the invalid hash in order to validate it and broadcast it.
fcUCallbackGen := func(node int) func([]byte, []byte) *proxy.Spoof {
return func(res []byte, req []byte) *proxy.Spoof {
var (
fcState ForkchoiceStateV1
pAttr PayloadAttributesV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCRequest(req, &fcState, &pAttr)
if err != nil {
panic(err)
}
// Validate the new payload in the node that produced it
if invalidPayloadNodeID == node && fcState.HeadBlockHash == invalidPayloadHash {
t.Logf("INFO (%v): Validating forkchoiceUpdated: %s", t.TestID, fcState.HeadBlockHash)
spoof, err = forkchoiceResponseSpoof(EngineForkchoiceUpdatedV1, PayloadStatusV1{
Status: Valid,
LatestValidHash: &fcState.HeadBlockHash,
ValidationError: nil,
}, nil)
if err != nil {
panic(err)
}
return spoof
}
return nil
}
}
for n, p := range testnet.Proxies().Running() {
p.AddResponseCallback(EngineGetPayloadV1, getPayloadCallbackGen(n))
p.AddResponseCallback(EngineNewPayloadV1, newPayloadCallbackGen(n))
p.AddResponseCallback(EngineForkchoiceUpdatedV1, fcUCallbackGen(n))
}
// Network should recover from this
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
finalized, err := testnet.WaitForFinality(ctx, testnet.spec.SLOTS_PER_EPOCH*beacon.Slot(EPOCHS_TO_FINALITY+1))
if err != nil {
t.Fatalf("FAIL: Waiting for finality: %v", err)
}
if err := VerifyParticipation(testnet, ctx, FirstSlotAfterCheckpoint{&finalized}, 0.95); err != nil {
t.Fatalf("FAIL: Verifying participation: %v", err)
}
if err := VerifyExecutionPayloadIsCanonical(testnet, ctx, LastSlotAtCheckpoint{&finalized}); err != nil {
t.Fatalf("FAIL: Verifying execution payload is canonical: %v", err)
}
if err := VerifyProposers(testnet, ctx, LastSlotAtCheckpoint{&finalized}, true); err != nil {
t.Fatalf("FAIL: Verifying proposers: %v", err)
}
if err := VerifyELHeads(testnet, ctx); err != nil {
t.Fatalf("FAIL: Verifying EL Heads: %v", err)
}
}
// Generates a testnet case where one payload is invalidated in the recipient nodes.
// invalidPayloadNumber: The number of the payload to invalidate -- 1 is transition payload, 2+ is any canonical chain payload.
// invalidStatusResponse: The validation error response to inject in the recipient nodes.
func InvalidPayloadGen(invalidPayloadNumber int, invalidStatusResponse PayloadStatus) func(t *hivesim.T, env *testEnv, n node) {
return func(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: Nodes{
n,
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
// All proxies will use the same callback, therefore we need to use a lock and a counter
var (
getPayloadLock sync.Mutex
getPayloadCount int
invalidPayloadHash common.Hash
invalidPayloadProxyId int
)
// The EL mock will intercept the first engine_getPayloadV1 and corrupt the stateRoot in the response
getPayloadCallbackGen := func(id int) func(res []byte, req []byte) *proxy.Spoof {
return func(res []byte, req []byte) *proxy.Spoof {
getPayloadLock.Lock()
defer getPayloadLock.Unlock()
getPayloadCount++
if getPayloadCount == invalidPayloadNumber {
// We are not going to spoof anything here, we just need to save the transition payload hash and the id of the validator that generated it
// to invalidate it in other clients.
var (
payload ExecutableDataV1
)
err := UnmarshalFromJsonRPCResponse(res, &payload)
if err != nil {
panic(err)
}
invalidPayloadHash = payload.BlockHash
invalidPayloadProxyId = id
// Remove this validator from the verification
testnet.RemoveNodeAsVerifier(id)
}
return nil
}
}
// Here we will intercept the response from the rest of the clients that did not generate the payload to artificially invalidate them
newPayloadCallbackGen := func(id int) func(res []byte, req []byte) *proxy.Spoof {
return func(res []byte, req []byte) *proxy.Spoof {
t.Logf("INFO: newPayload callback node %d", id)
var (
payload ExecutableDataV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCRequest(req, &payload)
if err != nil {
panic(err)
}
// Only invalidate if the payload hash matches the invalid payload hash and this validator is not the one that generated it
if invalidPayloadProxyId != id && payload.BlockHash == invalidPayloadHash {
var latestValidHash common.Hash
// Latest valid hash depends on the error we are injecting
if invalidPayloadNumber == 1 || invalidStatusResponse == InvalidBlockHash {
// The transition payload has a PoW parent, hash must be 0.
// If the payload has an invalid hash, we cannot link it to any other payload, hence 0.
latestValidHash = common.Hash{}
} else {
latestValidHash = payload.ParentHash
}
status := PayloadStatusV1{
Status: invalidStatusResponse,
LatestValidHash: &latestValidHash,
ValidationError: nil,
}
spoof, err = payloadStatusSpoof(EngineNewPayloadV1, &status)
if err != nil {
panic(err)
}
t.Logf("INFO: Invalidating payload on validator %d: %v", id, payload.BlockHash)
}
return spoof
}
}
// We pass the id of the proxy to identify which one it is within the callback
for i, p := range testnet.Proxies().Running() {
p.AddResponseCallback(EngineGetPayloadV1, getPayloadCallbackGen(i))
p.AddResponseCallback(EngineNewPayloadV1, newPayloadCallbackGen(i))
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := testnet.WaitForExecutionPayload(ctx, SlotsUntilMerge(testnet, config))
if err != nil {
t.Fatalf("FAIL: Waiting for execution payload: %v", err)
}
// Wait 5 slots after the invalidated payload
time.Sleep(time.Duration(testnet.spec.SECONDS_PER_SLOT) * time.Second * time.Duration(5+invalidPayloadNumber))
// Verify beacon block with invalid payload is not accepted
b, err := VerifyExecutionPayloadHashInclusion(testnet, ctx, LastestSlotByHead{}, invalidPayloadHash)
if err != nil {
t.Fatalf("FAIL: Error during payload verification: %v", err)
} else if b != nil {
t.Fatalf("FAIL: Invalid Payload %v was included in slot %d (%v)", invalidPayloadHash, b.Message.Slot, b.Message.StateRoot)
}
}
}
// The produced and broadcasted payload contains an invalid prevrandao value.
// The PREVRANDAO opcode is not used in any transaction and therefore not introduced in the state changes.
func IncorrectHeaderPrevRandaoPayload(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: Nodes{
n,
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
// All proxies will use the same callback, therefore we need to use a lock and a counter
var (
getPayloadLock sync.Mutex
getPayloadCount int
invalidPayloadHash common.Hash
)
// The EL mock will intercept an engine_getPayloadV1 call and corrupt the prevRandao in the response
c := func(res []byte, req []byte) *proxy.Spoof {
getPayloadLock.Lock()
defer getPayloadLock.Unlock()
getPayloadCount++
// Invalidate a payload after the transition payload
if getPayloadCount == 2 {
var (
payload ExecutableDataV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCResponse(res, &payload)
if err != nil {
panic(err)
}
t.Logf("INFO (%v): Invalidating payload: %s", t.TestID, res)
invalidPayloadHash, spoof, err = generateInvalidPayloadSpoof(EngineGetPayloadV1, &payload, InvalidPrevRandao)
if err != nil {
panic(err)
}
t.Logf("INFO (%v): Invalidated payload hash: %v", t.TestID, invalidPayloadHash)
return spoof
}
return nil
}
for _, p := range testnet.Proxies().Running() {
p.AddResponseCallback(EngineGetPayloadV1, c)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := testnet.WaitForExecutionPayload(ctx, SlotsUntilMerge(testnet, config))
if err != nil {
t.Fatalf("FAIL: Waiting for execution payload: %v", err)
}
// Wait 5 slots
time.Sleep(time.Duration(testnet.spec.SECONDS_PER_SLOT) * time.Second * 5)
// Verify beacon block with invalid payload is not accepted
b, err := VerifyExecutionPayloadHashInclusion(testnet, ctx, LastestSlotByHead{}, invalidPayloadHash)
if err != nil {
t.Fatalf("FAIL: Error during payload verification: %v", err)
} else if b != nil {
t.Fatalf("FAIL: Invalid Payload %v was included in slot %d (%v)", invalidPayloadHash, b.Message.Slot, b.Message.StateRoot)
}
}
// The payload produced by the execution client contains an invalid timestamp value.
// This test covers scenario where the value of the timestamp is so high such that
// the next validators' attempts to produce payloads could fail by invalid payload
// attributes.
func InvalidTimestampPayload(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: Nodes{
n,
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
// All proxies will use the same callback, therefore we need to use a lock and a counter
var (
getPayloadLock sync.Mutex
getPayloadCount int
invalidPayloadHash common.Hash
done = make(chan interface{})
)
// The EL mock will intercept an engine_getPayloadV1 call and invalidate the timestamp in the response
c := func(res []byte, req []byte) *proxy.Spoof {
getPayloadLock.Lock()
defer getPayloadLock.Unlock()
getPayloadCount++
var (
payload ExecutableDataV1
payloadID PayloadID
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCResponse(res, &payload)
if err != nil {
panic(err)
}
err = UnmarshalFromJsonRPCRequest(req, &payloadID)
t.Logf("INFO: Got payload %v, parent=%v, from PayloadID=%x", payload.BlockHash, payload.ParentHash, payloadID)
// Invalidate a payload after the transition payload
if getPayloadCount == 2 {
t.Logf("INFO (%v): Invalidating payload: %s", t.TestID, res)
// We are pushing the timestamp past the slot time.
// The beacon chain shall identify this and reject the payload.
newTimestamp := payload.Timestamp + config.SlotTime.Uint64()
// We add some extraData to guarantee we can identify the payload we altered
extraData := []byte("alt")
invalidPayloadHash, spoof, err = customizePayloadSpoof(EngineGetPayloadV1, &payload,
&CustomPayloadData{
Timestamp: &newTimestamp,
ExtraData: &extraData,
})
if err != nil {
panic(err)
}
t.Logf("INFO (%v): Invalidated payload hash: %v", t.TestID, invalidPayloadHash)
select {
case done <- nil:
default:
}
return spoof
}
return nil
}
// No ForkchoiceUpdated with payload attributes should fail, which could happen if the payload
// with invalid timestamp is accepted (next payload would fail).
var (
fcuLock sync.Mutex
fcUAttrCount int
fcudone = make(chan error)
fcUCountLimit = 8
)
for _, p := range testnet.Proxies().Running() {
p.AddResponseCallback(EngineGetPayloadV1, c)
p.AddResponseCallback(EngineForkchoiceUpdatedV1, CheckErrorOnForkchoiceUpdatedPayloadAttr(&fcuLock, fcUCountLimit, &fcUAttrCount, fcudone))
}
// Wait until the invalid payload is produced
<-done
// Wait until we verified all subsequent forkchoiceUpdated calls
if err := <-fcudone; err != nil {
t.Fatalf("FAIL: ForkchoiceUpdated call failed: %v", err)
}
// Verify beacon block with invalid payload is not accepted
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
b, err := VerifyExecutionPayloadHashInclusion(testnet, ctx, LastestSlotByHead{}, invalidPayloadHash)
if err != nil {
t.Fatalf("FAIL: Error during payload verification: %v", err)
} else if b != nil {
t.Fatalf("FAIL: Invalid Payload %v was included in slot %d (%v)", invalidPayloadHash, b.Message.Slot, b.Message.StateRoot)
}
}
func IncorrectTTDConfigEL(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n)
elTTD := config.TerminalTotalDifficulty.Int64() - 2
config = config.join(&Config{
Nodes: Nodes{
node{
// Add a node with an incorrect TTD to reject the invalid payload
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ExecutionClientTTD: big.NewInt(elTTD),
},
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
var (
builder = testnet.BeaconClients().Running()[0]
eth = testnet.ExecutionClients().Running()[0]
ec = NewEngineClient(t, eth, big.NewInt(elTTD))
)
if !ec.waitForTTDWithTimeout(setup.CLIQUE_PERIOD_DEFAULT, time.After(time.Duration(setup.CLIQUE_PERIOD_DEFAULT*uint64(elTTD)*2)*time.Second)) {
t.Fatalf("FAIL: Bad TTD was never reached by the Execution Client")
}
// Wait a couple of slots
time.Sleep(time.Duration(config.SlotTime.Uint64()*5) * time.Second)
// Try to get the latest execution payload, must be nil
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
b, err := builder.GetLatestExecutionBeaconBlock(ctx)
if err != nil {
t.Fatalf("FAIL: Unable to query for the latest execution payload: %v", err)
}
if b != nil {
t.Fatalf("FAIL: Execution payload was included in the beacon chain with a misconfigured TTD on the EL: %v", b.Message.StateRoot)
}
}
// The produced and broadcasted transition payload has parent with an invalid total difficulty.
func IncorrectTerminalBlockGen(ttdDelta int64) func(t *hivesim.T, env *testEnv, n node) {
return func(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n)
BadTTD := big.NewInt(config.TerminalTotalDifficulty.Int64() + ttdDelta)
config = config.join(&Config{
Nodes: Nodes{
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 1,
TestVerificationNode: true,
},
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 1,
TestVerificationNode: true,
},
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 1,
TestVerificationNode: true,
},
node{
// Add a node with an incorrect TTD to reject the invalid payload
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 0,
ExecutionClientTTD: BadTTD,
BeaconNodeTTD: BadTTD,
},
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
var (
badTTDImporter = testnet.BeaconClients().Running()[3]
)
// Wait for all execution clients with the correct TTD reach the merge
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
transitionPayloadHash, err := testnet.WaitForExecutionPayload(ctx, SlotsUntilMerge(testnet, config))
if err != nil {
t.Fatalf("FAIL: Waiting for execution payload: %v", err)
}
ec := NewEngineClient(t, testnet.ExecutionClients().Running()[0], config.TerminalTotalDifficulty)
transitionHeader, err := ec.Eth.HeaderByHash(ec.Ctx(), transitionPayloadHash)
if err != nil {
t.Fatalf("FAIL: Unable to get transition payload header from execution client: %v", err)
}
var tb, tbp *TotalDifficultyHeader
if err := ec.cEth.CallContext(ec.Ctx(), &tb, "eth_getBlockByHash", transitionHeader.ParentHash, false); err != nil {
t.Fatalf("FAIL: Unable to get terminal block header from execution client: %v", err)
}
if err := ec.cEth.CallContext(ec.Ctx(), &tbp, "eth_getBlockByHash", tb.ParentHash, false); err != nil {
t.Fatalf("FAIL: Unable to get terminal block header from execution client: %v", err)
}
t.Logf("INFO: CorrectTTD=%d, BadTTD=%d, TerminalBlockTotalDifficulty=%d, TerminalBlockParentTotalDifficulty=%d", config.TerminalTotalDifficulty, BadTTD, (*big.Int)(tb.TotalDifficulty), (*big.Int)(tbp.TotalDifficulty))
// Wait a couple of slots
time.Sleep(time.Duration(5*config.SlotTime.Uint64()) * time.Second)
// Transition payload should not be part of the beacon node with bad TTD
b, err := VerifyExecutionPayloadHashInclusionNode(testnet, ctx, LastestSlotByHead{}, badTTDImporter, transitionPayloadHash)
if err != nil {
t.Fatalf("FAIL: Error during payload verification: %v", err)
} else if b != nil {
t.Fatalf("FAIL: Node with bad TTD included beacon block with correct TTD: %v", b)
}
}
}
func SyncingWithInvalidChain(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
Nodes: Nodes{
// Builder 1
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 1,
TestVerificationNode: false,
},
// Builder 2
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 1,
TestVerificationNode: false,
},
// Importer
node{
ExecutionClient: n.ExecutionClient,
ConsensusClient: n.ConsensusClient,
ValidatorShares: 0,
TestVerificationNode: true,
},
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
var (
transitionPayloadHeight uint64
lastValidHash common.Hash
invalidPayloadHashes = make([]common.Hash, 0)
payloadMap = make(map[common.Hash]ExecutableDataV1)
done = make(chan interface{})
)
// Payloads will be intercepted here and spoofed to simulate sync.
// Then after 4 payloads (p1, p2, p3, p4), the last one will be marked `INVALID` with
// `latestValidHash==p1.Hash`
newPayloadCallback := func(res []byte, req []byte) *proxy.Spoof {
var (
payload ExecutableDataV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCRequest(req, &payload)
if err != nil {
panic(err)
}
payloadMap[payload.BlockHash] = payload
if lastValidHash == (common.Hash{}) {
// This is the transition payload (P1) because it's the first time this callback is called
transitionPayloadHeight = payload.Number
lastValidHash = payload.BlockHash
t.Logf("INFO: Last VALID hash %d: %v", payload.Number-transitionPayloadHeight, payload.BlockHash)
} else {
if payload.Number >= transitionPayloadHeight+3 {
// This is P4
invalidPayloadHashes = append(invalidPayloadHashes, payload.BlockHash)
status := PayloadStatusV1{
Status: Invalid,
LatestValidHash: &lastValidHash,
ValidationError: nil,
}
spoof, err = payloadStatusSpoof(EngineNewPayloadV1, &status)
if err != nil {
panic(err)
}
t.Logf("INFO: Returning INVALID payload %d: %v", payload.Number-transitionPayloadHeight, payload.BlockHash)
select {
case done <- nil:
default:
}
} else if payload.Number > transitionPayloadHeight {
// For all other payloads, including P2/P3, return SYNCING
invalidPayloadHashes = append(invalidPayloadHashes, payload.BlockHash)
status := PayloadStatusV1{
Status: Syncing,
LatestValidHash: nil,
ValidationError: nil,
}
spoof, err = payloadStatusSpoof(EngineNewPayloadV1, &status)
if err != nil {
panic(err)
}
t.Logf("INFO: Returning SYNCING payload %d: %v", payload.Number-transitionPayloadHeight, payload.BlockHash)
}
}
return spoof
}
forkchoiceUpdatedCallback := func(res []byte, req []byte) *proxy.Spoof {
var (
fcState ForkchoiceStateV1
pAttr PayloadAttributesV1
spoof *proxy.Spoof
err error
)
err = UnmarshalFromJsonRPCRequest(req, &fcState, &pAttr)
if err != nil {
panic(err)
}
if lastValidHash == (common.Hash{}) {
panic(fmt.Errorf("NewPayload was not called before ForkchoiceUpdated"))
}
payload, ok := payloadMap[fcState.HeadBlockHash]
if !ok {
panic(fmt.Errorf("payload not found: %v", fcState.HeadBlockHash))
}
if payload.Number != transitionPayloadHeight {
if payload.Number == transitionPayloadHeight+3 {
// This is P4, but we probably won't receive this since NewPayload(P4) already returned INVALID
status := PayloadStatusV1{
Status: Invalid,
LatestValidHash: &lastValidHash,
ValidationError: nil,
}
spoof, err = forkchoiceResponseSpoof(EngineForkchoiceUpdatedV1, status, nil)
if err != nil {
panic(err)
}
t.Logf("INFO: Returning INVALID payload %d (ForkchoiceUpdated): %v", payload.Number-transitionPayloadHeight, payload.BlockHash)
} else {
// For all other payloads, including P2/P3, return SYNCING
status := PayloadStatusV1{
Status: Syncing,
LatestValidHash: nil,
ValidationError: nil,
}
spoof, err = forkchoiceResponseSpoof(EngineForkchoiceUpdatedV1, status, nil)
if err != nil {
panic(err)
}
t.Logf("INFO: Returning SYNCING payload %d (ForkchoiceUpdated): %v", payload.Number-transitionPayloadHeight, payload.BlockHash)
}
}
return spoof
}
var (
importerProxy = testnet.Proxies().Running()[2]
)
// Add the callback to the last proxy which will not produce blocks
importerProxy.AddResponseCallback(EngineNewPayloadV1, newPayloadCallback)
importerProxy.AddResponseCallback(EngineForkchoiceUpdatedV1, forkchoiceUpdatedCallback)
<-done
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Wait a few slots for re-org to happen
time.Sleep(time.Duration(testnet.spec.SECONDS_PER_SLOT) * time.Second * 5)
// Verify the head of the chain, it should be a block with the latestValidHash included
for _, bn := range testnet.VerificationNodes().BeaconClients().Running() {
var versionedBlock eth2api.VersionedSignedBeaconBlock
if exists, err := beaconapi.BlockV2(ctx, bn.API, eth2api.BlockHead, &versionedBlock); err != nil {
t.Fatalf("FAIL: Unable to poll beacon chain head: %v", err)
} else if !exists {
t.Fatalf("FAIL: Unable to poll beacon chain head")
}
if versionedBlock.Version != "bellatrix" {
// Block can't contain an executable payload
t.Fatalf("FAIL: Head of the chain is not a bellatrix fork block")
}
block := versionedBlock.Data.(*bellatrix.SignedBeaconBlock)
payload := block.Message.Body.ExecutionPayload
if bytes.Compare(payload.BlockHash[:], lastValidHash[:]) != 0 {
t.Fatalf("FAIL: Head does not contain the expected execution payload: %v != %v", payload.BlockHash.String(), lastValidHash.Hex())
}
}
// Verify payloads
if b, err := VerifyExecutionPayloadHashInclusion(testnet, ctx, LastestSlotByHead{}, lastValidHash); b == nil || err != nil {
if err != nil {
t.Fatalf("FAIL: Valid Payload %v could not be found: %v", lastValidHash, err)
}
t.Fatalf("FAIL: Valid Payload %v could not be found", lastValidHash)
}
for i, p := range invalidPayloadHashes {
b, err := VerifyExecutionPayloadHashInclusion(testnet, ctx, LastestSlotByHead{}, p)
if err != nil {
t.Fatalf("FAIL: Error during payload verification: %v", err)
} else if b != nil {
t.Fatalf("FAIL: Invalid Payload (%d) %v was included in slot %d (%v)", i+1, p, b.Message.Slot, b.Message.StateRoot)
}
}
}
func BaseFeeEncodingCheck(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n).join(&Config{
InitialBaseFeePerGas: big.NewInt(9223372036854775807), // 2**63 - 1
Nodes: []node{
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
transitionPayloadHash, err := testnet.WaitForExecutionPayload(ctx, SlotsUntilMerge(testnet, config))
if err != nil {
t.Fatalf("FAIL: Waiting for execution payload: %v", err)
}
// Check the base fee value in the transition payload.
// Must be at least 256 to guarantee that the endianess encoding is correct.
ec := NewEngineClient(t, testnet.ExecutionClients().Running()[0], config.TerminalTotalDifficulty)
h, err := ec.Eth.HeaderByHash(ec.Ctx(), transitionPayloadHash)
if err != nil {
t.Fatalf("FAIL: Unable to get transition payload header from execution client: %v", err)
}
if h.Difficulty.Cmp(common.Big0) != 0 {
t.Fatalf("FAIL: Transition header obtained is not PoS header: difficulty=%x", h.Difficulty)
}
if h.BaseFee.Cmp(common.Big256) < 0 {
t.Fatalf("FAIL: Basefee insufficient for test: %x", h.BaseFee)
}
t.Logf("INFO: Transition Payload created with sufficient baseFee: %x", h.BaseFee)
}
func EqualTimestampTerminalTransitionBlock(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n)
config = config.join(&Config{
// We are increasing the clique period, therefore we can reduce the TTD
TerminalTotalDifficulty: big.NewInt(config.TerminalTotalDifficulty.Int64() / 3),
Nodes: []node{
n,
n,
},
// The clique period needs to be equal to the slot time to try to get the CL client to attempt to produce
// a payload with the same timestamp as the terminal block
Eth1Consensus: &setup.Eth1CliqueConsensus{
CliquePeriod: config.SlotTime.Uint64(),
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
// No ForkchoiceUpdated with payload attributes should fail, which could happen if CL tries to create
// the payload with `timestamp==terminalBlock.timestamp`.
var (
fcuLock sync.Mutex
fcUAttrCount int
fcudone = make(chan error)
fcUCountLimit = 5
)
for _, p := range testnet.Proxies().Running() {
p.AddResponseCallback(EngineForkchoiceUpdatedV1, CheckErrorOnForkchoiceUpdatedPayloadAttr(&fcuLock, fcUCountLimit, &fcUAttrCount, fcudone))
}
// Wait until we verified all subsequent forkchoiceUpdated calls
if err := <-fcudone; err != nil {
t.Fatalf("FAIL: ForkchoiceUpdated call failed: %v", err)
}
}
func TTDBeforeBellatrix(t *hivesim.T, env *testEnv, n node) {
config := getClientConfig(n)
config = config.join(&Config{
AltairForkEpoch: common.Big1,
MergeForkEpoch: common.Big2,
TerminalTotalDifficulty: big.NewInt(150),
Nodes: []node{
n,
n,
},
})
testnet := startTestnet(t, env, config)
defer testnet.stopTestnet()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := testnet.WaitForExecutionPayload(ctx, SlotsUntilMerge(testnet, config))
if err != nil {
for i, e := range testnet.ExecutionClients().Running() {
ec := NewEngineClient(t, e, config.TerminalTotalDifficulty)
if b, err := ec.Eth.BlockByNumber(ec.Ctx(), nil); err == nil {
t.Logf("INFO: Last block on execution client %d: number=%d, hash=%s", i, b.NumberU64(), b.Hash())
}
}
t.Fatalf("FAIL: Waiting for execution payload: %v", err)
}
if err := VerifyELHeads(testnet, ctx); err != nil {
t.Fatalf("FAIL: Verifying EL Heads: %v", err)
}