Skip to main content

pca_folding_ivc/
lib.rs

1//! # pca-folding-ivc — one succinct proof of an agent's WHOLE action history (Nova folding)
2//!
3//! Recursive action-proof aggregation (PCA roadmap **T4.4**) done the *modern* way: a
4//! **folding scheme** (Microsoft Nova) instead of naive SNARK-of-a-SNARK recursion. We fold
5//! `N` per-action steps into a single [`RecursiveSNARK`] whose size and the per-step prover
6//! work are **independent of `N`**, then [`compress`] that into a succinct
7//! [`CompressedSNARK`] — ONE proof that attests the agent's entire history.
8//!
9//! ## What one proof attests
10//!
11//! The IVC running state is `z = [chain_digest, budget_spent]` (arity 2), starting at
12//! `z₀ = [0, 0]`. Step `i` consumes a per-action witness `(action_digestᵢ, costᵢ)` and
13//! enforces **in-circuit**:
14//!
15//!   1. **Unforgeable action history, cost-bound** — `chain_digest₍ᵢ₊₁₎ = H(chain_digestᵢ, H(action_digestᵢ, costᵢ))`
16//!      where `H` is a **Poseidon** 2-to-1 hash over the step circuit's native field (the
17//!      Pallas scalar field). The final `chain_digest` is therefore a collision-resistant
18//!      commitment to the *exact ordered sequence* of actions; no action can be inserted,
19//!      dropped or reordered without finding a Poseidon collision.
20//!   2. **Cumulative-risk bound** — `budget_spent₍ᵢ₊₁₎ = budget_spentᵢ + costᵢ` **and**
21//!      `budget_spent₍ᵢ₊₁₎ ≤ B_MAX`, enforced by an in-circuit bit-decomposition range gadget.
22//!      Because folding carries `budget_spent` across every step, this enforces the
23//!      whole-history invariant **Σcostᵢ ≤ B_MAX**. A step whose running total exceeds
24//!      `B_MAX` makes the step's R1CS unsatisfiable, so the aggregate proof is *unprovable*.
25//!
26//! ## Honest scope (candor)
27//!
28//! * The hash `H` is a **production, collision-resistant Poseidon** over the circuit's native
29//!   field — the vetted `neptune` implementation vendored by `nova-snark` itself and exposed at
30//!   `nova_snark::frontend::gadgets::poseidon` (the same code path Nova uses for its own
31//!   folding random oracle). We instantiate it through the sponge API with arity 2 (absorb
32//!   `[chain_digestᵢ, action_digestᵢ]`, squeeze one element) at `Strength::Standard`, i.e. the
33//!   Poseidon-paper round numbers for width `t = 3` targeting **128-bit security** over GF(p)
34//!   with the quintic (x⁵) S-box. The in-circuit sponge ([`SpongeCircuit`]) and the native
35//!   sponge ([`Sponge`]) share identical, deterministically-derived round constants and MDS
36//!   matrix, so they compute the same digest (Nova's own `provider::poseidon` tests assert this
37//!   native/circuit equivalence). This is no longer a didactic placeholder.
38//! * Nova folds over the **Pallas/Vesta** cycle with an **IPA** PCS and a Spartan
39//!   [`CompressedSNARK`]: transparent (no trusted setup) but **not** post-quantum. "PQ-friendly"
40//!   in the roadmap sense is that folding reduces the whole history to a *single* relaxed-R1CS
41//!   instance that a PQ final SNARK (e.g. a STARK) could compress
42//!   instead; wiring that PQ wrap is future work. We do not overstate it here.
43
44use ff::{Field, PrimeField};
45use serde::{Deserialize, Serialize};
46
47use generic_array::typenum::U2;
48use nova_snark::errors::NovaError;
49use nova_snark::frontend::gadgets::poseidon::{
50    Elt, IOPattern, PoseidonConstants, Simplex, Sponge, SpongeAPI, SpongeCircuit, SpongeOp,
51    SpongeTrait, Strength,
52};
53use nova_snark::frontend::{num::AllocatedNum, AllocatedBit, ConstraintSystem, SynthesisError};
54use nova_snark::nova::{CompressedSNARK, ProverKey, PublicParams, RecursiveSNARK, VerifierKey};
55use nova_snark::provider::{PallasEngine, VestaEngine};
56use nova_snark::traits::{circuit::StepCircuit, snark::RelaxedR1CSSNARKTrait, Engine};
57
58// ---- curve cycle + SNARK backends ----------------------------------------------------
59
60/// Primary engine (Pallas).
61pub type E1 = PallasEngine;
62/// Secondary engine (Vesta) — the other half of the cycle.
63pub type E2 = VestaEngine;
64/// Transparent IPA polynomial-evaluation engine on each curve (no trusted setup).
65pub type EE1 = nova_snark::provider::ipa_pc::EvaluationEngine<E1>;
66pub type EE2 = nova_snark::provider::ipa_pc::EvaluationEngine<E2>;
67/// Spartan relaxed-R1CS SNARK used to compress the folded instance on each curve.
68pub type S1 = nova_snark::spartan::snark::RelaxedR1CSSNARK<E1, EE1>;
69pub type S2 = nova_snark::spartan::snark::RelaxedR1CSSNARK<E2, EE2>;
70
71/// The step circuit's native field (the primary engine's scalar field).
72pub type Scalar = <E1 as Engine>::Scalar;
73
74/// The concrete step circuit type folded at every step.
75pub type Circuit = ActionCircuit<Scalar>;
76
77/// Nova public parameters for this step circuit.
78pub type PP = PublicParams<E1, E2, Circuit>;
79/// The folded recursive proof (one per history).
80pub type Recursive = RecursiveSNARK<E1, E2, Circuit>;
81/// Compressed-SNARK prover / verifier keys.
82pub type CompProverKey = ProverKey<E1, E2, Circuit, S1, S2>;
83pub type CompVerifierKey = VerifierKey<E1, E2, Circuit, S1, S2>;
84/// The final succinct proof of the whole history.
85pub type Compressed = CompressedSNARK<E1, E2, Circuit, S1, S2>;
86
87// ---- circuit parameters --------------------------------------------------------------
88
89/// Cumulative risk ceiling: Σcostᵢ must never exceed this across the whole history.
90pub const B_MAX: u64 = 1_000_000;
91/// Bit width for the per-action cost range check (costs live in `[0, 2^COST_BITS)`).
92pub const COST_BITS: usize = 32;
93/// Bit width for the running-budget / headroom range checks. `2^BUDGET_BITS` must exceed
94/// `B_MAX` and the largest attainable cumulative total.
95pub const BUDGET_BITS: usize = 40;
96/// Arity (sponge rate) of the Poseidon chain hash: we absorb exactly two field elements —
97/// `[chain_digestᵢ, action_digestᵢ]` — and squeeze one, a 2-to-1 compression. Width is
98/// `t = arity + 1 = 3`.
99pub type ChainHashArity = U2;
100
101// ---- public action input -------------------------------------------------------------
102
103/// One action in the agent's history, as plain data. `action_digest` is a digest of the
104/// action (here reduced to a `u64` for the demo; a real integration feeds a field element
105/// hashed from the canonical action bytes). `cost` is the action's metered risk/cost.
106#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
107pub struct ActionStep {
108    pub action_digest: u64,
109    pub cost: u64,
110}
111
112// ---- the step circuit ----------------------------------------------------------------
113
114/// The per-step circuit `F`: folds one action into the running `[chain_digest, budget_spent]`.
115#[derive(Clone, Debug)]
116pub struct ActionCircuit<F: PrimeField> {
117    action_digest: F,
118    cost: F,
119}
120
121impl<F: PrimeField> ActionCircuit<F> {
122    /// Build a step circuit from raw field-element witnesses. Honest callers use [`circuits_for`];
123    /// this exists so an adversarial prover (and the soundness tests) can present witnesses no `u64`
124    /// can express, e.g. a field-negative cost, and observe that the constraints reject them.
125    pub fn from_field_witness(action_digest: F, cost: F) -> Self {
126        Self { action_digest, cost }
127    }
128}
129
130impl<F: PrimeField> StepCircuit<F> for ActionCircuit<F> {
131    fn arity(&self) -> usize {
132        2
133    }
134
135    fn synthesize<CS: ConstraintSystem<F>>(
136        &self,
137        cs: &mut CS,
138        z: &[AllocatedNum<F>],
139    ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
140        // z = [chain_digest_in, budget_spent_in]
141        let chain_in = &z[0];
142        let budget_in = &z[1];
143
144        // --- per-action witness -------------------------------------------------------
145        let action_digest =
146            AllocatedNum::alloc(cs.namespace(|| "action_digest"), || Ok(self.action_digest))?;
147        let cost = AllocatedNum::alloc(cs.namespace(|| "cost"), || Ok(self.cost))?;
148        // cost ∈ [0, 2^COST_BITS): a non-negative, bounded cost (prevents a negative
149        // field-wrapped "cost" from gaming the cumulative bound).
150        enforce_range(cs.namespace(|| "cost_range"), &cost, COST_BITS)?;
151
152        // --- (1) unforgeable hash-chain of actions ------------------------------------
153        // RT-05: the cost is bound to the action. The chain absorbs the leaf commitment
154        // `leaf = H(action_digest, cost)`, never the bare digest, so the final chain digest commits
155        // to the exact (action, cost) sequence. A prover who relabels an action with a different
156        // cost (e.g. 0) folds a DIFFERENT chain digest; the verifier recomputes the expected digest
157        // from the ledger's (action, cost) records via `native_final_state`.
158        let leaf = hash2(cs.namespace(|| "leaf_commit"), &action_digest, &cost)?;
159        let chain_out = hash2(cs.namespace(|| "chain_hash"), chain_in, &leaf)?;
160
161        // --- (2) cumulative budget + bound --------------------------------------------
162        let budget_out = budget_in.add(cs.namespace(|| "budget_add"), &cost)?;
163        // budget_out ∈ [0, 2^BUDGET_BITS): non-negative, no field wrap.
164        enforce_range(cs.namespace(|| "budget_range"), &budget_out, BUDGET_BITS)?;
165
166        // headroom = B_MAX - budget_out, and headroom ∈ [0, 2^BUDGET_BITS) ⟹ budget_out ≤ B_MAX.
167        // If budget_out > B_MAX the headroom is a (huge) field-wrapped negative and cannot be
168        // bit-decomposed → the step is UNSATISFIABLE → the aggregate history is unprovable.
169        let bmax = F::from(B_MAX);
170        let headroom = AllocatedNum::alloc(cs.namespace(|| "headroom"), || {
171            let b = budget_out
172                .get_value()
173                .ok_or(SynthesisError::AssignmentMissing)?;
174            Ok(bmax - b)
175        })?;
176        cs.enforce(
177            || "budget_out + headroom == B_MAX",
178            |lc| lc + budget_out.get_variable() + headroom.get_variable(),
179            |lc| lc + CS::one(),
180            |lc| lc + (bmax, CS::one()),
181        );
182        enforce_range(cs.namespace(|| "headroom_range"), &headroom, BUDGET_BITS)?;
183
184        Ok(vec![chain_out, budget_out])
185    }
186}
187
188// ---- in-circuit gadgets (bellpepper, via nova_snark::frontend) ------------------------
189
190/// Range gadget: constrain `num ∈ [0, 2^n_bits)` by bit decomposition. Each bit is a
191/// booleanity-constrained [`AllocatedBit`]; one linear constraint ties their weighted sum to
192/// `num`. An out-of-range (or field-wrapped negative) value has no valid `n_bits` witness.
193fn enforce_range<F: PrimeField, CS: ConstraintSystem<F>>(
194    mut cs: CS,
195    num: &AllocatedNum<F>,
196    n_bits: usize,
197) -> Result<(), SynthesisError> {
198    let value = num.get_value();
199    let mut bits = Vec::with_capacity(n_bits);
200    for i in 0..n_bits {
201        let bit_val = value.map(|v| get_bit_le(&v, i));
202        let b = AllocatedBit::alloc(cs.namespace(|| format!("bit {i}")), bit_val)?;
203        bits.push(b);
204    }
205    // enforce  Σ 2^i · bitᵢ  ==  num
206    cs.enforce(
207        || "bit decomposition",
208        |lc| {
209            let mut lc = lc;
210            let mut coeff = F::ONE;
211            for b in &bits {
212                lc = lc + (coeff, b.get_variable());
213                coeff = coeff.double();
214            }
215            lc
216        },
217        |lc| lc + CS::one(),
218        |lc| lc + num.get_variable(),
219    );
220    Ok(())
221}
222
223/// The vetted Poseidon constants for the arity-2 chain hash: the `neptune` port shipped inside
224/// `nova-snark` at `nova_snark::frontend::gadgets::poseidon`, instantiated at
225/// `Strength::Standard` (Poseidon-paper round numbers for width `t = 3`, quintic S-box, GF(p),
226/// 128-bit security target). The derivation is deterministic in the field `F` (Grain-LFSR round
227/// constants + MDS from the field modulus), so the in-circuit [`SpongeCircuit`] and the native
228/// [`Sponge`] below use byte-for-byte identical parameters and therefore compute the same digest.
229fn chain_hash_constants<F: PrimeField>() -> PoseidonConstants<F, ChainHashArity> {
230    Sponge::<F, ChainHashArity>::api_constants(Strength::Standard)
231}
232
233/// The sponge IO pattern for one 2-to-1 compression: absorb two field elements, squeeze one.
234fn chain_hash_io() -> IOPattern {
235    IOPattern(vec![SpongeOp::Absorb(2), SpongeOp::Squeeze(1)])
236}
237
238/// Poseidon 2-to-1 chain hash `out = H(left, right)` **in circuit**, over the step circuit's
239/// native field. Absorbs `[left, right]` into a Poseidon sponge (arity 2) and squeezes one
240/// element. Collision resistance comes from Poseidon at `Strength::Standard`; the sponge's
241/// domain tag + IO pattern bind the (fixed, length-2) input framing. Mirrored exactly by
242/// [`hash2_native`] — same constants, same IO pattern — so the folded IVC output equals the
243/// native replay.
244fn hash2<F: PrimeField, CS: ConstraintSystem<F>>(
245    mut cs: CS,
246    left: &AllocatedNum<F>,
247    right: &AllocatedNum<F>,
248) -> Result<AllocatedNum<F>, SynthesisError> {
249    let constants = chain_hash_constants::<F>();
250
251    let mut ns = cs.namespace(|| "poseidon_chain_hash");
252    let hash = {
253        let mut sponge = SpongeCircuit::new_with_constants(&constants, Simplex);
254        sponge.start(chain_hash_io(), None, &mut ns);
255        SpongeAPI::absorb(
256            &mut sponge,
257            2,
258            &[Elt::Allocated(left.clone()), Elt::Allocated(right.clone())],
259            &mut ns,
260        );
261        let output = SpongeAPI::squeeze(&mut sponge, 1, &mut ns);
262        sponge.finish(&mut ns).expect("sponge IO pattern honoured");
263        output
264    };
265    // Bind the sub-namespace to a `let` so it (and the `ns`/`constants` borrows it
266    // transitively holds) outlives the final call — a bare `ns.namespace(..)` temporary
267    // in the tail expression is dropped too early (E0597).
268    let mut ensure_ns = ns.namespace(|| "ensure_allocated");
269    let out = Elt::ensure_allocated(&hash[0], &mut ensure_ns)?;
270    Ok(out)
271}
272
273// ---- native (out-of-circuit) mirror --------------------------------------------------
274
275/// The native (non-circuit) image of [`hash2`]: Poseidon over `F` with the identical arity-2
276/// constants and IO pattern. Lets callers precompute the expected final `chain_digest` and
277/// cross-check the IVC output. The vendored sponge guarantees this equals the in-circuit result.
278pub fn hash2_native<F: PrimeField>(left: F, right: F) -> F {
279    let constants = chain_hash_constants::<F>();
280
281    let mut sponge = Sponge::new_with_constants(&constants, Simplex);
282    let acc = &mut ();
283    sponge.start(chain_hash_io(), None, acc);
284    SpongeAPI::absorb(&mut sponge, 2, &[left, right], acc);
285    let hash = SpongeAPI::squeeze(&mut sponge, 1, acc);
286    sponge.finish(acc).expect("sponge IO pattern honoured");
287    hash[0]
288}
289
290/// Native image of the in-circuit leaf commitment `H(action_digest, cost)` (RT-05): binds the
291/// metered cost to the action inside the hash chain.
292pub fn action_leaf_native(action_digest: u64, cost: u64) -> Scalar {
293    hash2_native(Scalar::from(action_digest), Scalar::from(cost))
294}
295
296/// Natively replay a history to the expected final `(chain_digest, budget_spent)`.
297pub fn native_final_state(actions: &[ActionStep]) -> (Scalar, Scalar) {
298    let mut chain = Scalar::ZERO;
299    let mut budget = Scalar::ZERO;
300    for a in actions {
301        chain = hash2_native(chain, action_leaf_native(a.action_digest, a.cost));
302        budget += Scalar::from(a.cost);
303    }
304    (chain, budget)
305}
306
307/// Does this history stay within the cumulative bound? (A native pre-check; the circuit is the
308/// authority.)
309pub fn within_budget(actions: &[ActionStep]) -> bool {
310    actions.iter().map(|a| a.cost as u128).sum::<u128>() <= B_MAX as u128
311}
312
313// ---- top-level prove / fold / compress / verify --------------------------------------
314
315/// The IVC initial state `z₀ = [0, 0]`: the ONE starting state this scheme's verifiers accept (R3-15).
316///
317/// The step circuit only constrains `budget_spent' ∈ [0, B_MAX]`, so a prover that starts from a
318/// field-negative `z₀ = [0, -X]` can fold a history whose real total exceeds `B_MAX` by `X` and still pass
319/// Nova's check *under that z₀*. The verifiers therefore never take `z₀` from the caller or from the
320/// proof's public-IO file: [`verify_compressed`] and [`verify_recursive`] always use this constant.
321pub fn initial_state() -> Vec<Scalar> {
322    vec![Scalar::ZERO, Scalar::ZERO]
323}
324
325/// Commitment to the pinned initial state, `H(z₀[0], z₀[1])` (Poseidon, same sponge as the chain). Recorded in
326/// the public-IO fixture (`z0_commitment`) so an out-of-band consumer can check which start the proof was
327/// verified against; [`check_claimed_z0`] recomputes and compares it.
328pub fn initial_state_commitment() -> Scalar {
329    let z = initial_state();
330    hash2_native(z[0], z[1])
331}
332
333/// Compare a start state a *prover or fixture claims* against the pinned one. Succeeds only for exactly
334/// `[0, 0]`: right arity, canonical field elements, equal commitment.
335pub fn check_claimed_z0(claimed: &[Scalar]) -> Result<(), NovaError> {
336    let pinned = initial_state();
337    let ok = claimed.len() == pinned.len()
338        && claimed.iter().zip(&pinned).all(|(a, b)| a == b)
339        && (claimed.len() < 2 || hash2_native(claimed[0], claimed[1]) == initial_state_commitment());
340    if ok {
341        Ok(())
342    } else {
343        Err(NovaError::ProofVerifyError {
344            reason: "claimed initial state z0 differs from the pinned [0, 0]".to_string(),
345        })
346    }
347}
348
349/// Build the per-step circuits for a history.
350pub fn circuits_for(actions: &[ActionStep]) -> Vec<Circuit> {
351    actions
352        .iter()
353        .map(|a| ActionCircuit {
354            action_digest: Scalar::from(a.action_digest),
355            cost: Scalar::from(a.cost),
356        })
357        .collect()
358}
359
360/// Derive Nova public parameters for the step circuit (shape-only; witness values in
361/// `sample` are irrelevant).
362pub fn public_params(sample: &Circuit) -> Result<PP, NovaError> {
363    PublicParams::<E1, E2, Circuit>::setup(sample, &*S1::ck_floor(), &*S2::ck_floor())
364}
365
366/// A folded, verified recursive proof of one history, with everything needed to compress it.
367pub struct ProvedHistory {
368    pub pp: PP,
369    pub recursive: Recursive,
370    pub z0: Vec<Scalar>,
371    pub final_state: Vec<Scalar>,
372    pub num_steps: usize,
373}
374
375/// Fold an entire action history into one [`RecursiveSNARK`] and verify it.
376///
377/// Returns `Err` for an over-budget (or otherwise unsatisfiable) history: either a
378/// `prove_step` fails to fold, or the final `verify` rejects the accumulated instance — in
379/// release builds (the demo runs `--release`) the invariant surfaces as a rejected proof, never
380/// a panic.
381pub fn prove_history(actions: &[ActionStep]) -> Result<ProvedHistory, NovaError> {
382    assert!(!actions.is_empty(), "history must contain at least one action");
383    let circuits = circuits_for(actions);
384    let pp = public_params(&circuits[0])?;
385    let z0 = initial_state();
386
387    let mut recursive = RecursiveSNARK::<E1, E2, Circuit>::new(&pp, &circuits[0], &z0)?;
388    for c in &circuits {
389        recursive.prove_step(&pp, c)?;
390    }
391    let num_steps = circuits.len();
392    let final_state = verify_recursive(&pp, &recursive, num_steps)?;
393
394    Ok(ProvedHistory {
395        pp,
396        recursive,
397        z0,
398        final_state,
399        num_steps,
400    })
401}
402
403/// Verify a folded recursive proof against the PINNED initial state ([`initial_state`]). Returns the final
404/// `[chain_digest, budget_spent]`. There is deliberately no `z0` parameter (R3-15).
405pub fn verify_recursive(pp: &PP, recursive: &Recursive, num_steps: usize) -> Result<Vec<Scalar>, NovaError> {
406    recursive.verify(pp, num_steps, &initial_state())
407}
408
409/// [`verify_recursive`] for a caller that holds a *claimed* `z0` (e.g. read from a public-IO file): the claim is
410/// compared with the pinned start state first and the call fails if they differ. It can never verify a proof
411/// under any start other than `[0, 0]`.
412pub fn verify_recursive_claimed(
413    pp: &PP,
414    recursive: &Recursive,
415    num_steps: usize,
416    claimed_z0: &[Scalar],
417) -> Result<Vec<Scalar>, NovaError> {
418    check_claimed_z0(claimed_z0)?;
419    verify_recursive(pp, recursive, num_steps)
420}
421
422/// Derive the compressed-SNARK prover/verifier keys.
423pub fn compress_keys(pp: &PP) -> Result<(CompProverKey, CompVerifierKey), NovaError> {
424    CompressedSNARK::<E1, E2, Circuit, S1, S2>::setup(pp)
425}
426
427/// Compress the folded recursive proof into a single succinct [`CompressedSNARK`] — the one
428/// proof of the whole history.
429pub fn compress(
430    pp: &PP,
431    pk: &CompProverKey,
432    recursive: &Recursive,
433) -> Result<Compressed, NovaError> {
434    CompressedSNARK::<E1, E2, Circuit, S1, S2>::prove(pp, pk, recursive)
435}
436
437/// Verify the compressed proof against the PINNED initial state ([`initial_state`]). Returns the final
438/// `[chain_digest, budget_spent]`. There is deliberately no `z0` parameter (R3-15): the start state is part
439/// of what the verifier is, not something the prover or a fixture file gets to choose.
440pub fn verify_compressed(proof: &Compressed, vk: &CompVerifierKey, num_steps: usize) -> Result<Vec<Scalar>, NovaError> {
441    proof.verify(vk, num_steps, &initial_state())
442}
443
444/// [`verify_compressed`] for a caller that holds a *claimed* `z0`: fails unless the claim equals the pinned
445/// start state, and never verifies under any other start.
446pub fn verify_compressed_claimed(
447    proof: &Compressed,
448    vk: &CompVerifierKey,
449    num_steps: usize,
450    claimed_z0: &[Scalar],
451) -> Result<Vec<Scalar>, NovaError> {
452    check_claimed_z0(claimed_z0)?;
453    verify_compressed(proof, vk, num_steps)
454}
455
456// ---- small serialization helpers -----------------------------------------------------
457
458/// Big-endian `0x`-hex of a field element (for the JSON public-IO fixtures).
459pub fn felt_to_hex<F: PrimeField>(f: &F) -> String {
460    let repr = f.to_repr();
461    let mut be = repr.as_ref().to_vec(); // Pasta reprs are little-endian
462    be.reverse();
463    let mut s = String::with_capacity(2 + be.len() * 2);
464    s.push_str("0x");
465    for b in be {
466        s.push_str(&format!("{b:02x}"));
467    }
468    s
469}
470
471/// Extract bit `i` (little-endian) of a field element's canonical representation.
472fn get_bit_le<F: PrimeField>(v: &F, i: usize) -> bool {
473    let repr = v.to_repr();
474    let bytes = repr.as_ref();
475    let byte = i / 8;
476    if byte >= bytes.len() {
477        return false;
478    }
479    (bytes[byte] >> (i % 8)) & 1 == 1
480}