diff --git a/.gitignore b/.gitignore index cdfddfb0c3..454e640bd6 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ tests/core/pyspec/eth2spec/deneb/ tests/core/pyspec/eth2spec/eip6110/ tests/core/pyspec/eth2spec/eip7002/ tests/core/pyspec/eth2spec/whisk/ +tests/core/pyspec/eth2spec/peerdas/ # coverage reports .htmlcov diff --git a/Makefile b/Makefile index cd0967e7cb..2999477aff 100644 --- a/Makefile +++ b/Makefile @@ -34,7 +34,7 @@ MARKDOWN_FILES = $(wildcard $(SPEC_DIR)/*/*.md) \ $(wildcard $(SPEC_DIR)/_features/*/*/*.md) \ $(wildcard $(SSZ_DIR)/*.md) -ALL_EXECUTABLE_SPECS = phase0 altair bellatrix capella deneb eip6110 whisk +ALL_EXECUTABLE_SPECS = phase0 altair bellatrix capella deneb eip6110 whisk peerdas # The parameters for commands. Use `foreach` to avoid listing specs again. COVERAGE_SCOPE := $(foreach S,$(ALL_EXECUTABLE_SPECS), --cov=eth2spec.$S.$(TEST_PRESET_TYPE)) PYLINT_SCOPE := $(foreach S,$(ALL_EXECUTABLE_SPECS), ./eth2spec/$S) diff --git a/configs/minimal.yaml b/configs/minimal.yaml index cdfbca3a2c..ad11010929 100644 --- a/configs/minimal.yaml +++ b/configs/minimal.yaml @@ -58,6 +58,9 @@ EIP7002_FORK_EPOCH: 18446744073709551615 # WHISK WHISK_FORK_VERSION: 0x06000001 WHISK_FORK_EPOCH: 18446744073709551615 +# PEERDAS +PEERDAS_FORK_VERSION: 0x06000001 +PEERDAS_FORK_EPOCH: 18446744073709551615 # Time parameters diff --git a/presets/mainnet/peerdas.yaml b/presets/mainnet/peerdas.yaml new file mode 100644 index 0000000000..0f8a39a860 --- /dev/null +++ b/presets/mainnet/peerdas.yaml @@ -0,0 +1,10 @@ +# Mainnet preset - PeerDAS + +# Misc +# --------------------------------------------------------------- +# uint64(floorlog2(get_generalized_index(BeaconBlockBody, 'blob_kzg_commitments')) +KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH: 4 +# `uint64(2**6)` (= 64) +FIELD_ELEMENTS_PER_CELL: 64 +# `uint64((FIELD_ELEMENTS_PER_BLOB * 2) // FIELD_ELEMENTS_PER_CELL)` (= 128) +NUMBER_OF_COLUMNS: 128 diff --git a/presets/minimal/peerdas.yaml b/presets/minimal/peerdas.yaml new file mode 100644 index 0000000000..ae2b3feb49 --- /dev/null +++ b/presets/minimal/peerdas.yaml @@ -0,0 +1,10 @@ +# Minimal preset - PeerDAS + +# Misc +# --------------------------------------------------------------- +# uint64(floorlog2(get_generalized_index(BeaconBlockBody, 'blob_kzg_commitments')) +KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH: 4 +# `uint64(2**6)` (= 64) +FIELD_ELEMENTS_PER_CELL: 64 +# `uint64((FIELD_ELEMENTS_PER_BLOB * 2) // FIELD_ELEMENTS_PER_CELL)` (= 128) +NUMBER_OF_COLUMNS: 128 diff --git a/pysetup/constants.py b/pysetup/constants.py index 8d53455634..7f1d6dcdcf 100644 --- a/pysetup/constants.py +++ b/pysetup/constants.py @@ -7,6 +7,7 @@ EIP6110 = 'eip6110' EIP7002 = 'eip7002' WHISK = 'whisk' +PEERDAS = 'peerdas' diff --git a/pysetup/md_doc_paths.py b/pysetup/md_doc_paths.py index 781ae41db3..24621aac38 100644 --- a/pysetup/md_doc_paths.py +++ b/pysetup/md_doc_paths.py @@ -9,6 +9,7 @@ EIP6110, WHISK, EIP7002, + PEERDAS, ) @@ -21,6 +22,7 @@ EIP6110: DENEB, WHISK: CAPELLA, EIP7002: CAPELLA, + PEERDAS: DENEB, } ALL_FORKS = list(PREVIOUS_FORK_OF.keys()) diff --git a/pysetup/spec_builders/__init__.py b/pysetup/spec_builders/__init__.py index 794ae50d29..745010d0ca 100644 --- a/pysetup/spec_builders/__init__.py +++ b/pysetup/spec_builders/__init__.py @@ -6,12 +6,13 @@ from .eip6110 import EIP6110SpecBuilder from .eip7002 import EIP7002SpecBuilder from .whisk import WhiskSpecBuilder +from .peerdas import PeerDASSpecBuilder spec_builders = { builder.fork: builder for builder in ( Phase0SpecBuilder, AltairSpecBuilder, BellatrixSpecBuilder, CapellaSpecBuilder, DenebSpecBuilder, - EIP6110SpecBuilder, EIP7002SpecBuilder, WhiskSpecBuilder, + EIP6110SpecBuilder, EIP7002SpecBuilder, WhiskSpecBuilder, PeerDASSpecBuilder, ) } diff --git a/pysetup/spec_builders/peerdas.py b/pysetup/spec_builders/peerdas.py new file mode 100644 index 0000000000..aea630ad76 --- /dev/null +++ b/pysetup/spec_builders/peerdas.py @@ -0,0 +1,27 @@ +from typing import Dict + +from .base import BaseSpecBuilder +from ..constants import PEERDAS + + +class PeerDASSpecBuilder(BaseSpecBuilder): + fork: str = PEERDAS + + @classmethod + def imports(cls, preset_name: str): + return f''' +from eth2spec.deneb import {preset_name} as deneb +''' + + @classmethod + def hardcoded_custom_type_dep_constants(cls, spec_object) -> str: + return { + 'NUMBER_OF_COLUMNS': spec_object.preset_vars['NUMBER_OF_COLUMNS'].value, + 'FIELD_ELEMENTS_PER_CELL': spec_object.preset_vars['FIELD_ELEMENTS_PER_CELL'].value, + } + + @classmethod + def hardcoded_func_dep_presets(cls, spec_object) -> Dict[str, str]: + return { + 'KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH': spec_object.preset_vars['KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH'].value, + } \ No newline at end of file diff --git a/specs/_features/peerdas/das-core.md b/specs/_features/peerdas/das-core.md new file mode 100644 index 0000000000..4d94e5fb27 --- /dev/null +++ b/specs/_features/peerdas/das-core.md @@ -0,0 +1,240 @@ +# Peer Data Availability Sampling -- Core + +**Notice**: This document is a work-in-progress for researchers and implementers. + +## Table of contents + + + + + +- [Custom types](#custom-types) +- [Configuration](#configuration) + - [Data size](#data-size) + - [Custody setting](#custody-setting) + - [Helper functions](#helper-functions) + - [`get_custody_lines`](#get_custody_lines) + - [`compute_extended_data`](#compute_extended_data) + - [`compute_extended_matrix`](#compute_extended_matrix) + - [`compute_samples_and_proofs`](#compute_samples_and_proofs) + - [`get_data_column_sidecars`](#get_data_column_sidecars) +- [Custody](#custody) + - [Custody requirement](#custody-requirement) + - [Public, deterministic selection](#public-deterministic-selection) +- [Peer discovery](#peer-discovery) +- [Extended data](#extended-data) +- [Column gossip](#column-gossip) + - [Parameters](#parameters) + - [Reconstruction and cross-seeding](#reconstruction-and-cross-seeding) +- [Peer sampling](#peer-sampling) +- [Peer scoring](#peer-scoring) +- [DAS providers](#das-providers) +- [A note on fork choice](#a-note-on-fork-choice) +- [FAQs](#faqs) + - [Row (blob) custody](#row-blob-custody) + + + + +## Custom types + +We define the following Python custom types for type hinting and readability: + +| Name | SSZ equivalent | Description | +| - | - | - | +| `DataCell` | `Vector[BLSFieldElement, FIELD_ELEMENTS_PER_CELL]` | The data unit of a cell in the extended data matrix | +| `DataColumn` | `List[DataCell, MAX_BLOBS_PER_BLOCK]` | The data of each column in PeerDAS | +| `ExtendedMatrix` | `List[DataCell, MAX_BLOBS_PER_BLOCK * NUMBER_OF_COLUMNS]` | The full data with blobs and one-dimensional erasure coding extension | +| `FlatExtendedMatrix` | `List[BLSFieldElement, MAX_BLOBS_PER_BLOCK * FIELD_ELEMENTS_PER_BLOB * NUMBER_OF_COLUMNS]` | The flattened format of `ExtendedMatrix` | +| `LineIndex` | `uint64` | The index of the rows or columns in `FlatExtendedMatrix` matrix | + +## Configuration + +### Data size + +| Name | Value | Description | +| - | - | - | +| `FIELD_ELEMENTS_PER_CELL` | `uint64(2**6)` (= 64) | Elements per `DataCell` | +| `NUMBER_OF_COLUMNS` | `uint64((FIELD_ELEMENTS_PER_BLOB * 2) // FIELD_ELEMENTS_PER_CELL)` (= 128) | Number of columns in the extended data matrix. | + +### Custody setting + +| Name | Value | Description | +| - | - | - | +| `SAMPLES_PER_SLOT` | `8` | Number of random samples a node queries per slot | +| `CUSTODY_REQUIREMENT` | `2` | Minimum number of columns an honest node custodies and serves samples from | +| `TARGET_NUMBER_OF_PEERS` | `70` | Suggested minimum peer count | + +### Helper functions + +#### `get_custody_lines` + +```python +def get_custody_lines(node_id: NodeID, custody_size: uint64) -> Sequence[LineIndex]: + assert custody_size <= NUMBER_OF_COLUMNS + all_items = list(range(NUMBER_OF_COLUMNS)) + line_index = node_id % NUMBER_OF_COLUMNS + return [LineIndex(all_items[(line_index + i) % len(all_items)]) for i in range(custody_size)] +``` + +#### `compute_extended_data` + +```python +def compute_extended_data(data: Sequence[BLSFieldElement]) -> Sequence[BLSFieldElement]: + # TODO + # pylint: disable=unused-argument + ... +``` + +#### `compute_extended_matrix` + +```python +def compute_extended_matrix(blobs: Sequence[Blob]) -> FlatExtendedMatrix: + matrix = [compute_extended_data(blob) for blob in blobs] + return FlatExtendedMatrix(matrix) +``` + +#### `compute_samples_and_proofs` + +```python +def compute_samples_and_proofs(blob: Blob) -> Tuple[ + Vector[DataCell, NUMBER_OF_COLUMNS], + Vector[KZGProof, NUMBER_OF_COLUMNS]]: + """ + Defined in polynomial-commitments-sampling.md + """ + # pylint: disable=unused-argument + ... +``` + +#### `get_data_column_sidecars` + +```python +def get_data_column_sidecars(signed_block: SignedBeaconBlock, + blobs: Sequence[Blob]) -> Sequence[DataColumnSidecar]: + signed_block_header = compute_signed_block_header(signed_block) + block = signed_block.message + kzg_commitments_inclusion_proof = compute_merkle_proof( + block.body, + get_generalized_index(BeaconBlockBody, 'blob_kzg_commitments'), + ) + cells_and_proofs = [compute_samples_and_proofs(blob) for blob in blobs] + blob_count = len(blobs) + cells = [cells_and_proofs[i][0] for i in range(blob_count)] + proofs = [cells_and_proofs[i][1] for i in range(blob_count)] + sidecars = [] + for column_index in range(NUMBER_OF_COLUMNS): + column = DataColumn([cells[row_index][column_index] + for row_index in range(blob_count)]) + kzg_proof_of_column = [proofs[row_index][column_index] + for row_index in range(blob_count)] + sidecars.append(DataColumnSidecar( + index=column_index, + column=column, + kzg_commitments=block.body.blob_kzg_commitments, + kzg_proofs=kzg_proof_of_column, + signed_block_header=signed_block_header, + kzg_commitments_inclusion_proof=kzg_commitments_inclusion_proof, + )) + return sidecars +``` + +## Custody + +### Custody requirement + +Each node downloads and custodies a minimum of `CUSTODY_REQUIREMENT` columns per slot. The particular columns that the node is required to custody are selected pseudo-randomly (more on this below). + +A node *may* choose to custody and serve more than the minimum honesty requirement. Such a node explicitly advertises a number greater than `CUSTODY_REQUIREMENT` via the peer discovery mechanism -- for example, in their ENR (e.g. `custody_lines: 8` if the node custodies `8` columns each slot) -- up to a `NUMBER_OF_COLUMNS` (i.e. a super-full node). + +A node stores the custodied columns for the duration of the pruning period and responds to peer requests for samples on those columns. + +### Public, deterministic selection + +The particular columns that a node custodies are selected pseudo-randomly as a function (`get_custody_lines`) of the node-id and custody size -- importantly this function can be run by any party as the inputs are all public. + +*Note*: increasing the `custody_size` parameter for a given `node_id` extends the returned list (rather than being an entirely new shuffle) such that if `custody_size` is unknown, the default `CUSTODY_REQUIREMENT` will be correct for a subset of the node's custody. + +## Peer discovery + +At each slot, a node needs to be able to readily sample from *any* set of columns. To this end, a node should find and maintain a set of diverse and reliable peers that can regularly satisfy their sampling demands. + +A node runs a background peer discovery process, maintaining at least `TARGET_NUMBER_OF_PEERS` of various custody distributions (both custody_size and column assignments). The combination of advertised `custody_size` size and public node-id make this readily and publicly accessible. + +`TARGET_NUMBER_OF_PEERS` should be tuned upward in the event of failed sampling. + +*Note*: while high-capacity and super-full nodes are high value with respect to satisfying sampling requirements, a node should maintain a distribution across node capacities as to not centralize the p2p graph too much (in the extreme becomes hub/spoke) and to distribute sampling load better across all nodes. + +*Note*: A DHT-based peer discovery mechanism is expected to be utilized in the above. The beacon-chain network currently utilizes discv5 in a similar method as described for finding peers of particular distributions of attestation subnets. Additional peer discovery methods are valuable to integrate (e.g., latent peer discovery via libp2p gossipsub) to add a defense in breadth against one of the discovery methods being attacked. + +## Extended data + +In this construction, we extend the blobs using a one-dimensional erasure coding extension. The matrix comprises maximum `MAX_BLOBS_PER_BLOCK` rows and fixed `NUMBER_OF_COLUMNS` columns, with each row containing a `Blob` and its corresponding extension. + +## Column gossip + +### Parameters + +For each column -- use `data_column_sidecar_{subnet_id}` subnets, where each column index maps to the `subnet_id`. The sidecars can be computed with `get_data_column_sidecars(signed_block: SignedBeaconBlock, blobs: Sequence[Blob])` helper. + +To custody a particular column, a node joins the respective gossip subnet. Verifiable samples from their respective column are gossiped on the assigned subnet. + +### Reconstruction and cross-seeding + +If the node obtains 50%+ of all the columns, they can reconstruct the full data matrix via `recover_samples_impl` helper. + +If a node fails to sample a peer or fails to get a column on the column subnet, a node can utilize the Req/Resp message to query the missing column from other peers. + +Once the node obtain the column, the node should send the missing columns to the column subnets. + +*Note*: A node always maintains a matrix view of the rows and columns they are following, able to cross-reference and cross-seed in either direction. + +*Note*: There are timing considerations to analyze -- at what point does a node consider samples missing and choose to reconstruct and cross-seed. + +*Note*: There may be anti-DoS and quality-of-service considerations around how to send samples and consider samples -- is each individual sample a message or are they sent in aggregate forms. + +## Peer sampling + +At each slot, a node makes (locally randomly determined) `SAMPLES_PER_SLOT` queries for samples from their peers via `DataColumnSidecarByRoot` request. A node utilizes `get_custody_lines` helper to determine which peer(s) to request from. If a node has enough good/honest peers across all rows and columns, this has a high chance of success. + +## Peer scoring + +Due to the deterministic custody functions, a node knows exactly what a peer should be able to respond to. In the event that a peer does not respond to samples of their custodied rows/columns, a node may downscore or disconnect from a peer. + +## DAS providers + +A DAS provider is a consistently-available-for-DAS-queries, super-full (or high capacity) node. To the p2p, these look just like other nodes but with high advertised capacity, and they should generally be able to be latently found via normal discovery. + +DAS providers can also be found out-of-band and configured into a node to connect to directly and prioritize. Nodes can add some set of these to their local configuration for persistent connection to bolster their DAS quality of service. + +Such direct peering utilizes a feature supported out of the box today on all nodes and can complement (and reduce attackability and increase quality-of-service) alternative peer discovery mechanisms. + +## A note on fork choice + +*Fork choice spec TBD, but it will just be a replacement of `is_data_available()` call in Deneb with column sampling instead of full download. Note the `is_data_available(slot_N)` will likely do a `-1` follow distance so that you just need to check the availability of slot `N-1` for slot `N` (starting with the block proposer of `N`).* + +The fork choice rule (essentially a DA filter) is *orthogonal to a given DAS design*, other than the efficiency of a particular design impacting it. + +In any DAS design, there are probably a few degrees of freedom around timing, acceptability of short-term re-orgs, etc. + +For example, the fork choice rule might require validators to do successful DAS on slot N to be able to include block of slot `N` in its fork choice. That's the tightest DA filter. But trailing filters are also probably acceptable, knowing that there might be some failures/short re-orgs but that they don't hurt the aggregate security. For example, the rule could be — DAS must be completed for slot N-1 for a child block in N to be included in the fork choice. + +Such trailing techniques and their analysis will be valuable for any DAS construction. The question is — can you relax how quickly you need to do DA and in the worst case not confirm unavailable data via attestations/finality, and what impact does it have on short-term re-orgs and fast confirmation rules. + +## FAQs + +### Row (blob) custody + +In the one-dimension construction, a node samples the peers by requesting the whole `DataColumn`. In reconstruction, a node can reconstruct all the blobs by 50% of the columns. Note that nodes can still download the row via `blob_sidecar_{subnet_id}` subnets. + +The potential benefits of having row custody could include: + +1. Allow for more "natural" distribution of data to consumers -- e.g., roll-ups -- but honestly, they won't know a priori which row their blob is going to be included in in the block, so they would either need to listen to all rows or download a particular row after seeing the block. The former looks just like listening to column [0, N) and the latter is req/resp instead of gossiping. +2. Help with some sort of distributed reconstruction. Those with full rows can compute extensions and seed missing samples to the network. This would either need to be able to send individual points on the gossip or would need some sort of req/resp faculty, potentially similar to an `IHAVEPOINTBITFIELD` and `IWANTSAMPLE`. + +However, for simplicity, we don't assign row custody assignments to nodes in the current design. + + +### Subnet stability + +To start with a simple, stable backbone, for now, we don't shuffle the subnet assignments via the deterministic custody selection helper `get_custody_lines`. However, staggered rotation likely needs to happen on the order of the pruning period to ensure subnets can be utilized for recovery. For example, introducing an `epoch` argument allows the function to maintain stability over many epochs. diff --git a/specs/_features/peerdas/fork.md b/specs/_features/peerdas/fork.md new file mode 100644 index 0000000000..4b141fe913 --- /dev/null +++ b/specs/_features/peerdas/fork.md @@ -0,0 +1,124 @@ +# PeerDAS -- Fork Logic + +**Notice**: This document is a work-in-progress for researchers and implementers. + +## Table of contents + + + + +- [Introduction](#introduction) +- [Configuration](#configuration) +- [Helper functions](#helper-functions) + - [Misc](#misc) + - [Modified `compute_fork_version`](#modified-compute_fork_version) +- [Fork to PeerDAS](#fork-to-peerdas) + - [Fork trigger](#fork-trigger) + - [Upgrading the state](#upgrading-the-state) + + + +## Introduction + +This document describes the process of PeerDAS upgrade. + +## Configuration + +Warning: this configuration is not definitive. + +| Name | Value | +| - | - | +| `PEERDAS_FORK_VERSION` | `Version('0x05000000')` | +| `PEERDAS_FORK_EPOCH` | `Epoch(18446744073709551615)` **TBD** | + +## Helper functions + +### Misc + +#### Modified `compute_fork_version` + +```python +def compute_fork_version(epoch: Epoch) -> Version: + """ + Return the fork version at the given ``epoch``. + """ + if epoch >= PEERDAS_FORK_EPOCH: + return PEERDAS_FORK_VERSION + if epoch >= DENEB_FORK_EPOCH: + return DENEB_FORK_VERSION + if epoch >= CAPELLA_FORK_EPOCH: + return CAPELLA_FORK_VERSION + if epoch >= BELLATRIX_FORK_EPOCH: + return BELLATRIX_FORK_VERSION + if epoch >= ALTAIR_FORK_EPOCH: + return ALTAIR_FORK_VERSION + return GENESIS_FORK_VERSION +``` + +## Fork to PeerDAS + +### Fork trigger + +TBD. This fork is defined for testing purposes, the EIP may be combined with other consensus-layer upgrade. +For now, we assume the condition will be triggered at epoch `PEERDAS_FORK_EPOCH`. + +Note that for the pure PeerDAS networks, we don't apply `upgrade_to_peerdas` since it starts with PeerDAS version logic. + +### Upgrading the state + +If `state.slot % SLOTS_PER_EPOCH == 0` and `compute_epoch_at_slot(state.slot) == PEERDAS_FORK_EPOCH`, +an irregular state change is made to upgrade to PeerDAS. + +```python +def upgrade_to_peerdas(pre: deneb.BeaconState) -> BeaconState: + epoch = deneb.get_current_epoch(pre) + post = BeaconState( + # Versioning + genesis_time=pre.genesis_time, + genesis_validators_root=pre.genesis_validators_root, + slot=pre.slot, + fork=Fork( + previous_version=pre.fork.current_version, + current_version=PEERDAS_FORK_VERSION, # [Modified in PeerDAS] + epoch=epoch, + ), + # History + latest_block_header=pre.latest_block_header, + block_roots=pre.block_roots, + state_roots=pre.state_roots, + historical_roots=pre.historical_roots, + # Eth1 + eth1_data=pre.eth1_data, + eth1_data_votes=pre.eth1_data_votes, + eth1_deposit_index=pre.eth1_deposit_index, + # Registry + validators=pre.validators, + balances=pre.balances, + # Randomness + randao_mixes=pre.randao_mixes, + # Slashings + slashings=pre.slashings, + # Participation + previous_epoch_participation=pre.previous_epoch_participation, + current_epoch_participation=pre.current_epoch_participation, + # Finality + justification_bits=pre.justification_bits, + previous_justified_checkpoint=pre.previous_justified_checkpoint, + current_justified_checkpoint=pre.current_justified_checkpoint, + finalized_checkpoint=pre.finalized_checkpoint, + # Inactivity + inactivity_scores=pre.inactivity_scores, + # Sync + current_sync_committee=pre.current_sync_committee, + next_sync_committee=pre.next_sync_committee, + # Execution-layer + latest_execution_payload_header=pre.latest_execution_payload_header, + # Withdrawals + next_withdrawal_index=pre.next_withdrawal_index, + next_withdrawal_validator_index=pre.next_withdrawal_validator_index, + # Deep history valid from Capella onwards + historical_summaries=pre.historical_summaries, + ) + + return post +``` diff --git a/specs/_features/peerdas/p2p-interface.md b/specs/_features/peerdas/p2p-interface.md new file mode 100644 index 0000000000..e8ed52d43e --- /dev/null +++ b/specs/_features/peerdas/p2p-interface.md @@ -0,0 +1,197 @@ +# Peer Data Availability Sampling -- Networking + +**Notice**: This document is a work-in-progress for researchers and implementers. + +## Table of contents + + + + + +- [Modifications in PeerDAS](#modifications-in-peerdas) + - [Preset](#preset) + - [Configuration](#configuration) + - [Containers](#containers) + - [`DataColumnSidecar`](#datacolumnsidecar) + - [`DataColumnIdentifier`](#datacolumnidentifier) + - [Helpers](#helpers) + - [`verify_sample_proof_batch`](#verify_sample_proof_batch) + - [`verify_data_column_sidecar_kzg_proof`](#verify_data_column_sidecar_kzg_proof) + - [`verify_data_column_sidecar_inclusion_proof`](#verify_data_column_sidecar_inclusion_proof) + - [`compute_subnet_for_data_column_sidecar`](#compute_subnet_for_data_column_sidecar) + - [The gossip domain: gossipsub](#the-gossip-domain-gossipsub) + - [Topics and messages](#topics-and-messages) + - [Samples subnets](#samples-subnets) + - [`data_column_sidecar_{subnet_id}`](#data_column_sidecar_subnet_id) + - [The Req/Resp domain](#the-reqresp-domain) + - [Messages](#messages) + - [DataColumnSidecarByRoot v1](#datacolumnsidecarbyroot-v1) + + + + +## Modifications in PeerDAS + +### Preset + +| Name | Value | Description | +|------------------------------------------|-----------------------------------|---------------------------------------------------------------------| +| `KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH` | `uint64(floorlog2(get_generalized_index(BeaconBlockBody, 'blob_kzg_commitments')))` (= 4) | Merkle proof index for `blob_kzg_commitments` | + +### Configuration + +| Name | Value | Description | +|------------------------------------------|-----------------------------------|---------------------------------------------------------------------| +| `DATA_COLUMN_SIDECAR_SUBNET_COUNT` | `32` | The number of data column sidecar subnets used in the gossipsub protocol. | + +### Containers + +#### `DataColumnSidecar` + +```python +class DataColumnSidecar(Container): + index: LineIndex # Index of column in extended matrix + column: DataColumn + kzg_commitments: List[KZGCommitment, MAX_BLOB_COMMITMENTS_PER_BLOCK] + kzg_proofs: List[KZGProof, MAX_BLOB_COMMITMENTS_PER_BLOCK] + signed_block_header: SignedBeaconBlockHeader + kzg_commitments_inclusion_proof: Vector[Bytes32, KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH] +``` + +#### `DataColumnIdentifier` + +```python +class DataColumnIdentifier(Container): + block_root: Root + index: LineIndex +``` + +### Helpers + +##### `verify_sample_proof_batch` + +```python +def verify_sample_proof_batch( + row_commitments: Sequence[KZGCommitment], + row_ids: Sequence[LineIndex], + column_ids: Sequence[LineIndex], + datas: Sequence[Vector[BLSFieldElement, FIELD_ELEMENTS_PER_CELL]], + proofs: Sequence[KZGProof]) -> bool: + """ + Defined in polynomial-commitments-sampling.md + """ + # pylint: disable=unused-argument + ... +``` + +##### `verify_data_column_sidecar_kzg_proof` + +```python +def verify_data_column_sidecar_kzg_proof(sidecar: DataColumnSidecar) -> bool: + """ + Verify if the proofs are correct + """ + row_ids = [LineIndex(i) for i in range(len(sidecar.column))] + assert len(sidecar.column) == len(sidecar.kzg_commitments) == len(sidecar.kzg_proofs) + + # KZG batch verifies that the cells match the corresponding commitments and proofs + return verify_sample_proof_batch( + row_commitments=sidecar.kzg_commitments, + row_ids=row_ids, # all rows + column_ids=[sidecar.index], + datas=sidecar.column, + proofs=sidecar.kzg_proofs, + ) +``` + +##### `verify_data_column_sidecar_inclusion_proof` + +```python +def verify_data_column_sidecar_inclusion_proof(sidecar: DataColumnSidecar) -> bool: + """ + Verify if the given KZG commitments included in the given beacon block. + """ + gindex = get_subtree_index(get_generalized_index(BeaconBlockBody, 'blob_kzg_commitments')) + return is_valid_merkle_branch( + leaf=hash_tree_root(sidecar.kzg_commitments), + branch=sidecar.kzg_commitments_inclusion_proof, + depth=KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH, + index=gindex, + root=sidecar.signed_block_header.message.body_root, + ) +``` + +##### `compute_subnet_for_data_column_sidecar` + +```python +def compute_subnet_for_data_column_sidecar(column_index: LineIndex) -> SubnetID: + return SubnetID(column_index % DATA_COLUMN_SIDECAR_SUBNET_COUNT) +``` + + +### The gossip domain: gossipsub + +Some gossip meshes are upgraded in the fork of Pe to support upgraded types. + +#### Topics and messages + +##### Samples subnets + +###### `data_column_sidecar_{subnet_id}` + +This topic is used to propagate column sidecars, where each column maps to some `subnet_id`. + +The *type* of the payload of this topic is `DataColumnSidecar`. + +The following validations MUST pass before forwarding the `sidecar: DataColumnSidecar` on the network, assuming the alias `block_header = sidecar.signed_block_header.message`: + +- _[REJECT]_ The sidecar's index is consistent with `NUMBER_OF_COLUMNS` -- i.e. `sidecar.index < NUMBER_OF_COLUMNS`. +- _[REJECT]_ The sidecar is for the correct subnet -- i.e. `compute_subnet_for_data_column_sidecar(sidecar.index) == subnet_id`. +- _[IGNORE]_ The sidecar is not from a future slot (with a `MAXIMUM_GOSSIP_CLOCK_DISPARITY` allowance) -- i.e. validate that `block_header.slot <= current_slot` (a client MAY queue future sidecars for processing at the appropriate slot). +- _[IGNORE]_ The sidecar is from a slot greater than the latest finalized slot -- i.e. validate that `block_header.slot > compute_start_slot_at_epoch(state.finalized_checkpoint.epoch)` +- _[REJECT]_ The proposer signature of `sidecar.signed_block_header`, is valid with respect to the `block_header.proposer_index` pubkey. +- _[IGNORE]_ The sidecar's block's parent (defined by `block_header.parent_root`) has been seen (via both gossip and non-gossip sources) (a client MAY queue sidecars for processing once the parent block is retrieved). +- _[REJECT]_ The sidecar's block's parent (defined by `block_header.parent_root`) passes validation. +- _[REJECT]_ The sidecar is from a higher slot than the sidecar's block's parent (defined by `block_header.parent_root`). +- _[REJECT]_ The current finalized_checkpoint is an ancestor of the sidecar's block -- i.e. `get_checkpoint_block(store, block_header.parent_root, store.finalized_checkpoint.epoch) == store.finalized_checkpoint.root`. +- _[REJECT]_ The sidecar's `kzg_commitments` field inclusion proof is valid as verified by `verify_data_column_sidecar_inclusion_proof(sidecar)`. +- _[REJECT]_ The sidecar's column data is valid as verified by `verify_data_column_sidecar_kzg_proof(sidecar)`. +- _[IGNORE]_ The sidecar is the first sidecar for the tuple `(block_header.slot, block_header.proposer_index, sidecar.index)` with valid header signature, sidecar inclusion proof, and kzg proof. +- _[REJECT]_ The sidecar is proposed by the expected `proposer_index` for the block's slot in the context of the current shuffling (defined by `block_header.parent_root`/`block_header.slot`). + If the `proposer_index` cannot immediately be verified against the expected shuffling, the sidecar MAY be queued for later processing while proposers for the block's branch are calculated -- in such a case _do not_ `REJECT`, instead `IGNORE` this message. + +*Note:* In the `verify_data_column_sidecar_inclusion_proof(sidecar)` check, for all the sidecars of the same block, it verifies against the same set of `kzg_commitments` of the given beacon beacon. Client can choose to cache the result of the arguments tuple `(sidecar.kzg_commitments, sidecar.kzg_commitments_inclusion_proof, sidecar.signed_block_header)`. + +### The Req/Resp domain + +#### Messages + +##### DataColumnSidecarByRoot v1 + +**Protocol ID:** `/eth2/beacon_chain/req/data_column_sidecar_by_root/1/` + +*[New in Deneb:EIP4844]* + +The `` field is calculated as `context = compute_fork_digest(fork_version, genesis_validators_root)`: + +[1]: # (eth2spec: skip) + +| `fork_version` | Chunk SSZ type | +|--------------------------|-------------------------------| +| `PEERDAS_FORK_VERSION` | `peerdas.DataColumnSidecar` | + +Request Content: + +``` +( + DataColumnIdentifier +) +``` + +Response Content: + +``` +( + DataColumnSidecar +) +``` diff --git a/specs/deneb/validator.md b/specs/deneb/validator.md index 3e2c91f817..900da37a1f 100644 --- a/specs/deneb/validator.md +++ b/specs/deneb/validator.md @@ -63,6 +63,19 @@ class GetPayloadResponse(object): blobs_bundle: BlobsBundle # [New in Deneb:EIP4844] ``` +```python +def compute_signed_block_header(signed_block: SignedBeaconBlock) -> SignedBeaconBlockHeader: + block = signed_block.message + block_header = BeaconBlockHeader( + slot=block.slot, + proposer_index=block.proposer_index, + parent_root=block.parent_root, + state_root=block.state_root, + body_root=hash_tree_root(block.body), + ) + return SignedBeaconBlockHeader(message=block_header, signature=signed_block.signature) +``` + ## Protocol ### `ExecutionEngine` @@ -147,14 +160,7 @@ def get_blob_sidecars(signed_block: SignedBeaconBlock, blobs: Sequence[Blob], blob_kzg_proofs: Sequence[KZGProof]) -> Sequence[BlobSidecar]: block = signed_block.message - block_header = BeaconBlockHeader( - slot=block.slot, - proposer_index=block.proposer_index, - parent_root=block.parent_root, - state_root=block.state_root, - body_root=hash_tree_root(block.body), - ) - signed_block_header = SignedBeaconBlockHeader(message=block_header, signature=signed_block.signature) + signed_block_header = compute_signed_block_header(signed_block) return [ BlobSidecar( index=index, diff --git a/tests/core/pyspec/eth2spec/test/context.py b/tests/core/pyspec/eth2spec/test/context.py index 7289fdf0fa..6cf15c1020 100644 --- a/tests/core/pyspec/eth2spec/test/context.py +++ b/tests/core/pyspec/eth2spec/test/context.py @@ -10,12 +10,13 @@ from eth2spec.deneb import mainnet as spec_deneb_mainnet, minimal as spec_deneb_minimal from eth2spec.eip6110 import mainnet as spec_eip6110_mainnet, minimal as spec_eip6110_minimal from eth2spec.eip7002 import mainnet as spec_eip7002_mainnet, minimal as spec_eip7002_minimal +from eth2spec.peerdas import mainnet as spec_peerdas_mainnet, minimal as spec_peerdas_minimal from eth2spec.utils import bls from .exceptions import SkippedTest from .helpers.constants import ( PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, - EIP6110, EIP7002, + EIP6110, EIP7002, PEERDAS, MINIMAL, MAINNET, ALL_PHASES, ALL_FORK_UPGRADES, @@ -85,6 +86,7 @@ class ForkMeta: DENEB: spec_deneb_minimal, EIP6110: spec_eip6110_minimal, EIP7002: spec_eip7002_minimal, + PEERDAS: spec_peerdas_minimal, }, MAINNET: { PHASE0: spec_phase0_mainnet, @@ -94,6 +96,7 @@ class ForkMeta: DENEB: spec_deneb_mainnet, EIP6110: spec_eip6110_mainnet, EIP7002: spec_eip7002_mainnet, + PEERDAS: spec_peerdas_mainnet, }, } @@ -565,6 +568,7 @@ def wrapper(*args, spec: Spec, **kw): with_deneb_and_later = with_all_phases_from(DENEB) with_eip6110_and_later = with_all_phases_from(EIP6110) with_eip7002_and_later = with_all_phases_from(EIP7002) +with_peerdas_and_later = with_all_phases_from(PEERDAS) class quoted_str(str): diff --git a/tests/core/pyspec/eth2spec/test/helpers/constants.py b/tests/core/pyspec/eth2spec/test/helpers/constants.py index 82e4f9d0a5..b8eca5d161 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/constants.py +++ b/tests/core/pyspec/eth2spec/test/helpers/constants.py @@ -18,6 +18,7 @@ DAS = SpecForkName('das') EIP6110 = SpecForkName('eip6110') EIP7002 = SpecForkName('eip7002') +PEERDAS = SpecForkName('peerdas') # # SpecFork settings @@ -34,6 +35,7 @@ # Experimental patches EIP6110, EIP7002, + PEERDAS, ) # The forks that have light client specs LIGHT_CLIENT_TESTING_FORKS = (*[item for item in MAINNET_FORKS if item != PHASE0], DENEB) diff --git a/tests/core/pyspec/eth2spec/test/helpers/das.py b/tests/core/pyspec/eth2spec/test/helpers/das.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/core/pyspec/eth2spec/test/helpers/fork_transition.py b/tests/core/pyspec/eth2spec/test/helpers/fork_transition.py index 80c54d9c1f..2fcd83f79a 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/fork_transition.py +++ b/tests/core/pyspec/eth2spec/test/helpers/fork_transition.py @@ -17,6 +17,7 @@ DENEB, EIP6110, EIP7002, + PEERDAS, ) from eth2spec.test.helpers.deposits import ( prepare_state_and_deposit, @@ -164,6 +165,8 @@ def do_fork(state, spec, post_spec, fork_epoch, with_block=True, sync_aggregate= state = post_spec.upgrade_to_eip6110(state) elif post_spec.fork == EIP7002: state = post_spec.upgrade_to_eip7002(state) + elif post_spec.fork == PEERDAS: + state = post_spec.update_to_peerdas(state) assert state.fork.epoch == fork_epoch diff --git a/tests/core/pyspec/eth2spec/test/helpers/forks.py b/tests/core/pyspec/eth2spec/test/helpers/forks.py index 492af47fe3..7d7d2c735f 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/forks.py +++ b/tests/core/pyspec/eth2spec/test/helpers/forks.py @@ -1,10 +1,12 @@ from .constants import ( PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, - EIP6110, EIP7002, + EIP6110, EIP7002, PEERDAS, ) def is_post_fork(a, b): + if a == PEERDAS: + return b in [PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, PEERDAS] if a == EIP7002: return b in [PHASE0, ALTAIR, BELLATRIX, CAPELLA, EIP7002] if a == EIP6110: diff --git a/tests/core/pyspec/eth2spec/test/helpers/genesis.py b/tests/core/pyspec/eth2spec/test/helpers/genesis.py index e55bdef5ce..97c8be1230 100644 --- a/tests/core/pyspec/eth2spec/test/helpers/genesis.py +++ b/tests/core/pyspec/eth2spec/test/helpers/genesis.py @@ -1,5 +1,5 @@ from eth2spec.test.helpers.constants import ( - ALTAIR, BELLATRIX, CAPELLA, DENEB, EIP6110, EIP7002, + ALTAIR, BELLATRIX, CAPELLA, DENEB, EIP6110, EIP7002, PEERDAS, ) from eth2spec.test.helpers.execution_payload import ( compute_el_header_block_hash, @@ -93,6 +93,9 @@ def create_genesis_state(spec, validator_balances, activation_threshold): elif spec.fork == EIP7002: previous_version = spec.config.CAPELLA_FORK_VERSION current_version = spec.config.EIP7002_FORK_VERSION + elif spec.fork == PEERDAS: + previous_version = spec.config.DENEB_FORK_VERSION + current_version = spec.config.PEERDAS_FORK_VERSION state = spec.BeaconState( genesis_time=0, diff --git a/tests/core/pyspec/eth2spec/test/peerdas/__init__.py b/tests/core/pyspec/eth2spec/test/peerdas/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/core/pyspec/eth2spec/test/peerdas/merkle_proof/__init__.py b/tests/core/pyspec/eth2spec/test/peerdas/merkle_proof/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/core/pyspec/eth2spec/test/peerdas/merkle_proof/test_single_merkle_proof.py b/tests/core/pyspec/eth2spec/test/peerdas/merkle_proof/test_single_merkle_proof.py new file mode 100644 index 0000000000..2ea9fb41ac --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/peerdas/merkle_proof/test_single_merkle_proof.py @@ -0,0 +1,74 @@ +import random + +from eth2spec.test.context import ( + spec_state_test, + with_peerdas_and_later, + with_test_suite_name, +) +from eth2spec.test.helpers.block import ( + build_empty_block_for_next_slot, + sign_block, +) +from eth2spec.test.helpers.execution_payload import ( + compute_el_block_hash, +) +from eth2spec.test.helpers.sharding import ( + get_sample_opaque_tx, +) +from eth2spec.debug.random_value import ( + RandomizationMode, + get_random_ssz_object, +) + + +def _run_blob_kzg_commitments_merkle_proof_test(spec, state, rng=None): + opaque_tx, blobs, blob_kzg_commitments, proofs = get_sample_opaque_tx(spec, blob_count=1) + if rng is None: + block = build_empty_block_for_next_slot(spec, state) + else: + block = get_random_ssz_object( + rng, + spec.BeaconBlock, + max_bytes_length=2000, + max_list_length=2000, + mode=RandomizationMode, + chaos=True, + ) + block.body.blob_kzg_commitments = blob_kzg_commitments + block.body.execution_payload.transactions = [opaque_tx] + block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) + signed_block = sign_block(spec, state, block, proposer_index=0) + column_sidcars = spec.get_data_column_sidecars(signed_block, blobs) + column_sidcar = column_sidcars[0] + + yield "object", block.body + kzg_commitments_inclusion_proof = column_sidcar.kzg_commitments_inclusion_proof + gindex = spec.get_generalized_index(spec.BeaconBlockBody, 'blob_kzg_commitments') + yield "proof", { + "leaf": "0x" + column_sidcar.kzg_commitments.hash_tree_root().hex(), + "leaf_index": gindex, + "branch": ['0x' + root.hex() for root in kzg_commitments_inclusion_proof] + } + assert spec.is_valid_merkle_branch( + leaf=column_sidcar.kzg_commitments.hash_tree_root(), + branch=column_sidcar.kzg_commitments_inclusion_proof, + depth=spec.floorlog2(gindex), + index=spec.get_subtree_index(gindex), + root=column_sidcar.signed_block_header.message.body_root, + ) + assert spec.verify_data_column_sidecar_inclusion_proof(column_sidcar) + + +@with_test_suite_name("BeaconBlockBody") +@with_peerdas_and_later +@spec_state_test +def test_blob_kzg_commitments_merkle_proof__basic(spec, state): + yield from _run_blob_kzg_commitments_merkle_proof_test(spec, state) + + +@with_test_suite_name("BeaconBlockBody") +@with_peerdas_and_later +@spec_state_test +def test_blob_kzg_commitments_merkle_proof__random_block_1(spec, state): + rng = random.Random(1111) + yield from _run_blob_kzg_commitments_merkle_proof_test(spec, state, rng=rng) diff --git a/tests/core/pyspec/eth2spec/test/peerdas/unittests/__init__.py b/tests/core/pyspec/eth2spec/test/peerdas/unittests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_config_invariants.py b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_config_invariants.py new file mode 100644 index 0000000000..018a0f9552 --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_config_invariants.py @@ -0,0 +1,17 @@ +from eth2spec.test.context import ( + spec_test, + single_phase, + with_peerdas_and_later, +) + + +@with_peerdas_and_later +@spec_test +@single_phase +def test_invariants(spec): + assert spec.FIELD_ELEMENTS_PER_BLOB % spec.FIELD_ELEMENTS_PER_CELL == 0 + assert spec.FIELD_ELEMENTS_PER_BLOB * 2 % spec.NUMBER_OF_COLUMNS == 0 + assert spec.SAMPLES_PER_SLOT <= spec.NUMBER_OF_COLUMNS + assert spec.CUSTODY_REQUIREMENT <= spec.NUMBER_OF_COLUMNS + assert spec.DATA_COLUMN_SIDECAR_SUBNET_COUNT <= spec.NUMBER_OF_COLUMNS + assert spec.NUMBER_OF_COLUMNS % spec.DATA_COLUMN_SIDECAR_SUBNET_COUNT == 0 diff --git a/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_custody.py b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_custody.py new file mode 100644 index 0000000000..890623d040 --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_custody.py @@ -0,0 +1,41 @@ +from eth2spec.test.context import ( + expect_assertion_error, + spec_test, + single_phase, + with_peerdas_and_later, +) + + +@with_peerdas_and_later +@spec_test +@single_phase +def test_get_custody_lines_peers_within_number_of_columns(spec): + peer_count = 10 + custody_size = spec.CUSTODY_REQUIREMENT + assert spec.NUMBER_OF_COLUMNS > peer_count + assignments = [spec.get_custody_lines(node_id, custody_size) for node_id in range(peer_count)] + + for assignment in assignments: + assert len(assignment) == custody_size + + +@with_peerdas_and_later +@spec_test +@single_phase +def test_get_custody_lines_peers_more_than_number_of_columns(spec): + peer_count = 200 + custody_size = spec.CUSTODY_REQUIREMENT + assert spec.NUMBER_OF_COLUMNS < peer_count + assignments = [spec.get_custody_lines(node_id, custody_size) for node_id in range(peer_count)] + + for assingment in assignments: + assert len(assingment) == custody_size + + +@with_peerdas_and_later +@spec_test +@single_phase +def test_get_custody_lines_custody_size_more_than_number_of_columns(spec): + node_id = 1 + custody_size = spec.NUMBER_OF_COLUMNS + 1 + expect_assertion_error(lambda: spec.get_custody_lines(node_id, custody_size)) diff --git a/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_networking.py b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_networking.py new file mode 100644 index 0000000000..f3d5b2f177 --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_networking.py @@ -0,0 +1,19 @@ +from eth2spec.test.context import ( + spec_test, + single_phase, + with_peerdas_and_later, +) + + +@with_peerdas_and_later +@spec_test +@single_phase +def test_compute_subnet_for_data_column_sidecar(spec): + subnet_results = [] + for column_index in range(spec.DATA_COLUMN_SIDECAR_SUBNET_COUNT): + subnet_results.append(spec.compute_subnet_for_data_column_sidecar(column_index)) + # no duplicates + assert len(subnet_results) == len(set(subnet_results)) + # next one should be duplicate + next_subnet = spec.compute_subnet_for_data_column_sidecar(spec.DATA_COLUMN_SIDECAR_SUBNET_COUNT) + assert next_subnet == subnet_results[0] diff --git a/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_security.py b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_security.py new file mode 100644 index 0000000000..d6146ff337 --- /dev/null +++ b/tests/core/pyspec/eth2spec/test/peerdas/unittests/test_security.py @@ -0,0 +1,24 @@ +from eth2spec.test.context import ( + MAINNET, + spec_test, + single_phase, + with_peerdas_and_later, + with_phases, +) + + +@with_peerdas_and_later +@spec_test +@single_phase +@with_phases([MAINNET]) +def test_sampling_config(spec): + probability_of_unavailable = 2 ** (-int(spec.SAMPLES_PER_SLOT)) + # TODO: What is the security requirement? + security_requirement = 0.01 + assert probability_of_unavailable <= security_requirement + + column_size_in_bytes = spec.FIELD_ELEMENTS_PER_CELL * spec.BYTES_PER_FIELD_ELEMENT * spec.MAX_BLOBS_PER_BLOCK + bytes_per_slot = column_size_in_bytes * spec.SAMPLES_PER_SLOT + # TODO: What is the bandwidth requirement? + bandwidth_requirement = 10000 # bytes/s + assert bytes_per_slot // spec.config.SECONDS_PER_SLOT < bandwidth_requirement