### Production SRS Setup Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/plonk/src/dsl/README.md An example demonstrating the setup and usage of the SRSManager, Prover, and Verifier for PLONK circuits. ```APIDOC ## Production SRS Setup (example) ### Description This example shows how to load and check the SRS (Structured Reference String), create a KZG commitment scheme, and then use the Prover and Verifier to generate and verify a PLONK proof. ### Method N/A (Example Code) ### Endpoint N/A (Example Code) ### Parameters N/A (Example Code) ### Request Example N/A (Example Code) ### Response N/A (Example Code) ### Code Example ```rust use lambdaworks_plonk::srs::SRSManager; use lambdaworks_plonk::prover::Prover; use lambdaworks_plonk::test_utils::utils::{SecureRandomFieldGenerator, KZG}; use lambdaworks_plonk::verifier::Verifier; use lambdaworks_math::elliptic_curve::short_weierstrass::curves::bls12_381::{ curve::BLS12381Curve, twist::BLS12381TwistCurve, }; use lambdaworks_math::elliptic_curve::traits::IsEllipticCurve; type G1Point = ::PointRepresentation; type G2Point = ::PointRepresentation; // Load SRS and ensure it is large enough for the circuit size `cpi.n` let srs = SRSManager::load::("ceremony.srs")?; SRSManager::check_size(&srs, cpi.n)?; // Assumes `cpi`, `witness`, `public_inputs`, and `vk` are already built let kzg = KZG::new(srs); let prover = Prover::new(kzg.clone(), SecureRandomFieldGenerator); let proof = prover.prove(&witness, &public_inputs, &cpi, &vk)?; let verifier = Verifier::new(kzg); verifier.verify_with_result(&proof, &public_inputs, &cpi, &vk)?; ``` ``` -------------------------------- ### Verification Key Setup in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/plonk/implementation.md Performs the setup phase for the KZG commitment scheme, generating a verification key from the common preprocessed input. ```rust let verifying_key = setup(&common_preprocessed_input, &kzg); ``` -------------------------------- ### Install cargo-criterion Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/math/src/field/README.md Install the cargo-criterion tool for running benchmarks locally. ```bash cargo install cargo-criterion ``` -------------------------------- ### Groth16 Setup, Prove, and Verify with Lambdaworks Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/groth16/arkworks-adapter/README.md After converting to a Lambdaworks QAP, perform standard Groth16 operations: setup, prove, and verify. Ensure the public inputs are correctly sliced from the witness. ```rust let (pk, vk) = setup(&qap); let proof = Prover::prove(&w, &qap, &pk).expect("proving failed"); let public_inputs = &w[..qap.num_of_public_inputs]; let accept = verify(&vk, &proof, public_inputs); assert!(accept); ``` -------------------------------- ### Full Example: Linear Exponentiation Circuit Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/groth16/arkworks-adapter/README.md An example demonstrating the creation of a linear exponentiation circuit using Arkworks, conversion to Lambdaworks format, and subsequent Groth16 proving and verification on BLS12-381. ```rust use crate::to_lambda; use ark_bls12_381::Fr; use ark_relations::{lc, r1cs::ConstraintSystem, r1cs::Variable}; use lambdaworks_groth16::{setup, verify, Prover}; use rand::Rng; // ... // ... let mut rng = rand::thread_rng(); let x = rng.gen::(); let exp = rng.gen::(); // Define the circuit using Arkworks let cs = ConstraintSystem::::new_ref(); let x = Fr::from(x); let mut _x = cs.new_witness_variable(|| Ok(x)).unwrap(); let mut acc = Fr::from(x); let mut _acc = cs.new_witness_variable(|| Ok(x)).unwrap(); for _ in 0..exp - 1 { acc *= x; let _new_acc = cs.new_witness_variable(|| Ok(acc)).unwrap(); cs.enforce_constraint(lc!() + _acc, lc!() + _x, lc!() + _new_acc) .unwrap(); _acc = _new_acc; } let _out = cs.new_input_variable(|| Ok(acc)).unwrap(); cs.enforce_constraint(lc!() + _out, lc!() + Variable::One, lc!() + _acc) .unwrap(); // Make Lambdaworks-compatible let (qap, w) = to_lambda(&cs); // Use Lambdaworks Groth16 backend let (pk, vk) = setup(&qap); let proof = Prover::prove(&w, &qap, &pk).expect("proving failed"); let public_inputs = &w[..qap.num_of_public_inputs]; let accept = verify(&vk, &proof, public_inputs); assert!(accept); ``` -------------------------------- ### Run Univariate Logup GKR Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/gkr-logup/README.md Demonstrates univariate commitments on a cyclic domain using three examples: grand product, LogUp singles, and LogUp multiplicities. ```bash cargo run -p lambdaworks-gkr-logup --example univariate_logup_gkr ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/lambdaclass/lambdaworks/blob/main/README.md Serve the project's documentation locally after installing mdbook and the Katex preprocessor. This command builds and serves the documentation. ```shell make docs ``` -------------------------------- ### Setup Evaluation and Verification Keys Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/pinocchio/Readme.md Generates the EvaluationKey and VerificationKey required for the prover and verifier, respectively, using a QAP and toxic waste. ```rust let (evaluation_key, verification_key) = setup(&test_qap, toxic_waste); ``` -------------------------------- ### Run FROST Example with Cargo Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/frost-signature/README.md Use this command to compile and run the FROST signature example using Cargo, the Rust build system and package manager. ```bash cargo run -p frost-signature ``` -------------------------------- ### Consolidated Setup Commands Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/groth16/circom-adapter/README.md A consolidated bash snippet to perform circuit compilation, witness generation, and JSON export in one go. Replace 'test' with your circuit's name. ```bash circom test.circom --r1cs --wasm -p bls12381; node test_js/generate_witness.js test_js/test.wasm input.json witness.wtns; snarkjs wtns export json witness.wtns; snarkjs r1cs export json test.r1cs test.r1cs.json; ``` -------------------------------- ### Groth16 Setup Parameters Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/groth16/README.md Defines the initial random field elements required for Groth16 setup. These 'toxic waste' values are crucial for key generation and must be securely handled. ```plaintext t, \u03b1, \u03b2, \u03b3, \u03b4 ``` -------------------------------- ### Verify Merkle Proof Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/merkle-tree-cli/README.md This command demonstrates verifying a Merkle Proof using the generated root, proof, and leaf files for the sample tree. ```bash cargo run --release verify-proof sample_tree_root.txt 0 sample_tree_proof_0.json sample_tree_leaf_0.txt ``` -------------------------------- ### Virtual Column Trace Evaluation Example 2 Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/starks/virtual_cols.md Demonstrates row evaluation for a virtual column setup with a dummy flag 'D', where constraints are applied with a larger stride. This configuration is useful for aligning evaluations to powers of two. ```diff + A0 | + B0 | + C0 | + D0 | + A1 | + B1 | + C1 | + D1 | A2 | B2 | C2 | D2 | A3 | B3 | C3 | D3 | ``` ```diff A0 | B0 | C0 | D0 | + A1 | + B1 | + C1 | + D1 | + A2 | + B2 | + C2 | + D2 | A3 | B3 | C3 | D3 | ``` ```diff A0 | B0 | C0 | D0 | A1 | B1 | C1 | D1 | + A2 | + B2 | + C2 | + D2 | + A3 | + B3 | + C3 | + D3 | ``` -------------------------------- ### Install nightly Rust toolchain Source: https://github.com/lambdaclass/lambdaworks/blob/main/fuzz/README.md Installs the nightly Rust toolchain, which is a prerequisite for using cargo-fuzz. ```bash rustup toolchain install nightly ``` -------------------------------- ### Merkle Tree Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/getting-started.md Demonstrates building and verifying a Merkle tree using field elements and Keccak256 hashing. Requires `lambdaworks-crypto` and `lambdaworks-math`. ```rust use lambdaworks_crypto::merkle_tree::merkle::MerkleTree; use lambdaworks_crypto::merkle_tree::backends::field_element::FieldElementBackend; use lambdaworks_math::field::element::FieldElement; use lambdaworks_math::field::fields::fft_friendly::stark_252_prime_field::Stark252PrimeField; use sha3::Keccak256; type F = Stark252PrimeField; type FE = FieldElement; fn main() { // Create some data let values: Vec = (1..9).map(FE::from).collect(); // Build the Merkle tree let tree = MerkleTree::>::build(&values).unwrap(); // Generate a proof for element at index 3 let proof = tree.get_proof_by_pos(3).unwrap(); // Verify the proof let is_valid = proof.verify::>( &tree.root, 3, &values[3] ); assert!(is_valid); println!("Merkle proof verified successfully!"); } ``` -------------------------------- ### Schnorr Signature Example in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/schnorr-signature/README.md This example demonstrates the basic usage of the Schnorr signature implementation. It covers key generation, message signing, and signature verification. Ensure the necessary elliptic curve and field elements are correctly set up. ```rust use ark_bn254::Fr as FE; use lambdaworks_gadgets::schnorr_signature::{get_public_key, sign_message, verify_signature}; // Choose a private key. let private_key = FE::from(5); // Compute the public key. let public_key = get_public_key(&private_key); // Write the message let message = "hello world"; // Sign the message let message_signed = sign_message(&private_key, message); // Verify the signature let is_the_signature_correct = verify_signature( &public_key, &message_signed ); ``` -------------------------------- ### Run Reed-Solomon Codes Demo Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/reed-solomon-codes/README.md Navigate to the examples directory and run the cargo command to see an interactive demonstration of Reed-Solomon encoding, decoding, and list decoding. ```bash cd examples/reed-solomon-codes cargo run ``` -------------------------------- ### Simple STARK Proof (Fibonacci) Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/getting-started.md Generates and verifies a STARK proof for the Fibonacci sequence. Requires `stark-platinum-prover`, `lambdaworks-math`, and `sha3` dependencies. ```rust use lambdaworks_math::field::element::FieldElement; use lambdaworks_math::field::fields::fft_friendly::stark_252_prime_field::Stark252PrimeField; use stark_platinum_prover::proof::options::ProofOptions; use stark_platinum_prover::prover::{IsStarkProver, Prover}; use stark_platinum_prover::verifier::{IsStarkVerifier, Verifier}; use stark_platinum_prover::examples::simple_fibonacci::{ FibonacciAIR, FibonacciPublicInputs, fibonacci_trace }; use stark_platinum_prover::transcript::StoneProverTranscript; type Felt = FieldElement; fn main() { // Generate the Fibonacci trace (first 8 numbers) let mut trace = fibonacci_trace([Felt::from(1), Felt::from(1)], 8); // Set proof options let proof_options = ProofOptions::default_test_options(); // Define public inputs (initial values) let pub_inputs = FibonacciPublicInputs { a0: Felt::one(), a1: Felt::one(), }; // Generate the proof let proof = Prover::>::prove( &mut trace, &pub_inputs, &proof_options, StoneProverTranscript::new(&[]), ).unwrap(); // Verify the proof let is_valid = Verifier::>::verify( &proof, &pub_inputs, &proof_options, StoneProverTranscript::new(&[]), ); assert!(is_valid); println!("STARK proof verified successfully!"); } ``` -------------------------------- ### GKR Protocol Example Usage Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/gkr/README.md Demonstrates how to generate and verify a GKR proof for a predefined circuit. Ensure the necessary field and circuit components are defined before use. ```rust use lambdaworks_math::field::fields::u64_prime_field::U64PrimeField; use lambdaworks_math::field::element::FieldElement; use lambdaworks_gkr::{gkr_prove, gkr_verify, circuit_from_lambda}; // Define the field (We use modulus 23 as in the example of our blog post). const MODULUS23: u64 = 23; type F23 = U64PrimeField; type F23E = FieldElement; // Create the circuit of our blog post. // This creates a 2-layer circuit plus the input layer. let circuit = lambda_post_circuit.unwrap(); // Define input values (from the post example). let input = [F23E::from(3), F23E::from(1)]; // Generate proof. let proof_result = gkr_prove(&circuit, &input); assert!(proof_result.is_ok()); let proof = proof_result.unwrap(); // Verify proof. let verification_result = gkr_verify(&proof, &circuit, &input); assert!(verification_result.is_ok() && verification_result.unwrap()); println!("GKR verification successful!"); // You can also check the actual output. let evaluation = circuit.evaluate(&input); println!("Circuit output: {:?}", evaluation.layers[0]); ``` -------------------------------- ### Build and Prove Plonk Circuits Source: https://context7.com/lambdaclass/lambdaworks/llms.txt Demonstrates building a constraint system for a simple multiplication circuit and generating a proof. Requires setup and verification components not shown. ```rust use lambdaworks_plonk::constraint_system::ConstraintSystem; use lambdaworks_plonk::setup::{setup, CommonPreprocessedInput}; use lambdaworks_plonk::prover::Prover; use lambdaworks_plonk::verifier::Verifier; use lambdaworks_crypto::commitments::kzg::KateZaveruchaGoldberg; use lambdaworks_math::elliptic_curve::short_weierstrass::curves::bls12_381::default_types::FrField; use lambdaworks_math::field::element::FieldElement; use std::collections::HashMap; type FE = FieldElement; // Build constraint system: prove x * e = y let system = &mut ConstraintSystem::::new(); // Define variables let x = system.new_public_input(); // Public input let y = system.new_public_input(); // Public input let e = system.new_variable(); // Private witness // Add constraint: x * e = y let z = system.mul(&x, &e); system.assert_eq(&y, &z); // Setup phase // let common = CommonPreprocessedInput::from_constraint_system(&system, &ORDER_R_MINUS_1_ROOT_UNITY); // let srs = test_srs(common.n); // let kzg = KZG::new(srs); // let verifying_key = setup(&common, &kzg); // Prove with concrete values: x=4, e=3, y=12 let inputs = HashMap::from([ (x, FE::from(4u64)), (e, FE::from(3u64)), ]); let assignments = system.solve(inputs).unwrap(); // Generate and verify proof // let witness = Witness::new(assignments, &system); // let public_inputs = system.public_input_values(&assignments); // let prover = Prover::new(kzg.clone(), TestRandomFieldGenerator {}); // let proof = prover.prove(&witness, &public_inputs, &common, &verifying_key); // Verify // let verifier = Verifier::new(kzg); // assert!(verifier.verify(&proof, &public_inputs, &common, &verifying_key)); ``` -------------------------------- ### Setup Proving and Verification Keys in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/baby-snark/README.md Generates the proving (pk) and verification (vk) keys from the constructed Square Span Program (ssp). ```rust let (pk, vk) = setup(&ssp); ``` -------------------------------- ### Generate Merkle Proof Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/merkle-tree-cli/README.md This command demonstrates generating a Merkle Proof for the leaf at position 0 in the sample tree. It will create a JSON file for the proof and a TXT file for the leaf's value. ```bash cargo run --release generate-proof sample_tree.csv 0 ``` -------------------------------- ### Production SRS Setup and Verification Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/plonk/src/dsl/README.md Loads a Secure Random Sampling (SRS) and performs prover and verifier operations. Ensure the SRS is sufficiently large for the circuit size. ```rust use lambdaworks_plonk::srs::SRSManager; use lambdaworks_plonk::prover::Prover; use lambdaworks_plonk::test_utils::utils::{SecureRandomFieldGenerator, KZG}; use lambdaworks_plonk::verifier::Verifier; use lambdaworks_math::elliptic_curve::short_weierstrass::curves::bls12_381:: curve::BLS12381Curve, twist::BLS12381TwistCurve, ; use lambdaworks_math::elliptic_curve::traits::IsEllipticCurve; type G1Point = ::PointRepresentation; type G2Point = ::PointRepresentation; // Load SRS and ensure it is large enough for the circuit size `cpi.n` let srs = SRSManager::load::("ceremony.srs")?; SRSManager::check_size(&srs, cpi.n)?; // Assumes `cpi`, `witness`, `public_inputs`, and `vk` are already built let kzg = KZG::new(srs); let prover = Prover::new(kzg.clone(), SecureRandomFieldGenerator); let proof = prover.prove(&witness, &public_inputs, &cpi, &vk)?; let verifier = Verifier::new(kzg); verifier.verify_with_result(&proof, &public_inputs, &cpi, &vk)?; ``` -------------------------------- ### Run Logup GKR Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/gkr-logup/README.md Executes the LogUpSingles and LogUpMultiplicities batch instances to verify memory accesses against a ROM table. This is used for read-only memory checks. ```bash cargo run -p lambdaworks-gkr-logup --example logup_gkr ``` -------------------------------- ### Finite Field Arithmetic Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/getting-started.md Demonstrates basic arithmetic operations on field elements using Stark252PrimeField. Ensure `lambdaworks-math` is added to your dependencies. ```rust use lambdaworks_math::field::element::FieldElement; use lambdaworks_math::field::fields::fft_friendly::stark_252_prime_field::Stark252PrimeField; // Create a type alias for convenience type FE = FieldElement; fn main() { // Create field elements let a = FE::from(42u64); let b = FE::from(7u64); // Basic operations let sum = &a + &b; // Addition let product = &a * &b; // Multiplication let quotient = &a / &b; // Division let squared = a.square(); // Squaring let inverse = b.inv().unwrap(); // Multiplicative inverse println!("a + b = {:?}", sum); println!("a * b = {:?}", product); println!("a / b = {:?}", quotient); println!("a^2 = {:?}", squared); println!("b^(-1) = {:?}", inverse); // Verify: b * b^(-1) = 1 assert_eq!(&b * &inverse, FE::one()); } ``` -------------------------------- ### Creating a Custom Cube Gadget Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/plonk/src/dsl/README.md Illustrates how to create a reusable custom gadget by implementing the `Gadget` trait. This example defines a `Cube` gadget that computes `x^3` using two multiplication gates. ```rust use lambdaworks_plonk::dsl::gadgets::{Gadget, GadgetError}; use lambdaworks_plonk::dsl::{CircuitBuilder, FieldVar}; /// Computes x^3 pub struct Cube; impl Gadget for Cube { type Input = FieldVar; type Output = FieldVar; fn synthesize( builder: &mut CircuitBuilder, x: Self::Input, ) -> Result { let x_squared = builder.mul(&x, &x); let x_cubed = builder.mul(&x_squared, &x); Ok(x_cubed) } fn constraint_count() -> usize { 2 // Two multiplication gates } fn name() -> &'static str { "Cube" } } ``` -------------------------------- ### Create Simple Main Boundary Constraint Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/stark/README.md Illustrates the creation of a single boundary constraint. This specific example applies a constraint to the second row (index 1) using a public input value. ```rust let a1 = BoundaryConstraint::new_simple_main(1, self.pub_inputs.a1.clone()); ``` -------------------------------- ### KZG Polynomial Commitment Placeholder Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/README.md A placeholder indicating the usage of the Kate-Zaverucha-Goldberg (KZG) polynomial commitment scheme. A full example requires a trusted setup (SRS). ```rust use lambdaworks_crypto::commitments::kzg::KateZaveruchaGoldberg; use lambdaworks_math::polynomial::Polynomial; // KZG requires a trusted setup (SRS) // See the full example in the crate documentation ``` -------------------------------- ### Virtual Column Trace Evaluation Example 1 Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/starks/virtual_cols.md Illustrates the row evaluation for a virtual column setup where constraints are applied over consecutive rows. This is used when constraints do not involve other trace cells. ```diff + A0 | B0 | C0 + A1 | B1 | C1 A2 | B2 | C2 A3 | B3 | C3 ``` ```diff A0 | B0 | C0 + A1 | B1 | C1 + A2 | B2 | C2 A3 | B3 | C3 ``` -------------------------------- ### Install honggfuzz Source: https://github.com/lambdaclass/lambdaworks/blob/main/fuzz/README.md Installs honggfuzz, the fuzzer used for CUDA targets. This also requires installing build essentials and development libraries. ```bash cargo install honggfuzz ``` ```bash apt install build-essential ``` ```bash apt-get install binutils-dev ``` ```bash sudo apt-get install libunwind-dev ``` ```bash sudo apt-get install lldb ``` -------------------------------- ### Install cargo-fuzzer Source: https://github.com/lambdaclass/lambdaworks/blob/main/README.md Use this command to install the cargo-fuzzer tool, which is required for running CPU fuzzers. ```bash cargo install cargo-fuzz ``` -------------------------------- ### Run Prover with Default Settings Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/stark/PROFILING.md Execute the profiling binary with default trace length (2^16 rows). ```bash ./target/release/deps/prover_profile-*[!.d] --trace-length 16 ``` -------------------------------- ### Example dhat Memory Output Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/stark/PROFILING.md Example output from dhat memory profiling, showing total allocations, peak usage, and final memory state. ```text dhat: Total: 200,078,545 bytes in 952,106 blocks dhat: At t-gmax: 33,292,816 bytes in 98,327 blocks dhat: At t-end: 64 bytes in 1 blocks ``` -------------------------------- ### Setup and SRS for PLONK Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/plonk/constraint_system.md Generates the common preprocessed input and the structured reference string (SRS) required for PLONK setup. The SRS is used by the commitment scheme. ```rust let common = CommonPreprocessedInput::from_constraint_system(&system, &ORDER_R_MINUS_1_ROOT_UNITY); let srs = test_srs(common.n); let kzg = KZG::new(srs); // The commitment scheme for plonk. let vk = setup(&common, &kzg); ``` -------------------------------- ### KZG Initialization Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/commitments/README.md Demonstrates how to load a Structured Reference String (SRS) and initialize the KZG commitment scheme instance. ```APIDOC ## KZG Initialization ### Description Initializes the KZG commitment scheme by loading a Structured Reference String (SRS) and creating a KZG instance. ### Method Initialization ### Endpoint N/A (Code-based initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use lambdaworks_crypto::commitments::kzg::{KateZaveruchaGoldberg, StructuredReferenceString}; use lambdaworks_crypto::commitments::traits::IsCommitmentScheme; use lambdaworks_math::elliptic_curve::short_weierstrass::curves::bls12_381::{ curve::BLS12381Curve, default_types::{FrElement, FrField}, pairing::BLS12381AtePairing, twist::BLS12381TwistCurve, }; use lambdaworks_math::elliptic_curve::short_weierstrass::point::ShortWeierstrassProjectivePoint; // Load SRS from a file let srs_file = "path/to/srs.bin"; let srs = StructuredReferenceString::from_file(srs_file).unwrap(); // Create a KZG instance let kzg = KateZaveruchaGoldberg::::new(srs); ``` ### Response #### Success Response (200) N/A (Initialization is a code operation) #### Response Example N/A ``` -------------------------------- ### Create IPA Instance in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/commitments/README.md Demonstrates how to create an IPA instance with deterministic generators. Ensure the number of generators is a power of two. ```rust use lambdaworks_crypto::commitments::ipa::{Ipa, IpaSetup}; use lambdaworks_math::{ elliptic_curve::short_weierstrass::curves::pallas::curve::PallasCurve, elliptic_curve::traits::IsEllipticCurve, field::element::FieldElement, field::fields::vesta_field::Vesta255PrimeField, polynomial::Polynomial, }; type F = Vesta255PrimeField; type FE = FieldElement; type G = ::PointRepresentation; // Create generators deterministically let g = PallasCurve::generator(); let n = 8; // must be a power of two let generators: Vec = (1..=n as u64) .map(|i| g.operate_with_self(i)) .collect(); let u = g.operate_with_self(n as u64 + 1337); let setup = IpaSetup { generators, u }; let ipa = Ipa::<4, F, G>::new(setup); ``` -------------------------------- ### Full Happy Path Proof Generation and Verification in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/plonk/implementation.md This snippet illustrates the complete process of generating a proof for a circuit and then verifying it. It requires setting up the common preprocessed input, witness, SRS, and KZG commitment scheme. ```rust // This is the common preprocessed input for // the test circuit ( ASSERT(x * e + 5 == y) ) let common_preprocessed_input = test_common_preprocessed_input_2(); // Input let x = FieldElement::from(2_u64); // Private input let e = FieldElement::from(3_u64); let y, witness = test_witness_2(x, e); let srs = test_srs(common_preprocessed_input.n); let kzg = KZG::new(srs); let verifying_key = setup(&common_preprocessed_input, &kzg); let random_generator = TestRandomFieldGenerator {}; let prover = Prover::new(kzg.clone(), random_generator); let public_input = vec![x.clone(), y]; let proof = prover.prove( &witness, &public_input, &common_preprocessed_input, &verifying_key, ); let verifier = Verifier::new(kzg); assert!(verifier.verify( &proof, &public_input, &common_preprocessed_input, &verifying_key )); ``` -------------------------------- ### Build and Verify Merkle Tree with BatchPoseidonTree Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/merkle_tree/README.md Shows how to build a Merkle tree using BatchPoseidonTree for efficient batch hashing with Poseidon, and then generate and verify an inclusion proof. This backend is optimized for ZK systems. ```rust use lambdaworks_crypto::merkle_tree::{ merkle::MerkleTree, backends::field_element_vector::BatchPoseidonTree, }; use lambdaworks_crypto::hash::poseidon::starknet::PoseidonCairoStark252; use lambdaworks_math::field::{ element::FieldElement, fields::fft_friendly::stark_252_prime_field::Stark252PrimeField, }; // Define the types we'll use type F = Stark252PrimeField; type FE = FieldElement; // Create some data (vectors of field elements) let values: Vec> = vec![ vec![FE::from(1), FE::from(2)], vec![FE::from(3), FE::from(4)], vec![FE::from(5), FE::from(6)], vec![FE::from(7), FE::from(8)], ]; // Build the Merkle tree using Poseidon hash function let merkle_tree = MerkleTree::>::build(&values).unwrap(); // Generate a proof for a specific element let proof = merkle_tree.get_proof_by_pos(1).unwrap(); // Verify the proof let is_valid = proof.verify::>( &merkle_tree.root, 1, &values[1] ); assert!(is_valid, "Proof verification failed"); ``` -------------------------------- ### Build Profiling Binary Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/stark/PROFILING.md Build the release binary for the STARK prover with profiling capabilities enabled. ```bash cargo build --release -p stark-platinum-prover --bench prover_profile ``` -------------------------------- ### Check Rust Version Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/getting-started.md Verify that your Rust installation meets the minimum version requirement. ```bash rustc --version ``` -------------------------------- ### Serialization and Deserialization of SRS Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/commitments/README.md Provides examples for serializing the SRS to bytes and deserializing it back. ```APIDOC ## Serialization and Deserialization of SRS ### Description Allows for the serialization of the Structured Reference String (SRS) into a byte format for storage or transmission, and deserialization back into an SRS object. ### Method Serialization and Deserialization ### Endpoint N/A (Code-based operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming 'srs' is an initialized StructuredReferenceString instance // Serialize the SRS let bytes = srs.as_bytes(); // Deserialize the SRS let deserialized_srs = StructuredReferenceString::< ShortWeierstrassProjectivePoint, ShortWeierstrassProjectivePoint, >::deserialize(&bytes).unwrap(); ``` ### Response #### Success Response (200) - **bytes** (Vec) - The serialized SRS as a byte vector. - **deserialized_srs** (StructuredReferenceString) - The deserialized SRS object. #### Response Example N/A (Serialization/Deserialization are data transformations within code) ``` -------------------------------- ### Sample Merkle Tree CSV Content Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/merkle-tree-cli/README.md An example of the content within a sample Merkle Tree CSV file. ```csv 0x12345;0x6789A;0xBCDEF ``` -------------------------------- ### Build and Verify Merkle Tree with Field Element Vectors Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/merkle_tree/README.md Demonstrates building a Merkle tree using vectors of field elements as leaves and then generating and verifying a proof. This example requires importing necessary traits and types for field elements and the Merkle tree backend. ```rust use lambdaworks_crypto::merkle_tree::{ merkle::MerkleTree, backends::field_element_vector::FieldElementVectorBackend, }; use lambdaworks_math::field::{ element::FieldElement, fields::fft_friendly::stark_252_prime_field::Stark252PrimeField, }; use sha3::Keccak256; // Define the types we'll use type F = Stark252PrimeField; type FE = FieldElement; // Create some data (vectors of field elements) let values: Vec> = vec![ vec![FE::from(1), FE::from(2)], vec![FE::from(3), FE::from(4)], vec![FE::from(5), FE::from(6)], ]; // Build the Merkle tree let merkle_tree = MerkleTree::>::build(&values).unwrap(); // Generate a proof let proof = merkle_tree.get_proof_by_pos(0).unwrap(); // Verify the proof let is_valid = proof.verify::>( &merkle_tree.root, 0, &values[0] ); assert!(is_valid, "Proof verification failed"); ``` -------------------------------- ### Run CPU Fuzzer Source: https://github.com/lambdaclass/lambdaworks/blob/main/README.md Execute a specific CPU fuzzer by providing its name to the make command. Ensure cargo-fuzzer is installed. ```bash make run-fuzzer FUZZER=stark252 ``` -------------------------------- ### Construct a Test R1CS QAP Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/pinocchio/Readme.md Initializes a test Quadratic Arithmetic Program (QAP) for use in the Pinocchio protocol setup. ```rust let test_qap = new_test_r1cs().into(); ``` -------------------------------- ### Elliptic Curve Operations in Rust Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/math/README.md Shows how to get the generator of the BLS12-381 curve and perform scalar multiplication and addition operations. ```rust use lambdaworks_math::elliptic_curve:: short_weierstrass::curves::bls12_381::curve::BLS12381Curve, traits::IsEllipticCurve, ; let generator = BLS12381Curve::generator(); let doubled = generator.operate_with_self(2u64); let sum = generator.operate_with(&doubled); ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/math/src/field/README.md Execute the complete benchmark suite for the lambdaworks project. ```bash make benchmarks ``` -------------------------------- ### Rust XMSS Usage Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/xmss-signature/README.md Demonstrates how to use the XMSS library in Rust, including creating an instance, generating a key pair, signing a message, and verifying the signature. Ensure secure random number generation for production environments. ```rust use xmss_signature::{Xmss, Sha256Hasher}; // Create XMSS instance let xmss = Xmss::new(Sha256Hasher::new()); // Generate key pair (use secure random in production!) let mut seed = [0u8; 96]; rand::thread_rng().fill_bytes(&mut seed); let (public_key, mut secret_key) = xmss.keygen(&seed); // Sign a message let message = b"Hello, post-quantum world!"; let signature = xmss.sign(message, &mut secret_key)?; // Verify assert!(xmss.verify(message, &signature, &public_key)); // Check remaining signatures println!("Remaining signatures: {}", secret_key.remaining_signatures()); ``` -------------------------------- ### Merkle Leaf Value Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/merkle-tree-cli/README.md The content of the TXT file storing the value of a specific leaf, generated after running the generate-proof command. ```plaintext 0x12345 ``` -------------------------------- ### Elliptic Curve Operations Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/docs/src/getting-started.md Shows scalar multiplication and point addition on the BLS12-381 elliptic curve. Requires `lambdaworks-math` dependency. ```rust use lambdaworks_math::elliptic_curve::short_weierstrass::curves::bls12_381::curve::BLS12381Curve; use lambdaworks_math::elliptic_curve::traits::IsEllipticCurve; use lambdaworks_math::cyclic_group::IsGroup; fn main() { // Get the generator point let g = BLS12381Curve::generator(); // Scalar multiplication: compute 5 * G let five_g = g.operate_with_self(5u64); // Point addition: compute G + 5G = 6G let six_g = g.operate_with(&five_g); // Verify: 6G = 6 * G let six_g_direct = g.operate_with_self(6u64); assert_eq!(six_g.to_affine(), six_g_direct.to_affine()); println!("6G computed two ways - they match!"); } ``` -------------------------------- ### Run Univariate to Multilinear Transform Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/provers/gkr-logup/README.md Converts polynomial evaluations from a cyclic domain to a multilinear extension layout using IFFT and bit-reversal, then applies the standard multilinear GKR prover. This is an alternative to the univariate IOP. ```bash cargo run -p lambdaworks-gkr-logup --example univariate_to_multilinear ``` -------------------------------- ### Generating and Verifying Proofs Source: https://github.com/lambdaclass/lambdaworks/blob/main/crates/crypto/src/commitments/README.md Explains how to generate an opening proof for a polynomial evaluation and verify its validity. ```APIDOC ## Generating and Verifying Proofs ### Description Generates a proof for a polynomial's evaluation at a specific point and verifies the proof against the commitment. ### Method Proof Generation and Verification ### Endpoint N/A (Code-based operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming 'kzg' is an initialized KateZaveruchaGoldberg instance and 'p' is a Polynomial // Choose a point to evaluate the polynomial let x = -FieldElement::one(); // Compute the evaluation let y = p.evaluate(&x); // Should be 0 for p(x) = x + 1 when x = -1 // Generate a proof for this evaluation let proof = kzg.open(&x, &y, &p); // Verify the proof let is_valid = kzg.verify(&x, &y, &commitment, &proof); assert!(is_valid, "Proof verification failed"); ``` ### Response #### Success Response (200) - **is_valid** (bool) - True if the proof is valid, false otherwise. #### Response Example N/A (Verification is a boolean result within code) ``` -------------------------------- ### Merkle Tree Root Output Example Source: https://github.com/lambdaclass/lambdaworks/blob/main/examples/merkle-tree-cli/README.md The content of the TXT file that stores the Merkle Tree root, generated after running the generate-tree command. ```plaintext 0xa3bbbb9eac9f79d18862b802ea79f87e75efc37d4f4af4464976784c14a851b69c09aa04b1e8a8d1eb9825b713dc6ca ```