Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 56쪽

/learn/S-two-book/how-it-works/circle-fri/fri_prover). 4. **Proof of Work**: * A proof-of-work step is performed, with the result mixed into the channel. 5. **FRI Decommitment Phase**: * The function generates random query positions using the channel and decommits the FRI layers at those positions, providing Merkle decommitments for all queried values. For more details, refer to the [FRI prover section](/learn/S-two-book/how-it-works/circle-fri/fri_prover). 6. **Decommitment of Committed Trees**: * For each commitment tree, the function decommits the Merkle tree at the FRI query positions, providing the queried values and authentication paths. 7. **Return Proof Object**: * The function returns a `CommitmentSchemeProof` object containing: * Merkle roots of all commitments * Sampled values at all sample points * Merkle decommitments for all queries * Queried values * Proof-of-work result * FRI proof * Protocol configuration We will now look into the proof verifier implementation. # Polynomial Commitment Scheme Verifier Source: https://docs.starknet.io/learn/S-two-book/how-it-works/pcs/verifier In this section, we describe the implementation of the polynomial commitment scheme verifier. ## Commitment Scheme Verifier The `CommitmentSchemeVerifier` struct manages the verification process for the polynomial commitment scheme. It maintains a collection of [Merkle verifiers](/learn/S-two-book/how-it-works/vcs/merkle_verifier) (one for each commitment tree) and the protocol configuration. ```rust theme={null} pub struct CommitmentSchemeVerifier<MC: MerkleChannel> { pub trees: TreeVec<MerkleVerifier<MC::H>>, pub config: PcsConfig, } ``` We will now see some key functions defined for the `CommitmentSchemeVerifier` struct. ### Read Commitments The `commit` function reads a Merkle root from the prover and initializes a `MerkleVerifier` for the committed columns. It is implemented as follows: ```rust theme={null} pub fn commit( &mut self, commitment: <MC::H as MerkleHasher>::Hash, log_sizes: &[u32], channel: &mut MC::C, ) { MC::mix_root(channel, commitment); let extended_log_sizes = log_sizes .iter() .map(|&log_size| log_size + self.config.fri_config.log_blowup_factor) .collect(); let verifier = MerkleVerifier::new(commitment, extended_log_sizes); self.trees.push(verifier); } ``` ### Verify The `verify_values` function is the core of the verification protocol. It checks that the prover's openings at the sampled points are consistent with the commitments and that the committed polynomials are of low degree via the FRI protocol. It is implemented as follows: ```rust theme={null} pub fn verify_values( &self, sampled_points: TreeVec<ColumnVec<Vec<CirclePoint<SecureField>>>>, proof: CommitmentSchemeProof<MC::H>, channel: &mut MC::C, ) -> Result<(), VerificationError> { channel.mix_felts(&proof.sampled_values.clone().flatten_cols()); let random_coeff = channel.draw_secure_felt(); let bounds = self .column_log_sizes() .flatten() .into_iter() .sorted() .rev() .dedup() .map(|log_size| { CirclePolyDegreeBound::new(log_size - self.config.fri_config.log_blowup_factor) }) .collect_vec(); // FRI commitment phase on OODS quotients. let mut fri_verifier = FriVerifier::<MC>::commit(channel, self.config.fri_config, proof.fri_proof, bounds)?; // Verify proof of work. channel.mix_u64(proof.proof_of_work); if channel.trailing_zeros() < self.config.pow_bits { return Err(VerificationError::ProofOfWork); } // Get FRI query positions. let query_positions_per_log_size = fri_verifier.sample_query_positions(channel); // Verify merkle decommitments. self.trees .as_ref() .zip_eq(proof.decommitments) .zip_eq(proof.queried_values.clone()) .map(|((tree, decommitment), queried_values)| { tree.verify(&query_positions_per_log_size, queried_values, decommitment) }) .0 .into_iter() .collect::<Result<(), _>>()?; // Answer FRI queries. let samples = sampled_points.zip_cols(proof.sampled_values).map_cols( |(sampled_points, sampled_values)| { zip(sampled_points, sampled_values) .map(|(point, value)| PointSample { point, value }) .collect_vec() }, ); let n_columns_per_log_size = self.trees.as_ref().map(|tree| &tree.n_columns_per_log_size); let fri_answers = fri_answers( self.column_log_sizes(), samples, random_coeff, &query_positions_per_log_size, proof.queried_values, n_columns_per_log_size, )?; fri_verifier.decommit(fri_answers)?; Ok(()) } ``` Here is a detailed breakdown: 1. **Mix Sampled Values into the Fiat-Shamir Channel**: * The verifier mixes the `sampled_values` (openings at the queried points) into the Fiat-Shamir channel, ensuring that all subsequent randomness is bound to these values. 2. **Draw Random Coefficient**: * The verifier draws a `random_coeff` from the channel, which is used to combine the quotient polynomials in the FRI protocol. 3. **Determine Degree Bounds**: * The verifier computes the degree `bounds` for each column, based on the log sizes and the protocol's blowup factor. These bounds are used to configure the FRI verifier. 4. **FRI Commitment Phase**: * The verifier initializes the `fri_verifier` with the FRI protocol configuration, the FRI proof from the prover, and the degree bounds. 5. **Verify Proof of Work**: * The verifier checks the `proof_of_work` value provided by the prover using the `pow_bits` in the PCS config. 6. **Sample FRI Query Positions**: * The verifier uses the channel to generate random `query_positions_per_log_size` for the FRI protocol. 7. **Verify Merkle Decommitments**: * For each commitment tree, the verifier checks that the Merkle decommitments at the queried positions are valid and that the opened values match the commitments. 8. **Prepare FRI Query Answers**: * The verifier assembles the answers to the FRI queries by matching the sampled points and values, and prepares them for the FRI verifier. 9. **FRI Decommitment Phase**: * The verifier provides the FRI query answers to the FRI verifier, which checks that the quotient polynomials are of low degree. 10. **Return Verification Result**: * If all checks pass, the function returns `Ok(())`. If any check fails (e.g., Merkle decommitment, proof of work, or FRI check), it returns an appropriate error. # Introduction Source: https://docs.starknet.io/learn/S-two-book/how-it-works/stark_proof/index > In this final section, we cover the implementation of the STARK prover and verifier. This section brings together all the components from previous sections and describes the complete STARK proof generation and verification algorithms. We explain the `prove` and `verify` functions used to generate and verify proofs, as introduced in the [Writing a Simple AIR section](/learn/S-two-book/air-development/writing-a-simple-air/proving-an-air). This section is organized as follows: * [**STARK Prover**](/learn/S-two-book/how-it-works/stark_proof/prove): Details the implementation of the proof generation algorithm. * [**STARK Verifier**](/learn/S-two-book/how-it-works/stark_proof/verify): Describes the verification algorithm. # STARK Prover Source: https://docs.starknet.io/learn/S-two-book/how-it-works/stark_proof/prove This section provides an overview of the `prove` function, the key function in the STARK proof generation process. It is implemented as follows: ```rust theme={null} pub fn prove<B: BackendForChannel<MC>, MC: MerkleChannel>( components: &[&dyn ComponentProver<B>], channel: &mut MC::C, mut commitment_scheme: CommitmentSchemeProver<'_, B, MC>, ) -> Result<StarkProof<MC::H>, ProvingError> { let n_preprocessed_columns = commitment_scheme.trees[PREPROCESSED_TRACE_IDX] .polynomials .len(); let component_provers = ComponentProvers { components: components.to_vec(), n_preprocessed_columns, }; let trace = commitment_scheme.trace(); // Evaluate and commit on composition polynomial. let random_coeff = channel.draw_secure_felt(); let span = span!(Level::INFO, "Composition", class = "Composition").entered(); let span1 = span!( Level::INFO, "Generation", class = "CompositionPolynomialGeneration" ) .entered(); let composition_poly = component_provers.compute_composition_polynomial(random_coeff, &trace); span1.exit(); let mut tree_builder = commitment_scheme.tree_builder(); tree_builder.extend_polys(composition_poly.into_coordinate_polys()); tree_builder.commit(channel); span.exit(); // Draw OODS point. let oods_point = CirclePoint::<SecureField>::get_random_point(channel); // Get mask sample points relative to oods point. let mut sample_points = component_provers.components().mask_points(oods_point); // Add the composition polynomial mask points. sample_points.push(vec![vec![oods_point]; SECURE_EXTENSION_DEGREE]); // Prove the trace and composition OODS values, and retrieve them. let commitment_scheme_proof = commitment_scheme.prove_values(sample_points, channel); let proof = StarkProof(commitment_scheme_proof); info!(proof_size_estimate = proof.size_estimate()); // Evaluate composition polynomial at OODS point and check that it matches the trace OODS // values. This is a sanity check. if proof.extract_composition_oods_eval().unwrap() != component_provers .components() .eval_composition_polynomial_at_point(oods_point, &proof.sampled_values, random_coeff) { return Err(ProvingError::ConstraintsNotSatisfied); } Ok(proof) } ``` Let us go through the function in detail. ## Input and Output It takes the following as input: * `components`: A list of AIR components. For more details, refer to the [Components](/learn/S-two-book/how-it-works/air/components) and [Prover Components](/learn/S-two-book/how-it-works/air/prover_components) sections. * `channel`: A Fiat-Shamir channel for non-interactive randomness. * `commitment_scheme`: A `CommitmentSchemeProver` for committing to trace and composition polynomials. For more details, refer to the [PCS Prover section](/learn/S-two-book/how-it-works/pcs/prover). It outputs a `StarkProof` object if successful, or a `ProvingError` if any constraint is not satisfied. The `StarkProof` object is a wrapper around `CommitmentSchemeProof`. ```rust theme={null} pub struct StarkProof<H: MerkleHasher>(pub CommitmentSchemeProof<H>); ``` ## Step-by-Step Breakdown 1. **Determine Preprocessed Columns** * The function determines the number of preprocessed columns, `n_preprocessed_columns`, from the `commitment_scheme`, which is used to initialize the `ComponentProvers` structure. 2. **Collect Trace Data** * The `trace`, containing all columns (execution, interaction, preprocessed), is retrieved from the `commitment_scheme`. This includes both coefficient and evaluation forms for each column. 3. **Composition Polynomial Construction** * A `random_coeff` is drawn from the channel. * The `composition_poly` is computed as a random linear combination of all constraint quotient polynomials, using powers of the random coefficient. For more details, refer to the [Prover Components](/learn/S-two-book/how-it-works/air/prover_components) section. 4. **Commit to the Composition Polynomial** * The `composition_poly` is split into coordinate polynomials and committed to using a Merkle tree. 5. **Out-of-Domain Sampling (OODS)** * An `oods_point` is drawn randomly from the channel. This point is used to bind the prover to a unique low-degree polynomial, preventing ambiguity in the list decoding regime. For more details, refer to the [Out-of-Domain Sampling](/learn/S-two-book/how-it-works/pcs/overview#out-of-domain-sampling) section. 6. **Determine Sample Points** * The function computes all `sample_points` required to verify constraints at the OODS point, using the `mask_points` function. This includes all necessary offsets for each constraint and the OODS points for the composition polynomial. 7. **Openings and Proof Generation** * The `commitment_scheme` is asked to open all committed polynomials at the sampled points, producing the required evaluations and Merkle authentication paths. This is handled by the `prove_values` function, which also integrates the FRI protocol for low-degree testing. For more details, refer to the [PCS Prover](/learn/S-two-book/how-it-works/pcs/prover#prove) section. 8. **Sanity Check** * The function checks that the composition polynomial evaluated at the OODS point matches the value reconstructed from the sampled trace values. If not, it returns a `ConstraintsNotSatisfied` error. 9. **Return Proof** * If all checks pass, the function returns a `StarkProof` object containing the full proof transcript, including all commitments, openings, and FRI proof. # STARK Verifier Source: https://docs.starknet.io/learn/S-two-book/how-it-works/stark_proof/verify This section provides an overview of the `verify` function, the key function that verifies the STARK proof. It is implemented as follows: ```rust theme={null} pub fn verify<MC: MerkleChannel>( components: &[&dyn Component], channel: &mut MC::C, commitment_scheme: &mut CommitmentSchemeVerifier<MC>, proof: StarkProof<MC::H>, ) -> Result<(), VerificationError> { let n_preprocessed_columns = commitment_scheme.trees[PREPROCESSED_TRACE_IDX] .column_log_sizes .len(); let components = Components { components: components.to_vec(), n_preprocessed_columns, }; tracing::info!( "Composition polynomial log degree bound: {}", components.composition_log_degree_bound() ); let random_coeff = channel.draw_secure_felt(); // Read composition polynomial commitment. commitment_scheme.commit( *proof.commitments.last().unwrap(), &[components.composition_log_degree_bound(); SECURE_EXTENSION_DEGREE], channel, ); // Draw OODS point. let oods_point = CirclePoint::<SecureField>::get_random_point(channel); // Get mask sample points relative to oods point. let mut sample_points = components.mask_points(oods_point); // Add the composition polynomial mask points. sample_points.push(vec![vec![oods_point]; SECURE_EXTENSION_DEGREE]); let sample_points_by_column = sample_points.as_cols_ref().flatten(); tracing::info!("Sampling {} columns.", sample_points_by_column.len()); tracing::info!( "Total sample points: {}.", sample_points_by_column.into_iter().flatten().count() ); let composition_oods_eval = proof .extract_composition_oods_eval() .ok_or(VerificationError::InvalidStructure( std_shims::ToString::to_string(&"Unexpected sampled_values structure"), ))?; if composition_oods_eval != components.eval_composition_polynomial_at_point( oods_point, &proof.sampled_values, random_coeff, ) { return Err(VerificationError::OodsNotMatching); } commitment_scheme.verify_values(sample_points, proof.0, channel) } ``` Let us go through the function in detail. ## Input and Output The `verify` function is the entry point for verifying a STARK proof. It takes as input: * `components`: A list of AIR components. For more details, refer to the [Components](/learn/S-two-book/how-it-works/air/components) section. * `channel`: A Fiat-Shamir channel for non-interactive randomness. * `commitment_scheme`: A `CommitmentSchemeVerifier` for verifying Merkle commitments and FRI proofs. For more details, refer to the [PCS Verifier section](/learn/S-two-book/how-it-works/pcs/verifier). * `proof`: The `StarkProof` object to be verified. It returns `Ok(())` if the proof is valid, or a `VerificationError` if any check fails. ## Step-by-Step Breakdown 1. **Determine Preprocessed Columns** * The function determines the number of preprocessed columns, `n_preprocessed_columns`, from the `commitment_scheme`, which is used to initialize the `Components` struct. 2. **Initialize Components** * The `Components` structure is created, encapsulating all AIR components and the number of preprocessed columns. 3. **Read Composition Polynomial Commitment** * The verifier reads the Merkle root of the composition polynomial from the `proof` and registers it with the commitment scheme verifier, along with the degree bounds for each coordinate polynomial. 4. **Out-of-Domain Sampling (OODS)** * An `oods_point` is drawn randomly from the channel. This point is used to bind the prover to a unique low-degree polynomial and prevent ambiguity in the list decoding regime. 5. **Determine Sample Points** * The function computes all `sample_points` required to verify constraints at the OODS point, using the `mask_points` function. This includes all necessary offsets for each constraint and the OODS points for the composition polynomial. 6. **Sanity Check: Composition Polynomial Evaluation** * The function checks that the composition polynomial evaluated at the OODS point (as provided in the proof) matches the value reconstructed from the sampled trace values. If not, it returns an `OodsNotMatching` error. 7. **Invoke Commitment Scheme Verifier** * The function calls `verify_values` on the commitment scheme verifier, passing the `sample_points`, the `proof`, and the `channel`. This step checks all Merkle decommitments, FRI low-degree proofs, and protocol soundness. 8. **Return Verification Result** * If all checks pass, the function returns `Ok(())`. If any check fails (e.g., Merkle decommitment, FRI check, or OODS mismatch), it returns an appropriate `VerificationError`. # Hash Functions Source: https://docs.starknet.io/learn/S-two-book/how-it-works/vcs/hash_functions This section describes the traits and implementations of hash functions used in the Merkle commitment scheme. S-two supports two hash functions: **BLAKE2s-256** and **Poseidon252**. Here, we focus on the implementation for BLAKE2s-256; Poseidon252 is implemented similarly (see [Poseidon reference](https://docs.starknet.io/learn/protocol/cryptography#poseidon-hash)). ## MerkleHasher Trait The `MerkleHasher` trait defines the interface for hash functions used in Merkle trees. Its main function, `hash_node`, computes the hash of a node from its children and (optionally) column values: ```rust theme={null} pub trait MerkleHasher: Debug + Default + Clone { type Hash: Hash; /// Hashes a single Merkle node. See [MerkleHasher] for more details. fn hash_node( children_hashes: Option<(Self::Hash, Self::Hash)>, column_values: &[BaseField], ) -> Self::Hash; } ``` ### Implementation for BLAKE2s-256 The `MerkleHasher` implementation for BLAKE2s-256 uses a wrapper struct `Blake2sHash`: ```rust theme={null} pub struct Blake2sHash(pub [u8; 32]); ``` The trait implementation is provided by `Blake2sMerkleHasher`: ```rust theme={null} pub struct Blake2sMerkleHasher; impl MerkleHasher for Blake2sMerkleHasher { type Hash = Blake2sHash; fn hash_node( children_hashes: Option<(Self::Hash, Self::Hash)>, column_values: &[BaseField], ) -> Self::Hash { let mut hasher = Blake2s256::new(); if let Some((left_child, right_child)) = children_hashes { hasher.update(left_child); hasher.update(right_child); } for value in column_values { hasher.update(value.0.to_le_bytes()); } Blake2sHash(hasher.finalize().into()) } } ``` In this Merkle tree implementation, node hashes are computed using both the children hashes and the column values. This differs from standard Merkle trees, where node hashes typically depend only on the children. More details are discussed in the next sections. ## MerkleOps Trait The `MerkleOps` trait defines Merkle tree operations for a commitment scheme, parameterized by a `MerkleHasher`. Its main function, `commit_on_layer`, takes the previous layer's hashes and the current layer's column values to generate the hashes for the next layer: ```rust theme={null} pub trait MerkleOps<H: MerkleHasher>: ColumnOps<BaseField> + ColumnOps<H::Hash> + for<'de> Deserialize<'de> + Serialize { /// Commits on an entire layer of the Merkle tree. /// See [MerkleHasher] for more details. /// /// The layer has 2^`log_size` nodes that need to be hashed. The topmost layer has 1 node, /// which is a hash of 2 children and some columns. ///
프로젝트로 돌아가기