From 9eac95121e3eb19d80a45b5449c758d0cb074e3d Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Wed, 19 Aug 2026 11:42:34 -0400 Subject: [PATCH 01/22] feat: load a ceremony proving key and expose its verifier constants A node must not derive its own key: circuit_specific_setup leaves one party able to forge any statement, which spec 18.2's multiparty Phase 2 exists to prevent. load_proving_key reads a ceremony's output instead, kept as a separate function so the unsound path cannot be reached by omitting an argument, and validating point encodings once at load rather than trusting them per proof. verifying_key_constants derives the flat field elements the generated Solidity verifier compiles in. A node holds only the proving half but the escrow embeds the verifying half, so this lets it confirm the two came from the same setup before proving rather than discovering the mismatch as a rejected proof after fronting a transfer. A test pins the derivation against contracts/Verifier.sol. Tests share one key: setup is ~8.7 GiB, and four of them in parallel exhausted memory before reaching an assertion. --- crates/prover/src/lib.rs | 98 ++++++++++++++++++++++++ crates/prover/tests/settlement.rs | 122 +++++++++++++++++++++++++++++- 2 files changed, 217 insertions(+), 3 deletions(-) diff --git a/crates/prover/src/lib.rs b/crates/prover/src/lib.rs index 2275f0c..756275c 100644 --- a/crates/prover/src/lib.rs +++ b/crates/prover/src/lib.rs @@ -131,6 +131,9 @@ pub fn proof_points(proof: &Proof) -> [[u8; 32]; 8] { /// What can go wrong producing a settlement proof. #[derive(Debug)] pub enum SettlementError { + /// A proving key could not be read: wrong encoding, truncated, or not a + /// key for this curve. + KeyLoad(String), Setup(String), Prove(String), Verify(String), @@ -144,6 +147,7 @@ pub enum SettlementError { impl std::fmt::Display for SettlementError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Self::KeyLoad(e) => write!(f, "proving key could not be loaded: {e}"), Self::Setup(e) => write!(f, "groth16 setup failed: {e}"), Self::Prove(e) => write!(f, "proving failed: {e}"), Self::Verify(e) => write!(f, "verification errored: {e}"), @@ -183,3 +187,97 @@ pub fn check_bounds(bounds: Bounds, w: &Witness) -> Result<(), SettlementError> } Ok(()) } + +/// Loads a proving key produced by the trusted setup. +/// +/// # Why this is not `setup` +/// +/// [`setup`] runs `circuit_specific_setup`, where one party learns the toxic +/// waste and can forge a proof for any statement. Spec 18.2 requires the +/// production key come from a multiparty Phase 2 instead, so a node must load a +/// ceremony's output rather than derive its own. Keeping the two as separate +/// functions means a caller cannot reach for the unsound one by leaving an +/// argument off. +/// +/// `compressed` must match how the ceremony serialized the key: the encodings +/// are not self-describing, and reading one as the other fails at a point curve +/// check rather than as a clean length error. +pub fn load_proving_key( + bytes: &[u8], + compressed: bool, +) -> Result, SettlementError> { + use ark_serialize::{CanonicalDeserialize, Compress, Validate}; + let mode = if compressed { + Compress::Yes + } else { + Compress::No + }; + // Validated rather than trusted: a malformed key is a wrong answer, not a + // crash, and the check runs once per startup rather than per settlement. + ProvingKey::::deserialize_with_mode(bytes, mode, Validate::Yes) + .map_err(|e| SettlementError::KeyLoad(e.to_string())) +} + +/// The verifying key implied by a proving key. +/// +/// A node holds only the proving half, but the escrow embeds the verifying +/// half, and the two must come from the same setup. Deriving it here lets a +/// node check that before proving rather than discovering the mismatch as a +/// rejected proof. +pub fn verifying_key_of(pk: &ProvingKey) -> VerifyingKey { + pk.vk.clone() +} + +/// The verifying key's on-chain form: the constants the generated Solidity +/// verifier compiles in. +/// +/// Ordered as the template emits them, so a node can compare against what it +/// reads from a deployed escrow. Any difference means the key and the contract +/// came from different setups, and every proof would be rejected. +pub fn verifying_key_constants(vk: &VerifyingKey) -> VerifyingKeyConstants { + use ark_ff::PrimeField; + use num_bigint::BigUint; + + let fq = |v: ark_bn254::Fq| -> [u8; 32] { + let n: BigUint = v.into_bigint().into(); + let be = n.to_bytes_be(); + let mut out = [0u8; 32]; + out[32 - be.len()..].copy_from_slice(&be); + out + }; + + VerifyingKeyConstants { + alpha: [fq(vk.alpha_g1.x), fq(vk.alpha_g1.y)], + beta: [ + fq(vk.beta_g2.x.c1), + fq(vk.beta_g2.x.c0), + fq(vk.beta_g2.y.c1), + fq(vk.beta_g2.y.c0), + ], + gamma: [ + fq(vk.gamma_g2.x.c1), + fq(vk.gamma_g2.x.c0), + fq(vk.gamma_g2.y.c1), + fq(vk.gamma_g2.y.c0), + ], + delta: [ + fq(vk.delta_g2.x.c1), + fq(vk.delta_g2.x.c0), + fq(vk.delta_g2.y.c1), + fq(vk.delta_g2.y.c0), + ], + ic: vk.gamma_abc_g1.iter().map(|p| [fq(p.x), fq(p.y)]).collect(), + } +} + +/// A verifying key as the flat field elements the Solidity verifier holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifyingKeyConstants { + pub alpha: [[u8; 32]; 2], + pub beta: [[u8; 32]; 4], + pub gamma: [[u8; 32]; 4], + pub delta: [[u8; 32]; 4], + /// One point per public input, plus the constant term. Three entries for + /// this relation's two signals. + pub ic: Vec<[[u8; 32]; 2]>, +} diff --git a/crates/prover/tests/settlement.rs b/crates/prover/tests/settlement.rs index 4ca4882..d07d181 100644 --- a/crates/prover/tests/settlement.rs +++ b/crates/prover/tests/settlement.rs @@ -1,13 +1,23 @@ //! The library proving path produces what the escrow expects. -use mirage_prover::{check_bounds, prove_seeded, setup, SettlementError}; +use mirage_prover::{check_bounds, prove_seeded, setup, Keys, SettlementError}; use mirage_relation::{fixture, Bounds}; +use std::sync::OnceLock; + +/// One setup for the whole binary. +/// +/// Setup costs ~33s and ~8.7 GiB. Run per test and in parallel it exhausts +/// memory before any assertion is reached, so every test shares this key. +fn keys() -> &'static Keys { + static KEYS: OnceLock = OnceLock::new(); + KEYS.get_or_init(|| setup(Bounds::default(), 0).expect("setup")) +} #[test] fn proves_and_self_checks_a_genuine_settlement() { let bounds = Bounds::default(); - let keys = setup(bounds, 0).expect("setup"); - let settlement = prove_seeded(&keys, bounds, &fixture::genuine(), 0).expect("prove"); + let keys = keys(); + let settlement = prove_seeded(keys, bounds, &fixture::genuine(), 0).expect("prove"); // The signals must be the ones the native encoder derives, since that is // what the escrow recomputes from its own storage. @@ -39,3 +49,109 @@ fn rejects_a_witness_past_a_bound() { fn accepts_a_witness_within_every_bound() { check_bounds(Bounds::default(), &fixture::genuine()).expect("the fixture must fit"); } + +/// A key must survive the round trip the ceremony's output takes to a node. +#[test] +fn a_serialized_proving_key_round_trips() { + use ark_serialize::CanonicalSerialize; + + let keys = keys(); + + let mut bytes = Vec::new(); + keys.pk.serialize_compressed(&mut bytes).expect("serialize"); + let loaded = mirage_prover::load_proving_key(&bytes, true).expect("load"); + + assert_eq!( + mirage_prover::verifying_key_constants(&mirage_prover::verifying_key_of(&loaded)), + mirage_prover::verifying_key_constants(&keys.vk), + "a round-tripped key must imply the same verifying key" + ); +} + +/// Reading a compressed key as uncompressed must fail rather than yield a key +/// that produces rejected proofs. +#[test] +fn a_mismatched_encoding_is_rejected() { + use ark_serialize::CanonicalSerialize; + + let keys = keys(); + let mut bytes = Vec::new(); + keys.pk.serialize_compressed(&mut bytes).expect("serialize"); + + assert!( + mirage_prover::load_proving_key(&bytes, false).is_err(), + "a compressed key read as uncompressed must not load" + ); +} + +/// The constants must be the ones the exported verifier compiles in. +/// +/// This is the check a node runs against a deployed escrow: if the derived +/// constants and the contract's disagree, the key and the verifier came from +/// different setups and every proof would be rejected. +#[test] +fn verifying_key_constants_have_the_verifier_shape() { + let keys = keys(); + let c = mirage_prover::verifying_key_constants(&keys.vk); + + assert_eq!( + c.ic.len(), + 3, + "two public signals plus the constant term, matching PUB_0/PUB_1/CONSTANT" + ); + for (i, p) in c.ic.iter().enumerate() { + assert!( + p[0].iter().any(|&b| b != 0) || p[1].iter().any(|&b| b != 0), + "IC point {i} is the origin" + ); + } +} + +/// The derived constants must be the ones the exported verifier compiles in. +/// +/// The seeded setup is reproducible, so `contracts/Verifier.sol` is the exact +/// artifact this key produces. Parsing it back and comparing is what makes the +/// node's on-chain key check meaningful: if these agree here, a disagreement in +/// production means the escrow was built from a different setup. +#[test] +fn derived_constants_match_the_exported_verifier() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../contracts/Verifier.sol"); + let Ok(source) = std::fs::read_to_string(path) else { + eprintln!("skipping: {path} not exported"); + return; + }; + + let constant = |name: &str| -> [u8; 32] { + let line = source + .lines() + .find(|l| l.contains(&format!("constant {name} ="))) + .unwrap_or_else(|| panic!("{name} missing from the exported verifier")); + let decimal = line + .rsplit('=') + .next() + .unwrap() + .trim() + .trim_end_matches(';'); + let n: num_bigint::BigUint = decimal.parse().expect("constant is not a decimal integer"); + let be = n.to_bytes_be(); + let mut out = [0u8; 32]; + out[32 - be.len()..].copy_from_slice(&be); + out + }; + + let c = mirage_prover::verifying_key_constants(&keys().vk); + for (i, (x, y)) in [ + ("CONSTANT_X", "CONSTANT_Y"), + ("PUB_0_X", "PUB_0_Y"), + ("PUB_1_X", "PUB_1_Y"), + ] + .iter() + .enumerate() + { + assert_eq!( + c.ic[i], + [constant(x), constant(y)], + "IC point {i} disagrees with the exported verifier's {x}/{y}" + ); + } +} From f841958545d07deb351df1b114daf33b53927f57 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Fri, 21 Aug 2026 01:08:12 -0400 Subject: [PATCH 02/22] fix: give the fixture a lease a real bond() can grant The statement carried a 180-block lease and a witness 100 blocks after bonding. EscrowBase sets executionDeadline = block.number + 25, so no caller that bonded through the contract could ever hold that state: the proof was only spendable by forging bond storage directly. Narrows the lease to 25 blocks and moves the witness inside it, so a fund/bond/collect chain reproduces the statement. The header's encoded number moves with it, since the relation binds the two. Regenerates proof.json and calldata.txt. Verifier.sol is unchanged: the constraint system did not move, only the witness. --- contracts/calldata.txt | 8 ++++---- contracts/proof.json | 14 +++++++------- crates/relation/src/lib.rs | 13 ++++++++++--- foundry.lock | 3 +++ 4 files changed, 24 insertions(+), 14 deletions(-) diff --git a/contracts/calldata.txt b/contracts/calldata.txt index 1baf2ac..4ed3c65 100644 --- a/contracts/calldata.txt +++ b/contracts/calldata.txt @@ -1,6 +1,6 @@ verifyProof( - [0x284d0ca267a6bcdec14f26b25dfefef12cdbff8037b01ddf5fadb4151f50afef, 0x2287ddd069fe92f847eb4a6a67d195a71bcf3fe62954d69101c4bb8829ebd743], - [[0x1c971d655685d85217ebb32974eefa561bc9d5d833ccd43499157fe898abf95b, 0x1f08f74d689ba70827301e355613a2919e91f35afaf904a24a04aad8e6df07c4], [0x065e219d3a630fe908520b14ef2f15a8353dda97586bcafaf0fe3d4b81972791, 0x2bf5690f0e9cff95de8a7468ff6026d72b85877446c58330b31c67eb94a497a1]], - [0x245129a75240bcd5621438310e91a169a397576b4072d7198df3d23713987f47, 0x2610b905d8e5c59b04ff012274231d2d12aa477d17124053a1f53c9f03f72f18], - [0xa2e1c2121f9af063923e7fecdcdab89e, 0xe82c46cd98b51c401ee16453967d0e0b] + [0x2ae5b09b408d8d564a48df9cfb4e3a55bce45abaa2a0c939a0bfd18a5718a807, 0x1dc2874e7429b6f41cfb51ceb3a6fe32d615e1988fa407ed1a0c5f2b8022c047], + [[0x2f5864201023dfc99ad652e93c653d2e190ce8a9709c1e57880e487ebd903dd6, 0x189007e3f60ce2e65c8e085bbbee05c8eb080027e23bab8c4771abbb363d6873], [0x016233173aae2cb9843c5e75fe382a3f4319e9a5995bbef365a3fa73f3aa775d, 0x289e812f4cc2a5352fe0e01955ff121e91492df88bce52dda5507950671258ba]], + [0x2ab4942e40110425225c677a41a5d7c3a17eb8ad6be5178dde91d6f6641c611b, 0x100bb92d6c63ce0f9088c3f1b2c217b2a28c0dce2526cc1dff6602c63b7a2c49], + [0x092266ba8abfaa46c44008e2060f644e, 0xaed57f88f7d3b0a2e36fd07769591c33] ) \ No newline at end of file diff --git a/contracts/proof.json b/contracts/proof.json index 8820187..3505685 100644 --- a/contracts/proof.json +++ b/contracts/proof.json @@ -1,10 +1,10 @@ { "proof": [ - "0x284d0ca267a6bcdec14f26b25dfefef12cdbff8037b01ddf5fadb4151f50afef", "0x2287ddd069fe92f847eb4a6a67d195a71bcf3fe62954d69101c4bb8829ebd743", - "0x1c971d655685d85217ebb32974eefa561bc9d5d833ccd43499157fe898abf95b", "0x1f08f74d689ba70827301e355613a2919e91f35afaf904a24a04aad8e6df07c4", "0x065e219d3a630fe908520b14ef2f15a8353dda97586bcafaf0fe3d4b81972791", "0x2bf5690f0e9cff95de8a7468ff6026d72b85877446c58330b31c67eb94a497a1", - "0x245129a75240bcd5621438310e91a169a397576b4072d7198df3d23713987f47", "0x2610b905d8e5c59b04ff012274231d2d12aa477d17124053a1f53c9f03f72f18" + "0x2ae5b09b408d8d564a48df9cfb4e3a55bce45abaa2a0c939a0bfd18a5718a807", "0x1dc2874e7429b6f41cfb51ceb3a6fe32d615e1988fa407ed1a0c5f2b8022c047", + "0x2f5864201023dfc99ad652e93c653d2e190ce8a9709c1e57880e487ebd903dd6", "0x189007e3f60ce2e65c8e085bbbee05c8eb080027e23bab8c4771abbb363d6873", "0x016233173aae2cb9843c5e75fe382a3f4319e9a5995bbef365a3fa73f3aa775d", "0x289e812f4cc2a5352fe0e01955ff121e91492df88bce52dda5507950671258ba", + "0x2ab4942e40110425225c677a41a5d7c3a17eb8ad6be5178dde91d6f6641c611b", "0x100bb92d6c63ce0f9088c3f1b2c217b2a28c0dce2526cc1dff6602c63b7a2c49" ], - "publicSignals": ["0xa2e1c2121f9af063923e7fecdcdab89e", "0xe82c46cd98b51c401ee16453967d0e0b"], + "publicSignals": ["0x092266ba8abfaa46c44008e2060f644e", "0xaed57f88f7d3b0a2e36fd07769591c33"], "statement": { "instanceDomain": "0x1111111111111111111111111111111111111111111111111111111111111111", "chainId": 1, @@ -14,12 +14,12 @@ "intentCommitment": "0x187e649a78731c2dd46dc0c66cd13b2d06c78b5a81825efe17d51f6194aa46be", "bondAttempt": 1, "bondStartBlock": 20999900, - "bondDeadline": 21000080, + "bondDeadline": 20999925, "bondedCollector": "0x5555555555555555555555555555555555555555", "rowPayoutAsset": "0x7777777777777777777777777777777777777777", "rowPayoutAmount": "0x000000000000000000000000000000000000000000000000000000003b9aca00", - "witnessBlockNumber": 21000000, - "witnessBlockHash": "0xac9ad31ae5b5ab30cb08b4bc58b5baaff1a1747be050eb2ebfc1dc36348f95ee" + "witnessBlockNumber": 20999910, + "witnessBlockHash": "0x1d05fb8842f7f9f879a82357bcc0ec8e51d4cfdfcef3458d6d7660622f31d00a" }, "note": "proof is [a.x, a.y, b.x1, b.x0, b.y1, b.y0, c.x, c.y]; the EVM pairing precompile takes G2 coordinates in that order, which is the reverse of arkworks' serialization. The statement block is what the escrow must reproduce from its own state for this proof to verify against it." } diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index c4d5bfd..38c29bb 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -582,7 +582,7 @@ pub mod fixture { // The header must carry the trie's actual root, or the binding chain // header -> receiptsRoot -> inclusion does not close. let root_hash = keccak(&root_node); - let header = header_with_receipts_root(&root_hash, 21_000_000); + let header = header_with_receipts_root(&root_hash, 20_999_910); let header_hash = keccak(&header); Witness { @@ -603,8 +603,15 @@ pub mod fixture { // to what the statement hash carries. intent_commitment: commitment, bond_attempt: 1, + // A lease a real `bond()` can actually grant: the escrow sets + // `bondStartBlock = block.number` and + // `executionDeadline = block.number + BOND_DURATION_BLOCKS`, + // which is 25. A wider lease makes the proof unusable by any + // caller that bonded through the contract rather than by + // writing storage, so the consumers of this fixture would have + // to forge the bond state to spend it. bond_start_block: 20_999_900, - bond_deadline: 21_000_080, + bond_deadline: 20_999_925, bonded_collector: [0x55; 20], // An ERC-20 payout asset, not native. The escrow that consumes // this fixture is EscrowERC20, which rejects a zero payout @@ -615,7 +622,7 @@ pub mod fixture { a[24..].copy_from_slice(&1_000_000_000u64.to_be_bytes()); a }, - witness_block_number: 21_000_000, + witness_block_number: 20_999_910, witness_block_hash: header_hash, }, } diff --git a/foundry.lock b/foundry.lock index 1a0a229..b6139b2 100644 --- a/foundry.lock +++ b/foundry.lock @@ -4,5 +4,8 @@ }, "../lib/openzeppelin-contracts": { "rev": "5fd1781b1454fd1ef8e722282f86f9293cacf256" + }, + "lib/forge-std": { + "rev": "467ffd422ca01fed5797a4c766a1e4e3a5327902" } } \ No newline at end of file From 8274905a083c0c85a595686f0806bcbbf1701fd6 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Fri, 21 Aug 2026 01:22:53 -0400 Subject: [PATCH 03/22] fix: put the fixture escrow at a reachable CREATE address The statement committed to 0x22..22, which no deployment produces. A consumer could only get the contract there by relocating it after construction, and that breaks bond(): the escrow caches its EIP-712 domain separator over address(this) at construction, so a moved copy rejects every signature written against its new address. Uses the address a CREATE from 0x01..01 at nonce 0 yields, so the escrow can be deployed where the proof expects it and the whole fund/bond/ collect chain runs. The intent commitment moves with it, since spec 8.3 binds the escrow. --- contracts/calldata.txt | 8 ++++---- contracts/proof.json | 12 ++++++------ crates/relation/src/lib.rs | 25 +++++++++++++++++++++++-- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/contracts/calldata.txt b/contracts/calldata.txt index 4ed3c65..00767d5 100644 --- a/contracts/calldata.txt +++ b/contracts/calldata.txt @@ -1,6 +1,6 @@ verifyProof( - [0x2ae5b09b408d8d564a48df9cfb4e3a55bce45abaa2a0c939a0bfd18a5718a807, 0x1dc2874e7429b6f41cfb51ceb3a6fe32d615e1988fa407ed1a0c5f2b8022c047], - [[0x2f5864201023dfc99ad652e93c653d2e190ce8a9709c1e57880e487ebd903dd6, 0x189007e3f60ce2e65c8e085bbbee05c8eb080027e23bab8c4771abbb363d6873], [0x016233173aae2cb9843c5e75fe382a3f4319e9a5995bbef365a3fa73f3aa775d, 0x289e812f4cc2a5352fe0e01955ff121e91492df88bce52dda5507950671258ba]], - [0x2ab4942e40110425225c677a41a5d7c3a17eb8ad6be5178dde91d6f6641c611b, 0x100bb92d6c63ce0f9088c3f1b2c217b2a28c0dce2526cc1dff6602c63b7a2c49], - [0x092266ba8abfaa46c44008e2060f644e, 0xaed57f88f7d3b0a2e36fd07769591c33] + [0x12854742bf7a02db2cca2a8033697c0f39e8838b4c9cd16b98517a33677bbe30, 0x18917fc0abe882532dd35ba0887f0c75affb0b97828fe2f7829bb7e40d8ca9d1], + [[0x1ddf52b69dfc5e489e09ac68e57a392bda7e0754319da64b215e6fa3c8076b7a, 0x031228b4e762fd03cd0af0d79e0c912c0d796aa9586188e83310e7621d6c6cf3], [0x090e06d7234cb155c6181b1e4d75cf15ef6df32db227b82d61d833b3eadf2686, 0x1770cc517ec797fd7be65fb31a687b44b3b7c60ce6fb2af1874e0b89ff5b4e2c]], + [0x2e6a3a0c9bbcd986501ffa2f45e03cf2b21671933e6681c9b58145024cf7bdcd, 0x06f237fcac96bb9cf2d5accadc5c373f57d042484157667cae7885680ec936ca], + [0x5ce039e6e0168697c1ee39fd592efdb1, 0x0273a75f1a45c7da3342430d209ab119] ) \ No newline at end of file diff --git a/contracts/proof.json b/contracts/proof.json index 3505685..71bfbde 100644 --- a/contracts/proof.json +++ b/contracts/proof.json @@ -1,17 +1,17 @@ { "proof": [ - "0x2ae5b09b408d8d564a48df9cfb4e3a55bce45abaa2a0c939a0bfd18a5718a807", "0x1dc2874e7429b6f41cfb51ceb3a6fe32d615e1988fa407ed1a0c5f2b8022c047", - "0x2f5864201023dfc99ad652e93c653d2e190ce8a9709c1e57880e487ebd903dd6", "0x189007e3f60ce2e65c8e085bbbee05c8eb080027e23bab8c4771abbb363d6873", "0x016233173aae2cb9843c5e75fe382a3f4319e9a5995bbef365a3fa73f3aa775d", "0x289e812f4cc2a5352fe0e01955ff121e91492df88bce52dda5507950671258ba", - "0x2ab4942e40110425225c677a41a5d7c3a17eb8ad6be5178dde91d6f6641c611b", "0x100bb92d6c63ce0f9088c3f1b2c217b2a28c0dce2526cc1dff6602c63b7a2c49" + "0x12854742bf7a02db2cca2a8033697c0f39e8838b4c9cd16b98517a33677bbe30", "0x18917fc0abe882532dd35ba0887f0c75affb0b97828fe2f7829bb7e40d8ca9d1", + "0x1ddf52b69dfc5e489e09ac68e57a392bda7e0754319da64b215e6fa3c8076b7a", "0x031228b4e762fd03cd0af0d79e0c912c0d796aa9586188e83310e7621d6c6cf3", "0x090e06d7234cb155c6181b1e4d75cf15ef6df32db227b82d61d833b3eadf2686", "0x1770cc517ec797fd7be65fb31a687b44b3b7c60ce6fb2af1874e0b89ff5b4e2c", + "0x2e6a3a0c9bbcd986501ffa2f45e03cf2b21671933e6681c9b58145024cf7bdcd", "0x06f237fcac96bb9cf2d5accadc5c373f57d042484157667cae7885680ec936ca" ], - "publicSignals": ["0x092266ba8abfaa46c44008e2060f644e", "0xaed57f88f7d3b0a2e36fd07769591c33"], + "publicSignals": ["0x5ce039e6e0168697c1ee39fd592efdb1", "0x0273a75f1a45c7da3342430d209ab119"], "statement": { "instanceDomain": "0x1111111111111111111111111111111111111111111111111111111111111111", "chainId": 1, - "escrow": "0x2222222222222222222222222222222222222222", + "escrow": "0x1c81a61a407017c58397a47d2ab28191b9b8ec9b", "requestId": "0x3333333333333333333333333333333333333333333333333333333333333333", "rowIndex": 0, - "intentCommitment": "0x187e649a78731c2dd46dc0c66cd13b2d06c78b5a81825efe17d51f6194aa46be", + "intentCommitment": "0xcecbba1151ca56f105982395b280672c18142a1e2d1a0b8dd569c4962982f860", "bondAttempt": 1, "bondStartBlock": 20999900, "bondDeadline": 20999925, diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 38c29bb..7245949 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -442,6 +442,20 @@ fn native_signals(c: &StatementContext) -> (u128, u128) { pub mod fixture { use super::Witness; + /// The escrow address the fixture statement commits to. + /// + /// This is what a `CREATE` from `0x01..01` at nonce 0 produces, so a + /// consumer can deploy the escrow at this address rather than relocating + /// it. That matters because the escrow caches its EIP-712 domain separator + /// over `address(this)` at construction: a copy moved after deployment + /// carries the separator of wherever it was built, and every bond + /// signature checked against it fails. Keeping the address reachable lets + /// the whole fund/bond/collect chain run against this proof. + pub const FIXTURE_ESCROW: [u8; 20] = [ + 0x1c, 0x81, 0xa6, 0x1a, 0x40, 0x70, 0x17, 0xc5, 0x83, 0x97, 0xa4, 0x7d, 0x2a, 0xb2, 0x81, + 0x91, 0xb9, 0xb8, 0xec, 0x9b, + ]; + fn enc_str(p: &[u8]) -> Vec { if p.len() == 1 && p[0] < 0x80 { return p.to_vec(); @@ -556,7 +570,14 @@ pub mod fixture { let intent = super::IntentOpening { instance_domain: [0x11; 32], chain_id: 1, - escrow: [0x22; 20], + // The address a CREATE from 0x01..01 at nonce 0 produces. The + // escrow caches its EIP-712 domain separator over `address(this)` + // at construction, so a consumer that wants a working `bond()` has + // to deploy the contract rather than relocate it: a relocated copy + // carries the separator of wherever it was built, and its bond + // signatures no longer validate. A reachable address keeps the + // whole fund/bond/collect chain exercisable. + escrow: FIXTURE_ESCROW, request_id: [0x33; 32], row_index: 0, asset_kind: 1, @@ -596,7 +617,7 @@ pub mod fixture { statement: super::StatementContext { instance_domain: [0x11; 32], chain_id: 1, - escrow: [0x22; 20], + escrow: FIXTURE_ESCROW, request_id: [0x33; 32], row_index: 0, // The escrow's stored commitment, so the opening above binds From 9a47b65e3d2cd48043ff2386bf3ace9792a931b4 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 24 Aug 2026 23:58:19 -0400 Subject: [PATCH 04/22] feat: serialize a proving key, and name the key types load_proving_key had no inverse, so a caller that generated a key could not persist it. save_proving_key mirrors it, sharing the compressed flag the two must agree on, and serialize_verifying_key exposes the canonical bytes that identify a setup: hashing them gives a caller a fingerprint to check an untrusted proving key against without reproducing the setup. The key types are aliased so a consumer can name what Keys holds without depending on the arkworks crates directly. --- crates/encoding/src/bin/gen_vectors.rs | 14 +++- crates/encoding/src/statement.rs | 70 +++++++++++++---- crates/encoding/src/vectors.rs | 25 ++++-- crates/fixtures/src/bin/collect.rs | 35 +++++++-- crates/fixtures/src/chain.rs | 23 ++++-- crates/fixtures/src/trie.rs | 6 +- crates/gadgets/src/bytes.rs | 22 ++++-- crates/gadgets/src/commitment.rs | 30 ++++++-- crates/gadgets/src/header.rs | 14 +++- crates/gadgets/src/keccak/permutation.rs | 14 +++- crates/gadgets/src/keccak/sponge.rs | 22 ++++-- crates/gadgets/src/lib.rs | 6 +- crates/gadgets/src/mpt/harness.rs | 11 +-- crates/gadgets/src/mpt/mod.rs | 2 +- crates/gadgets/src/mpt/node.rs | 51 ++++++++----- crates/gadgets/src/mpt/path.rs | 26 +++++-- crates/gadgets/src/mpt/tests.rs | 96 +++++++++++++++++------- crates/gadgets/src/mpt/traverse.rs | 26 +++---- crates/gadgets/src/receipt/envelope.rs | 11 ++- crates/gadgets/src/receipt/log.rs | 5 +- crates/gadgets/src/receipt/tests.rs | 51 +++++++++---- crates/gadgets/src/rlp/cursor.rs | 20 +++-- crates/gadgets/src/rlp/tests.rs | 20 +++-- crates/gadgets/src/statement.rs | 75 +++++++++++++----- crates/prover/src/bin/export_verifier.rs | 12 ++- crates/prover/src/bin/measure.rs | 18 +++-- crates/prover/src/lib.rs | 65 +++++++++++++++- crates/prover/tests/settlement.rs | 49 +++++++++++- crates/relation/src/lib.rs | 47 +++++------- crates/relation/tests/mainnet.rs | 18 +++-- 30 files changed, 647 insertions(+), 237 deletions(-) diff --git a/crates/encoding/src/bin/gen_vectors.rs b/crates/encoding/src/bin/gen_vectors.rs index 69bdfbc..90d61ca 100644 --- a/crates/encoding/src/bin/gen_vectors.rs +++ b/crates/encoding/src/bin/gen_vectors.rs @@ -23,7 +23,12 @@ fn main() -> Result<(), Box> { .iter() .map(|(name, description, intent)| { let v = IntentVector::from(intent); - Case { name, description, input: v.input, expected: v.expected } + Case { + name, + description, + input: v.input, + expected: v.expected, + } }) .collect(), }; @@ -42,7 +47,12 @@ fn main() -> Result<(), Box> { .iter() .map(|(name, description, statement)| { let v = StatementVector::from(statement); - Case { name, description, input: v.input, expected: v.expected } + Case { + name, + description, + input: v.input, + expected: v.expected, + } }) .collect(), }; diff --git a/crates/encoding/src/statement.rs b/crates/encoding/src/statement.rs index dbc6da8..0662a26 100644 --- a/crates/encoding/src/statement.rs +++ b/crates/encoding/src/statement.rs @@ -183,20 +183,62 @@ mod tests { // ever dropped from `preimage()`, this catches it. let base = sample().hash(); let mutations: Vec = vec![ - Statement { instance_domain: [0x12; 32], ..sample() }, - Statement { chain_id: 2, ..sample() }, - Statement { escrow: [0x23; 20], ..sample() }, - Statement { request_id: [0x34; 32], ..sample() }, - Statement { row_index: 1, ..sample() }, - Statement { intent_commitment: [0x45; 32], ..sample() }, - Statement { bond_attempt: 2, ..sample() }, - Statement { bond_start_block: 1001, ..sample() }, - Statement { bond_deadline: 1181, ..sample() }, - Statement { bonded_collector: [0x56; 20], ..sample() }, - Statement { row_payout_asset: [0x01; 20], ..sample() }, - Statement { row_payout_amount: [0x01; 32], ..sample() }, - Statement { witness_block_number: 1101, ..sample() }, - Statement { witness_block_hash: [0x67; 32], ..sample() }, + Statement { + instance_domain: [0x12; 32], + ..sample() + }, + Statement { + chain_id: 2, + ..sample() + }, + Statement { + escrow: [0x23; 20], + ..sample() + }, + Statement { + request_id: [0x34; 32], + ..sample() + }, + Statement { + row_index: 1, + ..sample() + }, + Statement { + intent_commitment: [0x45; 32], + ..sample() + }, + Statement { + bond_attempt: 2, + ..sample() + }, + Statement { + bond_start_block: 1001, + ..sample() + }, + Statement { + bond_deadline: 1181, + ..sample() + }, + Statement { + bonded_collector: [0x56; 20], + ..sample() + }, + Statement { + row_payout_asset: [0x01; 20], + ..sample() + }, + Statement { + row_payout_amount: [0x01; 32], + ..sample() + }, + Statement { + witness_block_number: 1101, + ..sample() + }, + Statement { + witness_block_hash: [0x67; 32], + ..sample() + }, ]; assert_eq!(mutations.len(), 14, "one case per context field"); for (i, m) in mutations.iter().enumerate() { diff --git a/crates/encoding/src/vectors.rs b/crates/encoding/src/vectors.rs index 5416acb..bc13a9b 100644 --- a/crates/encoding/src/vectors.rs +++ b/crates/encoding/src/vectors.rs @@ -76,7 +76,10 @@ pub fn intent_cases() -> Vec<(&'static str, &'static str, Intent)> { ( "erc20_row_max_index", "Row index 31, the largest valid index in a 32-row batch", - Intent { row_index: 31, ..base.clone() }, + Intent { + row_index: 31, + ..base.clone() + }, ), ( "native_row", @@ -114,12 +117,18 @@ pub fn intent_cases() -> Vec<(&'static str, &'static str, Intent)> { ( "amount_max", "settlementAmount = 2^256 - 1, both limbs saturated", - Intent { settlement_amount: [0xff; 32], ..base.clone() }, + Intent { + settlement_amount: [0xff; 32], + ..base.clone() + }, ), ( "chain_id_large", "chainId near 2^64 - 1, the widest value the circuit accepts", - Intent { chain_id: u64::MAX, ..base.clone() }, + Intent { + chain_id: u64::MAX, + ..base.clone() + }, ), ] } @@ -153,12 +162,18 @@ pub fn statement_cases(commitment: crate::Bytes32) -> Vec<(&'static str, &'stati ( "native_payout_attempt_two", "Same row, second attempt: digest must differ from attempt one", - Statement { bond_attempt: 2, ..base.clone() }, + Statement { + bond_attempt: 2, + ..base.clone() + }, ), ( "erc20_payout", "ERC-20 payout asset, exercising the asset field", - Statement { row_payout_asset: fill(0x90), ..base.clone() }, + Statement { + row_payout_asset: fill(0x90), + ..base.clone() + }, ), ( "block_numbers_wide", diff --git a/crates/fixtures/src/bin/collect.rs b/crates/fixtures/src/bin/collect.rs index e4bd5e1..3071eb3 100644 --- a/crates/fixtures/src/bin/collect.rs +++ b/crates/fixtures/src/bin/collect.rs @@ -38,13 +38,17 @@ const RPC: &str = "https://eth.drpc.org"; fn main() { let args: Vec = std::env::args().collect(); - let count = arg(&args, "--count").and_then(|v| v.parse().ok()).unwrap_or(100usize); + let count = arg(&args, "--count") + .and_then(|v| v.parse().ok()) + .unwrap_or(100usize); let out = arg(&args, "--out").unwrap_or_else(|| "test/vectors/mainnet.json".into()); let rpc_url = arg(&args, "--rpc").unwrap_or_else(|| RPC.into()); // A prime stride spreads sampling rather than clustering in one period of // activity. Kept small because free endpoints time out on blocks far from // the tip; raise it against an archive node. - let stride: u64 = arg(&args, "--stride").and_then(|v| v.parse().ok()).unwrap_or(13); + let stride: u64 = arg(&args, "--stride") + .and_then(|v| v.parse().ok()) + .unwrap_or(13); let latest = match rpc(&rpc_url, "eth_blockNumber", vec![]) { Ok(v) => u64::from_str_radix(v.as_str().unwrap_or("0x0").trim_start_matches("0x"), 16) @@ -68,7 +72,11 @@ fn main() { let want = (count - fixtures.len()).min(3); match collect_block(&rpc_url, block, want) { Ok(got) if !got.is_empty() => { - eprintln!(" block {block}: +{} (total {})", got.len(), fixtures.len() + got.len()); + eprintln!( + " block {block}: +{} (total {})", + got.len(), + fixtures.len() + got.len() + ); fixtures.extend(got); } Ok(_) => {} @@ -97,8 +105,14 @@ fn main() { if let Some(s) = dataset.shape() { eprintln!(" depth {} to {}", s.depth.0, s.depth.1); eprintln!(" node bytes {} to {}", s.node_bytes.0, s.node_bytes.1); - eprintln!(" receipt bytes {} to {}", s.receipt_bytes.0, s.receipt_bytes.1); - eprintln!(" header bytes {} to {}", s.header_bytes.0, s.header_bytes.1); + eprintln!( + " receipt bytes {} to {}", + s.receipt_bytes.0, s.receipt_bytes.1 + ); + eprintln!( + " header bytes {} to {}", + s.header_bytes.0, s.header_bytes.1 + ); eprintln!(" receipt types {:?}", s.types); eprintln!("\nagainst the compiled bounds (node 544, key 4, receipt 1024, depth 4):"); report("depth", s.depth.1, 4); @@ -114,7 +128,9 @@ fn report(name: &str, observed: usize, bound: usize) { } fn arg(args: &[String], name: &str) -> Option { - args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1).cloned()) } fn rpc(url: &str, method: &str, params: Vec) -> Result { @@ -144,10 +160,13 @@ fn rpc(url: &str, method: &str, params: Vec) -> Result { Err(format!("{method} failed: {last}")) } - fn collect_block(url: &str, number: u64, want: usize) -> Result, String> { let tag = Value::String(format!("0x{number:x}")); - let block = rpc(url, "eth_getBlockByNumber", vec![tag.clone(), Value::Bool(false)])?; + let block = rpc( + url, + "eth_getBlockByNumber", + vec![tag.clone(), Value::Bool(false)], + )?; let receipts = rpc(url, "eth_getBlockReceipts", vec![tag])?; let receipts = receipts.as_array().ok_or("receipts not an array")?; if receipts.is_empty() { diff --git a/crates/fixtures/src/chain.rs b/crates/fixtures/src/chain.rs index 3a542d3..3fab04f 100644 --- a/crates/fixtures/src/chain.rs +++ b/crates/fixtures/src/chain.rs @@ -18,7 +18,8 @@ use crate::trie::{key_for, Trie}; use crate::{from_hex, from_hex_fixed, from_hex_quantity, hash, hex_str}; /// `Transfer(address,address,uint256)`. -pub const TRANSFER_TOPIC0: &str = "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; +pub const TRANSFER_TOPIC0: &str = + "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; /// The RLP block header, in the frozen 21-field post-Prague layout. /// @@ -32,7 +33,8 @@ pub fn encode_header(h: &Value) -> Result, String> { .and_then(|v| v.as_str()) .ok_or_else(|| format!("header missing {k}")) }; - let fixed = |k: &str, n: usize| -> Result { Ok(Item::Str(from_hex_fixed(f(k)?, n)?)) }; + let fixed = + |k: &str, n: usize| -> Result { Ok(Item::Str(from_hex_fixed(f(k)?, n)?)) }; let qty = |k: &str| -> Result { Ok(Item::Str(from_hex_quantity(f(k)?)?)) }; let extra = from_hex(f("extraData")?)?; @@ -88,7 +90,10 @@ pub fn encode_receipt(r: &Value) -> Result, String> { .collect(); let status = u64::from_str_radix( - r["status"].as_str().ok_or("status")?.trim_start_matches("0x"), + r["status"] + .as_str() + .ok_or("status")? + .trim_start_matches("0x"), 16, ) .map_err(|e| e.to_string())?; @@ -104,7 +109,10 @@ pub fn encode_receipt(r: &Value) -> Result, String> { let payload = Item::List(vec![ Item::int(status), Item::int(gas), - Item::Str(from_hex_fixed(r["logsBloom"].as_str().ok_or("bloom")?, 256)?), + Item::Str(from_hex_fixed( + r["logsBloom"].as_str().ok_or("bloom")?, + 256, + )?), Item::List(logs?), ]) .encode(); @@ -198,7 +206,12 @@ pub fn inclusion_proof( let encoded = encoded?; let receipt = encoded .get(tx_index) - .ok_or_else(|| format!("tx index {tx_index} past the block's {} receipts", encoded.len()))? + .ok_or_else(|| { + format!( + "tx index {tx_index} past the block's {} receipts", + encoded.len() + ) + })? .clone(); let trie = Trie::build(&encoded); diff --git a/crates/fixtures/src/trie.rs b/crates/fixtures/src/trie.rs index 3b25d92..e2f4eba 100644 --- a/crates/fixtures/src/trie.rs +++ b/crates/fixtures/src/trie.rs @@ -211,7 +211,11 @@ mod tests { assert_eq!(hex_prefix(&[0xa], false), vec![0x1a], "odd extension"); assert_eq!(hex_prefix(&[], true), vec![0x20], "even leaf"); assert_eq!(hex_prefix(&[0xa], true), vec![0x3a], "odd leaf"); - assert_eq!(hex_prefix(&[1, 2], true), vec![0x20, 0x12], "even leaf pair"); + assert_eq!( + hex_prefix(&[1, 2], true), + vec![0x20, 0x12], + "even leaf pair" + ); } #[test] diff --git a/crates/gadgets/src/bytes.rs b/crates/gadgets/src/bytes.rs index 2a7aae0..0402c1e 100644 --- a/crates/gadgets/src/bytes.rs +++ b/crates/gadgets/src/bytes.rs @@ -32,11 +32,11 @@ use ark_r1cs_std::alloc::AllocVar; use ark_r1cs_std::boolean::Boolean; use ark_r1cs_std::convert::ToBitsGadget; use ark_r1cs_std::eq::EqGadget; -use ark_r1cs_std::GR1CSVar; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::fields::FieldVar; use ark_r1cs_std::select::CondSelectGadget; use ark_r1cs_std::uint8::UInt8; +use ark_r1cs_std::GR1CSVar; use ark_relations::gr1cs::{ConstraintSystemRef, SynthesisError}; /// `sel[i] = 1` for `i < len`, else 0. Also enforces `len <= n`. @@ -127,10 +127,7 @@ pub fn assert_zero_tail( /// Proving those three facts is equivalent to proving each `out[i] = (idx == /// i)` individually, at a fraction of the cost. Reuse the vector across every /// read against the same index. -pub fn one_hot( - idx: &FpVar, - n: usize, -) -> Result>, SynthesisError> { +pub fn one_hot(idx: &FpVar, n: usize) -> Result>, SynthesisError> { let cs = idx.cs(); let idx_val = idx.value().ok(); @@ -428,7 +425,10 @@ mod tests { fn prefix_mask_rejects_len_past_the_bound() { let cs = ConstraintSystem::::new_ref(); let _ = prefix_mask(&fp(cs.clone(), 9), 8, &Boolean::TRUE).unwrap(); - assert!(!cs.is_satisfied().unwrap(), "len 9 accepted for an 8-byte buffer"); + assert!( + !cs.is_satisfied().unwrap(), + "len 9 accepted for an 8-byte buffer" + ); } #[test] @@ -544,7 +544,10 @@ mod tests { let shared = cs_b.num_constraints() - before_b; println!("reading {l} bytes from {n}: naive {naive}, shared {shared}"); - assert!(shared < naive, "sharing did not reduce cost: {shared} vs {naive}"); + assert!( + shared < naive, + "sharing did not reduce cost: {shared} vs {naive}" + ); } #[test] @@ -555,7 +558,10 @@ mod tests { let idx = fp(cs.clone(), 0); let before = cs.num_constraints(); let _ = select_byte(&buf, &idx).unwrap(); - println!("select_byte over {n} bytes: {} constraints", cs.num_constraints() - before); + println!( + "select_byte over {n} bytes: {} constraints", + cs.num_constraints() - before + ); } } } diff --git a/crates/gadgets/src/commitment.rs b/crates/gadgets/src/commitment.rs index 4153daa..1b6e4fe 100644 --- a/crates/gadgets/src/commitment.rs +++ b/crates/gadgets/src/commitment.rs @@ -150,7 +150,9 @@ pub fn open( let is_native = opening .asset_kind .is_eq(&UInt8::constant(ASSET_KIND_NATIVE))?; - let is_erc20 = opening.asset_kind.is_eq(&UInt8::constant(ASSET_KIND_ERC20))?; + let is_erc20 = opening + .asset_kind + .is_eq(&UInt8::constant(ASSET_KIND_ERC20))?; (is_native.clone() | is_erc20).conditional_enforce_equal(&Boolean::TRUE, active)?; // A native row's token must be exactly zero; an ERC-20 row's must not be. @@ -243,7 +245,11 @@ mod tests { let i = native_sample(); let cs = ConstraintSystem::::new_ref(); let opening = alloc(cs.clone(), &i); - let got: Vec = opening.preimage().iter().map(|b| b.value().unwrap()).collect(); + let got: Vec = opening + .preimage() + .iter() + .map(|b| b.value().unwrap()) + .collect(); assert_eq!(got.len(), PREIMAGE_LEN); assert_eq!(got, i.preimage().to_vec(), "preimage bytes differ"); } @@ -271,7 +277,10 @@ mod tests { let i = native_sample(); let mut wrong = i.commitment(); wrong[0] ^= 0xff; - assert!(!run(&i, wrong), "accepted an opening against a wrong commitment"); + assert!( + !run(&i, wrong), + "accepted an opening against a wrong commitment" + ); } /// **Forgery: swapping the recipient while keeping the commitment.** @@ -297,7 +306,10 @@ mod tests { i.asset_kind = AssetKind::Native; // Commitment computed over the inconsistent opening, so the hash // matches; only the intent assertion can catch it. - assert!(!run(&i, i.commitment()), "accepted a native row with a token"); + assert!( + !run(&i, i.commitment()), + "accepted a native row with a token" + ); } /// **Forgery: an ERC-20 row with a zero token.** @@ -305,7 +317,10 @@ mod tests { fn rejects_erc20_without_a_token() { let mut i = native_sample(); i.settlement_token = [0u8; 20]; - assert!(!run(&i, i.commitment()), "accepted an ERC-20 row with no token"); + assert!( + !run(&i, i.commitment()), + "accepted an ERC-20 row with no token" + ); } /// **Forgery: a zero recipient.** @@ -344,7 +359,10 @@ mod tests { let mut b = native_sample(); b.escrow = [0x23; 20]; assert_ne!(a.commitment(), b.commitment()); - assert!(!run(&b, a.commitment()), "proof was portable between escrows"); + assert!( + !run(&b, a.commitment()), + "proof was portable between escrows" + ); } #[test] diff --git a/crates/gadgets/src/header.rs b/crates/gadgets/src/header.rs index d4ae5be..98abf28 100644 --- a/crates/gadgets/src/header.rs +++ b/crates/gadgets/src/header.rs @@ -75,7 +75,8 @@ pub fn parse( // The list must span the whole header: no trailing bytes. let list = Cursor::decode_item(header, &zero, active)?; - list.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; list.end().conditional_enforce_equal(header_len, active)?; // The three 32-byte hash fields this build reads. @@ -232,7 +233,11 @@ mod tests { for n in [0u64, 1, 255, 256, 21_000_000, u32::MAX as u64] { let (ok, h) = run(&header_fixture(&[0xcd; 32], n)); assert!(ok, "rejected header with number {n}"); - assert_eq!(h.unwrap().number.value().unwrap(), Fr::from(n), "number {n}"); + assert_eq!( + h.unwrap().number.value().unwrap(), + Fr::from(n), + "number {n}" + ); } } @@ -279,7 +284,10 @@ mod tests { fields.push(enc_str(&[0x11; 32])); } } - assert!(!run(&enc_list(&fields)).0, "accepted a 16-byte receiptsRoot"); + assert!( + !run(&enc_list(&fields)).0, + "accepted a 16-byte receiptsRoot" + ); } /// **Forgery: trailing bytes after the header list.** diff --git a/crates/gadgets/src/keccak/permutation.rs b/crates/gadgets/src/keccak/permutation.rs index ad6c9db..b902e02 100644 --- a/crates/gadgets/src/keccak/permutation.rs +++ b/crates/gadgets/src/keccak/permutation.rs @@ -124,8 +124,9 @@ pub fn keccak_f1600(mut st: State) -> Result, Synthes for b in 0..64 { anded.push(not_next[b].clone() & &row[(j + 2) % 5][b]); } - let anded: [Boolean; 64] = - anded.try_into().map_err(|_| SynthesisError::Unsatisfiable)?; + let anded: [Boolean; 64] = anded + .try_into() + .map_err(|_| SynthesisError::Unsatisfiable)?; st[(i * 5) + j] = xor_lane(&row[j], &anded)?; } } @@ -181,7 +182,10 @@ mod tests { } } - fn alloc_state(cs: ark_relations::gr1cs::ConstraintSystemRef, lanes: &[u64; 25]) -> State { + fn alloc_state( + cs: ark_relations::gr1cs::ConstraintSystemRef, + lanes: &[u64; 25], + ) -> State { core::array::from_fn(|i| { core::array::from_fn(|b| { Boolean::new_witness(cs.clone(), || Ok((lanes[i] >> b) & 1 == 1)).unwrap() @@ -218,7 +222,9 @@ mod tests { fn permutation_matches_native_on_patterned_state() { let cs = ConstraintSystem::::new_ref(); let lanes: [u64; 25] = core::array::from_fn(|i| { - (i as u64).wrapping_mul(0x0123_4567_89ab_cdef).rotate_left(i as u32) + (i as u64) + .wrapping_mul(0x0123_4567_89ab_cdef) + .rotate_left(i as u32) }); let out = keccak_f1600(alloc_state(cs.clone(), &lanes)).unwrap(); diff --git a/crates/gadgets/src/keccak/sponge.rs b/crates/gadgets/src/keccak/sponge.rs index aa33de1..0990f91 100644 --- a/crates/gadgets/src/keccak/sponge.rs +++ b/crates/gadgets/src/keccak/sponge.rs @@ -69,10 +69,7 @@ fn empty_state() -> State { /// `8j..8j+8` little-endian. That convention is what removes ZoKrates' /// explicit `swap_u64` calls: with a bit array, the byte order is an indexing /// choice rather than a computation. -fn absorb_block( - st: &mut State, - block: &[Byte], -) -> Result<(), SynthesisError> { +fn absorb_block(st: &mut State, block: &[Byte]) -> Result<(), SynthesisError> { debug_assert!(block.len() <= RATE); for (byte_idx, byte) in block.iter().enumerate() { let lane = byte_idx / 8; @@ -199,7 +196,11 @@ pub fn keccak256_var( let mut message = Vec::with_capacity(padded_len); for i in 0..padded_len { // In-range real byte, or zero past the buffer. - let real = if i < max { buf[i].clone() } else { zero.clone() }; + let real = if i < max { + buf[i].clone() + } else { + zero.clone() + }; // Is this the last byte of the block containing the padding start? let is_block_end = (i + 1) % RATE == 0; @@ -315,7 +316,11 @@ mod tests { "digest mismatch for {} byte input", data.len() ); - assert!(cs.is_satisfied().unwrap(), "unsatisfied for len {}", data.len()); + assert!( + cs.is_satisfied().unwrap(), + "unsatisfied for len {}", + data.len() + ); } #[test] @@ -470,7 +475,10 @@ mod tests { let before = cs.num_constraints(); let _ = keccak256_fixed(&input).unwrap(); let cost = cs.num_constraints() - before; - println!("{len} bytes ({blocks} blocks): {cost} constraints, {} per block", cost / blocks); + println!( + "{len} bytes ({blocks} blocks): {cost} constraints, {} per block", + cost / blocks + ); } } } diff --git a/crates/gadgets/src/lib.rs b/crates/gadgets/src/lib.rs index 6824d27..6b0f7e4 100644 --- a/crates/gadgets/src/lib.rs +++ b/crates/gadgets/src/lib.rs @@ -27,13 +27,13 @@ //! so a cost regression is visible in the diff. pub mod bytes; +pub mod commitment; +pub mod header; +pub mod keccak; pub mod mpt; pub mod receipt; pub mod rlp; pub mod statement; -pub mod commitment; -pub mod header; -pub mod keccak; /// Compiled bounds from spec section 12.9. /// diff --git a/crates/gadgets/src/mpt/harness.rs b/crates/gadgets/src/mpt/harness.rs index d22d032..ba90ed0 100644 --- a/crates/gadgets/src/mpt/harness.rs +++ b/crates/gadgets/src/mpt/harness.rs @@ -125,11 +125,9 @@ pub fn stage_map>(p: &NativeProof) -> Vec<(String, usize)> { let root = alloc_bounded(cs.clone(), &p.root, 32).unwrap(); let key = alloc_bounded(cs.clone(), &p.key, TEST_KEY_BYTES).unwrap(); - let key_len = - FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.key.len() as u64))).unwrap(); + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.key.len() as u64))).unwrap(); let value = alloc_bounded(cs.clone(), &p.value, value_bound()).unwrap(); - let value_len = - FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64))).unwrap(); + let value_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64))).unwrap(); marks.push(("inputs allocated".to_string(), cs.num_constraints())); let mut nodes = Vec::with_capacity(TEST_DEPTH); @@ -149,7 +147,10 @@ pub fn stage_map>(p: &NativeProof) -> Vec<(String, usize)> { let _ = V::verify_inclusion(&root, &key, &key_len, &value, &value_len, &nodes); marks.push(("verify done".to_string(), cs.num_constraints())); marks.push(( - format!("UNSATISFIED at {:?}", cs.which_is_unsatisfied().ok().flatten()), + format!( + "UNSATISFIED at {:?}", + cs.which_is_unsatisfied().ok().flatten() + ), 0, )); marks diff --git a/crates/gadgets/src/mpt/mod.rs b/crates/gadgets/src/mpt/mod.rs index 7ecc47d..7460387 100644 --- a/crates/gadgets/src/mpt/mod.rs +++ b/crates/gadgets/src/mpt/mod.rs @@ -38,11 +38,11 @@ #[cfg(test)] pub mod harness; +pub mod node; #[cfg(test)] pub mod null; pub mod path; pub mod traverse; -pub mod node; #[cfg(test)] mod tests; diff --git a/crates/gadgets/src/mpt/node.rs b/crates/gadgets/src/mpt/node.rs index f523b32..d67c3f2 100644 --- a/crates/gadgets/src/mpt/node.rs +++ b/crates/gadgets/src/mpt/node.rs @@ -68,7 +68,8 @@ pub fn decode_branch( ) -> Result, SynthesisError> { // The outer list header, decoded generally: its length varies with fill. let list = Cursor::decode_item(node, &zero_at(node)?, active)?; - list.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; // The list must span the whole node, or bytes hide outside it. list.end().conditional_enforce_equal(node_len, active)?; @@ -92,11 +93,8 @@ pub fn decode_branch( occupied.push(is_hash.clone()); // 1 byte for empty, 33 for a hash reference. - let step = FpVar::conditionally_select( - &is_hash, - &FpVar::constant(F::from(33u64)), - &FpVar::one(), - )?; + let step = + FpVar::conditionally_select(&is_hash, &FpVar::constant(F::from(33u64)), &FpVar::one())?; cursor += step; } @@ -217,7 +215,8 @@ pub fn is_branch( // The reliable discriminator is the item count, so decode two items and // check whether they close the list. let list = Cursor::decode_item(node, &zero_at(node)?, active)?; - list.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; list.end().conditional_enforce_equal(node_len, active)?; let first = Cursor::decode_item(node, &list.offset, active)?; @@ -261,18 +260,18 @@ mod tests { assert!(cs.is_satisfied().unwrap(), "rejected a valid sparse branch"); for (i, occ) in b.occupied.iter().enumerate() { - assert_eq!( - occ.value().unwrap(), - i == 3, - "slot {i} occupancy" - ); + assert_eq!(occ.value().unwrap(), i == 3, "slot {i} occupancy"); } // Read only the child the key selects, which is the whole point. let nibble = FpVar::new_witness(cs.clone(), || Ok(Fr::from(3u64))).unwrap(); let hash = branch_child_hash(&buf, &b, &nibble, &Boolean::TRUE).unwrap(); let got: Vec = hash.iter().map(|x| x.value().unwrap()).collect(); - assert_eq!(got, mirage_encoding::keccak256(&leaf).to_vec(), "slot 3 hash"); + assert_eq!( + got, + mirage_encoding::keccak256(&leaf).to_vec(), + "slot 3 hash" + ); assert!(cs.is_satisfied().unwrap()); } @@ -438,14 +437,26 @@ mod tests { fn distinguishes_branch_from_short() { let leaf = leaf_node(&[5, 7, 1], &[0xaa; 40]); let (cs1, buf1, len1) = alloc(&leaf); - assert!(!is_branch(&buf1, &len1, &Boolean::TRUE).unwrap().value().unwrap(), "leaf"); + assert!( + !is_branch(&buf1, &len1, &Boolean::TRUE) + .unwrap() + .value() + .unwrap(), + "leaf" + ); assert!(cs1.is_satisfied().unwrap()); let mut children: [Option>; 16] = Default::default(); children[3] = Some(leaf); let node = branch_node(children, None); let (cs2, buf2, len2) = alloc(&node); - assert!(is_branch(&buf2, &len2, &Boolean::TRUE).unwrap().value().unwrap(), "branch"); + assert!( + is_branch(&buf2, &len2, &Boolean::TRUE) + .unwrap() + .value() + .unwrap(), + "branch" + ); assert!(cs2.is_satisfied().unwrap()); } @@ -469,13 +480,19 @@ mod tests { println!("branch layout ({BOUND} B buffer): {layout} constraints"); println!("one selected child hash read: {read} constraints"); - println!("total per traversal level: {} constraints", layout + read); + println!( + "total per traversal level: {} constraints", + layout + read + ); // For comparison: a general 17-item RLP list decode over the same node. let (cs2, buf2, _) = alloc(&node); let z = zero_at(&buf2).unwrap(); let before3 = cs2.num_constraints(); let _ = Cursor::decode_list(&buf2, &z, 17, &Boolean::TRUE).unwrap(); - println!("general decode_list(17): {} constraints", cs2.num_constraints() - before3); + println!( + "general decode_list(17): {} constraints", + cs2.num_constraints() - before3 + ); } } diff --git a/crates/gadgets/src/mpt/path.rs b/crates/gadgets/src/mpt/path.rs index f4a1eb7..aac56ec 100644 --- a/crates/gadgets/src/mpt/path.rs +++ b/crates/gadgets/src/mpt/path.rs @@ -21,8 +21,8 @@ use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::fields::FieldVar; use ark_r1cs_std::select::CondSelectGadget; -use ark_r1cs_std::GR1CSVar; use ark_r1cs_std::uint8::UInt8; +use ark_r1cs_std::GR1CSVar; use ark_relations::gr1cs::SynthesisError; use crate::bytes::{one_hot, select_byte_with}; @@ -158,10 +158,26 @@ mod tests { #[test] fn flags_match_the_yellow_paper() { - assert_eq!(flags_of(hex_prefix(&[], false)[0]), (false, false), "even extension"); - assert_eq!(flags_of(hex_prefix(&[0xa], false)[0]), (false, true), "odd extension"); - assert_eq!(flags_of(hex_prefix(&[], true)[0]), (true, false), "even leaf"); - assert_eq!(flags_of(hex_prefix(&[0xa], true)[0]), (true, true), "odd leaf"); + assert_eq!( + flags_of(hex_prefix(&[], false)[0]), + (false, false), + "even extension" + ); + assert_eq!( + flags_of(hex_prefix(&[0xa], false)[0]), + (false, true), + "odd extension" + ); + assert_eq!( + flags_of(hex_prefix(&[], true)[0]), + (true, false), + "even leaf" + ); + assert_eq!( + flags_of(hex_prefix(&[0xa], true)[0]), + (true, true), + "odd leaf" + ); } #[test] diff --git a/crates/gadgets/src/mpt/tests.rs b/crates/gadgets/src/mpt/tests.rs index b3ded2c..4a41976 100644 --- a/crates/gadgets/src/mpt/tests.rs +++ b/crates/gadgets/src/mpt/tests.rs @@ -87,18 +87,12 @@ fn keccak(b: &[u8]) -> [u8; 32] { /// A leaf node: hex-prefixed remaining path, then the value. pub fn leaf_node(path_nibbles: &[u8], value: &[u8]) -> Vec { - enc_list(&[ - enc_str(&hex_prefix(path_nibbles, true)), - enc_str(value), - ]) + enc_list(&[enc_str(&hex_prefix(path_nibbles, true)), enc_str(value)]) } /// An extension node: hex-prefixed shared path, then a child reference. pub fn extension_node(path_nibbles: &[u8], child: &[u8]) -> Vec { - enc_list(&[ - enc_str(&hex_prefix(path_nibbles, false)), - child_ref(child), - ]) + enc_list(&[enc_str(&hex_prefix(path_nibbles, false)), child_ref(child)]) } /// A branch node: 16 child slots plus a value slot. @@ -131,14 +125,22 @@ pub fn child_ref(node: &[u8]) -> Vec { /// Returns (root hash, key, value, nodes root-first). pub fn simple_trie(n: u8, key: &[u8], value: &[u8]) -> ([u8; 32], Vec, Vec, Vec>) { let nibbles = to_nibbles(key); - assert_eq!(nibbles[0], n, "key's first nibble must select the branch slot"); + assert_eq!( + nibbles[0], n, + "key's first nibble must select the branch slot" + ); let leaf = leaf_node(&nibbles[1..], value); let mut children: [Option>; 16] = Default::default(); children[n as usize] = Some(leaf.clone()); let root = branch_node(children, None); - (keccak(&root), key.to_vec(), value.to_vec(), vec![root, leaf]) + ( + keccak(&root), + key.to_vec(), + value.to_vec(), + vec![root, leaf], + ) } // ---------------------------------------------------------------- harness @@ -150,7 +152,12 @@ fn genuine() -> NativeProof { let key = vec![0x35, 0x71]; let value = b"a-receipt-standing-in-for-the-real-thing".to_vec(); let (root, key, value, nodes) = simple_trie(0x3, &key, &value); - NativeProof { root, key, value, nodes } + NativeProof { + root, + key, + value, + nodes, + } } // ------------------------------------------------------- positive cases @@ -174,7 +181,11 @@ pub fn fixtures_are_well_formed() { assert_eq!(hex_prefix(&[0xa], false), vec![0x1a], "odd extension"); assert_eq!(hex_prefix(&[], true), vec![0x20], "even leaf"); assert_eq!(hex_prefix(&[0xa], true), vec![0x3a], "odd leaf"); - assert_eq!(hex_prefix(&[0x1, 0x2], true), vec![0x20, 0x12], "even leaf, two nibbles"); + assert_eq!( + hex_prefix(&[0x1, 0x2], true), + vec![0x20, 0x12], + "even leaf, two nibbles" + ); assert_eq!(to_nibbles(&[0x35, 0x71]), vec![3, 5, 7, 1]); @@ -225,7 +236,10 @@ pub fn rejects_unlinked_node>() { // still references the original leaf's hash, so the link is broken. let nibbles = to_nibbles(&p.key); p.nodes[1] = leaf_node(&nibbles[1..], b"a-value-the-prover-would-prefer"); - assert!(!verify::(&p), "accepted a node not matching its parent reference"); + assert!( + !verify::(&p), + "accepted a node not matching its parent reference" + ); } /// **Forgery: root hash not checked against the claimed root.** @@ -258,7 +272,10 @@ pub fn rejects_wrong_nibble_child>() { value, nodes: vec![root, leaf], }; - assert!(!verify::(&p), "accepted a child from the wrong nibble slot"); + assert!( + !verify::(&p), + "accepted a child from the wrong nibble slot" + ); } /// **Forgery: leaf path does not match the key remainder.** @@ -281,7 +298,10 @@ pub fn rejects_leaf_path_mismatch>() { value, nodes: vec![root, leaf], }; - assert!(!verify::(&p), "accepted a leaf whose path differs from the key"); + assert!( + !verify::(&p), + "accepted a leaf whose path differs from the key" + ); } /// **Forgery: extension path not compared.** @@ -306,7 +326,10 @@ pub fn rejects_extension_path_mismatch>() { value, nodes: vec![root, ext, leaf], }; - assert!(!verify::(&p), "accepted an extension whose path differs from the key"); + assert!( + !verify::(&p), + "accepted an extension whose path differs from the key" + ); } /// **Forgery: hex-prefix flags ignored.** @@ -337,7 +360,10 @@ pub fn rejects_hex_prefix_flag_confusion>() { value, nodes: vec![root, leaf], }; - assert!(!verify::(&p), "accepted a node with a corrupted hex-prefix flag"); + assert!( + !verify::(&p), + "accepted a node with a corrupted hex-prefix flag" + ); } /// **Forgery: an inactive depth slot treated as active.** @@ -386,7 +412,10 @@ pub fn rejects_partial_key_consumption>() { value, nodes: vec![root, leaf], }; - assert!(!verify::(&p), "accepted a leaf that leaves key nibbles unconsumed"); + assert!( + !verify::(&p), + "accepted a leaf that leaves key nibbles unconsumed" + ); } /// **Forgery: the value is present at a non-terminating level.** @@ -445,8 +474,6 @@ pub fn run_suite>() { run_forgeries::(); } - - #[test] fn fixture_sanity() { fixtures_are_well_formed(); @@ -464,16 +491,28 @@ fn forgeries_defeat_the_null_verifier() { let cases: Vec<(&str, fn())> = vec![ ("unlinked_node", || rejects_unlinked_node::()), ("wrong_root", || rejects_wrong_root::()), - ("wrong_nibble_child", || rejects_wrong_nibble_child::()), - ("leaf_path_mismatch", || rejects_leaf_path_mismatch::()), - ("extension_path_mismatch", || rejects_extension_path_mismatch::()), - ("hex_prefix_flag_confusion", || rejects_hex_prefix_flag_confusion::()), - ("active_slot_past_depth", || rejects_active_slot_past_depth::()), + ("wrong_nibble_child", || { + rejects_wrong_nibble_child::() + }), + ("leaf_path_mismatch", || { + rejects_leaf_path_mismatch::() + }), + ("extension_path_mismatch", || { + rejects_extension_path_mismatch::() + }), + ("hex_prefix_flag_confusion", || { + rejects_hex_prefix_flag_confusion::() + }), + ("active_slot_past_depth", || { + rejects_active_slot_past_depth::() + }), ("value_mismatch", || rejects_value_mismatch::()), ("value_at_non_terminating_level", || { rejects_value_at_a_non_terminating_level::() }), - ("partial_key_consumption", || rejects_partial_key_consumption::()), + ("partial_key_consumption", || { + rejects_partial_key_consumption::() + }), ]; for (name, case) in cases { @@ -488,5 +527,8 @@ fn forgeries_defeat_the_null_verifier() { /// Reports the cost of one verification, once an implementation exists. pub fn report_cost>(label: &str) { - println!("{label}: inclusion proof: {} constraints", cost::(&genuine())); + println!( + "{label}: inclusion proof: {} constraints", + cost::(&genuine()) + ); } diff --git a/crates/gadgets/src/mpt/traverse.rs b/crates/gadgets/src/mpt/traverse.rs index 1f3977c..95fecba 100644 --- a/crates/gadgets/src/mpt/traverse.rs +++ b/crates/gadgets/src/mpt/traverse.rs @@ -172,8 +172,7 @@ impl MptVerifier for Traversal { // ---- branch case: follow the nibble's child (invariant 3) ---- profile(&level.bytes, "decoders", &mut mark); let nibble = nibble_at(key, &consumed)?; - let child_offset = - branch_child_offset(&branch, &nibble, &branch_active)?; + let child_offset = branch_child_offset(&branch, &nibble, &branch_active)?; // ---- short case: read flags and match the path (invariant 4) ---- profile(&level.bytes, "child-hash", &mut mark); @@ -207,7 +206,6 @@ impl MptVerifier for Traversal { &short_active, )?; - // An extension's tail is the child reference the walk follows next. // // Only 32 bytes are read, but at ~10 constraints per buffer byte @@ -223,11 +221,8 @@ impl MptVerifier for Traversal { // over a 544-byte node is ~160k constraints, and doing it twice was // 18% of a level. profile(&level.bytes, "path-match", &mut mark); - let next_offset = FpVar::conditionally_select( - &this_is_branch, - &child_offset, - &short.tail_offset, - )?; + let next_offset = + FpVar::conditionally_select(&this_is_branch, &child_offset, &short.tail_offset)?; let next_ref = select_bytes(&level.bytes, &next_offset, 32)?; // ---- terminate or descend ---- @@ -250,18 +245,13 @@ impl MptVerifier for Traversal { // every level costs ~2M each. let is_term = active.clone() & terminates.clone(); term_node = select_bytes_cond(&level.bytes, &term_node, &is_term)?; - term_offset = - FpVar::conditionally_select(&is_term, &short.tail_offset, &term_offset)?; + term_offset = FpVar::conditionally_select(&is_term, &short.tail_offset, &term_offset)?; term_len = FpVar::conditionally_select(&is_term, &short.tail_len, &term_len)?; profile(&level.bytes, "consume+value", &mut mark); // Advance. A branch consumes one nibble, an extension consumes its // path, a leaf ends the walk. - let step = FpVar::conditionally_select( - &this_is_branch, - &FpVar::one(), - &path_nibbles, - )?; + let step = FpVar::conditionally_select(&this_is_branch, &FpVar::one(), &path_nibbles)?; consumed = FpVar::conditionally_select( &(active.clone() & !terminates.clone()), &(&consumed + &step), @@ -269,7 +259,11 @@ impl MptVerifier for Traversal { )?; // The next expected hash. - expected = cond_select_bytes(&next_ref, &expected, &(active.clone() & !terminates.clone()))?; + expected = cond_select_bytes( + &next_ref, + &expected, + &(active.clone() & !terminates.clone()), + )?; profile(&level.bytes, "advance", &mut mark); // Invariant 7: nothing may follow a termination. diff --git a/crates/gadgets/src/receipt/envelope.rs b/crates/gadgets/src/receipt/envelope.rs index e1ecc76..b6bcc2b 100644 --- a/crates/gadgets/src/receipt/envelope.rs +++ b/crates/gadgets/src/receipt/envelope.rs @@ -75,7 +75,8 @@ pub fn parse( let is_list_header = bits[7].clone() & bits[6].clone(); // Exactly one of the two, positively. Anything else fails closed. - (is_typed.clone() | is_list_header.clone()).conditional_enforce_equal(&Boolean::TRUE, active)?; + (is_typed.clone() | is_list_header.clone()) + .conditional_enforce_equal(&Boolean::TRUE, active)?; (is_typed.clone() & is_list_header).conditional_enforce_equal(&Boolean::FALSE, active)?; // The payload begins after the prefix, if there is one. @@ -85,7 +86,8 @@ pub fn parse( // the tiling; a fifth item or a gap is rejected there. let items = Cursor::decode_list(receipt, &payload_at, 4, active)?; let list = Cursor::decode_item(receipt, &payload_at, active)?; - list.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; // The receipt must end where the payload ends: no trailing bytes. list.end().conditional_enforce_equal(receipt_len, active)?; @@ -114,10 +116,7 @@ pub fn parse( // cumulativeGasUsed below 2^64: at most 8 payload bytes. The RLP decoder // already rejects non-canonical encodings, so a short field cannot have // leading zeros. - let gas_ok = crate::bytes::le( - &cumulative_gas.payload_len, - &FpVar::constant(F::from(8u64)), - )?; + let gas_ok = crate::bytes::le(&cumulative_gas.payload_len, &FpVar::constant(F::from(8u64)))?; gas_ok.conditional_enforce_equal(&Boolean::TRUE, active)?; Ok(Payload { diff --git a/crates/gadgets/src/receipt/log.rs b/crates/gadgets/src/receipt/log.rs index 86b8589..bfe5639 100644 --- a/crates/gadgets/src/receipt/log.rs +++ b/crates/gadgets/src/receipt/log.rs @@ -36,8 +36,8 @@ use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; use super::Intent; -use crate::bytes::{lt, one_hot, select_bytes, zero_like}; use crate::bounds::MAX_LOGS; +use crate::bytes::{lt, one_hot, select_bytes, zero_like}; use crate::rlp::{cursor::Cursor, Item, RlpDecoder}; /// keccak256("Transfer(address,address,uint256)") @@ -192,7 +192,8 @@ pub fn sole_log( active: &Boolean, ) -> Result, SynthesisError> { let log = Cursor::decode_item(receipt, &logs.offset, active)?; - log.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + log.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; // Exactly one: the log must fill the list. Without this a prover appends a // second event whose contents the relation never inspects, which is the diff --git a/crates/gadgets/src/receipt/tests.rs b/crates/gadgets/src/receipt/tests.rs index 7b7c1dd..ba5003c 100644 --- a/crates/gadgets/src/receipt/tests.rs +++ b/crates/gadgets/src/receipt/tests.rs @@ -78,14 +78,15 @@ pub fn log_item(emitter: &[u8; 20], topics: &[Vec], data: &[u8]) -> Vec } /// A canonical ERC-20 Transfer log. -pub fn transfer_log(token: &[u8; 20], from: &[u8; 20], to: &[u8; 20], amount: &[u8; 32]) -> Vec { +pub fn transfer_log( + token: &[u8; 20], + from: &[u8; 20], + to: &[u8; 20], + amount: &[u8; 32], +) -> Vec { log_item( token, - &[ - transfer_topic0().to_vec(), - addr_topic(from), - addr_topic(to), - ], + &[transfer_topic0().to_vec(), addr_topic(from), addr_topic(to)], amount, ) } @@ -136,7 +137,12 @@ fn cs() -> ConstraintSystemRef { ConstraintSystem::::new_ref() } -fn intent(token: &[u8; 20], recipient: &[u8; 20], amt: &[u8; 32], c: ConstraintSystemRef) -> Intent { +fn intent( + token: &[u8; 20], + recipient: &[u8; 20], + amt: &[u8; 32], + c: ConstraintSystemRef, +) -> Intent { Intent { token: alloc_bounded(c.clone(), token, 20).unwrap(), recipient: alloc_bounded(c.clone(), recipient, 20).unwrap(), @@ -250,7 +256,10 @@ pub fn fixtures_are_well_formed() { let (r, _, _) = genuine(); assert_eq!(r[0], 0x02, "typed prefix"); - assert!(r.len() < TEST_RECEIPT_BYTES, "fixture exceeds the test bound"); + assert!( + r.len() < TEST_RECEIPT_BYTES, + "fixture exceeds the test bound" + ); // logsBloom is 256 bytes, so its RLP header is 0xb9 0x01 0x00. let legacy = receipt(1, &[], None); @@ -645,11 +654,19 @@ fn single_log_cost() { let before = c.num_constraints(); if single { let _ = >::verify( - &buf, &len, &idx, &it, &Boolean::TRUE, + &buf, + &len, + &idx, + &it, + &Boolean::TRUE, ); } else { let _ = >::verify( - &buf, &len, &idx, &it, &Boolean::TRUE, + &buf, + &len, + &idx, + &it, + &Boolean::TRUE, ); } costs.push(c.num_constraints() - before); @@ -678,9 +695,8 @@ fn cost() { let i = FpVar::new_witness(c.clone(), || Ok(Fr::from(idx as u64))).unwrap(); let it = intent(&TOKEN, &RECIPIENT, &amt, c.clone()); let before = c.num_constraints(); - let _ = >::verify( - &buf, &len, &i, &it, &Boolean::TRUE, - ); + let _ = + >::verify(&buf, &len, &i, &it, &Boolean::TRUE); println!( "receipt relation, {bound} byte bound: {} constraints", c.num_constraints() - before @@ -715,7 +731,10 @@ fn log_walk_cost() { let check = c.num_constraints() - before_check; println!("envelope parse: {env}"); - println!("log walk: {walk} <- {} MAX_LOGS steps", crate::bounds::MAX_LOGS); + println!( + "log walk: {walk} <- {} MAX_LOGS steps", + crate::bounds::MAX_LOGS + ); println!("transfer checks: {check}"); println!("total: {}", env + walk + check); } @@ -767,7 +786,9 @@ fn forgeries_defeat_the_null_relation() { ("unsupported_envelope", || { rejects_unsupported_envelope::() }), - ("wrong_bloom_length", || rejects_wrong_bloom_length::()), + ("wrong_bloom_length", || { + rejects_wrong_bloom_length::() + }), ("wrong_payload_field_count", || { rejects_wrong_payload_field_count::() }), diff --git a/crates/gadgets/src/rlp/cursor.rs b/crates/gadgets/src/rlp/cursor.rs index 70a5bda..000ff72 100644 --- a/crates/gadgets/src/rlp/cursor.rs +++ b/crates/gadgets/src/rlp/cursor.rs @@ -231,9 +231,8 @@ impl RlpDecoder for Cursor { // Canonical: a short string of exactly one byte below 0x80 must have // been written bare. Reject 0x81 followed by such a byte. - let is_one_byte_str = p.is_short_form.clone() - & !p.is_list.clone() - & p.short_len.is_eq(&FpVar::one())?; + let is_one_byte_str = + p.is_short_form.clone() & !p.is_list.clone() & p.short_len.is_eq(&FpVar::one())?; let content_sel = one_hot(&offset, buf.len())?; let content = select_byte_with(buf, &content_sel)?; let content_lt_80 = less_than_const(&byte_to_field(&content)?, 0x80)?; @@ -259,7 +258,8 @@ impl RlpDecoder for Cursor { active: &Boolean, ) -> Result>, SynthesisError> { let list = Self::decode_item(buf, at, active)?; - list.is_list.conditional_enforce_equal(&Boolean::TRUE, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; let list_end = list.end(); let mut cursor = list.offset.clone(); @@ -303,10 +303,10 @@ mod tests { /// decode is required either way to verify the hint. #[test] fn cost_breakdown() { + use crate::bytes::alloc_bounded; use ark_bn254::Fr; use ark_r1cs_std::alloc::AllocVar; use ark_relations::gr1cs::ConstraintSystem; - use crate::bytes::alloc_bounded; let bound = 1024; let data = vec![0x85, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa]; @@ -318,7 +318,10 @@ mod tests { let before = c.num_constraints(); let sel = crate::bytes::one_hot(&at, bound).unwrap(); let _ = crate::bytes::select_byte_with(&buf, &sel).unwrap(); - println!(" one byte read (one_hot + select): {}", c.num_constraints() - before); + println!( + " one byte read (one_hot + select): {}", + c.num_constraints() - before + ); // full decode_item let c2 = ConstraintSystem::::new_ref(); @@ -326,6 +329,9 @@ mod tests { let at2 = FpVar::new_witness(c2.clone(), || Ok(Fr::from(0u64))).unwrap(); let before2 = c2.num_constraints(); let _ = >::decode_item(&buf2, &at2, &Boolean::TRUE).unwrap(); - println!(" full decode_item: {}", c2.num_constraints() - before2); + println!( + " full decode_item: {}", + c2.num_constraints() - before2 + ); } } diff --git a/crates/gadgets/src/rlp/tests.rs b/crates/gadgets/src/rlp/tests.rs index dc635f8..336d3ed 100644 --- a/crates/gadgets/src/rlp/tests.rs +++ b/crates/gadgets/src/rlp/tests.rs @@ -68,10 +68,10 @@ fn trim_leading_zeros(b: &[u8]) -> Vec { /// A receipt-shaped fixture: `[status, cumulativeGasUsed, logsBloom, logs]`. fn receipt_fixture() -> Vec { enc_list(&[ - enc_str(&[1]), // status - enc_str(&[0x52, 0x08]), // cumulativeGasUsed - enc_str(&[0u8; 256]), // logsBloom - enc_list(&[]), // logs, empty + enc_str(&[1]), // status + enc_str(&[0x52, 0x08]), // cumulativeGasUsed + enc_str(&[0u8; 256]), // logsBloom + enc_list(&[]), // logs, empty ]) } @@ -81,7 +81,10 @@ fn receipt_fixture() -> Vec { /// rejection, since neither produces a proof. fn accepts(buf_bytes: &[u8], bound: usize, body: Body) -> bool where - Body: Fn(&[ark_r1cs_std::uint8::UInt8], ConstraintSystemRef) -> Result<(), SynthesisError>, + Body: Fn( + &[ark_r1cs_std::uint8::UInt8], + ConstraintSystemRef, + ) -> Result<(), SynthesisError>, { let c = cs(); let buf = alloc_bounded(c.clone(), buf_bytes, bound).unwrap(); @@ -102,7 +105,12 @@ pub fn accepts_canonical_forms>() { ("short string", enc_str(&[0xaa; 5]), 1, 5), ("long string", enc_str(&[0xbb; 100]), 2, 100), ("empty list", enc_list(&[]), 1, 0), - ("short list", enc_list(&[enc_str(&[1]), enc_str(&[2])]), 1, 2), + ( + "short list", + enc_list(&[enc_str(&[1]), enc_str(&[2])]), + 1, + 2, + ), ]; for (name, bytes, want_off, want_len) in cases { diff --git a/crates/gadgets/src/statement.rs b/crates/gadgets/src/statement.rs index ab4e2f5..31f8505 100644 --- a/crates/gadgets/src/statement.rs +++ b/crates/gadgets/src/statement.rs @@ -130,10 +130,7 @@ pub fn compute(ctx: &Context) -> Result, SynthesisE // The digest as 32 bytes, then split into two 16-byte limbs. 16 bytes is // always below the BN254 modulus, so each packing is injective; 32 would // alias. - let digest: Vec> = digest_bits - .iter() - .map(|b| UInt8::from_bits_le(b)) - .collect(); + let digest: Vec> = digest_bits.iter().map(|b| UInt8::from_bits_le(b)).collect(); Ok(Signals { hi: pack_bytes_16(&digest[..16])?, @@ -245,20 +242,62 @@ mod tests { }; let mutations: Vec = vec![ - Statement { instance_domain: [0x12; 32], ..native_sample() }, - Statement { chain_id: 2, ..native_sample() }, - Statement { escrow: [0x23; 20], ..native_sample() }, - Statement { request_id: [0x34; 32], ..native_sample() }, - Statement { row_index: 8, ..native_sample() }, - Statement { intent_commitment: [0x45; 32], ..native_sample() }, - Statement { bond_attempt: 4, ..native_sample() }, - Statement { bond_start_block: 1001, ..native_sample() }, - Statement { bond_deadline: 1181, ..native_sample() }, - Statement { bonded_collector: [0x56; 20], ..native_sample() }, - Statement { row_payout_asset: [0x01; 20], ..native_sample() }, - Statement { row_payout_amount: [0x01; 32], ..native_sample() }, - Statement { witness_block_number: 1101, ..native_sample() }, - Statement { witness_block_hash: [0x67; 32], ..native_sample() }, + Statement { + instance_domain: [0x12; 32], + ..native_sample() + }, + Statement { + chain_id: 2, + ..native_sample() + }, + Statement { + escrow: [0x23; 20], + ..native_sample() + }, + Statement { + request_id: [0x34; 32], + ..native_sample() + }, + Statement { + row_index: 8, + ..native_sample() + }, + Statement { + intent_commitment: [0x45; 32], + ..native_sample() + }, + Statement { + bond_attempt: 4, + ..native_sample() + }, + Statement { + bond_start_block: 1001, + ..native_sample() + }, + Statement { + bond_deadline: 1181, + ..native_sample() + }, + Statement { + bonded_collector: [0x56; 20], + ..native_sample() + }, + Statement { + row_payout_asset: [0x01; 20], + ..native_sample() + }, + Statement { + row_payout_amount: [0x01; 32], + ..native_sample() + }, + Statement { + witness_block_number: 1101, + ..native_sample() + }, + Statement { + witness_block_hash: [0x67; 32], + ..native_sample() + }, ]; assert_eq!(mutations.len(), 14, "one case per context field"); diff --git a/crates/prover/src/bin/export_verifier.rs b/crates/prover/src/bin/export_verifier.rs index 5838faf..7847f11 100644 --- a/crates/prover/src/bin/export_verifier.rs +++ b/crates/prover/src/bin/export_verifier.rs @@ -85,7 +85,6 @@ fn render(vk: &VerifyingKey) -> String { .expect("render template") } - fn proof_json(proof: &[[u8; 32]; 8], hi: u128, lo: u128, w: &mirage_relation::Witness) -> String { let p = proof.map(|w| format!("0x{}", hex::encode(w))); let s = &w.statement; @@ -117,7 +116,16 @@ fn proof_json(proof: &[[u8; 32]; 8], hi: u128, lo: u128, w: &mirage_relation::Wi "note": "proof is [a.x, a.y, b.x1, b.x0, b.y1, b.y0, c.x, c.y]; the EVM pairing precompile takes G2 coordinates in that order, which is the reverse of arkworks' serialization. The statement block is what the escrow must reproduce from its own state for this proof to verify against it." }} "#, - p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], hi, lo, + p[0], + p[1], + p[2], + p[3], + p[4], + p[5], + p[6], + p[7], + hi, + lo, hx(&s.instance_domain), s.chain_id, hx(&s.escrow), diff --git a/crates/prover/src/bin/measure.rs b/crates/prover/src/bin/measure.rs index 3223421..ae4bad9 100644 --- a/crates/prover/src/bin/measure.rs +++ b/crates/prover/src/bin/measure.rs @@ -61,7 +61,10 @@ fn main() { .expect("synthesis"); let satisfied = cs.is_satisfied().expect("satisfiability"); let n = cs.num_constraints(); - println!("synthesis: {:>8.1}s {n} constraints, satisfied={satisfied}", t.elapsed().as_secs_f64()); + println!( + "synthesis: {:>8.1}s {n} constraints, satisfied={satisfied}", + t.elapsed().as_secs_f64() + ); assert!(satisfied, "witness does not satisfy the circuit"); drop(cs); @@ -73,8 +76,9 @@ fn main() { // artifact through a sound process. let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(0); let t = Instant::now(); - let (pk, vk) = Groth16::::circuit_specific_setup(ReceiptCircuit::setup(bounds), &mut rng) - .expect("setup"); + let (pk, vk) = + Groth16::::circuit_specific_setup(ReceiptCircuit::setup(bounds), &mut rng) + .expect("setup"); let setup_secs = t.elapsed().as_secs_f64(); let pk_bytes = pk.serialized_size(ark_serialize::Compress::No); let pk_compressed = pk.serialized_size(ark_serialize::Compress::Yes); @@ -86,8 +90,12 @@ fn main() { // ---- prove ---- let t = Instant::now(); - let proof = Groth16::::prove(&pk, ReceiptCircuit::prove(bounds, fixture::genuine()), &mut rng) - .expect("prove"); + let proof = Groth16::::prove( + &pk, + ReceiptCircuit::prove(bounds, fixture::genuine()), + &mut rng, + ) + .expect("prove"); let prove_secs = t.elapsed().as_secs_f64(); println!("prove: {prove_secs:>8.1}s"); diff --git a/crates/prover/src/lib.rs b/crates/prover/src/lib.rs index 756275c..2716779 100644 --- a/crates/prover/src/lib.rs +++ b/crates/prover/src/lib.rs @@ -27,6 +27,16 @@ pub struct Keys { pub vk: VerifyingKey, } +/// The proving half of a [`Keys`], as [`save_proving_key`] writes it. +/// +/// Aliased so a caller can name what [`Keys`] holds without depending on the +/// arkworks crates directly, which would mean version-locking them against +/// this crate's own. +pub type SettlementProvingKey = ProvingKey; + +/// The verifying half of a [`Keys`], which the escrow embeds. +pub type SettlementVerifyingKey = VerifyingKey; + /// Runs the circuit-specific setup for `bounds`. /// /// Spec 18.2 requires a multiparty Phase 2 for production; this is the toy @@ -35,8 +45,9 @@ pub struct Keys { /// rather than drawn from entropy so a rebuild reproduces the same key. pub fn setup(bounds: Bounds, seed: u64) -> Result { let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(seed); - let (pk, vk) = Groth16::::circuit_specific_setup(ReceiptCircuit::setup(bounds), &mut rng) - .map_err(|e| SettlementError::Setup(e.to_string()))?; + let (pk, vk) = + Groth16::::circuit_specific_setup(ReceiptCircuit::setup(bounds), &mut rng) + .map_err(|e| SettlementError::Setup(e.to_string()))?; Ok(Keys { pk, vk }) } @@ -63,8 +74,9 @@ pub fn prove( .map_err(|e| SettlementError::Prove(e.to_string()))?; let pvk = PreparedVerifyingKey::from(keys.vk.clone()); - let ok = Groth16::::verify_with_processed_vk(&pvk, &[Fr::from(hi), Fr::from(lo)], &proof) - .map_err(|e| SettlementError::Verify(e.to_string()))?; + let ok = + Groth16::::verify_with_processed_vk(&pvk, &[Fr::from(hi), Fr::from(lo)], &proof) + .map_err(|e| SettlementError::Verify(e.to_string()))?; if !ok { return Err(SettlementError::SelfCheck); } @@ -134,6 +146,9 @@ pub enum SettlementError { /// A proving key could not be read: wrong encoding, truncated, or not a /// key for this curve. KeyLoad(String), + /// A key could not be serialized. Only reachable through a writer error, + /// since the in-memory key is already well formed. + KeySave(String), Setup(String), Prove(String), Verify(String), @@ -148,6 +163,7 @@ impl std::fmt::Display for SettlementError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::KeyLoad(e) => write!(f, "proving key could not be loaded: {e}"), + Self::KeySave(e) => write!(f, "key could not be serialized: {e}"), Self::Setup(e) => write!(f, "groth16 setup failed: {e}"), Self::Prove(e) => write!(f, "proving failed: {e}"), Self::Verify(e) => write!(f, "verification errored: {e}"), @@ -218,6 +234,32 @@ pub fn load_proving_key( .map_err(|e| SettlementError::KeyLoad(e.to_string())) } +/// Serializes a proving key, as [`load_proving_key`] reads it. +/// +/// The inverse lives next to its counterpart so the two encodings cannot drift: +/// the format is not self-describing, and a mismatch surfaces as a curve point +/// check failure rather than a clean error. `compressed` must match what the +/// reader will pass. +/// +/// A caller that holds a key only because it generated one with [`setup`] is +/// holding the unsound kind; writing it somewhere durable does not make it a +/// ceremony key. +pub fn save_proving_key( + pk: &ProvingKey, + compressed: bool, +) -> Result, SettlementError> { + use ark_serialize::{CanonicalSerialize, Compress}; + let mode = if compressed { + Compress::Yes + } else { + Compress::No + }; + let mut bytes = Vec::with_capacity(pk.serialized_size(mode)); + pk.serialize_with_mode(&mut bytes, mode) + .map_err(|e| SettlementError::KeySave(e.to_string()))?; + Ok(bytes) +} + /// The verifying key implied by a proving key. /// /// A node holds only the proving half, but the escrow embeds the verifying @@ -228,6 +270,21 @@ pub fn verifying_key_of(pk: &ProvingKey) -> VerifyingKey { pk.vk.clone() } +/// Serializes a verifying key to its canonical uncompressed bytes. +/// +/// Exposed so a caller can identify a setup without reproducing it: hashing +/// these bytes yields a stable fingerprint that two keys share if and only if +/// they came from the same setup. That is what lets a node accept a proving key +/// from an untrusted source, by checking the verifying half it implies against +/// a fingerprint the node already trusts. +pub fn serialize_verifying_key(vk: &VerifyingKey) -> Result, SettlementError> { + use ark_serialize::{CanonicalSerialize, Compress}; + let mut bytes = Vec::with_capacity(vk.serialized_size(Compress::No)); + vk.serialize_with_mode(&mut bytes, Compress::No) + .map_err(|e| SettlementError::KeySave(e.to_string()))?; + Ok(bytes) +} + /// The verifying key's on-chain form: the constants the generated Solidity /// verifier compiles in. /// diff --git a/crates/prover/tests/settlement.rs b/crates/prover/tests/settlement.rs index d07d181..e3bce52 100644 --- a/crates/prover/tests/settlement.rs +++ b/crates/prover/tests/settlement.rs @@ -22,7 +22,11 @@ fn proves_and_self_checks_a_genuine_settlement() { // The signals must be the ones the native encoder derives, since that is // what the escrow recomputes from its own storage. let (hi, lo) = mirage_relation::public_signals(&fixture::genuine()); - assert_eq!(settlement.signals, [hi, lo], "signals disagree with the encoder"); + assert_eq!( + settlement.signals, + [hi, lo], + "signals disagree with the encoder" + ); // Every coordinate is a field element, so none may be all-zero: a zero // point would mean the conversion dropped a coordinate. @@ -155,3 +159,46 @@ fn derived_constants_match_the_exported_verifier() { ); } } + +#[test] +fn a_saved_proving_key_reloads_to_the_same_setup() { + let keys = keys(); + + // Uncompressed is what a caller caching locally uses: compression trades + // decompression work on every load for bytes that never leave the host. + let bytes = mirage_prover::save_proving_key(&keys.pk, false).expect("save"); + let reloaded = mirage_prover::load_proving_key(&bytes, false).expect("load"); + + // The verifying half is what the escrow agrees with, so matching it is + // what makes a reloaded key usable rather than merely well formed. + assert_eq!( + mirage_prover::serialize_verifying_key(&mirage_prover::verifying_key_of(&reloaded)) + .expect("serialize reloaded vk"), + mirage_prover::serialize_verifying_key(&keys.vk).expect("serialize vk"), + "a reloaded key implies a different verifying key" + ); + + // A proof from the reloaded key must still self-check, which the compressed + // round trip would also have to satisfy. + prove_seeded( + &Keys { + pk: reloaded, + vk: keys.vk.clone(), + }, + Bounds::default(), + &fixture::genuine(), + 0, + ) + .expect("prove with the reloaded key"); +} + +#[test] +fn reading_a_saved_key_with_the_wrong_encoding_fails() { + let bytes = mirage_prover::save_proving_key(&keys().pk, false).expect("save"); + // The encodings are not self-describing, so this is the failure a caller + // gets for disagreeing about `compressed` -- not a clean length error. + assert!( + mirage_prover::load_proving_key(&bytes, true).is_err(), + "an uncompressed key read as compressed should not load" + ); +} diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 7245949..1e54a37 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -534,11 +534,7 @@ pub mod fixture { let log = enc_list(&[ enc_str(&TOKEN), - enc_list(&[ - enc_str(&topic0), - enc_str(&from_topic), - enc_str(&to_topic), - ]), + enc_list(&[enc_str(&topic0), enc_str(&from_topic), enc_str(&to_topic)]), enc_str(&amount), ]); @@ -554,10 +550,7 @@ pub mod fixture { // Trie: root branch, leaf under the key's first nibble. let key = vec![0x35, 0x71]; let nibbles = to_nibbles(&key); - let leaf = enc_list(&[ - enc_str(&hex_prefix(&nibbles[1..], true)), - enc_str(&receipt), - ]); + let leaf = enc_list(&[enc_str(&hex_prefix(&nibbles[1..], true)), enc_str(&receipt)]); let mut children: Vec> = (0..16).map(|_| enc_str(&[])).collect(); children[nibbles[0] as usize] = enc_str(&keccak(&leaf)); @@ -652,27 +645,27 @@ pub mod fixture { /// A 21-field post-Prague header carrying the given receipts root. fn header_with_receipts_root(receipts_root: &[u8; 32], number: u64) -> Vec { enc_list(&[ - enc_str(&[0x01; 32]), // parentHash - enc_str(&[0x02; 32]), // ommersHash - enc_str(&[0x03; 20]), // beneficiary - enc_str(&[0x04; 32]), // stateRoot - enc_str(&[0x05; 32]), // transactionsRoot - enc_str(receipts_root), // receiptsRoot - enc_str(&[0u8; 256]), // logsBloom - enc_str(&[]), // difficulty + enc_str(&[0x01; 32]), // parentHash + enc_str(&[0x02; 32]), // ommersHash + enc_str(&[0x03; 20]), // beneficiary + enc_str(&[0x04; 32]), // stateRoot + enc_str(&[0x05; 32]), // transactionsRoot + enc_str(receipts_root), // receiptsRoot + enc_str(&[0u8; 256]), // logsBloom + enc_str(&[]), // difficulty enc_str(&trim(&number.to_be_bytes())), // number enc_str(&[0x01, 0xc9, 0xc3, 0x80]), // gasLimit - enc_str(&[0x52, 0x08]), // gasUsed + enc_str(&[0x52, 0x08]), // gasUsed enc_str(&[0x66, 0x00, 0x00, 0x00]), // timestamp - enc_str(&[]), // extraData - enc_str(&[0x06; 32]), // prevRandao - enc_str(&[0u8; 8]), // nonce - enc_str(&[0x07]), // baseFeePerGas - enc_str(&[0x08; 32]), // withdrawalsRoot - enc_str(&[]), // blobGasUsed - enc_str(&[]), // excessBlobGas - enc_str(&[0x09; 32]), // parentBeaconBlockRoot - enc_str(&[0x0a; 32]), // requestsHash + enc_str(&[]), // extraData + enc_str(&[0x06; 32]), // prevRandao + enc_str(&[0u8; 8]), // nonce + enc_str(&[0x07]), // baseFeePerGas + enc_str(&[0x08; 32]), // withdrawalsRoot + enc_str(&[]), // blobGasUsed + enc_str(&[]), // excessBlobGas + enc_str(&[0x09; 32]), // parentBeaconBlockRoot + enc_str(&[0x0a; 32]), // requestsHash ]) } } diff --git a/crates/relation/tests/mainnet.rs b/crates/relation/tests/mainnet.rs index 2015bc4..8990c74 100644 --- a/crates/relation/tests/mainnet.rs +++ b/crates/relation/tests/mainnet.rs @@ -57,8 +57,7 @@ struct FixtureIntent { } fn dataset_path() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../test/vectors/mainnet.json") + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../test/vectors/mainnet.json") } fn load() -> Option { @@ -131,7 +130,10 @@ fn witness(f: &Fixture) -> Witness { fn bounds(d: &Dataset) -> Bounds { let b = Bounds::default(); let max = |f: &dyn Fn(&Fixture) -> usize| d.fixtures.iter().map(f).max().unwrap_or(0); - assert!(max(&|f| f.depth) <= b.depth, "a fixture is deeper than the bound"); + assert!( + max(&|f| f.depth) <= b.depth, + "a fixture is deeper than the bound" + ); assert!( max(&|f| f.max_node_bytes) <= b.node_bytes, "a fixture node exceeds the bound" @@ -210,8 +212,7 @@ fn dataset_is_varied() { .iter() .map(|f| f.intent.settlement_token.as_str()) .collect(); - let types: std::collections::BTreeSet = - d.fixtures.iter().map(|f| f.receipt_type).collect(); + let types: std::collections::BTreeSet = d.fixtures.iter().map(|f| f.receipt_type).collect(); let blocks: std::collections::BTreeSet = d.fixtures.iter().map(|f| f.block_number).collect(); @@ -236,8 +237,11 @@ fn commitments_are_distinct() { let Some(d) = load() else { return; }; - let set: std::collections::BTreeSet<&str> = - d.fixtures.iter().map(|f| f.intent.commitment.as_str()).collect(); + let set: std::collections::BTreeSet<&str> = d + .fixtures + .iter() + .map(|f| f.intent.commitment.as_str()) + .collect(); assert_eq!( set.len(), d.fixtures.len(), From 6dea00aecd33840a9637b15226955cd2a71b8ddd Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:29:57 -0400 Subject: [PATCH 05/22] chore: add relation constraint profiling --- crates/relation/src/lib.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 1e54a37..4d4967c 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -46,6 +46,24 @@ use mirage_gadgets::statement; pub const MEASUREMENT_SCOPE: &str = "commitment + header + MPT inclusion + ERC-20 relation + statement hash"; +/// Prints an attributable constraint delta when `RELATION_PROFILE` is set. +/// +/// This deliberately observes only `num_constraints`: it does not allocate +/// variables or otherwise change the circuit. Optimization branches use these +/// stable stage names so their deltas can be compared against one baseline. +fn profile( + cs: &ConstraintSystemRef, + stage: &str, + last: &mut usize, +) { + if std::env::var_os("RELATION_PROFILE").is_none() { + return; + } + let now = cs.num_constraints(); + eprintln!("{stage:>24}: {:>10}", now - *last); + *last = now; +} + /// Compiled bounds for this build. #[derive(Clone, Copy)] pub struct Bounds { @@ -190,6 +208,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { let b = self.bounds; let w = self.w(); + let mut mark = cs.num_constraints(); // ---- public inputs ---- // @@ -236,6 +255,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { amount: opening.settlement_amount.clone(), }; let log_index = FpVar::new_witness(cs.clone(), || Ok(F::from(w.log_index as u64)))?; + profile(&cs, "allocation", &mut mark); // ---- the relation ---- // @@ -250,6 +270,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { // is what turns "some Transfer happened" into "the Transfer this escrow // committed to happened". mirage_gadgets::commitment::open(&opening, &ctx.intent_commitment, &Boolean::TRUE)?; + profile(&cs, "intent commitment", &mut mark); // The commitment's deployment/request/row context must be the same // context whose statement hash the verifier checks. The commitment @@ -259,11 +280,13 @@ impl ConstraintSynthesizer for ReceiptCircuit { enforce_bytes_equal(&opening.escrow, &ctx.escrow)?; enforce_bytes_equal(&opening.request_id, &ctx.request_id)?; enforce_bytes_equal(&opening.row_index, &ctx.row_index)?; + profile(&cs, "context equality", &mut mark); // // The header supplies the root rather than the caller. Accepting a // caller-supplied root would let a prover invent a trie containing // whatever it liked. let parsed = header::parse(&header_bytes, &header_len, &Boolean::TRUE)?; + profile(&cs, "header parse", &mut mark); // Authenticate both header identity fields carried by the statement. // Parsing a receiptsRoot is not useful unless the parsed header is the @@ -273,6 +296,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { for (got, want) in header_digest.iter().zip(ctx.witness_block_hash.iter()) { UInt8::from_bits_le(got).enforce_equal(want)?; } + profile(&cs, "header hash", &mut mark); let witness_number = fixed_be_value(&ctx.witness_block_number)?; parsed.number.enforce_equal(&witness_number)?; @@ -282,6 +306,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { let bond_deadline = fixed_be_value(&ctx.bond_deadline)?; lt_u64(&bond_start, &parsed.number)?.enforce_equal(&Boolean::TRUE)?; lt_u64(&bond_deadline, &parsed.number)?.enforce_equal(&Boolean::FALSE)?; + profile(&cs, "block/time checks", &mut mark); // The receipt is the MPT leaf's value, so inclusion binds the exact // bytes the log walk then inspects. Without that link the relation @@ -295,6 +320,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { &receipt_len, &nodes, )?; + profile(&cs, "MPT traversal", &mut mark); // The single-log variant: spec 20.3 requires production settlements be a // direct `transfer()` call, whose receipt carries exactly one event. // Skipping the walk to log `k` saves 16% of the receipt relation. @@ -303,6 +329,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { // which the enclave's pre-settlement token review must enforce rather // than the prover discovering it. See `receipt::log::sole_log`. Erc20SingleLog::verify(&receipt, &receipt_len, &log_index, &intent, &Boolean::TRUE)?; + profile(&cs, "receipt relation", &mut mark); // ---- statement hash ---- // @@ -311,6 +338,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { // them down only shrinks the verifier. let signals = statement::compute(&ctx)?; statement::enforce(&signals, &public_hi, &public_lo, &Boolean::TRUE)?; + profile(&cs, "statement hash", &mut mark); Ok(()) } From 1671ecd2710a8eb054729236f601d21516954f17 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:46:50 -0400 Subject: [PATCH 06/22] perf: specialize single-transfer receipt layout --- EXPERIMENT.md | 28 +++++ crates/gadgets/src/receipt/log.rs | 165 ++++++++++++++++++++++++++++ crates/gadgets/src/receipt/tests.rs | 11 ++ crates/relation/src/lib.rs | 4 +- 4 files changed, 206 insertions(+), 2 deletions(-) create mode 100644 EXPERIMENT.md diff --git a/EXPERIMENT.md b/EXPERIMENT.md new file mode 100644 index 0000000..d524dad --- /dev/null +++ b/EXPERIMENT.md @@ -0,0 +1,28 @@ +# Fixed-layout direct-transfer receipt experiment + +Baseline: `opt/baseline-profiling` (`6dea00a`). + +## Result + +| Metric | Baseline | This branch | Delta | +|---|---:|---:|---:| +| Receipt relation | 828,585 | 2,535 | -826,050 | +| Full relation | 10,426,684 | 9,600,634 | -826,050 (-7.9%) | + +The existing single-log adversarial suite passes, and all 100 mainnet fixtures +satisfy the full relation. + +## Why it works + +With exactly one canonical `Transfer`, only the envelope byte and encoded width +of `cumulativeGasUsed` move field boundaries. The circuit enumerates the 18 +possible layouts and reads every checked byte at a compile-time offset. Layout +selectors are derived from the receipt bytes and exact length; no native parse +result is trusted. + +## Feasibility + +High for the already-adopted direct-transfer/single-log policy. It deliberately +does not support general multi-log receipts. Before production, add exhaustive +tests over gas widths 1 through 9 and preserve the generic parser as the +reference oracle for differential fuzzing. diff --git a/crates/gadgets/src/receipt/log.rs b/crates/gadgets/src/receipt/log.rs index bfe5639..0049029 100644 --- a/crates/gadgets/src/receipt/log.rs +++ b/crates/gadgets/src/receipt/log.rs @@ -28,6 +28,7 @@ use ark_ff::PrimeField; use ark_r1cs_std::boolean::Boolean; +use ark_r1cs_std::convert::ToBitsGadget; use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::fields::FieldVar; @@ -212,6 +213,170 @@ pub struct Erc20; /// walk. See [`sole_log`] for what that trades away. pub struct Erc20SingleLog; +/// The single-Transfer relation expressed as a finite set of fixed layouts. +/// +/// Once a receipt is restricted to one canonical ERC-20 `Transfer`, only two +/// values move any field boundary: whether an EIP-2718 type byte is present, +/// and the encoded width of `cumulativeGasUsed`. Enumerating those 18 layouts +/// turns every receipt access into a compile-time index. The candidate flags +/// are derived from the receipt bytes and exact length, so the native witness +/// builder supplies no trusted parse result. +pub struct Erc20FixedLayout; + +impl super::ReceiptRelation for Erc20FixedLayout { + fn verify( + receipt: &[UInt8], + receipt_len: &FpVar, + log_index: &FpVar, + intent: &Intent, + active: &Boolean, + ) -> Result<(), SynthesisError> { + // This relation is deliberately the same single-log narrowing as + // `Erc20SingleLog`. + log_index.conditional_enforce_equal(&FpVar::zero(), active)?; + + // A typed envelope is one of exactly 0x01..0x04. Legacy starts with the + // payload's 0xf9 list prefix. All supported direct-transfer receipts + // have a two-byte outer payload length. + let mut type_ok = Boolean::FALSE; + for t in 1u8..=4 { + type_ok |= receipt[0].is_eq(&UInt8::constant(t))?; + } + let legacy_prefix = receipt[0].is_eq(&UInt8::constant(0xf9))?; + let typed_payload_prefix = receipt[1].is_eq(&UInt8::constant(0xf9))?; + + let mut accepted = Boolean::FALSE; + for payload_at in 0usize..=1 { + for gas_total in 1usize..=9 { + // Outer list: three-byte header plus a body containing status + // (1), gas (gas_total), bloom (259), and logs (159). + let total = payload_at + 422 + gas_total; + let length_matches = + receipt_len.is_eq(&FpVar::constant(F::from(total as u64)))?; + let envelope_matches = if payload_at == 0 { + legacy_prefix.clone() + } else { + type_ok.clone() & typed_payload_prefix.clone() + }; + let candidate = length_matches & envelope_matches; + accepted |= candidate.clone(); + + check_fixed_layout( + receipt, + payload_at, + gas_total, + intent, + &(active.clone() & candidate), + )?; + } + } + + accepted.conditional_enforce_equal(&Boolean::TRUE, active)?; + Ok(()) + } +} + +fn check_fixed_layout( + receipt: &[UInt8], + payload_at: usize, + gas_total: usize, + intent: &Intent, + active: &Boolean, +) -> Result<(), SynthesisError> { + // payload = [status, cumulativeGasUsed, logsBloom, [Transfer]] + assert!(receipt.len() >= payload_at + 431, "receipt bound too small"); + let body_len = 419 + gas_total; + byte_eq(receipt, payload_at, 0xf9, active)?; + byte_eq(receipt, payload_at + 1, 0x01, active)?; + byte_eq(receipt, payload_at + 2, (body_len - 256) as u8, active)?; + byte_eq(receipt, payload_at + 3, 0x01, active)?; // successful status + + let gas_at = payload_at + 4; + if gas_total == 1 { + // Empty (zero) or a bare byte below 0x80. 0x81 would be non-minimal. + let bits = receipt[gas_at].to_bits_le()?; + let empty = receipt[gas_at].is_eq(&UInt8::constant(0x80))?; + (!bits[7].clone() | empty).conditional_enforce_equal(&Boolean::TRUE, active)?; + } else { + byte_eq(receipt, gas_at, 0x80 + (gas_total - 1) as u8, active)?; + if gas_total == 2 { + // RLP must encode a one-byte value below 0x80 in bare form. + let bits = receipt[gas_at + 1].to_bits_le()?; + bits[7].conditional_enforce_equal(&Boolean::TRUE, active)?; + } + } + + let bloom_at = gas_at + gas_total; + byte_eq(receipt, bloom_at, 0xb9, active)?; + byte_eq(receipt, bloom_at + 1, 0x01, active)?; + byte_eq(receipt, bloom_at + 2, 0x00, active)?; + + let logs_at = bloom_at + 259; + byte_eq(receipt, logs_at, 0xf8, active)?; + byte_eq(receipt, logs_at + 1, 0x9d, active)?; // one 157-byte log + + let log_at = logs_at + 2; + byte_eq(receipt, log_at, 0xf8, active)?; + byte_eq(receipt, log_at + 1, 0x9b, active)?; // 155-byte log body + + let address_at = log_at + 2; + byte_eq(receipt, address_at, 0x94, active)?; + bytes_equal(&receipt[address_at + 1..address_at + 21], &intent.token, active)?; + + let topics_at = address_at + 21; + byte_eq(receipt, topics_at, 0xf8, active)?; + byte_eq(receipt, topics_at + 1, 0x63, active)?; + + let topic0_at = topics_at + 2; + byte_eq(receipt, topic0_at, 0xa0, active)?; + for (got, want) in receipt[topic0_at + 1..topic0_at + 33] + .iter() + .zip(TRANSFER_TOPIC0.iter()) + { + got.conditional_enforce_equal(&UInt8::constant(*want), active)?; + } + + let topic1_at = topic0_at + 33; + byte_eq(receipt, topic1_at, 0xa0, active)?; // sender intentionally free + + let topic2_at = topic1_at + 33; + byte_eq(receipt, topic2_at, 0xa0, active)?; + for byte in &receipt[topic2_at + 1..topic2_at + 13] { + byte.conditional_enforce_equal(&UInt8::constant(0), active)?; + } + bytes_equal( + &receipt[topic2_at + 13..topic2_at + 33], + &intent.recipient, + active, + )?; + + let data_at = topic2_at + 33; + byte_eq(receipt, data_at, 0xa0, active)?; + bytes_equal(&receipt[data_at + 1..data_at + 33], &intent.amount, active)?; + Ok(()) +} + +fn byte_eq( + receipt: &[UInt8], + at: usize, + want: u8, + active: &Boolean, +) -> Result<(), SynthesisError> { + receipt[at].conditional_enforce_equal(&UInt8::constant(want), active) +} + +fn bytes_equal( + got: &[UInt8], + want: &[UInt8], + active: &Boolean, +) -> Result<(), SynthesisError> { + assert_eq!(got.len(), want.len()); + for (got, want) in got.iter().zip(want.iter()) { + got.conditional_enforce_equal(want, active)?; + } + Ok(()) +} + impl super::ReceiptRelation for Erc20SingleLog { fn verify( receipt: &[UInt8], diff --git a/crates/gadgets/src/receipt/tests.rs b/crates/gadgets/src/receipt/tests.rs index ba5003c..f8c532a 100644 --- a/crates/gadgets/src/receipt/tests.rs +++ b/crates/gadgets/src/receipt/tests.rs @@ -576,6 +576,17 @@ fn single_log_adversarial_suite() { run_forgeries::(); } +/// The finite-layout implementation must preserve the complete single-log +/// relation, including every adversarial rejection case. +#[test] +fn fixed_layout_adversarial_suite() { + use super::log::Erc20FixedLayout as R; + accepts_genuine_receipt::(); + accepts_every_supported_envelope::(); + accepts_any_sender::(); + run_forgeries::(); +} + /// The narrowing the variant trades for its saving: a receipt with a second /// event must be rejected, where the general relation accepts it. /// diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 4d4967c..53defce 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -30,7 +30,7 @@ use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystemRef, Synthesis use mirage_gadgets::bytes::alloc_bounded; use mirage_gadgets::header; use mirage_gadgets::mpt::{traverse::Traversal, MptVerifier, ProofNode}; -use mirage_gadgets::receipt::{log::Erc20SingleLog, Intent, ReceiptRelation}; +use mirage_gadgets::receipt::{log::Erc20FixedLayout, Intent, ReceiptRelation}; use mirage_gadgets::statement; /// What this circuit does and does not include, so the measured numbers are @@ -328,7 +328,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { // The trade is that a receipt with any second event becomes unprovable, // which the enclave's pre-settlement token review must enforce rather // than the prover discovering it. See `receipt::log::sole_log`. - Erc20SingleLog::verify(&receipt, &receipt_len, &log_index, &intent, &Boolean::TRUE)?; + Erc20FixedLayout::verify(&receipt, &receipt_len, &log_index, &intent, &Boolean::TRUE)?; profile(&cs, "receipt relation", &mut mark); // ---- statement hash ---- From cbbb8e06e9f1b656d1639fdb7203d0c1d6ecb158 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:59:30 -0400 Subject: [PATCH 07/22] test: exhaust fixed receipt layout widths --- EXPERIMENT.md | 6 ++-- crates/gadgets/src/receipt/tests.rs | 48 +++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/EXPERIMENT.md b/EXPERIMENT.md index d524dad..cc1a510 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -23,6 +23,6 @@ result is trusted. ## Feasibility High for the already-adopted direct-transfer/single-log policy. It deliberately -does not support general multi-log receipts. Before production, add exhaustive -tests over gas widths 1 through 9 and preserve the generic parser as the -reference oracle for differential fuzzing. +does not support general multi-log receipts. Exhaustive tests cover gas widths +1 through 9 and every supported receipt envelope. Preserve the generic parser +as the reference oracle for differential fuzzing. diff --git a/crates/gadgets/src/receipt/tests.rs b/crates/gadgets/src/receipt/tests.rs index f8c532a..c46e574 100644 --- a/crates/gadgets/src/receipt/tests.rs +++ b/crates/gadgets/src/receipt/tests.rs @@ -587,6 +587,54 @@ fn fixed_layout_adversarial_suite() { run_forgeries::(); } +#[test] +fn fixed_layout_accepts_every_gas_width() { + let amt = amount(77); + let log = transfer_log(&TOKEN, &SENDER, &RECIPIENT, &amt); + for gas_total in 1usize..=9 { + let encoded_gas = if gas_total == 1 { + vec![0x7f] // canonical bare byte + } else { + let width = gas_total - 1; + let mut item = vec![0x80 + width as u8]; + item.push(if width == 1 { 0x80 } else { 0x01 }); + item.resize(gas_total, 0); + item + }; + let payload = enc_list(&[ + enc_str(&[1]), + encoded_gas, + enc_str(&[0u8; 256]), + enc_list(std::slice::from_ref(&log)), + ]); + for envelope in [None, Some(1u8), Some(2), Some(3), Some(4)] { + let mut receipt = envelope.into_iter().collect::>(); + receipt.extend_from_slice(&payload); + assert!( + accepts_genuine_intent::(&receipt, 0, &amt), + "rejected gas width {gas_total}, envelope {envelope:?}" + ); + } + } +} + +#[test] +fn fixed_layout_rejects_nonminimal_one_byte_gas() { + let amt = amount(77); + let log = transfer_log(&TOKEN, &SENDER, &RECIPIENT, &amt); + let payload = enc_list(&[ + enc_str(&[1]), + vec![0x81, 0x7f], // must be encoded as bare 0x7f + enc_str(&[0u8; 256]), + enc_list(&[log]), + ]); + let mut receipt = vec![0x02]; + receipt.extend_from_slice(&payload); + assert!(!accepts_genuine_intent::( + &receipt, 0, &amt + )); +} + /// The narrowing the variant trades for its saving: a receipt with a second /// event must be rejected, where the general relation accepts it. /// From 3b7b1a60f2461d3c09fc3b7e14ad384c84095b8a Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:48:01 -0400 Subject: [PATCH 08/22] perf: extract authenticated header fields at fixed offsets --- EXPERIMENT.md | 35 ++++++---------- crates/gadgets/src/header.rs | 81 ++++++++++++++++++++++++++++++++++++ crates/relation/src/lib.rs | 3 +- 3 files changed, 96 insertions(+), 23 deletions(-) diff --git a/EXPERIMENT.md b/EXPERIMENT.md index cc1a510..656c69a 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -1,28 +1,19 @@ -# Fixed-layout direct-transfer receipt experiment +# Combined fixed-layout candidate Baseline: `opt/baseline-profiling` (`6dea00a`). -## Result +This branch combines the independently measured fixed-layout receipt and +authenticated-header-prefix experiments. See the corresponding branches for +their detailed soundness arguments and isolated measurements. -| Metric | Baseline | This branch | Delta | -|---|---:|---:|---:| -| Receipt relation | 828,585 | 2,535 | -826,050 | -| Full relation | 10,426,684 | 9,600,634 | -826,050 (-7.9%) | +Expected additive result before measuring this branch: -The existing single-log adversarial suite passes, and all 100 mainnet fixtures -satisfy the full relation. +| Optimization | Constraint delta | +|---|---:| +| Single-transfer receipt layout | -826,050 | +| Authenticated header prefix | -1,114,749 | +| Combined | -1,940,799 (-18.6%) | -## Why it works - -With exactly one canonical `Transfer`, only the envelope byte and encoded width -of `cumulativeGasUsed` move field boundaries. The circuit enumerates the 18 -possible layouts and reads every checked byte at a compile-time offset. Layout -selectors are derived from the receipt bytes and exact length; no native parse -result is trusted. - -## Feasibility - -High for the already-adopted direct-transfer/single-log policy. It deliberately -does not support general multi-log receipts. Exhaustive tests cover gas widths -1 through 9 and every supported receipt envelope. Preserve the generic parser -as the reference oracle for differential fuzzing. +The expected full relation size is 8,485,885 constraints. The receipt change is +high feasibility for the existing single-log policy. The header change requires +explicit approval of the narrower authenticated-extraction responsibility. diff --git a/crates/gadgets/src/header.rs b/crates/gadgets/src/header.rs index 98abf28..0307860 100644 --- a/crates/gadgets/src/header.rs +++ b/crates/gadgets/src/header.rs @@ -31,9 +31,11 @@ use ark_ff::PrimeField; use ark_r1cs_std::boolean::Boolean; +use ark_r1cs_std::convert::ToBitsGadget; use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::fields::FieldVar; +use ark_r1cs_std::select::CondSelectGadget; use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; @@ -104,6 +106,85 @@ pub fn parse( }) } +/// Extracts the fields before the first variable-width header item using the +/// fixed post-Prague prefix layout. +/// +/// This variant is sound only when the caller separately proves that +/// `keccak256(header)` is a canonical chain block hash. Consensus then supplies +/// the full-header validity that [`parse`] establishes syntactically. The +/// circuit still pins every fixed prefix through `difficulty` and canonically +/// decodes `number`; an unknown fork that changes this prefix fails closed. +pub fn parse_authenticated_prefix( + header: &[UInt8], + _header_len: &FpVar, + active: &Boolean, +) -> Result, SynthesisError> { + // Two-byte long-list length, followed by the fixed-width fields through + // post-Merge difficulty. Payload length bytes remain variable. + for (at, want) in [ + (0usize, 0xf9u8), + (3, 0xa0), // parentHash + (36, 0xa0), // ommersHash + (69, 0x94), // beneficiary + (90, 0xa0), // stateRoot + (123, 0xa0), // transactionsRoot + (156, 0xa0), // receiptsRoot + (189, 0xb9), // logsBloom, 256 bytes + (190, 0x01), + (191, 0x00), + (448, 0x80), // post-Merge difficulty == 0 + ] { + header[at].conditional_enforce_equal(&UInt8::constant(want), active)?; + } + + let parent_hash = header[4..36].to_vec(); + let receipts_root = header[157..189].to_vec(); + + // Number begins at a compile-time offset. Enumerating its at-most-eight + // byte canonical integer forms is dramatically cheaper than walking the + // other twenty RLP items to discover the same offset. + let prefix = &header[449]; + let bits = { + use ark_r1cs_std::convert::ToBitsGadget; + prefix.to_bits_le()? + }; + let bare = !bits[7].clone(); + let mut accepted = bare.clone(); + let mut number = crate::bytes::byte_to_field(prefix)?; + + for width in 1usize..=8 { + let selected = prefix.is_eq(&UInt8::constant(0x80 + width as u8))?; + accepted |= selected.clone(); + + let mut value = FpVar::zero(); + for byte in &header[450..450 + width] { + value = value * FpVar::constant(F::from(256u64)) + + crate::bytes::byte_to_field(byte)?; + } + number = FpVar::conditionally_select(&selected, &value, &number)?; + + // Minimal integer encoding, beyond ordinary canonical RLP: a one-byte + // payload below 0x80 is bare, and a wider integer has no leading zero. + if width == 1 { + let first_bits = header[450].to_bits_le()?; + first_bits[7].conditional_enforce_equal(&Boolean::TRUE, &(active.clone() & selected))?; + } else { + let first_is_zero = header[450].is_eq(&UInt8::constant(0))?; + first_is_zero.conditional_enforce_equal( + &Boolean::FALSE, + &(active.clone() & selected), + )?; + } + } + accepted.conditional_enforce_equal(&Boolean::TRUE, active)?; + + Ok(Header { + parent_hash, + receipts_root, + number, + }) +} + /// Reads up to `max` bytes at `offset` as a big-endian integer, honouring a /// witnessed length. /// diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 53defce..1f3ddfd 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -285,7 +285,8 @@ impl ConstraintSynthesizer for ReceiptCircuit { // The header supplies the root rather than the caller. Accepting a // caller-supplied root would let a prover invent a trie containing // whatever it liked. - let parsed = header::parse(&header_bytes, &header_len, &Boolean::TRUE)?; + let parsed = + header::parse_authenticated_prefix(&header_bytes, &header_len, &Boolean::TRUE)?; profile(&cs, "header parse", &mut mark); // Authenticate both header identity fields carried by the statement. From 2709f00ef93ff4b49087c69fd72d661d3b93e11e Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:55:52 -0400 Subject: [PATCH 09/22] test: cover authenticated header prefix extraction --- crates/gadgets/src/header.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/gadgets/src/header.rs b/crates/gadgets/src/header.rs index 0307860..f7057ae 100644 --- a/crates/gadgets/src/header.rs +++ b/crates/gadgets/src/header.rs @@ -309,6 +309,30 @@ mod tests { assert_eq!(h.number.value().unwrap(), Fr::from(21_000_000u64), "number"); } + #[test] + fn authenticated_prefix_matches_the_full_parser() { + let root = [0xab; 32]; + let bytes = header_fixture(&root, 21_000_000); + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &bytes, BOUND).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(bytes.len() as u64))).unwrap(); + let h = parse_authenticated_prefix(&buf, &len, &Boolean::TRUE).unwrap(); + assert_eq!(h.receipts_root.iter().map(|b| b.value().unwrap()).collect::>(), root); + assert_eq!(h.number.value().unwrap(), Fr::from(21_000_000u64)); + assert!(cs.is_satisfied().unwrap()); + } + + #[test] + fn authenticated_prefix_rejects_a_shifted_schema() { + let mut bytes = header_fixture(&[0xab; 32], 21_000_000); + bytes[156] = 0x9f; // receiptsRoot is no longer a 32-byte string. + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &bytes, BOUND).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(bytes.len() as u64))).unwrap(); + let _ = parse_authenticated_prefix(&buf, &len, &Boolean::TRUE).unwrap(); + assert!(!cs.is_satisfied().unwrap()); + } + #[test] fn reads_small_and_large_block_numbers() { for n in [0u64, 1, 255, 256, 21_000_000, u32::MAX as u64] { From 85af001da2b74b29032157ebab45d299ffc5f731 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 13:02:58 -0400 Subject: [PATCH 10/22] docs: record combined optimization result --- EXPERIMENT.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/EXPERIMENT.md b/EXPERIMENT.md index 656c69a..81deb33 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -6,7 +6,7 @@ This branch combines the independently measured fixed-layout receipt and authenticated-header-prefix experiments. See the corresponding branches for their detailed soundness arguments and isolated measurements. -Expected additive result before measuring this branch: +Measured additive result: | Optimization | Constraint delta | |---|---:| @@ -14,6 +14,7 @@ Expected additive result before measuring this branch: | Authenticated header prefix | -1,114,749 | | Combined | -1,940,799 (-18.6%) | -The expected full relation size is 8,485,885 constraints. The receipt change is +The full relation is 8,485,885 constraints, exactly matching the isolated +measurements. The receipt change is high feasibility for the existing single-log policy. The header change requires explicit approval of the narrower authenticated-extraction responsibility. From 902ad3e91d143a319bb6483cf56caf9b196bc300 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 13:16:48 -0400 Subject: [PATCH 11/22] perf: add structural receipt bound to combined candidate --- EXPERIMENT.md | 15 ++++++++------- crates/relation/src/lib.rs | 15 ++++++--------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/EXPERIMENT.md b/EXPERIMENT.md index 81deb33..86f08c0 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -2,19 +2,20 @@ Baseline: `opt/baseline-profiling` (`6dea00a`). -This branch combines the independently measured fixed-layout receipt and -authenticated-header-prefix experiments. See the corresponding branches for -their detailed soundness arguments and isolated measurements. +This branch combines the independently measured fixed-layout receipt, +448-byte structural receipt bound, and authenticated-header-prefix experiments. +See the corresponding branches for their detailed soundness arguments and +isolated measurements. Measured additive result: | Optimization | Constraint delta | |---|---:| | Single-transfer receipt layout | -826,050 | +| 448-byte receipt bound after fixed layout | -88,896 | | Authenticated header prefix | -1,114,749 | -| Combined | -1,940,799 (-18.6%) | +| Combined | -2,029,695 (-19.5%) | -The full relation is 8,485,885 constraints, exactly matching the isolated -measurements. The receipt change is -high feasibility for the existing single-log policy. The header change requires +The full relation is 8,396,989 constraints. The receipt changes are high +feasibility for the existing single-log policy. The header change requires explicit approval of the narrower authenticated-extraction responsibility. diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 1f3ddfd..12133f5 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -90,15 +90,12 @@ impl Default for Bounds { // Path matching iterates `key.len() * 2` times over two buffers, so // this is a direct multiplier on that sub-step. key_bytes: 3, - // Measured across 100 mainnet direct-transfer receipts: 425 to 428 - // bytes. 512 leaves 20% headroom over the observed maximum while - // costing roughly 760k fewer constraints than 1024. - // - // The headroom matters more than the saving: an over-tight bound - // makes a settlement unprovable at the executor's expense (spec - // 12.9). A token emitting a slightly larger Transfer, or one whose - // cumulativeGasUsed needs an extra byte, must still fit. - receipt_bytes: 512, + // A canonical status receipt containing exactly one ERC-20 + // Transfer is at most 432 bytes, including a typed envelope and a + // nine-byte cumulativeGasUsed item. The production policy already + // rejects additional logs, so 448 retains 16 bytes above the + // structural maximum rather than padding to a general receipt. + receipt_bytes: 448, // Measured across 100 mainnet blocks: 632 to 655 bytes, a 23-byte // spread driven entirely by `extraData`. // From 734913c79fb4ea4574f5fd43f27ba7c642aa02a5 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 12:47:23 -0400 Subject: [PATCH 12/22] perf: prototype constructed receipt trie leaf --- EXPERIMENT.md | 26 ++-- crates/gadgets/src/mpt/constructed_leaf.rs | 147 +++++++++++++++++++++ crates/gadgets/src/mpt/mod.rs | 1 + 3 files changed, 156 insertions(+), 18 deletions(-) create mode 100644 crates/gadgets/src/mpt/constructed_leaf.rs diff --git a/EXPERIMENT.md b/EXPERIMENT.md index 86f08c0..6f1a777 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -1,21 +1,11 @@ -# Combined fixed-layout candidate +# Combined candidate with constructed terminal leaf -Baseline: `opt/baseline-profiling` (`6dea00a`). +Parent: `opt/combined-candidate` (`902ad3e`), 8,396,989 constraints. -This branch combines the independently measured fixed-layout receipt, -448-byte structural receipt bound, and authenticated-header-prefix experiments. -See the corresponding branches for their detailed soundness arguments and -isolated measurements. +This branch integrates a finite family of canonically constructed receipt-trie +leaves into the combined receipt/header candidate. The circuit constructs the +leaf from the already-bound key remainder and receipt, rather than accepting a +raw terminal-node witness and generically parsing and copying its value. -Measured additive result: - -| Optimization | Constraint delta | -|---|---:| -| Single-transfer receipt layout | -826,050 | -| 448-byte receipt bound after fixed layout | -88,896 | -| Authenticated header prefix | -1,114,749 | -| Combined | -2,029,695 (-19.5%) | - -The full relation is 8,396,989 constraints. The receipt changes are high -feasibility for the existing single-log policy. The header change requires -explicit approval of the narrower authenticated-extraction responsibility. +Measurements and final feasibility conclusions will be recorded after full +relation integration. diff --git a/crates/gadgets/src/mpt/constructed_leaf.rs b/crates/gadgets/src/mpt/constructed_leaf.rs new file mode 100644 index 0000000..35e2966 --- /dev/null +++ b/crates/gadgets/src/mpt/constructed_leaf.rs @@ -0,0 +1,147 @@ +//! Canonical construction of the common receipt-trie terminal leaf. +//! +//! After two branch levels consume a one-byte `RLP(transactionIndex)` key, the +//! remaining compact path is the empty leaf path `0x20`. For receipts between +//! 256 and 512 bytes the complete node has one fixed shape: +//! +//! ```text +//! f9 20 b9 +//! ``` +//! +//! Constructing those bytes from the already-bound receipt removes the generic +//! leaf decoder, path comparison, and witness-positioned value copy. This +//! module is intentionally a shape prototype; broader key/depth cases need +//! either additional finite shapes or the existing generic traversal. + +use ark_ff::{BigInteger, PrimeField}; +use ark_r1cs_std::alloc::AllocVar; +use ark_r1cs_std::boolean::Boolean; +use ark_r1cs_std::eq::EqGadget; +use ark_r1cs_std::fields::fp::FpVar; +use ark_r1cs_std::fields::FieldVar; +use ark_r1cs_std::uint8::UInt8; +use ark_r1cs_std::GR1CSVar; +use ark_relations::gr1cs::SynthesisError; + +use crate::bytes::byte_to_field; +use crate::keccak::sponge::Byte; +use crate::keccak::keccak256_var; + +/// Constructs and hashes `RLP([empty_leaf_path, receipt])`. +/// +/// `receipt` remains a normal left-aligned bounded buffer. The two allocated +/// length bytes are not hints: field equalities bind them to `receipt_len`. +pub fn hash_empty_path_leaf( + receipt: &[UInt8], + receipt_len: &FpVar, + active: &Boolean, +) -> Result<[Byte; 32], SynthesisError> { + let cs = receipt_len.cs(); + let len_value = receipt_len.value().unwrap_or(F::zero()); + let mut len_bytes = len_value.into_bigint().to_bytes_le(); + len_bytes.resize(8, 0); + let native_len = u64::from_le_bytes(len_bytes[..8].try_into().expect("eight bytes")); + + let receipt_hi = UInt8::new_witness(cs.clone(), || Ok((native_len >> 8) as u8))?; + let receipt_low = UInt8::new_witness(cs.clone(), || Ok(native_len as u8))?; + let body_len = native_len.saturating_add(4); + let body_hi = UInt8::new_witness(cs.clone(), || Ok((body_len >> 8) as u8))?; + let body_low = UInt8::new_witness(cs, || Ok(body_len as u8))?; + + let decode_u16 = |hi: &UInt8, low: &UInt8| -> Result, SynthesisError> { + Ok(byte_to_field(hi)? * FpVar::constant(F::from(256u64)) + byte_to_field(low)?) + }; + decode_u16(&receipt_hi, &receipt_low)? + .conditional_enforce_equal(receipt_len, active)?; + decode_u16(&body_hi, &body_low)? + .conditional_enforce_equal(&(receipt_len + FpVar::constant(F::from(4u64))), active)?; + + // Long-form length-of-length is exactly two bytes. The leaf buffer's own + // bounded hash enforces the upper end (receipt_len <= receipt.len()). + let receipt_hi_ok = receipt_hi.is_eq(&UInt8::constant(1))? + | receipt_hi.is_eq(&UInt8::constant(2))?; + let body_hi_ok = body_hi.is_eq(&UInt8::constant(1))? | body_hi.is_eq(&UInt8::constant(2))?; + receipt_hi_ok.conditional_enforce_equal(&Boolean::TRUE, active)?; + body_hi_ok.conditional_enforce_equal(&Boolean::TRUE, active)?; + + let mut leaf = Vec::with_capacity(receipt.len() + 7); + leaf.extend([ + UInt8::constant(0xf9), + body_hi, + body_low, + UInt8::constant(0x20), + UInt8::constant(0xb9), + receipt_hi, + receipt_low, + ]); + leaf.extend_from_slice(receipt); + + let leaf_len = receipt_len + FpVar::constant(F::from(7u64)); + keccak256_var(&leaf, &leaf_len, active) +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_bn254::Fr; + use ark_r1cs_std::fields::fp::FpVar; + use ark_relations::gr1cs::ConstraintSystem; + + use crate::bytes::alloc_bounded; + + fn native_leaf(receipt: &[u8]) -> Vec { + assert!((256..=512).contains(&receipt.len())); + let body = receipt.len() + 4; + let mut out = vec![ + 0xf9, + (body >> 8) as u8, + body as u8, + 0x20, + 0xb9, + (receipt.len() >> 8) as u8, + receipt.len() as u8, + ]; + out.extend_from_slice(receipt); + out + } + + #[test] + fn constructed_leaf_matches_native_rlp() { + let receipt = vec![0x42; 428]; + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let digest = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); + let got: Vec = digest + .iter() + .map(|bits| { + bits.iter().enumerate().fold(0u8, |v, (i, b)| { + v | ((b.value().unwrap() as u8) << i) + }) + }) + .collect(); + assert_eq!(got, mirage_encoding::keccak256(&native_leaf(&receipt))); + assert!(cs.is_satisfied().unwrap()); + } + + #[test] + fn rejects_a_length_outside_the_shape() { + let receipt = vec![0x42; 255]; + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let _ = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); + assert!(!cs.is_satisfied().unwrap()); + } + + #[test] + fn cost() { + let receipt = vec![0x42; 428]; + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let before = cs.num_constraints(); + let _ = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); + println!("constructed empty-path leaf: {} constraints", cs.num_constraints() - before); + } +} diff --git a/crates/gadgets/src/mpt/mod.rs b/crates/gadgets/src/mpt/mod.rs index 7460387..33b9430 100644 --- a/crates/gadgets/src/mpt/mod.rs +++ b/crates/gadgets/src/mpt/mod.rs @@ -37,6 +37,7 @@ //! present an unrelated node. The adversarial suite in [`tests`] names each. #[cfg(test)] +pub mod constructed_leaf; pub mod harness; pub mod node; #[cfg(test)] From c7ef3008f9c249e7e550e55a65563b2f5de502cf Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 13:47:55 -0400 Subject: [PATCH 13/22] perf: construct terminal MPT leaf in circuit --- EXPERIMENT.md | 34 +- crates/gadgets/src/mpt/constructed_leaf.rs | 284 ++++++++++---- .../gadgets/src/mpt/constructed_traverse.rs | 371 ++++++++++++++++++ crates/gadgets/src/mpt/mod.rs | 3 +- crates/gadgets/src/mpt/node.rs | 23 +- crates/gadgets/src/mpt/traverse.rs | 6 +- crates/relation/src/lib.rs | 27 +- 7 files changed, 655 insertions(+), 93 deletions(-) create mode 100644 crates/gadgets/src/mpt/constructed_traverse.rs diff --git a/EXPERIMENT.md b/EXPERIMENT.md index 6f1a777..a115de7 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -7,5 +7,35 @@ leaves into the combined receipt/header candidate. The circuit constructs the leaf from the already-bound key remainder and receipt, rather than accepting a raw terminal-node witness and generically parsing and copying its value. -Measurements and final feasibility conclusions will be recorded after full -relation integration. +## Result + +| Metric | Baseline | Parent combined | This branch | +|---|---:|---:|---:| +| MPT traversal | 6,722,724 | 6,634,340 | 3,304,933 | +| Full relation | 10,426,684 | 8,396,989 | 5,061,149 | +| Reduction from baseline | — | 19.5% | **51.5%** | + +The terminal construction supports every remaining path length for the +three-byte key bound, not only the common empty path. Ancestor buffers use +structural maxima: 308 bytes for an active root branch and 532 bytes for a +fully occupied deeper branch. A root leaf is represented by zero ancestors. + +The shape Boolean is an untrusted witness hint: it only selects whether the +complete 17-item branch decoder or complete two-item extension decoder must +pass. The wrong hint cannot bypass either decoder. + +## Fast verification + +- All seven remaining-path layouts match native RLP and Keccak. +- Genuine branch-to-leaf, extension, and root-leaf shapes satisfy. +- Wrong root, key, receipt, ancestor, extension path, and appended-node cases + reject. +- Existing branch-as-short and short-as-branch decoder tests reject. +- The representative full relation satisfies at exactly 5,061,149 constraints. + +## Feasibility + +High for the current relation's existing depth-four and three-byte-key policy. +The witness API still carries a redundant raw terminal node which synthesis +ignores; remove it in a cleanup pass before merging. Full fixture and proving +tests remain final-candidate gates rather than iteration gates. diff --git a/crates/gadgets/src/mpt/constructed_leaf.rs b/crates/gadgets/src/mpt/constructed_leaf.rs index 35e2966..218a64c 100644 --- a/crates/gadgets/src/mpt/constructed_leaf.rs +++ b/crates/gadgets/src/mpt/constructed_leaf.rs @@ -1,17 +1,11 @@ -//! Canonical construction of the common receipt-trie terminal leaf. +//! Canonical construction of a receipt-trie terminal leaf. //! -//! After two branch levels consume a one-byte `RLP(transactionIndex)` key, the -//! remaining compact path is the empty leaf path `0x20`. For receipts between -//! 256 and 512 bytes the complete node has one fixed shape: -//! -//! ```text -//! f9 20 b9 -//! ``` -//! -//! Constructing those bytes from the already-bound receipt removes the generic -//! leaf decoder, path comparison, and witness-positioned value copy. This -//! module is intentionally a shape prototype; broader key/depth cases need -//! either additional finite shapes or the existing generic traversal. +//! The key is at most three bytes, so a terminal leaf has only seven possible +//! remaining-path lengths (zero through six nibbles). This module enumerates +//! those finite layouts, constructs the canonical hex-prefix path and RLP from +//! the already-bound key and receipt, and hashes the selected layout once. +//! There is no raw leaf witness to decode and no witness-positioned receipt to +//! copy out of it. use ark_ff::{BigInteger, PrimeField}; use ark_r1cs_std::alloc::AllocVar; @@ -19,6 +13,7 @@ use ark_r1cs_std::boolean::Boolean; use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::fields::FieldVar; +use ark_r1cs_std::select::CondSelectGadget; use ark_r1cs_std::uint8::UInt8; use ark_r1cs_std::GR1CSVar; use ark_relations::gr1cs::SynthesisError; @@ -26,14 +21,19 @@ use ark_relations::gr1cs::SynthesisError; use crate::bytes::byte_to_field; use crate::keccak::sponge::Byte; use crate::keccak::keccak256_var; +use crate::mpt::path::nibble_at; -/// Constructs and hashes `RLP([empty_leaf_path, receipt])`. +/// Constructs and hashes `RLP([HP(key[consumed..], leaf), receipt])`. /// -/// `receipt` remains a normal left-aligned bounded buffer. The two allocated -/// length bytes are not hints: field equalities bind them to `receipt_len`. -pub fn hash_empty_path_leaf( +/// `receipt` and `key` remain normal left-aligned bounded buffers. Every RLP +/// length byte and every packed path byte is constrained to the source fields; +/// the native values used to allocate them are only witness generators. +pub fn hash_leaf_from_remainder( receipt: &[UInt8], receipt_len: &FpVar, + key: &[UInt8], + key_len: &FpVar, + consumed: &FpVar, active: &Boolean, ) -> Result<[Byte; 32], SynthesisError> { let cs = receipt_len.cs(); @@ -44,42 +44,114 @@ pub fn hash_empty_path_leaf( let receipt_hi = UInt8::new_witness(cs.clone(), || Ok((native_len >> 8) as u8))?; let receipt_low = UInt8::new_witness(cs.clone(), || Ok(native_len as u8))?; - let body_len = native_len.saturating_add(4); - let body_hi = UInt8::new_witness(cs.clone(), || Ok((body_len >> 8) as u8))?; - let body_low = UInt8::new_witness(cs, || Ok(body_len as u8))?; - let decode_u16 = |hi: &UInt8, low: &UInt8| -> Result, SynthesisError> { Ok(byte_to_field(hi)? * FpVar::constant(F::from(256u64)) + byte_to_field(low)?) }; decode_u16(&receipt_hi, &receipt_low)? .conditional_enforce_equal(receipt_len, active)?; - decode_u16(&body_hi, &body_low)? - .conditional_enforce_equal(&(receipt_len + FpVar::constant(F::from(4u64))), active)?; - - // Long-form length-of-length is exactly two bytes. The leaf buffer's own - // bounded hash enforces the upper end (receipt_len <= receipt.len()). - let receipt_hi_ok = receipt_hi.is_eq(&UInt8::constant(1))? - | receipt_hi.is_eq(&UInt8::constant(2))?; - let body_hi_ok = body_hi.is_eq(&UInt8::constant(1))? | body_hi.is_eq(&UInt8::constant(2))?; - receipt_hi_ok.conditional_enforce_equal(&Boolean::TRUE, active)?; - body_hi_ok.conditional_enforce_equal(&Boolean::TRUE, active)?; - - let mut leaf = Vec::with_capacity(receipt.len() + 7); - leaf.extend([ - UInt8::constant(0xf9), - body_hi, - body_low, - UInt8::constant(0x20), - UInt8::constant(0xb9), - receipt_hi, - receipt_low, - ]); - leaf.extend_from_slice(receipt); - - let leaf_len = receipt_len + FpVar::constant(F::from(7u64)); + receipt_hi + .conditional_enforce_equal(&UInt8::constant(1), active)?; + + let total_nibbles = key_len * FpVar::constant(F::from(2u64)); + let remaining = &total_nibbles - consumed; + let max_nibbles = key.len() * 2; + let mut layouts = Vec::with_capacity(max_nibbles + 1); + let mut any_layout = Boolean::FALSE; + let mut path_item_len = FpVar::zero(); + for n in 0..=max_nibbles { + let selected = remaining.is_eq(&FpVar::constant(F::from(n as u64)))?; + any_layout |= selected.clone(); + let encoded_len = if n <= 1 { 1 } else { 2 + n / 2 }; + path_item_len = FpVar::conditionally_select( + &selected, + &FpVar::constant(F::from(encoded_len as u64)), + &path_item_len, + )?; + layouts.push((selected, encoded_len, path_bytes(key, consumed, n, active)?)); + } + any_layout.conditional_enforce_equal(&Boolean::TRUE, active)?; + + let body_len_var = receipt_len + &path_item_len + FpVar::constant(F::from(3u64)); + let native_body_len = fp_to_u64(body_len_var.value().unwrap_or(F::zero())); + let body_hi = UInt8::new_witness(cs.clone(), || Ok((native_body_len >> 8) as u8))?; + let body_low = UInt8::new_witness(cs, || Ok(native_body_len as u8))?; + decode_u16(&body_hi, &body_low)?.conditional_enforce_equal(&body_len_var, active)?; + body_hi.conditional_enforce_equal(&UInt8::constant(1), active)?; + + // Maximum layout: 3-byte outer header, 5-byte encoded path, 3-byte + // receipt header, and the bounded receipt. + let node_bound = receipt.len() + 11; + let mut leaf = vec![UInt8::constant(0); node_bound]; + for (selected, encoded_len, path) in layouts { + let mut candidate = vec![UInt8::constant(0); node_bound]; + candidate[0] = UInt8::constant(0xf9); + candidate[1] = body_hi.clone(); + candidate[2] = body_low.clone(); + if path.len() == 1 { + candidate[3] = path[0].clone(); + } else { + candidate[3] = UInt8::constant(0x80 + path.len() as u8); + candidate[4..4 + path.len()].clone_from_slice(&path); + } + let receipt_at = 3 + encoded_len; + candidate[receipt_at] = UInt8::constant(0xb9); + candidate[receipt_at + 1] = receipt_hi.clone(); + candidate[receipt_at + 2] = receipt_low.clone(); + candidate[receipt_at + 3..receipt_at + 3 + receipt.len()].clone_from_slice(receipt); + for (out, byte) in leaf.iter_mut().zip(candidate.iter()) { + *out = UInt8::conditionally_select(&selected, byte, out)?; + } + } + + let leaf_len = receipt_len + path_item_len + FpVar::constant(F::from(6u64)); keccak256_var(&leaf, &leaf_len, active) } +fn path_bytes( + key: &[UInt8], + consumed: &FpVar, + n: usize, + active: &Boolean, +) -> Result>, SynthesisError> { + let cs = consumed.cs(); + let mut expressions = Vec::with_capacity(1 + n / 2); + if n % 2 == 0 { + expressions.push(FpVar::constant(F::from(0x20u64))); + } else { + expressions.push( + FpVar::constant(F::from(0x30u64)) + nibble_at(key, consumed)?, + ); + } + let mut j = n % 2; + while j < n { + let high = nibble_at(key, &(consumed + FpVar::constant(F::from(j as u64))))?; + let low = nibble_at( + key, + &(consumed + FpVar::constant(F::from((j + 1) as u64))), + )?; + expressions.push(high * FpVar::constant(F::from(16u64)) + low); + j += 2; + } + + expressions + .into_iter() + .map(|expression| { + let native = fp_to_u64(expression.value().unwrap_or(F::zero())) as u8; + let byte = UInt8::new_witness(cs.clone(), || Ok(native))?; + byte_to_field(&byte)?.conditional_enforce_equal(&expression, active)?; + Ok(byte) + }) + .collect() +} + +fn fp_to_u64(value: F) -> u64 { + let bytes = value.into_bigint().to_bytes_le(); + let mut out = [0u8; 8]; + let n = bytes.len().min(8); + out[..n].copy_from_slice(&bytes[..n]); + u64::from_le_bytes(out) +} + #[cfg(test)] mod tests { use super::*; @@ -89,48 +161,97 @@ mod tests { use crate::bytes::alloc_bounded; - fn native_leaf(receipt: &[u8]) -> Vec { - assert!((256..=512).contains(&receipt.len())); - let body = receipt.len() + 4; - let mut out = vec![ - 0xf9, - (body >> 8) as u8, - body as u8, - 0x20, - 0xb9, - (receipt.len() >> 8) as u8, - receipt.len() as u8, - ]; + fn native_leaf(receipt: &[u8], key: &[u8], consumed: usize) -> Vec { + assert!((256..=448).contains(&receipt.len())); + let nibbles: Vec = key + .iter() + .flat_map(|byte| [byte >> 4, byte & 0x0f]) + .skip(consumed) + .collect(); + let mut path = Vec::with_capacity(1 + nibbles.len() / 2); + let mut at = 0; + if nibbles.len() % 2 == 0 { + path.push(0x20); + } else { + path.push(0x30 | nibbles[0]); + at = 1; + } + while at < nibbles.len() { + path.push(nibbles[at] << 4 | nibbles[at + 1]); + at += 2; + } + let mut path_item = if path.len() == 1 { + path + } else { + let mut item = vec![0x80 + path.len() as u8]; + item.extend(path); + item + }; + let body = path_item.len() + 3 + receipt.len(); + let mut out = vec![0xf9, (body >> 8) as u8, body as u8]; + out.append(&mut path_item); + out.extend([0xb9, (receipt.len() >> 8) as u8, receipt.len() as u8]); out.extend_from_slice(receipt); out } #[test] - fn constructed_leaf_matches_native_rlp() { + fn every_remaining_path_layout_matches_native_rlp() { let receipt = vec![0x42; 428]; - let cs = ConstraintSystem::::new_ref(); - let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); - let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); - let digest = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); - let got: Vec = digest - .iter() - .map(|bits| { - bits.iter().enumerate().fold(0u8, |v, (i, b)| { - v | ((b.value().unwrap() as u8) << i) + let key = [0x12, 0x34, 0x56]; + for consumed in 0..=6 { + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &receipt, 448).unwrap(); + let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let key_buf = alloc_bounded(cs.clone(), &key, 3).unwrap(); + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(3u64))).unwrap(); + let consumed_var = + FpVar::new_witness(cs.clone(), || Ok(Fr::from(consumed as u64))).unwrap(); + let digest = hash_leaf_from_remainder( + &buf, + &len, + &key_buf, + &key_len, + &consumed_var, + &Boolean::TRUE, + ) + .unwrap(); + let got: Vec = digest + .iter() + .map(|bits| { + bits.iter().enumerate().fold(0u8, |v, (i, b)| { + v | ((b.value().unwrap() as u8) << i) + }) }) - }) - .collect(); - assert_eq!(got, mirage_encoding::keccak256(&native_leaf(&receipt))); - assert!(cs.is_satisfied().unwrap()); + .collect(); + assert_eq!( + got, + mirage_encoding::keccak256(&native_leaf(&receipt, &key, consumed)), + "remaining path length {}", + 6 - consumed + ); + assert!(cs.is_satisfied().unwrap()); + } } #[test] fn rejects_a_length_outside_the_shape() { let receipt = vec![0x42; 255]; let cs = ConstraintSystem::::new_ref(); - let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); + let buf = alloc_bounded(cs.clone(), &receipt, 448).unwrap(); let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); - let _ = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); + let key = alloc_bounded(cs.clone(), &[0x12], 3).unwrap(); + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(1u64))).unwrap(); + let consumed = FpVar::new_witness(cs.clone(), || Ok(Fr::from(0u64))).unwrap(); + let _ = hash_leaf_from_remainder( + &buf, + &len, + &key, + &key_len, + &consumed, + &Boolean::TRUE, + ) + .unwrap(); assert!(!cs.is_satisfied().unwrap()); } @@ -138,10 +259,21 @@ mod tests { fn cost() { let receipt = vec![0x42; 428]; let cs = ConstraintSystem::::new_ref(); - let buf = alloc_bounded(cs.clone(), &receipt, 512).unwrap(); + let buf = alloc_bounded(cs.clone(), &receipt, 448).unwrap(); let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let key = alloc_bounded(cs.clone(), &[0x12], 3).unwrap(); + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(1u64))).unwrap(); + let consumed = FpVar::new_witness(cs.clone(), || Ok(Fr::from(2u64))).unwrap(); let before = cs.num_constraints(); - let _ = hash_empty_path_leaf(&buf, &len, &Boolean::TRUE).unwrap(); - println!("constructed empty-path leaf: {} constraints", cs.num_constraints() - before); + let _ = hash_leaf_from_remainder( + &buf, + &len, + &key, + &key_len, + &consumed, + &Boolean::TRUE, + ) + .unwrap(); + println!("constructed finite-family leaf: {} constraints", cs.num_constraints() - before); } } diff --git a/crates/gadgets/src/mpt/constructed_traverse.rs b/crates/gadgets/src/mpt/constructed_traverse.rs new file mode 100644 index 0000000..8dee85f --- /dev/null +++ b/crates/gadgets/src/mpt/constructed_traverse.rs @@ -0,0 +1,371 @@ +//! MPT traversal with a canonically constructed terminal leaf. +//! +//! Witness nodes contain only branches and extensions. After those ancestors +//! consume a prefix of the key, the terminal leaf is constructed from the +//! remaining key nibbles and the already-bound receipt. This removes the +//! generic terminal decoder and witness-positioned value copy while preserving +//! the same root-to-value inclusion statement. + +use ark_ff::{BigInteger, PrimeField}; +use ark_r1cs_std::alloc::AllocVar; +use ark_r1cs_std::boolean::Boolean; +use ark_r1cs_std::eq::EqGadget; +use ark_r1cs_std::fields::fp::FpVar; +use ark_r1cs_std::fields::FieldVar; +use ark_r1cs_std::select::CondSelectGadget; +use ark_r1cs_std::uint8::UInt8; +use ark_r1cs_std::GR1CSVar; +use ark_relations::gr1cs::SynthesisError; + +use super::constructed_leaf::hash_leaf_from_remainder; +use super::node::{branch_child_offset, decode_branch, decode_short}; +use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at, read_flags}; +use super::traverse::{assert_path_matches, bits_to_byte}; +use super::{MptVerifier, ProofNode}; +use crate::bytes::{one_hot, select_byte_with, select_bytes, zero_like}; +use crate::keccak::keccak256_var; + +pub struct ConstructedLeafTraversal; + +fn profile(buf: &[UInt8], step: &str, last: &mut usize) { + if std::env::var_os("MPT_PROFILE").is_none() { + return; + } + if let Some(byte) = buf.first() { + let now = byte.cs().num_constraints(); + eprintln!("{:>12} {step}", now - *last); + *last = now; + } +} + +impl MptVerifier for ConstructedLeafTraversal { + fn verify_inclusion( + root: &[UInt8], + key: &[UInt8], + key_len: &FpVar, + value: &[UInt8], + value_len: &FpVar, + nodes: &[ProofNode], + ) -> Result<(), SynthesisError> { + let mut expected = root.to_vec(); + let mut consumed = zero_like(key)?; + let mut inactive_seen = Boolean::FALSE; + + for (level_index, level) in nodes.iter().enumerate() { + let mut mark = level + .bytes + .first() + .map(|byte| byte.cs().num_constraints()) + .unwrap_or(0); + let active = level.active.clone(); + + // Ancestors form one active prefix. Otherwise a prover could skip + // a link and resume from an unrelated later node. + (inactive_seen.clone() & active.clone()).enforce_equal(&Boolean::FALSE)?; + inactive_seen |= !active.clone(); + + let digest = keccak256_var(&level.bytes, &level.len, &active)?; + for (digest_byte, want) in digest.iter().zip(expected.iter()) { + bits_to_byte(digest_byte)?.conditional_enforce_equal(want, &active)?; + } + profile(&level.bytes, "link-hash", &mut mark); + + // A non-leaf receipt trie contains indices 0 and 1, whose RLP + // keys begin with nibbles 8 and 0. Therefore an active root cannot + // be an extension; the zero-ancestor case handles a root leaf. + // Compile this position as branch-only instead of paying for the + // speculative short-node decoder and path machinery. + if level_index == 0 { + let branch = decode_branch(&level.bytes, &level.len, &active)?; + let nibble = nibble_at(key, &consumed)?; + let child_offset = branch_child_offset(&branch, &nibble, &active)?; + let next_ref = select_bytes(&level.bytes, &child_offset, 32)?; + consumed = FpVar::conditionally_select( + &active, + &(&consumed + FpVar::one()), + &consumed, + )?; + expected = expected + .iter() + .zip(next_ref.iter()) + .map(|(old, new)| UInt8::conditionally_select(&active, new, old)) + .collect::, _>>()?; + profile(&level.bytes, "root-branch", &mut mark); + continue; + } + + // Shape is a witness hint, not a trusted parse result. Whichever + // value the prover chooses activates a decoder that fully proves + // either 17 branch items or exactly two short-node items. This + // avoids decoding the outer list and its first two children a + // third time merely to choose between those same decoders. + let native_len = fp_to_usize(level.len.value().unwrap_or(F::zero())); + let native_bytes: Vec = level + .bytes + .iter() + .take(native_len.min(level.bytes.len())) + .map(|byte| byte.value().unwrap_or(0)) + .collect(); + let native_branch = native_list_arity(&native_bytes) == Some(17); + let this_is_branch = + Boolean::new_witness(level.len.cs(), || Ok(native_branch))?; + profile(&level.bytes, "shape-hint", &mut mark); + let branch_active = active.clone() & this_is_branch.clone(); + let short_active = active.clone() & !this_is_branch.clone(); + let branch = decode_branch(&level.bytes, &level.len, &branch_active)?; + let short = decode_short(&level.bytes, &level.len, &short_active)?; + profile(&level.bytes, "decoders", &mut mark); + + let nibble = nibble_at(key, &consumed)?; + let child_offset = branch_child_offset(&branch, &nibble, &branch_active)?; + profile(&level.bytes, "child-offset", &mut mark); + + let first_sel = one_hot(&short.path_offset, level.bytes.len())?; + let first = select_byte_with(&level.bytes, &first_sel)?; + assert_canonical_flags(&first, &short_active)?; + let flags = read_flags(&first)?; + assert_even_pad_is_zero(&first, &flags.is_odd, &short_active)?; + + // Every witnessed short node is an extension. The leaf is derived + // below and therefore cannot be replaced by prover-supplied bytes. + flags + .is_leaf + .conditional_enforce_equal(&Boolean::FALSE, &short_active)?; + short.tail_len.conditional_enforce_equal( + &FpVar::constant(F::from(32u64)), + &short_active, + )?; + profile(&level.bytes, "flags", &mut mark); + + let path_nibbles = &short.path_len * FpVar::constant(F::from(2u64)) + - FpVar::conditionally_select( + &flags.is_odd, + &FpVar::one(), + &FpVar::constant(F::from(2u64)), + )?; + assert_path_matches( + &level.bytes, + &short, + &flags.is_odd, + key, + &consumed, + &path_nibbles, + &short_active, + )?; + profile(&level.bytes, "path-match", &mut mark); + + let next_offset = + FpVar::conditionally_select(&this_is_branch, &child_offset, &short.tail_offset)?; + let next_ref = select_bytes(&level.bytes, &next_offset, 32)?; + profile(&level.bytes, "tail-read", &mut mark); + let step = FpVar::conditionally_select( + &this_is_branch, + &FpVar::one(), + &path_nibbles, + )?; + consumed = FpVar::conditionally_select( + &active, + &(&consumed + step), + &consumed, + )?; + expected = expected + .iter() + .zip(next_ref.iter()) + .map(|(old, new)| UInt8::conditionally_select(&active, new, old)) + .collect::, _>>()?; + profile(&level.bytes, "advance", &mut mark); + } + + let mut leaf_mark = key + .first() + .map(|byte| byte.cs().num_constraints()) + .unwrap_or(0); + let leaf_digest = + hash_leaf_from_remainder(value, value_len, key, key_len, &consumed, &Boolean::TRUE)?; + profile(key, "constructed-leaf", &mut leaf_mark); + for (digest_byte, want) in leaf_digest.iter().zip(expected.iter()) { + bits_to_byte(digest_byte)?.enforce_equal(want)?; + } + Ok(()) + } +} + +fn fp_to_usize(value: F) -> usize { + let bytes = value.into_bigint().to_bytes_le(); + let mut out = [0u8; 8]; + let n = bytes.len().min(8); + out[..n].copy_from_slice(&bytes[..n]); + u64::from_le_bytes(out) as usize +} + +/// Native witness generation only. Circuit soundness comes from the selected +/// decoder; a wrong result here makes a genuine witness fail, not a forgery +/// pass. +fn native_list_arity(bytes: &[u8]) -> Option { + let (header, payload) = native_item_shape(bytes, 0)?; + let end = header.checked_add(payload)?; + if end != bytes.len() || bytes.first().copied()? < 0xc0 { + return None; + } + let mut at = header; + let mut count = 0; + while at < end { + let (item_header, item_payload) = native_item_shape(bytes, at)?; + at = at.checked_add(item_header)?.checked_add(item_payload)?; + if at > end { + return None; + } + count += 1; + } + (at == end).then_some(count) +} + +fn native_item_shape(bytes: &[u8], at: usize) -> Option<(usize, usize)> { + let prefix = *bytes.get(at)?; + match prefix { + 0x00..=0x7f => Some((0, 1)), + 0x80..=0xb7 => Some((1, (prefix - 0x80) as usize)), + 0xb8..=0xbf => native_long_shape(bytes, at, (prefix - 0xb7) as usize), + 0xc0..=0xf7 => Some((1, (prefix - 0xc0) as usize)), + 0xf8..=0xff => native_long_shape(bytes, at, (prefix - 0xf7) as usize), + } +} + +fn native_long_shape(bytes: &[u8], at: usize, len_of_len: usize) -> Option<(usize, usize)> { + let mut payload = 0usize; + for byte in bytes.get(at + 1..at + 1 + len_of_len)? { + payload = payload.checked_mul(256)?.checked_add(*byte as usize)?; + } + Some((1 + len_of_len, payload)) +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_bn254::Fr; + use ark_r1cs_std::alloc::AllocVar; + use ark_relations::gr1cs::{ConstraintSystem, ConstraintSystemRef}; + + use crate::bytes::alloc_bounded; + use crate::mpt::harness::NativeProof; + use crate::mpt::tests::{ + branch_node, extension_node, leaf_node, simple_trie, + }; + + fn genuine() -> NativeProof { + let key = vec![0x35, 0x71]; + let value = vec![0x42; 300]; + let (root, key, value, nodes) = simple_trie(3, &key, &value); + NativeProof { + root, + key, + value, + nodes, + } + } + + fn verify(p: &NativeProof) -> bool { + let cs = ConstraintSystem::::new_ref(); + match build(cs.clone(), p) { + Err(_) => false, + Ok(()) => cs.is_satisfied().unwrap_or(false), + } + } + + fn build( + cs: ConstraintSystemRef, + p: &NativeProof, + ) -> Result<(), SynthesisError> { + let root = alloc_bounded(cs.clone(), &p.root, 32)?; + let key = alloc_bounded(cs.clone(), &p.key, 3)?; + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.key.len() as u64)))?; + let value = alloc_bounded(cs.clone(), &p.value, 448)?; + let value_len = + FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64)))?; + + let ancestor_count = p.nodes.len().saturating_sub(1); + let mut nodes = Vec::with_capacity(3); + for i in 0..3 { + let (bytes, len, active) = match p.nodes.get(i).filter(|_| i < ancestor_count) { + Some(node) => (node.clone(), node.len(), true), + None => (Vec::new(), 0, false), + }; + nodes.push(ProofNode { + bytes: alloc_bounded(cs.clone(), &bytes, 544)?, + len: FpVar::new_witness(cs.clone(), || Ok(Fr::from(len as u64)))?, + active: Boolean::new_witness(cs.clone(), || Ok(active))?, + }); + } + ConstructedLeafTraversal::verify_inclusion( + &root, + &key, + &key_len, + &value, + &value_len, + &nodes, + ) + } + + #[test] + fn accepts_a_genuine_constructed_leaf_proof() { + assert!(verify(&genuine())); + } + + #[test] + fn accepts_a_root_leaf_without_ancestors() { + let key = vec![0x80]; + let value = vec![0x42; 300]; + let leaf = leaf_node(&[8, 0], &value); + let proof = NativeProof { + root: mirage_encoding::keccak256(&leaf), + key, + value, + nodes: vec![leaf], + }; + assert!(verify(&proof)); + } + + #[test] + fn rejects_wrong_root_key_value_and_ancestor() { + let mut wrong_root = genuine(); + wrong_root.root[0] ^= 1; + assert!(!verify(&wrong_root), "accepted a wrong root"); + + let mut wrong_key = genuine(); + wrong_key.key[1] ^= 1; + assert!(!verify(&wrong_key), "accepted a wrong key remainder"); + + let mut wrong_value = genuine(); + wrong_value.value[17] ^= 1; + assert!(!verify(&wrong_value), "accepted a wrong receipt value"); + + let mut wrong_ancestor = genuine(); + wrong_ancestor.nodes[0][7] ^= 1; + assert!(!verify(&wrong_ancestor), "accepted an unauthenticated ancestor"); + } + + #[test] + fn rejects_an_extension_with_the_wrong_path() { + let key = vec![0x35, 0x71]; + let value = vec![0x42; 300]; + let leaf = leaf_node(&[1], &value); + let extension = extension_node(&[9, 9], &leaf); + let mut children: [Option>; 16] = Default::default(); + children[3] = Some(extension.clone()); + let root_node = branch_node(children, None); + let proof = NativeProof { + root: mirage_encoding::keccak256(&root_node), + key, + value, + nodes: vec![root_node, extension, leaf], + }; + assert!(!verify(&proof), "accepted a mismatched extension path"); + } + + #[test] + fn rejects_a_node_appended_after_the_terminal_leaf() { + let mut proof = genuine(); + proof.nodes.push(leaf_node(&[1], &vec![0x55; 300])); + assert!(!verify(&proof), "accepted a node past the terminal leaf"); + } +} diff --git a/crates/gadgets/src/mpt/mod.rs b/crates/gadgets/src/mpt/mod.rs index 33b9430..d1a3c47 100644 --- a/crates/gadgets/src/mpt/mod.rs +++ b/crates/gadgets/src/mpt/mod.rs @@ -36,8 +36,9 @@ //! Every one of those is a place where a missing constraint lets a prover //! present an unrelated node. The adversarial suite in [`tests`] names each. -#[cfg(test)] pub mod constructed_leaf; +pub mod constructed_traverse; +#[cfg(test)] pub mod harness; pub mod node; #[cfg(test)] diff --git a/crates/gadgets/src/mpt/node.rs b/crates/gadgets/src/mpt/node.rs index d67c3f2..7730a7b 100644 --- a/crates/gadgets/src/mpt/node.rs +++ b/crates/gadgets/src/mpt/node.rs @@ -185,16 +185,27 @@ pub fn decode_short( node_len: &FpVar, active: &Boolean, ) -> Result, SynthesisError> { - let items = Cursor::decode_list(node, &zero_at(node)?, 2, active)?; - // The list must span the whole node. let list = Cursor::decode_item(node, &zero_at(node)?, active)?; + list.is_list + .conditional_enforce_equal(&Boolean::TRUE, active)?; list.end().conditional_enforce_equal(node_len, active)?; + let first = Cursor::decode_item(node, &list.offset, active)?; + first + .is_list + .conditional_enforce_equal(&Boolean::FALSE, active)?; + let second = Cursor::decode_item(node, &first.end(), active)?; + second + .is_list + .conditional_enforce_equal(&Boolean::FALSE, active)?; + // Starting each item at the previous end gives adjacency; this equality + // proves that exactly two items tile the outer list. + second.end().conditional_enforce_equal(&list.end(), active)?; Ok(ShortNode { - path_offset: items[0].offset.clone(), - path_len: items[0].payload_len.clone(), - tail_offset: items[1].offset.clone(), - tail_len: items[1].payload_len.clone(), + path_offset: first.offset, + path_len: first.payload_len, + tail_offset: second.offset, + tail_len: second.payload_len, }) } diff --git a/crates/gadgets/src/mpt/traverse.rs b/crates/gadgets/src/mpt/traverse.rs index 95fecba..1248313 100644 --- a/crates/gadgets/src/mpt/traverse.rs +++ b/crates/gadgets/src/mpt/traverse.rs @@ -290,7 +290,9 @@ impl MptVerifier for Traversal { } /// Eight boolean bits, least significant first, back into a `UInt8`. -fn bits_to_byte(bits: &[Boolean; 8]) -> Result, SynthesisError> { +pub(super) fn bits_to_byte( + bits: &[Boolean; 8], +) -> Result, SynthesisError> { Ok(UInt8::from_bits_le(bits)) } @@ -318,7 +320,7 @@ fn cond_select_bytes( /// /// Invariant 4. Compares up to a compiled maximum, gating each position on /// whether it is within the actual path length. -fn assert_path_matches( +pub(super) fn assert_path_matches( node: &[UInt8], short: &super::node::ShortNode, is_odd: &Boolean, diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 12133f5..0d383d4 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -29,7 +29,9 @@ use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystemRef, Synthesis use mirage_gadgets::bytes::alloc_bounded; use mirage_gadgets::header; -use mirage_gadgets::mpt::{traverse::Traversal, MptVerifier, ProofNode}; +use mirage_gadgets::mpt::{ + constructed_traverse::ConstructedLeafTraversal, MptVerifier, ProofNode, +}; use mirage_gadgets::receipt::{log::Erc20FixedLayout, Intent, ReceiptRelation}; use mirage_gadgets::statement; @@ -227,14 +229,27 @@ impl ConstraintSynthesizer for ReceiptCircuit { let receipt = alloc_bounded(cs.clone(), &w.receipt, b.receipt_bytes)?; let receipt_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.receipt.len() as u64)))?; - let mut nodes = Vec::with_capacity(b.depth); - for i in 0..b.depth { - let (bytes, len, active) = match w.nodes.get(i) { + // The terminal leaf is constructed from the key remainder and receipt, + // so only the at-most `depth - 1` ancestor nodes are witnesses. + let ancestor_count = w.nodes.len().saturating_sub(1); + let mut nodes = Vec::with_capacity(b.depth.saturating_sub(1)); + for i in 0..b.depth.saturating_sub(1) { + // An active root is necessarily a branch: a root leaf is the + // zero-ancestor case constructed below. With three-byte RLP + // transaction-index keys, only first nibbles 0..=8 can occur, so + // at most nine 33-byte child references plus seven empty slots, + // an empty value and the three-byte list header fit in 308 bytes. + // Deeper branches can occupy all sixteen slots: 16*33 bytes of + // hash references, one empty value byte, and a three-byte list + // header are exactly 532 bytes. These are structural maxima, not + // sampled cutoffs. + let node_bound = if i == 0 { 308 } else { 532 }; + let (bytes, len, active) = match w.nodes.get(i).filter(|_| i < ancestor_count) { Some(n) => (n.clone(), n.len(), true), None => (Vec::new(), 0, false), }; nodes.push(ProofNode { - bytes: alloc_bounded(cs.clone(), &bytes, b.node_bytes)?, + bytes: alloc_bounded(cs.clone(), &bytes, node_bound)?, len: FpVar::new_witness(cs.clone(), || Ok(F::from(len as u64)))?, active: Boolean::new_witness(cs.clone(), || Ok(active))?, }); @@ -310,7 +325,7 @@ impl ConstraintSynthesizer for ReceiptCircuit { // bytes the log walk then inspects. Without that link the relation // would prove a Transfer in *some* receipt rather than one in this // block's trie. - Traversal::verify_inclusion( + ConstructedLeafTraversal::verify_inclusion( &parsed.receipts_root, &key, &key_len, From a8fbe1cf1efc30f5cda6adfefbf338694120ca3b Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 13:50:20 -0400 Subject: [PATCH 14/22] chore: profile sequential receipt trie shapes --- EXPERIMENT.md | 7 +++ .../fixtures/src/bin/profile_trie_shapes.rs | 63 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 crates/fixtures/src/bin/profile_trie_shapes.rs diff --git a/EXPERIMENT.md b/EXPERIMENT.md index a115de7..1214d95 100644 --- a/EXPERIMENT.md +++ b/EXPERIMENT.md @@ -39,3 +39,10 @@ High for the current relation's existing depth-four and three-byte-key policy. The witness API still carries a redundant raw terminal node which synthesis ignores; remove it in a cleanup pass before merging. Full fixture and proving tests remain final-candidate gates rather than iteration gates. + +The native sequential-trie profiler also exposes a pre-existing coverage +limit: proof depth reaches 5 at 130 receipts, 6 at 273, and 7 near 1,022. The +current depth-four circuit is therefore already a coverage tier, despite its +three-byte key buffer. Conversely, a one-byte transaction-index key has a +structural maximum of two branch ancestors and no extensions; that narrower +tier is measured separately rather than silently folded into this branch. diff --git a/crates/fixtures/src/bin/profile_trie_shapes.rs b/crates/fixtures/src/bin/profile_trie_shapes.rs new file mode 100644 index 0000000..acff125 --- /dev/null +++ b/crates/fixtures/src/bin/profile_trie_shapes.rs @@ -0,0 +1,63 @@ +//! Profiles canonical receipt-trie proof shapes over sequential transaction +//! indices. This is an optimization tool, not a network collector. + +use mirage_fixtures::trie::{key_for, Trie}; + +fn main() { + let mut counts: Vec = (1..=512).collect(); + for boundary in [1024usize, 2048, 4096, 8192, 16_384, 32_768, 65_536] { + for delta in -2isize..=2 { + let count = boundary.saturating_add_signed(delta); + if count > 0 && count <= 65_536 { + counts.push(count); + } + } + } + counts.sort_unstable(); + counts.dedup(); + + let value = vec![0x42; 432]; + let mut global_depth = 0usize; + let mut global_position = Vec::::new(); + let mut witnesses = Vec::<(usize, usize, usize, usize)>::new(); + + for count in counts { + let values = vec![value.clone(); count]; + let trie = Trie::build(&values); + let mut count_depth = 0usize; + let mut count_position = Vec::::new(); + for index in 0..count { + let proof = trie.proof(&key_for(index)).expect("proof"); + count_depth = count_depth.max(proof.len()); + // The final node is the constructed leaf and is not an ancestor + // witness in the optimized relation. + for (position, node) in proof[..proof.len() - 1].iter().enumerate() { + if count_position.len() <= position { + count_position.resize(position + 1, 0); + } + count_position[position] = count_position[position].max(node.len()); + if global_position.len() <= position { + global_position.resize(position + 1, 0); + } + if node.len() > global_position[position] { + global_position[position] = node.len(); + witnesses.push((position, node.len(), count, index)); + } + } + } + if count_depth > global_depth { + global_depth = count_depth; + eprintln!("new depth {global_depth} at receipt count {count}"); + } + if count <= 20 || matches!(count, 127..=130 | 255..=258 | 510..=512) { + eprintln!("count {count:>5}: depth {count_depth}, ancestors {count_position:?}"); + } + } + + println!("max proof depth: {global_depth}"); + println!("max ancestor bytes by position: {global_position:?}"); + println!("maxima witnesses (position, bytes, receipt_count, tx_index):"); + for witness in witnesses { + println!(" {witness:?}"); + } +} From da4f0978e82fd505bf000d8be8ff2c2df82aa67f Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Mon, 31 Aug 2026 18:01:18 -0400 Subject: [PATCH 15/22] perf: add universal depth-seven MPT tier --- UNIVERSAL_MPT_OPTIMIZATION.md | 39 +++++++++++++++++++++++++++++++++++ crates/relation/src/lib.rs | 12 +++++------ 2 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 UNIVERSAL_MPT_OPTIMIZATION.md diff --git a/UNIVERSAL_MPT_OPTIMIZATION.md b/UNIVERSAL_MPT_OPTIMIZATION.md new file mode 100644 index 0000000..6e02f59 --- /dev/null +++ b/UNIVERSAL_MPT_OPTIMIZATION.md @@ -0,0 +1,39 @@ +# Universal in-circuit MPT tier + +Branch: `opt/universal-depth-7-constructed-leaf` + +This is the universal circuit/VK candidate under the existing explicit bounds: + +- canonical receipt-trie key at most three bytes (transaction index below + 65,536), hence at most six key nibbles; +- receipt at most 448 bytes; +- header at most 704 bytes; +- structurally bounded root and deeper MPT nodes. + +Each branch consumes one key nibble and each extension consumes at least one. +Therefore a six-nibble key admits at most six ancestor nodes followed by the +constructed terminal leaf, for a maximum compiled depth of seven. All unused +slots are constrained inert, but R1CS still pays their Keccak and decoder cost. + +The entire Ethereum authentication chain remains inside the circuit: full +header Keccak, receipts-root extraction, every MPT Keccak/RLP/path link, +terminal-leaf construction, receipt semantics, intent opening, and statement +hashing. + +## Why ordinary preprocessing cannot shorten the proof + +An MPT node authenticates only its immediate child reference. Removing an +intermediate node also removes the Keccak equation connecting the parent hash +to the descendant. Off-circuit offsets, decoded shapes, or intermediate hashes +are only hints; the circuit must recompute and constrain every omitted link. + +A genuinely constant-depth input would require a succinct proof attesting to +the omitted links, or an independently authenticated non-MPT commitment. The +former is a recursive/folding architecture and the latter is not supplied by +Ethereum's current receipt commitment. Neither is a preprocessing-only change +to this Groth16 relation. + +Fast verification uses exact synthesis/profile counts, one representative +satisfying relation, adversarial gadget tests already shared with the parent, +and workspace compilation. Full setup/proving/EVM export remains a finalist +gate. diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 0d383d4..7830580 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -77,10 +77,10 @@ pub struct Bounds { } impl Default for Bounds { - /// The bounds the optimization phase settled on: a 544-byte node is the - /// structural worst case for a receipt-trie branch, a receipt-trie key is - /// `rlp(transactionIndex)` at four bytes, and depth 4 covers a typical - /// block's receipt trie. + /// Universal tier for the current three-byte transaction-index-key policy. + /// Such a key has at most six nibbles. Every branch consumes one nibble and + /// every extension consumes at least one, so at most six ancestors plus + /// the constructed terminal leaf can occur: total depth seven. fn default() -> Self { Self { node_bytes: 544, @@ -112,7 +112,7 @@ impl Default for Bounds { // already paid. Headroom here is cheap insurance against a field // this sample happened not to exercise. header_bytes: 704, - depth: 4, + depth: 7, } } } @@ -833,6 +833,6 @@ mod tests { "unsatisfied: {:?}", cs.which_is_unsatisfied() ); - println!("constraints: {}", cs.num_constraints()); + assert_eq!(cs.num_constraints(), 8_095_727); } } From d2eda3b5904e9b39afe9c0f5000fb30098eefd42 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Tue, 1 Sep 2026 15:44:17 -0400 Subject: [PATCH 16/22] perf: prototype arkworks Keccacheck verifier --- Cargo.toml | 2 +- experiments/keccacheck-arkworks/Cargo.lock | 1017 +++++++++++++++++ experiments/keccacheck-arkworks/Cargo.toml | 28 + experiments/keccacheck-arkworks/README.md | 42 + experiments/keccacheck-arkworks/RESULTS.md | 102 ++ experiments/keccacheck-arkworks/src/direct.rs | 173 +++ experiments/keccacheck-arkworks/src/lib.rs | 10 + experiments/keccacheck-arkworks/src/main.rs | 82 ++ .../keccacheck-arkworks/src/poseidon2.rs | 162 +++ .../src/poseidon2_constants.rs | 354 ++++++ .../keccacheck-arkworks/src/verifier.rs | 607 ++++++++++ 11 files changed, 2578 insertions(+), 1 deletion(-) create mode 100644 experiments/keccacheck-arkworks/Cargo.lock create mode 100644 experiments/keccacheck-arkworks/Cargo.toml create mode 100644 experiments/keccacheck-arkworks/README.md create mode 100644 experiments/keccacheck-arkworks/RESULTS.md create mode 100644 experiments/keccacheck-arkworks/src/direct.rs create mode 100644 experiments/keccacheck-arkworks/src/lib.rs create mode 100644 experiments/keccacheck-arkworks/src/main.rs create mode 100644 experiments/keccacheck-arkworks/src/poseidon2.rs create mode 100644 experiments/keccacheck-arkworks/src/poseidon2_constants.rs create mode 100644 experiments/keccacheck-arkworks/src/verifier.rs diff --git a/Cargo.toml b/Cargo.toml index 53a52dd..6489435 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = [ "crates/prover", "crates/fixtures", ] -exclude = ["bench-arkworks"] +exclude = ["bench-arkworks", "experiments/keccacheck-arkworks"] [workspace.package] version = "0.1.0" diff --git a/experiments/keccacheck-arkworks/Cargo.lock b/experiments/keccacheck-arkworks/Cargo.lock new file mode 100644 index 0000000..158b1d3 --- /dev/null +++ b/experiments/keccacheck-arkworks/Cargo.lock @@ -0,0 +1,1017 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "ark-bn254" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +dependencies = [ + "ark-ec", + "ark-ff", + "ark-r1cs-std", + "ark-std", +] + +[[package]] +name = "ark-crypto-primitives" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0c292754729c8a190e50414fd1a37093c786c709899f29c9f7daccecfa855e" +dependencies = [ + "ahash", + "ark-crypto-primitives-macros", + "ark-ec", + "ark-ff", + "ark-relations", + "ark-serialize", + "ark-snark", + "ark-std", + "blake2", + "derivative", + "digest", + "fnv", + "merlin", + "rayon", + "sha2", +] + +[[package]] +name = "ark-crypto-primitives-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e89fe77d1f0f4fe5b96dfc940923d88d17b6a773808124f21e764dfb063c6a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ark-ec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" +dependencies = [ + "ahash", + "ark-ff", + "ark-poly", + "ark-serialize", + "ark-std", + "educe", + "fnv", + "hashbrown", + "itertools", + "num-bigint", + "num-integer", + "num-traits", + "rayon", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" +dependencies = [ + "ark-ff-asm", + "ark-ff-macros", + "ark-serialize", + "ark-std", + "arrayvec", + "digest", + "educe", + "itertools", + "num-bigint", + "num-traits", + "paste", + "rayon", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ark-ff-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ark-groth16" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88f1d0f3a534bb54188b8dcc104307db6c56cdae574ddc3212aec0625740fc7e" +dependencies = [ + "ark-crypto-primitives", + "ark-ec", + "ark-ff", + "ark-poly", + "ark-relations", + "ark-serialize", + "ark-std", + "rayon", +] + +[[package]] +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" +dependencies = [ + "ahash", + "ark-ff", + "ark-serialize", + "ark-std", + "educe", + "fnv", + "hashbrown", + "rayon", +] + +[[package]] +name = "ark-r1cs-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" +dependencies = [ + "ark-ec", + "ark-ff", + "ark-relations", + "ark-std", + "educe", + "num-bigint", + "num-integer", + "num-traits", + "tracing", +] + +[[package]] +name = "ark-relations" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec46ddc93e7af44bcab5230937635b06fb5744464dd6a7e7b083e80ebd274384" +dependencies = [ + "ark-ff", + "ark-std", + "tracing", + "tracing-subscriber 0.2.25", +] + +[[package]] +name = "ark-serialize" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" +dependencies = [ + "ark-serialize-derive", + "ark-std", + "arrayvec", + "digest", + "num-bigint", + "rayon", +] + +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ark-snark" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d368e2848c2d4c129ce7679a7d0d2d612b6a274d3ea6a13bad4445d61b381b88" +dependencies = [ + "ark-ff", + "ark-relations", + "ark-serialize", + "ark-std", +] + +[[package]] +name = "ark-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" +dependencies = [ + "num-traits", + "rand", + "rayon", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "cc" +version = "1.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "enum-ordinalize" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89dd01549b09589510cf0647475075d12071456586d70f5c75c98ae2a5537677" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gkr" +version = "0.1.0" +source = "git+https://github.com/reilabs/keccacheck.git?rev=15f00e3da5622f1c7155b02d1f9c00bd2416c282#15f00e3da5622f1c7155b02d1f9c00bd2416c282" +dependencies = [ + "ark-bn254", + "ark-ec", + "ark-ff", + "ciborium", + "const-oid", + "hex", + "hex-literal", + "keccak", + "rayon", + "tracing", + "tracing-forest", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures 0.2.17", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "merlin" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" +dependencies = [ + "byteorder", + "keccak", + "rand_core", + "zeroize", +] + +[[package]] +name = "mirage-keccacheck-arkworks" +version = "0.1.0" +dependencies = [ + "ark-bn254", + "ark-ff", + "ark-groth16", + "ark-r1cs-std", + "ark-relations", + "ark-serialize", + "ark-snark", + "ark-std", + "blake3", + "gkr", + "keccak", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-forest" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee40835db14ddd1e3ba414292272eddde9dad04d3d4b65509656414d1c42592f" +dependencies = [ + "smallvec", + "thiserror", + "tracing", + "tracing-subscriber 0.3.23", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0d2eaa99c3c2e41547cfa109e910a68ea03823cccad4a0525dcbc9b01e8c71" +dependencies = [ + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/experiments/keccacheck-arkworks/Cargo.toml b/experiments/keccacheck-arkworks/Cargo.toml new file mode 100644 index 0000000..7d7702c --- /dev/null +++ b/experiments/keccacheck-arkworks/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "mirage-keccacheck-arkworks" +version = "0.1.0" +edition = "2024" +publish = false +license = "Apache-2.0" + +[dependencies] +ark-bn254 = { version = "0.5", features = ["std"] } +ark-ff = { version = "0.5", features = ["asm"] } +ark-groth16 = { version = "0.5", features = ["parallel"] } +ark-r1cs-std = { version = "0.5", features = ["std"] } +ark-relations = { version = "0.5", features = ["std"] } +ark-serialize = { version = "0.5", features = ["std"] } +ark-snark = "0.5" +ark-std = { version = "0.5", features = ["std"] } +blake3 = "1.8" +gkr = { git = "https://github.com/reilabs/keccacheck.git", rev = "15f00e3da5622f1c7155b02d1f9c00bd2416c282", default-features = false } +keccak = "0.1.5" + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 + +[profile.dev] +opt-level = 1 + diff --git a/experiments/keccacheck-arkworks/README.md b/experiments/keccacheck-arkworks/README.md new file mode 100644 index 0000000..e6fa302 --- /dev/null +++ b/experiments/keccacheck-arkworks/README.md @@ -0,0 +1,42 @@ +# Keccacheck arkworks experiment + +This excluded standalone crate ports the recursive Keccacheck verifier from +gnark to arkworks R1CS. It deliberately consumes the native proof produced by +Reilabs' Rust `gkr` crate at pinned commit +`15f00e3da5622f1c7155b02d1f9c00bd2416c282` with WHIR disabled, matching the +reference's direct input-bit verification mode. + +The experiment is isolated because the reference currently uses arkworks 0.5 +while Mirage uses 0.6. It is not production code and does not alter Mirage's +existing Keccak gadget or relation. + +Upstream Keccacheck is licensed Apache-2.0. The verifier formulas and Poseidon2 +transcript parameters ported here retain that provenance; see + and ePrint 2025/1764. + +Run the fast comparison with: + +```sh +nix develop -c cargo run --release --manifest-path \ + experiments/keccacheck-arkworks/Cargo.toml -- compare 1 2 8 +``` + +The comparison reports native proof construction, arkworks synthesis, +constraint satisfaction, and the direct bit-level Keccak control cost. Full +Groth16 setup/proving is deliberately excluded from this exploration because +constraint synthesis is the fast iteration gate. See [RESULTS.md](RESULTS.md) +for the measurements and integration assessment. + +## Protocol shape + +The native witness generator runs Keccacheck's GKR prover over a power-of-two +batch of Keccak-f permutations. The arkworks gadget verifies that proof *inside* +the surrounding R1CS and binds the claimed inputs and outputs. It is therefore +not a second proof checked alongside Groth16 and does not move Keccak checking +on-chain. The final deployment would still expose one ordinary Groth16 proof. + +The upstream gnark wrapper derives an output challenge using gnark's extended +Groth16 commitment API. Stock arkworks Groth16 has no equivalent API, so this +experiment derives that challenge in-circuit with the pinned Poseidon2 +transcript after absorbing every claimed output word. This is a protocol +adaptation and must receive cryptographic review before production use. diff --git a/experiments/keccacheck-arkworks/RESULTS.md b/experiments/keccacheck-arkworks/RESULTS.md new file mode 100644 index 0000000..88e0435 --- /dev/null +++ b/experiments/keccacheck-arkworks/RESULTS.md @@ -0,0 +1,102 @@ +# Arkworks Keccacheck exploration results + +Reference: Reilabs Keccacheck commit +[`15f00e3da5622f1c7155b02d1f9c00bd2416c282`](https://github.com/reilabs/keccacheck/tree/15f00e3da5622f1c7155b02d1f9c00bd2416c282), +with WHIR disabled. Measurements are from this branch's arkworks 0.5 R1CS port. +They use native proof generation followed by constraint synthesis and +`is_satisfied`; no Groth16 setup was run during the optimization loop. + +## Measured comparison + +The direct control is Mirage's Boolean Keccak-f construction. It costs 155,200 +constraints per independently allocated permutation: 1,600 input-bit +booleanity constraints and 153,600 permutation constraints. + +| permutations | GKR proof Fr elements | proof bytes | arkworks GKR constraints | direct constraints | direct / GKR | +|---:|---:|---:|---:|---:|---:| +| 1 | 6,255 | 200,160 | 987,628 | 155,200 | 0.157x | +| 2 | 6,809 | 217,888 | 1,090,792 | 310,400 | 0.285x | +| 4 | 7,363 | 235,616 | 1,194,930 | 620,800 | 0.520x | +| 8 | 7,917 | 253,344 | 1,308,423 | 1,241,600 | 0.949x | +| 16 | 8,471 | 271,072 | 1,440,626 | 2,483,200 | 1.724x | +| 32 | 9,025 | 288,800 | 1,610,249 | 4,966,400 | 3.084x | +| 64 | 9,579 | 306,528 | 1,854,712 | 9,932,800 | 5.355x | +| 128 | 10,133 | 324,256 | 2,248,855 | 19,865,600 | 8.834x | + +The crossover in this port is between 8 and 16 permutations. Keccacheck is a +regression for small isolated hashes and becomes compelling only when many +permutations share one GKR proof. + +At 64 permutations, the 1,854,712 constraints break down as follows: + +| component | constraints | +|---|---:| +| input Boolean allocation | 102,400 | +| output Fiat-Shamir binding | 88,800 | +| output word/bit reduction | 10,083 | +| 24 Keccak round reductions | 1,546,910 | +| final input binding | 106,519 | + +The upstream README reports 638,682 gnark constraints for one permutation, +791,597 for eight, and 1,379,176 for 128. This arkworks port is respectively +55%, 65%, and 63% larger. The port intentionally uses ordinary `FpVar` +operations with no custom compiler optimization pass, so closing that gap is a +separate optimization opportunity; the present numbers are the safe comparison +for Mirage's backend. + +## Projection for the universal circuit + +The universal depth-seven relation is 8,095,727 constraints. Its bounded +Keccak calls compile 38 Keccak-f permutations: + +- commitment: 2; +- statement: 3; +- header: 6; +- six MPT ancestors: 23; +- constructed leaf: 4. + +Those permutation cores cost `38 * 153,600 = 5,836,800` constraints. A fixed +64-way Keccacheck batch costs 1,854,712 in this standalone model. Replacing only +the permutation cores therefore gives the preliminary projection: + +```text +8,095,727 - 5,836,800 + 1,854,712 = 4,113,639 constraints +``` + +That is 3,982,088 fewer constraints, or 49.2% of the whole universal relation. +The standalone input-bit allocation is a reasonable placeholder for the output +bits that integration must expose: caller input bits can be reused, while GKR +outputs need Boolean variables for sponge chaining and digest extraction. The +exact integrated count may move by roughly this 102,400-constraint boundary and +must be measured on an integration branch. + +## Correctness checks + +- Poseidon2 permutation values are differential-tested against the pinned + native implementation. +- Direct arkworks Keccak is differential-tested against native `keccak::f1600` + and locks the 155,200-constraint control cost. +- A native Keccacheck proof satisfies the full 24-round arkworks verifier. +- Mutating either a proof element or an output word makes the R1CS + unsatisfied. +- All tests use the reference's corrected late-round Keccak constants. + +## Feasibility and remaining work + +This is promising for the universal circuit, but it is not yet drop-in code. + +1. Refactor the verifier to accept and return caller-owned Boolean state bits, + rather than allocating standalone `u64` witnesses. +2. Flatten every sponge invocation into one 64-way batch, including inactive + padding permutations, while preserving each sponge's chaining and + variable-length state selection. +3. Differential-test the integrated circuit against every existing relation + fixture and mutation test. +4. Audit the Poseidon-derived output challenge and transcript domain separation. +5. Investigate the roughly 60% arkworks overhead relative to gnark, principally + in the round verifier and transcript expression lowering. +6. Only after the integrated count is stable, run one full Groth16 setup/prove/ + verify benchmark and evaluate the larger witness-generation path. + +The GKR proof occupies about 307 KiB at 64 permutations, but it is private +Groth16 witness data, not calldata and not an additional on-chain proof. diff --git a/experiments/keccacheck-arkworks/src/direct.rs b/experiments/keccacheck-arkworks/src/direct.rs new file mode 100644 index 0000000..1a1ab4b --- /dev/null +++ b/experiments/keccacheck-arkworks/src/direct.rs @@ -0,0 +1,173 @@ +//! Direct bit-level R1CS Keccak control. +//! +//! This is the same Boolean construction used by Mirage: theta and chi use +//! ordinary Boolean XOR/AND constraints while rho and pi are wire permutations. + +use ark_ff::PrimeField; +use ark_r1cs_std::{alloc::AllocVar, boolean::Boolean}; +use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError}; + +pub type StateVar = [[Boolean; 64]; 25]; + +const RHO: [u32; 24] = [ + 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44, +]; + +const PI: [usize; 24] = [ + 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1, +]; + +const RC: [u64; 24] = [ + 0x0000000000000001, + 0x0000000000008082, + 0x800000000000808a, + 0x8000000080008000, + 0x000000000000808b, + 0x0000000080000001, + 0x8000000080008081, + 0x8000000000008009, + 0x000000000000008a, + 0x0000000000000088, + 0x0000000080008009, + 0x000000008000000a, + 0x000000008000808b, + 0x800000000000008b, + 0x8000000000008089, + 0x8000000000008003, + 0x8000000000008002, + 0x8000000000000080, + 0x000000000000800a, + 0x800000008000000a, + 0x8000000080008081, + 0x8000000000008080, + 0x0000000080000001, + 0x8000000080008008, +]; + +fn rotl(lane: &[Boolean; 64], n: u32) -> [Boolean; 64] { + let n = (n % 64) as usize; + core::array::from_fn(|i| lane[(i + 64 - n) % 64].clone()) +} + +fn xor_lane( + a: &[Boolean; 64], + b: &[Boolean; 64], +) -> Result<[Boolean; 64], SynthesisError> { + let mut out = Vec::with_capacity(64); + for i in 0..64 { + out.push(a[i].clone() ^ &b[i]); + } + out.try_into().map_err(|_| SynthesisError::Unsatisfiable) +} + +pub fn keccak_f1600(mut st: StateVar) -> Result, SynthesisError> { + for rc in RC { + let mut bc = Vec::with_capacity(5); + for i in 0..5 { + let mut acc = st[i].clone(); + for j in 1..5 { + acc = xor_lane(&acc, &st[i + 5 * j])?; + } + bc.push(acc); + } + + for i in 0..5 { + let t = xor_lane(&bc[(i + 4) % 5], &rotl(&bc[(i + 1) % 5], 1))?; + for j in 0..5 { + st[j * 5 + i] = xor_lane(&st[j * 5 + i], &t)?; + } + } + + let mut t = st[1].clone(); + for i in 0..24 { + let j = PI[i]; + let tmp = st[j].clone(); + st[j] = rotl(&t, RHO[i]); + t = tmp; + } + + for i in 0..5 { + let row: Vec<[Boolean; 64]> = (0..5).map(|j| st[i * 5 + j].clone()).collect(); + for j in 0..5 { + let not_next: [Boolean; 64] = + core::array::from_fn(|b| !row[(j + 1) % 5][b].clone()); + let mut anded = Vec::with_capacity(64); + for b in 0..64 { + anded.push(not_next[b].clone() & &row[(j + 2) % 5][b]); + } + let anded: [Boolean; 64] = anded + .try_into() + .map_err(|_| SynthesisError::Unsatisfiable)?; + st[i * 5 + j] = xor_lane(&row[j], &anded)?; + } + } + + for (b, bit) in st[0].iter_mut().enumerate() { + if (rc >> b) & 1 == 1 { + *bit = !bit.clone(); + } + } + } + Ok(st) +} + +pub fn synthesize_batch( + cs: ConstraintSystemRef, + inputs: &[[u64; 25]], +) -> Result<(), SynthesisError> { + for input in inputs { + let mut lanes = Vec::with_capacity(25); + for word in input { + let mut bits = Vec::with_capacity(64); + for bit in 0..64 { + bits.push(Boolean::new_witness(cs.clone(), || { + Ok((word >> bit) & 1 == 1) + })?); + } + lanes.push(bits.try_into().map_err(|_| SynthesisError::Unsatisfiable)?); + } + let state: StateVar = lanes + .try_into() + .map_err(|_| SynthesisError::Unsatisfiable)?; + let _ = keccak_f1600(state)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_bn254::Fr; + use ark_r1cs_std::R1CSVar; + use ark_relations::r1cs::ConstraintSystem; + + #[test] + fn direct_control_matches_mirage_cost() { + let cs = ConstraintSystem::::new_ref(); + synthesize_batch(cs.clone(), &[[0u64; 25]]).unwrap(); + assert!(cs.is_satisfied().unwrap()); + assert_eq!(cs.num_constraints(), 155_200); + } + + #[test] + fn direct_control_matches_native_keccak() { + let cs = ConstraintSystem::::new_ref(); + let mut expected: [u64; 25] = core::array::from_fn(|i| i as u64); + let state: StateVar = core::array::from_fn(|lane| { + core::array::from_fn(|bit| { + Boolean::new_witness(cs.clone(), || Ok((expected[lane] >> bit) & 1 == 1)).unwrap() + }) + }); + keccak::f1600(&mut expected); + let output = keccak_f1600(state).unwrap(); + for lane in 0..25 { + for (bit, output_bit) in output[lane].iter().enumerate() { + assert_eq!( + output_bit.value().unwrap(), + (expected[lane] >> bit) & 1 == 1 + ); + } + } + assert!(cs.is_satisfied().unwrap()); + } +} diff --git a/experiments/keccacheck-arkworks/src/lib.rs b/experiments/keccacheck-arkworks/src/lib.rs new file mode 100644 index 0000000..c13c41a --- /dev/null +++ b/experiments/keccacheck-arkworks/src/lib.rs @@ -0,0 +1,10 @@ +//! Experimental arkworks R1CS verifier for Keccacheck. +//! +//! The native GKR prover is used unchanged from Reilabs commit `15f00e3`. +//! This crate ports only the verifier that would replace Mirage's direct +//! Keccak-f constraints. + +pub mod direct; +pub mod poseidon2; +mod poseidon2_constants; +pub mod verifier; diff --git a/experiments/keccacheck-arkworks/src/main.rs b/experiments/keccacheck-arkworks/src/main.rs new file mode 100644 index 0000000..0886a60 --- /dev/null +++ b/experiments/keccacheck-arkworks/src/main.rs @@ -0,0 +1,82 @@ +use ark_bn254::Fr; +use ark_relations::r1cs::ConstraintSystem; +use mirage_keccacheck_arkworks::verifier::{make_witness, verify_witness_profile}; +use std::{env, process::ExitCode, time::Instant}; + +const DIRECT_CONSTRAINTS_PER_PERMUTATION: usize = 155_200; + +fn usage() { + eprintln!("usage: mirage-keccacheck-arkworks compare [power-of-two instances ...]"); +} + +fn compare(instances: usize) -> Result<(), String> { + if !instances.is_power_of_two() { + return Err(format!("instance count {instances} is not a power of two")); + } + + let started = Instant::now(); + let witness = make_witness(instances); + let prove_ms = started.elapsed().as_millis(); + + let cs = ConstraintSystem::::new_ref(); + let started = Instant::now(); + let profile = + verify_witness_profile(cs.clone(), &witness).map_err(|error| error.to_string())?; + let synth_ms = started.elapsed().as_millis(); + let started = Instant::now(); + let satisfied = cs.is_satisfied().map_err(|error| error.to_string())?; + let check_ms = started.elapsed().as_millis(); + if !satisfied { + return Err(format!( + "valid {instances}-instance proof was not satisfied" + )); + } + + let gkr_constraints = cs.num_constraints(); + let direct_constraints = DIRECT_CONSTRAINTS_PER_PERMUTATION * instances; + println!( + "{instances},{},{},{gkr_constraints},{direct_constraints},{:.3},{},{},{},{},{},{prove_ms},{synth_ms},{check_ms}", + witness.proof.len(), + witness.proof.len() * 32, + direct_constraints as f64 / gkr_constraints as f64, + profile.allocation, + profile.output_binding, + profile.output_reduction, + profile.rounds, + profile.input_binding, + ); + Ok(()) +} + +fn run() -> Result<(), String> { + let mut args = env::args().skip(1); + if args.next().as_deref() != Some("compare") { + usage(); + return Err("missing compare command".to_owned()); + } + let instances = args + .map(|arg| arg.parse::().map_err(|error| error.to_string())) + .collect::, _>>()?; + let instances = if instances.is_empty() { + vec![1, 2, 8] + } else { + instances + }; + println!( + "instances,proof_elements,proof_bytes,gkr_constraints,direct_constraints,direct_over_gkr,allocation_constraints,output_binding_constraints,output_reduction_constraints,round_constraints,input_binding_constraints,native_prove_ms,synthesize_ms,check_ms" + ); + for count in instances { + compare(count)?; + } + Ok(()) +} + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("error: {error}"); + ExitCode::FAILURE + } + } +} diff --git a/experiments/keccacheck-arkworks/src/poseidon2.rs b/experiments/keccacheck-arkworks/src/poseidon2.rs new file mode 100644 index 0000000..5a0b6eb --- /dev/null +++ b/experiments/keccacheck-arkworks/src/poseidon2.rs @@ -0,0 +1,162 @@ +//! Width-16 Poseidon2 transcript gadget matching Keccacheck commit `15f00e3`. + +use crate::poseidon2_constants::RC16; +use ark_bn254::Fr; +use ark_ff::MontFp; +use ark_r1cs_std::fields::fp::FpVar; + +pub const RATE: usize = 10; +const WIDTH: usize = 16; + +pub const INITIAL_STATE: [Fr; WIDTH] = [ + MontFp!("314159265358979323846264338327950288419716939937510582097494"), + MontFp!("45923078164062862089986280348253421170679821480865132823066470"), + MontFp!("93844609550582231725359408128481117450284102701938521105559644"), + MontFp!("62294895493038196442881097566593344612847564823378678316527120"), + MontFp!("19091456485669234603486104543266482133936072602491412737245870"), + MontFp!("06606315588174881520920962829254091715364367892590360011330530"), + MontFp!("54882046652138414695194151160943305727036575959195309218611738"), + MontFp!("19326117931051185480744623799627495673518857527248912279381830"), + MontFp!("11949129833673362440656643086021394946395224737190702179860943"), + MontFp!("70277053921717629317675238467481846766940513200056812714526356"), + MontFp!("08277857713427577896091736371787214684409012249534301465495853"), + MontFp!("71050792279689258923542019956112129021960864034418159813629774"), + MontFp!("77130996051870721134999999837297804995105973173281609631859502"), + MontFp!("44594553469083026425223082533446850352619311881710100031378387"), + MontFp!("52886587533208381420617177669147303598253490428755468731159562"), + MontFp!("86388235378759375195778185778053217122680661300192787661119590"), +]; + +fn sbox(x: &FpVar) -> FpVar { + let x2 = x * x; + let x4 = &x2 * &x2; + x4 * x +} + +fn mat_full_4(state: &mut [FpVar]) { + let t0 = &state[0] + &state[1]; + let t1 = &state[2] + &state[3]; + let t2 = &state[1] + &state[1] + &t1; + let t3 = &state[3] + &state[3] + &t0; + let t4 = &t1 + &t1 + &t1 + &t1 + &t3; + let t5 = &t0 + &t0 + &t0 + &t0 + &t2; + let t6 = &t3 + &t5; + let t7 = &t2 + &t4; + state.clone_from_slice(&[t6, t5, t7, t4]); +} + +fn mat_full_16(state: &mut [FpVar; WIDTH]) { + let mut sum: [FpVar; 4] = core::array::from_fn(|_| FpVar::Constant(Fr::from(0u64))); + for chunk in state.chunks_exact_mut(4) { + mat_full_4(chunk); + for j in 0..4 { + sum[j] += &chunk[j]; + } + } + for chunk in state.chunks_exact_mut(4) { + for j in 0..4 { + chunk[j] += &sum[j]; + } + } +} + +fn mat_partial_16(state: &mut [FpVar; WIDTH]) { + let sum = state + .iter() + .cloned() + .fold(FpVar::Constant(Fr::from(0u64)), |acc, x| acc + x); + const DIAG: [u64; WIDTH] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 16, 17]; + for i in 0..WIDTH { + state[i] = &state[i] * Fr::from(DIAG[i]) + ∑ + } +} + +pub fn permute_16(state: &mut [FpVar; WIDTH]) { + mat_full_16(state); + for rc in RC16.0 { + for i in 0..WIDTH { + state[i] += rc[i]; + state[i] = sbox(&state[i]); + } + mat_full_16(state); + } + for rc in RC16.1 { + state[0] += rc; + state[0] = sbox(&state[0]); + mat_partial_16(state); + } + for rc in RC16.2 { + for i in 0..WIDTH { + state[i] += rc[i]; + state[i] = sbox(&state[i]); + } + mat_full_16(state); + } +} + +#[derive(Clone)] +pub struct SpongeVar { + state: [FpVar; WIDTH], + idx: usize, + dirty: bool, +} + +impl SpongeVar { + pub fn new() -> Self { + Self { + state: INITIAL_STATE.map(FpVar::Constant), + idx: 0, + dirty: true, + } + } + + pub fn absorb(&mut self, value: &FpVar) { + if self.idx < RATE { + self.state[self.idx] += value; + self.idx += 1; + } else { + permute_16(&mut self.state); + self.state[0] += value; + self.idx = 1; + } + self.dirty = true; + } + + pub fn squeeze(&mut self) -> FpVar { + if self.dirty || self.idx >= RATE { + permute_16(&mut self.state); + self.idx = 0; + self.dirty = false; + } + let out = self.state[self.idx].clone(); + self.idx += 1; + out + } +} + +impl Default for SpongeVar { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_r1cs_std::{R1CSVar, alloc::AllocVar}; + use ark_relations::r1cs::ConstraintSystem; + + #[test] + fn permutation_matches_upstream_native() { + let cs = ConstraintSystem::::new_ref(); + let input: [Fr; 16] = core::array::from_fn(|i| Fr::from(i as u64)); + let mut expected = input; + gkr::poseidon::permute_16(&mut expected); + let mut state: [FpVar; 16] = + core::array::from_fn(|i| FpVar::new_witness(cs.clone(), || Ok(input[i])).unwrap()); + permute_16(&mut state); + let got: Vec = state.iter().map(|x| x.value().unwrap()).collect(); + assert_eq!(got, expected); + assert!(cs.is_satisfied().unwrap()); + } +} diff --git a/experiments/keccacheck-arkworks/src/poseidon2_constants.rs b/experiments/keccacheck-arkworks/src/poseidon2_constants.rs new file mode 100644 index 0000000..48cea9a --- /dev/null +++ b/experiments/keccacheck-arkworks/src/poseidon2_constants.rs @@ -0,0 +1,354 @@ +// Ported from Reilabs/keccacheck commit 15f00e3, Apache-2.0. +// Originally generated from HorizenLabs/poseidon2 BN256 parameters. +use ark_bn254::Fr; +use ark_ff::MontFp; + +pub static RC16: ([[Fr; 16]; 4], [Fr; 57], [[Fr; 16]; 4]) = ( + [ + [ + MontFp!("7987508670305577132467175719839098676114873458512853854612810620998666595583"), + MontFp!("2789787787788692092835830565661406728726297908279586884556390502260801752643"), + MontFp!("2923085958268023927518067610501534000679804083365451744377158124878282576025"), + MontFp!("4136897588693623681614261973792194839081753316827752013355333397406268139780"), + MontFp!( + "13481757729937031981267616300485677282763428226259483639104644219055114857610" + ), + MontFp!("4549712975212827362836681120412415081147952438701098901238795063645041765827"), + MontFp!( + "19323176998751969108905402456091598168231652031407617505638005194731985531809" + ), + MontFp!("6406539181147875582313956743397651288040059510190563896011413357029541481331"), + MontFp!( + "15243734910010515309988343061534882675085318947037100669003270565128119155410" + ), + MontFp!("6388136752421810075373716462240882592495422546329348514548788721980652241190"), + MontFp!( + "15011693089484106333908735231458665842898768850629770618083591692823296397418" + ), + MontFp!( + "11573961130835252474134142707558401302450719556440598834241929878272009168922" + ), + MontFp!( + "19407328810644338405687201905285041369722438092537480512342756077136358932018" + ), + MontFp!( + "21430969851023225465341423232454445521443493598561439390118567123649599289990" + ), + MontFp!( + "17193706251743551030683388818560678852389994042303420464797006277508144868714" + ), + MontFp!("3791389208205509792081160535750038379805378554116913395600290273440345828801"), + ], + [ + MontFp!("4443674022116082358924119737152423343543828046835293367105977299369313051402"), + MontFp!( + "20556007757692803339827754697137127496495384580976799643773337453486500345582" + ), + MontFp!( + "21732614309896215525770849543758552311770742754064665928678206230967824841788" + ), + MontFp!("2350394113400461715410541165020187676490904100545319432739327347084889078879"), + MontFp!( + "19775936974090295685601178438242036004295778610224530197438576921136701664389" + ), + MontFp!("1725376439060272492390615929908985193366172570313768162872577650731402232757"), + MontFp!( + "12255515761389684964195750005688015602250339153684484138116108547484432798851" + ), + MontFp!("3510498058011570022390323631394973426748397464109728409897284676359435249321"), + MontFp!( + "17416184599740753939934645848798651978876453145155036284211391780977918367579" + ), + MontFp!( + "17590806640629642315191745876646662541138768460798306415762298545806324501600" + ), + MontFp!("9126984626176303392851410234353741886438699847036393256153057857512200197211"), + MontFp!("7816717136399410148891198230719597376774716829530786579057127695430583454655"), + MontFp!("9356587658664432900999201095599992383032248997575871565753557852426605440413"), + MontFp!("3613118892154837104061140735743996391126463221572779017302631598167534538587"), + MontFp!( + "15312641583002364503616465240500469768167116409579865529609815461858872106607" + ), + MontFp!( + "20895281281030313702072042074060167627684590415649329700200364234420653948223" + ), + ], + [ + MontFp!("5137463410503668412705556578968301760708802365793381795577596837508895587974"), + MontFp!("2992783576564647231225506926232193550692501617041554226743522120885841387288"), + MontFp!( + "14720088594609875079595433704692718753566732357332013457611025775312394181948" + ), + MontFp!("8768144036608441921566501796338809165738698892354098807810091005871730975052"), + MontFp!("7532991134485300087254721801054399089197214400547286818586737795748985756136"), + MontFp!("3792901996819634685401178811381934330083161130574204908308391729693370429116"), + MontFp!( + "15935101110199908700215275768883255043945244840238297847431023548570202816588" + ), + MontFp!( + "19393642961767592426452532568396502989981014395147778872221390448675609171346" + ), + MontFp!("155918949363761233353288426181480562951420403007714564609379470458362418360"), + MontFp!("8542612983080903416798197308326653235584238440638486502402108452663527109386"), + MontFp!("3102078100956228176110489205020115250719306552636033822543101833673231973361"), + MontFp!( + "10997874161021911675594999155670135314002657381856718081615532885981471075751" + ), + MontFp!("5625265727695002995728469200863087634322980325285271879057120517352284218721"), + MontFp!("1868598188897437704195089876316298344255918248761606779366147769224503638354"), + MontFp!( + "20559221099104651466845775367092516774981735754372572904406935920494116000577" + ), + MontFp!( + "18244597479912127451043989744623814361014933779254004993799631541123080589434" + ), + ], + [ + MontFp!( + "18198648546362166439166930003556212265878411671611964855634217505426135463642" + ), + MontFp!( + "10356043958022108717942589723822419638579802025381703267680794514671539448413" + ), + MontFp!( + "13462076557842678595809262539855912349193288208056721394689145675513594475608" + ), + MontFp!( + "11384754856824723950667845324670478860096509933183112521740195554878825089822" + ), + MontFp!( + "11846199089561237014635000209735309930768341499968217281358420792832604390328" + ), + MontFp!( + "14756810345512093457111979243567081369178730838502550598767324114642318412028" + ), + MontFp!("1165595406641358948440089116770331694759228710449216719254551181578852444634"), + MontFp!( + "20666835367900319417421572973401937187766999145362063796299481474822091896839" + ), + MontFp!( + "12990061010481109646624139476687927621447917816835360909851944807656553760572" + ), + MontFp!("1783116977987781742463841851758577081073383877973038317820752019796562465302"), + MontFp!("8903940416606150176329049763389212458551439722921621550960793657396018455541"), + MontFp!("7818691246611756097003750504136679795785695725892097643498661262459955136804"), + MontFp!("4882277172763670736261863083249473517190733364755948887880727165161561106826"), + MontFp!("9546021855862660306521063506063099579472876630386444749970743211912624609092"), + MontFp!( + "16884909448813178978130991149821810809300452856451925597438640784766121620580" + ), + MontFp!("4432065177462568548089478599231774157969827260421894502967549624495636336960"), + ], + ], + [ + MontFp!("6815126499856609672222254042135780832357912225575034785912608291432260232898"), + MontFp!("19646638830255621667048617952591606101396134625966867452105978140921616739655"), + MontFp!("11302138239612418360180855820394166113153931161226392355253979303164992468696"), + MontFp!("8902180098716288109045797508667606993836580272659627608764644610681706696552"), + MontFp!("15024248372289072696331123537928635082008690205771322614522410218457671669030"), + MontFp!("9108466869828573129651669104555335894770021048312797648102016083513498189708"), + MontFp!("5593581617985601126480748728563223791129944024411661362725580196781911695155"), + MontFp!("17431191399111931959268470356880027957220257813539474017925853546766139947893"), + MontFp!("20056694111825808624858160513735077869168456469163075458067235173482415291365"), + MontFp!("12425741074116631847070073667050652108769825328521477531880334996410762798746"), + MontFp!("8955408976800781140561678077373743838002095630499168236895969637952385171003"), + MontFp!("16662900256793530901152466262552794342547681785570027585388969103311394050068"), + MontFp!("15534164228080370012679725691771388077179275625252514968160336771975181843179"), + MontFp!("9363965140782610052578675294485873070433012080344413495407814264639339184892"), + MontFp!("19323319623697285883311426120970144662636352560337139024696211699935323462843"), + MontFp!("19667520618631568063264954914272864405753811574830113293225984150020916441476"), + MontFp!("15782940336500567106839930973880972342821561605750106087667365073898555788045"), + MontFp!("5160923045939029364513911716806710141262457627449653152435264456021279783023"), + MontFp!("10043139883103967293969307566861487191986860139967140695758533322158789704934"), + MontFp!("9993445169513036925291543630609937171163102986151833918628389141526688082060"), + MontFp!("6582884302334998268745699301765552962157195564283098789965526726552616923981"), + MontFp!("8305041229363478171256261139992283753297590760909273490788620715914389211529"), + MontFp!("7079796897596439072858593128409359911268318613394891418800636910413207278585"), + MontFp!("20678635817698043899626321797240587099874320926950451316190641720259265816441"), + MontFp!("14894753067584981454975694161439288445040723553115504042795053427766005842897"), + MontFp!("16460106341643514138189486974101781739866313417094020885985622623293974674192"), + MontFp!("11239237884257511514154110959163936194004449833910018125975354050164196118126"), + MontFp!("3123641689295544333004782541102957732852154140928731747113401366319710400061"), + MontFp!("16451488751543818933205167779631131791174557117152667491386061673610076525602"), + MontFp!("15931468796949795021075512772761791067340694123789545949980516951699751528241"), + MontFp!("1066577891854656847806919264940037580194504112770946710163536535894158923970"), + MontFp!("15595202527205548564243068207186579625413834115497641737606549613925017303248"), + MontFp!("3644290738195458277775191003855366932943208997370146040039121556214152130509"), + MontFp!("18314413067954647895689599701967816867934254241849175305689696351121800065506"), + MontFp!("5879380050156536162954242728743382119442317829662395623582267425305171763846"), + MontFp!("15881728806833779669142923432009047220075586328068810300670424799337668770015"), + MontFp!("112867594202583638301419177992010799843740675324183999356030947780085784843"), + MontFp!("8803331613264154400592631625538219536471149451207752597135044894573888781430"), + MontFp!("11738836600183962573940017458875930177485668909144396985192921089029743853920"), + MontFp!("19513172302020035623140909201016474298886363379992337073395143009330447744476"), + MontFp!("28068217483705394910315625084026354256424731655830382177919239861876103676"), + MontFp!("17947924735718282282337271927131035663057758605166870825867480796443981188745"), + MontFp!("9682873619339968299771516390700909696215007477689106778005010864103430988188"), + MontFp!("14934049656087985335393986301360927724481032122405901654656994092735611149786"), + MontFp!("450929916328870735102789275352399099901601504938095618223402639964680612624"), + MontFp!("8440163230602863997243958203195728474722920060951188580301844847673586095325"), + MontFp!("1930288126134614873378707816837667742844508187465616914161544215337647022335"), + MontFp!("15268141562824701150734622447786145131756742795495381280691829367288304516432"), + MontFp!("16942655511827247804632190687377518819617097881981535231389546091106308464233"), + MontFp!("4051392020423020121600324415237789574761059434547630352009196511936590214670"), + MontFp!("2583368247209608786367878957201317579599589557403714213419916875979008228180"), + MontFp!("2307366759343760238637553141164822296713858712864630022457473707021014682968"), + MontFp!("9628658505673033321937661675733619665817623960523368974782019509550325833346"), + MontFp!("2758257045058883328030628060582738490658948885480260653173014055397346274669"), + MontFp!("19105642330203703383081851860313150499920727669364908317985743236889987904091"), + MontFp!("2183122284249808311901286975903268266793628005635232283478272435841378141616"), + MontFp!("3723240487756852394377887331009098934500152744315121084282842578293413534502"), + ], + [ + [ + MontFp!( + "12798061852051494731939934571056882910112265953823605836237980041467007152856" + ), + MontFp!( + "14568325302050461741224170340184626483064917163410283367151830334318738249201" + ), + MontFp!( + "18276062790992197117520915640515497669875613512696035253614217546304637470021" + ), + MontFp!( + "20627460470815095235503561768532491088598154093806046061909949003725526571895" + ), + MontFp!( + "17245950571819753931533619001387650713165686747650814547134947309815298664483" + ), + MontFp!( + "11121556865844987632385224735371919379477576593206665792475389674170961534877" + ), + MontFp!("6245885212826865991432068547352935466370043397897885095862800217284554071424"), + MontFp!( + "14690855571967674705428311747416120698942846798420160396535112558027620183765" + ), + MontFp!("3235658783487238943593310349286355309113259814475596134348995210642028885643"), + MontFp!( + "20722254815730848854390862523298553268850029431838546301249799038348379700017" + ), + MontFp!( + "19642126089816196888361263588060661717723867255464321287022646144931390112284" + ), + MontFp!("8632072582309787677666221011033250027767655916164228152099011508045264115628"), + MontFp!( + "20043123735240162399387095494523656672619946732753439734143341922855067252668" + ), + MontFp!( + "11904583185911751509579710797281908145324957152597916871831617558146963369684" + ), + MontFp!( + "15425351929938470853193718127538286221363322147987668566416155015352849606487" + ), + MontFp!("7836679868165107790270453843508581901599186549445113382492611620451382004534"), + ], + [ + MontFp!("1400391591069146396388357308515920509261560123691496238504102856344666720158"), + MontFp!( + "14174858927021982333120256612552461500485120312339832053819158083211342214554" + ), + MontFp!( + "13932623367767696127644734712237196216797254927711341121444975790316174808543" + ), + MontFp!("1347625721745170599764025031547760372037468905693488526890308844799397223599"), + MontFp!( + "13405042718806919655454735399476138028224524636798057373290706002745159243492" + ), + MontFp!( + "13968798170414332138515357483205257457669805199389971029738637173834063240471" + ), + MontFp!( + "12880063112097200900343214738680204426539712096784765965633204714598974269900" + ), + MontFp!("1616907144150909322713379091213954152554304275469379126099951880593629465997"), + MontFp!("1304127795518325161691119438734502813585937787665151293717948276546158364899"), + MontFp!( + "10519101650579155624089241867464558732964322746696440671816554398639492010283" + ), + MontFp!( + "18828931459860199852717606888127153117321647594659992043075338883583443168532" + ), + MontFp!("2295869962934928531712533108809705584068393247061194775379130284834010646602"), + MontFp!( + "18150621187628277200476269779210788234711835351945125900538777078435916482876" + ), + MontFp!( + "14640835937562336386952719851409386401381343241582808213350078068859999364972" + ), + MontFp!( + "13897434461692657913682776955410351669769404536338213932873325060903666618850" + ), + MontFp!( + "20597831106970808887041371297726673787653852732760233683240573303573794622220" + ), + ], + [ + MontFp!( + "19778398643313208036144870697848233932488866547046796230853339000492658038515" + ), + MontFp!("6490771814639427939657087738362748430177047945561649728963763165932343827645"), + MontFp!( + "13006668608365365308391148447358562118183380975503495332476244695621883627943" + ), + MontFp!("2376633666069824802975429113636416861869648772191341321978213585368459504946"), + MontFp!( + "14026179117201516492847190067273767138692835223271547388459123109718263661737" + ), + MontFp!("1558342329810575234249139477022599561470462181488370537976139917078553051256"), + MontFp!( + "14134266516506569479923030844790504067461899926138690452282393042351639752970" + ), + MontFp!( + "14210241073253042293952413798925100594617964338995262636477200830442017966589" + ), + MontFp!("5307668150181429262219430832958965963829724801921042007172170952001831974281"), + MontFp!( + "21453805279253231447711595651829748575193474578778441511169986554818617878108" + ), + MontFp!("7651996536678626418407600708073875790655905425227927821193265453381907815315"), + MontFp!("6847056380992888470717155300697277311257577629811318780799101203119050536885"), + MontFp!("8070339622120719424098411455163926684249724389012164888625727422216270815130"), + MontFp!("7205797075464323398573529291457145214072527328852424058232457289443035067442"), + MontFp!("4536189390770865756295851679323920555154397086063070003221280725313014220755"), + MontFp!( + "12868369594844424189974419334382583438474381206841382987726155167536734592505" + ), + ], + [ + MontFp!( + "11048642748974047225921811671756048438211802032845752026884537530907616453545" + ), + MontFp!("8512354908309061211733136180112768331784856936839249322262003771206917210899"), + MontFp!("9990797211482285791722506260638436977981204610385607689787591992921347349469"), + MontFp!( + "16917295660967180721362182776927486975161088518245147837387780258581634757297" + ), + MontFp!("9242678265077512551509868219912023157072368469592679399436785051623163092186"), + MontFp!( + "19374685276756598833312230288044544032925343679560847095932969931707155093482" + ), + MontFp!( + "21622567804515952265338511322387034516709116685689329667963362810804675904423" + ), + MontFp!( + "20635613322803017955230070354434498414231167117592436903959515733915710373994" + ), + MontFp!( + "12671162889020898856553715587109211682953311928918906931363397665130293702147" + ), + MontFp!( + "10831969496148798054134508249403502812489111994043367592193394348094618993154" + ), + MontFp!( + "11503512535039965163110471823710585207078679112424225764668901657520881406982" + ), + MontFp!("7510826680649704378408809285203616429460164251112831558949560497309441632406"), + MontFp!("9293593444621128830576184699951613976294160517788216200952332436763107636092"), + MontFp!("4589945008036274623436145388285284315086203451631952327982396273524682595904"), + MontFp!( + "16498543997546758928033844742180268058074271522298520395130043287308153701670" + ), + MontFp!("7832487555493762303358544193348956815233686901841649713063698970403681802113"), + ], + ], +); diff --git a/experiments/keccacheck-arkworks/src/verifier.rs b/experiments/keccacheck-arkworks/src/verifier.rs new file mode 100644 index 0000000..94a19b5 --- /dev/null +++ b/experiments/keccacheck-arkworks/src/verifier.rs @@ -0,0 +1,607 @@ +//! Keccacheck GKR verifier gadget. +//! +//! Ported from the upstream native and gnark verifiers at commit `15f00e3`. + +use crate::poseidon2::SpongeVar; +use ark_bn254::Fr; +use ark_ff::{MontFp, One, Zero}; +use ark_r1cs_std::{alloc::AllocVar, boolean::Boolean, eq::EqGadget, fields::fp::FpVar}; +use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError}; + +const HALF: Fr = + MontFp!("10944121435919637611123202872628637544274182200208017171849102093287904247809"); + +const ROUND_CONSTANTS: [u64; 24] = [ + 0x0000000000000001, + 0x0000000000008082, + 0x800000000000808a, + 0x8000000080008000, + 0x000000000000808b, + 0x0000000080000001, + 0x8000000080008081, + 0x8000000000008009, + 0x000000000000008a, + 0x0000000000000088, + 0x0000000080008009, + 0x000000008000000a, + 0x000000008000808b, + 0x800000000000008b, + 0x8000000000008089, + 0x8000000000008003, + 0x8000000000008002, + 0x8000000000000080, + 0x000000000000800a, + 0x800000008000000a, + 0x8000000080008081, + 0x8000000000008080, + 0x0000000080000001, + 0x8000000080008008, +]; + +const RHO_OFFSETS: [usize; 25] = [ + 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14, +]; + +const PI: [usize; 24] = [ + 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1, +]; + +type RoundClaims = (Vec>, Vec>); + +struct TranscriptVar { + sponge: SpongeVar, + proof: Vec>, + index: usize, +} + +impl TranscriptVar { + fn new(proof: Vec>) -> Self { + Self { + sponge: SpongeVar::new(), + proof, + index: 0, + } + } + + fn absorb(&mut self, value: &FpVar) { + self.sponge.absorb(value); + } + + fn generate(&mut self) -> FpVar { + self.sponge.squeeze() + } + + fn read(&mut self) -> Result, SynthesisError> { + let value = self + .proof + .get(self.index) + .cloned() + .ok_or(SynthesisError::Unsatisfiable)?; + self.index += 1; + self.sponge.absorb(&value); + Ok(value) + } + + fn finish(self) -> Result<(), SynthesisError> { + if self.index == self.proof.len() { + Ok(()) + } else { + Err(SynthesisError::Unsatisfiable) + } + } +} + +fn xor(a: &FpVar, b: &FpVar) -> FpVar { + let ab = a * b; + a + b - &ab - &ab +} + +fn enforce_named(_label: &str, left: &FpVar, right: &FpVar) -> Result<(), SynthesisError> { + left.enforce_equal(right) +} + +fn eval_eq(r: &[FpVar]) -> Vec> { + if r.is_empty() { + return vec![FpVar::Constant(Fr::one())]; + } + let mut out = vec![FpVar::Constant(Fr::one()) - &r[0], r[0].clone()]; + for ri in &r[1..] { + let one_minus = FpVar::Constant(Fr::one()) - ri; + let mut next = Vec::with_capacity(out.len() * 2); + for value in out { + let lo = &value * &one_minus; + let hi = value - &lo; + next.push(lo); + next.push(hi); + } + out = next; + } + out +} + +fn eval_mle_with_eq(mle: &[FpVar], eq: &[FpVar]) -> FpVar { + assert_eq!(mle.len(), eq.len()); + mle.iter() + .zip(eq) + .fold(FpVar::Constant(Fr::zero()), |acc, (a, b)| acc + a * b) +} + +fn eval_mle(mle: &[FpVar], r: &[FpVar]) -> FpVar { + assert_eq!(mle.len(), 1usize << r.len()); + let mut coeffs = mle.to_vec(); + for ri in r { + let half = coeffs.len() / 2; + coeffs = (0..half) + .map(|j| &coeffs[j] + ri * (&coeffs[half + j] - &coeffs[j])) + .collect(); + } + coeffs[0].clone() +} + +fn eq(a: &[FpVar], b: &[FpVar]) -> FpVar { + assert_eq!(a.len(), b.len()); + a.iter() + .zip(b) + .fold(FpVar::Constant(Fr::one()), |acc, (x, y)| { + let xy = x * y; + let term = &xy + &xy + FpVar::Constant(Fr::one()) - x - y; + acc * term + }) +} + +fn prefix_eq(a: &[FpVar], b: &[FpVar], prefix: usize) -> FpVar { + eq(&a[..prefix], &b[..prefix]) +} + +fn rot_from_eq( + lane: usize, + eq_a_suffix: &[FpVar], + eq_b_suffix: &[FpVar], + prefix: &FpVar, +) -> FpVar { + let mut rotated = vec![FpVar::Constant(Fr::zero()); eq_a_suffix.len()]; + let instances = eq_a_suffix.len() / 64; + for instance in 0..instances { + for bit in 0..64 { + rotated[instance * 64 + bit] = + eq_a_suffix[instance * 64 + (bit + RHO_OFFSETS[lane]) % 64].clone(); + } + } + prefix * eval_mle_with_eq(&rotated, eq_b_suffix) +} + +fn verify_sumcheck( + transcript: &mut TranscriptVar, + num_vars: usize, + mut claim: FpVar, +) -> Result<(FpVar, Vec>), SynthesisError> { + let mut challenges = Vec::with_capacity(num_vars); + for _ in 0..num_vars { + let mut p = Vec::with_capacity(DEGREE); + for _ in 0..DEGREE { + p.push(transcript.read()?); + } + let sum = p + .iter() + .cloned() + .fold(FpVar::Constant(Fr::zero()), |acc, x| acc + x); + let p0 = (claim - sum) * HALF; + let r = transcript.generate(); + challenges.push(r.clone()); + let mut acc = p[DEGREE - 1].clone(); + for j in (0..DEGREE - 1).rev() { + acc = &p[j] + &r * acc; + } + claim = p0 + r * acc; + } + Ok((claim, challenges)) +} + +fn add_col(j: usize, add: usize) -> usize { + let col = j % 5; + let row = j - col; + (col + add) % 5 + row +} + +fn strip_pi(pi: &[FpVar]) -> Vec> { + let mut rho = pi.to_vec(); + let mut last = 1usize; + for target in PI { + rho[last] = pi[target].clone(); + last = target; + } + rho +} + +fn verify_round( + transcript: &mut TranscriptVar, + num_vars: usize, + alpha: &[FpVar], + beta: &mut [FpVar], + sum: FpVar, + rc: u64, + round: usize, +) -> Result { + let (ve, vrs_iota) = verify_sumcheck::<3>(transcript, num_vars, sum)?; + let chi_00 = transcript.read()?; + let chi_rlc = transcript.read()?; + let e_eq = eq(alpha, &vrs_iota); + let rc_bits = (0..64) + .map(|bit| FpVar::Constant(Fr::from((rc >> bit) & 1))) + .collect::>(); + let e_rc = eval_mle(&rc_bits, &vrs_iota[num_vars - 6..]); + let expected = e_eq * (&beta[0] * xor(&chi_00, &e_rc) + &chi_rlc); + enforce_named(&format!("round {round}: iota"), &expected, &ve)?; + + let x = transcript.generate(); + let y = transcript.generate(); + beta[0] *= &x; + for value in &mut beta[1..] { + *value *= &y; + } + let expected_sum = &beta[0] * &chi_00 + &y * &chi_rlc; + + let (ve, vrs_chi) = verify_sumcheck::<4>(transcript, num_vars, expected_sum)?; + let mut pi = Vec::with_capacity(25); + for _ in 0..25 { + pi.push(transcript.read()?); + } + let e_eq = eq(&vrs_iota, &vrs_chi); + let mut checksum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + let chi = xor( + &pi[i], + &((FpVar::Constant(Fr::one()) - &pi[add_col(i, 1)]) * &pi[add_col(i, 2)]), + ); + checksum += &e_eq * &beta[i] * chi; + } + enforce_named(&format!("round {round}: chi"), &checksum, &ve)?; + + let rho = strip_pi(&pi); + let mut expected_sum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + beta[i] = transcript.generate(); + expected_sum += &beta[i] * &rho[i]; + } + let (ve, vrs_rho) = verify_sumcheck::<2>(transcript, num_vars, expected_sum)?; + let mut theta = Vec::with_capacity(25); + for _ in 0..25 { + theta.push(transcript.read()?); + } + let prefix = num_vars - 6; + let eq_chi_suffix = eval_eq(&vrs_chi[prefix..]); + let eq_rho_suffix = eval_eq(&vrs_rho[prefix..]); + let prefix_value = prefix_eq(&vrs_chi, &vrs_rho, prefix); + checksum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + let rotation = rot_from_eq(i, &eq_chi_suffix, &eq_rho_suffix, &prefix_value); + checksum += &beta[i] * rotation * &theta[i]; + } + enforce_named(&format!("round {round}: rho"), &checksum, &ve)?; + + let theta_xor_base = theta + .iter() + .map(|value| FpVar::Constant(Fr::one()) - value - value) + .collect::>(); + expected_sum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + beta[i] = transcript.generate(); + expected_sum += &beta[i] * &theta_xor_base[i]; + } + + let (ve, vrs_theta) = verify_sumcheck::<3>(transcript, num_vars, expected_sum)?; + let mut ai = Vec::with_capacity(5); + let mut d = Vec::with_capacity(5); + for _ in 0..5 { + ai.push(transcript.read()?); + } + for _ in 0..5 { + d.push(transcript.read()?); + } + let e_eq = eq(&vrs_rho, &vrs_theta); + checksum = FpVar::Constant(Fr::zero()); + for j in 0..5 { + checksum += &e_eq * &d[j] * &ai[j]; + } + enforce_named(&format!("round {round}: theta"), &checksum, &ve)?; + + expected_sum = FpVar::Constant(Fr::zero()); + let mut beta_d = Vec::with_capacity(5); + for value in &d { + let challenge = transcript.generate(); + expected_sum += &challenge * value; + beta_d.push(challenge); + } + let (ve, vrs_d) = verify_sumcheck::<3>(transcript, num_vars, expected_sum)?; + let mut c = Vec::with_capacity(5); + let mut rot_c = Vec::with_capacity(5); + for _ in 0..5 { + c.push(transcript.read()?); + } + for _ in 0..5 { + rot_c.push(transcript.read()?); + } + let e_eq = eq(&vrs_theta, &vrs_d); + checksum = FpVar::Constant(Fr::zero()); + for j in 0..5 { + checksum += &beta_d[j] * &e_eq * &c[(j + 4) % 5] * &rot_c[(j + 1) % 5]; + } + enforce_named(&format!("round {round}: theta_d"), &checksum, &ve)?; + + expected_sum = FpVar::Constant(Fr::zero()); + let mut beta_c = Vec::with_capacity(5); + let mut beta_rot_c = Vec::with_capacity(5); + for value in &c { + let challenge = transcript.generate(); + expected_sum += &challenge * value; + beta_c.push(challenge); + } + for value in &rot_c { + let challenge = transcript.generate(); + expected_sum += &challenge * value; + beta_rot_c.push(challenge); + } + let (ve, vrs_c) = verify_sumcheck::<6>(transcript, num_vars, expected_sum)?; + let mut a = Vec::with_capacity(25); + for _ in 0..25 { + a.push(transcript.read()?); + } + let e_eq = eq(&vrs_d, &vrs_c); + let eq_d_suffix = eval_eq(&vrs_d[prefix..]); + let eq_c_suffix = eval_eq(&vrs_c[prefix..]); + let prefix_value = prefix_eq(&vrs_d, &vrs_c, prefix); + let e_rot = rot_from_eq(1, &eq_d_suffix, &eq_c_suffix, &prefix_value); + checksum = FpVar::Constant(Fr::zero()); + for j in 0..5 { + let product = (0..5).fold(FpVar::Constant(Fr::one()), |acc, i| acc * &a[i * 5 + j]); + checksum += (&beta_c[j] * &e_eq + &beta_rot_c[j] * &e_rot) * product; + } + enforce_named(&format!("round {round}: theta_c"), &checksum, &ve)?; + + expected_sum = FpVar::Constant(Fr::zero()); + for (i, value) in ai.iter().enumerate() { + let challenge = transcript.generate(); + for row in 0..5 { + beta[row * 5 + i] *= &challenge; + } + expected_sum += challenge * value; + } + let mut beta_a = Vec::with_capacity(25); + for value in &a { + let challenge = transcript.generate(); + expected_sum += &challenge * value; + beta_a.push(challenge); + } + let (ve, vrs_a) = verify_sumcheck::<2>(transcript, num_vars, expected_sum)?; + let mut iota = Vec::with_capacity(25); + for _ in 0..25 { + iota.push(transcript.read()?); + } + let e_eq_ai = eq(&vrs_theta, &vrs_a); + let e_eq_a = eq(&vrs_c, &vrs_a); + checksum = FpVar::Constant(Fr::zero()); + for j in 0..25 { + checksum += &beta[j] * &e_eq_ai * &iota[j] + &beta_a[j] * &e_eq_a * &iota[j]; + } + enforce_named(&format!("round {round}: theta_a"), &checksum, &ve)?; + for value in &mut iota { + *value = (FpVar::Constant(Fr::one()) - &*value) * HALF; + } + Ok((vrs_a, iota)) +} + +pub fn derive_r_native(output: &[u64], log_instances: usize) -> Vec { + if log_instances == 0 { + return Vec::new(); + } + let mut sponge = gkr::transcript::Sponge::new(); + for value in output { + sponge.absorb(Fr::from(*value)); + } + (0..log_instances).map(|_| sponge.squeeze()).collect() +} + +fn derive_r_var(output: &[FpVar], log_instances: usize) -> Vec> { + if log_instances == 0 { + return Vec::new(); + } + let mut sponge = SpongeVar::new(); + for value in output { + sponge.absorb(value); + } + (0..log_instances).map(|_| sponge.squeeze()).collect() +} + +pub struct Witness { + pub proof: Vec, + pub input: Vec, + pub output: Vec, +} + +#[derive(Clone, Debug)] +pub struct VerificationProfile { + pub allocation: usize, + pub output_binding: usize, + pub output_reduction: usize, + pub rounds: usize, + pub input_binding: usize, + pub total: usize, +} + +pub fn verify_witness( + cs: ConstraintSystemRef, + witness: &Witness, +) -> Result<(), SynthesisError> { + verify_witness_profile(cs, witness).map(|_| ()) +} + +pub fn verify_witness_profile( + cs: ConstraintSystemRef, + witness: &Witness, +) -> Result { + let start = cs.num_constraints(); + let instances = witness.input.len() / 25; + assert!(instances.is_power_of_two()); + assert_eq!(witness.output.len(), 25 * instances); + let log_instances = instances.ilog2() as usize; + let num_vars = log_instances + 6; + + let proof = witness + .proof + .iter() + .map(|value| FpVar::new_witness(cs.clone(), || Ok(*value))) + .collect::, _>>()?; + let output = witness + .output + .iter() + .map(|value| FpVar::new_witness(cs.clone(), || Ok(Fr::from(*value)))) + .collect::, _>>()?; + let mut input_bits = Vec::with_capacity(witness.input.len() * 64); + for value in &witness.input { + for bit in 0..64 { + input_bits.push(Boolean::new_witness(cs.clone(), || { + Ok((value >> bit) & 1 == 1) + })?); + } + } + let input_bits = input_bits.into_iter().map(FpVar::from).collect::>(); + let after_allocation = cs.num_constraints(); + + let r = derive_r_var(&output, log_instances); + let after_output_binding = cs.num_constraints(); + let mut transcript = TranscriptVar::new(proof); + for challenge in &r { + transcript.absorb(challenge); + } + let mut beta = (0..25).map(|_| transcript.generate()).collect::>(); + let eq_r = eval_eq(&r); + let mut expected_sum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + expected_sum += + &beta[i] * eval_mle_with_eq(&output[i * instances..(i + 1) * instances], &eq_r); + } + let mut sum = transcript.read()?; + enforce_named("output sum", &sum, &expected_sum)?; + + let (claim, r_x) = verify_sumcheck::<2>(&mut transcript, log_instances, sum)?; + let words_r_x = transcript.read()?; + enforce_named( + "output word reduction", + &claim, + &(&words_r_x * eq(&r, &r_x)), + )?; + + let (claim, r_y) = verify_sumcheck::<2>(&mut transcript, 6, words_r_x)?; + let bit_eval = transcript.read()?; + let powers = (0..64) + .map(|i| FpVar::Constant(Fr::from(1u64 << i))) + .collect::>(); + enforce_named( + "output bit reduction", + &claim, + &(eval_mle(&powers, &r_y) * &bit_eval), + )?; + sum = bit_eval; + let mut alpha = r_x; + alpha.extend(r_y); + let after_output_reduction = cs.num_constraints(); + + let mut iota = Vec::new(); + for round in (0..24).rev() { + (alpha, iota) = verify_round( + &mut transcript, + num_vars, + &alpha, + &mut beta, + sum.clone(), + ROUND_CONSTANTS[round], + round, + )?; + if round != 0 { + sum = FpVar::Constant(Fr::zero()); + for i in 0..25 { + beta[i] = transcript.generate(); + sum += &beta[i] * &iota[i]; + } + } + } + let after_rounds = cs.num_constraints(); + + let eq_alpha = eval_eq(&alpha); + for (i, iota_value) in iota.iter().enumerate() { + let start = i * instances * 64; + let end = start + instances * 64; + enforce_named( + &format!("input lane {i}"), + &eval_mle_with_eq(&input_bits[start..end], &eq_alpha), + iota_value, + )?; + } + transcript.finish()?; + let total = cs.num_constraints(); + Ok(VerificationProfile { + allocation: after_allocation - start, + output_binding: after_output_binding - after_allocation, + output_reduction: after_output_reduction - after_output_binding, + rounds: after_rounds - after_output_reduction, + input_binding: total - after_rounds, + total: total - start, + }) +} + +pub fn make_witness(instances: usize) -> Witness { + assert!(instances.is_power_of_two()); + let data = (0..instances * 25).map(|i| i as u64).collect::>(); + let mut output = vec![0u64; instances * 25]; + for instance in 0..instances { + let mut state: [u64; 25] = core::array::from_fn(|lane| data[instance * 25 + lane]); + keccak::f1600(&mut state); + for lane in 0..25 { + output[lane * instances + instance] = state[lane]; + } + } + let r = derive_r_native(&output, instances.ilog2() as usize); + let (proof, input, proved_output) = gkr::keccacheck_og::prover::prove(&data, r); + assert_eq!(proved_output, output); + Witness { + proof, + input, + output, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_relations::r1cs::ConstraintSystem; + + #[test] + fn one_permutation_proof_satisfies() { + let witness = make_witness(1); + let cs = ConstraintSystem::::new_ref(); + verify_witness(cs.clone(), &witness).unwrap(); + assert!( + cs.is_satisfied().unwrap(), + "{:?}", + cs.which_is_unsatisfied() + ); + } + + #[test] + fn altered_output_is_rejected() { + let mut witness = make_witness(1); + witness.output[0] ^= 1; + let cs = ConstraintSystem::::new_ref(); + verify_witness(cs.clone(), &witness).unwrap(); + assert!(!cs.is_satisfied().unwrap()); + } + + #[test] + fn altered_proof_is_rejected() { + let mut witness = make_witness(1); + witness.proof[0] += Fr::one(); + let cs = ConstraintSystem::::new_ref(); + verify_witness(cs.clone(), &witness).unwrap(); + assert!(!cs.is_satisfied().unwrap()); + } +} From 8b60d00d95aec648ad47bfb6e65ea00e7c1f7063 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Wed, 2 Sep 2026 20:59:47 -0400 Subject: [PATCH 17/22] perf: integrate batched Keccacheck relation --- Cargo.lock | 276 +++++- crates/gadgets/src/commitment.rs | 13 +- crates/gadgets/src/keccak/mod.rs | 4 +- crates/gadgets/src/keccak/permutation.rs | 18 + crates/gadgets/src/keccak/sponge.rs | 24 +- crates/gadgets/src/mpt/constructed_leaf.rs | 75 +- .../gadgets/src/mpt/constructed_traverse.rs | 92 +- crates/gadgets/src/statement.rs | 11 +- crates/prover/src/lib.rs | 42 +- crates/relation/Cargo.toml | 3 +- crates/relation/src/lib.rs | 408 +++++---- crates/relation/tests/mainnet.rs | 33 +- experiments/keccacheck-arkworks/Cargo.lock | 859 ++++++++++++++++-- experiments/keccacheck-arkworks/Cargo.toml | 21 +- experiments/keccacheck-arkworks/README.md | 17 +- experiments/keccacheck-arkworks/RESULTS.md | 77 +- experiments/keccacheck-arkworks/src/batch.rs | 160 ++++ experiments/keccacheck-arkworks/src/direct.rs | 6 +- experiments/keccacheck-arkworks/src/lib.rs | 1 + experiments/keccacheck-arkworks/src/main.rs | 2 +- .../keccacheck-arkworks/src/poseidon2.rs | 13 +- .../keccacheck-arkworks/src/verifier.rs | 129 ++- 22 files changed, 1882 insertions(+), 402 deletions(-) create mode 100644 experiments/keccacheck-arkworks/src/batch.rs diff --git a/Cargo.lock b/Cargo.lock index 44552b0..2d24924 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -68,14 +68,27 @@ dependencies = [ "libc", ] +[[package]] +name = "ark-bn254" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-r1cs-std 0.5.0", + "ark-std 0.5.0", +] + [[package]] name = "ark-bn254" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" dependencies = [ - "ark-ec", + "ark-ec 0.6.0", "ark-ff 0.6.0", + "ark-r1cs-std 0.6.0", "ark-std 0.6.0", ] @@ -87,10 +100,10 @@ checksum = "31b3409b1846fe459d19c95df039481575ac6d5842ae63858ad75cc31219bfc1" dependencies = [ "ahash", "ark-crypto-primitives-macros", - "ark-ec", + "ark-ec 0.6.0", "ark-ff 0.6.0", - "ark-r1cs-std", - "ark-relations", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", "ark-serialize 0.6.0", "ark-snark", "ark-std 0.6.0", @@ -116,6 +129,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ark-ec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.5", + "itertools 0.13.0", + "num-bigint", + "num-integer", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ec" version = "0.6.0" @@ -124,7 +158,7 @@ checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" dependencies = [ "ahash", "ark-ff 0.6.0", - "ark-poly", + "ark-poly 0.6.0", "ark-serialize 0.6.0", "ark-std 0.6.0", "educe", @@ -312,16 +346,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a293328aa422e65527e285614ce5d1dceb0bd7b8b18d18b1b63191ee1f74cb41" dependencies = [ "ark-crypto-primitives", - "ark-ec", + "ark-ec 0.6.0", "ark-ff 0.6.0", - "ark-poly", - "ark-relations", + "ark-poly 0.6.0", + "ark-relations 0.6.0", "ark-serialize 0.6.0", "ark-snark", "ark-std 0.6.0", "rayon", ] +[[package]] +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.5", +] + [[package]] name = "ark-poly" version = "0.6.0" @@ -338,15 +387,32 @@ dependencies = [ "rayon", ] +[[package]] +name = "ark-r1cs-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-relations 0.5.1", + "ark-std 0.5.0", + "educe", + "num-bigint", + "num-integer", + "num-traits", + "tracing", +] + [[package]] name = "ark-r1cs-std" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291f1c6628bfcac79b0dc2adbe401aa9100e2e96daa971645e0b18fc94de9a98" dependencies = [ - "ark-ec", + "ark-ec 0.6.0", "ark-ff 0.6.0", - "ark-relations", + "ark-relations 0.6.0", "ark-std 0.6.0", "educe", "itertools 0.14.0", @@ -356,6 +422,18 @@ dependencies = [ "tracing", ] +[[package]] +name = "ark-relations" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec46ddc93e7af44bcab5230937635b06fb5744464dd6a7e7b083e80ebd274384" +dependencies = [ + "ark-ff 0.5.0", + "ark-std 0.5.0", + "tracing", + "tracing-subscriber 0.2.25", +] + [[package]] name = "ark-relations" version = "0.6.0" @@ -363,14 +441,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe4c11c797a64b8a23e22bf4e77bf582ac27bb21395e3183a9a506ba2561e9f9" dependencies = [ "ark-ff 0.6.0", - "ark-poly", + "ark-poly 0.6.0", "ark-serialize 0.6.0", "ark-std 0.6.0", "foldhash 0.1.5", "indexmap 2.14.0", "rayon", "tracing", - "tracing-subscriber", + "tracing-subscriber 0.3.23", ] [[package]] @@ -400,6 +478,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" dependencies = [ + "ark-serialize-derive 0.5.0", "ark-std 0.5.0", "arrayvec", "digest 0.10.7", @@ -412,7 +491,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b" dependencies = [ - "ark-serialize-derive", + "ark-serialize-derive 0.6.0", "ark-std 0.6.0", "digest 0.10.7", "num-bigint", @@ -420,6 +499,17 @@ dependencies = [ "serde_with", ] +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "ark-serialize-derive" version = "0.6.0" @@ -438,7 +528,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bdb461d2be9b2bd6f303c79fffc89f5858790a7b4d33257bca3178e2c071fb9" dependencies = [ "ark-ff 0.6.0", - "ark-relations", + "ark-relations 0.6.0", "ark-serialize 0.6.0", "ark-std 0.6.0", ] @@ -755,6 +845,33 @@ dependencies = [ "windows-link", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "colored" version = "2.2.0" @@ -933,7 +1050,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" dependencies = [ - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -1276,6 +1393,24 @@ dependencies = [ "wasip2", ] +[[package]] +name = "gkr" +version = "0.1.0" +source = "git+https://github.com/reilabs/keccacheck.git?rev=15f00e3da5622f1c7155b02d1f9c00bd2416c282#15f00e3da5622f1c7155b02d1f9c00bd2416c282" +dependencies = [ + "ark-bn254 0.5.0", + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ciborium", + "const-oid", + "hex", + "hex-literal", + "keccak 0.1.6", + "rayon", + "tracing", + "tracing-forest", +] + [[package]] name = "group" version = "0.13.0" @@ -1287,12 +1422,32 @@ dependencies = [ "subtle", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -1327,6 +1482,12 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + [[package]] name = "hmac" version = "0.12.1" @@ -1748,24 +1909,43 @@ dependencies = [ name = "mirage-gadgets" version = "0.1.0" dependencies = [ - "ark-bn254", + "ark-bn254 0.6.0", "ark-ff 0.6.0", - "ark-r1cs-std", - "ark-relations", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", "ark-std 0.6.0", "hex", "mirage-encoding", ] +[[package]] +name = "mirage-keccacheck-arkworks" +version = "0.1.0" +dependencies = [ + "ark-bn254 0.5.0", + "ark-bn254 0.6.0", + "ark-ff 0.6.0", + "ark-groth16", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", + "ark-serialize 0.6.0", + "ark-snark", + "ark-std 0.6.0", + "blake3", + "gkr", + "keccak 0.1.6", + "mirage-gadgets", +] + [[package]] name = "mirage-prover" version = "0.1.0" dependencies = [ - "ark-bn254", - "ark-ec", + "ark-bn254 0.6.0", + "ark-ec 0.6.0", "ark-ff 0.6.0", "ark-groth16", - "ark-relations", + "ark-relations 0.6.0", "ark-serialize 0.6.0", "ark-snark", "ark-std 0.6.0", @@ -1779,14 +1959,15 @@ dependencies = [ name = "mirage-relation" version = "0.1.0" dependencies = [ - "ark-bn254", + "ark-bn254 0.6.0", "ark-ff 0.6.0", - "ark-r1cs-std", - "ark-relations", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", "ark-std 0.6.0", "hex", "mirage-encoding", "mirage-gadgets", + "mirage-keccacheck-arkworks", "serde", "serde_json", ] @@ -2566,8 +2747,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28ef11218070383cd71cc84a7650587646e316f57b24ee48091d109b77fb8661" dependencies = [ "alloy-primitives", - "ark-bn254", - "ark-ec", + "ark-bn254 0.6.0", + "ark-ec 0.6.0", "ark-ff 0.6.0", "ark-groth16", "askama", @@ -2581,13 +2762,33 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -2736,6 +2937,18 @@ dependencies = [ "valuable", ] +[[package]] +name = "tracing-forest" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee40835db14ddd1e3ba414292272eddde9dad04d3d4b65509656414d1c42592f" +dependencies = [ + "smallvec", + "thiserror 1.0.69", + "tracing", + "tracing-subscriber 0.3.23", +] + [[package]] name = "tracing-log" version = "0.2.0" @@ -2747,6 +2960,15 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-subscriber" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0d2eaa99c3c2e41547cfa109e910a68ea03823cccad4a0525dcbc9b01e8c71" +dependencies = [ + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.23" diff --git a/crates/gadgets/src/commitment.rs b/crates/gadgets/src/commitment.rs index 1b6e4fe..d44e19a 100644 --- a/crates/gadgets/src/commitment.rs +++ b/crates/gadgets/src/commitment.rs @@ -51,8 +51,8 @@ use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; -use crate::keccak::keccak256_fixed; use crate::keccak::sponge::to_bytes; +use crate::keccak::{keccak256_fixed_with, DirectPermutation, PermutationBackend}; /// Byte width of the spec 8.3 preimage. pub const PREIMAGE_LEN: usize = 226; @@ -138,10 +138,19 @@ pub fn open( opening: &Opening, commitment: &[UInt8], active: &Boolean, +) -> Result<(), SynthesisError> { + open_with(opening, commitment, active, &mut DirectPermutation) +} + +pub fn open_with>( + opening: &Opening, + commitment: &[UInt8], + active: &Boolean, + backend: &mut B, ) -> Result<(), SynthesisError> { assert_eq!(commitment.len(), 32, "commitment must be 32 bytes"); - let digest_bits = keccak256_fixed(&to_bytes(&opening.preimage())?)?; + let digest_bits = keccak256_fixed_with(&to_bytes(&opening.preimage())?, backend)?; for (bits, want) in digest_bits.iter().zip(commitment.iter()) { UInt8::from_bits_le(bits).conditional_enforce_equal(want, active)?; } diff --git a/crates/gadgets/src/keccak/mod.rs b/crates/gadgets/src/keccak/mod.rs index 085d257..9916f3e 100644 --- a/crates/gadgets/src/keccak/mod.rs +++ b/crates/gadgets/src/keccak/mod.rs @@ -55,8 +55,8 @@ mod permutation; pub mod sponge; -pub use permutation::{keccak_f1600, State}; -pub use sponge::{keccak256_fixed, keccak256_var}; +pub use permutation::{keccak_f1600, DirectPermutation, PermutationBackend, State}; +pub use sponge::{keccak256_fixed, keccak256_fixed_with, keccak256_var, keccak256_var_with}; /// Rate in bytes for keccak-256: 200 - 2*32. pub const RATE: usize = 136; diff --git a/crates/gadgets/src/keccak/permutation.rs b/crates/gadgets/src/keccak/permutation.rs index b902e02..2ef70de 100644 --- a/crates/gadgets/src/keccak/permutation.rs +++ b/crates/gadgets/src/keccak/permutation.rs @@ -29,6 +29,24 @@ use ark_relations::gr1cs::SynthesisError; /// 25 lanes of 64 bits. pub type State = [[Boolean; 64]; 25]; +/// Backend used by the sponge for each Keccak-f permutation. +/// +/// The default implementation below emits the direct Boolean constraints. +/// Experimental coprocessor backends can instead allocate the output state, +/// record the input/output pair, and verify the entire batch once. +pub trait PermutationBackend { + fn permute(&mut self, state: State) -> Result, SynthesisError>; +} + +#[derive(Default)] +pub struct DirectPermutation; + +impl PermutationBackend for DirectPermutation { + fn permute(&mut self, state: State) -> Result, SynthesisError> { + keccak_f1600(state) + } +} + /// Rotation offsets, indexed by the rho/pi step order. const RHO: [u32; 24] = [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44, diff --git a/crates/gadgets/src/keccak/sponge.rs b/crates/gadgets/src/keccak/sponge.rs index 0990f91..e738bdb 100644 --- a/crates/gadgets/src/keccak/sponge.rs +++ b/crates/gadgets/src/keccak/sponge.rs @@ -38,7 +38,7 @@ use ark_r1cs_std::select::CondSelectGadget; use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; -use super::permutation::{keccak_f1600, State}; +use super::permutation::{DirectPermutation, PermutationBackend, State}; use super::{DELIM_KECCAK, RATE}; use crate::bytes::{assert_zero_tail, prefix_mask}; @@ -97,12 +97,19 @@ fn squeeze_256(st: &State) -> [Byte; 32] { /// offset, so this needs no selection logic and costs exactly /// `ceil((len + 1) / RATE)` permutations. pub fn keccak256_fixed(input: &[Byte]) -> Result<[Byte; 32], SynthesisError> { + keccak256_fixed_with(input, &mut DirectPermutation) +} + +pub fn keccak256_fixed_with>( + input: &[Byte], + backend: &mut B, +) -> Result<[Byte; 32], SynthesisError> { let mut st = empty_state::(); let full_blocks = input.len() / RATE; for b in 0..full_blocks { absorb_block(&mut st, &input[b * RATE..(b + 1) * RATE])?; - st = keccak_f1600(st)?; + st = backend.permute(st)?; } // Final partial block, with padding. The delimiter goes at the first free @@ -120,7 +127,7 @@ pub fn keccak256_fixed(input: &[Byte]) -> Result<[Byte; 32] })); } absorb_block(&mut st, &last)?; - st = keccak_f1600(st)?; + st = backend.permute(st)?; Ok(squeeze_256(&st)) } @@ -166,6 +173,15 @@ pub fn keccak256_var( buf: &[UInt8], len: &FpVar, active: &Boolean, +) -> Result<[Byte; 32], SynthesisError> { + keccak256_var_with(buf, len, active, &mut DirectPermutation) +} + +pub fn keccak256_var_with>( + buf: &[UInt8], + len: &FpVar, + active: &Boolean, + backend: &mut B, ) -> Result<[Byte; 32], SynthesisError> { let max = buf.len(); let max_blocks = max / RATE + 1; @@ -235,7 +251,7 @@ pub fn keccak256_var( let mut states = Vec::with_capacity(max_blocks); for b in 0..max_blocks { absorb_block(&mut st, &msg_bytes[b * RATE..(b + 1) * RATE])?; - st = keccak_f1600(st)?; + st = backend.permute(st)?; states.push(st.clone()); } diff --git a/crates/gadgets/src/mpt/constructed_leaf.rs b/crates/gadgets/src/mpt/constructed_leaf.rs index 218a64c..f993906 100644 --- a/crates/gadgets/src/mpt/constructed_leaf.rs +++ b/crates/gadgets/src/mpt/constructed_leaf.rs @@ -20,7 +20,7 @@ use ark_relations::gr1cs::SynthesisError; use crate::bytes::byte_to_field; use crate::keccak::sponge::Byte; -use crate::keccak::keccak256_var; +use crate::keccak::{keccak256_var_with, DirectPermutation, PermutationBackend}; use crate::mpt::path::nibble_at; /// Constructs and hashes `RLP([HP(key[consumed..], leaf), receipt])`. @@ -35,6 +35,26 @@ pub fn hash_leaf_from_remainder( key_len: &FpVar, consumed: &FpVar, active: &Boolean, +) -> Result<[Byte; 32], SynthesisError> { + hash_leaf_from_remainder_with( + receipt, + receipt_len, + key, + key_len, + consumed, + active, + &mut DirectPermutation, + ) +} + +pub fn hash_leaf_from_remainder_with>( + receipt: &[UInt8], + receipt_len: &FpVar, + key: &[UInt8], + key_len: &FpVar, + consumed: &FpVar, + active: &Boolean, + backend: &mut B, ) -> Result<[Byte; 32], SynthesisError> { let cs = receipt_len.cs(); let len_value = receipt_len.value().unwrap_or(F::zero()); @@ -47,10 +67,8 @@ pub fn hash_leaf_from_remainder( let decode_u16 = |hi: &UInt8, low: &UInt8| -> Result, SynthesisError> { Ok(byte_to_field(hi)? * FpVar::constant(F::from(256u64)) + byte_to_field(low)?) }; - decode_u16(&receipt_hi, &receipt_low)? - .conditional_enforce_equal(receipt_len, active)?; - receipt_hi - .conditional_enforce_equal(&UInt8::constant(1), active)?; + decode_u16(&receipt_hi, &receipt_low)?.conditional_enforce_equal(receipt_len, active)?; + receipt_hi.conditional_enforce_equal(&UInt8::constant(1), active)?; let total_nibbles = key_len * FpVar::constant(F::from(2u64)); let remaining = &total_nibbles - consumed; @@ -104,7 +122,7 @@ pub fn hash_leaf_from_remainder( } let leaf_len = receipt_len + path_item_len + FpVar::constant(F::from(6u64)); - keccak256_var(&leaf, &leaf_len, active) + keccak256_var_with(&leaf, &leaf_len, active, backend) } fn path_bytes( @@ -118,17 +136,12 @@ fn path_bytes( if n % 2 == 0 { expressions.push(FpVar::constant(F::from(0x20u64))); } else { - expressions.push( - FpVar::constant(F::from(0x30u64)) + nibble_at(key, consumed)?, - ); + expressions.push(FpVar::constant(F::from(0x30u64)) + nibble_at(key, consumed)?); } let mut j = n % 2; while j < n { let high = nibble_at(key, &(consumed + FpVar::constant(F::from(j as u64))))?; - let low = nibble_at( - key, - &(consumed + FpVar::constant(F::from((j + 1) as u64))), - )?; + let low = nibble_at(key, &(consumed + FpVar::constant(F::from((j + 1) as u64))))?; expressions.push(high * FpVar::constant(F::from(16u64)) + low); j += 2; } @@ -202,7 +215,8 @@ mod tests { for consumed in 0..=6 { let cs = ConstraintSystem::::new_ref(); let buf = alloc_bounded(cs.clone(), &receipt, 448).unwrap(); - let len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); + let len = + FpVar::new_witness(cs.clone(), || Ok(Fr::from(receipt.len() as u64))).unwrap(); let key_buf = alloc_bounded(cs.clone(), &key, 3).unwrap(); let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(3u64))).unwrap(); let consumed_var = @@ -219,9 +233,9 @@ mod tests { let got: Vec = digest .iter() .map(|bits| { - bits.iter().enumerate().fold(0u8, |v, (i, b)| { - v | ((b.value().unwrap() as u8) << i) - }) + bits.iter() + .enumerate() + .fold(0u8, |v, (i, b)| v | ((b.value().unwrap() as u8) << i)) }) .collect(); assert_eq!( @@ -243,15 +257,8 @@ mod tests { let key = alloc_bounded(cs.clone(), &[0x12], 3).unwrap(); let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(1u64))).unwrap(); let consumed = FpVar::new_witness(cs.clone(), || Ok(Fr::from(0u64))).unwrap(); - let _ = hash_leaf_from_remainder( - &buf, - &len, - &key, - &key_len, - &consumed, - &Boolean::TRUE, - ) - .unwrap(); + let _ = hash_leaf_from_remainder(&buf, &len, &key, &key_len, &consumed, &Boolean::TRUE) + .unwrap(); assert!(!cs.is_satisfied().unwrap()); } @@ -265,15 +272,11 @@ mod tests { let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(1u64))).unwrap(); let consumed = FpVar::new_witness(cs.clone(), || Ok(Fr::from(2u64))).unwrap(); let before = cs.num_constraints(); - let _ = hash_leaf_from_remainder( - &buf, - &len, - &key, - &key_len, - &consumed, - &Boolean::TRUE, - ) - .unwrap(); - println!("constructed finite-family leaf: {} constraints", cs.num_constraints() - before); + let _ = hash_leaf_from_remainder(&buf, &len, &key, &key_len, &consumed, &Boolean::TRUE) + .unwrap(); + println!( + "constructed finite-family leaf: {} constraints", + cs.num_constraints() - before + ); } } diff --git a/crates/gadgets/src/mpt/constructed_traverse.rs b/crates/gadgets/src/mpt/constructed_traverse.rs index 8dee85f..42fe866 100644 --- a/crates/gadgets/src/mpt/constructed_traverse.rs +++ b/crates/gadgets/src/mpt/constructed_traverse.rs @@ -17,13 +17,13 @@ use ark_r1cs_std::uint8::UInt8; use ark_r1cs_std::GR1CSVar; use ark_relations::gr1cs::SynthesisError; -use super::constructed_leaf::hash_leaf_from_remainder; +use super::constructed_leaf::hash_leaf_from_remainder_with; use super::node::{branch_child_offset, decode_branch, decode_short}; use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at, read_flags}; use super::traverse::{assert_path_matches, bits_to_byte}; use super::{MptVerifier, ProofNode}; use crate::bytes::{one_hot, select_byte_with, select_bytes, zero_like}; -use crate::keccak::keccak256_var; +use crate::keccak::{keccak256_var_with, DirectPermutation, PermutationBackend}; pub struct ConstructedLeafTraversal; @@ -46,6 +46,28 @@ impl MptVerifier for ConstructedLeafTraversal { value: &[UInt8], value_len: &FpVar, nodes: &[ProofNode], + ) -> Result<(), SynthesisError> { + Self::verify_inclusion_with( + root, + key, + key_len, + value, + value_len, + nodes, + &mut DirectPermutation, + ) + } +} + +impl ConstructedLeafTraversal { + pub fn verify_inclusion_with>( + root: &[UInt8], + key: &[UInt8], + key_len: &FpVar, + value: &[UInt8], + value_len: &FpVar, + nodes: &[ProofNode], + backend: &mut B, ) -> Result<(), SynthesisError> { let mut expected = root.to_vec(); let mut consumed = zero_like(key)?; @@ -64,7 +86,7 @@ impl MptVerifier for ConstructedLeafTraversal { (inactive_seen.clone() & active.clone()).enforce_equal(&Boolean::FALSE)?; inactive_seen |= !active.clone(); - let digest = keccak256_var(&level.bytes, &level.len, &active)?; + let digest = keccak256_var_with(&level.bytes, &level.len, &active, backend)?; for (digest_byte, want) in digest.iter().zip(expected.iter()) { bits_to_byte(digest_byte)?.conditional_enforce_equal(want, &active)?; } @@ -80,11 +102,8 @@ impl MptVerifier for ConstructedLeafTraversal { let nibble = nibble_at(key, &consumed)?; let child_offset = branch_child_offset(&branch, &nibble, &active)?; let next_ref = select_bytes(&level.bytes, &child_offset, 32)?; - consumed = FpVar::conditionally_select( - &active, - &(&consumed + FpVar::one()), - &consumed, - )?; + consumed = + FpVar::conditionally_select(&active, &(&consumed + FpVar::one()), &consumed)?; expected = expected .iter() .zip(next_ref.iter()) @@ -107,8 +126,7 @@ impl MptVerifier for ConstructedLeafTraversal { .map(|byte| byte.value().unwrap_or(0)) .collect(); let native_branch = native_list_arity(&native_bytes) == Some(17); - let this_is_branch = - Boolean::new_witness(level.len.cs(), || Ok(native_branch))?; + let this_is_branch = Boolean::new_witness(level.len.cs(), || Ok(native_branch))?; profile(&level.bytes, "shape-hint", &mut mark); let branch_active = active.clone() & this_is_branch.clone(); let short_active = active.clone() & !this_is_branch.clone(); @@ -131,10 +149,9 @@ impl MptVerifier for ConstructedLeafTraversal { flags .is_leaf .conditional_enforce_equal(&Boolean::FALSE, &short_active)?; - short.tail_len.conditional_enforce_equal( - &FpVar::constant(F::from(32u64)), - &short_active, - )?; + short + .tail_len + .conditional_enforce_equal(&FpVar::constant(F::from(32u64)), &short_active)?; profile(&level.bytes, "flags", &mut mark); let path_nibbles = &short.path_len * FpVar::constant(F::from(2u64)) @@ -158,16 +175,8 @@ impl MptVerifier for ConstructedLeafTraversal { FpVar::conditionally_select(&this_is_branch, &child_offset, &short.tail_offset)?; let next_ref = select_bytes(&level.bytes, &next_offset, 32)?; profile(&level.bytes, "tail-read", &mut mark); - let step = FpVar::conditionally_select( - &this_is_branch, - &FpVar::one(), - &path_nibbles, - )?; - consumed = FpVar::conditionally_select( - &active, - &(&consumed + step), - &consumed, - )?; + let step = FpVar::conditionally_select(&this_is_branch, &FpVar::one(), &path_nibbles)?; + consumed = FpVar::conditionally_select(&active, &(&consumed + step), &consumed)?; expected = expected .iter() .zip(next_ref.iter()) @@ -180,8 +189,15 @@ impl MptVerifier for ConstructedLeafTraversal { .first() .map(|byte| byte.cs().num_constraints()) .unwrap_or(0); - let leaf_digest = - hash_leaf_from_remainder(value, value_len, key, key_len, &consumed, &Boolean::TRUE)?; + let leaf_digest = hash_leaf_from_remainder_with( + value, + value_len, + key, + key_len, + &consumed, + &Boolean::TRUE, + backend, + )?; profile(key, "constructed-leaf", &mut leaf_mark); for (digest_byte, want) in leaf_digest.iter().zip(expected.iter()) { bits_to_byte(digest_byte)?.enforce_equal(want)?; @@ -248,9 +264,7 @@ mod tests { use crate::bytes::alloc_bounded; use crate::mpt::harness::NativeProof; - use crate::mpt::tests::{ - branch_node, extension_node, leaf_node, simple_trie, - }; + use crate::mpt::tests::{branch_node, extension_node, leaf_node, simple_trie}; fn genuine() -> NativeProof { let key = vec![0x35, 0x71]; @@ -272,16 +286,12 @@ mod tests { } } - fn build( - cs: ConstraintSystemRef, - p: &NativeProof, - ) -> Result<(), SynthesisError> { + fn build(cs: ConstraintSystemRef, p: &NativeProof) -> Result<(), SynthesisError> { let root = alloc_bounded(cs.clone(), &p.root, 32)?; let key = alloc_bounded(cs.clone(), &p.key, 3)?; let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.key.len() as u64)))?; let value = alloc_bounded(cs.clone(), &p.value, 448)?; - let value_len = - FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64)))?; + let value_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64)))?; let ancestor_count = p.nodes.len().saturating_sub(1); let mut nodes = Vec::with_capacity(3); @@ -297,12 +307,7 @@ mod tests { }); } ConstructedLeafTraversal::verify_inclusion( - &root, - &key, - &key_len, - &value, - &value_len, - &nodes, + &root, &key, &key_len, &value, &value_len, &nodes, ) } @@ -341,7 +346,10 @@ mod tests { let mut wrong_ancestor = genuine(); wrong_ancestor.nodes[0][7] ^= 1; - assert!(!verify(&wrong_ancestor), "accepted an unauthenticated ancestor"); + assert!( + !verify(&wrong_ancestor), + "accepted an unauthenticated ancestor" + ); } #[test] diff --git a/crates/gadgets/src/statement.rs b/crates/gadgets/src/statement.rs index 31f8505..1d47cba 100644 --- a/crates/gadgets/src/statement.rs +++ b/crates/gadgets/src/statement.rs @@ -33,8 +33,8 @@ use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; use crate::bytes::pack_bytes_16; -use crate::keccak::keccak256_fixed; use crate::keccak::sponge::to_bytes; +use crate::keccak::{keccak256_fixed_with, DirectPermutation, PermutationBackend}; /// Byte width of the spec 10.2 preimage. pub const PREIMAGE_LEN: usize = 285; @@ -124,8 +124,15 @@ pub struct Signals { /// values. Splitting it that way keeps the public-input decision in the /// relation, where the spec 10.1 argument for exactly two signals lives. pub fn compute(ctx: &Context) -> Result, SynthesisError> { + compute_with(ctx, &mut DirectPermutation) +} + +pub fn compute_with>( + ctx: &Context, + backend: &mut B, +) -> Result, SynthesisError> { let preimage = ctx.preimage(); - let digest_bits = keccak256_fixed(&to_bytes(&preimage)?)?; + let digest_bits = keccak256_fixed_with(&to_bytes(&preimage)?, backend)?; // The digest as 32 bytes, then split into two 16-byte limbs. 16 bytes is // always below the BN254 modulus, so each packing is injective; 32 would diff --git a/crates/prover/src/lib.rs b/crates/prover/src/lib.rs index 2716779..59eea05 100644 --- a/crates/prover/src/lib.rs +++ b/crates/prover/src/lib.rs @@ -19,7 +19,7 @@ use ark_groth16::{Groth16, PreparedVerifyingKey, Proof, ProvingKey, VerifyingKey use ark_snark::SNARK; use ark_std::rand::SeedableRng; -use mirage_relation::{Bounds, ReceiptCircuit, Witness}; +use mirage_relation::{Bounds, KeccacheckReceiptCircuit, ReceiptCircuit, Witness}; /// A proving and verifying key pair for one circuit version. pub struct Keys { @@ -51,6 +51,16 @@ pub fn setup(bounds: Bounds, seed: u64) -> Result { Ok(Keys { pk, vk }) } +/// Experimental setup for the relation whose Keccak-f calls are verified by +/// the in-circuit Keccacheck batch verifier. +pub fn setup_keccacheck(bounds: Bounds, seed: u64) -> Result { + let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(seed); + let (pk, vk) = + Groth16::::circuit_specific_setup(KeccacheckReceiptCircuit::setup(bounds), &mut rng) + .map_err(|e| SettlementError::Setup(e.to_string()))?; + Ok(Keys { pk, vk }) +} + /// Proves that `witness` satisfies the relation, and checks the proof natively /// before returning it. /// @@ -87,6 +97,36 @@ pub fn prove( }) } +/// Experimental proving path matching [`setup_keccacheck`]. The native GKR +/// proof is generated in Rust while the Groth16 witness is synthesized. +pub fn prove_keccacheck( + keys: &Keys, + bounds: Bounds, + witness: &Witness, + rng: &mut R, +) -> Result { + check_bounds(bounds, witness)?; + let (hi, lo) = mirage_relation::public_signals(witness); + let proof = Groth16::::prove( + &keys.pk, + KeccacheckReceiptCircuit::prove(bounds, witness.clone()), + rng, + ) + .map_err(|e| SettlementError::Prove(e.to_string()))?; + + let pvk = PreparedVerifyingKey::from(keys.vk.clone()); + let ok = + Groth16::::verify_with_processed_vk(&pvk, &[Fr::from(hi), Fr::from(lo)], &proof) + .map_err(|e| SettlementError::Verify(e.to_string()))?; + if !ok { + return Err(SettlementError::SelfCheck); + } + Ok(Settlement { + proof: proof_points(&proof), + signals: [hi, lo], + }) +} + /// [`prove`] with a seeded RNG, for artifacts that must reproduce byte-exactly. /// /// Not for production settlements: a fixed seed reuses proof randomness across diff --git a/crates/relation/Cargo.toml b/crates/relation/Cargo.toml index 76815a0..68bf220 100644 --- a/crates/relation/Cargo.toml +++ b/crates/relation/Cargo.toml @@ -9,11 +9,12 @@ ark-ff.workspace = true ark-relations.workspace = true ark-r1cs-std.workspace = true ark-std.workspace = true +ark-bn254.workspace = true mirage-gadgets = { path = "../gadgets" } mirage-encoding = { path = "../encoding" } +mirage-keccacheck-arkworks = { path = "../../experiments/keccacheck-arkworks" } [dev-dependencies] -ark-bn254.workspace = true serde.workspace = true serde_json.workspace = true hex.workspace = true diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 7830580..5151774 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -17,6 +17,7 @@ //! //! Not wired: the delayed-witness ancestry chain (12.7), which is step 5. +use ark_bn254::Fr; use ark_ff::PrimeField; use ark_r1cs_std::alloc::AllocVar; use ark_r1cs_std::boolean::Boolean; @@ -29,9 +30,8 @@ use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystemRef, Synthesis use mirage_gadgets::bytes::alloc_bounded; use mirage_gadgets::header; -use mirage_gadgets::mpt::{ - constructed_traverse::ConstructedLeafTraversal, MptVerifier, ProofNode, -}; +use mirage_gadgets::keccak::{DirectPermutation, PermutationBackend}; +use mirage_gadgets::mpt::{constructed_traverse::ConstructedLeafTraversal, ProofNode}; use mirage_gadgets::receipt::{log::Erc20FixedLayout, Intent, ReceiptRelation}; use mirage_gadgets::statement; @@ -53,11 +53,7 @@ pub const MEASUREMENT_SCOPE: &str = /// This deliberately observes only `num_constraints`: it does not allocate /// variables or otherwise change the circuit. Optimization branches use these /// stable stage names so their deltas can be compared against one baseline. -fn profile( - cs: &ConstraintSystemRef, - stage: &str, - last: &mut usize, -) { +fn profile(cs: &ConstraintSystemRef, stage: &str, last: &mut usize) { if std::env::var_os("RELATION_PROFILE").is_none() { return; } @@ -205,156 +201,207 @@ impl ReceiptCircuit { impl ConstraintSynthesizer for ReceiptCircuit { fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { - let b = self.bounds; - let w = self.w(); - let mut mark = cs.num_constraints(); - - // ---- public inputs ---- - // - // Exactly two, per spec 10.1: the statement hash's 128-bit limbs. Each - // public input costs a scalar multiplication in the on-chain verifier - // and a G1 point in the embedded verification key, so collapsing the - // full context to two keeps the verifier fixed regardless of how many - // fields the relation binds. - let (want_hi, want_lo) = native_signals(&w.statement); - let public_hi = FpVar::new_input(cs.clone(), || Ok(F::from(want_hi)))?; - let public_lo = FpVar::new_input(cs.clone(), || Ok(F::from(want_lo)))?; - - // ---- witness allocation ---- - let header_bytes = alloc_bounded(cs.clone(), &w.header, b.header_bytes)?; - let header_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.header.len() as u64)))?; - let key = alloc_bounded(cs.clone(), &w.key, b.key_bytes)?; - let key_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.key.len() as u64)))?; - - let receipt = alloc_bounded(cs.clone(), &w.receipt, b.receipt_bytes)?; - let receipt_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.receipt.len() as u64)))?; - - // The terminal leaf is constructed from the key remainder and receipt, - // so only the at-most `depth - 1` ancestor nodes are witnesses. - let ancestor_count = w.nodes.len().saturating_sub(1); - let mut nodes = Vec::with_capacity(b.depth.saturating_sub(1)); - for i in 0..b.depth.saturating_sub(1) { - // An active root is necessarily a branch: a root leaf is the - // zero-ancestor case constructed below. With three-byte RLP - // transaction-index keys, only first nibbles 0..=8 can occur, so - // at most nine 33-byte child references plus seven empty slots, - // an empty value and the three-byte list header fit in 308 bytes. - // Deeper branches can occupy all sixteen slots: 16*33 bytes of - // hash references, one empty value byte, and a three-byte list - // header are exactly 532 bytes. These are structural maxima, not - // sampled cutoffs. - let node_bound = if i == 0 { 308 } else { 532 }; - let (bytes, len, active) = match w.nodes.get(i).filter(|_| i < ancestor_count) { - Some(n) => (n.clone(), n.len(), true), - None => (Vec::new(), 0, false), - }; - nodes.push(ProofNode { - bytes: alloc_bounded(cs.clone(), &bytes, node_bound)?, - len: FpVar::new_witness(cs.clone(), || Ok(F::from(len as u64)))?, - active: Boolean::new_witness(cs.clone(), || Ok(active))?, - }); + generate_constraints_with_backend(self, cs, &mut DirectPermutation) + } +} + +/// Experimental relation using one deferred Keccacheck batch instead of 38 +/// directly arithmetized Keccak-f permutations. +#[derive(Clone)] +pub struct KeccacheckReceiptCircuit(pub ReceiptCircuit); + +impl KeccacheckReceiptCircuit { + pub fn setup(bounds: Bounds) -> Self { + Self(ReceiptCircuit::setup(bounds)) + } + + pub fn prove(bounds: Bounds, witness: Witness) -> Self { + Self(ReceiptCircuit::prove(bounds, witness)) + } +} + +impl ConstraintSynthesizer for KeccacheckReceiptCircuit { + fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { + let mut batch = mirage_keccacheck_arkworks::batch::KeccacheckBatch::new(cs.clone()); + generate_constraints_with_backend(self.0, cs.clone(), &mut batch)?; + let before = cs.num_constraints(); + let result = batch.finish()?; + if std::env::var_os("RELATION_PROFILE").is_some() { + eprintln!( + "{:>24}: {:>10} ({} -> {} permutations)", + "Keccacheck verifier", + cs.num_constraints() - before, + result.recorded, + result.padded, + ); } + Ok(()) + } +} - // The opened commitment, whose token/recipient/amount become the intent - // the receipt relation checks. Opening it and then checking the log - // against different values would defeat the whole exercise, so the same - // allocations are used for both. - let opening = alloc_opening(cs.clone(), &w.intent)?; - let ctx = alloc_statement(cs.clone(), &w.statement)?; - let intent = Intent { - token: opening.settlement_token.clone(), - recipient: opening.recipient.clone(), - amount: opening.settlement_amount.clone(), +pub fn generate_constraints_with_backend>( + circuit: ReceiptCircuit, + cs: ConstraintSystemRef, + backend: &mut B, +) -> Result<(), SynthesisError> { + let b = circuit.bounds; + let w = circuit.w(); + let mut mark = cs.num_constraints(); + + // ---- public inputs ---- + // + // Exactly two, per spec 10.1: the statement hash's 128-bit limbs. Each + // public input costs a scalar multiplication in the on-chain verifier + // and a G1 point in the embedded verification key, so collapsing the + // full context to two keeps the verifier fixed regardless of how many + // fields the relation binds. + let (want_hi, want_lo) = native_signals(&w.statement); + let public_hi = FpVar::new_input(cs.clone(), || Ok(F::from(want_hi)))?; + let public_lo = FpVar::new_input(cs.clone(), || Ok(F::from(want_lo)))?; + + // ---- witness allocation ---- + let header_bytes = alloc_bounded(cs.clone(), &w.header, b.header_bytes)?; + let header_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.header.len() as u64)))?; + let key = alloc_bounded(cs.clone(), &w.key, b.key_bytes)?; + let key_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.key.len() as u64)))?; + + let receipt = alloc_bounded(cs.clone(), &w.receipt, b.receipt_bytes)?; + let receipt_len = FpVar::new_witness(cs.clone(), || Ok(F::from(w.receipt.len() as u64)))?; + + // The terminal leaf is constructed from the key remainder and receipt, + // so only the at-most `depth - 1` ancestor nodes are witnesses. + let ancestor_count = w.nodes.len().saturating_sub(1); + let mut nodes = Vec::with_capacity(b.depth.saturating_sub(1)); + for i in 0..b.depth.saturating_sub(1) { + // An active root is necessarily a branch: a root leaf is the + // zero-ancestor case constructed below. With three-byte RLP + // transaction-index keys, only first nibbles 0..=8 can occur, so + // at most nine 33-byte child references plus seven empty slots, + // an empty value and the three-byte list header fit in 308 bytes. + // Deeper branches can occupy all sixteen slots: 16*33 bytes of + // hash references, one empty value byte, and a three-byte list + // header are exactly 532 bytes. These are structural maxima, not + // sampled cutoffs. + let node_bound = if i == 0 { 308 } else { 532 }; + let (bytes, len, active) = match w.nodes.get(i).filter(|_| i < ancestor_count) { + Some(n) => (n.clone(), n.len(), true), + None => (Vec::new(), 0, false), }; - let log_index = FpVar::new_witness(cs.clone(), || Ok(F::from(w.log_index as u64)))?; - profile(&cs, "allocation", &mut mark); - - // ---- the relation ---- - // - // The chain of bindings is what makes this a proof rather than a - // satisfiability check: - // - // commitment -> token/recipient/amount - // header -> receiptsRoot -> MPT inclusion -> receipt -> log - // - // The commitment is the escrow's stored value, carried into the - // statement hash and therefore into the public signals. Opening it here - // is what turns "some Transfer happened" into "the Transfer this escrow - // committed to happened". - mirage_gadgets::commitment::open(&opening, &ctx.intent_commitment, &Boolean::TRUE)?; - profile(&cs, "intent commitment", &mut mark); - - // The commitment's deployment/request/row context must be the same - // context whose statement hash the verifier checks. The commitment - // hash alone only authenticates the opening internally. - enforce_bytes_equal(&opening.instance_domain, &ctx.instance_domain)?; - enforce_bytes_equal(&opening.chain_id, &ctx.chain_id)?; - enforce_bytes_equal(&opening.escrow, &ctx.escrow)?; - enforce_bytes_equal(&opening.request_id, &ctx.request_id)?; - enforce_bytes_equal(&opening.row_index, &ctx.row_index)?; - profile(&cs, "context equality", &mut mark); - // - // The header supplies the root rather than the caller. Accepting a - // caller-supplied root would let a prover invent a trie containing - // whatever it liked. - let parsed = - header::parse_authenticated_prefix(&header_bytes, &header_len, &Boolean::TRUE)?; - profile(&cs, "header parse", &mut mark); - - // Authenticate both header identity fields carried by the statement. - // Parsing a receiptsRoot is not useful unless the parsed header is the - // exact witness block selected by the verifier. - let header_digest = - mirage_gadgets::keccak::keccak256_var(&header_bytes, &header_len, &Boolean::TRUE)?; - for (got, want) in header_digest.iter().zip(ctx.witness_block_hash.iter()) { - UInt8::from_bits_le(got).enforce_equal(want)?; - } - profile(&cs, "header hash", &mut mark); - let witness_number = fixed_be_value(&ctx.witness_block_number)?; - parsed.number.enforce_equal(&witness_number)?; - - // Settlement is valid only in the half-open/closed lease interval: - // bondStartBlock < txBlockNumber <= bondDeadline. - let bond_start = fixed_be_value(&ctx.bond_start_block)?; - let bond_deadline = fixed_be_value(&ctx.bond_deadline)?; - lt_u64(&bond_start, &parsed.number)?.enforce_equal(&Boolean::TRUE)?; - lt_u64(&bond_deadline, &parsed.number)?.enforce_equal(&Boolean::FALSE)?; - profile(&cs, "block/time checks", &mut mark); - - // The receipt is the MPT leaf's value, so inclusion binds the exact - // bytes the log walk then inspects. Without that link the relation - // would prove a Transfer in *some* receipt rather than one in this - // block's trie. - ConstructedLeafTraversal::verify_inclusion( - &parsed.receipts_root, - &key, - &key_len, - &receipt, - &receipt_len, - &nodes, - )?; - profile(&cs, "MPT traversal", &mut mark); - // The single-log variant: spec 20.3 requires production settlements be a - // direct `transfer()` call, whose receipt carries exactly one event. - // Skipping the walk to log `k` saves 16% of the receipt relation. - // - // The trade is that a receipt with any second event becomes unprovable, - // which the enclave's pre-settlement token review must enforce rather - // than the prover discovering it. See `receipt::log::sole_log`. - Erc20FixedLayout::verify(&receipt, &receipt_len, &log_index, &intent, &Boolean::TRUE)?; - profile(&cs, "receipt relation", &mut mark); - - // ---- statement hash ---- - // - // Recomputed from privately supplied context and checked against the - // two public signals. Every field is already public on-chain; hashing - // them down only shrinks the verifier. - let signals = statement::compute(&ctx)?; - statement::enforce(&signals, &public_hi, &public_lo, &Boolean::TRUE)?; - profile(&cs, "statement hash", &mut mark); + nodes.push(ProofNode { + bytes: alloc_bounded(cs.clone(), &bytes, node_bound)?, + len: FpVar::new_witness(cs.clone(), || Ok(F::from(len as u64)))?, + active: Boolean::new_witness(cs.clone(), || Ok(active))?, + }); + } - Ok(()) + // The opened commitment, whose token/recipient/amount become the intent + // the receipt relation checks. Opening it and then checking the log + // against different values would defeat the whole exercise, so the same + // allocations are used for both. + let opening = alloc_opening(cs.clone(), &w.intent)?; + let ctx = alloc_statement(cs.clone(), &w.statement)?; + let intent = Intent { + token: opening.settlement_token.clone(), + recipient: opening.recipient.clone(), + amount: opening.settlement_amount.clone(), + }; + let log_index = FpVar::new_witness(cs.clone(), || Ok(F::from(w.log_index as u64)))?; + profile(&cs, "allocation", &mut mark); + + // ---- the relation ---- + // + // The chain of bindings is what makes this a proof rather than a + // satisfiability check: + // + // commitment -> token/recipient/amount + // header -> receiptsRoot -> MPT inclusion -> receipt -> log + // + // The commitment is the escrow's stored value, carried into the + // statement hash and therefore into the public signals. Opening it here + // is what turns "some Transfer happened" into "the Transfer this escrow + // committed to happened". + mirage_gadgets::commitment::open_with( + &opening, + &ctx.intent_commitment, + &Boolean::TRUE, + backend, + )?; + profile(&cs, "intent commitment", &mut mark); + + // The commitment's deployment/request/row context must be the same + // context whose statement hash the verifier checks. The commitment + // hash alone only authenticates the opening internally. + enforce_bytes_equal(&opening.instance_domain, &ctx.instance_domain)?; + enforce_bytes_equal(&opening.chain_id, &ctx.chain_id)?; + enforce_bytes_equal(&opening.escrow, &ctx.escrow)?; + enforce_bytes_equal(&opening.request_id, &ctx.request_id)?; + enforce_bytes_equal(&opening.row_index, &ctx.row_index)?; + profile(&cs, "context equality", &mut mark); + // + // The header supplies the root rather than the caller. Accepting a + // caller-supplied root would let a prover invent a trie containing + // whatever it liked. + let parsed = header::parse_authenticated_prefix(&header_bytes, &header_len, &Boolean::TRUE)?; + profile(&cs, "header parse", &mut mark); + + // Authenticate both header identity fields carried by the statement. + // Parsing a receiptsRoot is not useful unless the parsed header is the + // exact witness block selected by the verifier. + let header_digest = mirage_gadgets::keccak::keccak256_var_with( + &header_bytes, + &header_len, + &Boolean::TRUE, + backend, + )?; + for (got, want) in header_digest.iter().zip(ctx.witness_block_hash.iter()) { + UInt8::from_bits_le(got).enforce_equal(want)?; } + profile(&cs, "header hash", &mut mark); + let witness_number = fixed_be_value(&ctx.witness_block_number)?; + parsed.number.enforce_equal(&witness_number)?; + + // Settlement is valid only in the half-open/closed lease interval: + // bondStartBlock < txBlockNumber <= bondDeadline. + let bond_start = fixed_be_value(&ctx.bond_start_block)?; + let bond_deadline = fixed_be_value(&ctx.bond_deadline)?; + lt_u64(&bond_start, &parsed.number)?.enforce_equal(&Boolean::TRUE)?; + lt_u64(&bond_deadline, &parsed.number)?.enforce_equal(&Boolean::FALSE)?; + profile(&cs, "block/time checks", &mut mark); + + // The receipt is the MPT leaf's value, so inclusion binds the exact + // bytes the log walk then inspects. Without that link the relation + // would prove a Transfer in *some* receipt rather than one in this + // block's trie. + ConstructedLeafTraversal::verify_inclusion_with( + &parsed.receipts_root, + &key, + &key_len, + &receipt, + &receipt_len, + &nodes, + backend, + )?; + profile(&cs, "MPT traversal", &mut mark); + // The single-log variant: spec 20.3 requires production settlements be a + // direct `transfer()` call, whose receipt carries exactly one event. + // Skipping the walk to log `k` saves 16% of the receipt relation. + // + // The trade is that a receipt with any second event becomes unprovable, + // which the enclave's pre-settlement token review must enforce rather + // than the prover discovering it. See `receipt::log::sole_log`. + Erc20FixedLayout::verify(&receipt, &receipt_len, &log_index, &intent, &Boolean::TRUE)?; + profile(&cs, "receipt relation", &mut mark); + + // ---- statement hash ---- + // + // Recomputed from privately supplied context and checked against the + // two public signals. Every field is already public on-chain; hashing + // them down only shrinks the verifier. + let signals = statement::compute_with(&ctx, backend)?; + statement::enforce(&signals, &public_hi, &public_lo, &Boolean::TRUE)?; + profile(&cs, "statement hash", &mut mark); + + Ok(()) } fn enforce_bytes_equal( @@ -741,6 +788,14 @@ mod tests { assert!(!cs.is_satisfied().unwrap(), "{message}"); } + fn assert_rejected_batched(w: Witness, message: &str) { + let cs = ConstraintSystem::::new_ref(); + KeccacheckReceiptCircuit::prove(Bounds::default(), w) + .generate_constraints(cs.clone()) + .unwrap(); + assert!(!cs.is_satisfied().unwrap(), "{message}"); + } + /// The gap this closes: a prover must not be able to substitute the /// settlement details. /// @@ -835,4 +890,51 @@ mod tests { ); assert_eq!(cs.num_constraints(), 8_095_727); } + + #[test] + fn genuine_witness_satisfies_with_batched_keccacheck() { + use mirage_keccacheck_arkworks::batch::KeccacheckBatch; + + let cs = ConstraintSystem::::new_ref(); + let circuit = ReceiptCircuit::prove(Bounds::default(), fixture::genuine()); + let mut batch = KeccacheckBatch::new(cs.clone()); + generate_constraints_with_backend(circuit, cs.clone(), &mut batch).unwrap(); + let before_batch_verifier = cs.num_constraints(); + let result = batch.finish().unwrap(); + eprintln!( + "keccacheck relation: {} recorded, {} padded, {} non-GKR, {} GKR, {} total", + result.recorded, + result.padded, + before_batch_verifier, + result.profile.total, + cs.num_constraints(), + ); + assert_eq!(result.recorded, 38); + assert_eq!(result.padded, 64); + assert_eq!(cs.num_constraints(), 4_034_927); + assert!( + cs.is_satisfied().unwrap(), + "unsatisfied: {:?}", + cs.which_is_unsatisfied() + ); + } + + #[test] + fn batched_keccacheck_rejects_wrong_header_hash() { + let mut witness = fixture::genuine(); + witness.statement.witness_block_hash[0] ^= 1; + assert_rejected_batched( + witness, + "batched Keccacheck accepted a header digest mismatch", + ); + } + + #[test] + fn batched_setup_and_prove_shapes_match() { + let cs = ConstraintSystem::::new_ref(); + KeccacheckReceiptCircuit::setup(Bounds::default()) + .generate_constraints(cs.clone()) + .unwrap(); + assert_eq!(cs.num_constraints(), 4_034_927); + } } diff --git a/crates/relation/tests/mainnet.rs b/crates/relation/tests/mainnet.rs index 8990c74..d2570e6 100644 --- a/crates/relation/tests/mainnet.rs +++ b/crates/relation/tests/mainnet.rs @@ -12,7 +12,9 @@ use std::path::PathBuf; use ark_bn254::Fr; use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystem}; -use mirage_relation::{Bounds, IntentOpening, ReceiptCircuit, StatementContext, Witness}; +use mirage_relation::{ + Bounds, IntentOpening, KeccacheckReceiptCircuit, ReceiptCircuit, StatementContext, Witness, +}; use serde::Deserialize; #[derive(Deserialize)] @@ -200,6 +202,35 @@ fn satisfies_every_mainnet_fixture() { eprintln!("all {} mainnet fixtures satisfied", d.fixtures.len()); } +/// Fast integration gate for the experimental batched-Keccak circuit. Use the +/// deepest collected proof so branch/extension chaining is exercised without +/// paying for 100 GKR satisfaction scans on every optimization iteration. +#[test] +fn keccacheck_satisfies_a_deep_mainnet_fixture() { + let Some(d) = load() else { + return; + }; + let b = bounds(&d); + let fixture = d + .fixtures + .iter() + .max_by_key(|fixture| fixture.depth) + .expect("nonempty fixture set"); + let cs = ConstraintSystem::::new_ref(); + KeccacheckReceiptCircuit::prove(b, witness(fixture)) + .generate_constraints(cs.clone()) + .expect("synthesis"); + assert!( + cs.is_satisfied().unwrap_or(false), + "Keccacheck failed {} (block {}, tx {}, depth {}): {:?}", + fixture.tx_hash, + fixture.block_number, + fixture.tx_index, + fixture.depth, + cs.which_is_unsatisfied().ok().flatten() + ); +} + /// The dataset must cover more than one shape, or it is not testing variety. #[test] fn dataset_is_varied() { diff --git a/experiments/keccacheck-arkworks/Cargo.lock b/experiments/keccacheck-arkworks/Cargo.lock index 158b1d3..bdb60e8 100644 --- a/experiments/keccacheck-arkworks/Cargo.lock +++ b/experiments/keccacheck-arkworks/Cargo.lock @@ -20,37 +20,61 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "ark-bn254" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" dependencies = [ - "ark-ec", - "ark-ff", - "ark-r1cs-std", - "ark-std", + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-r1cs-std 0.5.0", + "ark-std 0.5.0", +] + +[[package]] +name = "ark-bn254" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-r1cs-std 0.6.0", + "ark-std 0.6.0", ] [[package]] name = "ark-crypto-primitives" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0c292754729c8a190e50414fd1a37093c786c709899f29c9f7daccecfa855e" +checksum = "31b3409b1846fe459d19c95df039481575ac6d5842ae63858ad75cc31219bfc1" dependencies = [ "ahash", "ark-crypto-primitives-macros", - "ark-ec", - "ark-ff", - "ark-relations", - "ark-serialize", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", + "ark-serialize 0.6.0", "ark-snark", - "ark-std", + "ark-std 0.6.0", "blake2", + "blake3", "derivative", "digest", "fnv", "merlin", + "num-bigint", "rayon", "sha2", ] @@ -73,14 +97,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", - "ark-ff", - "ark-poly", - "ark-serialize", - "ark-std", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.5", + "itertools 0.13.0", + "num-bigint", + "num-integer", + "num-traits", + "zeroize", +] + +[[package]] +name = "ark-ec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", "educe", "fnv", - "hashbrown", - "itertools", + "hashbrown 0.17.1", + "itertools 0.14.0", "num-bigint", "num-integer", "num-traits", @@ -94,17 +139,34 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" dependencies = [ - "ark-ff-asm", - "ark-ff-macros", - "ark-serialize", - "ark-std", + "ark-ff-asm 0.5.0", + "ark-ff-macros 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", "arrayvec", "digest", "educe", - "itertools", + "itertools 0.13.0", "num-bigint", "num-traits", "paste", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7a806ac6c8307b929df4645776290a50ee2aac754ad09d8bdf73391309e43af" +dependencies = [ + "ark-ff-asm 0.6.0", + "ark-ff-macros 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "digest", + "educe", + "num-bigint", + "num-traits", "rayon", "zeroize", ] @@ -119,6 +181,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ark-ff-asm" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1479009684adc073dff49a1025d3a7065b317a9ead25aaaca38cdc70058ba8a2" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "ark-ff-macros" version = "0.5.0" @@ -132,19 +204,33 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ark-ff-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "ark-groth16" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88f1d0f3a534bb54188b8dcc104307db6c56cdae574ddc3212aec0625740fc7e" +checksum = "a293328aa422e65527e285614ce5d1dceb0bd7b8b18d18b1b63191ee1f74cb41" dependencies = [ "ark-crypto-primitives", - "ark-ec", - "ark-ff", - "ark-poly", - "ark-relations", - "ark-serialize", - "ark-std", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-relations 0.6.0", + "ark-serialize 0.6.0", + "ark-snark", + "ark-std 0.6.0", "rayon", ] @@ -155,12 +241,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" dependencies = [ "ahash", - "ark-ff", - "ark-serialize", - "ark-std", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", "educe", "fnv", - "hashbrown", + "hashbrown 0.15.5", +] + +[[package]] +name = "ark-poly" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", "rayon", ] @@ -170,10 +271,10 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" dependencies = [ - "ark-ec", - "ark-ff", - "ark-relations", - "ark-std", + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-relations 0.5.1", + "ark-std 0.5.0", "educe", "num-bigint", "num-integer", @@ -181,30 +282,78 @@ dependencies = [ "tracing", ] +[[package]] +name = "ark-r1cs-std" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291f1c6628bfcac79b0dc2adbe401aa9100e2e96daa971645e0b18fc94de9a98" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-relations 0.6.0", + "ark-std 0.6.0", + "educe", + "itertools 0.14.0", + "num-bigint", + "num-integer", + "num-traits", + "tracing", +] + [[package]] name = "ark-relations" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec46ddc93e7af44bcab5230937635b06fb5744464dd6a7e7b083e80ebd274384" dependencies = [ - "ark-ff", - "ark-std", + "ark-ff 0.5.0", + "ark-std 0.5.0", "tracing", "tracing-subscriber 0.2.25", ] +[[package]] +name = "ark-relations" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4c11c797a64b8a23e22bf4e77bf582ac27bb21395e3183a9a506ba2561e9f9" +dependencies = [ + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "foldhash", + "indexmap 2.14.1", + "rayon", + "tracing", + "tracing-subscriber 0.3.23", +] + [[package]] name = "ark-serialize" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" dependencies = [ - "ark-serialize-derive", - "ark-std", + "ark-serialize-derive 0.5.0", + "ark-std 0.5.0", "arrayvec", "digest", "num-bigint", +] + +[[package]] +name = "ark-serialize" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b" +dependencies = [ + "ark-serialize-derive 0.6.0", + "ark-std 0.6.0", + "digest", + "num-bigint", "rayon", + "serde_with", ] [[package]] @@ -218,16 +367,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ark-serialize-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f153690697a2b91e5e1251ff98411ee5371500a111a0fd317a70e588eb300f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "ark-snark" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d368e2848c2d4c129ce7679a7d0d2d612b6a274d3ea6a13bad4445d61b381b88" +checksum = "5bdb461d2be9b2bd6f303c79fffc89f5858790a7b4d33257bca3178e2c071fb9" dependencies = [ - "ark-ff", - "ark-relations", - "ark-serialize", - "ark-std", + "ark-ff 0.6.0", + "ark-relations 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", ] [[package]] @@ -235,6 +395,16 @@ name = "ark-std" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "ark-std" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155" dependencies = [ "num-traits", "rand", @@ -253,6 +423,18 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "blake2" version = "0.10.6" @@ -284,6 +466,21 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + [[package]] name = "byteorder" version = "1.5.0" @@ -306,6 +503,18 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -345,6 +554,12 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -404,6 +619,46 @@ dependencies = [ "typenum", ] +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + [[package]] name = "derivative" version = "2.2.0" @@ -426,6 +681,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "educe" version = "0.6.0" @@ -464,6 +725,12 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -476,6 +743,36 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -491,9 +788,9 @@ name = "gkr" version = "0.1.0" source = "git+https://github.com/reilabs/keccacheck.git?rev=15f00e3da5622f1c7155b02d1f9c00bd2416c282#15f00e3da5622f1c7155b02d1f9c00bd2416c282" dependencies = [ - "ark-bn254", - "ark-ec", - "ark-ff", + "ark-bn254 0.5.0", + "ark-ec 0.5.0", + "ark-ff 0.5.0", "ciborium", "const-oid", "hex", @@ -515,6 +812,12 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.15.5" @@ -524,6 +827,15 @@ dependencies = [ "allocator-api2", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", +] + [[package]] name = "hex" version = "0.4.3" @@ -536,6 +848,53 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + [[package]] name = "itertools" version = "0.13.0" @@ -545,6 +904,85 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", +] + +[[package]] +name = "jiff-static" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "keccak" version = "0.1.6" @@ -572,6 +1010,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "merlin" version = "3.0.0" @@ -584,21 +1028,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "mirage-gadgets" +version = "0.1.0" +dependencies = [ + "ark-ff 0.6.0", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "mirage-keccacheck-arkworks" version = "0.1.0" dependencies = [ - "ark-bn254", - "ark-ff", + "ark-bn254 0.5.0", + "ark-bn254 0.6.0", + "ark-ff 0.6.0", "ark-groth16", - "ark-r1cs-std", - "ark-relations", - "ark-serialize", + "ark-r1cs-std 0.6.0", + "ark-relations 0.6.0", + "ark-serialize 0.6.0", "ark-snark", - "ark-std", + "ark-std 0.6.0", "blake3", "gkr", "keccak", + "mirage-gadgets", ] [[package]] @@ -620,6 +1076,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.47" @@ -656,6 +1118,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -729,6 +1212,56 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "serde" version = "1.0.229" @@ -759,6 +1292,39 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_with" +version = "3.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.1", + "jiff", + "schemars 0.9.0", + "schemars 1.2.2", + "serde_core", + "serde_json", + "time", +] + [[package]] name = "sha2" version = "0.10.9" @@ -785,6 +1351,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.0" @@ -836,7 +1408,16 @@ version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", ] [[package]] @@ -850,6 +1431,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + [[package]] name = "thread_local" version = "1.1.10" @@ -859,6 +1451,51 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tracing" version = "0.1.44" @@ -898,7 +1535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee40835db14ddd1e3ba414292272eddde9dad04d3d4b65509656414d1c42592f" dependencies = [ "smallvec", - "thiserror", + "thiserror 1.0.69", "tracing", "tracing-subscriber 0.3.23", ] @@ -961,12 +1598,110 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1015,3 +1750,9 @@ dependencies = [ "quote", "syn 2.0.119", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/experiments/keccacheck-arkworks/Cargo.toml b/experiments/keccacheck-arkworks/Cargo.toml index 7d7702c..1f1920c 100644 --- a/experiments/keccacheck-arkworks/Cargo.toml +++ b/experiments/keccacheck-arkworks/Cargo.toml @@ -6,17 +6,21 @@ publish = false license = "Apache-2.0" [dependencies] -ark-bn254 = { version = "0.5", features = ["std"] } -ark-ff = { version = "0.5", features = ["asm"] } -ark-groth16 = { version = "0.5", features = ["parallel"] } -ark-r1cs-std = { version = "0.5", features = ["std"] } -ark-relations = { version = "0.5", features = ["std"] } -ark-serialize = { version = "0.5", features = ["std"] } -ark-snark = "0.5" -ark-std = { version = "0.5", features = ["std"] } +ark-bn254 = { version = "0.6", features = ["std"] } +ark-ff = { version = "0.6", features = ["asm"] } +ark-groth16 = { version = "0.6", features = ["parallel"] } +ark-r1cs-std = { version = "0.6", features = ["std"] } +ark-relations = { version = "0.6", features = ["std"] } +ark-serialize = { version = "0.6", features = ["std"] } +ark-snark = "0.6" +ark-std = { version = "0.6", features = ["std"] } +# The pinned native prover has not migrated to arkworks 0.6 yet. This alias is +# confined to the native witness boundary; all circuit variables use 0.6. +ark-bn254-05 = { package = "ark-bn254", version = "0.5", features = ["std"] } blake3 = "1.8" gkr = { git = "https://github.com/reilabs/keccacheck.git", rev = "15f00e3da5622f1c7155b02d1f9c00bd2416c282", default-features = false } keccak = "0.1.5" +mirage-gadgets = { path = "../../crates/gadgets" } [profile.release] opt-level = 3 @@ -25,4 +29,3 @@ codegen-units = 1 [profile.dev] opt-level = 1 - diff --git a/experiments/keccacheck-arkworks/README.md b/experiments/keccacheck-arkworks/README.md index e6fa302..39be4f3 100644 --- a/experiments/keccacheck-arkworks/README.md +++ b/experiments/keccacheck-arkworks/README.md @@ -4,11 +4,18 @@ This excluded standalone crate ports the recursive Keccacheck verifier from gnark to arkworks R1CS. It deliberately consumes the native proof produced by Reilabs' Rust `gkr` crate at pinned commit `15f00e3da5622f1c7155b02d1f9c00bd2416c282` with WHIR disabled, matching the -reference's direct input-bit verification mode. - -The experiment is isolated because the reference currently uses arkworks 0.5 -while Mirage uses 0.6. It is not production code and does not alter Mirage's -existing Keccak gadget or relation. +reference's direct input-bit verification mode. The circuit side now uses +arkworks 0.6, matching Mirage; the pinned native Rust prover remains on 0.5 and +crosses that boundary through canonical BN254 scalar values. + +It is still experimental, but the integration branch now supplies a deferred +backend used by the real Mirage relation and an alternate Rust prover API. + +The runtime path is Rust-only. The gnark source is neither linked nor executed; +it was used as a readable reference for the circuit formulas. Cargo currently +fetches the pinned Rust `gkr` source at build time, so a production enclave +build should vendor that dependency, but the resulting enclave does not need +Go or network access. Upstream Keccacheck is licensed Apache-2.0. The verifier formulas and Poseidon2 transcript parameters ported here retain that provenance; see diff --git a/experiments/keccacheck-arkworks/RESULTS.md b/experiments/keccacheck-arkworks/RESULTS.md index 88e0435..dd44328 100644 --- a/experiments/keccacheck-arkworks/RESULTS.md +++ b/experiments/keccacheck-arkworks/RESULTS.md @@ -2,7 +2,7 @@ Reference: Reilabs Keccacheck commit [`15f00e3da5622f1c7155b02d1f9c00bd2416c282`](https://github.com/reilabs/keccacheck/tree/15f00e3da5622f1c7155b02d1f9c00bd2416c282), -with WHIR disabled. Measurements are from this branch's arkworks 0.5 R1CS port. +with WHIR disabled. Measurements are from this branch's arkworks 0.6 R1CS port. They use native proof generation followed by constraint synthesis and `is_satisfied`; no Groth16 setup was run during the optimization loop. @@ -14,37 +14,37 @@ booleanity constraints and 153,600 permutation constraints. | permutations | GKR proof Fr elements | proof bytes | arkworks GKR constraints | direct constraints | direct / GKR | |---:|---:|---:|---:|---:|---:| -| 1 | 6,255 | 200,160 | 987,628 | 155,200 | 0.157x | -| 2 | 6,809 | 217,888 | 1,090,792 | 310,400 | 0.285x | -| 4 | 7,363 | 235,616 | 1,194,930 | 620,800 | 0.520x | -| 8 | 7,917 | 253,344 | 1,308,423 | 1,241,600 | 0.949x | -| 16 | 8,471 | 271,072 | 1,440,626 | 2,483,200 | 1.724x | -| 32 | 9,025 | 288,800 | 1,610,249 | 4,966,400 | 3.084x | -| 64 | 9,579 | 306,528 | 1,854,712 | 9,932,800 | 5.355x | -| 128 | 10,133 | 324,256 | 2,248,855 | 19,865,600 | 8.834x | +| 1 | 6,255 | 200,160 | 989,228 | 155,200 | 0.157x | +| 2 | 6,809 | 217,888 | 1,093,992 | 310,400 | 0.284x | +| 4 | 7,363 | 235,616 | 1,201,330 | 620,800 | 0.517x | +| 8 | 7,917 | 253,344 | 1,321,223 | 1,241,600 | 0.940x | +| 16 | 8,471 | 271,072 | 1,466,226 | 2,483,200 | 1.694x | +| 32 | 9,025 | 288,800 | 1,661,449 | 4,966,400 | 2.989x | +| 64 | 9,579 | 306,528 | 1,957,112 | 9,932,800 | 5.075x | The crossover in this port is between 8 and 16 permutations. Keccacheck is a regression for small isolated hashes and becomes compelling only when many permutations share one GKR proof. -At 64 permutations, the 1,854,712 constraints break down as follows: +At 64 independently witnessed permutations, the 1,957,112 constraints break +down as follows: | component | constraints | |---|---:| -| input Boolean allocation | 102,400 | +| input and output Boolean allocation | 204,800 | | output Fiat-Shamir binding | 88,800 | | output word/bit reduction | 10,083 | | 24 Keccak round reductions | 1,546,910 | | final input binding | 106,519 | -The upstream README reports 638,682 gnark constraints for one permutation, -791,597 for eight, and 1,379,176 for 128. This arkworks port is respectively -55%, 65%, and 63% larger. The port intentionally uses ordinary `FpVar` +The upstream README reports 638,682 gnark constraints for one permutation and +791,597 for eight. This arkworks port is respectively 55% and 67% larger. The +port intentionally uses ordinary `FpVar` operations with no custom compiler optimization pass, so closing that gap is a separate optimization opportunity; the present numbers are the safe comparison for Mirage's backend. -## Projection for the universal circuit +## Measured universal-circuit integration The universal depth-seven relation is 8,095,727 constraints. Its bounded Keccak calls compile 38 Keccak-f permutations: @@ -55,20 +55,20 @@ Keccak calls compile 38 Keccak-f permutations: - six MPT ancestors: 23; - constructed leaf: 4. -Those permutation cores cost `38 * 153,600 = 5,836,800` constraints. A fixed -64-way Keccacheck batch costs 1,854,712 in this standalone model. Replacing only -the permutation cores therefore gives the preliminary projection: +The integrated backend allocates each real output state as Boolean witnesses, +preserves the existing sponge chaining and variable-length state selection, +and pads the batch with 26 constant zero-input permutations. The complete +genuine relation synthesized and satisfied with this measured breakdown: ```text -8,095,727 - 5,836,800 + 1,854,712 = 4,113,639 constraints +non-GKR relation constraints: 2,330,003 +64-way GKR verifier: 1,704,924 +complete relation: 4,034,927 ``` -That is 3,982,088 fewer constraints, or 49.2% of the whole universal relation. -The standalone input-bit allocation is a reasonable placeholder for the output -bits that integration must expose: caller input bits can be reused, while GKR -outputs need Boolean variables for sponge chaining and digest extraction. The -exact integrated count may move by roughly this 102,400-constraint boundary and -must be measured on an integration branch. +This is 4,060,800 fewer constraints than the 8,095,727 direct-Keccak relation, +a measured 50.2% reduction. The integrated verifier is smaller than the fully +witnessed standalone 64-way case because the 26 padding states are constants. ## Correctness checks @@ -79,23 +79,26 @@ must be measured on an integration branch. - A native Keccacheck proof satisfies the full 24-round arkworks verifier. - Mutating either a proof element or an output word makes the R1CS unsatisfied. +- The complete genuine Mirage relation satisfies with 38 recorded and 64 + padded permutations. +- The batched relation rejects an incorrect authenticated header hash. +- The deepest fixture in the 100-case mainnet dataset satisfies the batched + circuit as a fast real-data integration gate. - All tests use the reference's corrected late-round Keccak constants. ## Feasibility and remaining work -This is promising for the universal circuit, but it is not yet drop-in code. - -1. Refactor the verifier to accept and return caller-owned Boolean state bits, - rather than allocating standalone `u64` witnesses. -2. Flatten every sponge invocation into one 64-way batch, including inactive - padding permutations, while preserving each sponge's chaining and - variable-length state selection. -3. Differential-test the integrated circuit against every existing relation - fixture and mutation test. -4. Audit the Poseidon-derived output challenge and transcript domain separation. -5. Investigate the roughly 60% arkworks overhead relative to gnark, principally +The integration now has an alternate `KeccacheckReceiptCircuit` and Rust +`setup_keccacheck`/`prove_keccacheck` APIs. Remaining finalist work is: + +1. Run the complete existing mutation and mainnet-fixture suites through the + batched circuit, rather than only the genuine fixture and header mutation. +2. Audit the Poseidon-derived output challenge and transcript domain separation. +3. Vendor or migrate the upstream Rust GKR prover to arkworks 0.6, removing the + temporary dual-version scalar conversion. +4. Investigate the arkworks overhead relative to gnark, principally in the round verifier and transcript expression lowering. -6. Only after the integrated count is stable, run one full Groth16 setup/prove/ +5. Only after those checks, run one full Groth16 setup/prove/ verify benchmark and evaluate the larger witness-generation path. The GKR proof occupies about 307 KiB at 64 permutations, but it is private diff --git a/experiments/keccacheck-arkworks/src/batch.rs b/experiments/keccacheck-arkworks/src/batch.rs new file mode 100644 index 0000000..d779043 --- /dev/null +++ b/experiments/keccacheck-arkworks/src/batch.rs @@ -0,0 +1,160 @@ +//! Deferred Keccak-f backend for integration with Mirage's sponge gadgets. + +use crate::verifier::{ + VerificationProfile, make_witness_from_data, proof_elements, verify_boolean_batch, +}; +use ark_bn254::Fr; +use ark_ff::Zero; +use ark_r1cs_std::{GR1CSVar, alloc::AllocVar, boolean::Boolean}; +use ark_relations::gr1cs::{ConstraintSystemRef, SynthesisError}; +use mirage_gadgets::keccak::{PermutationBackend, State}; + +pub struct BatchResult { + pub recorded: usize, + pub padded: usize, + pub profile: VerificationProfile, +} + +pub struct KeccacheckBatch { + cs: ConstraintSystemRef, + inputs: Vec>, + outputs: Vec>, + native_inputs: Option>, +} + +impl KeccacheckBatch { + pub fn new(cs: ConstraintSystemRef) -> Self { + Self { + cs, + inputs: Vec::new(), + outputs: Vec::new(), + native_inputs: Some(Vec::new()), + } + } + + pub fn finish(mut self) -> Result { + let recorded = self.inputs.len(); + assert!(recorded > 0, "cannot prove an empty Keccak batch"); + let padded = recorded.next_power_of_two(); + while self.inputs.len() < padded { + let input_words = [0u64; 25]; + let mut output_words = input_words; + keccak::f1600(&mut output_words); + self.inputs.push(constant_state(&input_words)); + self.outputs.push(constant_state(&output_words)); + if let Some(native) = &mut self.native_inputs { + native.push(input_words); + } + } + + let proof = match &self.native_inputs { + Some(native) => { + let data = native + .iter() + .flat_map(|state| state.iter().copied()) + .collect::>(); + make_witness_from_data(&data).proof + } + None => vec![Fr::zero(); proof_elements(padded)], + }; + let input_bits = transpose_states(&self.inputs); + let output_bits = transpose_states(&self.outputs); + let profile = verify_boolean_batch(self.cs, &proof, &input_bits, &output_bits)?; + Ok(BatchResult { + recorded, + padded, + profile, + }) + } +} + +impl PermutationBackend for KeccacheckBatch { + fn permute(&mut self, state: State) -> Result, SynthesisError> { + let native_input = state_words(&state); + let native_output = native_input.map(|mut words| { + keccak::f1600(&mut words); + words + }); + if let Some(inputs) = &mut self.native_inputs { + match native_input { + Some(words) => inputs.push(words), + None => self.native_inputs = None, + } + } + + let mut lanes = Vec::with_capacity(25); + for lane in 0..25 { + let mut bits = Vec::with_capacity(64); + for bit in 0..64 { + bits.push(Boolean::new_witness(self.cs.clone(), || { + native_output + .map(|words| (words[lane] >> bit) & 1 == 1) + .ok_or(SynthesisError::AssignmentMissing) + })?); + } + lanes.push(bits.try_into().map_err(|_| SynthesisError::Unsatisfiable)?); + } + let output: State = lanes + .try_into() + .map_err(|_| SynthesisError::Unsatisfiable)?; + self.inputs.push(state); + self.outputs.push(output.clone()); + Ok(output) + } +} + +fn state_words(state: &State) -> Option<[u64; 25]> { + let mut words = [0u64; 25]; + for lane in 0..25 { + for bit in 0..64 { + if state[lane][bit].value().ok()? { + words[lane] |= 1u64 << bit; + } + } + } + Some(words) +} + +fn constant_state(words: &[u64; 25]) -> State { + core::array::from_fn(|lane| { + core::array::from_fn(|bit| Boolean::constant((words[lane] >> bit) & 1 == 1)) + }) +} + +fn transpose_states(states: &[State]) -> Vec> { + let mut bits = Vec::with_capacity(states.len() * 25 * 64); + for lane in 0..25 { + for state in states { + bits.extend(state[lane].iter().cloned()); + } + } + bits +} + +#[cfg(test)] +mod tests { + use super::*; + use ark_relations::gr1cs::ConstraintSystem; + + fn witness_state(cs: ConstraintSystemRef, seed: u64) -> State { + core::array::from_fn(|lane| { + let word = seed.wrapping_add(lane as u64); + core::array::from_fn(|bit| { + Boolean::new_witness(cs.clone(), || Ok((word >> bit) & 1 == 1)).unwrap() + }) + }) + } + + #[test] + fn caller_owned_states_are_verified_and_padding_is_constant() { + let cs = ConstraintSystem::new_ref(); + let mut batch = KeccacheckBatch::new(cs.clone()); + for seed in [7, 11, 19] { + let _ = batch.permute(witness_state(cs.clone(), seed)).unwrap(); + } + let result = batch.finish().unwrap(); + assert_eq!(result.recorded, 3); + assert_eq!(result.padded, 4); + assert!(cs.is_satisfied().unwrap()); + } +} diff --git a/experiments/keccacheck-arkworks/src/direct.rs b/experiments/keccacheck-arkworks/src/direct.rs index 1a1ab4b..11c8650 100644 --- a/experiments/keccacheck-arkworks/src/direct.rs +++ b/experiments/keccacheck-arkworks/src/direct.rs @@ -5,7 +5,7 @@ use ark_ff::PrimeField; use ark_r1cs_std::{alloc::AllocVar, boolean::Boolean}; -use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError}; +use ark_relations::gr1cs::{ConstraintSystemRef, SynthesisError}; pub type StateVar = [[Boolean; 64]; 25]; @@ -138,8 +138,8 @@ pub fn synthesize_batch( mod tests { use super::*; use ark_bn254::Fr; - use ark_r1cs_std::R1CSVar; - use ark_relations::r1cs::ConstraintSystem; + use ark_r1cs_std::GR1CSVar; + use ark_relations::gr1cs::ConstraintSystem; #[test] fn direct_control_matches_mirage_cost() { diff --git a/experiments/keccacheck-arkworks/src/lib.rs b/experiments/keccacheck-arkworks/src/lib.rs index c13c41a..36fdc6d 100644 --- a/experiments/keccacheck-arkworks/src/lib.rs +++ b/experiments/keccacheck-arkworks/src/lib.rs @@ -4,6 +4,7 @@ //! This crate ports only the verifier that would replace Mirage's direct //! Keccak-f constraints. +pub mod batch; pub mod direct; pub mod poseidon2; mod poseidon2_constants; diff --git a/experiments/keccacheck-arkworks/src/main.rs b/experiments/keccacheck-arkworks/src/main.rs index 0886a60..8a7c3fa 100644 --- a/experiments/keccacheck-arkworks/src/main.rs +++ b/experiments/keccacheck-arkworks/src/main.rs @@ -1,5 +1,5 @@ use ark_bn254::Fr; -use ark_relations::r1cs::ConstraintSystem; +use ark_relations::gr1cs::ConstraintSystem; use mirage_keccacheck_arkworks::verifier::{make_witness, verify_witness_profile}; use std::{env, process::ExitCode, time::Instant}; diff --git a/experiments/keccacheck-arkworks/src/poseidon2.rs b/experiments/keccacheck-arkworks/src/poseidon2.rs index 5a0b6eb..e7686e8 100644 --- a/experiments/keccacheck-arkworks/src/poseidon2.rs +++ b/experiments/keccacheck-arkworks/src/poseidon2.rs @@ -143,19 +143,24 @@ impl Default for SpongeVar { #[cfg(test)] mod tests { use super::*; - use ark_r1cs_std::{R1CSVar, alloc::AllocVar}; - use ark_relations::r1cs::ConstraintSystem; + use ark_r1cs_std::{GR1CSVar, alloc::AllocVar}; + use ark_relations::gr1cs::ConstraintSystem; #[test] fn permutation_matches_upstream_native() { let cs = ConstraintSystem::::new_ref(); let input: [Fr; 16] = core::array::from_fn(|i| Fr::from(i as u64)); - let mut expected = input; + let mut expected: [ark_bn254_05::Fr; 16] = + core::array::from_fn(|i| ark_bn254_05::Fr::from(i as u64)); gkr::poseidon::permute_16(&mut expected); let mut state: [FpVar; 16] = core::array::from_fn(|i| FpVar::new_witness(cs.clone(), || Ok(input[i])).unwrap()); permute_16(&mut state); - let got: Vec = state.iter().map(|x| x.value().unwrap()).collect(); + let got = state + .iter() + .map(|x| x.value().unwrap().to_string()) + .collect::>(); + let expected = expected.iter().map(ToString::to_string).collect::>(); assert_eq!(got, expected); assert!(cs.is_satisfied().unwrap()); } diff --git a/experiments/keccacheck-arkworks/src/verifier.rs b/experiments/keccacheck-arkworks/src/verifier.rs index 94a19b5..5a6c219 100644 --- a/experiments/keccacheck-arkworks/src/verifier.rs +++ b/experiments/keccacheck-arkworks/src/verifier.rs @@ -4,9 +4,11 @@ use crate::poseidon2::SpongeVar; use ark_bn254::Fr; +use ark_bn254_05::Fr as Fr05; use ark_ff::{MontFp, One, Zero}; use ark_r1cs_std::{alloc::AllocVar, boolean::Boolean, eq::EqGadget, fields::fp::FpVar}; -use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError}; +use ark_relations::gr1cs::{ConstraintSystemRef, SynthesisError}; +use std::str::FromStr; const HALF: Fr = MontFp!("10944121435919637611123202872628637544274182200208017171849102093287904247809"); @@ -390,13 +392,13 @@ fn verify_round( Ok((vrs_a, iota)) } -pub fn derive_r_native(output: &[u64], log_instances: usize) -> Vec { +pub fn derive_r_native(output: &[u64], log_instances: usize) -> Vec { if log_instances == 0 { return Vec::new(); } let mut sponge = gkr::transcript::Sponge::new(); for value in output { - sponge.absorb(Fr::from(*value)); + sponge.absorb(Fr05::from(*value)); } (0..log_instances).map(|_| sponge.squeeze()).collect() } @@ -443,19 +445,12 @@ pub fn verify_witness_profile( let instances = witness.input.len() / 25; assert!(instances.is_power_of_two()); assert_eq!(witness.output.len(), 25 * instances); - let log_instances = instances.ilog2() as usize; - let num_vars = log_instances + 6; let proof = witness .proof .iter() .map(|value| FpVar::new_witness(cs.clone(), || Ok(*value))) .collect::, _>>()?; - let output = witness - .output - .iter() - .map(|value| FpVar::new_witness(cs.clone(), || Ok(Fr::from(*value)))) - .collect::, _>>()?; let mut input_bits = Vec::with_capacity(witness.input.len() * 64); for value in &witness.input { for bit in 0..64 { @@ -464,8 +459,90 @@ pub fn verify_witness_profile( })?); } } - let input_bits = input_bits.into_iter().map(FpVar::from).collect::>(); + let mut output_bits = Vec::with_capacity(witness.output.len() * 64); + for value in &witness.output { + for bit in 0..64 { + output_bits.push(Boolean::new_witness(cs.clone(), || { + Ok((value >> bit) & 1 == 1) + })?); + } + } let after_allocation = cs.num_constraints(); + verify_allocated( + cs, + proof, + &input_bits, + &output_bits, + instances, + start, + after_allocation, + ) +} + +/// Verify a Keccacheck proof against state bits owned by the calling circuit. +/// +/// Both bit slices use `[lane][instance][little-endian bit]` order. This is the +/// integration boundary needed by Mirage's sponge: verified output bits can be +/// reused directly as the next permutation's input state or as digest bits. +pub fn verify_boolean_batch( + cs: ConstraintSystemRef, + proof_values: &[Fr], + input_bits: &[Boolean], + output_bits: &[Boolean], +) -> Result { + assert_eq!(input_bits.len(), output_bits.len()); + assert_eq!(input_bits.len() % (25 * 64), 0); + let instances = input_bits.len() / (25 * 64); + assert!(instances.is_power_of_two()); + let start = cs.num_constraints(); + let proof = proof_values + .iter() + .map(|value| FpVar::new_witness(cs.clone(), || Ok(*value))) + .collect::, _>>()?; + let after_allocation = cs.num_constraints(); + verify_allocated( + cs, + proof, + input_bits, + output_bits, + instances, + start, + after_allocation, + ) +} + +fn verify_allocated( + cs: ConstraintSystemRef, + proof: Vec>, + input_booleans: &[Boolean], + output_booleans: &[Boolean], + instances: usize, + start: usize, + after_allocation: usize, +) -> Result { + let log_instances = instances.ilog2() as usize; + let num_vars = log_instances + 6; + let input_bits = input_booleans + .iter() + .cloned() + .map(FpVar::from) + .collect::>(); + let output_bits = output_booleans + .iter() + .cloned() + .map(FpVar::from) + .collect::>(); + let powers = (0..64).map(|i| Fr::from(1u64 << i)).collect::>(); + let output = output_bits + .chunks_exact(64) + .map(|bits| { + bits.iter() + .zip(&powers) + .fold(FpVar::Constant(Fr::zero()), |acc, (bit, power)| { + acc + bit * *power + }) + }) + .collect::>(); let r = derive_r_var(&output, log_instances); let after_output_binding = cs.num_constraints(); @@ -552,6 +629,18 @@ pub fn verify_witness_profile( pub fn make_witness(instances: usize) -> Witness { assert!(instances.is_power_of_two()); let data = (0..instances * 25).map(|i| i as u64).collect::>(); + make_witness_from_data(&data) +} + +pub fn proof_elements(instances: usize) -> usize { + assert!(instances.is_power_of_two()); + 6_255 + 554 * instances.ilog2() as usize +} + +pub fn make_witness_from_data(data: &[u64]) -> Witness { + assert_eq!(data.len() % 25, 0); + let instances = data.len() / 25; + assert!(instances.is_power_of_two()); let mut output = vec![0u64; instances * 25]; for instance in 0..instances { let mut state: [u64; 25] = core::array::from_fn(|lane| data[instance * 25 + lane]); @@ -561,8 +650,15 @@ pub fn make_witness(instances: usize) -> Witness { } } let r = derive_r_native(&output, instances.ilog2() as usize); - let (proof, input, proved_output) = gkr::keccacheck_og::prover::prove(&data, r); + let (proof_05, input, proved_output) = gkr::keccacheck_og::prover::prove(&data, r); assert_eq!(proved_output, output); + let proof = proof_05 + .iter() + .map(|value| { + Fr::from_str(&value.to_string()) + .expect("BN254 scalar converts across arkworks versions") + }) + .collect(); Witness { proof, input, @@ -573,7 +669,7 @@ pub fn make_witness(instances: usize) -> Witness { #[cfg(test)] mod tests { use super::*; - use ark_relations::r1cs::ConstraintSystem; + use ark_relations::gr1cs::ConstraintSystem; #[test] fn one_permutation_proof_satisfies() { @@ -604,4 +700,11 @@ mod tests { verify_witness(cs.clone(), &witness).unwrap(); assert!(!cs.is_satisfied().unwrap()); } + + #[test] + fn proof_length_formula_matches_native_prover() { + for instances in [1, 2, 4, 8, 16, 32, 64, 128] { + assert_eq!(make_witness(instances).proof.len(), proof_elements(instances)); + } + } } From 6237592ae7cc135264be616cc778ab816e80e36c Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Wed, 2 Sep 2026 21:59:27 -0400 Subject: [PATCH 18/22] bench: measure integrated Keccacheck prover --- crates/prover/src/bin/measure.rs | 55 +++++++++++++++++----- experiments/keccacheck-arkworks/RESULTS.md | 27 ++++++++++- 2 files changed, 68 insertions(+), 14 deletions(-) diff --git a/crates/prover/src/bin/measure.rs b/crates/prover/src/bin/measure.rs index ae4bad9..57d75ee 100644 --- a/crates/prover/src/bin/measure.rs +++ b/crates/prover/src/bin/measure.rs @@ -8,6 +8,7 @@ //! Run: //! ```sh //! RAYON_NUM_THREADS=16 cargo run -p mirage-prover --release --bin measure +//! RAYON_NUM_THREADS=16 cargo run -p mirage-prover --release --bin measure -- --keccacheck //! ``` //! //! Peak RSS is read from `/proc/self/status` `VmHWM`, the same metric the @@ -22,7 +23,9 @@ use ark_serialize::CanonicalSerialize; use ark_snark::SNARK; use ark_std::rand::SeedableRng; -use mirage_relation::{fixture, Bounds, ReceiptCircuit, MEASUREMENT_SCOPE}; +use mirage_relation::{ + fixture, Bounds, KeccacheckReceiptCircuit, ReceiptCircuit, MEASUREMENT_SCOPE, +}; /// Peak resident set size in bytes, from `VmHWM`. fn peak_rss() -> u64 { @@ -42,10 +45,19 @@ fn gb(bytes: u64) -> f64 { } fn main() { + let keccacheck = std::env::args().any(|arg| arg == "--keccacheck"); let threads = std::env::var("RAYON_NUM_THREADS").unwrap_or_else(|_| "default".into()); let bounds = Bounds::default(); println!("scope: {MEASUREMENT_SCOPE}"); + println!( + "circuit: {}", + if keccacheck { + "KeccacheckReceiptCircuit" + } else { + "ReceiptCircuit" + } + ); println!( "bounds: node {} B, key {} B, receipt {} B, depth {}", bounds.node_bytes, bounds.key_bytes, bounds.receipt_bytes, bounds.depth @@ -56,9 +68,15 @@ fn main() { // ---- constraint count ---- let t = Instant::now(); let cs = ConstraintSystem::::new_ref(); - ReceiptCircuit::prove(bounds, fixture::genuine()) - .generate_constraints(cs.clone()) - .expect("synthesis"); + if keccacheck { + KeccacheckReceiptCircuit::prove(bounds, fixture::genuine()) + .generate_constraints(cs.clone()) + .expect("synthesis"); + } else { + ReceiptCircuit::prove(bounds, fixture::genuine()) + .generate_constraints(cs.clone()) + .expect("synthesis"); + } let satisfied = cs.is_satisfied().expect("satisfiability"); let n = cs.num_constraints(); println!( @@ -76,9 +94,13 @@ fn main() { // artifact through a sound process. let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(0); let t = Instant::now(); - let (pk, vk) = + let (pk, vk) = if keccacheck { + Groth16::::circuit_specific_setup(KeccacheckReceiptCircuit::setup(bounds), &mut rng) + .expect("setup") + } else { Groth16::::circuit_specific_setup(ReceiptCircuit::setup(bounds), &mut rng) - .expect("setup"); + .expect("setup") + }; let setup_secs = t.elapsed().as_secs_f64(); let pk_bytes = pk.serialized_size(ark_serialize::Compress::No); let pk_compressed = pk.serialized_size(ark_serialize::Compress::Yes); @@ -90,12 +112,21 @@ fn main() { // ---- prove ---- let t = Instant::now(); - let proof = Groth16::::prove( - &pk, - ReceiptCircuit::prove(bounds, fixture::genuine()), - &mut rng, - ) - .expect("prove"); + let proof = if keccacheck { + Groth16::::prove( + &pk, + KeccacheckReceiptCircuit::prove(bounds, fixture::genuine()), + &mut rng, + ) + .expect("prove") + } else { + Groth16::::prove( + &pk, + ReceiptCircuit::prove(bounds, fixture::genuine()), + &mut rng, + ) + .expect("prove") + }; let prove_secs = t.elapsed().as_secs_f64(); println!("prove: {prove_secs:>8.1}s"); diff --git a/experiments/keccacheck-arkworks/RESULTS.md b/experiments/keccacheck-arkworks/RESULTS.md index dd44328..7c826d6 100644 --- a/experiments/keccacheck-arkworks/RESULTS.md +++ b/experiments/keccacheck-arkworks/RESULTS.md @@ -98,8 +98,31 @@ The integration now has an alternate `KeccacheckReceiptCircuit` and Rust temporary dual-version scalar conversion. 4. Investigate the arkworks overhead relative to gnark, principally in the round verifier and transcript expression lowering. -5. Only after those checks, run one full Groth16 setup/prove/ - verify benchmark and evaluate the larger witness-generation path. +5. Measure a latency distribution and peak proving-only memory on the target + enclave after the native GKR dependency is made enclave-compatible. The GKR proof occupies about 307 KiB at 64 permutations, but it is private Groth16 witness data, not calldata and not an additional on-chain proof. + +## End-to-end Groth16 measurement + +Commit `8b60d00` was measured in release mode on an Intel Core i9-14900HX with +16 Rayon threads. This is one complete local sample, not a latency +distribution or an enclave measurement. + +| Stage | Measurement | +|---|---:| +| Constraints | 4,034,927 | +| Satisfying diagnostic synthesis | 35.7 s | +| Circuit-specific Groth16 setup | 28.8 s | +| Groth16 proving | 24.9 s | +| Groth16 verification | 1.52 ms | +| Peak process RSS across synthesis, setup, and proving | 12.6 GiB | +| Proving key | 1.44 GiB uncompressed / 0.72 GiB compressed | +| Compressed proof | 128 bytes | + +The 24.9-second proving measurement includes native GKR witness generation, +outer-circuit synthesis, witness mapping, and the Groth16 multiexponentiations. +The generated proof verified against its two public statement-hash limbs and +was rejected after mutating one limb. The 28.8-second deterministic setup is a +measurement stand-in, not a production ceremony. From 5f16efb258efd4b793972b947e87ec10d307e5ab Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Thu, 3 Sep 2026 12:28:00 -0400 Subject: [PATCH 19/22] feat: export Keccacheck verifier artifacts --- contracts/Verifier.sol | 12 ++++++------ contracts/calldata.txt | 6 +++--- contracts/proof.json | 6 +++--- crates/prover/src/bin/export_verifier.rs | 17 +++++++++++++++-- 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/contracts/Verifier.sol b/contracts/Verifier.sol index 968a30c..106a5d1 100644 --- a/contracts/Verifier.sol +++ b/contracts/Verifier.sol @@ -75,12 +75,12 @@ contract Verifier { uint256 constant DELTA_NEG_Y_1 = 19257957324113511611720790992651491173029981678335866461361133554601815821372; // Constant and public input points - uint256 constant CONSTANT_X = 16208839724471277216601460661420983062276407618665006588326578935414763551635; - uint256 constant CONSTANT_Y = 9940980535099599717419533404020065535259107309790897410751122444250949482832; - uint256 constant PUB_0_X = 13140574417491532082542376956995810142852812141951714597942587116697734247084; - uint256 constant PUB_0_Y = 19437488196263352531732679871899443478925195370665642208888307033221185496979; - uint256 constant PUB_1_X = 12279282134251549331686514719497445837688998891797504738355585676440180297197; - uint256 constant PUB_1_Y = 1570097439651360812443069379342259804237432750561298171817028858121495635769; + uint256 constant CONSTANT_X = 15138933018800168104626208562752643351694693240728940576908099378077506127809; + uint256 constant CONSTANT_Y = 13440600505088464263913789249055128799319615219633549393247549586787259087349; + uint256 constant PUB_0_X = 17429719968351208872274701233868480357977279897948794222132726423007938649717; + uint256 constant PUB_0_Y = 16243863455167378616029873147049730070812431399223228044387392130975618122073; + uint256 constant PUB_1_X = 4292678073581155621200320656201434929785497837407533610793076027134243625633; + uint256 constant PUB_1_Y = 15639844169511816418353966019502957734362208535917293570815730516143903737786; /// Negation in Fp. /// @notice Returns a number x such that a + x = 0 in Fp. diff --git a/contracts/calldata.txt b/contracts/calldata.txt index 00767d5..bc9c2da 100644 --- a/contracts/calldata.txt +++ b/contracts/calldata.txt @@ -1,6 +1,6 @@ verifyProof( - [0x12854742bf7a02db2cca2a8033697c0f39e8838b4c9cd16b98517a33677bbe30, 0x18917fc0abe882532dd35ba0887f0c75affb0b97828fe2f7829bb7e40d8ca9d1], - [[0x1ddf52b69dfc5e489e09ac68e57a392bda7e0754319da64b215e6fa3c8076b7a, 0x031228b4e762fd03cd0af0d79e0c912c0d796aa9586188e83310e7621d6c6cf3], [0x090e06d7234cb155c6181b1e4d75cf15ef6df32db227b82d61d833b3eadf2686, 0x1770cc517ec797fd7be65fb31a687b44b3b7c60ce6fb2af1874e0b89ff5b4e2c]], - [0x2e6a3a0c9bbcd986501ffa2f45e03cf2b21671933e6681c9b58145024cf7bdcd, 0x06f237fcac96bb9cf2d5accadc5c373f57d042484157667cae7885680ec936ca], + [0x2ce1c0972184a6b47cb4cd25dc8ff88abfe797b19927bb8ae7de594b929c6bc6, 0x2f845012415f3bdc2a0f707d67a3494d18e17c49f07cea2cf736d5c623dee5b6], + [[0x2196511bc2eae46c3a22646730a48b417dd1cf809b220dc2735cfd83f9196bb0, 0x13624c8a626f9288aa7c50acb057b6d4a240db1cf8f93d7e44d227cb821021d2], [0x28735ab23f96cfa06e2fa035764426fa8c3a17f82347d8d2a4886877f88cfe91, 0x19836e95d5c9993d7b8dab32e5ee54b21105c6d2d1d96b355887464bde87a41a]], + [0x0d8d95904e20733d0c1e6f0dff0864a0543ea4d6286d30330ae76c35c150c87f, 0x264cee3f1ee8629a8b2b63c2765e3b0f0669f7438d08adba32724cf79deca00a], [0x5ce039e6e0168697c1ee39fd592efdb1, 0x0273a75f1a45c7da3342430d209ab119] ) \ No newline at end of file diff --git a/contracts/proof.json b/contracts/proof.json index 71bfbde..65cc60e 100644 --- a/contracts/proof.json +++ b/contracts/proof.json @@ -1,8 +1,8 @@ { "proof": [ - "0x12854742bf7a02db2cca2a8033697c0f39e8838b4c9cd16b98517a33677bbe30", "0x18917fc0abe882532dd35ba0887f0c75affb0b97828fe2f7829bb7e40d8ca9d1", - "0x1ddf52b69dfc5e489e09ac68e57a392bda7e0754319da64b215e6fa3c8076b7a", "0x031228b4e762fd03cd0af0d79e0c912c0d796aa9586188e83310e7621d6c6cf3", "0x090e06d7234cb155c6181b1e4d75cf15ef6df32db227b82d61d833b3eadf2686", "0x1770cc517ec797fd7be65fb31a687b44b3b7c60ce6fb2af1874e0b89ff5b4e2c", - "0x2e6a3a0c9bbcd986501ffa2f45e03cf2b21671933e6681c9b58145024cf7bdcd", "0x06f237fcac96bb9cf2d5accadc5c373f57d042484157667cae7885680ec936ca" + "0x2ce1c0972184a6b47cb4cd25dc8ff88abfe797b19927bb8ae7de594b929c6bc6", "0x2f845012415f3bdc2a0f707d67a3494d18e17c49f07cea2cf736d5c623dee5b6", + "0x2196511bc2eae46c3a22646730a48b417dd1cf809b220dc2735cfd83f9196bb0", "0x13624c8a626f9288aa7c50acb057b6d4a240db1cf8f93d7e44d227cb821021d2", "0x28735ab23f96cfa06e2fa035764426fa8c3a17f82347d8d2a4886877f88cfe91", "0x19836e95d5c9993d7b8dab32e5ee54b21105c6d2d1d96b355887464bde87a41a", + "0x0d8d95904e20733d0c1e6f0dff0864a0543ea4d6286d30330ae76c35c150c87f", "0x264cee3f1ee8629a8b2b63c2765e3b0f0669f7438d08adba32724cf79deca00a" ], "publicSignals": ["0x5ce039e6e0168697c1ee39fd592efdb1", "0x0273a75f1a45c7da3342430d209ab119"], "statement": { diff --git a/crates/prover/src/bin/export_verifier.rs b/crates/prover/src/bin/export_verifier.rs index 7847f11..68f44fe 100644 --- a/crates/prover/src/bin/export_verifier.rs +++ b/crates/prover/src/bin/export_verifier.rs @@ -2,6 +2,7 @@ //! //! ```sh //! cargo run -p mirage-prover --release --bin export-verifier +//! cargo run -p mirage-prover --release --bin export-verifier -- --keccachecheck //! ``` //! //! Writes three artifacts to `contracts/`: @@ -22,10 +23,12 @@ use std::path::PathBuf; use ark_bn254::Bn254; use ark_groth16::VerifyingKey; +use ark_std::rand::SeedableRng; use taceo_groth16_sol::{SolidityVerifierConfig, SolidityVerifierContext}; use mirage_relation::{fixture, Bounds}; fn main() { + let keccachecheck = std::env::args().any(|arg| arg == "--keccachecheck"); // CARGO_MANIFEST_DIR is `crates/prover`, so reaching the repo's // `contracts/` takes two levels up, not one. @@ -40,7 +43,11 @@ fn main() { // rendered below is structurally identical either way, so the size and gas // measurements hold; only the key's provenance differs. eprintln!("setup..."); - let keys = mirage_prover::setup(bounds, 0).expect("setup"); + let keys = if keccachecheck { + mirage_prover::setup_keccacheck(bounds, 0).expect("Keccacheck setup") + } else { + mirage_prover::setup(bounds, 0).expect("setup") + }; // The contract. eprintln!("rendering verifier..."); @@ -57,7 +64,13 @@ fn main() { // compiled. `prove` verifies natively before returning: a contract test // that fails is ambiguous unless the proof is known good. eprintln!("proving..."); - let settlement = mirage_prover::prove_seeded(&keys, bounds, &witness, 0).expect("prove"); + let settlement = if keccachecheck { + let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(0); + mirage_prover::prove_keccacheck(&keys, bounds, &witness, &mut rng) + .expect("Keccacheck prove") + } else { + mirage_prover::prove_seeded(&keys, bounds, &witness, 0).expect("prove") + }; let [hi, lo] = settlement.signals; let json = proof_json(&settlement.proof, hi, lo, &witness); From 08148cb0311a45c4bf7ca2ee883c053dd00cdafc Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Thu, 3 Sep 2026 12:30:35 -0400 Subject: [PATCH 20/22] feat: add reproducible Keccacheck proving helper --- crates/prover/src/bin/export_verifier.rs | 4 +--- crates/prover/src/lib.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/prover/src/bin/export_verifier.rs b/crates/prover/src/bin/export_verifier.rs index 68f44fe..a4e900e 100644 --- a/crates/prover/src/bin/export_verifier.rs +++ b/crates/prover/src/bin/export_verifier.rs @@ -23,7 +23,6 @@ use std::path::PathBuf; use ark_bn254::Bn254; use ark_groth16::VerifyingKey; -use ark_std::rand::SeedableRng; use taceo_groth16_sol::{SolidityVerifierConfig, SolidityVerifierContext}; use mirage_relation::{fixture, Bounds}; @@ -65,8 +64,7 @@ fn main() { // that fails is ambiguous unless the proof is known good. eprintln!("proving..."); let settlement = if keccachecheck { - let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(0); - mirage_prover::prove_keccacheck(&keys, bounds, &witness, &mut rng) + mirage_prover::prove_keccacheck_seeded(&keys, bounds, &witness, 0) .expect("Keccacheck prove") } else { mirage_prover::prove_seeded(&keys, bounds, &witness, 0).expect("prove") diff --git a/crates/prover/src/lib.rs b/crates/prover/src/lib.rs index 59eea05..9cea135 100644 --- a/crates/prover/src/lib.rs +++ b/crates/prover/src/lib.rs @@ -141,6 +141,20 @@ pub fn prove_seeded( prove(keys, bounds, witness, &mut rng) } +/// Experimental [`prove_keccacheck`] with deterministic proof randomness. +/// +/// This exists for reproducible cross-repository fixtures and tests. Production +/// settlements must call [`prove_keccacheck`] with fresh randomness. +pub fn prove_keccacheck_seeded( + keys: &Keys, + bounds: Bounds, + witness: &Witness, + seed: u64, +) -> Result { + let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(seed); + prove_keccacheck(keys, bounds, witness, &mut rng) +} + /// A proof and the two public signals it is bound to, ready for `collect`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Settlement { From b5192b4bb8cedcc6eeb342da5c381057d33278b7 Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Wed, 9 Sep 2026 12:46:57 -0400 Subject: [PATCH 21/22] fix: assert one-hot selectors hit for in-range reads The all-zero selector is how `one_hot` encodes an out-of-range index, so it is satisfiable for an in-range index too. A prover supplying it suppresses a byte or nibble read, which then returns zero and satisfies any equality against it. Range-constraining the index does not help: the suppressed read is at an in-range index. Add `one_hot_in_range` and `nibble_at_with`, which keep the definitional constraints ungated and add a gated assertion that a hit occurred. Gate the reads whose zero would otherwise satisfy something: branch child selection, the traversal nibbles, the hex-prefix flag byte, both sides of the path match, and the constructed leaf path. Speculative reads still pass a false active. Also bound `receipt_len` by the receipt buffer in the leaf gadget and `key_len` by the key buffer in the traversal, so neither depends on a sibling module for the extent it hashes, and pin `asset_kind` to ERC-20 in the relation rather than resting on address(0) being unable to emit logs. Costs 1,456 constraints: 8,095,727 to 8,097,183 direct, 4,034,927 to 4,036,383 batched. --- crates/gadgets/src/bytes.rs | 42 +++++++++++ crates/gadgets/src/mpt/constructed_leaf.rs | 31 ++++++-- .../gadgets/src/mpt/constructed_traverse.rs | 57 ++++++++++++-- crates/gadgets/src/mpt/node.rs | 6 +- crates/gadgets/src/mpt/path.rs | 25 ++++++- crates/gadgets/src/mpt/traverse.rs | 31 ++++++-- crates/gadgets/tests/soundness_audit.rs | 74 +++++++++++++++++++ crates/relation/src/lib.rs | 29 +++++++- 8 files changed, 271 insertions(+), 24 deletions(-) create mode 100644 crates/gadgets/tests/soundness_audit.rs diff --git a/crates/gadgets/src/bytes.rs b/crates/gadgets/src/bytes.rs index 0402c1e..6db6623 100644 --- a/crates/gadgets/src/bytes.rs +++ b/crates/gadgets/src/bytes.rs @@ -87,6 +87,19 @@ pub fn prefix_mask( Ok(sel) } +/// Enforces `len <= n` when `active`, without the zero-tail requirement. +/// +/// [`assert_zero_tail`] carries the same bound, so use this only where a length +/// is checked against a buffer it is not itself the extent of. +pub fn assert_at_most( + len: &FpVar, + n: usize, + active: &Boolean, +) -> Result<(), SynthesisError> { + let _ = prefix_mask(len, n, active)?; + Ok(()) +} + /// Requires `buf[i] == 0` for every `i >= len`. /// /// This is the check that makes a bounded buffer safe to hash or parse. @@ -141,6 +154,35 @@ pub fn one_hot(idx: &FpVar, n: usize) -> Result Ok(sel) } +/// A one-hot indicator vector that must actually hit, when `active`. +/// +/// [`one_hot`] alone permits the all-zero assignment for *any* index, because +/// the all-zero vector is how an out-of-range index is encoded. That is the +/// right default for a speculative read, and wrong wherever the caller knows +/// the index is in range: a prover who claims out-of-range for an in-range +/// index suppresses the read, and [`select_byte_with`] returns zero. +/// +/// Suppressing a read is not the same as choosing an out-of-range index, and no +/// range constraint on the index prevents it. Where a zero read would satisfy +/// something, use this instead. +/// +/// The hit assertion is separate from [`enforce_one_hot`] on purpose. That +/// function's constraints define the indicators and must stay ungated; this one +/// asserts a fact about the caller's data and is therefore gated. +pub fn one_hot_in_range( + idx: &FpVar, + n: usize, + active: &Boolean, +) -> Result>, SynthesisError> { + let sel = one_hot(idx, n)?; + let mut sum = FpVar::zero(); + for bit in &sel { + sum += FpVar::from(bit.clone()); + } + sum.conditional_enforce_equal(&FpVar::one(), active)?; + Ok(sel) +} + fn enforce_one_hot( idx: &FpVar, sel: &[Boolean], diff --git a/crates/gadgets/src/mpt/constructed_leaf.rs b/crates/gadgets/src/mpt/constructed_leaf.rs index f993906..3ac12e5 100644 --- a/crates/gadgets/src/mpt/constructed_leaf.rs +++ b/crates/gadgets/src/mpt/constructed_leaf.rs @@ -21,7 +21,7 @@ use ark_relations::gr1cs::SynthesisError; use crate::bytes::byte_to_field; use crate::keccak::sponge::Byte; use crate::keccak::{keccak256_var_with, DirectPermutation, PermutationBackend}; -use crate::mpt::path::nibble_at; +use crate::mpt::path::nibble_at_with; /// Constructs and hashes `RLP([HP(key[consumed..], leaf), receipt])`. /// @@ -70,6 +70,13 @@ pub fn hash_leaf_from_remainder_with>( decode_u16(&receipt_hi, &receipt_low)?.conditional_enforce_equal(receipt_len, active)?; receipt_hi.conditional_enforce_equal(&UInt8::constant(1), active)?; + // The leaf buffer is wider than the receipt buffer, so bounding `leaf_len` + // alone permits a `receipt_len` that runs past the receipt's own bytes and + // absorbs the leaf's constant padding. That commits to a receipt this + // gadget never saw. The receipt relation happens to pin the length too, but + // a hash gadget must not depend on its caller for the extent it hashes. + crate::bytes::assert_at_most(receipt_len, receipt.len(), active)?; + let total_nibbles = key_len * FpVar::constant(F::from(2u64)); let remaining = &total_nibbles - consumed; let max_nibbles = key.len() * 2; @@ -85,7 +92,12 @@ pub fn hash_leaf_from_remainder_with>( &FpVar::constant(F::from(encoded_len as u64)), &path_item_len, )?; - layouts.push((selected, encoded_len, path_bytes(key, consumed, n, active)?)); + let layout_active = active.clone() & selected.clone(); + layouts.push(( + selected, + encoded_len, + path_bytes(key, consumed, n, &layout_active)?, + )); } any_layout.conditional_enforce_equal(&Boolean::TRUE, active)?; @@ -136,12 +148,21 @@ fn path_bytes( if n % 2 == 0 { expressions.push(FpVar::constant(F::from(0x20u64))); } else { - expressions.push(FpVar::constant(F::from(0x30u64)) + nibble_at(key, consumed)?); + expressions + .push(FpVar::constant(F::from(0x30u64)) + nibble_at_with(key, consumed, active)?); } let mut j = n % 2; while j < n { - let high = nibble_at(key, &(consumed + FpVar::constant(F::from(j as u64))))?; - let low = nibble_at(key, &(consumed + FpVar::constant(F::from((j + 1) as u64))))?; + let high = nibble_at_with( + key, + &(consumed + FpVar::constant(F::from(j as u64))), + active, + )?; + let low = nibble_at_with( + key, + &(consumed + FpVar::constant(F::from((j + 1) as u64))), + active, + )?; expressions.push(high * FpVar::constant(F::from(16u64)) + low); j += 2; } diff --git a/crates/gadgets/src/mpt/constructed_traverse.rs b/crates/gadgets/src/mpt/constructed_traverse.rs index 42fe866..0c2e62c 100644 --- a/crates/gadgets/src/mpt/constructed_traverse.rs +++ b/crates/gadgets/src/mpt/constructed_traverse.rs @@ -19,10 +19,10 @@ use ark_relations::gr1cs::SynthesisError; use super::constructed_leaf::hash_leaf_from_remainder_with; use super::node::{branch_child_offset, decode_branch, decode_short}; -use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at, read_flags}; +use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at_with, read_flags}; use super::traverse::{assert_path_matches, bits_to_byte}; use super::{MptVerifier, ProofNode}; -use crate::bytes::{one_hot, select_byte_with, select_bytes, zero_like}; +use crate::bytes::{one_hot_in_range, select_byte_with, select_bytes, zero_like}; use crate::keccak::{keccak256_var_with, DirectPermutation, PermutationBackend}; pub struct ConstructedLeafTraversal; @@ -69,6 +69,12 @@ impl ConstructedLeafTraversal { nodes: &[ProofNode], backend: &mut B, ) -> Result<(), SynthesisError> { + // Nibble reads past the key buffer return zero rather than failing, so + // an unbounded `key_len` lets the path consume nibbles the key does not + // have. The nibble reads are gated in range individually; this bounds + // the length they are measured against. + crate::bytes::assert_at_most(key_len, key.len(), &Boolean::TRUE)?; + let mut expected = root.to_vec(); let mut consumed = zero_like(key)?; let mut inactive_seen = Boolean::FALSE; @@ -99,7 +105,7 @@ impl ConstructedLeafTraversal { // speculative short-node decoder and path machinery. if level_index == 0 { let branch = decode_branch(&level.bytes, &level.len, &active)?; - let nibble = nibble_at(key, &consumed)?; + let nibble = nibble_at_with(key, &consumed, &active)?; let child_offset = branch_child_offset(&branch, &nibble, &active)?; let next_ref = select_bytes(&level.bytes, &child_offset, 32)?; consumed = @@ -134,11 +140,11 @@ impl ConstructedLeafTraversal { let short = decode_short(&level.bytes, &level.len, &short_active)?; profile(&level.bytes, "decoders", &mut mark); - let nibble = nibble_at(key, &consumed)?; + let nibble = nibble_at_with(key, &consumed, &branch_active)?; let child_offset = branch_child_offset(&branch, &nibble, &branch_active)?; profile(&level.bytes, "child-offset", &mut mark); - let first_sel = one_hot(&short.path_offset, level.bytes.len())?; + let first_sel = one_hot_in_range(&short.path_offset, level.bytes.len(), &short_active)?; let first = select_byte_with(&level.bytes, &first_sel)?; assert_canonical_flags(&first, &short_active)?; let flags = read_flags(&first)?; @@ -311,6 +317,47 @@ mod tests { ) } + /// A `key_len` past the key buffer must be rejected. + /// + /// Nibble reads past the buffer return zero rather than failing, so an + /// unbounded `key_len` let the path consume nibbles the key does not have. + /// The relation derives `key_len` from the witness, so this is only + /// constructible here. + #[test] + fn rejects_a_key_length_past_the_buffer() { + let p = genuine(); + let cs = ConstraintSystem::::new_ref(); + let root = alloc_bounded(cs.clone(), &p.root, 32).unwrap(); + let key = alloc_bounded(cs.clone(), &p.key, 3).unwrap(); + // The buffer holds three bytes; claim four. + let key_len = FpVar::new_witness(cs.clone(), || Ok(Fr::from(4u64))).unwrap(); + let value = alloc_bounded(cs.clone(), &p.value, 448).unwrap(); + let value_len = + FpVar::new_witness(cs.clone(), || Ok(Fr::from(p.value.len() as u64))).unwrap(); + + let ancestor_count = p.nodes.len().saturating_sub(1); + let mut nodes = Vec::with_capacity(3); + for i in 0..3 { + let (bytes, len, active) = match p.nodes.get(i).filter(|_| i < ancestor_count) { + Some(node) => (node.clone(), node.len(), true), + None => (Vec::new(), 0, false), + }; + nodes.push(ProofNode { + bytes: alloc_bounded(cs.clone(), &bytes, 544).unwrap(), + len: FpVar::new_witness(cs.clone(), || Ok(Fr::from(len as u64))).unwrap(), + active: Boolean::new_witness(cs.clone(), || Ok(active)).unwrap(), + }); + } + ConstructedLeafTraversal::verify_inclusion( + &root, &key, &key_len, &value, &value_len, &nodes, + ) + .unwrap(); + assert!( + !cs.is_satisfied().unwrap(), + "accepted a key length past the key buffer" + ); + } + #[test] fn accepts_a_genuine_constructed_leaf_proof() { assert!(verify(&genuine())); diff --git a/crates/gadgets/src/mpt/node.rs b/crates/gadgets/src/mpt/node.rs index 7730a7b..4185da6 100644 --- a/crates/gadgets/src/mpt/node.rs +++ b/crates/gadgets/src/mpt/node.rs @@ -27,7 +27,9 @@ use ark_r1cs_std::select::CondSelectGadget; use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; -use crate::bytes::{one_hot, select_byte_with, select_bytes, zero_like as zero_at}; +use crate::bytes::{ + one_hot, one_hot_in_range, select_byte_with, select_bytes, zero_like as zero_at, +}; use crate::rlp::{cursor::Cursor, RlpDecoder}; /// A branch node's child layout. @@ -146,7 +148,7 @@ pub fn branch_child_offset( nibble: &FpVar, active: &Boolean, ) -> Result, SynthesisError> { - let sel = one_hot(nibble, 16)?; + let sel = one_hot_in_range(nibble, 16, active)?; // Zip stops at the shortest, so a short branch would silently select over // fewer slots rather than failing. The selector must cover all sixteen. assert_eq!(branch.child_offset.len(), 16, "branch has sixteen children"); diff --git a/crates/gadgets/src/mpt/path.rs b/crates/gadgets/src/mpt/path.rs index aac56ec..795db26 100644 --- a/crates/gadgets/src/mpt/path.rs +++ b/crates/gadgets/src/mpt/path.rs @@ -25,7 +25,7 @@ use ark_r1cs_std::uint8::UInt8; use ark_r1cs_std::GR1CSVar; use ark_relations::gr1cs::SynthesisError; -use crate::bytes::{one_hot, select_byte_with}; +use crate::bytes::{one_hot_in_range, select_byte_with}; /// The two flag bits of a hex-prefix path. pub struct Flags { @@ -87,10 +87,31 @@ pub fn assert_even_pad_is_zero( pub fn nibble_at( buf: &[UInt8], index: &FpVar, +) -> Result, SynthesisError> { + nibble_at_with(buf, index, &Boolean::FALSE) +} + +/// [`nibble_at`], additionally asserting the read lands inside `buf` when +/// `active`. +/// +/// Without the assertion a prover can supply the all-zero selector for an index +/// that *is* in range, so the nibble reads zero and any equality against it +/// passes. That is a live forgery wherever the nibble drives the traversal: +/// following child 0 instead of the key's actual nibble, or matching an +/// extension path against zeros. Range-constraining the index does not help, +/// because the suppressed read is at an in-range index. +/// +/// Speculative callers pass a false `active`: a path-match iteration past +/// `path_nibbles`, or an unselected leaf layout, legitimately reads out of +/// range. +pub fn nibble_at_with( + buf: &[UInt8], + index: &FpVar, + active: &Boolean, ) -> Result, SynthesisError> { // byte = index / 2, high half when index is even. let (byte_index, remainder) = halve_with_remainder(index)?; - let sel = one_hot(&byte_index, buf.len())?; + let sel = one_hot_in_range(&byte_index, buf.len(), active)?; let byte = select_byte_with(buf, &sel)?; let bits = byte.to_bits_le()?; diff --git a/crates/gadgets/src/mpt/traverse.rs b/crates/gadgets/src/mpt/traverse.rs index 1248313..52ec164 100644 --- a/crates/gadgets/src/mpt/traverse.rs +++ b/crates/gadgets/src/mpt/traverse.rs @@ -39,9 +39,9 @@ use ark_r1cs_std::uint8::UInt8; use ark_relations::gr1cs::SynthesisError; use super::node::{branch_child_offset, decode_branch, decode_short, is_branch}; -use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at, read_flags}; +use super::path::{assert_canonical_flags, assert_even_pad_is_zero, nibble_at_with, read_flags}; use super::{MptVerifier, ProofNode}; -use crate::bytes::{lt as less_than, one_hot, select_byte_with, select_bytes, zero_like}; +use crate::bytes::{lt as less_than, one_hot_in_range, select_byte_with, select_bytes, zero_like}; use crate::keccak::keccak256_var; /// # Conditional enforcement: the rule this module exists to demonstrate @@ -66,6 +66,22 @@ use crate::keccak::keccak256_var; /// The rule: **gate assertions about the caller's data; never gate a constraint /// that defines a witness.** /// +/// # The gap that rule left +/// +/// Definitional constraints being ungated is right, but it does not follow that +/// a definitional gadget needs no assertion *alongside* it. `one_hot` encodes +/// an out-of-range index as the all-zero vector, so that vector is available +/// for an in-range index too, and `select_byte_with` then reads zero. A prover +/// suppresses a read the circuit believes it made. Range-constraining the index +/// does not help: the suppressed read is at an in-range index. +/// +/// So a read whose zero would satisfy something takes +/// `bytes::one_hot_in_range` or `path::nibble_at_with`, which keep the +/// definitional constraints ungated and add a gated "a hit did occur" +/// assertion. Reads that are genuinely speculative still pass a false +/// `active`: a path-match iteration past `path_nibbles`, or an unselected +/// leaf layout. +/// /// Cost is unaffected either way — `conditional_enforce_equal` costs what /// `enforce_equal` does. /// @@ -171,12 +187,12 @@ impl MptVerifier for Traversal { // ---- branch case: follow the nibble's child (invariant 3) ---- profile(&level.bytes, "decoders", &mut mark); - let nibble = nibble_at(key, &consumed)?; + let nibble = nibble_at_with(key, &consumed, &branch_active)?; let child_offset = branch_child_offset(&branch, &nibble, &branch_active)?; // ---- short case: read flags and match the path (invariant 4) ---- profile(&level.bytes, "child-hash", &mut mark); - let first_sel = one_hot(&short.path_offset, level.bytes.len())?; + let first_sel = one_hot_in_range(&short.path_offset, level.bytes.len(), &short_active)?; let first = select_byte_with(&level.bytes, &first_sel)?; // These bind only for short nodes: on a branch, `path_offset` is // a child-reference prefix such as 0xa0, whose high bits are set by @@ -341,16 +357,17 @@ pub(super) fn assert_path_matches( for j in 0..max_path_nibbles { let jf = FpVar::constant(F::from(j as u64)); let within = less_than(&jf, path_nibbles)?; + let bind = active.clone() & within; // Path nibble, read relative to the path field's start. let path_pos = &short.path_offset * FpVar::constant(F::from(2u64)) + &skip + &jf; - let from_path = nibble_at(node, &path_pos)?; + let from_path = nibble_at_with(node, &path_pos, &bind)?; // Key nibble. let key_pos = consumed + &jf; - let from_key = nibble_at(key, &key_pos)?; + let from_key = nibble_at_with(key, &key_pos, &bind)?; - from_path.conditional_enforce_equal(&from_key, &(active.clone() & within))?; + from_path.conditional_enforce_equal(&from_key, &bind)?; } Ok(()) } diff --git a/crates/gadgets/tests/soundness_audit.rs b/crates/gadgets/tests/soundness_audit.rs new file mode 100644 index 0000000..67bcb73 --- /dev/null +++ b/crates/gadgets/tests/soundness_audit.rs @@ -0,0 +1,74 @@ +//! Reproductions of soundness findings, not assertions that the circuit is safe. +//! These tests should stop reproducing after the corresponding fixes. + +use ark_bn254::Fr; +use ark_r1cs_std::{alloc::AllocVar, fields::fp::FpVar, GR1CSVar}; +use ark_relations::gr1cs::ConstraintSystem; +use mirage_gadgets::bytes::{alloc_bounded, one_hot, select_byte_with}; + +#[test] +fn audit_reproduces_zero_selector_for_in_range_index() { + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &[11, 22, 33], 3).unwrap(); + // Generate the all-zero selector witness using an out-of-range index. + let idx = FpVar::new_witness(cs.clone(), || Ok(Fr::from(99u64))).unwrap(); + let selectors = one_hot(&idx, buf.len()).unwrap(); + let read = select_byte_with(&buf, &selectors).unwrap(); + assert_eq!(read.value().unwrap(), 0); + assert!(cs.is_satisfied().unwrap()); + + // A malicious prover controls assignments, not just the honest generator. + // Change only the index assignment; all other assignments stay unchanged. + let FpVar::Var(allocated) = idx else { + unreachable!() + }; + cs.borrow_mut().unwrap().assignments.witness_assignment[allocated.variable.index().unwrap()] = + Fr::from(1u64); + assert!(cs.is_satisfied().unwrap(), "attack no longer reproduces"); + assert_ne!(read.value().unwrap(), 22, "buf[1] is 22, not zero"); +} + +/// `one_hot_in_range` must reject the all-zero selector for an in-range index. +/// +/// The all-zero vector is how `one_hot` encodes out-of-range, so it is +/// satisfiable for any index. Where the caller knows the index is in range, +/// accepting it lets a prover suppress the read and get zero back. +#[test] +fn in_range_selector_rejects_a_suppressed_read() { + use ark_r1cs_std::boolean::Boolean; + use mirage_gadgets::bytes::one_hot_in_range; + + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &[11, 22, 33], 3).unwrap(); + let idx = FpVar::new_witness(cs.clone(), || Ok(Fr::from(99u64))).unwrap(); + let selectors = one_hot_in_range(&idx, buf.len(), &Boolean::TRUE).unwrap(); + let read = select_byte_with(&buf, &selectors).unwrap(); + assert_eq!(read.value().unwrap(), 0); + // Out of range with an asserted hit is already unsatisfiable. + assert!(!cs.is_satisfied().unwrap()); + + // Repoint the index at an in-range slot, keeping the all-zero selector. + let FpVar::Var(allocated) = idx else { + unreachable!() + }; + cs.borrow_mut().unwrap().assignments.witness_assignment[allocated.variable.index().unwrap()] = + Fr::from(1u64); + assert!( + !cs.is_satisfied().unwrap(), + "all-zero selector still accepted for an in-range index" + ); +} + +/// The ungated form stays satisfiable out of range, which speculative +/// callers depend on. +#[test] +fn in_range_selector_still_permits_speculative_reads() { + use ark_r1cs_std::boolean::Boolean; + use mirage_gadgets::bytes::one_hot_in_range; + + let cs = ConstraintSystem::::new_ref(); + let buf = alloc_bounded(cs.clone(), &[11, 22, 33], 3).unwrap(); + let idx = FpVar::new_witness(cs.clone(), || Ok(Fr::from(99u64))).unwrap(); + let _ = one_hot_in_range(&idx, buf.len(), &Boolean::FALSE).unwrap(); + assert!(cs.is_satisfied().unwrap()); +} diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 5151774..6021e93 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -328,6 +328,15 @@ pub fn generate_constraints_with_backend )?; profile(&cs, "intent commitment", &mut mark); + // This is the ERC-20 relation, so the opening must be an ERC-20 intent. + // A native opening forces `settlement_token` to zero, and the log walk + // then requires address(0) to have emitted a Transfer. That is + // unsatisfiable, but only because address(0) has no code. Pin the kind + // directly rather than resting on that. + opening.asset_kind.enforce_equal(&UInt8::constant( + mirage_gadgets::commitment::ASSET_KIND_ERC20, + ))?; + // The commitment's deployment/request/row context must be the same // context whose statement hash the verifier checks. The commitment // hash alone only authenticates the opening internally. @@ -796,6 +805,20 @@ mod tests { assert!(!cs.is_satisfied().unwrap(), "{message}"); } + /// The ERC-20 relation must not accept a native-asset opening. + /// + /// A native opening forces `settlement_token` to zero, which the log walk + /// then requires address(0) to have emitted. That is unsatisfiable only + /// because address(0) has no code; the relation pins the kind directly. + #[test] + fn rejects_a_native_asset_opening() { + let mut w = fixture::genuine(); + w.intent.asset_kind = 0; + w.intent.settlement_token = [0u8; 20]; + refresh_commitment(&mut w); + assert_rejected(w, "accepted a native opening in the ERC-20 relation"); + } + /// The gap this closes: a prover must not be able to substitute the /// settlement details. /// @@ -888,7 +911,7 @@ mod tests { "unsatisfied: {:?}", cs.which_is_unsatisfied() ); - assert_eq!(cs.num_constraints(), 8_095_727); + assert_eq!(cs.num_constraints(), 8_097_183); } #[test] @@ -911,7 +934,7 @@ mod tests { ); assert_eq!(result.recorded, 38); assert_eq!(result.padded, 64); - assert_eq!(cs.num_constraints(), 4_034_927); + assert_eq!(cs.num_constraints(), 4_036_383); assert!( cs.is_satisfied().unwrap(), "unsatisfied: {:?}", @@ -935,6 +958,6 @@ mod tests { KeccacheckReceiptCircuit::setup(Bounds::default()) .generate_constraints(cs.clone()) .unwrap(); - assert_eq!(cs.num_constraints(), 4_034_927); + assert_eq!(cs.num_constraints(), 4_036_383); } } From c43d92e4073dfce337404de7b67e912973f8d48b Mon Sep 17 00:00:00 2001 From: ozwaldorf Date: Wed, 9 Sep 2026 13:27:27 -0400 Subject: [PATCH 22/22] test: close batched, singleton and sole-log coverage gaps The batched circuit is the one that would ship but only ran two mutation cases, so a deferral that dropped a binding rather than only its cost would not have been caught. Run the direct circuit's mutations through it as well. A one-permutation batch is a distinct path: log_instances is zero, the first sumcheck runs zero rounds, and the output claim reduces to a linear combination of the claimed output words. Since padded is a power of two, any caller doing a single permutation reaches it. Cover both directions. Extend the second-event rejection to Erc20FixedLayout, which is the variant the relation wires; only Erc20SingleLog was covered. Record the open security items in RESULTS.md: the receipt-identity gap is carried by an out-of-circuit nomad invariant, and the Poseidon-derived output challenge and absent transcript domain separation still need cryptographic sign-off. Update the constraint counts for b5192b4. --- crates/gadgets/src/receipt/tests.rs | 7 ++ crates/relation/src/lib.rs | 81 ++++++++++++++++++ experiments/keccacheck-arkworks/RESULTS.md | 90 ++++++++++++++++++-- experiments/keccacheck-arkworks/src/batch.rs | 54 ++++++++++++ 4 files changed, 224 insertions(+), 8 deletions(-) diff --git a/crates/gadgets/src/receipt/tests.rs b/crates/gadgets/src/receipt/tests.rs index c46e574..79183d7 100644 --- a/crates/gadgets/src/receipt/tests.rs +++ b/crates/gadgets/src/receipt/tests.rs @@ -659,6 +659,13 @@ fn single_log_rejects_a_second_event() { !accepts::(&r, 0, &TOKEN, &RECIPIENT, &amt), "the single-log variant accepted a receipt with a second event" ); + // The fixed layout is the variant the relation wires, so it carries the + // same obligation. Its logs-list header is pinned to one 157-byte entry, + // which a second event cannot satisfy. + assert!( + !accepts::(&r, 0, &TOKEN, &RECIPIENT, &amt), + "the fixed layout accepted a receipt with a second event" + ); } /// Both relations must agree on every single-log receipt, or the optimization diff --git a/crates/relation/src/lib.rs b/crates/relation/src/lib.rs index 6021e93..0e113c6 100644 --- a/crates/relation/src/lib.rs +++ b/crates/relation/src/lib.rs @@ -16,6 +16,20 @@ //! (12.5), the ERC-20 relation (12.6), and the statement hash (10.2). //! //! Not wired: the delayed-witness ancestry chain (12.7), which is step 5. +//! +//! # What this relation does not prove +//! +//! It proves a matching Transfer exists somewhere in the witness block, not +//! that a particular transaction produced it: the MPT key is a free witness +//! and no transaction identity reaches the statement. One on-chain Transfer +//! therefore satisfies every live row whose intent shares +//! `(token, recipient, amount)`, and the log's sender is unconstrained. +//! +//! That is closed by policy, not here: the nomad must never hold two live +//! requests with identical intents. Settlement soundness depends on that +//! invariant holding off-chain. See the "Carried by out-of-circuit policy" +//! section of `experiments/keccacheck-arkworks/RESULTS.md` for the analysis +//! and the alternatives if it stops being tenable. use ark_bn254::Fr; use ark_ff::PrimeField; @@ -952,6 +966,73 @@ mod tests { ); } + /// The batched circuit is the one that would ship, so every mutation the + /// direct circuit rejects must also fail here. + /// + /// Deferring 38 permutations to one GKR batch changes how Keccak is + /// proved, not what the relation says. A mutation that the direct circuit + /// catches but the batched one accepts would mean the deferral dropped a + /// binding rather than only its cost. + #[test] + fn batched_keccacheck_rejects_every_direct_mutation() { + let cases: Vec<(&str, Witness)> = vec![ + ("substituted recipient", { + let mut w = fixture::genuine(); + w.intent.recipient = [0xee; 20]; + w + }), + ("substituted amount", { + let mut w = fixture::genuine(); + let mut smaller = [0u8; 32]; + smaller[31] = 1; + w.intent.settlement_amount = smaller; + w + }), + ("commitment from another context", { + let mut w = fixture::genuine(); + w.intent.instance_domain = [0xa1; 32]; + w.intent.chain_id = 2; + w.intent.escrow = [0xa2; 20]; + w.intent.request_id = [0xa3; 32]; + w.intent.row_index = 7; + refresh_commitment(&mut w); + w + }), + ("native asset opening", { + let mut w = fixture::genuine(); + w.intent.asset_kind = 0; + w.intent.settlement_token = [0u8; 20]; + refresh_commitment(&mut w); + w + }), + ("block number not in the statement", { + let mut w = fixture::genuine(); + w.statement.witness_block_number += 1; + w + }), + ("block at bondStartBlock", { + let mut w = fixture::genuine(); + w.statement.bond_start_block = w.statement.witness_block_number; + w + }), + ("block after bondDeadline", { + let mut w = fixture::genuine(); + w.statement.bond_deadline = w.statement.witness_block_number - 1; + w + }), + ("tampered receipt byte", { + let mut w = fixture::genuine(); + let last = w.receipt.len() - 1; + w.receipt[last] ^= 1; + w + }), + ]; + + for (name, witness) in cases { + assert_rejected_batched(witness, &format!("batched circuit accepted: {name}")); + } + } + #[test] fn batched_setup_and_prove_shapes_match() { let cs = ConstraintSystem::::new_ref(); diff --git a/experiments/keccacheck-arkworks/RESULTS.md b/experiments/keccacheck-arkworks/RESULTS.md index 7c826d6..9ccc11a 100644 --- a/experiments/keccacheck-arkworks/RESULTS.md +++ b/experiments/keccacheck-arkworks/RESULTS.md @@ -61,15 +61,19 @@ and pads the batch with 26 constant zero-input permutations. The complete genuine relation synthesized and satisfied with this measured breakdown: ```text -non-GKR relation constraints: 2,330,003 +non-GKR relation constraints: 2,331,459 64-way GKR verifier: 1,704,924 -complete relation: 4,034,927 +complete relation: 4,036,383 ``` -This is 4,060,800 fewer constraints than the 8,095,727 direct-Keccak relation, +This is 4,060,800 fewer constraints than the 8,097,183 direct-Keccak relation, a measured 50.2% reduction. The integrated verifier is smaller than the fully witnessed standalone 64-way case because the 26 padding states are constants. +Both figures include the 1,456 constraints added by the one-hot in-range +assertions and buffer bounds in `b5192b4`. The timings below predate that +commit and were not re-measured; the delta is 0.04% of the relation. + ## Correctness checks - Poseidon2 permutation values are differential-tested against the pinned @@ -81,7 +85,13 @@ witnessed standalone 64-way case because the 26 padding states are constants. unsatisfied. - The complete genuine Mirage relation satisfies with 38 recorded and 64 padded permutations. -- The batched relation rejects an incorrect authenticated header hash. +- The batched relation rejects an incorrect authenticated header hash, and + rejects every mutation the direct relation rejects: substituted recipient and + amount, a commitment from another context, a native-asset opening, a block + number outside the statement, both lease-window boundaries, and a tampered + receipt byte. +- A one-permutation batch, whose zero-round sumcheck is a distinct code path, + verifies a genuine permutation and rejects a flipped output bit. - The deepest fixture in the 100-case mainnet dataset satisfies the batched circuit as a fast real-data integration gate. - All tests use the reference's corrected late-round Keccak constants. @@ -91,9 +101,12 @@ witnessed standalone 64-way case because the 26 padding states are constants. The integration now has an alternate `KeccacheckReceiptCircuit` and Rust `setup_keccacheck`/`prove_keccacheck` APIs. Remaining finalist work is: -1. Run the complete existing mutation and mainnet-fixture suites through the - batched circuit, rather than only the genuine fixture and header mutation. -2. Audit the Poseidon-derived output challenge and transcript domain separation. +1. Run the remaining mainnet-fixture suite through the batched circuit. The + mutation suite now runs there (`batched_keccacheck_rejects_every_direct_mutation`). +2. Obtain cryptographic sign-off on the Poseidon-derived output challenge and + the absent transcript domain separation. Reviewed adversarially and no + exploitable gap was found; see "Open security items" below for what a + reviewer still needs to confirm. 3. Vendor or migrate the upstream Rust GKR prover to arkworks 0.6, removing the temporary dual-version scalar conversion. 4. Investigate the arkworks overhead relative to gnark, principally @@ -112,7 +125,7 @@ distribution or an enclave measurement. | Stage | Measurement | |---|---:| -| Constraints | 4,034,927 | +| Constraints | 4,034,927 (now 4,036,383) | | Satisfying diagnostic synthesis | 35.7 s | | Circuit-specific Groth16 setup | 28.8 s | | Groth16 proving | 24.9 s | @@ -126,3 +139,64 @@ outer-circuit synthesis, witness mapping, and the Groth16 multiexponentiations. The generated proof verified against its two public statement-hash limbs and was rejected after mutating one limb. The 28.8-second deterministic setup is a measurement stand-in, not a production ceremony. + +## Open security items + +An adversarial review of the integrated relation ran five independent attack +surfaces: the GKR verifier, MPT inclusion and the constructed leaf, the receipt +and ERC-20 log relation, the header parse and variable-length sponge, and the +commitment, statement hash and protocol replay surface. One in-circuit forgery +was found and fixed in `b5192b4`. The items below remain open and are not +fixable in this crate. + +### Needs cryptographic sign-off + +The output challenge `r` is derived in-circuit with Poseidon2 over the claimed +output words, replacing gnark's Groth16 commitment API. Transcript ordering was +checked and is correct: outputs are absorbed before `r` is squeezed, `r` is +absorbed before `beta`, and every proof value is absorbed before the challenge +that tests it. The residual difference from upstream is that a +commitment-derived challenge also binds the witness commitment, whereas this +binds only the output words. + +`derive_r_var` and the main transcript are separate sponge instances started +from the same `INITIAL_STATE`, with no domain separation tag. Their absorb +sequences differ, so no collision is reachable, and upstream has no tag either. +Adding one would fork the transcript from the pinned native prover at +`15f00e3`, so it is a protocol change rather than a local fix. + +The singleton batch is a distinct code path: with one permutation +`log_instances` is zero, the first sumcheck runs zero rounds, and the output +claim reduces to a transcript-derived linear combination of the output words. +`batch::tests` now covers it in both directions. + +### Carried by out-of-circuit policy + +Nothing in the statement or the commitment binds the transaction hash, +`transactionIndex`, or log position. The MPT key is a free witness. The +relation therefore proves that a matching Transfer exists somewhere in the +block, not that a particular transaction produced it. + +Consequently one on-chain Transfer satisfies every live row whose intent has +the same token, recipient and amount. Two requests for the same payment can be +settled by a single transfer. The log's sender is also unconstrained, so an +executor can claim a coincidental third-party transfer that lands inside its +lease. + +This is closed by policy rather than by the circuit. **The nomad must never +hold two live requests whose intents share `(token, recipient, amount)`**, +enforced by rejecting or jittering a duplicate at request creation. That keeps +the constraint count and the privacy properties unchanged, at the cost of +making settlement soundness depend on an off-chain invariant: a nomad bug that +admits duplicate live intents silently reintroduces the double-settle, and +nothing on-chain will catch it. The invariant therefore belongs in the nomad's +own test suite, not only in its request path. + +The alternatives, if that invariant ever becomes untenable: bind +`transactionIndex` into the statement preimage (a relation version bump, and +the escrow must then store the settled index per row), or expose a receipt +nullifier as a third public signal (strongest, enforced on-chain, but adds a +public input and a linkable per-settlement tag). If `transactionIndex` is ever +bound, note that the one-hot in-range assertions in `b5192b4` are what make +that binding meaningful: without them a prover could suppress a key nibble read +and prove a genuine receipt at a fabricated index. diff --git a/experiments/keccacheck-arkworks/src/batch.rs b/experiments/keccacheck-arkworks/src/batch.rs index d779043..4c109ff 100644 --- a/experiments/keccacheck-arkworks/src/batch.rs +++ b/experiments/keccacheck-arkworks/src/batch.rs @@ -157,4 +157,58 @@ mod tests { assert_eq!(result.padded, 4); assert!(cs.is_satisfied().unwrap()); } + + /// A one-permutation batch is a distinct code path, and `padded` is a power + /// of two, so any caller doing a single permutation reaches it. + /// + /// With `log_instances == 0` the output challenge vector is empty, the + /// first sumcheck runs zero rounds, and the output claim reduces to a + /// linear combination of the claimed output words. That combination is + /// still transcript-derived and still feeds the round reduction, so it must + /// verify a genuine permutation and reject a forged output. + #[test] + fn a_single_permutation_batch_verifies() { + let cs = ConstraintSystem::new_ref(); + let mut batch = KeccacheckBatch::new(cs.clone()); + let _ = batch.permute(witness_state(cs.clone(), 7)).unwrap(); + let result = batch.finish().unwrap(); + assert_eq!(result.recorded, 1); + assert_eq!(result.padded, 1); + assert!( + cs.is_satisfied().unwrap(), + "genuine singleton batch rejected" + ); + } + + /// The same path must not accept an output that is not `keccak-f(input)`. + /// + /// Flipping one output bit after the batch is built leaves every constraint + /// in place and changes only the assignment, which is what a malicious + /// prover controls. + #[test] + fn a_single_permutation_batch_rejects_a_forged_output() { + let cs = ConstraintSystem::new_ref(); + let mut batch = KeccacheckBatch::new(cs.clone()); + let output = batch.permute(witness_state(cs.clone(), 7)).unwrap(); + let _ = batch.finish().unwrap(); + assert!(cs.is_satisfied().unwrap()); + + let Boolean::Var(bit) = output[0][0].clone() else { + panic!("output bit is not an allocated witness"); + }; + let index = bit.variable().index().unwrap(); + let flipped = { + let assignment = &cs.borrow().unwrap().assignments.witness_assignment[index]; + if assignment.is_zero() { + Fr::from(1u64) + } else { + Fr::zero() + } + }; + cs.borrow_mut().unwrap().assignments.witness_assignment[index] = flipped; + assert!( + !cs.is_satisfied().unwrap(), + "singleton batch accepted an output bit that is not keccak-f(input)" + ); + } }