### Run Example Programs with Custom Parameters Source: https://context7.com/irreducibleoss/binius/llms.txt Execute example programs with custom parameters to test different configurations and scales. This demonstrates how to pass arguments to the example binaries. ```bash cargo run --release --example sha256 -- --n-blocks 16384 ``` ```bash cargo run --release --example keccak -- --n-permutations 1024 --log-inv-rate 2 ``` -------------------------------- ### Run Example Programs Source: https://context7.com/irreducibleoss/binius/llms.txt Execute example programs demonstrating various use cases of Binius. The '--release' flag enables optimizations for better performance. Examples include SHA-256, Keccak, u32_add, and Merkle tree proofs. ```bash cargo run --release --example sha256 # SHA-256 proof generation ``` ```bash cargo run --release --example keccak # Keccak-f permutation proof ``` ```bash cargo run --release --example u32_add # 32-bit addition proof ``` ```bash cargo run --release --example merkle_tree # Merkle tree proof ``` -------------------------------- ### Run SNARK example Source: https://github.com/irreducibleoss/binius/blob/main/README.md Execute the sha256_circuit example in release mode. ```bash cargo run --release --example sha256_circuit ``` -------------------------------- ### Run Specific Benchmarks Source: https://context7.com/irreducibleoss/binius/llms.txt Execute a specific benchmark by providing its name to the 'cargo bench' command. Examples include 'sumcheck' and 'poly_commit'. ```bash cargo bench --bench sumcheck ``` ```bash cargo bench --bench poly_commit ``` -------------------------------- ### Commit message style Source: https://github.com/irreducibleoss/binius/blob/main/CONTRIBUTING.md Examples of preferred and discouraged commit message phrasing. ```text ❌ This function will return the right answer ✅ This function returns the right answer ❌ Fixed the bug in the gizmo ✅ Fix the bug in the gizmo ``` -------------------------------- ### Building Constraint Systems with Binius M3 Source: https://context7.com/irreducibleoss/binius/llms.txt Illustrates how to initialize a ConstraintSystem and define tables, columns, and data flow channels for M3 arithmetization. Use this to structure your zero-knowledge computation. Ensure channels are properly defined before use. ```rust use binius_m3::builder::{ConstraintSystem, B1, B8, B32, B128}; // Create a new constraint system let mut cs = ConstraintSystem::::new(); // Add a channel for data flow between tables let data_channel = cs.add_channel("data"); // Add a table to the constraint system let mut table = cs.add_table("computation"); // Add committed columns (witness data provided by prover) let input_a: Col = table.add_committed("input_a"); let input_b: Col = table.add_committed("input_b"); // Add computed columns (derived from other columns) let output = table.add_computed("output", input_a * input_b); // Add constant columns let constant_val = table.add_constant("const", [B32::new(42)]); // Assert zero constraint (expression must equal zero for all rows) table.assert_zero("constraint", input_a * input_b - output); // Assert column values are non-zero table.assert_nonzero(input_a); // Push/pull data through channels table.push(data_channel, [input_a, input_b]); let table_id = table.id(); ``` -------------------------------- ### Generate local API documentation Source: https://github.com/irreducibleoss/binius/blob/main/README.md Build the project's documentation locally without dependencies. ```bash cargo doc --no-deps ``` -------------------------------- ### Generate and Verify Binius Proofs Source: https://context7.com/irreducibleoss/binius/llms.txt This snippet demonstrates the process of compiling a constraint system, generating a proof using a compute layer, and then verifying that proof. It involves setting up the necessary cryptographic components and parameters for proving and verification. ```rust use binius_core::{constraint_system, fiat_shamir::HasherChallenger}; use binius_m3::builder::{ConstraintSystem, WitnessIndex, B128}; use binius_compute::{ComputeHolder, cpu::alloc::CpuComputeAllocator}; use binius_fast_compute::layer::FastCpuLayerHolder; use binius_field::{ arch::OptimalUnderlier, as_packed_field::PackedType, tower::CanonicalTowerFamily }; use binius_hal::make_portable_backend; use binius_hash::groestl::{Groestl256, Groestl256ByteCompression, Groestl256Parallel}; // Build constraint system and witness (see previous examples) let mut cs = ConstraintSystem::new(); // ... add tables and constraints ... let mut allocator = CpuComputeAllocator::new(1 << 20); let allocator = allocator.into_bump_allocator(); let mut witness = WitnessIndex::>::new(&cs, &allocator); // ... fill witness ... // Compile constraint system let ccs = cs.compile().unwrap(); let cs_digest = ccs.digest::(); let table_sizes = witness.table_sizes(); let witness = witness.into_multilinear_extension_index(); // Setup compute layer let mut compute_holder = FastCpuLayerHolder< CanonicalTowerFamily, PackedType, >::new(1 << 20, 1 << 28); // Generate proof const SECURITY_BITS: usize = 100; const LOG_INV_RATE: usize = 1; let boundaries = vec![]; let proof = constraint_system::prove::< _, OptimalUnderlier, CanonicalTowerFamily, Groestl256Parallel, Groestl256ByteCompression, HasherChallenger, _, _, _, >( &mut compute_holder.to_data(), &ccs, LOG_INV_RATE, SECURITY_BITS, &cs_digest, &boundaries, &table_sizes, witness, &make_portable_backend(), ).unwrap(); println!("Proof size: {} bytes", proof.get_proof_size()); // Verify proof constraint_system::verify::< OptimalUnderlier, CanonicalTowerFamily, Groestl256, Groestl256ByteCompression, HasherChallenger, >(&ccs, LOG_INV_RATE, SECURITY_BITS, &cs_digest, &boundaries, proof).unwrap(); ``` -------------------------------- ### Generate Local Documentation Source: https://context7.com/irreducibleoss/binius/llms.txt Generate local documentation for the project without including external dependencies. The '--open' flag automatically opens the generated documentation in a web browser. ```bash cargo doc --no-deps --open ``` -------------------------------- ### Configure and Use U32Add Gadget Source: https://context7.com/irreducibleoss/binius/llms.txt Set up a constraint system, add a U32Add gadget for 32-bit addition with optional carry, and populate witness data for testing. Ensure correct input and output column configurations. ```rust use binius_m3:: builder::{ConstraintSystem, WitnessIndex, TableBuilder, B1, B128, Col}, gadgets::add::{U32Add, U32AddFlags}; use binius_compute::cpu::alloc::CpuComputeAllocator; use binius_field::{arch::OptimalUnderlier, as_packed_field::PackedType}; let mut cs = ConstraintSystem::new(); let mut table = cs.add_table("u32_add"); // Create input columns (32 bits packed vertically) let xin: Col = table.add_committed("xin"); let yin: Col = table.add_committed("yin"); // Configure addition flags let flags = U32AddFlags { carry_in_bit: None, // No external carry input expose_final_carry: true, commit_zout: true, // Commit output column }; // Create the adder gadget let adder = U32Add::new(&mut table, xin, yin, flags); // Access outputs let zout: Col = adder.zout; // Sum result let carry: Option> = adder.final_carry; // Overflow bit let table_id = table.id(); drop(table); // Test data let test_vector: Vec<(u32, u32)> = vec![ (0xFFFFFFFF, 0x00000001), // Overflow case (0x12345678, 0x87654321), (0, 0), ]; // Create and populate witness let mut allocator = CpuComputeAllocator::new(1 << 12); let allocator = allocator.into_bump_allocator(); let mut witness = WitnessIndex::>::new(&cs, &allocator); let table_witness = witness.init_table(table_id, test_vector.len()).unwrap(); let mut segment = table_witness.full_segment(); // Fill input columns { let mut xin_bits = segment.get_mut_as::(adder.xin).unwrap(); let mut yin_bits = segment.get_mut_as::(adder.yin).unwrap(); for (i, (x, y)) in test_vector.iter().enumerate() { xin_bits[i] = *x; yin_bits[i] = *y; } } // Populate gadget internal columns adder.populate(&mut segment).unwrap(); // Verify results let zout_bits = segment.get_as::(adder.zout).unwrap(); assert_eq!(zout_bits[0], 0x00000000); // 0xFFFFFFFF + 1 overflows to 0 ``` -------------------------------- ### Documenting components Source: https://github.com/irreducibleoss/binius/blob/main/CONTRIBUTING.md Recommended structure for item documentation. ```text [short sentence explaining what it is] [more detailed explanation] [at least one code example that users can copy/paste to try it] [even more advanced explanations if necessary] ``` -------------------------------- ### Implement Keccak Gadget with Table Filler Source: https://context7.com/irreducibleoss/binius/llms.txt Set up a constraint system and Keccakf gadget. Define a custom `TableFiller` for Keccak operations and populate witness data with random input states for parallel processing. ```rust use binius_m3:: builder::{ConstraintSystem, WitnessIndex, TableFiller, TableWitnessSegment, TableId, B1, B8, B64, B128}, gadgets::hash::keccak::{StateMatrix, stacked::Keccakf}; use binius_field::{PackedFieldIndexable, PackedExtension, PackedSubfield, linear_transformation::PackedTransformationFactory}; use binius_compute::cpu::alloc::CpuComputeAllocator; use binius_field::{arch::OptimalUnderlier, as_packed_field::PackedType}; use anyhow::Result; // Create constraint system with Keccak table let mut cs = ConstraintSystem::new(); let mut table = cs.add_table("keccak_permutation"); let keccakf = Keccakf::new(&mut table); let table_id = table.id(); drop(table); // Define a table filler for Keccak struct KeccakTable { table_id: TableId, keccakf: Keccakf, } impl

