-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbeacon-chain.k
2207 lines (1966 loc) · 107 KB
/
beacon-chain.k
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
/*
* Notes:
* - bls_verify is not implemented (as discussed). Signature verification is not done.
*/
requires "hash-tree.k"
requires "uint64.k"
module BEACON-CHAIN
imports DOMAINS
imports HASH-TREE
imports UINT64
// Hacks around pyk/json front-end limitations
//====================================================
//Workarounds to make kast happy. Cannot put a function with no-args in init <k>, with json input.
syntax KItem ::= "wrap_hash_tree_root" "(" BytesOrContainer ")" [klabel(wrap_hash_tree_root), symbol]
| "wrap_hash_tree_root_state" "(" ")" [klabel(wrap_hash_tree_root_state), symbol]
| "wrap_is_valid_genesis_state" "(" ")" [klabel(wrap_is_valid_genesis_state), symbol]
rule wrap_hash_tree_root(OBJ) => hash_tree_root(OBJ)
rule wrap_hash_tree_root_state() => hash_tree_root_state()
rule wrap_is_valid_genesis_state() => is_valid_genesis_state()
syntax KItem ::= "test_process_slots" "(" Int ")" [klabel(test_process_slots), symbol]
rule <k> test_process_slots(NrSlots) => process_slots(SLOT +Int NrSlots) ...</k>
<slot> SLOT </slot>
// Initialization
//====================================================
syntax KItem ::= "noop" [klabel(noop), symbol]
| "init" [klabel(init), symbol]
| initZeroHashes(Int, Int)
/*
ZERO_BYTES32 = b'\x00' * 32
zerohashes = [ZERO_BYTES32]
for layer in range(1, 100):
zerohashes.append(hash(zerohashes[layer - 1] + zerohashes[layer - 1]))
*/
rule <k> init => initZeroHashes(1, 64) ...</k> //max pre-computed zerohash is 64 - ehough for all cases
<zerohashes-cache> .Map => (0 |-> defaultRoot()) </zerohashes-cache>
rule <k> initZeroHashes(I => I +Int 1, N) ...</k>
<zerohashes-cache> (.Map => (I |-> hashConcat(zerohashes(I -Int 1), zerohashes(I -Int 1)))) ...</zerohashes-cache>
requires I <Int N
rule initZeroHashes(N, N) => .K
// Helper functions -- Math
//====================================================
/*
def integer_squareroot(n: uint64) -> uint64:
"""
Return the largest integer ``x`` such that ``x**2 <= n``.
"""
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
*/
syntax Int ::= "integer_squareroot" "(" Int ")" [function]
rule integer_squareroot(N) => integer_squareroot_aux(N, N, (N +Int 1) /Int 2)
requires N >=Int 0
syntax Int ::= "integer_squareroot_aux" "(" Int "," Int "," Int ")" [function]
rule integer_squareroot_aux(N, X => Y, Y => (Y +Int N /Int Y) /Int 2)
requires Y <Int X
rule integer_squareroot_aux(N, X, Y) => X
requires Y >=Int X
/*
def xor(bytes_1: Bytes32, bytes_2: Bytes32) -> Bytes32:
"""
Return the exclusive-or of two 32-byte strings.
"""
return Bytes32(a ^ b for a, b in zip(bytes_1, bytes_2))
*/
syntax Bytes ::= xor( Bytes, Bytes ) [function]
rule xor(A, B) => chrChar(ordChar(substrString(A, 0, 1)) xorInt ordChar(substrString(B, 0, 1)))
+Bytes xor(substrString(A, 1, lengthString(A)), substrString(B, 1, lengthString(B)))
requires lengthString(A) >Int 0 andBool lengthString(B) >Int 0
rule xor("", "") => ""
// Helper functions -- Predicates
//====================================================
/*
def is_active_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is active.
"""
return validator.activation_epoch <= epoch < validator.exit_epoch
*/
syntax Bool ::= "is_active_validator" "(" Validator "," Int ")" [function]
rule is_active_validator( VAL, EPOCH )
=> VAL.activationEpoch <=Int EPOCH andBool EPOCH <Int VAL.exitEpoch
/*
def is_eligible_for_activation_queue(validator: Validator) -> bool:
"""
Check if ``validator`` is eligible to be placed into the activation queue.
"""
return (
validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH
and validator.effective_balance == MAX_EFFECTIVE_BALANCE
)
*/
syntax Bool ::= "is_eligible_for_activation_queue" "(" Validator ")" [function]
rule is_eligible_for_activation_queue ( VAL )
=> VAL.activationEligibilityEpoch ==Int FAR_FUTURE_EPOCH
andBool VAL.effectiveBalance ==Int MAX_EFFECTIVE_BALANCE
/*
def is_eligible_for_activation(state: BeaconState, validator: Validator) -> bool:
"""
Check if ``validator`` is eligible for activation.
"""
return (
# Placement in queue is finalized
validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch
# Has not yet been activated
and validator.activation_epoch == FAR_FUTURE_EPOCH
)
*/
syntax Bool ::= "is_eligible_for_activation" "(" Validator ")" [function]
rule [[ is_eligible_for_activation ( VAL )
=> VAL.activationEligibilityEpoch <=Int CHECKPOINT.epoch
andBool VAL.activationEpoch ==K FAR_FUTURE_EPOCH ]]
<finalized-checkpoint> CHECKPOINT </finalized-checkpoint>
/*
def is_slashable_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is slashable.
"""
return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch)
*/
syntax Bool ::= "is_slashable_validator" "(" Validator "," Int ")" [function]
rule is_slashable_validator( VAL, EPOCH )
=> notBool VAL.slashed andBool VAL.activationEpoch <=Int EPOCH andBool EPOCH <Int VAL.withdrawableEpoch
/*
def is_slashable_attestation_data(data_1: AttestationData, data_2: AttestationData) -> bool:
"""
Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
"""
return (
# Double vote
(data_1 != data_2 and data_1.target.epoch == data_2.target.epoch) or
# Surround vote
(data_1.source.epoch < data_2.source.epoch and data_2.target.epoch < data_1.target.epoch)
)
*/
syntax Bool ::= "is_slashable_attestation_data" "(" AttestationData "," AttestationData ")" [function]
rule is_slashable_attestation_data(
#AttestationData(S1, I1, H1, #Checkpoint(S1EP,S1H),#Checkpoint(T1EP,T1H)),
#AttestationData(S2, I2, H2, #Checkpoint(S2EP,S2H),#Checkpoint(T2EP,T2H))
) =>
// Double vote
//((H1 =/=K H2 orBool S1EP =/=K S2EP orBool S1H =/=K S2H orBool T1H =/=K T2H orBool CL1 =/=K CL2) andBool
// T1EP ==K T2EP) orBool
(#AttestationData(S1, I1, H1, #Checkpoint(S1EP,S1H),#Checkpoint(T1EP,T1H))
=/=K #AttestationData(S2, I2, H2, #Checkpoint(S2EP,S2H),#Checkpoint(T2EP,T2H))
andBool T1EP ==K T2EP) orBool
// Surround vote
(S1EP <Int S2EP andBool T2EP <Int T1EP)
/*
def is_valid_indexed_attestation(state: BeaconState, indexed_attestation: IndexedAttestation) -> bool:
"""
Check if ``indexed_attestation`` has valid indices and signature.
"""
indices = indexed_attestation.attesting_indices
# Verify max number of indices
if not len(indices) <= MAX_VALIDATORS_PER_COMMITTEE:
return False
# Verify indices are sorted and unique
if not indices == sorted(set(indices)):
return False
# Verify aggregate signature
pubkeys = [state.validators[i].pubkey for i in indices]
domain = get_domain(state, DOMAIN_BEACON_ATTESTER, indexed_attestation.data.target.epoch)
signing_root = compute_signing_root(indexed_attestation.data, domain)
return bls.FastAggregateVerify(pubkeys, signing_root, indexed_attestation.signature)
*/
syntax Bool ::= "is_valid_indexed_attestation" "(" IndexedAttestation ")" [function]
rule is_valid_indexed_attestation(IAtt)
=> len(IAtt.attesting_indices) <=Int MAX_VALIDATORS_PER_COMMITTEE
andBool IAtt.attesting_indices ==K sortUniqueIntList(IAtt.attesting_indices)
//we do not check for BLS signature
/*
def is_valid_merkle_branch(leaf: Bytes32, branch: Sequence[Bytes32], depth: uint64, index: uint64, root: Root) -> bool:
"""
Check if ``leaf`` at ``index`` verifies against the Merkle ``root`` and ``branch``.
"""
value = leaf
for i in range(depth):
if index // (2**i) % 2:
value = hash(branch[i] + value)
else:
value = hash(value + branch[i])
return value == root
*/
syntax Bool ::= "is_valid_merkle_branch" "(" Bytes32 "," BytesList "," Int "," Int "," Root ")" [function]
rule is_valid_merkle_branch(Leaf, Branch, Depth, Index, Root)
=> is_valid_merkle_branch_aux(Branch, Depth, Index, Root, 0, Leaf)
syntax Bool ::= "is_valid_merkle_branch_aux" "(" BytesList "," Int "," Int "," Root "," Int "," Root ")" [function]
rule is_valid_merkle_branch_aux(Branch, Depth, Index, _,
I => I +Int 1,
Value => #if Index /Int (2 ^Int I) %Int 2 ==Int 1
#then {hash(Branch[I] +Bytes Value)}:>Root
#else {hash(Value +Bytes Branch[I])}:>Root
#fi
)
requires I <Int Depth
rule is_valid_merkle_branch_aux(_, Depth, _, Root, I, Value) => Root ==String Value
requires I >=Int Depth
// Helper functions -- Misc
//====================================================
/*
def compute_shuffled_index(index: ValidatorIndex, index_count: uint64, seed: Bytes32) -> ValidatorIndex:
"""
Return the shuffled validator index corresponding to ``seed`` (and ``index_count``).
"""
assert index < index_count
# Swap or not (https://link.springer.com/content/pdf/10.1007%2F978-3-642-32009-5_1.pdf)
# See the 'generalized domain' algorithm on page 3
for current_round in range(SHUFFLE_ROUND_COUNT):
pivot = bytes_to_int(hash(seed + int_to_bytes(current_round, length=1))[0:8]) % index_count
flip = ValidatorIndex((pivot + index_count - index) % index_count)
position = max(index, flip)
source = hash(seed + int_to_bytes(current_round, length=1) + int_to_bytes(position // 256, length=4))
byte = source[(position % 256) // 8]
bit = (byte >> (position % 8)) % 2
index = flip if bit else index
return ValidatorIndex(index)
*/
syntax Int ::= "compute_shuffled_index" "(" Int "," Int "," Bytes32 ")" [function]
rule compute_shuffled_index(INDEX, COUNT, SEED) => compute_shuffled_index_loop(INDEX, COUNT, SEED, 0, SHUFFLE_ROUND_COUNT)
requires INDEX <Int COUNT
syntax Int ::= "compute_shuffled_index_loop" "(" Int "," Int "," Bytes32 "," Int "," Int ")" [function]
rule compute_shuffled_index_loop(
INDEX => #if computeBit(maxInt(INDEX, computeFlip(computePivot(SEED, CurrRound, COUNT), INDEX, COUNT)),
SEED, CurrRound)
#then computeFlip(computePivot(SEED, CurrRound, COUNT), INDEX, COUNT)
#else INDEX
#fi,
COUNT,
SEED,
CurrRound => CurrRound +Int 1,
RoundCount
)
requires CurrRound <Int RoundCount
rule compute_shuffled_index_loop(INDEX, _, _, CurrRound, RoundCount) => INDEX
requires CurrRound >=Int RoundCount
// byte = source[(position % 256) // 8]
// bit = (byte >> (position % 8)) % 2
syntax Bool ::= computeBit(Int /* position */, Root /* seed */, Int /* current round */ ) [function]
rule computeBit(Position, Seed, CurrRound)
=> (ordChar( substrString({computeSource(Position, Seed, CurrRound)}:>String,
(Position %Int 256) /Int 8,
(Position %Int 256) /Int 8 +Int 1)
) /Int 2 ^Int (Position %Int 8)) // shifting right by (position % 8)
%Int 2 ==Int 1
syntax Root ::= computeSource(Int /* position */, Root /* seed */, Int /* current round */) [function]
rule computeSource(Position, Seed, CurrRound)
=> hash(({Seed}:>Bytes +Bytes to_bytes(CurrRound, 1)) +Bytes to_bytes(Position /Int 256, 4))
syntax Int ::= computeFlip(Int /* pivot */, Int /* index */, Int /* count */ ) [function]
rule computeFlip(Pivot, Index, Count) => (Pivot +Int Count -Int Index) %Int Count
//pivot = bytes_to_int(hash(seed + int_to_bytes(current_round, length=1))[0:8]) % index_count
syntax Int ::= computePivot(Root /* seed */, Int /* current round */, Int /* index count */ ) [function]
rule computePivot(Seed, CurrRound, Count)
=> bytes_to_int(substrString({hash({Seed}:>Bytes +Bytes to_bytes(CurrRound, 1))}:>String, 0, 8)) %Int Count
/*
def compute_proposer_index(statE: BeaconState, indices: Sequence[ValidatorIndex], seed: Root) -> ValidatorIndex:
"""
Return from ``indices`` a random index sampled by effective balance.
"""
assert len(indices) > 0
MAX_RANDOM_BYTE = 2**8 - 1
i = 0
while True:
candidate_index = indices[compute_shuffled_index(ValidatorIndex(i % len(indices)), len(indices), seed)]
random_byte = hash(seed + int_to_bytes(i // 32, length=8))[i % 32]
effective_balance = state.validators[candidate_index].effective_balance
if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE * random_byte:
return ValidatorIndex(candidate_index)
i += 1
*/
syntax ValidatorIndex ::= "compute_proposer_index" "(" IntList "," Root ")" [function]
rule compute_proposer_index(INDICES, SEED) => computeProposerIndexLoop(INDICES, SEED, 0)
requires INDICES =/=K .IntList
syntax ValidatorIndex ::= computeProposerIndexLoop(IntList, Root, Int) [function]
rule computeProposerIndexLoop(INDICES, SEED, I)
=> #fun(CandidateIndex
=> #fun(RandomByte
=> #fun(EffectiveBalance
=> computeProposerIndexLoopAux(INDICES, SEED, I, EffectiveBalance, RandomByte, CandidateIndex)
)(getValidator(CandidateIndex).effectiveBalance)
//random_byte = hash(seed + int_to_bytes(i // 32, length=8))[i % 32]
)(getByte( hashConcat(SEED, to_bytes(I /Int 32, 8)), I %Int 32))
)(INDICES[compute_shuffled_index(I %Int len(INDICES), len(INDICES), SEED)])
syntax ValidatorIndex ::= computeProposerIndexLoopAux(IntList, Root, Int, Int, Int, ValidatorIndex) [function]
rule computeProposerIndexLoopAux(INDICES, SEED, I, EffectiveBalance, RandomByte, CandidateIndex) =>
computeProposerIndexLoop(INDICES, SEED, I +Int 1)
requires EffectiveBalance *Int (2 ^Int 8 -Int 1) <Int MAX_EFFECTIVE_BALANCE *Int RandomByte
//MAX_RANDOM_BYTE
rule computeProposerIndexLoopAux(INDICES, SEED, I, EffectiveBalance, RandomByte, CandidateIndex) =>
CandidateIndex
requires EffectiveBalance *Int (2 ^Int 8 -Int 1) >=Int MAX_EFFECTIVE_BALANCE *Int RandomByte
//MAX_RANDOM_BYTE
/*
def compute_committee(indices: Sequence[ValidatorIndex],
seed: Bytes32,
index: uint64,
count: uint64) -> Sequence[ValidatorIndex]:
"""
Return the committee corresponding to ``indices``, ``seed``, ``index``, and committee ``count``.
"""
start = (len(indices) * index) // count
end = (len(indices) * (index + 1)) // count
return [indices[compute_shuffled_index(ValidatorIndex(i), len(indices), seed)] for i in range(start, end)]
*/
syntax IntList ::= "compute_committee" "(" IntList "," Bytes32 "," Int "," Int ")" [function]
rule compute_committee(INDICES, SEED, INDEX, COUNT)
=> computeCommitteeLoop(
(len(INDICES) *Int INDEX) /Int COUNT,
(len(INDICES) *Int (INDEX +Int 1)) /Int COUNT,
SEED,
INDICES,
.IntList
)
syntax IntList ::= computeCommitteeLoop( Int, Int, Bytes32, IntList, IntList ) [function]
rule computeCommitteeLoop(I => I +Int 1, END, SEED, INDICES,
RESULT => RESULT +append INDICES[compute_shuffled_index(I, len(INDICES), SEED)] )
requires I <Int END
rule computeCommitteeLoop(I, END, _,_, RESULT) => RESULT
requires I >=Int END
/*
def compute_epoch_at_slot(slot: Slot) -> Epoch:
"""
Return the epoch number of ``slot``.
"""
return Epoch(slot // SLOTS_PER_EPOCH)
*/
syntax Int ::= "compute_epoch_at_slot" "(" Int ")" [function]
rule compute_epoch_at_slot(SLOT) => SLOT /Int SLOTS_PER_EPOCH
/*
def compute_start_slot_at_epoch(epoch: Epoch) -> Slot:
"""
Return the start slot of ``epoch``.
"""
return Slot(epoch * SLOTS_PER_EPOCH)
*/
syntax Int ::= "compute_start_slot_at_epoch" "(" Int ")" [function]
rule compute_start_slot_at_epoch(EPOCH) => EPOCH *Int SLOTS_PER_EPOCH
/*
def compute_activation_exit_epoch(epoch: Epoch) -> Epoch:
"""
Return the epoch during which validator activations and exits initiated in ``epoch`` take effect.
"""
return Epoch(epoch + 1 + MAX_SEED_LOOKAHEAD)
*/
syntax Int ::= "compute_activation_exit_epoch" "(" Int ")" [function]
rule compute_activation_exit_epoch(EP) => EP +Int 1 +Int MAX_SEED_LOOKAHEAD
/*
def compute_domain(domain_type: DomainType, fork_version: Optional[Version]=None) -> Domain:
"""
Return the domain for the ``domain_type`` and ``fork_version``.
"""
if fork_version is None:
fork_version = GENESIS_FORK_VERSION
return Domain(domain_type + fork_version)
*/
syntax Domain ::= "compute_domain" "(" DomainType "," OptionVersion ")" [function]
rule compute_domain(DTYPE, OVERSION)
=> compute_domain_aux(DTYPE, #if isNone(OVERSION) #then GENESIS_FORK_VERSION #else versOf(OVERSION) #fi)
syntax Domain ::= "compute_domain_aux" "(" DomainType "," Version ")" [function]
rule compute_domain_aux(Domain_Type, Fork_Version) => {Domain_Type +Bytes Fork_Version}:>Domain
// Helper functions -- Beacon state accessors
//====================================================
/*
def get_current_epoch(state: BeaconState) -> Epoch:
"""
Return the current epoch.
"""
return compute_epoch_at_slot(state.slot)
*/
syntax Int ::= "get_current_epoch" "(" ")" [function]
rule [[ get_current_epoch() => compute_epoch_at_slot(SLOT) ]]
<slot> SLOT </slot>
/*
def get_previous_epoch(state: BeaconState) -> Epoch:
"""`
Return the previous epoch (unless the current epoch is ``GENESIS_EPOCH``).
"""
current_epoch = get_current_epoch(state)
return GENESIS_EPOCH if current_epoch == GENESIS_EPOCH else Epoch(current_epoch - 1)
*/
syntax Int ::= "get_previous_epoch" "(" ")" [function]
rule get_previous_epoch() => #if get_current_epoch() ==K GENESIS_EPOCH
#then GENESIS_EPOCH
#else get_current_epoch() -Int 1
#fi
/*
def get_block_root(state: BeaconState, epoch: Epoch) -> Root:
"""
Return the block root at the start of a recent ``epoch``.
"""
return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch))
*/
syntax Root ::= "get_block_root" "(" Int ")" [function]
rule get_block_root(EP) => get_block_root_at_slot(compute_start_slot_at_epoch(EP))
/*
def get_block_root_at_slot(state: BeaconState, slot: Slot) -> Root:
"""
Return the block root at a recent ``slot``.
"""
assert slot < state.slot <= slot + SLOTS_PER_HISTORICAL_ROOT
return state.block_roots[slot % SLOTS_PER_HISTORICAL_ROOT]
*/
syntax Root ::= "get_block_root_at_slot" "(" Int ")" [function]
rule [[ get_block_root_at_slot(SLOT) => {BLOCKROOTS[ SLOT %Int SLOTS_PER_HISTORICAL_ROOT ]}:>Root ]]
<slot> StateSLOT </slot>
<block-roots> BLOCKROOTS </block-roots>
requires SLOT <Int StateSLOT andBool StateSLOT <=Int (SLOT +Int SLOTS_PER_HISTORICAL_ROOT)
/*
def get_randao_mix(state: BeaconState, epoch: Epoch) -> Bytes32:
"""
Return the randao mix at a recent ``epoch``.
"""
return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR]
*/
syntax Bytes32 ::= "get_randao_mix" "(" Int ")" [function]
rule [[ get_randao_mix( EPOCH ) => {RMS[ EPOCH %Int EPOCHS_PER_HISTORICAL_VECTOR ]}:>Bytes32 ]]
<randao-mixes> RMS </randao-mixes>
/*
def get_active_validator_indices(state: BeaconState, epoch: Epoch) -> Sequence[ValidatorIndex]:
"""
Return the sequence of active validator indices at ``epoch``.
"""
return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)]
*/
syntax IntList ::= "get_active_validator_indices" "(" epoch: Int ")" [function]
rule [[ get_active_validator_indices(EP) => getActiveValidatorIndicesAux(.IntList, 0, VALIDATORS, EP) ]]
<validators> VALIDATORS </validators>
syntax IntList ::= getActiveValidatorIndicesAux( result: IntList, i: Int, validators: Map, epoch: Int ) [function]
rule getActiveValidatorIndicesAux(_, I => I +Int 1, _:Map (I |-> V => .Map), EP )
requires notBool is_active_validator(V, EP)
rule getActiveValidatorIndicesAux(Is => Is +append I, I => I +Int 1, _:Map (I |-> V => .Map), EP )
requires is_active_validator(V, EP)
rule getActiveValidatorIndicesAux(Is, _, .Map, _) => Is
/*
def get_validator_churn_limit(state: BeaconState) -> uint64:
"""
Return the validator churn limit for the current epoch.
"""
active_validator_indices = get_active_validator_indices(state, get_current_epoch(state))
return max(MIN_PER_EPOCH_CHURN_LIMIT, len(active_validator_indices) // CHURN_LIMIT_QUOTIENT)
*/
syntax Int ::= "get_validator_churn_limit" "(" ")" [function]
rule get_validator_churn_limit() => maxInt(
MIN_PER_EPOCH_CHURN_LIMIT,
len(get_active_validator_indices(get_current_epoch())) /Int CHURN_LIMIT_QUOTIENT )
/*
def get_seed(state: BeaconState, epoch: Epoch, domain_type: DomainType) -> Root:
"""
Return the seed at ``epoch``.
"""
mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1)) # Avoid underflow
return hash(domain_type + int_to_bytes(epoch, length=8) + mix)
*/
syntax Root ::= "get_seed" "(" Int "," DomainType ")" [function]
rule get_seed(Epoch, DOMAINTYPE)
=> hash( (DOMAINTYPE
+Bytes to_bytes(Epoch, 8))
+Bytes get_randao_mix(Epoch +Int EPOCHS_PER_HISTORICAL_VECTOR -Int MIN_SEED_LOOKAHEAD -Int 1)
)
/*
def get_committee_count_at_slot(state: BeaconState, slot: Slot) -> uint64:
"""
Return the number of committees at ``slot``.
"""
epoch = compute_epoch_at_slot(slot)
return max(1, min(
MAX_COMMITTEES_PER_SLOT,
len(get_active_validator_indices(state, epoch)) // SLOTS_PER_EPOCH // TARGET_COMMITTEE_SIZE,
))
*/
syntax Int ::= "get_committee_count_at_slot" "(" Int ")" [function]
rule get_committee_count_at_slot( SLOT )
=> maxInt(1, minInt(MAX_COMMITTEES_PER_SLOT,
len(get_active_validator_indices(compute_epoch_at_slot( SLOT ))) /Int SLOTS_PER_EPOCH /Int TARGET_COMMITTEE_SIZE
)
)
/*
def get_beacon_committee(state: BeaconState, slot: Slot, index: CommitteeIndex) -> Sequence[ValidatorIndex]:
"""
Return the beacon committee at ``slot`` for ``index``.
"""
epoch = compute_epoch_at_slot(slot)
committees_per_slot = get_committee_count_at_slot(state, slot)
return compute_committee(
indices=get_active_validator_indices(state, epoch),
seed=get_seed(state, epoch, DOMAIN_BEACON_ATTESTER),
index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index,
count=committees_per_slot * SLOTS_PER_EPOCH,
)
*/
syntax IntList ::= "get_beacon_committee" "(" Int "," Int ")" [function]
rule get_beacon_committee(SLOT, INDEX)
=> #fun(CommitteesPerSlot
=> #fun(EPOCH
=> compute_committee(
get_active_validator_indices(EPOCH),
get_seed(EPOCH, DOMAIN_BEACON_ATTESTER),
(SLOT %Int SLOTS_PER_EPOCH) *Int CommitteesPerSlot +Int INDEX,
CommitteesPerSlot *Int SLOTS_PER_EPOCH)
)(compute_epoch_at_slot(SLOT))
)(get_committee_count_at_slot(SLOT))
/*
def get_beacon_proposer_index(state: BeaconState) -> ValidatorIndex:
"""
Return the beacon proposer index at the current slot.
"""
epoch = get_current_epoch(state)
seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + int_to_bytes(state.slot, length=8))
indices = get_active_validator_indices(state, epoch)
return compute_proposer_index(state, indices, seed)
*/
syntax ValidatorIndex ::= "get_beacon_proposer_index" "(" ")" [function]
rule [[ get_beacon_proposer_index()
=> #fun(EPOCH
=> #fun(SEED
=> #fun(INDICES
=> compute_proposer_index(INDICES, SEED)
)(get_active_validator_indices(EPOCH))
)(hashConcat(get_seed(EPOCH, DOMAIN_BEACON_PROPOSER), to_bytes(SLOT, 8)))
)(get_current_epoch())
]]
<slot> SLOT </slot>
/*
def get_total_balance(state: BeaconState, indices: Set[ValidatorIndex]) -> Gwei:
"""
Return the combined effective balance of the ``indices``. (1 Gwei minimum to avoid divisions by zero.)
"""
return Gwei(max(1, sum([state.validators[index].effective_balance for index in indices])))
*/
syntax Int ::= "get_total_balance" "(" IntList ")" [function]
rule get_total_balance(INDICES) => maxInt(1, getTotalBalancePure(INDICES, 0))
syntax Int ::= getTotalBalancePure( IntList, Int ) [function]
rule getTotalBalancePure(I IL => IL, S => S +Int getValidator(I).effectiveBalance)
rule getTotalBalancePure(.IntList, S) => S
/*
def get_total_active_balance(state: BeaconState) -> Gwei:
"""
Return the combined effective balance of the active validators.
"""
return get_total_balance(state, set(get_active_validator_indices(state, get_current_epoch(state))))
*/
syntax Int ::= "get_total_active_balance" "(" ")" [function]
rule get_total_active_balance() => get_total_balance(get_active_validator_indices(get_current_epoch()))
/*
def get_domain(state: BeaconState, domain_type: DomainType, epoch: Epoch=None) -> Domain:
"""
Return the signature domain (fork version concatenated with domain type) of a message.
"""
epoch = get_current_epoch(state) if epoch is None else epoch
fork_version = state.fork.previous_version if epoch < state.fork.epoch else state.fork.current_version
return compute_domain(domain_type, fork_version)
*/
syntax Domain ::= "get_domain" "(" DomainType "," OptionInt ")" [function]
rule get_domain(DTYPE, OEPOCH)
=> get_domain_aux(DTYPE, #if isNone(OEPOCH) #then get_current_epoch() #else intOf(OEPOCH) #fi)
syntax Domain ::= "get_domain_aux" "(" DomainType "," Int ")" [function]
rule [[ get_domain_aux(DTYPE, EPOCH)
=> compute_domain(DTYPE, #if EPOCH <Int FEPOCH #then #SomeVers(FPREV) #else #SomeVers(FCURR) #fi) ]]
<fork> #Fork(FPREV,FCURR,FEPOCH) </fork>
/*
def get_indexed_attestation(state: BeaconState, attestation: Attestation) -> IndexedAttestation:
"""
Return the indexed attestation corresponding to ``attestation``.
"""
attesting_indices = get_attesting_indices(state, attestation.data, attestation.aggregation_bits)
return IndexedAttestation(
attesting_indices=sorted(attesting_indices),
data=attestation.data,
signature=attestation.signature,
)
*/
syntax IndexedAttestation ::= "get_indexed_attestation" "(" Attestation ")" [function]
rule get_indexed_attestation(#Attestation(AggregationBits, DATA, SIG)) =>
#fun(AttestingIndices => #IndexedAttestation(
sortIntList(AttestingIndices),
DATA,
SIG
)
)(get_attesting_indices(DATA, AggregationBits))
/*
def get_attesting_indices(state: BeaconState,
data: AttestationData,
bits: Bitlist[MAX_VALIDATORS_PER_COMMITTEE]) -> Set[ValidatorIndex]:
"""
Return the set of attesting indices corresponding to ``data`` and ``bits``.
"""
committee = get_beacon_committee(state, data.slot, data.index)
return set(index for i, index in enumerate(committee) if bits[i])
*/
syntax IntList ::= "get_attesting_indices" "(" AttestationData "," BitList ")" [function]
rule get_attesting_indices(#AttestationData(SLOT,INDEX,_,_,_), BL) =>
extractAttestingIndices(get_beacon_committee(SLOT, INDEX), BL, .IntList)
syntax IntList ::= extractAttestingIndices(IntList, BitList, IntList) [function]
rule extractAttestingIndices(I IL => IL, true BL => BL, AL => AL +append I)
rule extractAttestingIndices(I IL => IL, false BL => BL, AL)
rule extractAttestingIndices(.IntList,_, AL) => AL
// Helper functions -- Beacon state mutators
//====================================================
/*
def increase_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
"""
Increase the validator balance at index ``index`` by ``delta``.
"""
state.balances[index] += delta
*/
syntax KItem ::= "increase_balance" "(" ValidatorIndex "," Int ")"
rule <k> increase_balance(ValIndex, Delta) => . ...</k>
<balances>... ValIndex |-> (BAL => BAL +Int Delta) ...</balances>
/*
def decrease_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
"""
Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
"""
state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta
*/
syntax KItem ::= "decrease_balance" "(" ValidatorIndex "," Int ")"
rule <k> decrease_balance(ValIndex, Delta) => . ...</k>
<balances>... ValIndex |-> (BAL => #if Delta >Int BAL #then 0 #else BAL -Int Delta #fi) ...</balances>
/*
def initiate_validator_exit(state: BeaconState, index: ValidatorIndex) -> None:
"""
Initiate the exit of the validator with index ``index``.
"""
# Return if validator already initiated exit
validator = state.validators[index]
if validator.exit_epoch != FAR_FUTURE_EPOCH:
return
# Compute exit queue epoch
exit_epochs = [v.exit_epoch for v in state.validators if v.exit_epoch != FAR_FUTURE_EPOCH]
exit_queue_epoch = max(exit_epochs + [compute_activation_exit_epoch(get_current_epoch(state))])
exit_queue_churn = len([v for v in state.validators if v.exit_epoch == exit_queue_epoch])
if exit_queue_churn >= get_validator_churn_limit(state):
exit_queue_epoch += Epoch(1)
# Set validator exit epoch and withdrawable epoch
validator.exit_epoch = exit_queue_epoch
validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
*/
syntax KItem ::= "initiate_validator_exit" "(" Int ")"
| initiateValidatorExitAux( Int /*index*/ , Int /*exit_queue_epoch*/ )
rule initiate_validator_exit(INDEX) => .K
requires getValidator(INDEX).exitEpoch =/=K FAR_FUTURE_EPOCH
rule initiate_validator_exit(INDEX) => initiateValidatorExitAux(INDEX, exitQueueEpochAux(INDEX))
requires getValidator(INDEX).exitEpoch ==K FAR_FUTURE_EPOCH
rule <k> initiateValidatorExitAux(INDEX, ExitQEpoch) => .K ...</k>
<validators>
VALIDATORS:Map
INDEX |-> #Validator(_,_,_,_,_,_,
ExitEPOCH => #if exitQueueChurnAux(ExitQEpoch, VALIDATORS, 0) >=Int get_validator_churn_limit()
#then ExitQEpoch +Int 1
#else ExitQEpoch
#fi ,
WithdrEpoch => #if exitQueueChurnAux(ExitQEpoch, VALIDATORS, 0) >=Int get_validator_churn_limit()
#then ExitQEpoch +Int 1
#else ExitQEpoch
#fi +Int MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
</validators>
syntax Int ::= exitQueueEpochAux ( Int ) [function]
rule [[ exitQueueEpochAux(INDEX)
=> maxAux(compute_activation_exit_epoch(get_current_epoch())
exitEpochsAux(VALIDATORS, .IntList) ) ]]
<validators> VALIDATORS </validators>
syntax IntList ::= exitEpochsAux( Map /*validators*/ , IntList /*result*/ ) [function]
rule exitEpochsAux(_:Map (_ |-> VAL => .Map),
RES => VAL.exitEpoch RES )
requires VAL.exitEpoch =/=K FAR_FUTURE_EPOCH
rule exitEpochsAux(_:Map (_ |-> VAL => .Map),
RES /*unchanged*/ )
requires VAL.exitEpoch ==K FAR_FUTURE_EPOCH
rule exitEpochsAux(.Map, RES) => RES
// exit_queue_churn = len([v for v in state.validator_registry if v.exit_epoch == exit_queue_epoch])
syntax Int ::= exitQueueChurnAux ( Int /*exit_queue_epoch*/ , Map /*validator_registry*/ , Int /*result*/ ) [function]
rule exitQueueChurnAux( ExitQEpoch, _:Map (_ |-> VAL => .Map), RES => RES +Int 1 )
requires VAL.exitEpoch ==K ExitQEpoch
rule exitQueueChurnAux( ExitQEpoch, _:Map (_ |-> VAL => .Map), _ )
requires VAL.exitEpoch =/=K ExitQEpoch
rule exitQueueChurnAux( _, .Map, RES ) => RES
/*
def slash_validator(state: BeaconState,
slashed_index: ValidatorIndex,
whistleblower_index: ValidatorIndex=None) -> None:
"""
Slash the validator with index ``slashed_index``.
"""
epoch = get_current_epoch(state)
initiate_validator_exit(state, slashed_index)
validator = state.validators[slashed_index]
validator.slashed = True
validator.withdrawable_epoch = max(validator.withdrawable_epoch, Epoch(epoch + EPOCHS_PER_SLASHINGS_VECTOR))
state.slashings[epoch % EPOCHS_PER_SLASHINGS_VECTOR] += validator.effective_balance
decrease_balance(state, slashed_index, validator.effective_balance // MIN_SLASHING_PENALTY_QUOTIENT)
# Apply proposer and whistleblower rewards
proposer_index = get_beacon_proposer_index(state)
if whistleblower_index is None:
whistleblower_index = proposer_index
whistleblower_reward = Gwei(validator.effective_balance // WHISTLEBLOWER_REWARD_QUOTIENT)
proposer_reward = Gwei(whistleblower_reward // PROPOSER_REWARD_QUOTIENT)
increase_balance(state, proposer_index, proposer_reward)
increase_balance(state, whistleblower_index, whistleblower_reward - proposer_reward)
*/
syntax KItem ::= "slash_validator" "(" ValidatorIndex "," /*slashed_index*/
ValidatorIndex /*whistleblower_index or .ValidatorIndex if none*/ ")"
rule <k> slash_validator(SlashedINDEX, WhistleblINDEX)
=> initiate_validator_exit(SlashedINDEX)
~> slashValidatorAux(SlashedINDEX,
#if WhistleblINDEX ==K .ValidatorIndex #then get_beacon_proposer_index() #else WhistleblINDEX #fi,
get_beacon_proposer_index(),
VAL.effectiveBalance /Int WHISTLEBLOWER_REWARD_QUOTIENT, //whistleblower_reward
VAL.effectiveBalance /Int WHISTLEBLOWER_REWARD_QUOTIENT /Int PROPOSER_REWARD_QUOTIENT, //proposer_reward
get_current_epoch()) //epoch
...</k>
<validators> SlashedINDEX |-> VAL ...</validators>
syntax KItem ::= "slashValidatorAux" "(" ValidatorIndex "," ValidatorIndex "," ValidatorIndex "," Int "," Int "," Int ")"
rule <k> slashValidatorAux(SlashedINDEX, WhistleblINDEX, ProposerINDEX, WhistleREWARD, ProposerREWARD, Epoch)
=> decrease_balance(SlashedINDEX, EffBALANCE /Int MIN_SLASHING_PENALTY_QUOTIENT)
~> increase_balance(ProposerINDEX, ProposerREWARD)
~> increase_balance(WhistleblINDEX, WhistleREWARD -Int ProposerREWARD)
...</k>
<validators>
SlashedINDEX |-> #Validator(
_,_,
EffBALANCE,
_ => true, //slashed
_,_,_,
WithdEPOCH => maxInt(WithdEPOCH, Epoch +Int EPOCHS_PER_SLASHINGS_VECTOR) //withdrawable epoch
)
...
</validators>
<slashings> Epoch %Int EPOCHS_PER_SLASHINGS_VECTOR |-> (SL => SL +Int EffBALANCE) ...</slashings>
// Genesis state
//====================================================
/*
def initialize_beacon_state_from_eth1(eth1_block_hash: Bytes32,
eth1_timestamp: uint64,
deposits: Sequence[Deposit]) -> BeaconState:
fork = Fork(
previous_version=GENESIS_FORK_VERSION,
current_version=GENESIS_FORK_VERSION,
epoch=GENESIS_EPOCH,
)
state = BeaconState(
genesis_time=eth1_timestamp - eth1_timestamp % MIN_GENESIS_DELAY + 2 * MIN_GENESIS_DELAY,
fork=fork,
eth1_data=Eth1Data(block_hash=eth1_block_hash, deposit_count=len(deposits)),
latest_block_header=BeaconBlockHeader(body_root=hash_tree_root(BeaconBlockBody())),
randao_mixes=[eth1_block_hash] * EPOCHS_PER_HISTORICAL_VECTOR, # Seed RANDAO with Eth1 entropy
)
# Process deposits
leaves = list(map(lambda deposit: deposit.data, deposits))
for index, deposit in enumerate(deposits):
deposit_data_list = List[DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH](*leaves[:index + 1])
state.eth1_data.deposit_root = hash_tree_root(deposit_data_list)
process_deposit(state, deposit)
# Process activations
for index, validator in enumerate(state.validators):
balance = state.balances[index]
validator.effective_balance = min(balance - balance % EFFECTIVE_BALANCE_INCREMENT, MAX_EFFECTIVE_BALANCE)
if validator.effective_balance == MAX_EFFECTIVE_BALANCE:
validator.activation_eligibility_epoch = GENESIS_EPOCH
validator.activation_epoch = GENESIS_EPOCH
return state
*/
syntax KItem ::= "initialize_beacon_state_from_eth1" "(" Root "," Int "," DepositList ")" [klabel(initialize_beacon_state_from_eth1), symbol]
rule <k> initialize_beacon_state_from_eth1(E1BH, E1TS, Deposits)
=> stateInit
~> processEth1Deposits(Deposits, getDataList(Deposits), 0)
~> processEth1Activations
... </k>
<genesis-time> _ => E1TS -Int E1TS %Int MIN_GENESIS_DELAY +Int 2 *Int MIN_GENESIS_DELAY </genesis-time>
<eth1-data> _ => #Eth1Data(defaultRoot(), len(Deposits), E1BH) </eth1-data>
<randao-mixes> _ => fillInVector(E1BH, EPOCHS_PER_HISTORICAL_VECTOR) </randao-mixes>
<latest-block-header>
//BeaconBlockHeader(body_root=hash_tree_root(BeaconBlockBody()))
_ => #BeaconBlockHeader(0, defaultRoot(), defaultRoot(), hash_tree_root(defaultBeaconBlockBody()))
</latest-block-header>
//Full state initialization, when generating genesis state
syntax KItem ::= "stateInit"
rule <k> stateInit => .K ...</k>
<fork> _ => #Fork(GENESIS_FORK_VERSION, GENESIS_FORK_VERSION, GENESIS_EPOCH) </fork>
<block-roots> _ => fillInMap(defaultRoot(), SLOTS_PER_HISTORICAL_ROOT) </block-roots> //Vector[Root, SLOTS_PER_HISTORICAL_ROOT]
<state-roots> _ => fillInMap(defaultRoot(), SLOTS_PER_HISTORICAL_ROOT) </state-roots> //Vector[Root, SLOTS_PER_HISTORICAL_ROOT]
<slashings> _ => fillInMap(0, EPOCHS_PER_SLASHINGS_VECTOR) </slashings> //Vector[Gwei, EPOCHS_PER_SLASHINGS_VECTOR]
<justification-bits> _ => false false false false .BitList </justification-bits> //Bitvector[JUSTIFICATION_BITS_LENGTH]
<previous-justified-checkpoint> _ => defaultCheckpoint() </previous-justified-checkpoint>
<current-justified-checkpoint> _ => defaultCheckpoint() </current-justified-checkpoint>
<finalized-checkpoint> _ => defaultCheckpoint() </finalized-checkpoint>
/* leaves = list(map(lambda deposit: deposit.data, deposits))
for index, deposit in enumerate(deposits):
deposit_data_list = List[DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH](*leaves[:index + 1])
state.eth1_data.deposit_root = hash_tree_root(deposit_data_list)
process_deposit(state, deposit) */
syntax KItem ::= "processEth1Deposits" "(" DepositList "," DepositDataList "," Int ")"
rule <k> (. => process_deposit(Dep))
~> processEth1Deposits(Dep Deposits => Deposits, Leaves, INDEX => INDEX +Int 1)
... </k>
<eth1-data>
ETH1Data => setDepositRoot(ETH1Data,
//List[DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH]
hash_tree_root_list(slice(Leaves, 0, INDEX +Int 1), 2 ^Int DEPOSIT_CONTRACT_TREE_DEPTH, %container, false))
</eth1-data>
rule processEth1Deposits(.DepositList, _,_) => .K
syntax Eth1Data ::= setDepositRoot(Eth1Data, Root) [function]
rule setDepositRoot(#Eth1Data(DROOT, COUNT, BHASH), NewDROOT) => #Eth1Data(NewDROOT, COUNT, BHASH)
syntax DepositDataList ::= getDataList(DepositList) [function]
rule getDataList(Dep Deps) => Dep.data getDataList(Deps)
rule getDataList(.DepositList) => .DepositDataList
/* for index, validator in enumerate(state.validators):
balance = state.balances[index]
validator.effective_balance = min(balance - balance % EFFECTIVE_BALANCE_INCREMENT, MAX_EFFECTIVE_BALANCE)
if validator.effective_balance == MAX_EFFECTIVE_BALANCE:
validator.activation_eligibility_epoch = GENESIS_EPOCH
validator.activation_epoch = GENESIS_EPOCH */
syntax KItem ::= "processEth1Activations"
| processEth1Activations( Int, Int )
rule processEth1Activations => processEth1Activations(0, numOfValidators())
rule <k> processEth1Activations(INDEX => INDEX +Int 1, COUNT) ...</k>
<balances> INDEX |-> BAL ...</balances>
<validators> INDEX |-> #Validator(_,_,
(_ => minInt(BAL -Int BAL %Int EFFECTIVE_BALANCE_INCREMENT, MAX_EFFECTIVE_BALANCE)),
_,
(AEE => #if MAX_EFFECTIVE_BALANCE <=Int BAL -Int BAL %Int EFFECTIVE_BALANCE_INCREMENT
#then GENESIS_EPOCH
#else AEE
#fi),
(AE => #if MAX_EFFECTIVE_BALANCE <=Int BAL -Int BAL %Int EFFECTIVE_BALANCE_INCREMENT
#then GENESIS_EPOCH
#else AE
#fi),
_,_)
...</validators>
requires INDEX <Int COUNT
rule processEth1Activations(COUNT, COUNT) => .K
/*
def is_valid_genesis_state(state: BeaconState) -> bool:
if state.genesis_time < MIN_GENESIS_TIME:
return False
if len(get_active_validator_indices(state, GENESIS_EPOCH)) < MIN_GENESIS_ACTIVE_VALIDATOR_COUNT:
return False
return True
*/
syntax Bool ::= "is_valid_genesis_state" "(" ")" [function, klabel(is_valid_genesis_state), symbol]
rule [[ is_valid_genesis_state()
=> #if Gtime <Int MIN_GENESIS_TIME
orBool len(get_active_validator_indices(GENESIS_EPOCH)) <Int MIN_GENESIS_ACTIVE_VALIDATOR_COUNT
#then false
#else true
#fi ]]
<genesis-time> Gtime </genesis-time>
// Beacon chain state transition function
//====================================================
/*
def state_transition(state: BeaconState, signed_block: SignedBeaconBlock, validate_result: bool=True) -> BeaconState:
block = signed_block.message
# Process slots (including those with no blocks) since block
process_slots(state, block.slot)
# Verify signature
if validate_result:
assert verify_block_signature(state, signed_block)
# Process block
process_block(state, block)
# Verify state root
if validate_result:
assert block.state_root == hash_tree_root(state)
# Return post-state
return state
*/
syntax KItem ::= "state_transition" "(" signedBlock: SignedBeaconBlock "," validateResult: Bool ")" [klabel(state_transition), symbol]
rule state_transition(SIGNEDBLOCK, VSR) => process_slots(SIGNEDBLOCK.message._slot) ~> process_block(SIGNEDBLOCK.message) ~> validateStateRoot(SIGNEDBLOCK.message, VSR)
syntax KItem ::= validateStateRoot ( BeaconBlock, Bool )
rule validateStateRoot(BLOCK, VSR) => .K
requires (notBool VSR) orBool (BLOCK.stateRoot ==K hash_tree_root_state())
// * - bls_verify is not implemented (as discussed). Signature verification is not done.
/*
def process_slots(state: BeaconState, slot: Slot) -> None:
assert state.slot <= slot
while state.slot < slot:
process_slot(state)
# Process epoch on the start slot of the next epoch
if (state.slot + 1) % SLOTS_PER_EPOCH == 0:
process_epoch(state)
state.slot += Slot(1)
*/
syntax KItem ::= "process_slots" "(" Int ")" [klabel(process_slots), symbol]
rule <k> process_slots(SLOT) => processSlotsLoop(SLOT) ...</k>
<slot> StateSLOT </slot>
requires StateSLOT <=Int SLOT
syntax KItem ::= "processSlotsLoop" "(" Int ")"
rule <k> processSlotsLoop(SLOT) =>
process_slot()
~> #if (StateSLOT +Int 1) %Int SLOTS_PER_EPOCH ==K 0 #then process_epoch() #else .K #fi