diff --git a/Makefile b/Makefile index b468e648c..e8f3d21bc 100644 --- a/Makefile +++ b/Makefile @@ -77,6 +77,10 @@ test: pyspec . venv/bin/activate; cd $(PY_SPEC_DIR); \ python -m pytest -n 4 --cov=eth2spec.phase0.spec --cov=eth2spec.phase1.spec --cov-report="html:$(COV_HTML_OUT)" --cov-branch eth2spec +find_test: pyspec + . venv/bin/activate; cd $(PY_SPEC_DIR); \ + python -m pytest -k=$(K) --cov=eth2spec.phase0.spec --cov=eth2spec.phase1.spec --cov-report="html:$(COV_HTML_OUT)" --cov-branch eth2spec + citest: pyspec mkdir -p tests/core/pyspec/test-reports/eth2spec; . venv/bin/activate; cd $(PY_SPEC_DIR); \ python -m pytest -n 4 --junitxml=eth2spec/test_results.xml eth2spec diff --git a/setup.py b/setup.py index 53d0dab01..911eb65b0 100644 --- a/setup.py +++ b/setup.py @@ -92,6 +92,8 @@ from dataclasses import ( field, ) +from lru import LRU + from eth2spec.utils.ssz.ssz_impl import hash_tree_root from eth2spec.utils.ssz.ssz_typing import ( View, boolean, Container, List, Vector, uint64, @@ -114,6 +116,8 @@ from dataclasses import ( field, ) +from lru import LRU + from eth2spec.utils.ssz.ssz_impl import hash_tree_root from eth2spec.utils.ssz.ssz_typing import ( View, boolean, Container, List, Vector, uint64, uint8, bit, @@ -152,8 +156,8 @@ def hash(x: bytes) -> Bytes32: # type: ignore return hash_cache[x] -def cache_this(key_fn, value_fn): # type: ignore - cache_dict = {} # type: ignore +def cache_this(key_fn, value_fn, lru_size): # type: ignore + cache_dict = LRU(size=lru_size) def wrapper(*args, **kw): # type: ignore key = key_fn(*args, **kw) @@ -164,44 +168,50 @@ def cache_this(key_fn, value_fn): # type: ignore return wrapper +_compute_shuffled_index = compute_shuffled_index +compute_shuffled_index = cache_this( + lambda index, index_count, seed: (index, index_count, seed), + _compute_shuffled_index, lru_size=SLOTS_PER_EPOCH * 3) + +_get_total_active_balance = get_total_active_balance +get_total_active_balance = cache_this( + lambda state: (state.validators.hash_tree_root(), compute_epoch_at_slot(state.slot)), + _get_total_active_balance, lru_size=10) + _get_base_reward = get_base_reward get_base_reward = cache_this( - lambda state, index: (state.validators.hash_tree_root(), state.slot), - _get_base_reward) - + lambda state, index: (state.validators.hash_tree_root(), state.slot, index), + _get_base_reward, lru_size=2048) _get_committee_count_at_slot = get_committee_count_at_slot get_committee_count_at_slot = cache_this( lambda state, epoch: (state.validators.hash_tree_root(), epoch), - _get_committee_count_at_slot) - + _get_committee_count_at_slot, lru_size=SLOTS_PER_EPOCH * 3) _get_active_validator_indices = get_active_validator_indices get_active_validator_indices = cache_this( lambda state, epoch: (state.validators.hash_tree_root(), epoch), - _get_active_validator_indices) - - -_get_total_active_balance = get_total_active_balance -get_total_active_balance = cache_this( - lambda state: (state.validators.hash_tree_root(), get_current_epoch(state)), - _get_total_active_balance) - + _get_active_validator_indices, lru_size=3) _get_beacon_committee = get_beacon_committee get_beacon_committee = cache_this( lambda state, slot, index: (state.validators.hash_tree_root(), state.randao_mixes.hash_tree_root(), slot, index), - _get_beacon_committee) + _get_beacon_committee, lru_size=SLOTS_PER_EPOCH * MAX_COMMITTEES_PER_SLOT * 3) _get_matching_target_attestations = get_matching_target_attestations get_matching_target_attestations = cache_this( lambda state, epoch: (state.hash_tree_root(), epoch), - _get_matching_target_attestations) + _get_matching_target_attestations, lru_size=10) _get_matching_head_attestations = get_matching_head_attestations get_matching_head_attestations = cache_this( lambda state, epoch: (state.hash_tree_root(), epoch), - _get_matching_head_attestations)''' + _get_matching_head_attestations, lru_size=10) + +_get_attesting_indices = get_attesting_indices +get_attesting_indices = cache_this( + lambda state, data, bits: (state.validators.hash_tree_root(), data.hash_tree_root(), bits.hash_tree_root()), + _get_attesting_indices, lru_size=SLOTS_PER_EPOCH * MAX_COMMITTEES_PER_SLOT * 3)''' def objects_to_spec(spec_object: SpecObject, imports: str, fork: str) -> str: @@ -490,6 +500,7 @@ setup( "py_ecc==2.0.0", "dataclasses==0.6", "remerkleable==0.1.12", - "ruamel.yaml==0.16.5" + "ruamel.yaml==0.16.5", + "lru-dict==1.1.6" ] ) diff --git a/specs/phase0/beacon-chain.md b/specs/phase0/beacon-chain.md index bd5e7f5f4..23fa5ceee 100644 --- a/specs/phase0/beacon-chain.md +++ b/specs/phase0/beacon-chain.md @@ -996,10 +996,11 @@ def get_beacon_proposer_index(state: BeaconState) -> ValidatorIndex: ```python def get_total_balance(state: BeaconState, indices: Set[ValidatorIndex]) -> Gwei: """ - Return the combined effective balance of the ``indices``. (1 Gwei minimum to avoid divisions by zero.) + Return the combined effective balance of the ``indices``. + ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero. Math safe up to ~10B ETH, afterwhich this overflows uint64. """ - return Gwei(max(1, sum([state.validators[index].effective_balance for index in indices]))) + return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices]))) ``` #### `get_total_active_balance` @@ -1008,6 +1009,7 @@ def get_total_balance(state: BeaconState, indices: Set[ValidatorIndex]) -> Gwei: def get_total_active_balance(state: BeaconState) -> Gwei: """ Return the combined effective balance of the active validators. + Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero. """ return get_total_balance(state, set(get_active_validator_indices(state, get_current_epoch(state)))) ``` @@ -1289,6 +1291,10 @@ def get_unslashed_attesting_indices(state: BeaconState, ```python def get_attesting_balance(state: BeaconState, attestations: Sequence[PendingAttestation]) -> Gwei: + """ + Return the combined effective balance of the set of unslashed validators participating in ``attestations``. + Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero. + """ return get_total_balance(state, get_unslashed_attesting_indices(state, attestations)) ``` @@ -1366,7 +1372,7 @@ def get_attestation_deltas(state: BeaconState) -> Tuple[Sequence[Gwei], Sequence if index in unslashed_attesting_indices: increment = EFFECTIVE_BALANCE_INCREMENT # Factored out from balance totals to avoid uint64 overflow reward_numerator = get_base_reward(state, index) * (attesting_balance // increment) - rewards[index] = reward_numerator // (total_balance // increment) + rewards[index] += reward_numerator // (total_balance // increment) else: penalties[index] += get_base_reward(state, index) diff --git a/specs/phase0/p2p-interface.md b/specs/phase0/p2p-interface.md index 77eeb21df..841432efd 100644 --- a/specs/phase0/p2p-interface.md +++ b/specs/phase0/p2p-interface.md @@ -28,6 +28,7 @@ It consists of four main sections: - [Multiplexing](#multiplexing) - [Eth2 network interaction domains](#eth2-network-interaction-domains) - [Configuration](#configuration) + - [MetaData](#metadata) - [The gossip domain: gossipsub](#the-gossip-domain-gossipsub) - [Topics and messages](#topics-and-messages) - [Global topics](#global-topics) @@ -49,6 +50,8 @@ It consists of four main sections: - [Goodbye](#goodbye) - [BeaconBlocksByRange](#beaconblocksbyrange) - [BeaconBlocksByRoot](#beaconblocksbyroot) + - [Ping](#ping) + - [GetMetaData](#getmetadata) - [The discovery domain: discv5](#the-discovery-domain-discv5) - [Integration into libp2p stacks](#integration-into-libp2p-stacks) - [ENR structure](#enr-structure) @@ -157,8 +160,7 @@ The following SecIO parameters MUST be supported by all stacks: The [Libp2p-noise](https://github.com/libp2p/specs/tree/master/noise) secure channel handshake with `secp256k1` identities will be used for mainnet. -As specified in the libp2p specification, clients MUST support the `XX` handshake pattern and -can optionally implement the `IK` and `XXfallback` patterns for optimistic 0-RTT. +As specified in the libp2p specification, clients MUST support the `XX` handshake pattern. ## Protocol Negotiation @@ -196,6 +198,24 @@ This section outlines constants that are used in this spec. | `ATTESTATION_PROPAGATION_SLOT_RANGE` | `32` | The maximum number of slots during which an attestation can be propagated. | | `MAXIMUM_GOSSIP_CLOCK_DISPARITY` | `500ms` | The maximum milliseconds of clock disparity assumed between honest nodes. | +## MetaData + +Clients MUST locally store the following `MetaData`: + +``` +( + seq_number: uint64 + attnets: Bitvector[ATTESTATION_SUBNET_COUNT] +) +``` + +Where + +- `seq_number` is a `uint64` starting at `0` used to version the node's metadata. If any other field in the local `MetaData` changes, the node MUST increment `seq_number` by 1. +- `attnets` is a `Bitvector` representing the node's persistent attestation subnet subscriptions. + +*Note*: `MetaData.seq_number` is used for versioning of the node's metadata, is entirely independent of the ENR sequence number, and will in most cases be out of sync with the ENR sequence number. + ## The gossip domain: gossipsub Clients MUST support the [gossipsub](https://github.com/libp2p/specs/tree/master/pubsub/gossipsub) libp2p protocol. @@ -260,9 +280,10 @@ There are two primary global topics used to propagate beacon blocks and aggregat - `beacon_block` - This topic is used solely for propagating new signed beacon blocks to all nodes on the networks. Signed blocks are sent in their entirety. The following validations MUST pass before forwarding the `signed_beacon_block` on the network - The block is not from a future slot (with a `MAXIMUM_GOSSIP_CLOCK_DISPARITY` allowance) -- i.e. validate that `signed_beacon_block.message.slot <= current_slot` (a client MAY queue future blocks for processing at the appropriate slot). - - The block is from a slot greater than the latest finalized slot (with a `MAXIMUM_GOSSIP_CLOCK_DISPARITY` allowance) -- i.e. validate that `signed_beacon_block.message.slot > compute_start_slot_at_epoch(state.finalized_checkpoint.epoch)` (a client MAY choose to validate and store such blocks for additional purposes -- e.g. slashing detection, archive nodes, etc). + - The block is from a slot greater than the latest finalized slot -- i.e. validate that `signed_beacon_block.message.slot > compute_start_slot_at_epoch(state.finalized_checkpoint.epoch)` (a client MAY choose to validate and store such blocks for additional purposes -- e.g. slashing detection, archive nodes, etc). - The block is the first block with valid signature received for the proposer for the slot, `signed_beacon_block.message.slot`. - - The proposer signature, `signed_beacon_block.signature`, is valid. + - The proposer signature, `signed_beacon_block.signature`, is valid with respect to the `proposer_index` pubkey. + - The block is proposed by the expected `proposer_index` for the block's slot in the context of the current shuffling (defined by `parent_root`/`slot`). If the `proposer_index` cannot immediately be verified against the expected shuffling, the block MAY be queued for later processing while proposers for the block's branch are calculated. - `beacon_aggregate_and_proof` - This topic is used to propagate aggregated attestations (as `SignedAggregateAndProof`s) to subscribing nodes (typically validators) to be included in future blocks. The following validations MUST pass before forwarding the `signed_aggregate_and_proof` on the network. (We define the following for convenience -- `aggregate_and_proof = signed_aggregate_and_proof.message` and `aggregate = aggregate_and_proof.aggregate`) - `aggregate.data.slot` is within the last `ATTESTATION_PROPAGATION_SLOT_RANGE` slots (with a `MAXIMUM_GOSSIP_CLOCK_DISPARITY` allowance) -- i.e. `aggregate.data.slot + ATTESTATION_PROPAGATION_SLOT_RANGE >= current_slot >= aggregate.data.slot` (a client MAY queue future aggregates for processing at the appropriate slot). - The aggregate attestation defined by `hash_tree_root(aggregate)` has _not_ already been seen (via aggregate gossip, within a block, or through the creation of an equivalent aggregate locally). @@ -601,6 +622,60 @@ Clients MUST support requesting blocks since the latest finalized epoch. Clients MUST respond with at least one block, if they have it. Clients MAY limit the number of blocks in the response. +#### Ping + +**Protocol ID:** `/eth2/beacon_chain/req/ping/1/` + +Request Content: + +``` +( + uint64 +) +``` + +Response Content: + +``` +( + uint64 +) +``` + +Sent intermittently, the `Ping` protocol checks liveness of connected peers. +Peers request and respond with their local metadata sequence number (`MetaData.seq_number`). + +If the peer does not respond to the `Ping` request, the client MAY disconnect from the peer. + +A client can then determine if their local record of a peer's MetaData is up to date +and MAY request an updated version via the `MetaData` RPC method if not. + +The request MUST be encoded as an SSZ-field. + +The response MUST consist of a single `response_chunk`. + +#### GetMetaData + +**Protocol ID:** `/eth2/beacon_chain/req/metadata/1/` + +No Request Content. + +Response Content: + +``` +( + MetaData +) +``` + +Requests the MetaData of a peer. The request opens and negotiates the stream without +sending any request content. Once established the receiving peer responds with +it's local most up-to-date MetaData. + +The response MUST be encoded as an SSZ-container. + +The response MUST consist of a single `response_chunk`. + ## The discovery domain: discv5 Discovery Version 5 ([discv5](https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md)) is used for peer discovery, both in the interoperability testnet and mainnet. @@ -622,6 +697,9 @@ This integration enables the libp2p stack to subsequently form connections and s The Ethereum Node Record (ENR) for an Ethereum 2.0 client MUST contain the following entries (exclusive of the sequence number and signature, which MUST be present in an ENR): - The compressed secp256k1 publickey, 33 bytes (`secp256k1` field). + +The ENR MAY contain the following entries: + - An IPv4 address (`ip` field) and/or IPv6 address (`ip6` field). - A TCP port (`tcp` field) representing the local libp2p listening port. - A UDP port (`udp` field) representing the local discv5 listening port. @@ -630,12 +708,16 @@ Specifications of these parameters can be found in the [ENR Specification](http: #### Attestation subnet bitfield -The ENR MAY contain an entry (`attnets`) signifying the attestation subnet bitfield with the following form to more easily discover peers participating in particular attestation gossip subnets. +The ENR `attnets` entry signifies the attestation subnet bitfield with the following form to more easily discover peers participating in particular attestation gossip subnets. | Key | Value | |:-------------|:-------------------------------------------------| | `attnets` | SSZ `Bitvector[ATTESTATION_SUBNET_COUNT]` | +If a node's `MetaData.attnets` has any non-zero bit, the ENR MUST include the `attnets` entry with the same value as `MetaData.attnets`. + +If a node's `MetaData.attnets` is composed of all zeros, the ENR MAY optionally include the `attnets` entry or leave it out entirely. + #### Interop In the interoperability testnet, all peers will support all capabilities defined in this document (gossip, full Req/Resp suite, discovery protocol), therefore the ENR record does not need to carry Eth2 capability information, as it would be superfluous. diff --git a/specs/phase0/validator.md b/specs/phase0/validator.md index 6ddbef81f..bc7510403 100644 --- a/specs/phase0/validator.md +++ b/specs/phase0/validator.md @@ -200,9 +200,11 @@ The beacon chain shufflings are designed to provide a minimum of 1 epoch lookahe Specifically a validator should: * Call `get_committee_assignment(state, next_epoch, validator_index)` when checking for next epoch assignments. -* Join the pubsub topic -- `committee_index{committee_index % ATTESTATION_SUBNET_COUNT}_beacon_attestation`. - * For any current peer subscribed to the topic, the validator simply sends a `subscribe` message for the new topic. - * If an _insufficient_ number of current peers are subscribed to the topic, the validator must discover new peers on this topic. Via the discovery protocol, find peers with an ENR containing the `attnets` entry such that `ENR["attnets"][committee_index % ATTESTATION_SUBNET_COUNT] == True`. +* Find peers of the pubsub topic `committee_index{committee_index % ATTESTATION_SUBNET_COUNT}_beacon_attestation`. + * If an _insufficient_ number of current peers are subscribed to the topic, the validator must discover new peers on this topic. Via the discovery protocol, find peers with an ENR containing the `attnets` entry such that `ENR["attnets"][committee_index % ATTESTATION_SUBNET_COUNT] == True`. Then validate that the peers are still persisted on the desired topic by requesting `GetMetaData` and checking the resulting `attnets` field. + * If the validator is assigned to be an aggregator for the slot (see `is_aggregator()`), then subscribe to the topic. + +*Note*: If the validator is _not_ assigned to be an aggregator, the validator only needs sufficient number of peers on the topic to be able to publish messages. The validator does not need to _subscribe_ and listen to all messages on the topic. ## Beacon chain responsibilities @@ -404,12 +406,12 @@ Set `attestation.data = attestation_data` where `attestation_data` is the `Attes ##### Aggregate signature -Set `attestation.signature = signed_attestation_data` where `signed_attestation_data` is obtained from: +Set `attestation.signature = attestation_signature` where `attestation_signature` is obtained from: ```python -def get_signed_attestation_data(state: BeaconState, attestation: IndexedAttestation, privkey: int) -> BLSSignature: - domain = get_domain(state, DOMAIN_BEACON_ATTESTER, attestation.data.target.epoch) - signing_root = compute_signing_root(attestation.data, domain) +def get_attestation_signature(state: BeaconState, attestation_data: AttestationData, privkey: int) -> BLSSignature: + domain = get_domain(state, DOMAIN_BEACON_ATTESTER, attestation_data.target.epoch) + signing_root = compute_signing_root(attestation_data, domain) return bls.Sign(privkey, signing_root) ``` diff --git a/specs/phase1/custody-game.md b/specs/phase1/custody-game.md index 72f9b6394..eb243f8fb 100644 --- a/specs/phase1/custody-game.md +++ b/specs/phase1/custody-game.md @@ -192,10 +192,10 @@ def get_custody_atoms(bytez: bytes) -> Sequence[bytes]: def compute_custody_bit(key: BLSSignature, data: bytes) -> bit: full_G2_element = bls.signature_to_G2(key) s = full_G2_element[0].coeffs - bits = [legendre_bit(sum(s[i % 2]**i * int.from_bytes(atom, "little")), BLS12_381_Q) - for i, atom in enumerate(get_custody_atoms(data))] - # XOR all atom bits - return bit(sum(bits) % 2) + custody_atoms = get_custody_atoms(data) + n = len(custody_atoms) + a = sum(s[i % 2]**i * int.from_bytes(atom, "little") for i, atom in enumerate(custody_atoms) + s[n % 2]**n) + return legendre_bit(a, BLS12_381_Q) ``` ### `get_randao_epoch_for_custody_period` diff --git a/tests/core/pyspec/eth2spec/VERSION.txt b/tests/core/pyspec/eth2spec/VERSION.txt index 142464bf2..027934ea1 100644 --- a/tests/core/pyspec/eth2spec/VERSION.txt +++ b/tests/core/pyspec/eth2spec/VERSION.txt @@ -1 +1 @@ -0.11.0 \ No newline at end of file +0.11.1 \ No newline at end of file diff --git a/tests/core/pyspec/eth2spec/test/context.py b/tests/core/pyspec/eth2spec/test/context.py index c4ce15ed8..bdc6ec698 100644 --- a/tests/core/pyspec/eth2spec/test/context.py +++ b/tests/core/pyspec/eth2spec/test/context.py @@ -6,6 +6,7 @@ from .helpers.genesis import create_genesis_state from .utils import vector_test, with_meta_tags +from random import Random from typing import Any, Callable, Sequence, TypedDict, Protocol from importlib import reload @@ -73,6 +74,14 @@ def default_activation_threshold(spec): return spec.MAX_EFFECTIVE_BALANCE +def zero_activation_threshold(spec): + """ + Helper method to use 0 gwei as the activation threshold for state creation for tests. + Usage: `@with_custom_state(threshold_fn=zero_activation_threshold, ...)` + """ + return 0 + + def default_balances(spec): """ Helper method to create a series of default balances. @@ -102,8 +111,18 @@ def misc_balances(spec): Usage: `@with_custom_state(balances_fn=misc_balances, ...)` """ num_validators = spec.SLOTS_PER_EPOCH * 8 - num_misc_validators = spec.SLOTS_PER_EPOCH - return [spec.MAX_EFFECTIVE_BALANCE] * num_validators + [spec.MIN_DEPOSIT_AMOUNT] * num_misc_validators + balances = [spec.MAX_EFFECTIVE_BALANCE * 2 * i // num_validators for i in range(num_validators)] + rng = Random(1234) + rng.shuffle(balances) + return balances + + +def low_single_balance(spec): + """ + Helper method to create a single of balance of 1 Gwei. + Usage: `@with_custom_state(balances_fn=low_single_balance, ...)` + """ + return [1] def single_phase(fn): diff --git a/tests/core/pyspec/eth2spec/test/helpers/attestations.py b/tests/core/pyspec/eth2spec/test/helpers/attestations.py index 1e7c6300d..af989a9c0 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/attestations.py +++ b/tests/core/pyspec/eth2spec/test/helpers/attestations.py @@ -101,7 +101,7 @@ def get_valid_on_time_attestation(spec, state, slot=None, index=None, signed=Fal if index is None: index = 0 - return get_valid_attestation(spec, state, slot, index, signed, True) + return get_valid_attestation(spec, state, slot=slot, index=index, signed=signed, on_time=True) def get_valid_late_attestation(spec, state, slot=None, index=None, signed=False): @@ -113,10 +113,10 @@ def get_valid_late_attestation(spec, state, slot=None, index=None, signed=False) if index is None: index = 0 - return get_valid_attestation(spec, state, slot, index, signed, False) + return get_valid_attestation(spec, state, slot=slot, index=index, signed=signed, on_time=False) -def get_valid_attestation(spec, state, slot=None, index=None, signed=False, on_time=True): +def get_valid_attestation(spec, state, slot=None, index=None, empty=False, signed=False, on_time=True): if slot is None: slot = state.slot if index is None: @@ -136,7 +136,8 @@ def get_valid_attestation(spec, state, slot=None, index=None, signed=False, on_t aggregation_bits=aggregation_bits, data=attestation_data, ) - fill_aggregate_attestation(spec, state, attestation) + if not empty: + fill_aggregate_attestation(spec, state, attestation) if signed: sign_attestation(spec, state, attestation) diff --git a/tests/core/pyspec/eth2spec/test/phase_0/block_processing/test_process_attestation.py b/tests/core/pyspec/eth2spec/test/phase_0/block_processing/test_process_attestation.py index 9528ff6eb..8663391aa 100644 --- a/tests/core/pyspec/eth2spec/test/phase_0/block_processing/test_process_attestation.py +++ b/tests/core/pyspec/eth2spec/test/phase_0/block_processing/test_process_attestation.py @@ -264,14 +264,12 @@ def test_bad_source_root(spec, state): @spec_state_test def test_empty_aggregation_bits(spec, state): next_slot(spec, state) - attestation = get_valid_attestation(spec, state) + attestation = get_valid_attestation(spec, state, empty=True) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) - attestation.aggregation_bits = Bitlist[spec.MAX_VALIDATORS_PER_COMMITTEE]( + assert attestation.aggregation_bits == Bitlist[spec.MAX_VALIDATORS_PER_COMMITTEE]( *([0b0] * len(attestation.aggregation_bits))) - sign_attestation(spec, state, attestation) - yield from run_attestation_processing(spec, state, attestation) diff --git a/tests/core/pyspec/eth2spec/test/phase_0/epoch_processing/test_process_rewards_and_penalties.py b/tests/core/pyspec/eth2spec/test/phase_0/epoch_processing/test_process_rewards_and_penalties.py index 0a1df9d63..317c97149 100644 --- a/tests/core/pyspec/eth2spec/test/phase_0/epoch_processing/test_process_rewards_and_penalties.py +++ b/tests/core/pyspec/eth2spec/test/phase_0/epoch_processing/test_process_rewards_and_penalties.py @@ -1,9 +1,9 @@ -from copy import deepcopy - from eth2spec.test.context import ( spec_state_test, spec_test, with_all_phases, with_phases, single_phase, - misc_balances, with_custom_state, default_activation_threshold + with_custom_state, + zero_activation_threshold, + misc_balances, low_single_balance, ) from eth2spec.test.helpers.state import ( next_epoch, @@ -21,7 +21,7 @@ def run_process_rewards_and_penalties(spec, state): yield from run_epoch_processing_with(spec, state, 'process_rewards_and_penalties') -def prepare_state_with_full_attestations(spec, state): +def prepare_state_with_full_attestations(spec, state, empty=False): start_slot = state.slot start_epoch = spec.get_current_epoch(state) next_start_epoch = spec.compute_start_slot_at_epoch(start_epoch + 1) @@ -30,7 +30,7 @@ def prepare_state_with_full_attestations(spec, state): # create an attestation for each index in each slot in epoch if state.slot < next_start_epoch: for committee_index in range(spec.get_committee_count_at_slot(state, state.slot)): - attestation = get_valid_attestation(spec, state, index=committee_index, signed=True) + attestation = get_valid_attestation(spec, state, index=committee_index, empty=empty, signed=True) attestations.append(attestation) # fill each created slot in state after inclusion delay if state.slot >= start_slot + spec.MIN_ATTESTATION_INCLUSION_DELAY: @@ -48,7 +48,7 @@ def prepare_state_with_full_attestations(spec, state): @with_phases(['phase0']) @spec_state_test def test_genesis_epoch_no_attestations_no_penalties(spec, state): - pre_state = deepcopy(state) + pre_state = state.copy() assert spec.compute_epoch_at_slot(state.slot) == spec.GENESIS_EPOCH @@ -76,7 +76,7 @@ def test_genesis_epoch_full_attestations_no_rewards(spec, state): # ensure has not cross the epoch boundary assert spec.compute_epoch_at_slot(state.slot) == spec.GENESIS_EPOCH - pre_state = deepcopy(state) + pre_state = state.copy() yield from run_process_rewards_and_penalties(spec, state) @@ -91,7 +91,7 @@ def test_full_attestations(spec, state): next_epoch(spec, state) attestations = prepare_state_with_full_attestations(spec, state) - pre_state = deepcopy(state) + pre_state = state.copy() yield from run_process_rewards_and_penalties(spec, state) @@ -129,20 +129,21 @@ def test_full_attestations_random_incorrect_fields(spec, state): @with_all_phases @spec_test -@with_custom_state(balances_fn=misc_balances, threshold_fn=default_activation_threshold) +@with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.MAX_EFFECTIVE_BALANCE // 2) @single_phase def test_full_attestations_misc_balances(spec, state): # Go to start of next epoch to ensure can have full participation next_epoch(spec, state) attestations = prepare_state_with_full_attestations(spec, state) - pre_state = deepcopy(state) + pre_state = state.copy() yield from run_process_rewards_and_penalties(spec, state) attesting_indices = spec.get_unslashed_attesting_indices(state, attestations) assert len(attesting_indices) > 0 assert len(attesting_indices) != len(pre_state.validators) + assert any(v.effective_balance != spec.MAX_EFFECTIVE_BALANCE for v in state.validators) for index in range(len(pre_state.validators)): if index in attesting_indices: assert state.balances[index] > pre_state.balances[index] @@ -150,13 +151,35 @@ def test_full_attestations_misc_balances(spec, state): assert state.balances[index] < pre_state.balances[index] else: assert state.balances[index] == pre_state.balances[index] + # Check if base rewards are consistent with effective balance. + brs = {} + for index in attesting_indices: + br = spec.get_base_reward(state, index) + if br in brs: + assert brs[br] == state.validators[index].effective_balance + else: + brs[br] = state.validators[index].effective_balance + + +@with_all_phases +@spec_test +@with_custom_state(balances_fn=low_single_balance, threshold_fn=zero_activation_threshold) +@single_phase +def test_full_attestations_one_validaor_one_gwei(spec, state): + attestations = prepare_state_with_full_attestations(spec, state) + + yield from run_process_rewards_and_penalties(spec, state) + + # Few assertions. Mainly to check that this extreme case can run without exception + attesting_indices = spec.get_unslashed_attesting_indices(state, attestations) + assert len(attesting_indices) == 1 @with_all_phases @spec_state_test def test_no_attestations_all_penalties(spec, state): next_epoch(spec, state) - pre_state = deepcopy(state) + pre_state = state.copy() assert spec.compute_epoch_at_slot(state.slot) == spec.GENESIS_EPOCH + 1 @@ -166,6 +189,22 @@ def test_no_attestations_all_penalties(spec, state): assert state.balances[index] < pre_state.balances[index] +@with_all_phases +@spec_state_test +def test_empty_attestations(spec, state): + attestations = prepare_state_with_full_attestations(spec, state, empty=True) + + pre_state = state.copy() + + yield from run_process_rewards_and_penalties(spec, state) + + attesting_indices = spec.get_unslashed_attesting_indices(state, attestations) + assert len(attesting_indices) == 0 + + for index in range(len(pre_state.validators)): + assert state.balances[index] < pre_state.balances[index] + + @with_all_phases @spec_state_test def test_duplicate_attestation(spec, state): @@ -182,8 +221,8 @@ def test_duplicate_attestation(spec, state): assert len(participants) > 0 - single_state = deepcopy(state) - dup_state = deepcopy(state) + single_state = state.copy() + dup_state = state.copy() inclusion_slot = state.slot + spec.MIN_ATTESTATION_INCLUSION_DELAY add_attestations_to_state(spec, single_state, [attestation], inclusion_slot) @@ -218,7 +257,7 @@ def test_attestations_some_slashed(spec, state): assert spec.compute_epoch_at_slot(state.slot) == spec.GENESIS_EPOCH + 1 assert len(state.previous_epoch_attestations) == len(attestations) - pre_state = deepcopy(state) + pre_state = state.copy() yield from run_process_rewards_and_penalties(spec, state) diff --git a/tests/formats/operations/README.md b/tests/formats/operations/README.md index f1ec0429a..bb4636ec0 100644 --- a/tests/formats/operations/README.md +++ b/tests/formats/operations/README.md @@ -18,11 +18,11 @@ A YAML-encoded `BeaconState`, the state before applying the operation. Also available as `pre.ssz`. -### `.yaml` +### `.yaml` A YAML-encoded operation object, e.g. a `ProposerSlashing`, or `Deposit`. -Also available as `.ssz`. +Also available as `.ssz`. ### `post.yaml` @@ -39,14 +39,14 @@ This excludes the other parts of the block-transition. Operations: -| *`operation-name`* | *`operation-object`* | *`input name`* | *`processing call`* | -|-------------------------|----------------------|----------------------|--------------------------------------------------------| -| `attestation` | `Attestation` | `attestation` | `process_attestation(state, attestation)` | -| `attester_slashing` | `AttesterSlashing` | `attester_slashing` | `process_attester_slashing(state, attester_slashing)` | -| `block_header` | `Block` | **`block`** | `process_block_header(state, block)` | -| `deposit` | `Deposit` | `deposit` | `process_deposit(state, deposit)` | -| `proposer_slashing` | `ProposerSlashing` | `proposer_slashing` | `process_proposer_slashing(state, proposer_slashing)` | -| `voluntary_exit` | `VoluntaryExit` | `voluntary_exit` | `process_voluntary_exit(state, voluntary_exit)` | +| *`operation-name`* | *`operation-object`* | *`input name`* | *`processing call`* | +|-------------------------|-----------------------|----------------------|--------------------------------------------------------| +| `attestation` | `Attestation` | `attestation` | `process_attestation(state, attestation)` | +| `attester_slashing` | `AttesterSlashing` | `attester_slashing` | `process_attester_slashing(state, attester_slashing)` | +| `block_header` | `BeaconBlock` | **`block`** | `process_block_header(state, block)` | +| `deposit` | `Deposit` | `deposit` | `process_deposit(state, deposit)` | +| `proposer_slashing` | `ProposerSlashing` | `proposer_slashing` | `process_proposer_slashing(state, proposer_slashing)` | +| `voluntary_exit` | `SignedVoluntaryExit` | `voluntary_exit` | `process_voluntary_exit(state, voluntary_exit)` | Note that `block_header` is not strictly an operation (and is a full `Block`), but processed in the same manner, and hence included here. diff --git a/tests/formats/sanity/blocks.md b/tests/formats/sanity/blocks.md index 2b50d19ca..991bc35d2 100644 --- a/tests/formats/sanity/blocks.md +++ b/tests/formats/sanity/blocks.md @@ -25,7 +25,7 @@ Also available as `pre.ssz`. A series of files, with `` in range `[0, blocks_count)`. Blocks need to be processed in order, following the main transition function (i.e. process slot and epoch transitions in between blocks as normal) -Each file is a YAML-encoded `BeaconBlock`. +Each file is a YAML-encoded `SignedBeaconBlock`. Each block is also available as `blocks_.ssz` diff --git a/tests/generators/epoch_processing/README.md b/tests/generators/epoch_processing/README.md index 9b57875e2..662b0b516 100644 --- a/tests/generators/epoch_processing/README.md +++ b/tests/generators/epoch_processing/README.md @@ -5,7 +5,7 @@ Epoch processing covers the sub-transitions during an epoch change. An epoch-processing test-runner can consume these sub-transition test-suites, and handle different kinds of epoch sub-transitions by processing the cases using the specified test handler. -Information on the format of the tests can be found in the [epoch-processing test formats documentation](../../specs/test_formats/epoch_processing/README.md). +Information on the format of the tests can be found in the [epoch-processing test formats documentation](../../formats/epoch_processing/README.md). diff --git a/tests/generators/operations/README.md b/tests/generators/operations/README.md index 5cb3afc98..a5d48c11b 100644 --- a/tests/generators/operations/README.md +++ b/tests/generators/operations/README.md @@ -6,7 +6,7 @@ Operations (or "transactions" in previous spec iterations), An operation test-runner can consume these operation test-suites, and handle different kinds of operations by processing the cases using the specified test handler. -Information on the format of the tests can be found in the [operations test formats documentation](../../specs/test_formats/operations/README.md). +Information on the format of the tests can be found in the [operations test formats documentation](../../formats/operations/README.md). diff --git a/tests/generators/sanity/README.md b/tests/generators/sanity/README.md index 6d2e2f30d..cbc6aef06 100644 --- a/tests/generators/sanity/README.md +++ b/tests/generators/sanity/README.md @@ -2,7 +2,7 @@ Sanity tests cover regular state-transitions in a common block-list format, to ensure the basics work. -Information on the format of the tests can be found in the [sanity test formats documentation](../../specs/test_formats/sanity/README.md). +Information on the format of the tests can be found in the [sanity test formats documentation](../../formats/sanity/README.md). diff --git a/tests/generators/ssz_static/README.md b/tests/generators/ssz_static/README.md index 2a5040192..160d1ebb4 100644 --- a/tests/generators/ssz_static/README.md +++ b/tests/generators/ssz_static/README.md @@ -3,4 +3,4 @@ The purpose of this test-generator is to provide test-vectors for the most important applications of SSZ: the serialization and hashing of Eth2 data types. -Test-format documentation can be found [here](../../specs/test_formats/ssz_static/README.md). +Test-format documentation can be found [here](../../formats/ssz_static/README.md).