TableFiller

for KeccakTable where P: PackedFieldIndexable + PackedExtension + PackedExtension + PackedExtension, PackedSubfield: PackedTransformationFactory>, { type Event = StateMatrix; fn id(&self) -> TableId { self.table_id } fn fill(&self, rows: &[Self::Event], witness: &mut TableWitnessSegment

) -> Result<()> { self.keccakf.populate_state_in(witness, rows)?; self.keccakf.populate(witness)?; Ok(()) } } // Create random input states use rand::RngCore; let mut rng = rand::rng(); let n_permutations = 512; let events: Vec> = (0..n_permutations) .map(|_| StateMatrix::from_fn(|_| rng.next_u64())) .collect(); let keccak_table = KeccakTable { table_id, keccakf }; // Allocate and fill witness let mut allocator = CpuComputeAllocator::new(1 << 20); let allocator = allocator.into_bump_allocator(); let mut witness = WitnessIndex::new(&cs, &allocator); witness.fill_table_parallel(&keccak_table, &events).unwrap(); ``` -------------------------------- ### Run All Benchmarks Source: https://context7.com/irreducibleoss/binius/llms.txt Execute all benchmarks included in the project using Cargo. This command utilizes the criterion library for benchmarking. ```bash cargo bench ``` -------------------------------- ### Enable native CPU optimizations Source: https://github.com/irreducibleoss/binius/blob/main/README.md Set the RUSTFLAGS environment variable to enable target-cpu=native optimizations. ```bash RUSTFLAGS="-C target-cpu=native" ``` -------------------------------- ### Configure Cargo release profile Source: https://github.com/irreducibleoss/binius/blob/main/README.md Add these lines to Cargo.toml to enable fat link-time optimization for better performance. ```toml [profile.release] lto = "fat" ``` -------------------------------- ### Run automated checks Source: https://github.com/irreducibleoss/binius/blob/main/CONTRIBUTING.md Commands to execute the project's formatter and linter. ```bash $ cargo fmt $ cargo clippy --all --all-features --tests --benches --examples -- -D warnings ``` -------------------------------- ### Initialize binius Math Rendering Source: https://github.com/irreducibleoss/binius/blob/main/doc/katex-header.html Call this function within a DOMContentLoaded event listener to ensure the document is fully loaded before rendering math. Configure delimiters for different display modes (inline and block). ```javascript document.addEventListener("DOMContentLoaded", function () { renderMathInElement(document.body, { delimiters: [ {left: "$$", right: "$$", display: true}, {left: "\\(", right: "\\)", display: false}, {left: "$", right: "$", display: false}, {left: "\[", right: "\]", display: true} ] }); }); ``` -------------------------------- ### Check for GFNI support Source: https://github.com/irreducibleoss/binius/blob/main/README.md Verify if the current processor supports the Galois Field New Instructions (GFNI) extension. ```bash rustc --print cfg -C target-cpu=native | grep gfni ``` -------------------------------- ### Run Unit Tests Source: https://context7.com/irreducibleoss/binius/llms.txt Execute all unit tests defined within the project using Cargo. This command helps ensure the correctness of individual components. ```bash cargo test ``` -------------------------------- ### Define and Fill a Custom Addition Table Source: https://context7.com/irreducibleoss/binius/llms.txt Implement a `TableFiller` for an addition table. This involves defining the table's structure and providing a `fill` method to populate its columns with data based on input events. Ensure all necessary columns are correctly accessed and populated. ```rust use binius_m3::builder::{ ConstraintSystem, WitnessIndex, TableFiller, TableWitnessSegment, TableId, B1, B32, B128, Col, }; use binius_compute::cpu::alloc::CpuComputeAllocator; use binius_field::{arch::OptimalUnderlier, as_packed_field::PackedType, PackedFieldIndexable, PackedExtension}; use anyhow::Result; // Define a table filler struct AdditionTable { table_id: TableId, x: Col, y: Col, sum: Col, } impl TableFiller> for AdditionTable { type Event = (u32, u32); // Input event type fn id(&self) -> TableId { self.table_id } fn fill( &self, rows: &[Self::Event], witness: &mut TableWitnessSegment>, ) -> Result<()> { // Get mutable access to columns let mut x_col = witness.get_scalars_mut(self.x)?; let mut y_col = witness.get_scalars_mut(self.y)?; let mut sum_col = witness.get_scalars_mut(self.sum)?; for (i, (x, y)) in rows.iter().enumerate() { x_col[i] = B32::new(*x); y_col[i] = B32::new(*y); sum_col[i] = B32::new(x.wrapping_add(*y)); } Ok(()) } } // Usage: let mut cs = ConstraintSystem::new(); let mut table = cs.add_table("addition"); let x = table.add_committed("x"); let y = table.add_committed("y"); let sum = table.add_committed("sum"); table.assert_zero("add_constraint", x + y - sum); let table_id = table.id(); drop(table); let addition_table = AdditionTable { table_id, x, y, sum }; let events = vec![(1u32, 2u32), (100, 200), (0xFFFFFFFF, 1)]; // Allocate witness memory let mut allocator = CpuComputeAllocator::new(1 << 12); let allocator = allocator.into_bump_allocator(); // Create and fill witness let mut witness = WitnessIndex::new(&cs, &allocator); witness.fill_table_parallel(&addition_table, &events).unwrap(); // Get table sizes for proving let table_sizes = witness.table_sizes(); ``` -------------------------------- ### Table Builder and Column Types in Binius Source: https://context7.com/irreducibleoss/binius/llms.txt Shows how to use TableBuilder to define various column types within a table, including committed, computed, shifted, packed, and selected columns. This is essential for defining the structure and relationships of data in your constraint system. Pay attention to packing and shifting parameters for correct data interpretation. ```rust use binius_m3::builder::{TableBuilder, Table, Col, B1, B8, B32, B128}; use binius_core::oracle::ShiftVariant; let mut inner_table = Table::::new(0, "example_table"); let mut table = TableBuilder::new(&mut inner_table); // Committed columns with vertical packing (VALUES_PER_ROW) let bits: Col = table.add_committed("bits"); // 32 bits packed vertically let bytes: Col = table.add_committed("bytes"); // 4 bytes packed // Multiple committed columns at once let data: [Col; 8] = table.add_committed_multiple("data"); // Shifted column (for accessing adjacent values) let bits_shifted = table.add_shifted( "bits_shifted", bits, 5, // log_block_size 1, // offset ShiftVariant::LogicalLeft // shift direction ); // Packed column (reinterpret smaller field as larger) let packed: Col = table.add_packed("packed", bits); // Selected column (extract single value from packed column) let first_bit: Col = table.add_selected("first_bit", bits, 0); // Namespace for organizing columns let mut arith_ns = table.with_namespace("arithmetic"); let add_result = arith_ns.add_committed::("result"); // Column name will be "arithmetic::result" // Require power-of-two table size table.require_power_of_two_size(); // Or require fixed size table.require_fixed_size(10); // exactly 2^10 = 1024 rows ``` -------------------------------- ### Binary Tower Field Operations in Rust Source: https://context7.com/irreducibleoss/binius/llms.txt Demonstrates creating and performing arithmetic operations on elements of binary tower fields like BinaryField32b. Includes field arithmetic, exponentiation, and conversion between tower levels. Ensure the correct field type is used for operations. ```rust use binius_field::{ BinaryField1b, BinaryField8b, BinaryField16b, BinaryField32b, BinaryField64b, BinaryField128b, TowerField, Field, }; // Create field elements let a = BinaryField32b::new(0x12345678); let b = BinaryField32b::new(0x87654321); // Field arithmetic (addition is XOR in binary fields) let sum = a + b; let product = a * b; let inverse = a.invert().unwrap(); // Exponentiation let squared = a * a; let powered = a.pow([3u64]); // Check tower level (log2 of bit width) assert_eq!(BinaryField32b::TOWER_LEVEL, 5); // 2^5 = 32 bits // Convert between tower levels let as_128: BinaryField128b = a.into(); ``` -------------------------------- ### Implement SHA-256 Gadget Source: https://context7.com/irreducibleoss/binius/llms.txt Defines a table filler for the SHA-256 compression function and populates the witness with random message blocks. ```rust use binius_m3::{ builder::{ConstraintSystem, WitnessIndex, TableFiller, TableWitnessSegment, TableId, B1, B32, B128}, gadgets::hash::sha256::Sha256, }; use binius_field::{PackedFieldIndexable, PackedExtension}; use binius_compute::cpu::alloc::CpuComputeAllocator; use binius_field::{arch::OptimalUnderlier, as_packed_field::PackedType}; use anyhow::Result; // Create constraint system with SHA-256 table let mut cs = ConstraintSystem::new(); let mut table = cs.add_table("sha256"); let sha256 = Sha256::new(&mut table); let table_id = table.id(); drop(table); // Table filler for SHA-256 struct Sha256Table { table_id: TableId, sha256: Sha256, } impl

