From 053b8ec2a54e65471d8a8801c8ee25fd64341af6 Mon Sep 17 00:00:00 2001 From: Danny Ryan Date: Mon, 28 Jan 2019 12:15:43 -0700 Subject: [PATCH] cleanup state transition organization and notes --- specs/core/0_beacon-chain.md | 1528 +++++++++++++++++----------------- 1 file changed, 773 insertions(+), 755 deletions(-) diff --git a/specs/core/0_beacon-chain.md b/specs/core/0_beacon-chain.md index c0e247108..f57ad9a6f 100644 --- a/specs/core/0_beacon-chain.md +++ b/specs/core/0_beacon-chain.md @@ -50,80 +50,86 @@ - [`Eth1Data`](#eth1data) - [`Eth1DataVote`](#eth1datavote) - [Custom Types](#custom-types) + - [Helper functions](#helper-functions) + - [`hash`](#hash) + - [`hash_tree_root`](#hash_tree_root) + - [`slot_to_epoch`](#slot_to_epoch) + - [`get_current_epoch`](#get_current_epoch) + - [`get_epoch_start_slot`](#get_epoch_start_slot) + - [`is_active_validator`](#is_active_validator) + - [`get_active_validator_indices`](#get_active_validator_indices) + - [`shuffle`](#shuffle) + - [`split`](#split) + - [`get_epoch_committee_count`](#get_epoch_committee_count) + - [`get_shuffling`](#get_shuffling) + - [`get_previous_epoch_committee_count`](#get_previous_epoch_committee_count) + - [`get_current_epoch_committee_count`](#get_current_epoch_committee_count) + - [`get_crosslink_committees_at_slot`](#get_crosslink_committees_at_slot) + - [`get_block_root`](#get_block_root) + - [`get_randao_mix`](#get_randao_mix) + - [`get_active_index_root`](#get_active_index_root) + - [`generate_seed`](#generate_seed) + - [`get_beacon_proposer_index`](#get_beacon_proposer_index) + - [`merkle_root`](#merkle_root) + - [`get_attestation_participants`](#get_attestation_participants) + - [`int_to_bytes1`, `int_to_bytes2`, ...](#int_to_bytes1-int_to_bytes2-) + - [`get_effective_balance`](#get_effective_balance) + - [`get_fork_version`](#get_fork_version) + - [`get_domain`](#get_domain) + - [`verify_slashable_vote_data`](#verify_slashable_vote_data) + - [`is_double_vote`](#is_double_vote) + - [`is_surround_vote`](#is_surround_vote) + - [`integer_squareroot`](#integer_squareroot) + - [`get_entry_exit_effect_epoch`](#get_entry_exit_effect_epoch) + - [`bls_verify`](#bls_verify) + - [`bls_verify_multiple`](#bls_verify_multiple) + - [`bls_aggregate_pubkeys`](#bls_aggregate_pubkeys) + - [`validate_proof_of_possession`](#validate_proof_of_possession) + - [`process_deposit`](#process_deposit) + - [`Routines for updating validator status`](#routines-for-updating-validator-status) + - [`activate_validator`](#activate_validator) + - [`initiate_validator_exit`](#initiate_validator_exit) + - [`exit_validator`](#exit_validator) + - [`penalize_validator`](#penalize_validator) + - [`prepare_validator_for_withdrawal`](#prepare_validator_for_withdrawal) - [Ethereum 1.0 deposit contract](#ethereum-10-deposit-contract) - [Deposit arguments](#deposit-arguments) - [Withdrawal credentials](#withdrawal-credentials) - [`Deposit` logs](#deposit-logs) - [`ChainStart` log](#chainstart-log) - [Vyper code](#vyper-code) + - [On startup](#on-startup) - [Beacon chain processing](#beacon-chain-processing) - [Beacon chain fork choice rule](#beacon-chain-fork-choice-rule) - [Beacon chain state transition function](#beacon-chain-state-transition-function) - - [Helper functions](#helper-functions) - - [`hash`](#hash) - - [`hash_tree_root`](#hash_tree_root) - - [`slot_to_epoch`](#slot_to_epoch) - - [`get_current_epoch`](#get_current_epoch) - - [`get_epoch_start_slot`](#get_epoch_start_slot) - - [`is_active_validator`](#is_active_validator) - - [`get_active_validator_indices`](#get_active_validator_indices) - - [`shuffle`](#shuffle) - - [`split`](#split) - - [`get_epoch_committee_count`](#get_epoch_committee_count) - - [`get_shuffling`](#get_shuffling) - - [`get_previous_epoch_committee_count`](#get_previous_epoch_committee_count) - - [`get_current_epoch_committee_count`](#get_current_epoch_committee_count) - - [`get_crosslink_committees_at_slot`](#get_crosslink_committees_at_slot) - - [`get_block_root`](#get_block_root) - - [`get_randao_mix`](#get_randao_mix) - - [`get_active_index_root`](#get_active_index_root) - - [`generate_seed`](#generate_seed) - - [`get_beacon_proposer_index`](#get_beacon_proposer_index) - - [`merkle_root`](#merkle_root) - - [`get_attestation_participants`](#get_attestation_participants) - - [`int_to_bytes1`, `int_to_bytes2`, ...](#int_to_bytes1-int_to_bytes2-) - - [`get_effective_balance`](#get_effective_balance) - - [`get_fork_version`](#get_fork_version) - - [`get_domain`](#get_domain) - - [`verify_slashable_vote_data`](#verify_slashable_vote_data) - - [`is_double_vote`](#is_double_vote) - - [`is_surround_vote`](#is_surround_vote) - - [`integer_squareroot`](#integer_squareroot) - - [`get_entry_exit_effect_epoch`](#get_entry_exit_effect_epoch) - - [`bls_verify`](#bls_verify) - - [`bls_verify_multiple`](#bls_verify_multiple) - - [`bls_aggregate_pubkeys`](#bls_aggregate_pubkeys) - - [On startup](#on-startup) - - [Routine for processing deposits](#routine-for-processing-deposits) - - [Routines for updating validator status](#routines-for-updating-validator-status) - - [Per-slot processing](#per-slot-processing) - - [Slot](#slot) - - [Block roots](#block-roots) - - [Per-block processing](#per-block-processing) - - [Slot](#slot-1) - - [Proposer signature](#proposer-signature) - - [RANDAO](#randao) - - [Eth1 data](#eth1-data) - - [Operations](#operations) - - [Proposer slashings](#proposer-slashings-1) - - [Attester slashings](#attester-slashings-1) - - [Attestations](#attestations-1) - - [Deposits](#deposits-1) - - [Exits](#exits-1) - - [Custody](#custody) - - [Per-epoch processing](#per-epoch-processing) - - [Helpers](#helpers) - - [Eth1 data](#eth1-data-1) - - [Justification](#justification) - - [Crosslinks](#crosslinks) - - [Rewards and penalties](#rewards-and-penalties) - - [Justification and finalization](#justification-and-finalization) - - [Attestation inclusion](#attestation-inclusion) - - [Crosslinks](#crosslinks-1) - - [Ejections](#ejections) - - [Validator registry and shuffling seed data](#validator-registry-and-shuffling-seed-data) - - [Final updates](#final-updates) - - [State root processing](#state-root-processing) + - [Per-slot processing](#per-slot-processing) + - [Slot](#slot) + - [Block roots](#block-roots) + - [Per-block processing](#per-block-processing) + - [Slot](#slot-1) + - [Proposer signature](#proposer-signature) + - [RANDAO](#randao) + - [Eth1 data](#eth1-data) + - [Operations](#operations) + - [Proposer slashings](#proposer-slashings-1) + - [Attester slashings](#attester-slashings-1) + - [Attestations](#attestations-1) + - [Deposits](#deposits-1) + - [Exits](#exits-1) + - [Custody](#custody) + - [Per-epoch processing](#per-epoch-processing) + - [Helpers](#helpers) + - [Eth1 data](#eth1-data-1) + - [Justification](#justification) + - [Crosslinks](#crosslinks) + - [Rewards and penalties](#rewards-and-penalties) + - [Justification and finalization](#justification-and-finalization) + - [Attestation inclusion](#attestation-inclusion) + - [Crosslinks](#crosslinks-1) + - [Ejections](#ejections) + - [Validator registry and shuffling seed data](#validator-registry-and-shuffling-seed-data) + - [Final updates](#final-updates) + - [State root verification](#state-root-verification) - [References](#references) - [Normative](#normative) - [Informative](#informative) @@ -622,6 +628,616 @@ We define the following Python custom types for type hinting and readability: | `BLSPubkey` | 48-byte data | a public key in BLS signature scheme | | `BLSSignature` | 96-byte data | a signature in BLS signature scheme | +## Helper functions + +Note: The definitions below are for specification purposes and are not necessarily optimal implementations. + +### `hash` + +The hash function is denoted by `hash`. In Phase 0 the beacon chain is deployed with the same hash function as Ethereum 1.0, i.e. Keccak-256 (also incorrectly known as SHA3). + +Note: We aim to migrate to a S[T/N]ARK-friendly hash function in a future Ethereum 2.0 deployment phase. + +### `hash_tree_root` + +`def hash_tree_root(object: SSZSerializable) -> Bytes32` is a function for hashing objects into a single root utilizing a hash tree structure. `hash_tree_root` is defined in the [SimpleSerialize spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/simple-serialize.md#tree-hash). + +### `slot_to_epoch` + +```python +def slot_to_epoch(slot: SlotNumber) -> EpochNumber: + return slot // EPOCH_LENGTH +``` + +### `get_current_epoch` + +```python +def get_current_epoch(state: BeaconState) -> EpochNumber: + return slot_to_epoch(state.slot) +``` + +### `get_epoch_start_slot` + +```python +def get_epoch_start_slot(epoch: EpochNumber) -> SlotNumber: + return epoch * EPOCH_LENGTH +``` + +### `is_active_validator` +```python +def is_active_validator(validator: Validator, epoch: EpochNumber) -> bool: + """ + Checks if ``validator`` is active. + """ + return validator.activation_epoch <= epoch < validator.exit_epoch +``` + +### `get_active_validator_indices` + +```python +def get_active_validator_indices(validators: List[Validator], epoch: EpochNumber) -> List[ValidatorIndex]: + """ + Gets indices of active validators from ``validators``. + """ + return [i for i, v in enumerate(validators) if is_active_validator(v, epoch)] +``` + +### `shuffle` + +```python +def shuffle(values: List[Any], seed: Bytes32) -> List[Any]: + """ + Returns the shuffled ``values`` with ``seed`` as entropy. + """ + values_count = len(values) + + # Entropy is consumed from the seed in 3-byte (24 bit) chunks. + rand_bytes = 3 + # The highest possible result of the RNG. + rand_max = 2 ** (rand_bytes * 8) - 1 + + # The range of the RNG places an upper-bound on the size of the list that + # may be shuffled. It is a logic error to supply an oversized list. + assert values_count < rand_max + + output = [x for x in values] + source = seed + index = 0 + while index < values_count - 1: + # Re-hash the `source` to obtain a new pattern of bytes. + source = hash(source) + # Iterate through the `source` bytes in 3-byte chunks. + for position in range(0, 32 - (32 % rand_bytes), rand_bytes): + # Determine the number of indices remaining in `values` and exit + # once the last index is reached. + remaining = values_count - index + if remaining == 1: + break + + # Read 3-bytes of `source` as a 24-bit big-endian integer. + sample_from_source = int.from_bytes(source[position:position + rand_bytes], 'big') + + # Sample values greater than or equal to `sample_max` will cause + # modulo bias when mapped into the `remaining` range. + sample_max = rand_max - rand_max % remaining + + # Perform a swap if the consumed entropy will not cause modulo bias. + if sample_from_source < sample_max: + # Select a replacement index for the current index. + replacement_position = (sample_from_source % remaining) + index + # Swap the current index with the replacement index. + output[index], output[replacement_position] = output[replacement_position], output[index] + index += 1 + else: + # The sample causes modulo bias. A new sample should be read. + pass + + return output +``` + +### `split` + +```python +def split(values: List[Any], split_count: int) -> List[List[Any]]: + """ + Splits ``values`` into ``split_count`` pieces. + """ + list_length = len(values) + return [ + values[(list_length * i // split_count): (list_length * (i + 1) // split_count)] + for i in range(split_count) + ] +``` + +### `get_epoch_committee_count` + +```python +def get_epoch_committee_count(active_validator_count: int) -> int: + return max( + 1, + min( + SHARD_COUNT // EPOCH_LENGTH, + active_validator_count // EPOCH_LENGTH // TARGET_COMMITTEE_SIZE, + ) + ) * EPOCH_LENGTH +``` + +### `get_shuffling` + +```python +def get_shuffling(seed: Bytes32, + validators: List[Validator], + epoch: EpochNumber) -> List[List[ValidatorIndex]] + """ + Shuffles ``validators`` into crosslink committees seeded by ``seed`` and ``epoch``. + Returns a list of ``committees_per_epoch`` committees where each + committee is itself a list of validator indices. + """ + + active_validator_indices = get_active_validator_indices(validators, epoch) + + committees_per_epoch = get_epoch_committee_count(len(active_validator_indices)) + + # Shuffle + seed = xor(seed, int_to_bytes32(epoch)) + shuffled_active_validator_indices = shuffle(active_validator_indices, seed) + + # Split the shuffled list into committees_per_epoch pieces + return split(shuffled_active_validator_indices, committees_per_epoch) +``` + +**Invariant**: if `get_shuffling(seed, validators, epoch)` returns some value `x` for some `epoch <= get_current_epoch(state) + ENTRY_EXIT_DELAY`, it should return the same value `x` for the same `seed` and `epoch` and possible future modifications of `validators` forever in phase 0, and until the ~1 year deletion delay in phase 2 and in the future. + +**Note**: this definition and the next few definitions make heavy use of repetitive computing. Production implementations are expected to appropriately use caching/memoization to avoid redoing work. + +#### `get_previous_epoch_committee_count` + +```python +def get_previous_epoch_committee_count(state: BeaconState) -> int: + previous_active_validators = get_active_validator_indices( + state.validator_registry, + state.previous_calculation_epoch, + ) + return get_epoch_committee_count(len(previous_active_validators)) +``` + +### `get_current_epoch_committee_count` + +```python +def get_current_epoch_committee_count(state: BeaconState) -> int: + current_active_validators = get_active_validator_indices( + state.validator_registry, + state.current_calculation_epoch, + ) + return get_epoch_committee_count(len(current_active_validators)) +``` + +### `get_crosslink_committees_at_slot` + +```python +def get_crosslink_committees_at_slot(state: BeaconState, + slot: SlotNumber) -> List[Tuple[List[ValidatorIndex], ShardNumber]]: + """ + Returns the list of ``(committee, shard)`` tuples for the ``slot``. + """ + epoch = slot_to_epoch(slot) + current_epoch = get_current_epoch(state) + previous_epoch = current_epoch - 1 if current_epoch > GENESIS_EPOCH else current_epoch + next_epoch = current_epoch + 1 + + assert previous_epoch <= epoch < next_epoch + + if epoch < current_epoch: + committees_per_epoch = get_previous_epoch_committee_count(state) + seed = state.previous_epoch_seed + shuffling_epoch = state.previous_calculation_epoch + shuffling_start_shard = state.previous_epoch_start_shard + else: + committees_per_epoch = get_current_epoch_committee_count(state) + seed = state.current_epoch_seed + shuffling_epoch = state.current_calculation_epoch + shuffling_start_shard = state.current_epoch_start_shard + + shuffling = get_shuffling( + seed, + state.validator_registry, + shuffling_epoch, + ) + offset = slot % EPOCH_LENGTH + committees_per_slot = committees_per_epoch // EPOCH_LENGTH + slot_start_shard = (shuffling_start_shard + committees_per_slot * offset) % SHARD_COUNT + + return [ + ( + shuffling[committees_per_slot * offset + i], + (slot_start_shard + i) % SHARD_COUNT, + ) + for i in range(committees_per_slot) + ] +``` + +**Note**: we plan to replace the shuffling algorithm with a pointwise-evaluable shuffle (see https://github.com/ethereum/eth2.0-specs/issues/323), which will allow calculation of the committees for each slot individually. + +### `get_block_root` + +```python +def get_block_root(state: BeaconState, + slot: SlotNumber) -> Bytes32: + """ + Returns the block root at a recent ``slot``. + """ + assert state.slot <= slot + LATEST_BLOCK_ROOTS_LENGTH + assert slot < state.slot + return state.latest_block_roots[slot % LATEST_BLOCK_ROOTS_LENGTH] +``` + +`get_block_root(_, s)` should always return `hash_tree_root` of the block in the beacon chain at slot `s`, and `get_crosslink_committees_at_slot(_, s)` should not change unless the [validator](#dfn-validator) registry changes. + +### `get_randao_mix` + +```python +def get_randao_mix(state: BeaconState, + epoch: EpochNumber) -> Bytes32: + """ + Returns the randao mix at a recent ``epoch``. + """ + assert get_current_epoch(state) - LATEST_RANDAO_MIXES_LENGTH < epoch <= get_current_epoch(state) + return state.latest_randao_mixes[epoch % LATEST_RANDAO_MIXES_LENGTH] +``` + +### `get_active_index_root` + +```python +def get_active_index_root(state: BeaconState, + epoch: EpochNumber) -> Bytes32: + """ + Returns the index root at a recent ``epoch``. + """ + assert get_current_epoch(state) - LATEST_INDEX_ROOTS_LENGTH < epoch <= get_current_epoch(state) + return state.latest_index_roots[epoch % LATEST_INDEX_ROOTS_LENGTH] +``` + +### `generate_seed` + +```python +def generate_seed(state: BeaconState, + epoch: EpochNumber) -> Bytes32: + """ + Generate a seed for the given ``epoch``. + """ + + return hash( + get_randao_mix(state, epoch - SEED_LOOKAHEAD) + + get_active_index_root(state, epoch) + ) +``` + +### `get_beacon_proposer_index` + +```python +def get_beacon_proposer_index(state: BeaconState, + slot: SlotNumber) -> ValidatorIndex: + """ + Returns the beacon proposer index for the ``slot``. + """ + first_committee, _ = get_crosslink_committees_at_slot(state, slot)[0] + return first_committee[slot % len(first_committee)] +``` + +### `merkle_root` + +```python +def merkle_root(values: List[Bytes32]) -> Bytes32: + """ + Merkleize ``values`` (where ``len(values)`` is a power of two) and return the Merkle root. + """ + o = [0] * len(values) + values + for i in range(len(values) - 1, 0, -1): + o[i] = hash(o[i * 2] + o[i * 2 + 1]) + return o[1] +``` + +### `get_attestation_participants` + +```python +def get_attestation_participants(state: BeaconState, + attestation_data: AttestationData, + aggregation_bitfield: bytes) -> List[ValidatorIndex]: + """ + Returns the participant indices at for the ``attestation_data`` and ``aggregation_bitfield``. + """ + + # Find the committee in the list with the desired shard + crosslink_committees = get_crosslink_committees_at_slot(state, attestation_data.slot) + + assert attestation_data.shard in [shard for _, shard in crosslink_committees] + crosslink_committee = [committee for committee, shard in crosslink_committees if shard == attestation_data.shard][0] + assert len(aggregation_bitfield) == (len(crosslink_committee) + 7) // 8 + + # Find the participating attesters in the committee + participants = [] + for i, validator_index in enumerate(crosslink_committee): + aggregation_bit = (aggregation_bitfield[i // 8] >> (7 - (i % 8))) % 2 + if aggregation_bit == 1: + participants.append(validator_index) + return participants +``` + +### `int_to_bytes1`, `int_to_bytes2`, ... + +`int_to_bytes1(x): return x.to_bytes(1, 'big')`, `int_to_bytes2(x): return x.to_bytes(2, 'big')`, and so on for all integers, particularly 1, 2, 3, 4, 8, 32, 48, 96. + +### `get_effective_balance` + +```python +def get_effective_balance(state: State, index: ValidatorIndex) -> Gwei: + """ + Returns the effective balance (also known as "balance at stake") for a ``validator`` with the given ``index``. + """ + return min(state.validator_balances[index], MAX_DEPOSIT_AMOUNT) +``` + +### `get_fork_version` + +```python +def get_fork_version(fork: Fork, + epoch: EpochNumber) -> int: + if epoch < fork.epoch: + return fork.previous_version + else: + return fork.current_version +``` + +### `get_domain` + +```python +def get_domain(fork: Fork, + epoch: EpochNumber, + domain_type: int) -> int: + return get_fork_version( + fork, + epoch, + ) * 2**32 + domain_type +``` + +### `verify_slashable_vote_data` + +```python +def verify_slashable_vote_data(state: BeaconState, vote_data: SlashableVoteData) -> bool: + if len(vote_data.custody_bit_0_indices) + len(vote_data.custody_bit_1_indices) > MAX_CASPER_VOTES: + return False + + return bls_verify_multiple( + pubkeys=[ + bls_aggregate_pubkeys([state.validator_registry[i].pubkey for i in vote_data.custody_bit_0_indices]), + bls_aggregate_pubkeys([state.validator_registry[i].pubkey for i in vote_data.custody_bit_1_indices]), + ], + messages=[ + hash_tree_root(AttestationDataAndCustodyBit(vote_data.data, False)), + hash_tree_root(AttestationDataAndCustodyBit(vote_data.data, True)), + ], + signature=vote_data.aggregate_signature, + domain=get_domain( + state.fork, + slot_to_epoch(vote_data.data.slot), + DOMAIN_ATTESTATION, + ), + ) +``` + +### `is_double_vote` + +```python +def is_double_vote(attestation_data_1: AttestationData, + attestation_data_2: AttestationData) -> bool + """ + Assumes ``attestation_data_1`` is distinct from ``attestation_data_2``. + Returns True if the provided ``AttestationData`` are slashable + due to a 'double vote'. + """ + target_epoch_1 = slot_to_epoch(attestation_data_1.slot) + target_epoch_2 = slot_to_epoch(attestation_data_2.slot) + return target_epoch_1 == target_epoch_2 +``` + +### `is_surround_vote` + +```python +def is_surround_vote(attestation_data_1: AttestationData, + attestation_data_2: AttestationData) -> bool: + """ + Assumes ``attestation_data_1`` is distinct from ``attestation_data_2``. + Returns True if the provided ``AttestationData`` are slashable + due to a 'surround vote'. + Note: parameter order matters as this function only checks + that ``attestation_data_1`` surrounds ``attestation_data_2``. + """ + source_epoch_1 = attestation_data_1.justified_epoch + source_epoch_2 = attestation_data_2.justified_epoch + target_epoch_1 = slot_to_epoch(attestation_data_1.slot) + target_epoch_2 = slot_to_epoch(attestation_data_2.slot) + return ( + (source_epoch_1 < source_epoch_2) and + (source_epoch_2 + 1 == target_epoch_2) and + (target_epoch_2 < target_epoch_1) + ) +``` + +### `integer_squareroot` + +```python +def integer_squareroot(n: int) -> int: + """ + The largest integer ``x`` such that ``x**2`` is less than or equal to ``n``. + """ + assert n >= 0 + x = n + y = (x + 1) // 2 + while y < x: + x = y + y = (x + n // x) // 2 + return x +``` + +### `get_entry_exit_effect_epoch` + +```python +def get_entry_exit_effect_epoch(epoch: EpochNumber) -> EpochNumber: + """ + An entry or exit triggered in the ``epoch`` given by the input takes effect at + the epoch given by the output. + """ + return epoch + 1 + ENTRY_EXIT_DELAY +``` + +### `bls_verify` + +`bls_verify` is a function for verifying a BLS signature, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_verify). + +### `bls_verify_multiple` + +`bls_verify_multiple` is a function for verifying a BLS signature constructed from multiple messages, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_verify_multiple). + +### `bls_aggregate_pubkeys` + +`bls_aggregate_pubkeys` is a function for aggregating multiple BLS public keys into a single aggregate key, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_aggregate_pubkeys). + + +### `validate_proof_of_possession` + +```python +def validate_proof_of_possession(state: BeaconState, + pubkey: BLSPubkey, + proof_of_possession: BLSSignature, + withdrawal_credentials: Bytes32) -> bool: + proof_of_possession_data = DepositInput( + pubkey=pubkey, + withdrawal_credentials=withdrawal_credentials, + proof_of_possession=EMPTY_SIGNATURE, + ) + + return bls_verify( + pubkey=pubkey, + message=hash_tree_root(proof_of_possession_data), + signature=proof_of_possession, + domain=get_domain( + state.fork, + get_current_epoch(state), + DOMAIN_DEPOSIT, + ) + ) +``` + +### `process_deposit` + +Used to add a [validator](#dfn-validator) or top up an existing [validator](#dfn-validator)'s balance by some `deposit` amount: + +```python +def process_deposit(state: BeaconState, + pubkey: BLSPubkey, + amount: Gwei, + proof_of_possession: BLSSignature, + withdrawal_credentials: Bytes32) -> None: + """ + Process a deposit from Ethereum 1.0. + Note that this function mutates ``state``. + """ + # Validate the given `proof_of_possession` + assert validate_proof_of_possession( + state, + pubkey, + proof_of_possession, + withdrawal_credentials, + ) + + validator_pubkeys = [v.pubkey for v in state.validator_registry] + + if pubkey not in validator_pubkeys: + # Add new validator + validator = Validator( + pubkey=pubkey, + withdrawal_credentials=withdrawal_credentials, + activation_epoch=FAR_FUTURE_EPOCH, + exit_epoch=FAR_FUTURE_EPOCH, + withdrawal_epoch=FAR_FUTURE_EPOCH, + penalized_epoch=FAR_FUTURE_EPOCH, + exit_count=0, + status_flags=0, + latest_custody_reseed_slot=GENESIS_SLOT, + penultimate_custody_reseed_slot=GENESIS_SLOT, + ) + + # Note: In phase 2 registry indices that have been withdrawn for a long time will be recycled. + state.validator_registry.append(validator) + state.validator_balances.append(amount) + else: + # Increase balance by deposit amount + index = validator_pubkeys.index(pubkey) + assert state.validator_registry[index].withdrawal_credentials == withdrawal_credentials + + state.validator_balances[index] += amount +``` + +### Routines for updating validator status + +Note: All functions in this section mutate `state`. + +#### `activate_validator` + +```python +def activate_validator(state: BeaconState, index: ValidatorIndex, genesis: bool) -> None: + validator = state.validator_registry[index] + + validator.activation_epoch = GENESIS_EPOCH if genesis else get_entry_exit_effect_epoch(get_current_epoch(state)) +``` + +#### `initiate_validator_exit` + +```python +def initiate_validator_exit(state: BeaconState, index: ValidatorIndex) -> None: + validator = state.validator_registry[index] + validator.status_flags |= INITIATED_EXIT +``` + +#### `exit_validator` + +```python +def exit_validator(state: BeaconState, index: ValidatorIndex) -> None: + validator = state.validator_registry[index] + + # The following updates only occur if not previous exited + if validator.exit_epoch <= get_entry_exit_effect_epoch(get_current_epoch(state)): + return + + validator.exit_epoch = get_entry_exit_effect_epoch(get_current_epoch(state)) + + state.validator_registry_exit_count += 1 + validator.exit_count = state.validator_registry_exit_count +``` + +#### `penalize_validator` + +```python +def penalize_validator(state: BeaconState, index: ValidatorIndex) -> None: + exit_validator(state, index) + validator = state.validator_registry[index] + state.latest_penalized_balances[get_current_epoch(state) % LATEST_PENALIZED_EXIT_LENGTH] += get_effective_balance(state, index) + + whistleblower_index = get_beacon_proposer_index(state, state.slot) + whistleblower_reward = get_effective_balance(state, index) // WHISTLEBLOWER_REWARD_QUOTIENT + state.validator_balances[whistleblower_index] += whistleblower_reward + state.validator_balances[index] -= whistleblower_reward + validator.penalized_epoch = get_current_epoch(state) +``` + +#### `prepare_validator_for_withdrawal` + +```python +def prepare_validator_for_withdrawal(state: BeaconState, index: ValidatorIndex) -> None: + validator = state.validator_registry[index] + validator.status_flags |= WITHDRAWABLE +``` + ## Ethereum 1.0 deposit contract The initial deployment phases of Ethereum 2.0 are implemented without consensus changes to Ethereum 1.0. A deposit contract at address `DEPOSIT_CONTRACT_ADDRESS` is added to Ethereum 1.0 for deposits of ETH to the beacon chain. Validator balances will be withdrawable to the shards in phase 2, i.e. when the EVM2.0 is deployed and the shards have state. @@ -715,553 +1331,7 @@ def get_branch(leaf: uint256) -> bytes32[32]: # size is DEPOSIT_CONTRACT_TREE_DE return branch ``` -## Beacon chain processing - -The beacon chain is the system chain for Ethereum 2.0. The main responsibilities of the beacon chain are: - -* Store and maintain the registry of [validators](#dfn-validator) -* Process crosslinks (see above) -* Process its per-slot consensus, as well as the finality gadget - -Processing the beacon chain is similar to processing the Ethereum 1.0 chain. Clients download and process blocks, and maintain a view of what is the current "canonical chain", terminating at the current "head". However, because of the beacon chain's relationship with Ethereum 1.0, and because it is a proof-of-stake chain, there are differences. - -For a beacon chain block, `block`, to be processed by a node, the following conditions must be met: - -* The parent block with root `block.parent_root` has been processed and accepted. -* The node has processed its `state` up to slot, `block.slot - 1`. -* An Ethereum 1.0 block pointed to by the `state.latest_eth1_data.block_hash` has been processed and accepted. -* The node's local clock time is greater than or equal to `state.genesis_time + block.slot * SLOT_DURATION`. - -If these conditions are not met, the client should delay processing the beacon block until the conditions are all satisfied. - -Beacon block production is significantly different because of the proof of stake mechanism. A client simply checks what it thinks is the canonical chain when it should create a block, and looks up what its slot number is; when the slot arrives, it either proposes or attests to a block as required. Note that this requires each node to have a clock that is roughly (i.e. within `SLOT_DURATION` seconds) synchronized with the other nodes. - -### Beacon chain fork choice rule - -The beacon chain fork choice rule is a hybrid that combines justification and finality with Latest Message Driven (LMD) Greediest Heaviest Observed SubTree (GHOST). At any point in time a [validator](#dfn-validator) `v` subjectively calculates the beacon chain head as follows. - -* Abstractly define `Store` as the type of storage object for the chain data and `store` be the set of attestations and blocks that the [validator](#dfn-validator) `v` has observed and verified (in particular, block ancestors must be recursively verified). Attestations not yet included in any chain are still included in `store`. -* Let `finalized_head` be the finalized block with the highest epoch. (A block `B` is finalized if there is a descendant of `B` in `store` the processing of which sets `B` as finalized.) -* Let `justified_head` be the descendant of `finalized_head` with the highest epoch that has been justified for at least 1 epoch. (A block `B` is justified if there is a descendant of `B` in `store` the processing of which sets `B` as justified.) If no such descendant exists set `justified_head` to `finalized_head`. -* Let `get_ancestor(store: Store, block: BeaconBlock, slot: SlotNumber) -> BeaconBlock` be the ancestor of `block` with slot number `slot`. The `get_ancestor` function can be defined recursively as `def get_ancestor(store: Store, block: BeaconBlock, slot: SlotNumber) -> BeaconBlock: return block if block.slot == slot else get_ancestor(store, store.get_parent(block), slot)`. -* Let `get_latest_attestation(store: Store, validator: Validator) -> Attestation` be the attestation with the highest slot number in `store` from `validator`. If several such attestations exist, use the one the [validator](#dfn-validator) `v` observed first. -* Let `get_latest_attestation_target(store: Store, validator: Validator) -> BeaconBlock` be the target block in the attestation `get_latest_attestation(store, validator)`. -* Let `get_children(store: Store, block: BeaconBlock) -> List[BeaconBlock]` returns the child blocks of the given `block`. -* Let `justified_head_state` be the resulting `BeaconState` object from processing the chain up to the `justified_head`. -* The `head` is `lmd_ghost(store, justified_head_state, justified_head)` where the function `lmd_ghost` is defined below. Note that the implementation below is suboptimal; there are implementations that compute the head in time logarithmic in slot count. - -```python -def lmd_ghost(store: Store, start_state: BeaconState, start_block: BeaconBlock) -> BeaconBlock: - validators = start_state.validator_registry - active_validators = [ - validators[i] - for i in get_active_validator_indices(validators, start_state.slot) - ] - attestation_targets = [ - get_latest_attestation_target(store, validator) - for validator in active_validators - ] - - def get_vote_count(block: BeaconBlock) -> int: - return len([ - target - for target in attestation_targets - if get_ancestor(store, target, block.slot) == block - ]) - - head = start_block - while 1: - children = get_children(store, head) - if len(children) == 0: - return head - head = max(children, key=get_vote_count) -``` - -## Beacon chain state transition function - -We now define the state transition function. At a high level the state transition is made up of three parts: - -1. The per-slot transitions, which happens every slot. -2. The per-block transitions, which happens at every block. -3. The per-epoch transitions, which happens at every epoch boundary (i.e. `(state.slot + 1) % EPOCH_LENGTH == 0`). - -The per-slot transitions focus on the slot counter and block roots records updates; the per-block transitions generally focus on verifying aggregate signatures and saving temporary records relating to the per-block activity in the `BeaconState`; the per-epoch transitions focus on the [validator](#dfn-validator) registry, including adjusting balances and activating and exiting [validators](#dfn-validator), as well as processing crosslinks and managing block justification/finalization. - -### Helper functions - -Note: The definitions below are for specification purposes and are not necessarily optimal implementations. - -#### `hash` - -The hash function is denoted by `hash`. In Phase 0 the beacon chain is deployed with the same hash function as Ethereum 1.0, i.e. Keccak-256 (also incorrectly known as SHA3). - -Note: We aim to migrate to a S[T/N]ARK-friendly hash function in a future Ethereum 2.0 deployment phase. - -#### `hash_tree_root` - -`def hash_tree_root(object: SSZSerializable) -> Bytes32` is a function for hashing objects into a single root utilizing a hash tree structure. `hash_tree_root` is defined in the [SimpleSerialize spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/simple-serialize.md#tree-hash). - -#### `slot_to_epoch` - -```python -def slot_to_epoch(slot: SlotNumber) -> EpochNumber: - return slot // EPOCH_LENGTH -``` - -#### `get_current_epoch` - -```python -def get_current_epoch(state: BeaconState) -> EpochNumber: - return slot_to_epoch(state.slot) -``` - -#### `get_epoch_start_slot` - -```python -def get_epoch_start_slot(epoch: EpochNumber) -> SlotNumber: - return epoch * EPOCH_LENGTH -``` - -#### `is_active_validator` -```python -def is_active_validator(validator: Validator, epoch: EpochNumber) -> bool: - """ - Checks if ``validator`` is active. - """ - return validator.activation_epoch <= epoch < validator.exit_epoch -``` - -#### `get_active_validator_indices` - -```python -def get_active_validator_indices(validators: List[Validator], epoch: EpochNumber) -> List[ValidatorIndex]: - """ - Gets indices of active validators from ``validators``. - """ - return [i for i, v in enumerate(validators) if is_active_validator(v, epoch)] -``` - -#### `shuffle` - -```python -def shuffle(values: List[Any], seed: Bytes32) -> List[Any]: - """ - Returns the shuffled ``values`` with ``seed`` as entropy. - """ - values_count = len(values) - - # Entropy is consumed from the seed in 3-byte (24 bit) chunks. - rand_bytes = 3 - # The highest possible result of the RNG. - rand_max = 2 ** (rand_bytes * 8) - 1 - - # The range of the RNG places an upper-bound on the size of the list that - # may be shuffled. It is a logic error to supply an oversized list. - assert values_count < rand_max - - output = [x for x in values] - source = seed - index = 0 - while index < values_count - 1: - # Re-hash the `source` to obtain a new pattern of bytes. - source = hash(source) - # Iterate through the `source` bytes in 3-byte chunks. - for position in range(0, 32 - (32 % rand_bytes), rand_bytes): - # Determine the number of indices remaining in `values` and exit - # once the last index is reached. - remaining = values_count - index - if remaining == 1: - break - - # Read 3-bytes of `source` as a 24-bit big-endian integer. - sample_from_source = int.from_bytes(source[position:position + rand_bytes], 'big') - - # Sample values greater than or equal to `sample_max` will cause - # modulo bias when mapped into the `remaining` range. - sample_max = rand_max - rand_max % remaining - - # Perform a swap if the consumed entropy will not cause modulo bias. - if sample_from_source < sample_max: - # Select a replacement index for the current index. - replacement_position = (sample_from_source % remaining) + index - # Swap the current index with the replacement index. - output[index], output[replacement_position] = output[replacement_position], output[index] - index += 1 - else: - # The sample causes modulo bias. A new sample should be read. - pass - - return output -``` - -#### `split` - -```python -def split(values: List[Any], split_count: int) -> List[List[Any]]: - """ - Splits ``values`` into ``split_count`` pieces. - """ - list_length = len(values) - return [ - values[(list_length * i // split_count): (list_length * (i + 1) // split_count)] - for i in range(split_count) - ] -``` - -#### `get_epoch_committee_count` - -```python -def get_epoch_committee_count(active_validator_count: int) -> int: - return max( - 1, - min( - SHARD_COUNT // EPOCH_LENGTH, - active_validator_count // EPOCH_LENGTH // TARGET_COMMITTEE_SIZE, - ) - ) * EPOCH_LENGTH -``` - -#### `get_shuffling` - -```python -def get_shuffling(seed: Bytes32, - validators: List[Validator], - epoch: EpochNumber) -> List[List[ValidatorIndex]] - """ - Shuffles ``validators`` into crosslink committees seeded by ``seed`` and ``epoch``. - Returns a list of ``committees_per_epoch`` committees where each - committee is itself a list of validator indices. - """ - - active_validator_indices = get_active_validator_indices(validators, epoch) - - committees_per_epoch = get_epoch_committee_count(len(active_validator_indices)) - - # Shuffle - seed = xor(seed, int_to_bytes32(epoch)) - shuffled_active_validator_indices = shuffle(active_validator_indices, seed) - - # Split the shuffled list into committees_per_epoch pieces - return split(shuffled_active_validator_indices, committees_per_epoch) -``` - -**Invariant**: if `get_shuffling(seed, validators, epoch)` returns some value `x` for some `epoch <= get_current_epoch(state) + ENTRY_EXIT_DELAY`, it should return the same value `x` for the same `seed` and `epoch` and possible future modifications of `validators` forever in phase 0, and until the ~1 year deletion delay in phase 2 and in the future. - -**Note**: this definition and the next few definitions make heavy use of repetitive computing. Production implementations are expected to appropriately use caching/memoization to avoid redoing work. - -#### `get_previous_epoch_committee_count` - -```python -def get_previous_epoch_committee_count(state: BeaconState) -> int: - previous_active_validators = get_active_validator_indices( - state.validator_registry, - state.previous_calculation_epoch, - ) - return get_epoch_committee_count(len(previous_active_validators)) -``` - -#### `get_current_epoch_committee_count` - -```python -def get_current_epoch_committee_count(state: BeaconState) -> int: - current_active_validators = get_active_validator_indices( - state.validator_registry, - state.current_calculation_epoch, - ) - return get_epoch_committee_count(len(current_active_validators)) -``` - -#### `get_crosslink_committees_at_slot` - -```python -def get_crosslink_committees_at_slot(state: BeaconState, - slot: SlotNumber) -> List[Tuple[List[ValidatorIndex], ShardNumber]]: - """ - Returns the list of ``(committee, shard)`` tuples for the ``slot``. - """ - epoch = slot_to_epoch(slot) - current_epoch = get_current_epoch(state) - previous_epoch = current_epoch - 1 if current_epoch > GENESIS_EPOCH else current_epoch - next_epoch = current_epoch + 1 - - assert previous_epoch <= epoch < next_epoch - - if epoch < current_epoch: - committees_per_epoch = get_previous_epoch_committee_count(state) - seed = state.previous_epoch_seed - shuffling_epoch = state.previous_calculation_epoch - shuffling_start_shard = state.previous_epoch_start_shard - else: - committees_per_epoch = get_current_epoch_committee_count(state) - seed = state.current_epoch_seed - shuffling_epoch = state.current_calculation_epoch - shuffling_start_shard = state.current_epoch_start_shard - - shuffling = get_shuffling( - seed, - state.validator_registry, - shuffling_epoch, - ) - offset = slot % EPOCH_LENGTH - committees_per_slot = committees_per_epoch // EPOCH_LENGTH - slot_start_shard = (shuffling_start_shard + committees_per_slot * offset) % SHARD_COUNT - - return [ - ( - shuffling[committees_per_slot * offset + i], - (slot_start_shard + i) % SHARD_COUNT, - ) - for i in range(committees_per_slot) - ] -``` - -**Note**: we plan to replace the shuffling algorithm with a pointwise-evaluable shuffle (see https://github.com/ethereum/eth2.0-specs/issues/323), which will allow calculation of the committees for each slot individually. - -#### `get_block_root` - -```python -def get_block_root(state: BeaconState, - slot: SlotNumber) -> Bytes32: - """ - Returns the block root at a recent ``slot``. - """ - assert state.slot <= slot + LATEST_BLOCK_ROOTS_LENGTH - assert slot < state.slot - return state.latest_block_roots[slot % LATEST_BLOCK_ROOTS_LENGTH] -``` - -`get_block_root(_, s)` should always return `hash_tree_root` of the block in the beacon chain at slot `s`, and `get_crosslink_committees_at_slot(_, s)` should not change unless the [validator](#dfn-validator) registry changes. - -#### `get_randao_mix` - -```python -def get_randao_mix(state: BeaconState, - epoch: EpochNumber) -> Bytes32: - """ - Returns the randao mix at a recent ``epoch``. - """ - assert get_current_epoch(state) - LATEST_RANDAO_MIXES_LENGTH < epoch <= get_current_epoch(state) - return state.latest_randao_mixes[epoch % LATEST_RANDAO_MIXES_LENGTH] -``` - -#### `get_active_index_root` - -```python -def get_active_index_root(state: BeaconState, - epoch: EpochNumber) -> Bytes32: - """ - Returns the index root at a recent ``epoch``. - """ - assert get_current_epoch(state) - LATEST_INDEX_ROOTS_LENGTH < epoch <= get_current_epoch(state) - return state.latest_index_roots[epoch % LATEST_INDEX_ROOTS_LENGTH] -``` - -#### `generate_seed` - -```python -def generate_seed(state: BeaconState, - epoch: EpochNumber) -> Bytes32: - """ - Generate a seed for the given ``epoch``. - """ - - return hash( - get_randao_mix(state, epoch - SEED_LOOKAHEAD) + - get_active_index_root(state, epoch) - ) -``` - -#### `get_beacon_proposer_index` - -```python -def get_beacon_proposer_index(state: BeaconState, - slot: SlotNumber) -> ValidatorIndex: - """ - Returns the beacon proposer index for the ``slot``. - """ - first_committee, _ = get_crosslink_committees_at_slot(state, slot)[0] - return first_committee[slot % len(first_committee)] -``` - -#### `merkle_root` - -```python -def merkle_root(values: List[Bytes32]) -> Bytes32: - """ - Merkleize ``values`` (where ``len(values)`` is a power of two) and return the Merkle root. - """ - o = [0] * len(values) + values - for i in range(len(values) - 1, 0, -1): - o[i] = hash(o[i * 2] + o[i * 2 + 1]) - return o[1] -``` - -#### `get_attestation_participants` - -```python -def get_attestation_participants(state: BeaconState, - attestation_data: AttestationData, - aggregation_bitfield: bytes) -> List[ValidatorIndex]: - """ - Returns the participant indices at for the ``attestation_data`` and ``aggregation_bitfield``. - """ - - # Find the committee in the list with the desired shard - crosslink_committees = get_crosslink_committees_at_slot(state, attestation_data.slot) - - assert attestation_data.shard in [shard for _, shard in crosslink_committees] - crosslink_committee = [committee for committee, shard in crosslink_committees if shard == attestation_data.shard][0] - assert len(aggregation_bitfield) == (len(crosslink_committee) + 7) // 8 - - # Find the participating attesters in the committee - participants = [] - for i, validator_index in enumerate(crosslink_committee): - aggregation_bit = (aggregation_bitfield[i // 8] >> (7 - (i % 8))) % 2 - if aggregation_bit == 1: - participants.append(validator_index) - return participants -``` - -#### `int_to_bytes1`, `int_to_bytes2`, ... - -`int_to_bytes1(x): return x.to_bytes(1, 'big')`, `int_to_bytes2(x): return x.to_bytes(2, 'big')`, and so on for all integers, particularly 1, 2, 3, 4, 8, 32, 48, 96. - -#### `get_effective_balance` - -```python -def get_effective_balance(state: State, index: ValidatorIndex) -> Gwei: - """ - Returns the effective balance (also known as "balance at stake") for a ``validator`` with the given ``index``. - """ - return min(state.validator_balances[index], MAX_DEPOSIT_AMOUNT) -``` - -#### `get_fork_version` - -```python -def get_fork_version(fork: Fork, - epoch: EpochNumber) -> int: - if epoch < fork.epoch: - return fork.previous_version - else: - return fork.current_version -``` - -#### `get_domain` - -```python -def get_domain(fork: Fork, - epoch: EpochNumber, - domain_type: int) -> int: - return get_fork_version( - fork, - epoch, - ) * 2**32 + domain_type -``` - -#### `verify_slashable_vote_data` - -```python -def verify_slashable_vote_data(state: BeaconState, vote_data: SlashableVoteData) -> bool: - if len(vote_data.custody_bit_0_indices) + len(vote_data.custody_bit_1_indices) > MAX_CASPER_VOTES: - return False - - return bls_verify_multiple( - pubkeys=[ - bls_aggregate_pubkeys([state.validator_registry[i].pubkey for i in vote_data.custody_bit_0_indices]), - bls_aggregate_pubkeys([state.validator_registry[i].pubkey for i in vote_data.custody_bit_1_indices]), - ], - messages=[ - hash_tree_root(AttestationDataAndCustodyBit(vote_data.data, False)), - hash_tree_root(AttestationDataAndCustodyBit(vote_data.data, True)), - ], - signature=vote_data.aggregate_signature, - domain=get_domain( - state.fork, - slot_to_epoch(vote_data.data.slot), - DOMAIN_ATTESTATION, - ), - ) -``` - -#### `is_double_vote` - -```python -def is_double_vote(attestation_data_1: AttestationData, - attestation_data_2: AttestationData) -> bool - """ - Assumes ``attestation_data_1`` is distinct from ``attestation_data_2``. - Returns True if the provided ``AttestationData`` are slashable - due to a 'double vote'. - """ - target_epoch_1 = slot_to_epoch(attestation_data_1.slot) - target_epoch_2 = slot_to_epoch(attestation_data_2.slot) - return target_epoch_1 == target_epoch_2 -``` - -#### `is_surround_vote` - -```python -def is_surround_vote(attestation_data_1: AttestationData, - attestation_data_2: AttestationData) -> bool: - """ - Assumes ``attestation_data_1`` is distinct from ``attestation_data_2``. - Returns True if the provided ``AttestationData`` are slashable - due to a 'surround vote'. - Note: parameter order matters as this function only checks - that ``attestation_data_1`` surrounds ``attestation_data_2``. - """ - source_epoch_1 = attestation_data_1.justified_epoch - source_epoch_2 = attestation_data_2.justified_epoch - target_epoch_1 = slot_to_epoch(attestation_data_1.slot) - target_epoch_2 = slot_to_epoch(attestation_data_2.slot) - return ( - (source_epoch_1 < source_epoch_2) and - (source_epoch_2 + 1 == target_epoch_2) and - (target_epoch_2 < target_epoch_1) - ) -``` - -#### `integer_squareroot` - -```python -def integer_squareroot(n: int) -> int: - """ - The largest integer ``x`` such that ``x**2`` is less than or equal to ``n``. - """ - assert n >= 0 - x = n - y = (x + 1) // 2 - while y < x: - x = y - y = (x + n // x) // 2 - return x -``` - -#### `get_entry_exit_effect_epoch` - -```python -def get_entry_exit_effect_epoch(epoch: EpochNumber) -> EpochNumber: - """ - An entry or exit triggered in the ``epoch`` given by the input takes effect at - the epoch given by the output. - """ - return epoch + 1 + ENTRY_EXIT_DELAY -``` - -#### `bls_verify` - -`bls_verify` is a function for verifying a BLS signature, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_verify). - -#### `bls_verify_multiple` - -`bls_verify_multiple` is a function for verifying a BLS signature constructed from multiple messages, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_verify_multiple). - -#### `bls_aggregate_pubkeys` - -`bls_aggregate_pubkeys` is a function for aggregating multiple BLS public keys into a single aggregate key, defined in the [BLS Signature spec](https://github.com/ethereum/eth2.0-specs/blob/master/specs/bls_signature.md#bls_aggregate_pubkeys). - -### On startup +## On startup A valid block with slot `GENESIS_SLOT` (a "genesis block") has the following values. Other validity rules (e.g. requiring a signature) do not apply. @@ -1364,173 +1434,121 @@ def get_initial_beacon_state(initial_validator_deposits: List[Deposit], return state ``` -### Routine for processing deposits +## Beacon chain processing -First, a helper function: +The beacon chain is the system chain for Ethereum 2.0. The main responsibilities of the beacon chain are: + +* Store and maintain the registry of [validators](#dfn-validator) +* Process crosslinks (see above) +* Process its per-block consensus, as well as the finality gadget + +Processing the beacon chain is similar to processing the Ethereum 1.0 chain. Clients download and process blocks, and maintain a view of what is the current "canonical chain", terminating at the current "head". However, because of the beacon chain's relationship with Ethereum 1.0, and because it is a proof-of-stake chain, there are differences. + +For a beacon chain block, `block`, to be processed by a node, the following conditions must be met: + +* The parent block with root `block.parent_root` has been processed and accepted. +* An Ethereum 1.0 block pointed to by the `state.latest_eth1_data.block_hash` has been processed and accepted. +* The node's local clock time is greater than or equal to `state.genesis_time + block.slot * SLOT_DURATION`. + +If these conditions are not met, the client should delay processing the beacon block until the conditions are all satisfied. + +Beacon block production is significantly different because of the proof of stake mechanism. A client simply checks what it thinks is the canonical chain when it should create a block, and looks up what its slot number is; when the slot arrives, it either proposes or attests to a block as required. Note that this requires each node to have a clock that is roughly (i.e. within `SLOT_DURATION` seconds) synchronized with the other nodes. + +### Beacon chain fork choice rule + +The beacon chain fork choice rule is a hybrid that combines justification and finality with Latest Message Driven (LMD) Greediest Heaviest Observed SubTree (GHOST). At any point in time a [validator](#dfn-validator) `v` subjectively calculates the beacon chain head as follows. + +* Abstractly define `Store` as the type of storage object for the chain data and `store` be the set of attestations and blocks that the [validator](#dfn-validator) `v` has observed and verified (in particular, block ancestors must be recursively verified). Attestations not yet included in any chain are still included in `store`. +* Let `finalized_head` be the finalized block with the highest epoch. (A block `B` is finalized if there is a descendant of `B` in `store` the processing of which sets `B` as finalized.) +* Let `justified_head` be the descendant of `finalized_head` with the highest epoch that has been justified for at least 1 epoch. (A block `B` is justified if there is a descendant of `B` in `store` the processing of which sets `B` as justified.) If no such descendant exists set `justified_head` to `finalized_head`. +* Let `get_ancestor(store: Store, block: BeaconBlock, slot: SlotNumber) -> BeaconBlock` be the ancestor of `block` with slot number `slot`. The `get_ancestor` function can be defined recursively as `def get_ancestor(store: Store, block: BeaconBlock, slot: SlotNumber) -> BeaconBlock: return block if block.slot == slot else get_ancestor(store, store.get_parent(block), slot)`. +* Let `get_latest_attestation(store: Store, validator: Validator) -> Attestation` be the attestation with the highest slot number in `store` from `validator`. If several such attestations exist, use the one the [validator](#dfn-validator) `v` observed first. +* Let `get_latest_attestation_target(store: Store, validator: Validator) -> BeaconBlock` be the target block in the attestation `get_latest_attestation(store, validator)`. +* Let `get_children(store: Store, block: BeaconBlock) -> List[BeaconBlock]` returns the child blocks of the given `block`. +* Let `justified_head_state` be the resulting `BeaconState` object from processing the chain up to the `justified_head`. +* The `head` is `lmd_ghost(store, justified_head_state, justified_head)` where the function `lmd_ghost` is defined below. Note that the implementation below is suboptimal; there are implementations that compute the head in time logarithmic in slot count. ```python -def validate_proof_of_possession(state: BeaconState, - pubkey: BLSPubkey, - proof_of_possession: BLSSignature, - withdrawal_credentials: Bytes32) -> bool: - proof_of_possession_data = DepositInput( - pubkey=pubkey, - withdrawal_credentials=withdrawal_credentials, - proof_of_possession=EMPTY_SIGNATURE, - ) +def lmd_ghost(store: Store, start_state: BeaconState, start_block: BeaconBlock) -> BeaconBlock: + validators = start_state.validator_registry + active_validators = [ + validators[i] + for i in get_active_validator_indices(validators, start_state.slot) + ] + attestation_targets = [ + get_latest_attestation_target(store, validator) + for validator in active_validators + ] - return bls_verify( - pubkey=pubkey, - message=hash_tree_root(proof_of_possession_data), - signature=proof_of_possession, - domain=get_domain( - state.fork, - get_current_epoch(state), - DOMAIN_DEPOSIT, - ) - ) + def get_vote_count(block: BeaconBlock) -> int: + return len([ + target + for target in attestation_targets + if get_ancestor(store, target, block.slot) == block + ]) + + head = start_block + while 1: + children = get_children(store, head) + if len(children) == 0: + return head + head = max(children, key=get_vote_count) ``` -Now, to add a [validator](#dfn-validator) or top up an existing [validator](#dfn-validator)'s balance by some `deposit` amount: +## Beacon chain state transition function -```python -def process_deposit(state: BeaconState, - pubkey: BLSPubkey, - amount: Gwei, - proof_of_possession: BLSSignature, - withdrawal_credentials: Bytes32) -> None: - """ - Process a deposit from Ethereum 1.0. - Note that this function mutates ``state``. - """ - # Validate the given `proof_of_possession` - assert validate_proof_of_possession( - state, - pubkey, - proof_of_possession, - withdrawal_credentials, - ) +We now define the state transition function. This is a parent to child block transition. At a high level the state transition is made up of three parts: - validator_pubkeys = [v.pubkey for v in state.validator_registry] +1. The per-slot transitions, which happens every slot. +2. The per-block transitions, which happens at every block. +3. The per-epoch transitions, which happens at every epoch boundary (i.e. `(state.slot + 1) % EPOCH_LENGTH == 0`). - if pubkey not in validator_pubkeys: - # Add new validator - validator = Validator( - pubkey=pubkey, - withdrawal_credentials=withdrawal_credentials, - activation_epoch=FAR_FUTURE_EPOCH, - exit_epoch=FAR_FUTURE_EPOCH, - withdrawal_epoch=FAR_FUTURE_EPOCH, - penalized_epoch=FAR_FUTURE_EPOCH, - exit_count=0, - status_flags=0, - latest_custody_reseed_slot=GENESIS_SLOT, - penultimate_custody_reseed_slot=GENESIS_SLOT, - ) +The per-slot transitions focus on the slot counter and block roots records updates; the per-block transitions generally focus on verifying aggregate signatures and saving temporary records relating to the per-block activity in the `BeaconState`; the per-epoch transitions focus on the [validator](#dfn-validator) registry, including adjusting balances and activating and exiting [validators](#dfn-validator), as well as processing crosslinks and managing block justification/finalization. - # Note: In phase 2 registry indices that have been withdrawn for a long time will be recycled. - state.validator_registry.append(validator) - state.validator_balances.append(amount) - else: - # Increase balance by deposit amount - index = validator_pubkeys.index(pubkey) - assert state.validator_registry[index].withdrawal_credentials == withdrawal_credentials +_Note_: If there are skipped slots between a block and its parent block, run the steps in the [per-slot](#per-slot-processing) and [per-epoch](#per-epoch-processing) sections once for each skipped slot and then once for the slot containing the new block. - state.validator_balances[index] += amount -``` +### Per-slot processing -### Routines for updating validator status +Below are the processing steps that happen at every slot. -Note: All functions in this section mutate `state`. - -```python -def activate_validator(state: BeaconState, index: ValidatorIndex, genesis: bool) -> None: - validator = state.validator_registry[index] - - validator.activation_epoch = GENESIS_EPOCH if genesis else get_entry_exit_effect_epoch(get_current_epoch(state)) -``` - -```python -def initiate_validator_exit(state: BeaconState, index: ValidatorIndex) -> None: - validator = state.validator_registry[index] - validator.status_flags |= INITIATED_EXIT -``` - -```python -def exit_validator(state: BeaconState, index: ValidatorIndex) -> None: - validator = state.validator_registry[index] - - # The following updates only occur if not previous exited - if validator.exit_epoch <= get_entry_exit_effect_epoch(get_current_epoch(state)): - return - - validator.exit_epoch = get_entry_exit_effect_epoch(get_current_epoch(state)) - - state.validator_registry_exit_count += 1 - validator.exit_count = state.validator_registry_exit_count -``` - -```python -def penalize_validator(state: BeaconState, index: ValidatorIndex) -> None: - exit_validator(state, index) - validator = state.validator_registry[index] - state.latest_penalized_balances[get_current_epoch(state) % LATEST_PENALIZED_EXIT_LENGTH] += get_effective_balance(state, index) - - whistleblower_index = get_beacon_proposer_index(state, state.slot) - whistleblower_reward = get_effective_balance(state, index) // WHISTLEBLOWER_REWARD_QUOTIENT - state.validator_balances[whistleblower_index] += whistleblower_reward - state.validator_balances[index] -= whistleblower_reward - validator.penalized_epoch = get_current_epoch(state) -``` - -```python -def prepare_validator_for_withdrawal(state: BeaconState, index: ValidatorIndex) -> None: - validator = state.validator_registry[index] - validator.status_flags |= WITHDRAWABLE -``` - -## Per-slot processing - -Below are the processing steps that happen at every slot. If there are skipped slots between a block and its parent block, run the steps in this section once for each skipped slot and then once for the slot containing the new block. - -### Slot +#### Slot * Set `state.slot += 1`. -### Block roots +#### Block roots * Let `previous_block_root` be the `tree_hash_root` of the previous beacon block processed in the chain. * Set `state.latest_block_roots[(state.slot - 1) % LATEST_BLOCK_ROOTS_LENGTH] = previous_block_root`. * If `state.slot % LATEST_BLOCK_ROOTS_LENGTH == 0` append `merkle_root(state.latest_block_roots)` to `state.batched_block_roots`. -## Per-block processing +### Per-block processing Below are the processing steps that happen at every `block`. -### Slot +#### Slot * Verify that `block.slot == state.slot`. -### Proposer signature +#### Proposer signature * Let `block_without_signature_root` be the `hash_tree_root` of `block` where `block.signature` is set to `EMPTY_SIGNATURE`. * Let `proposal_root = hash_tree_root(ProposalSignedData(state.slot, BEACON_CHAIN_SHARD_NUMBER, block_without_signature_root))`. * Verify that `bls_verify(pubkey=state.validator_registry[get_beacon_proposer_index(state, state.slot)].pubkey, message=proposal_root, signature=block.signature, domain=get_domain(state.fork, get_current_epoch(state), DOMAIN_PROPOSAL))`. -### RANDAO +#### RANDAO * Let `proposer = state.validator_registry[get_beacon_proposer_index(state, state.slot)]`. * Verify that `bls_verify(pubkey=proposer.pubkey, message=int_to_bytes32(get_current_epoch(state)), signature=block.randao_reveal, domain=get_domain(state.fork, get_current_epoch(state), DOMAIN_RANDAO))`. * Set `state.latest_randao_mixes[get_current_epoch(state) % LATEST_RANDAO_MIXES_LENGTH] = xor(get_randao_mix(state, get_current_epoch(state)), hash(block.randao_reveal))`. -### Eth1 data +#### Eth1 data * If `block.eth1_data` equals `eth1_data_vote.eth1_data` for some `eth1_data_vote` in `state.eth1_data_votes`, set `eth1_data_vote.vote_count += 1`. * Otherwise, append to `state.eth1_data_votes` a new `Eth1DataVote(eth1_data=block.eth1_data, vote_count=1)`. -### Operations +#### Operations -#### Proposer slashings +##### Proposer slashings Verify that `len(block.body.proposer_slashings) <= MAX_PROPOSER_SLASHINGS`. @@ -1545,7 +1563,7 @@ For each `proposer_slashing` in `block.body.proposer_slashings`: * Verify that `bls_verify(pubkey=proposer.pubkey, message=hash_tree_root(proposer_slashing.proposal_data_2), signature=proposer_slashing.proposal_signature_2, domain=get_domain(state.fork, slot_to_epoch(proposer_slashing.proposal_data_2.slot), DOMAIN_PROPOSAL))`. * Run `penalize_validator(state, proposer_slashing.proposer_index)`. -#### Attester slashings +##### Attester slashings Verify that `len(block.body.attester_slashings) <= MAX_ATTESTER_SLASHINGS`. @@ -1562,7 +1580,7 @@ For each `attester_slashing` in `block.body.attester_slashings`: * Verify that `verify_slashable_vote_data(state, slashable_vote_data_2)`. * For each [validator](#dfn-validator) index `i` in `intersection` run `penalize_validator(state, i)` if `state.validator_registry[i].penalized_epoch > get_current_epoch(state)`. -#### Attestations +##### Attestations Verify that `len(block.body.attestations) <= MAX_ATTESTATIONS`. @@ -1580,7 +1598,7 @@ For each `attestation` in `block.body.attestations`: * [TO BE REMOVED IN PHASE 1] Verify that `attestation.data.shard_block_root == ZERO_HASH`. * Append `PendingAttestation(data=attestation.data, aggregation_bitfield=attestation.aggregation_bitfield, custody_bitfield=attestation.custody_bitfield, slot_included=state.slot)` to `state.latest_attestations`. -#### Deposits +##### Deposits Verify that `len(block.body.deposits) <= MAX_DEPOSITS`. @@ -1615,7 +1633,7 @@ process_deposit( ) ``` -#### Exits +##### Exits Verify that `len(block.body.exits) <= MAX_EXITS`. @@ -1628,15 +1646,15 @@ For each `exit` in `block.body.exits`: * Verify that `bls_verify(pubkey=validator.pubkey, message=exit_message, signature=exit.signature, domain=get_domain(state.fork, exit.epoch, DOMAIN_EXIT))`. * Run `initiate_validator_exit(state, exit.validator_index)`. -#### Custody +##### Custody [TO BE REMOVED IN PHASE 1] Verify that `len(block.body.custody_reseeds) == len(block.body.custody_challenges) == len(block.body.custody_responses) == 0`. -## Per-epoch processing +### Per-epoch processing The steps below happen when `(state.slot + 1) % EPOCH_LENGTH == 0`. -### Helpers +#### Helpers * Let `current_epoch = get_current_epoch(state)`. * Let `previous_epoch = current_epoch - 1 if current_epoch > GENESIS_EPOCH else current_epoch`. @@ -1686,14 +1704,14 @@ Define the following helpers to process attestation inclusion rewards and inclus * Let `inclusion_slot(state, index) = a.slot_included` for the attestation `a` where `index` is in `get_attestation_participants(state, a.data, a.aggregation_bitfield)`. If multiple attestations are applicable, the attestation with lowest `slot_included` is considered. * Let `inclusion_distance(state, index) = a.slot_included - a.data.slot` where `a` is the above attestation. -### Eth1 data +#### Eth1 data If `next_epoch % ETH1_DATA_VOTING_PERIOD == 0`: * If `eth1_data_vote.vote_count * 2 > ETH1_DATA_VOTING_PERIOD * EPOCH_LENGTH` for some `eth1_data_vote` in `state.eth1_data_votes` (ie. more than half the votes in this voting period were for that value), set `state.latest_eth1_data = eth1_data_vote.data`. * Set `state.eth1_data_votes = []`. -### Justification +#### Justification First, update the justification bitfield: @@ -1714,13 +1732,13 @@ Finally, update the following: * Set `state.previous_justified_epoch = state.justified_epoch`. * Set `state.justified_epoch = new_justified_epoch`. -### Crosslinks +#### Crosslinks For every `slot in range(get_epoch_start_slot(previous_epoch), get_epoch_start_slot(next_epoch))`, let `crosslink_committees_at_slot = get_crosslink_committees_at_slot(state, slot)`. For every `(crosslink_committee, shard)` in `crosslink_committees_at_slot`, compute: * Set `state.latest_crosslinks[shard] = Crosslink(epoch=current_epoch, shard_block_root=winning_root(crosslink_committee))` if `3 * total_attesting_balance(crosslink_committee) >= 2 * total_balance(crosslink_committee)`. -### Rewards and penalties +#### Rewards and penalties First, we define some additional helpers: @@ -1728,7 +1746,7 @@ First, we define some additional helpers: * Let `base_reward(state, index) = get_effective_balance(state, index) // base_reward_quotient // 5` for any validator with the given `index`. * Let `inactivity_penalty(state, index, epochs_since_finality) = base_reward(state, index) + get_effective_balance(state, index) * epochs_since_finality // INACTIVITY_PENALTY_QUOTIENT // 2` for any validator with the given `index`. -#### Justification and finalization +##### Justification and finalization Note: When applying penalties in the following balance recalculations implementers should make sure the `uint64` does not underflow. @@ -1756,11 +1774,11 @@ Case 2: `epochs_since_finality > 4`: * Any [active_validator](#dfn-active-validator) `index` with `validator.penalized_epoch <= current_epoch`, loses `2 * inactivity_penalty(state, index, epochs_since_finality) + base_reward(state, index)`. * Any [validator](#dfn-validator) `index` in `previous_epoch_attester_indices` loses `base_reward(state, index) - base_reward(state, index) * MIN_ATTESTATION_INCLUSION_DELAY // inclusion_distance(state, index)` -#### Attestation inclusion +##### Attestation inclusion For each `index` in `previous_epoch_attester_indices`, we determine the proposer `proposer_index = get_beacon_proposer_index(state, inclusion_slot(state, index))` and set `state.validator_balances[proposer_index] += base_reward(state, index) // INCLUDER_REWARD_QUOTIENT`. -#### Crosslinks +##### Crosslinks For every `slot in range(get_epoch_start_slot(previous_epoch), get_epoch_start_slot(current_epoch))`: @@ -1769,7 +1787,7 @@ For every `slot in range(get_epoch_start_slot(previous_epoch), get_epoch_start_s * If `index in attesting_validators(crosslink_committee)`, `state.validator_balances[index] += base_reward(state, index) * total_attesting_balance(crosslink_committee) // total_balance(crosslink_committee))`. * If `index not in attesting_validators(crosslink_committee)`, `state.validator_balances[index] -= base_reward(state, index)`. -### Ejections +#### Ejections * Run `process_ejections(state)`. @@ -1784,7 +1802,7 @@ def process_ejections(state: BeaconState) -> None: exit_validator(state, index) ``` -### Validator registry and shuffling seed data +#### Validator registry and shuffling seed data First, update the following: @@ -1899,13 +1917,13 @@ def process_penalties_and_exits(state: BeaconState) -> None: break ``` -### Final updates +#### Final updates * Set `state.latest_penalized_balances[(next_epoch) % LATEST_PENALIZED_EXIT_LENGTH] = state.latest_penalized_balances[current_epoch % LATEST_PENALIZED_EXIT_LENGTH]`. * Set `state.latest_randao_mixes[next_epoch % LATEST_RANDAO_MIXES_LENGTH] = get_randao_mix(state, current_epoch)`. * Remove any `attestation` in `state.latest_attestations` such that `slot_to_epoch(attestation.data.slot) < current_epoch`. -## State root processing +### State root verification Verify `block.state_root == hash_tree_root(state)` if there exists a `block` for the slot being processed.