-
Notifications
You must be signed in to change notification settings - Fork 5
/
operations.go
671 lines (617 loc) · 22.8 KB
/
operations.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
package evaluators
import (
"bytes"
"context"
"fmt"
"math"
"strings"
"github.com/pkg/errors"
dilithium2 "github.com/theQRL/go-qrllib/dilithium"
corehelpers "github.com/theQRL/qrysm/v4/beacon-chain/core/helpers"
"github.com/theQRL/qrysm/v4/beacon-chain/core/signing"
"github.com/theQRL/qrysm/v4/beacon-chain/state"
"github.com/theQRL/qrysm/v4/config/params"
"github.com/theQRL/qrysm/v4/consensus-types/blocks"
"github.com/theQRL/qrysm/v4/consensus-types/primitives"
"github.com/theQRL/qrysm/v4/encoding/bytesutil"
"github.com/theQRL/qrysm/v4/encoding/ssz/detect"
zondpb "github.com/theQRL/qrysm/v4/proto/prysm/v1alpha1"
zondpbservice "github.com/theQRL/qrysm/v4/proto/zond/service"
v2 "github.com/theQRL/qrysm/v4/proto/zond/v2"
"github.com/theQRL/qrysm/v4/testing/endtoend/helpers"
e2e "github.com/theQRL/qrysm/v4/testing/endtoend/params"
"github.com/theQRL/qrysm/v4/testing/endtoend/policies"
e2etypes "github.com/theQRL/qrysm/v4/testing/endtoend/types"
"github.com/theQRL/qrysm/v4/testing/util"
"golang.org/x/exp/rand"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
var depositValCount = e2e.DepositCount
var numOfExits = 2
// Deposits should be processed in twice the length of the epochs per eth1 voting period.
var depositsInBlockStart = params.E2ETestConfig().EpochsPerEth1VotingPeriod * 2
// deposits included + finalization + MaxSeedLookahead for activation.
var depositActivationStartEpoch = depositsInBlockStart + 2 + params.E2ETestConfig().MaxSeedLookahead
var depositEndEpoch = depositActivationStartEpoch + primitives.Epoch(math.Ceil(float64(depositValCount)/float64(params.E2ETestConfig().MinPerEpochChurnLimit)))
var exitSubmissionEpoch = primitives.Epoch(7)
// ProcessesDepositsInBlocks ensures the expected amount of deposits are accepted into blocks.
var ProcessesDepositsInBlocks = e2etypes.Evaluator{
Name: "processes_deposits_in_blocks_epoch_%d",
Policy: policies.OnEpoch(depositsInBlockStart), // We expect all deposits to enter in one epoch.
Evaluation: processesDepositsInBlocks,
}
// VerifyBlockGraffiti ensures the block graffiti is one of the random list.
var VerifyBlockGraffiti = e2etypes.Evaluator{
Name: "verify_graffiti_in_blocks_epoch_%d",
Policy: policies.AfterNthEpoch(0),
Evaluation: verifyGraffitiInBlocks,
}
// ActivatesDepositedValidators ensures the expected amount of validator deposits are activated into the state.
var ActivatesDepositedValidators = e2etypes.Evaluator{
Name: "processes_deposit_validators_epoch_%d",
Policy: policies.BetweenEpochs(depositActivationStartEpoch, depositEndEpoch),
Evaluation: activatesDepositedValidators,
}
// DepositedValidatorsAreActive ensures the expected amount of validators are active after their deposits are processed.
var DepositedValidatorsAreActive = e2etypes.Evaluator{
Name: "deposited_validators_are_active_epoch_%d",
Policy: policies.AfterNthEpoch(depositEndEpoch),
Evaluation: depositedValidatorsAreActive,
}
// ProposeVoluntaryExit sends a voluntary exit from randomly selected validator in the genesis set.
var ProposeVoluntaryExit = e2etypes.Evaluator{
Name: "propose_voluntary_exit_epoch_%d",
Policy: policies.OnEpoch(exitSubmissionEpoch),
Evaluation: proposeVoluntaryExit,
}
// ValidatorsHaveExited checks the beacon state for the exited validator and ensures its marked as exited.
var ValidatorsHaveExited = e2etypes.Evaluator{
Name: "voluntary_has_exited_%d",
Policy: policies.OnEpoch(8),
Evaluation: validatorsHaveExited,
}
// SubmitWithdrawal sends a withdrawal from a previously exited validator.
var SubmitWithdrawal = e2etypes.Evaluator{
Name: "submit_withdrawal_epoch_%d",
Policy: policies.BetweenEpochs(helpers.CapellaE2EForkEpoch-2, helpers.CapellaE2EForkEpoch+1),
Evaluation: submitWithdrawal,
}
// ValidatorsHaveWithdrawn checks the beacon state for the withdrawn validator and ensures it has been withdrawn.
var ValidatorsHaveWithdrawn = e2etypes.Evaluator{
Name: "validator_has_withdrawn_%d",
Policy: func(currentEpoch primitives.Epoch) bool {
// Determine the withdrawal epoch by using the max seed lookahead. This value
// differs for our minimal and mainnet config which is why we calculate it
// each time the policy is executed.
validWithdrawnEpoch := exitSubmissionEpoch + 1 + params.BeaconConfig().MaxSeedLookahead
// Only run this for minimal setups after capella
if params.BeaconConfig().ConfigName == params.EndToEndName {
validWithdrawnEpoch = helpers.CapellaE2EForkEpoch + 1
}
requiredPolicy := policies.OnEpoch(validWithdrawnEpoch)
return requiredPolicy(currentEpoch)
},
Evaluation: validatorsAreWithdrawn,
}
// ValidatorsVoteWithTheMajority verifies whether validator vote for eth1data using the majority algorithm.
var ValidatorsVoteWithTheMajority = e2etypes.Evaluator{
Name: "validators_vote_with_the_majority_%d",
Policy: policies.AfterNthEpoch(0),
Evaluation: validatorsVoteWithTheMajority,
}
type mismatch struct {
k [dilithium2.CryptoPublicKeyBytes]byte
e uint64
o uint64
}
func (m mismatch) String() string {
return fmt.Sprintf("(%#x:%d:%d)", m.k, m.e, m.o)
}
func processesDepositsInBlocks(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
expected := ec.Balances(e2etypes.PostGenesisDepositBatch)
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
chainHead, err := client.GetChainHead(context.Background(), &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "failed to get chain head")
}
req := &zondpb.ListBlocksRequest{QueryFilter: &zondpb.ListBlocksRequest_Epoch{Epoch: chainHead.HeadEpoch - 1}}
blks, err := client.ListBeaconBlocks(context.Background(), req)
if err != nil {
return errors.Wrap(err, "failed to get blocks from beacon-chain")
}
observed := make(map[[dilithium2.CryptoPublicKeyBytes]byte]uint64)
for _, blk := range blks.BlockContainers {
sb, err := blocks.BeaconBlockContainerToSignedBeaconBlock(blk)
if err != nil {
return errors.Wrap(err, "failed to convert api response type to SignedBeaconBlock interface")
}
b := sb.Block()
deposits := b.Body().Deposits()
for _, d := range deposits {
k := bytesutil.ToBytes2592(d.Data.PublicKey)
v := observed[k]
observed[k] = v + d.Data.Amount
}
}
mismatches := []string{}
for k, ev := range expected {
ov := observed[k]
if ev != ov {
mismatches = append(mismatches, mismatch{k: k, e: ev, o: ov}.String())
}
}
if len(mismatches) != 0 {
return fmt.Errorf("not all expected deposits observed on chain, len(expected)=%d, len(observed)=%d, mismatches=%d; details(key:expected:observed): %s", len(expected), len(observed), len(mismatches), strings.Join(mismatches, ","))
}
return nil
}
func verifyGraffitiInBlocks(_ *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
chainHead, err := client.GetChainHead(context.Background(), &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "failed to get chain head")
}
begin := chainHead.HeadEpoch
// Prevent underflow when this runs at epoch 0.
if begin > 0 {
begin = begin.Sub(1)
}
req := &zondpb.ListBlocksRequest{QueryFilter: &zondpb.ListBlocksRequest_Epoch{Epoch: begin}}
blks, err := client.ListBeaconBlocks(context.Background(), req)
if err != nil {
return errors.Wrap(err, "failed to get blocks from beacon-chain")
}
for _, ctr := range blks.BlockContainers {
blk, err := blocks.BeaconBlockContainerToSignedBeaconBlock(ctr)
if err != nil {
return err
}
var e bool
slot := blk.Block().Slot()
graffitiInBlock := blk.Block().Body().Graffiti()
for _, graffiti := range helpers.Graffiti {
if bytes.Equal(bytesutil.PadTo([]byte(graffiti), 32), graffitiInBlock[:]) {
e = true
break
}
}
if !e && slot != 0 {
return errors.New("could not get graffiti from the list")
}
}
return nil
}
func activatesDepositedValidators(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
chainHead, err := client.GetChainHead(context.Background(), &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "failed to get chain head")
}
epoch := chainHead.HeadEpoch
validators, err := getAllValidators(client)
if err != nil {
return errors.Wrap(err, "failed to get validators")
}
expected := ec.Balances(e2etypes.PostGenesisDepositBatch)
var deposits, lowBalance, wrongExit, wrongWithdraw int
for _, v := range validators {
key := bytesutil.ToBytes2592(v.PublicKey)
if _, ok := expected[key]; !ok {
continue
}
delete(expected, key)
if v.ActivationEpoch != epoch {
continue
}
deposits++
if v.EffectiveBalance < params.BeaconConfig().MaxEffectiveBalance {
lowBalance++
}
if v.ExitEpoch != params.BeaconConfig().FarFutureEpoch {
wrongExit++
}
if v.WithdrawableEpoch != params.BeaconConfig().FarFutureEpoch {
wrongWithdraw++
}
}
// Make sure every post-genesis deposit has been proecssed, resulting in a validator.
if len(expected) > 0 {
return fmt.Errorf("missing %d validators for post-genesis deposits", len(expected))
}
if uint64(deposits) != params.BeaconConfig().MinPerEpochChurnLimit {
return fmt.Errorf("expected %d deposits to be processed in epoch %d, received %d", params.BeaconConfig().MinPerEpochChurnLimit, epoch, deposits)
}
if lowBalance > 0 {
return fmt.Errorf(
"%d validators did not have genesis validator effective balance of %d",
lowBalance,
params.BeaconConfig().MaxEffectiveBalance,
)
} else if wrongExit > 0 {
return fmt.Errorf("%d validators did not have an exit epoch of far future epoch", wrongExit)
} else if wrongWithdraw > 0 {
return fmt.Errorf("%d validators did not have a withdrawable epoch of far future epoch", wrongWithdraw)
}
return nil
}
func getAllValidators(c zondpb.BeaconChainClient) ([]*zondpb.Validator, error) {
vals := make([]*zondpb.Validator, 0)
pageToken := "0"
for pageToken != "" {
validatorRequest := &zondpb.ListValidatorsRequest{
PageSize: 100,
PageToken: pageToken,
}
validators, err := c.ListValidators(context.Background(), validatorRequest)
if err != nil {
return nil, errors.Wrap(err, "failed to get validators")
}
for _, v := range validators.ValidatorList {
vals = append(vals, v.Validator)
}
pageToken = validators.NextPageToken
}
return vals, nil
}
func depositedValidatorsAreActive(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
chainHead, err := client.GetChainHead(context.Background(), &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "failed to get chain head")
}
vals, err := getAllValidators(client)
if err != nil {
return errors.Wrap(err, "error retrieving validator list from API")
}
inactive := 0
lowBalance := 0
nexits := 0
expected := ec.Balances(e2etypes.PostGenesisDepositBatch)
nexpected := len(expected)
for _, v := range vals {
key := bytesutil.ToBytes2592(v.PublicKey)
if _, ok := expected[key]; !ok {
continue // we aren't checking for this validator
}
// ignore voluntary exits when checking balance and active status
exited := ec.ExitedVals[key]
if exited {
nexits++
delete(expected, key)
continue
}
if !corehelpers.IsActiveValidator(v, chainHead.HeadEpoch) {
inactive++
}
if v.EffectiveBalance < params.BeaconConfig().MaxEffectiveBalance {
lowBalance++
}
delete(expected, key)
}
if len(expected) > 0 {
mk := make([]string, 0)
for k := range expected {
mk = append(mk, fmt.Sprintf("%#x", k))
}
return fmt.Errorf("API response missing %d validators, based on deposits; keys=%s", len(expected), strings.Join(mk, ","))
}
if inactive != 0 || lowBalance != 0 {
return fmt.Errorf("active validator set does not match %d total deposited. %d exited, %d inactive, %d low balance", nexpected, nexits, inactive, lowBalance)
}
return nil
}
func proposeVoluntaryExit(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
valClient := zondpb.NewBeaconNodeValidatorClient(conn)
beaconClient := zondpb.NewBeaconChainClient(conn)
debugClient := zondpb.NewDebugClient(conn)
ctx := context.Background()
chainHead, err := beaconClient.GetChainHead(ctx, &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "could not get chain head")
}
stObj, err := debugClient.GetBeaconState(ctx, &zondpb.BeaconStateRequest{QueryFilter: &zondpb.BeaconStateRequest_Slot{Slot: chainHead.HeadSlot}})
if err != nil {
return errors.Wrap(err, "could not get state object")
}
versionedMarshaler, err := detect.FromState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state marshaler")
}
st, err := versionedMarshaler.UnmarshalBeaconState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state")
}
execIndices := []int{}
err = st.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error {
if val.WithdrawalCredentials()[0] == params.BeaconConfig().ETH1AddressWithdrawalPrefixByte {
execIndices = append(execIndices, idx)
}
return nil
})
if err != nil {
return err
}
if len(execIndices) > numOfExits {
execIndices = execIndices[:numOfExits]
}
deposits, privKeys, err := util.DeterministicDepositsAndKeys(params.BeaconConfig().MinGenesisActiveValidatorCount)
if err != nil {
return err
}
var sendExit = func(exitedIndex primitives.ValidatorIndex) error {
voluntaryExit := &zondpb.VoluntaryExit{
Epoch: chainHead.HeadEpoch,
ValidatorIndex: exitedIndex,
}
req := &zondpb.DomainRequest{
Epoch: chainHead.HeadEpoch,
Domain: params.BeaconConfig().DomainVoluntaryExit[:],
}
domain, err := valClient.DomainData(ctx, req)
if err != nil {
return err
}
signingData, err := signing.ComputeSigningRoot(voluntaryExit, domain.SignatureDomain)
if err != nil {
return err
}
signature := privKeys[exitedIndex].Sign(signingData[:])
signedExit := &zondpb.SignedVoluntaryExit{
Exit: voluntaryExit,
Signature: signature.Marshal(),
}
if _, err = valClient.ProposeExit(ctx, signedExit); err != nil {
return errors.Wrap(err, "could not propose exit")
}
pubk := bytesutil.ToBytes2592(deposits[exitedIndex].Data.PublicKey)
ec.ExitedVals[pubk] = true
return nil
}
// Send exits for keys which already contain execution credentials.
for _, idx := range execIndices {
if err := sendExit(primitives.ValidatorIndex(idx)); err != nil {
return err
}
}
// Send an exit for a non-exited validator.
for i := 0; i < numOfExits; {
randIndex := primitives.ValidatorIndex(rand.Uint64() % params.BeaconConfig().MinGenesisActiveValidatorCount)
if ec.ExitedVals[bytesutil.ToBytes2592(privKeys[randIndex].PublicKey().Marshal())] {
continue
}
if err := sendExit(randIndex); err != nil {
return err
}
i++
}
return nil
}
func validatorsHaveExited(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
for k := range ec.ExitedVals {
validatorRequest := &zondpb.GetValidatorRequest{
QueryFilter: &zondpb.GetValidatorRequest_PublicKey{
PublicKey: k[:],
},
}
validator, err := client.GetValidator(context.Background(), validatorRequest)
if err != nil {
return errors.Wrap(err, "failed to get validators")
}
if validator.ExitEpoch == params.BeaconConfig().FarFutureEpoch {
return fmt.Errorf("expected validator %#x to be submitted for exit", k)
}
}
return nil
}
func validatorsVoteWithTheMajority(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
client := zondpb.NewBeaconChainClient(conn)
chainHead, err := client.GetChainHead(context.Background(), &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "failed to get chain head")
}
begin := chainHead.HeadEpoch
// Prevent underflow when this runs at epoch 0.
if begin > 0 {
begin = begin.Sub(1)
}
req := &zondpb.ListBlocksRequest{QueryFilter: &zondpb.ListBlocksRequest_Epoch{Epoch: begin}}
blks, err := client.ListBeaconBlocks(context.Background(), req)
if err != nil {
return errors.Wrap(err, "failed to get blocks from beacon-chain")
}
slotsPerVotingPeriod := params.E2ETestConfig().SlotsPerEpoch.Mul(uint64(params.E2ETestConfig().EpochsPerEth1VotingPeriod))
for _, blk := range blks.BlockContainers {
var slot primitives.Slot
var vote []byte
switch blk.Block.(type) {
case *zondpb.BeaconBlockContainer_Phase0Block:
b := blk.GetPhase0Block().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_AltairBlock:
b := blk.GetAltairBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_BellatrixBlock:
b := blk.GetBellatrixBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_BlindedBellatrixBlock:
b := blk.GetBlindedBellatrixBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_CapellaBlock:
b := blk.GetCapellaBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_BlindedCapellaBlock:
b := blk.GetBlindedCapellaBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_DenebBlock:
b := blk.GetDenebBlock().Block
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
case *zondpb.BeaconBlockContainer_BlindedDenebBlock:
b := blk.GetBlindedDenebBlock().Message
slot = b.Slot
vote = b.Body.Eth1Data.BlockHash
default:
return errors.New("block neither phase0,altair or bellatrix")
}
ec.SeenVotes[slot] = vote
// We treat epoch 1 differently from other epoch for two reasons:
// - this evaluator is not executed for epoch 0 so we have to calculate the first slot differently
// - for some reason the vote for the first slot in epoch 1 is 0x000... so we skip this slot
var isFirstSlotInVotingPeriod bool
if chainHead.HeadEpoch == 1 && slot%params.BeaconConfig().SlotsPerEpoch == 0 {
continue
}
// We skipped the first slot so we treat the second slot as the starting slot of epoch 1.
if chainHead.HeadEpoch == 1 {
isFirstSlotInVotingPeriod = slot%params.BeaconConfig().SlotsPerEpoch == 1
} else {
isFirstSlotInVotingPeriod = slot%slotsPerVotingPeriod == 0
}
if isFirstSlotInVotingPeriod {
ec.ExpectedEth1DataVote = vote
return nil
}
if !bytes.Equal(vote, ec.ExpectedEth1DataVote) {
for i := primitives.Slot(0); i < slot; i++ {
v, ok := ec.SeenVotes[i]
if ok {
fmt.Printf("vote at slot=%d = %#x\n", i, v)
} else {
fmt.Printf("did not see slot=%d\n", i)
}
}
return fmt.Errorf("incorrect eth1data vote for slot %d; expected: %#x vs voted: %#x",
slot, ec.ExpectedEth1DataVote, vote)
}
}
return nil
}
func submitWithdrawal(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
beaconAPIClient := zondpbservice.NewBeaconChainClient(conn)
beaconClient := zondpb.NewBeaconChainClient(conn)
debugClient := zondpb.NewDebugClient(conn)
ctx := context.Background()
chainHead, err := beaconClient.GetChainHead(ctx, &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "could not get chain head")
}
stObj, err := debugClient.GetBeaconState(ctx, &zondpb.BeaconStateRequest{QueryFilter: &zondpb.BeaconStateRequest_Slot{Slot: chainHead.HeadSlot}})
if err != nil {
return errors.Wrap(err, "could not get state object")
}
versionedMarshaler, err := detect.FromState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state marshaler")
}
st, err := versionedMarshaler.UnmarshalBeaconState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state")
}
exitedIndices := make([]primitives.ValidatorIndex, 0)
for key := range ec.ExitedVals {
valIdx, ok := st.ValidatorIndexByPubkey(key)
if !ok {
return errors.Errorf("pubkey %#x does not exist in our state", key)
}
exitedIndices = append(exitedIndices, valIdx)
}
_, privKeys, err := util.DeterministicDepositsAndKeys(params.BeaconConfig().MinGenesisActiveValidatorCount)
if err != nil {
return err
}
changes := make([]*v2.SignedDilithiumToExecutionChange, 0)
// Only send half the number of changes each time, to allow us to test
// at the fork boundary.
wantedChanges := numOfExits / 2
for _, idx := range exitedIndices {
// Exit sending more change messages.
if len(changes) >= wantedChanges {
break
}
val, err := st.ValidatorAtIndex(idx)
if err != nil {
return err
}
if val.WithdrawalCredentials[0] == params.BeaconConfig().ETH1AddressWithdrawalPrefixByte {
continue
}
if !bytes.Equal(val.PublicKey, privKeys[idx].PublicKey().Marshal()) {
return errors.Errorf("pubkey is not equal, wanted %#x but received %#x", val.PublicKey, privKeys[idx].PublicKey().Marshal())
}
message := &v2.DilithiumToExecutionChange{
ValidatorIndex: idx,
FromDilithiumPubkey: privKeys[idx].PublicKey().Marshal(),
ToExecutionAddress: bytesutil.ToBytes(uint64(idx), 20),
}
domain, err := signing.ComputeDomain(params.BeaconConfig().DomainDilithiumToExecutionChange, params.BeaconConfig().GenesisForkVersion, st.GenesisValidatorsRoot())
if err != nil {
return err
}
sigRoot, err := signing.ComputeSigningRoot(message, domain)
if err != nil {
return err
}
signature := privKeys[idx].Sign(sigRoot[:]).Marshal()
change := &v2.SignedDilithiumToExecutionChange{
Message: message,
Signature: signature,
}
changes = append(changes, change)
}
_, err = beaconAPIClient.SubmitSignedDilithiumToExecutionChanges(ctx, &v2.SubmitDilithiumToExecutionChangesRequest{Changes: changes})
return err
}
func validatorsAreWithdrawn(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn) error {
conn := conns[0]
beaconClient := zondpb.NewBeaconChainClient(conn)
debugClient := zondpb.NewDebugClient(conn)
ctx := context.Background()
chainHead, err := beaconClient.GetChainHead(ctx, &emptypb.Empty{})
if err != nil {
return errors.Wrap(err, "could not get chain head")
}
stObj, err := debugClient.GetBeaconState(ctx, &zondpb.BeaconStateRequest{QueryFilter: &zondpb.BeaconStateRequest_Slot{Slot: chainHead.HeadSlot}})
if err != nil {
return errors.Wrap(err, "could not get state object")
}
versionedMarshaler, err := detect.FromState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state marshaler")
}
st, err := versionedMarshaler.UnmarshalBeaconState(stObj.Encoded)
if err != nil {
return errors.Wrap(err, "could not get state")
}
for key := range ec.ExitedVals {
valIdx, ok := st.ValidatorIndexByPubkey(key)
if !ok {
return errors.Errorf("pubkey %#x does not exist in our state", key)
}
bal, err := st.BalanceAtIndex(valIdx)
if err != nil {
return err
}
// Only return an error if the validator has more than 1 eth
// in its balance.
if bal > 1*params.BeaconConfig().GweiPerEth {
return errors.Errorf("Validator index %d with key %#x hasn't withdrawn. Their balance is %d.", valIdx, key, bal)
}
}
return nil
}