TableFiller

for Sha256Table where P: PackedFieldIndexable + PackedExtension + PackedExtension, { type Event = [u32; 16]; // 512-bit message block as 16 u32s fn id(&self) -> TableId { self.table_id } fn fill(&self, rows: &[Self::Event], witness: &mut TableWitnessSegment

) -> Result<()> { self.sha256.populate(witness, rows.iter())?; Ok(()) } } // Create random message blocks use rand::RngCore; let mut rng = rand::rng(); let n_blocks = 8192; let events: Vec<[u32; 16]> = (0..n_blocks) .map(|_| { let mut block = [0u32; 16]; for word in &mut block { *word = rng.next_u32(); } block }) .collect(); let sha256_table = Sha256Table { table_id, sha256 }; // Allocate and fill witness let mut allocator = CpuComputeAllocator::new(1 << 20); let allocator = allocator.into_bump_allocator(); let mut witness = WitnessIndex::new(&cs, &allocator); witness.fill_table_parallel(&sha256_table, &events).unwrap(); ``` -------------------------------- ### Enable CPU-Specific Optimizations Source: https://context7.com/irreducibleoss/binius/llms.txt Set the RUSTFLAGS environment variable to enable CPU-specific optimizations for improved performance. This is recommended for leveraging specific CPU instruction sets like GFNI. ```bash export RUSTFLAGS="-C target-cpu=native" ``` -------------------------------- ### Handle errors with expect Source: https://github.com/irreducibleoss/binius/blob/main/CONTRIBUTING.md Preferred way to handle potential errors in library code instead of using unwrap. ```rust let mut target_path = self.path().expect( "self is instance of DiskDirectory;\ DiskDirectory always returns path;\ qed" ); ``` -------------------------------- ### Define Arithmetic Constraints Source: https://context7.com/irreducibleoss/binius/llms.txt Utilizes the Expr DSL to perform arithmetic operations, define zero-constraints, and create computed columns. ```rust use binius_m3::builder::{ConstraintSystem, TableBuilder, Col, Expr, B32, B128}; let mut cs = ConstraintSystem::new(); let mut table = cs.add_table("arithmetic"); let a: Col = table.add_committed("a"); let b: Col = table.add_committed("b"); let c: Col = table.add_committed("c"); // Basic arithmetic operations let sum: Expr = a + b; let diff: Expr = a - b; let prod: Expr = a * b; let scaled: Expr = a * B32::new(5); // Complex expressions let quadratic = a * a + b * b + c * c; let polynomial = a * b * c + a * b + b * c + a + b + c; // Constraints from expressions table.assert_zero("sum_constraint", a + b - c); // a + b = c table.assert_zero("product_constraint", a * b - c); // a * b = c // Computed columns from expressions let computed = table.add_computed("computed", a * b + c); // Powers using multiplication let a_squared = a * a; let a_cubed = a * a * a; // Constants in expressions let with_const = a + B32::new(42); let zero_check = a * B32::ZERO; let identity = a * B32::ONE; ``` -------------------------------- ### Manage Data Flow with Channels Source: https://context7.com/irreducibleoss/binius/llms.txt Uses push/pull semantics to enforce multiset matching between producer and consumer tables, including conditional logic with selectors. ```rust use binius_m3::builder::{ConstraintSystem, FlushOpts, B32, B128, Col}; use binius_core::constraint_system::channel::Boundary; let mut cs = ConstraintSystem::new(); // Create channels for different data flows let lookup_channel = cs.add_channel("lookup"); let memory_channel = cs.add_channel("memory"); // Producer table - pushes values to channel let mut producer = cs.add_table("producer"); let output_a: Col = producer.add_committed("output_a"); let output_b: Col = producer.add_committed("output_b"); // Push values to channel (can be pulled by another table) producer.push(lookup_channel, [output_a, output_b]); let producer_id = producer.id(); drop(producer); // Consumer table - pulls values from channel let mut consumer = cs.add_table("consumer"); let input_a: Col = consumer.add_committed("input_a"); let input_b: Col = consumer.add_committed("input_b"); // Pull values from channel (must match pushed values) consumer.pull(lookup_channel, [input_a, input_b]); // Use selectors for conditional pushing/pulling let selector: Col = consumer.add_committed("selector"); consumer.push_with_opts( memory_channel, [input_a], FlushOpts { multiplicity: 1, selectors: vec![selector], // Only push when selector is 1 } ); // Pull with multiplicity (for lookups used multiple times) consumer.pull_with_opts( lookup_channel, [input_a], FlushOpts { multiplicity: 4, // This lookup is used 4 times selectors: vec![], } ); let consumer_id = consumer.id(); drop(consumer); // Boundary values are known inputs/outputs visible to verifier let boundaries: Vec> = vec![ // Boundary values would be created here for public inputs ]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.