diff --git a/specs/core/0_beacon-chain.md b/specs/core/0_beacon-chain.md index 681ff876f..6914c64e7 100644 --- a/specs/core/0_beacon-chain.md +++ b/specs/core/0_beacon-chain.md @@ -36,6 +36,7 @@ The primary source of load on the beacon chain are "attestations". Attestations | `DEPOSIT_SIZE` | 2**5 (= 32) | ETH | | `MIN_ONLINE_DEPOSIT_SIZE` | 2**4 (= 16) | ETH | | `GWEI_PER_ETH` | 10**9 | Gwei/ETH | +| `DEPOSIT_CONTRACT_ADDRESS` | **TBD** | - | | `TARGET_COMMITTEE_SIZE` | 2**8 (= 256) | validators | | `GENESIS_TIME` | **TBD** | seconds | | `SLOT_DURATION` | 2**4 (= 16) | seconds | @@ -43,11 +44,17 @@ The primary source of load on the beacon chain are "attestations". Attestations | `MIN_VALIDATOR_SET_CHANGE_INTERVAL` | 2**8 (= 256) | slots | ~1.1 hours | | `RANDAO_SLOTS_PER_LAYER` | 2**12 (= 4096) | slots | ~18 hours | | `SQRT_E_DROP_TIME` | 2**16 (= 65,536) | slots | ~12 days | -| `WITHDRAWAL_PERIOD` | 2**19 (= 524,288) | slots | ~97 days | +| `MIN_WITHDRAWAL_PERIOD` | 2**12 (= 4096) | slots | ~18 hours | +| `WITHDRAWALS_PER_CYCLE` | 8 | - | 4.3m ETH in ~6 months | +| `COLLECTIVE_PENALTY_CALCULATION_PERIOD` | 2**19 (= 524,288) | slots | ~3 months | +| `DELETION_PERIOD` | 2**21 (= 2,097,152) | slots | ~1.06 years | | `SHARD_PERSISTENT_COMMITTEE_CHANGE_PERIOD` | 2**16 (= 65,536) | slots | ~12 days | | `BASE_REWARD_QUOTIENT` | 2**15 (= 32,768) | — | -| `MAX_VALIDATOR_CHURN_QUOTIENT` | 2**5 (= 32) | — | -| `LOGOUT_MESSAGE` | `"LOGOUT"` | — | +| `MAX_VALIDATOR_CHURN_QUOTIENT` | 2**5 (= 32) | — | +| `POW_HASH_VOTING_PERIOD` | 2**10 (=1024) | - | +| `POW_CONTRACT_MERKLE_TREE_DEPTH` | 2**5 (=32) | - | +| `MAX_SPECIALS_PER_BLOCK` | 2**4 (= 16) | - | +| `LOGOUT_MESSAGE` | `"LOGOUT"` | — | | `INITIAL_FORK_VERSION` | 0 | — | **Notes** @@ -100,8 +107,8 @@ A `BeaconBlock` has the following fields: 'slot': 'uint64', # Proposer RANDAO reveal 'randao_reveal': 'hash32', - # Recent PoW chain reference (block hash) - 'pow_chain_reference': 'hash32', + # Recent PoW chain reference (receipt root) + 'candidate_pow_receipt_root': 'hash32', # Skip list of previous beacon block hashes # i'th item is the most recent ancestor whose slot is a multiple of 2**i for i = 0, ..., 31 'ancestor_hashes': ['hash32'], @@ -171,7 +178,7 @@ A `SpecialRecord` has the following fields: # Kind 'kind': 'uint8', # Data - 'data': ['bytes'] + 'data': 'bytes' } ``` @@ -206,6 +213,14 @@ The `BeaconState` has the following fields: 'deposits_penalized_in_period': ['uint32'], # Hash chain of validator set changes (for light clients to easily track deltas) 'validator_set_delta_hash_chain': 'hash32' + # Current sequence number for withdrawals + 'current_exit_seq': 'uint64', + # Genesis time + 'genesis_time': 'uint64', + # PoW chain reference + 'known_pow_receipt_root': 'hash32', + 'candidate_pow_receipt_root': 'hash32', + 'candidate_pow_receipt_root_votes': 'uint32', # Parameters relevant to hard forks / versioning. # Should be updated only by hard forks. 'pre_fork_version': 'uint32', @@ -213,8 +228,6 @@ The `BeaconState` has the following fields: 'fork_slot_number': 'uint64', # Attestations not yet processed 'pending_attestations': [AttestationRecord], - # Specials not yet been processed - 'pending_specials': [SpecialRecord] # recent beacon block hashes needed to process attestations, older to newer 'recent_block_hashes': ['hash32'], # RANDAO state @@ -242,6 +255,8 @@ A `ValidatorRecord` has the following fields: 'status': 'uint8', # Slot when validator exited (or 0) 'exit_slot': 'uint64' + # Sequence number when validator exited (or 0) + 'exit_seq': 'uint64' } ``` @@ -503,8 +518,209 @@ def int_sqrt(n: int) -> int: return x ``` +### PoW chain contract + +The beacon chain is initialized when a condition is met inside a contract on the existing PoW chain. This contract's code in Vyper is as follows: + +```python +HashChainValue: event({prev_tip: bytes32, data: bytes[2064], total_deposit_count: int128}) +ChainStart: event({hash_chain_tip: bytes32, time: bytes[8]}) + +receipt_tree: bytes32[int128] +total_deposit_count: int128 + +@payable +@public +def deposit(deposit_params: bytes[2048]): + index:int128 = self.total_deposit_count + 2**POW_CONTRACT_MERKLE_TREE_DEPTH + msg_gwei_bytes8: bytes[8] = slice(as_bytes32(msg.value / 10**9), 24, 8) + timestamp_bytes8: bytes[8] = slice(s_bytes32(block.timestamp), 24, 8) + deposit_data: bytes[2064] = concat(deposit_params, msg_gwei_bytes8, timestamp_bytes8) + + log.HashChainValue(self.receipt_tree[1], deposit_data, self.total_deposit_count) + + self.receipt_tree[index] = sha3(deposit_data) + for i in range(POW_CONTRACT_MERKLE_TREE_DEPTH): + index //= 2 + self.receipt_tree[index] = sha3(concat(self.receipt_tree[index * 2], self.receipt_tree[index * 2 + 1])) + self.total_deposit_count += 1 + if self.total_deposit_count == 16384: + log.ChainStart(self.receipt_tree[1], timestamp_bytes8) + +@public +@constant +def get_receipt_root() -> bytes32: + return self.receipt_tree[1] +``` + +The contract is at address `DEPOSIT_CONTRACT_ADDRESS`. When a user wishes to become a validator by moving their ETH from the 1.0 chain to the 2.0 chain, they should call the `deposit` function, sending along 32 ETH and providing as `deposit_params` a SimpleSerialize'd `DepositParams` object of the form: + +```python +{ + 'pubkey': 'int256', + 'proof_of_possession': ['int256'], + 'withdrawal_shard': 'int64', + 'withdrawal_address`: 'bytes20', + 'randao_commitment`: 'hash32' +} +``` + +If the user wishes to deposit more than `DEPOSIT_SIZE` ETH, they would need to make multiple calls. When the contract publishes a `ChainStart` log, this initializes the chain, calling `on_startup` with: + +* `initial_validator_entries` equal to the list of data records published as HashChainValue logs so far, in the order in which they were published (oldest to newest). +* `genesis_time` equal to the `time` value published in the log +* `pow_hash_chain_tip` equal to the `hash_chain_tip` value published in the log + ### On startup +A valid block with slot `0` (the "genesis block") has the following values. Other validity rules (eg. requiring a signature) do not apply. + +```python +{ + 'slot': 0, + 'randao_reveal': bytes32(0), + 'candidate_pow_receipt_root': bytes32(0), + 'ancestor_hashes': [bytes32(0) for i in range(32)], + 'state_root': STARTUP_STATE_ROOT, + 'attestations': [], + 'specials': [] +} +``` + +`STARTUP_STATE_ROOT` is the root of the initial state, computed by running the following code: + +```python +def on_startup(initial_validator_entries: List[Any], genesis_time: uint64, pow_hash_chain_tip: Hash32) -> BeaconState: + # Induct validators + validators = [] + for pubkey, proof_of_possession, withdrawal_shard, withdrawal_address, \ + randao_commitment in initial_validator_entries: + add_validator( + validators=validators, + pubkey=pubkey, + proof_of_possession=proof_of_possession, + withdrawal_shard=withdrawal_shard, + withdrawal_address=withdrawal_address, + randao_commitment=randao_commitment, + current_slot=0, + status=ACTIVE, + ) + # Setup state + x = get_new_shuffling(bytes([0] * 32), validators, 0) + crosslinks = [ + CrosslinkRecord( + slot=0, + hash=bytes([0] * 32) + ) + for i in range(SHARD_COUNT) + ] + state = BeaconState( + validator_set_change_slot=0, + validators=validators, + crosslinks=crosslinks, + last_state_recalculation_slot=0, + last_finalized_slot=0, + last_justified_slot=0, + justified_streak=0, + shard_and_committee_for_slots=x + x, + persistent_committees=split(shuffle(validators, bytes([0] * 32)), SHARD_COUNT), + persistent_committee_reassignments=[], + deposits_penalized_in_period=[], + next_shuffling_seed=b'\x00'*32, + validator_set_delta_hash_chain=bytes([0] * 32), # stub + current_exit_seq=0, + genesis_time=genesis_time, + known_pow_hash_chain_tip=pow_hash_chain_tip, + processed_pow_hash_chain_tip=pow_hash_chain_tip, + candidate_pow_hash_chain_tip=bytes([0] * 32), + candidate_pow_hash_chain_tip_votes=0, + pre_fork_version=INITIAL_FORK_VERSION, + post_fork_version=INITIAL_FORK_VERSION, + fork_slot_number=0, + pending_attestations=[], + pending_specials=[], + recent_block_hashes=[bytes([0] * 32) for _ in range(CYCLE_LENGTH * 2)], + randao_mix=bytes([0] * 32) # stub + ) + + return state +``` + +The `add_validator` routine is defined below. + +### Routine for adding a validator + +This routine should be run for every validator that is inducted as part of a log created on the PoW chain [TODO: explain where to check for these logs]. The status of the validators added after genesis is `PENDING_ACTIVATION`. These logs should be processed in the order in which they are emitted by the PoW chain. + +First, a helper function: + +```python +def min_empty_validator(validators: List[ValidatorRecord], current_slot: int): + for i, v in enumerate(validators): + if v.status == WITHDRAWN and v.exit_slot <= current_slot - DELETION_PERIOD: + return i + return None +``` + +Now, to add a validator: + +```python +def add_validator(validators: List[ValidatorRecord], + pubkey: int, + proof_of_possession: bytes, + withdrawal_shard: int, + withdrawal_address: Address, + randao_commitment: Hash32, + status: int, + current_slot: int) -> int: + # if following assert fails, validator induction failed + # move on to next validator registration log + signed_message = as_bytes32(pubkey) + as_bytes2(withdrawal_shard) + withdrawal_address + randao_commitment + assert BLSVerify(pub=pubkey, + msg=hash(signed_message), + sig=proof_of_possession) + # Pubkey uniqueness + assert pubkey not in [v.pubkey for v in validators] + rec = ValidatorRecord( + pubkey=pubkey, + withdrawal_shard=withdrawal_shard, + withdrawal_address=withdrawal_address, + randao_commitment=randao_commitment, + randao_last_change=current_slot, + balance=DEPOSIT_SIZE * GWEI_PER_ETH, + status=status, + exit_slot=0, + exit_seq=0 + ) + index = min_empty_validator(validators) + if index is None: + validators.append(rec) + return len(validators) - 1 + else: + validators[index] = rec + return index +``` + +`BLSVerify` is a function for verifying a BLS12-381 signature, defined in the BLS12-381 spec. + +### Routine for removing a validator + +```python +def exit_validator(index, state, penalize, current_slot): + validator = state.validators[index] + validator.exit_slot = current_slot + validator.exit_seq = state.current_exit_seq + state.current_exit_seq += 1 + if penalize: + validator.status = PENALIZED + state.deposits_penalized_in_period[current_slot // COLLECTIVE_PENALTY_CALCULATION_PERIOD] += validator.balance + else: + validator.status = PENDING_EXIT + add_validator_set_change_record(state, index, validator.pubkey, EXIT) +``` + +## On startup + Run the following code: ```python @@ -550,7 +766,6 @@ def on_startup(initial_validator_entries: List[Any]) -> BeaconState: post_fork_version=INITIAL_FORK_VERSION, fork_slot_number=0, pending_attestations=[], - pending_specials=[], recent_block_hashes=[bytes([0] * 32) for _ in range(CYCLE_LENGTH * 2)], randao_mix=bytes([0] * 32) # stub ) @@ -558,74 +773,7 @@ def on_startup(initial_validator_entries: List[Any]) -> BeaconState: return state ``` -The `add_validator` routine is defined below. - -### Routine for adding a validator - -This routine should be run for every validator that is inducted as part of a log created on the PoW chain [TODO: explain where to check for these logs]. The status of the validators added after genesis is `PENDING_ACTIVATION`. These logs should be processed in the order in which they are emitted by the PoW chain. - -First, a helper function: - -```python -def min_empty_validator(validators: List[ValidatorRecord]): - for i, v in enumerate(validators): - if v.status == WITHDRAWN: - return i - return None -``` - -Now, to add a validator: - -```python -def add_validator(validators: List[ValidatorRecord], - pubkey: int, - proof_of_possession: bytes, - withdrawal_shard: int, - withdrawal_address: Address, - randao_commitment: Hash32, - status: int, - current_slot: int) -> int: - # if following assert fails, validator induction failed - # move on to next validator registration log - assert BLSVerify(pub=pubkey, - msg=hash(pubkey), - sig=proof_of_possession) - rec = ValidatorRecord( - pubkey=pubkey, - withdrawal_shard=withdrawal_shard, - withdrawal_address=withdrawal_address, - randao_commitment=randao_commitment, - randao_last_change=current_slot, - balance=DEPOSIT_SIZE * GWEI_PER_ETH, - status=status, - exit_slot=0 - ) - index = min_empty_validator(validators) - if index is None: - validators.append(rec) - return len(validators) - 1 - else: - validators[index] = rec - return index -``` - -`BLSVerify` is a function for verifying a BLS12-381 signature, defined in the BLS12-381 spec. - -## Routine for removing a validator - -```python -def exit_validator(index, state, penalize, current_slot): - validator = state.validators[index] - validator.exit_slot = current_slot - if penalize: - validator.status = PENALIZED - state.deposits_penalized_in_period[current_slot // WITHDRAWAL_PERIOD] += validator.balance - else: - validator.status = PENDING_EXIT - add_validator_set_change_record(state, index, validator.pubkey, EXIT) -``` - -### Per-block processing +## Per-block processing This procedure should be carried out every beacon block. @@ -671,7 +819,7 @@ For each one of these attestations: * Let `fork_version = pre_fork_version if slot < fork_slot_number else post_fork_version`. * Verify that `aggregate_sig` verifies using the group pubkey generated and the serialized form of `AttestationSignedData(fork_version, slot, shard, parent_hashes, shard_block_hash, last_crosslinked_hash, shard_block_combined_data_root, justified_slot)` as the message. -Extend the list of `AttestationRecord` objects in the `state` with those included in the block, ordering the new additions in the same order as they came in the block. Similarly extend the list of `SpecialRecord` objects in the `state` with those included in the block. +Extend the list of `AttestationRecord` objects in the `state` with those included in the block, ordering the new additions in the same order as they came in the block. Let `curblock_proposer_index` be the validator index of the `block.slot % len(get_shards_and_committees_for_slot(state, block.slot)[0].committee)`'th attester in `get_shards_and_committees_for_slot(state, block.slot)[0]`, and `parent_proposer_index` be the validator index of the parent block, calculated similarly. Verify that an attestation from the `parent_proposer_index`'th validator is part of the first (ie. item 0 in the array) `AttestationRecord` object; this attester can be considered to be the proposer of the parent block. In general, when a beacon block is produced, it is broadcasted at the network layer along with the attestation from its proposer. @@ -679,9 +827,88 @@ Additionally, verify and update the RANDAO reveal. This is done as follows: * Let `repeat_hash(x, n) = x if n == 0 else repeat_hash(hash(x), n-1)`. * Let `V = state.validators[curblock_proposer_index]`. -* Verify that `repeat_hash(block.randao_reveal, (block.slot - V.randao_last_change) // RANDAO_SLOTS_PER_LAYER + 1) == V.randao_commitment`, and set `state.randao_mix = xor(state.randao_mix, block.randao_reveal)` and append to `state.pending_specials` a `SpecialObject(kind=RANDAO_CHANGE, data=[bytes8(curblock_proposer_index), block.randao_reveal, bytes8(block.slot)])`. +* Verify that `repeat_hash(block.randao_reveal, (block.slot - V.randao_last_change) // RANDAO_SLOTS_PER_LAYER + 1) == V.randao_commitment` +* Set `state.randao_mix = xor(state.randao_mix, block.randao_reveal)`, `V.randao_commitment = block.randao_reveal`, `V.randao_last_change = block.slot` -### State recalculations (every `CYCLE_LENGTH` slots) +Finally, if `block.candidate_pow_hash_chain_tip = state.candidate_pow_hash_chain_tip`, set `state.candidate_hash_chain_tip_votes += 1`. + +### Process penalties, logouts and other special objects + +Verify that there are at most `MAX_SPECIALS_PER_BLOCK` objects in `block.specials`. + +For each `SpecialRecord` `obj` in `block.specials`, verify that its `kind` is one of the below values, and that `obj.data` deserializes according to the format for the given `kind`, then process it. The word "verify" when used below means that if the given verification check fails, the block containing that `SpecialRecord` is invalid. + +#### LOGOUT + +```python +{ + 'validator_index': 'uint64', + 'signature': '[uint256]' +} +``` +Perform the following checks: + +* Let `fork_version = pre_fork_version if block.slot < fork_slot_number else post_fork_version`. Verify that `BLSVerify(pubkey=validators[data.validator_index].pubkey, msg=hash(LOGOUT_MESSAGE + bytes8(fork_version)), sig=data.signature)` +* Verify that `validators[validator_index].status == ACTIVE`. + +Run `exit_validator(data.validator_index, state, penalize=False, current_slot=block.slot)`. + +#### CASPER_SLASHING + +```python +{ + 'vote1_aggregate_sig_indices': '[uint24]', + 'vote1_data': AttestationSignedData, + 'vote1_aggregate_sig': '[uint256]', + 'vote2_aggregate_sig_indices': '[uint24]', + 'vote2_data': AttestationSignedData, + 'vote2_aggregate_sig': '[uint256]', +} +``` + +Perform the following checks: + +* For each `aggregate_sig`, verify that `BLSVerify(pubkey=aggregate_pubkey([validators[i].pubkey for i in aggregate_sig_indices]), msg=vote_data, sig=aggsig)` passes. +* Verify that `vote1_data != vote2_data`. +* Let `intersection = [x for x in vote1_aggregate_sig_indices if x in vote2_aggregate_sig_indices]`. Verify that `len(intersection) >= 1`. +* Verify that `vote1_data.justified_slot < vote2_data.justified_slot < vote2_data.slot <= vote1_data.slot`. + +For each validator index `v` in `intersection`, if `state.validators[v].status` does not equal `PENALIZED`, then run `exit_validator(v, state, penalize=True, current_slot=block.slot)` + +#### DEPOSIT_PROOF + +```python +{ + 'merkle_branch': '[hash32]', + 'merkle_tree_index': 'uint64', + 'deposit_data': { + 'deposit_params': DepositParams, + 'msg_value': 'uint64', + 'timestamp': 'uint64' + } +} +``` + +Note that `deposit_data` in serialized form should be the `DepositParams` followed by 8 bytes for the `msg_value` and 8 bytes for the `timestamp`, or exactly the `deposit_data` in the PoW contract of which the hash was placed into the Merkle tree. + +Use the following procedure to verify the `merkle_branch`, setting `leaf=serialized_deposit_data`, `depth=POW_CONTRACT_MERKLE_TREE_DEPTH` and `root=state.known_pow_receipt_root`: + +```python +def verify_merkle_branch(leaf: Hash32, branch: [Hash32], depth: int, index: int, root: Hash32) -> bool: + value = leaf + for i in range(depth): + if index % 2: + value = hash(branch[i], value) + else: + value = hash(value, branch[i]) + return value == root +``` + +Verify that `deposit_data.msg_value == DEPOSIT_SIZE` and `block.slot - (deposit_data.timestamp - state.genesis_time) // SLOT_DURATION < DELETION_PERIOD`. + +Run `add_validator(validators, deposit_data.deposit_params.pubkey, deposit_data.deposit_params.proof_of_possession, deposit_data.deposit_params.withdrawal_shard, data.deposit_params.withdrawal_address, deposit_data.deposit_params.randao_commitment, PENDING_ACTIVATION, block.slot)`. + +## State recalculations (every `CYCLE_LENGTH` slots) Repeat while `slot - last_state_recalculation_slot >= CYCLE_LENGTH`: @@ -735,14 +962,14 @@ For every shard number `shard` for which a crosslink committee exists in the cyc * Adjust balances as follows: * Participating validators gain `B // reward_quotient * (2 * total_balance_of_v_participating - total_balance_of_v) // total_balance_of_v`. * Non-participating validators lose `B // reward_quotient`. + +#### PoW chain related rules -#### Process penalties, logouts and other special objects +If `last_state_recalculation_slot % POW_HASH_VOTING_PERIOD == 0`, then: -For each `SpecialRecord` `obj` in `state.pending_specials`: - -* **[covers `LOGOUT`]**: If `obj.kind == LOGOUT`, interpret `data[0]` as a `uint24` and `data[1]` as a `hash32`, where `validator_index = data[0]` and `signature = data[1]`. If `BLSVerify(pubkey=validators[validator_index].pubkey, msg=hash(LOGOUT_MESSAGE + bytes8(fork_version)), sig=signature)`, where `fork_version = pre_fork_version if slot < fork_slot_number else post_fork_version`, and `validators[validator_index].status == ACTIVE`, run `exit_validator(validator_index, state, penalize=False, current_slot=block.slot)` -* **[covers `NO_DBL_VOTE`, `NO_SURROUND`, `NO_DBL_PROPOSE` slashing conditions]:** If `obj.kind == CASPER_SLASHING`, interpret `data[0]` as a list of concatenated `uint32` values where each value represents an index into `validators`, `data[1]` as the data being signed and `data[2]` as an aggregate signature. Interpret `data[3:6]` similarly. Verify that both signatures are valid, that the two signatures are signing distinct data, and that they are either signing the same slot number, or that one surrounds the other (ie. `source1 < source2 < target2 < target1`). Let `indices` be the list of indices in both signatures; verify that its length is at least 1. For each validator index `v` in `indices`, if its `status` does not equal `PENALIZED`, then run `exit_validator(v, state, penalize=True, current_slot=block.slot)` -* **[covers `RANDAO_CHANGE`]**: If `obj.kind == RANDAO_CHANGE`, interpret `data[0]` as a `uint24`, `data[1]` as a `hash32`, and `data[2]` as a `uint64`, where `proposer_index = data[0]`, `randao_commitment = data[1]`, and `randao_last_change = data[2]`. Set `validators[proposer_index].randao_commitment = randao_commitment`, and set `validators[proposer_index].randao_last_change = randao_last_change`. +* If `state.candidate_hash_chain_tip_votes * 3 >= POW_HASH_VOTING_PERIOD * 2`, set `state.hash_chain_tip = state.candidate_hash_chain_tip` +* Set `state.candidate_hash_chain_tip = block.candidate_pow_hash_chain_tip` +* Set `state.candidate_hash_chain_tip_votes = 0` ### Validator set change @@ -755,7 +982,7 @@ A validator set change can happen after a state recalculation if all of the foll Then, run the following algorithm to update the validator set: ```python -def change_validators(validators: List[ValidatorRecord]) -> None: +def change_validators(validators: List[ValidatorRecord], current_slot: int) -> None: # The active validator set active_validators = get_active_validator_indices(validators) # The total balance of active validators @@ -791,7 +1018,7 @@ def change_validators(validators: List[ValidatorRecord]) -> None: break # Calculate the total ETH that has been penalized in the last ~2-3 withdrawal periods - period_index = current_slot // WITHDRAWAL_PERIOD + period_index = current_slot // COLLECTIVE_PENALTY_CALCULATION_PERIOD total_penalties = ( (state.deposits_penalized_in_period[period_index]) + (state.deposits_penalized_in_period[period_index - 1] if period_index >= 1 else 0) + @@ -799,15 +1026,20 @@ def change_validators(validators: List[ValidatorRecord]) -> None: ) # Separate loop to withdraw validators that have been logged out for long enough, and # calculate their penalties if they were slashed - for i in range(len(validators)): - if validators[i].status in (PENDING_WITHDRAW, PENALIZED) and current_slot >= validators[i].exit_slot + WITHDRAWAL_PERIOD: - if validators[i].status == PENALIZED: - validators[i].balance -= validators[i].balance * min(total_penalties * 3, total_balance) // total_balance - validators[i].status = WITHDRAWN - withdraw_amount = validators[i].balance - ... - # STUB: withdraw to shard chain + def withdrawable(v): + return v.status in (PENDING_WITHDRAW, PENALIZED) and current_slot >= v.exit_slot + MIN_WITHDRAWAL_PERIOD + + withdrawable_validators = sorted(filter(withdrawable, validators), key=lambda v: v.exit_seq) + for v in withdrawable_validators[:WITHDRAWALS_PER_CYCLE]: + if v.status == PENALIZED: + v.balance -= v.balance * min(total_penalties * 3, total_balance) // total_balance + v.status = WITHDRAWN + v.exit_slot = current_slot + + withdraw_amount = v.balance + ... + # STUB: withdraw to shard chain ``` * Set `state.validator_set_change_slot = state.last_state_recalculation_slot` @@ -879,6 +1111,7 @@ Note: This spec is ~65% complete. * [ ] Specify the logic for proofs of custody, including slashing conditions * [ ] Specify BLSVerify and rework the spec for BLS12-381 throughout * [ ] Specify the constraints for `SpecialRecord`s ([issue 43](https://github.com/ethereum/eth2.0-specs/issues/43)) +* [ ] Specify the calculation and validation of `BeaconBlock.state_root` * [ ] Undergo peer review, security audits and formal verification **Documentation**