Skip to main content

moonproof_runtime_ir/
layout.rs

1//! Pure, dependency-free single source of truth for FAB `AlignedValue` ↔ ZKIR v3
2//! field-element layout.
3//!
4//! This module encodes the canonical atom and field-element geometry for every
5//! flat [`TypeDescriptor`] without depending on any ledger or proving crate:
6//!
7//! - **`Bytes<N>` chunking**: each native BLS12-381 scalar field element stores
8//!   at most [`FR_BYTES_STORED`] (31) arbitrary bytes. Multi-chunk `Bytes<N>`
9//!   values occupy `ceil(N / 31)` field elements (`0` for `Bytes<0>`), emitted
10//!   MSB-chunk-first in FAB [`ChunkOrder::MsbFirst`] and LSB-chunk-first in
11//!   ZKIR v3 [`ChunkOrder::LsbFirst`].
12//! - **`Uint` byte widths**: respects explicit `alignment-bytes` when present,
13//!   otherwise derives the standard `{1, 2, 4, 8, 16}`-byte alignment width from
14//!   `maxval` (or minimal byte width for wider bounds).
15//! - **Foreign-field limb splits & `-1 mod p` rotation**: two-atom foreign
16//!   fields store `(v - 1) mod p` split into `[24, 8]` bytes (192-bit low limb)
17//!   for secp256k1 / secp256r1 / Curve25519 base fields, and `[26, 7]` bytes
18//!   (204-bit low limb) for Curve25519's scalar field.
19//! - **Curve points**:
20//!   - `JubjubPoint`: 2 native `Field` slots (`x`, `y`).
21//!   - `Secp256k1Point` / `Secp256r1Point`: 5 slots (`x_lo`, `x_hi`, `y_lo`,
22//!     `y_hi`, native `Field` identity flag).
23//!   - `Curve25519Point`: 4 slots (`x_lo`, `x_hi`, `y_lo`, `y_hi`; Edwards
24//!     identity `(0, 1)` needs no flag).
25
26use ethnum::{I256, U256};
27
28use crate::ir::{FieldType, IntLit, TypeDescriptor};
29
30/// Maximum number of arbitrary raw bytes that fit unconditionally inside one
31/// native BLS12-381 scalar field element (`Fr`).
32pub const FR_BYTES_STORED: u32 = 31;
33
34/// Canonical little-endian byte width of a native BLS12-381 scalar field element.
35pub const FR_BYTES: u32 = 32;
36
37/// Order of the Jubjub scalar field.
38pub const JUBJUB_SCALAR_MODULUS: U256 = U256::from_words(
39    0x0E7D_B4EA_6533_AFA9_0667_3B01_0134_3B00,
40    0xA668_2093_CCC8_1082_D097_0E5E_D6F7_2CB7,
41);
42
43/// Order of the secp256k1 base field (`2^256 - 2^32 - 977`).
44pub const SECP256K1_BASE_MODULUS: U256 = U256::from_words(
45    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
46    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFE_FFFF_FC2F,
47);
48
49/// Order of the secp256k1 scalar field.
50pub const SECP256K1_SCALAR_MODULUS: U256 = U256::from_words(
51    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
52    0xBAAE_DCE6_AF48_A03B_BFD2_5E8C_D036_4141,
53);
54
55/// Order of the secp256r1 (P-256) base field (`2^256 - 2^224 + 2^192 + 2^96 - 1`).
56pub const SECP256R1_BASE_MODULUS: U256 = U256::from_words(
57    0xFFFF_FFFF_0000_0001_0000_0000_0000_0000,
58    0x0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
59);
60
61/// Order of the secp256r1 (P-256) scalar field.
62pub const SECP256R1_SCALAR_MODULUS: U256 = U256::from_words(
63    0xFFFF_FFFF_0000_0000_FFFF_FFFF_FFFF_FFFF,
64    0xBCE6_FAAD_A717_9E84_F3B9_CAC2_FC63_2551,
65);
66
67/// Order of the Curve25519 base field (`2^255 - 19`).
68pub const CURVE25519_BASE_MODULUS: U256 = U256::from_words(
69    0x7FFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
70    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFED,
71);
72
73/// Order of the Curve25519 prime-order scalar subgroup.
74pub const CURVE25519_SCALAR_MODULUS: U256 = U256::from_words(
75    0x1000_0000_0000_0000_0000_0000_0000_0000,
76    0x14DE_F9DE_A2F7_9CD6_5812_631A_5CF5_D3ED,
77);
78
79/// Ordering of 31-byte field-element chunks for multi-chunk `Bytes<N>` atoms.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub enum ChunkOrder {
82    /// FAB `AlignedValue` / `FieldRepr` order: most-significant chunk first
83    /// (e.g. `Bytes<32>` → `[bytes[31..32], bytes[0..31]]`).
84    MsbFirst,
85    /// ZKIR v3 circuit input/output order: least-significant chunk first
86    /// (e.g. `Bytes<32>` → `[bytes[0..31], bytes[31..32]]`).
87    LsbFirst,
88}
89
90/// Two-atom limb split geometry for a foreign field element.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub struct ForeignFieldSplit {
93    /// Number of bits held in the low limb atom.
94    pub low_bits: u32,
95    /// Byte width of the low limb `Bytes` atom.
96    pub low_bytes: u32,
97    /// Byte width of the high limb `Bytes` atom.
98    pub high_bytes: u32,
99}
100
101impl ForeignFieldSplit {
102    /// Standard 192/64-bit split (`bytes:24` + `bytes:8`) used by secp256k1,
103    /// secp256r1, and Curve25519 base fields.
104    pub const SPLIT_192: Self = Self {
105        low_bits: 192,
106        low_bytes: 24,
107        high_bytes: 8,
108    };
109
110    /// 204/49-bit split (`bytes:26` + `bytes:7`) used by Curve25519's scalar
111    /// field (five 51-bit internal limbs).
112    pub const SPLIT_204: Self = Self {
113        low_bits: 204,
114        low_bytes: 26,
115        high_bytes: 7,
116    };
117}
118
119/// Single FAB alignment atom in the flattened representation of a type.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub enum AtomLayout {
122    /// Fixed-length byte atom (`AlignmentAtom::Bytes { length }`).
123    Bytes { length: u32 },
124    /// Native BLS12-381 scalar field element (`AlignmentAtom::Field`).
125    Field,
126    /// Dynamically-sized opaque value compressed via `transient_commit`
127    /// (`AlignmentAtom::Compress`).
128    Compress,
129}
130
131impl AtomLayout {
132    /// Number of native field elements this atom occupies in ZKIR / `FieldRepr`.
133    #[must_use]
134    pub const fn field_slots(self) -> usize {
135        match self {
136            Self::Field | Self::Compress => 1,
137            Self::Bytes { length } => length.div_ceil(FR_BYTES_STORED) as usize,
138        }
139    }
140
141    /// Binary hash representation length in bytes (matches FAB `AlignmentAtom::bin_len`).
142    #[must_use]
143    pub const fn binary_len(self) -> usize {
144        match self {
145            Self::Field | Self::Compress => FR_BYTES as usize,
146            Self::Bytes { length } => length as usize,
147        }
148    }
149
150    /// Returns `true` if this atom spans more than one field element and therefore
151    /// depends on [`ChunkOrder`] when converting between FAB and ZKIR v3.
152    #[must_use]
153    pub const fn is_multi_chunk_bytes(self) -> bool {
154        matches!(self, Self::Bytes { length } if length > FR_BYTES_STORED)
155    }
156}
157
158/// Flattened FAB atom sequence and ZKIR field-element geometry for a [`TypeDescriptor`].
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct FieldLayout {
161    /// Ordered sequence of FAB alignment atoms comprising this type.
162    pub atoms: Vec<AtomLayout>,
163}
164
165impl FieldLayout {
166    /// Construct an empty layout (zero atoms, zero field slots).
167    #[must_use]
168    pub const fn empty() -> Self {
169        Self { atoms: Vec::new() }
170    }
171
172    /// Derive the flattened layout of a [`FieldType`].
173    #[must_use]
174    pub fn from_field_type(field_type: FieldType) -> Self {
175        match foreign_field_split(field_type) {
176            None => Self {
177                atoms: vec![AtomLayout::Field],
178            },
179            Some(split) => Self {
180                atoms: vec![
181                    AtomLayout::Bytes {
182                        length: split.low_bytes,
183                    },
184                    AtomLayout::Bytes {
185                        length: split.high_bytes,
186                    },
187                ],
188            },
189        }
190    }
191
192    /// Derive the flattened FAB / ZKIR layout of a [`TypeDescriptor`].
193    ///
194    /// Returns `None` for non-flat container types (`Map`, `Set`, `List`,
195    /// `MerkleTree`, `HistoricMerkleTree`), `Unknown`, or invalid `Uint` bounds.
196    #[must_use]
197    pub fn from_descriptor(descriptor: &TypeDescriptor) -> Option<Self> {
198        let mut atoms = Vec::new();
199        push_descriptor_atoms(descriptor, &mut atoms)?;
200        Some(Self { atoms })
201    }
202
203    /// Number of FAB alignment atoms.
204    #[must_use]
205    pub fn atom_count(&self) -> usize {
206        self.atoms.len()
207    }
208
209    /// Total number of native BLS12-381 field elements occupied by this type.
210    #[must_use]
211    pub fn field_slots(&self) -> usize {
212        self.atoms.iter().map(|a| a.field_slots()).sum()
213    }
214
215    /// Total binary hash representation length in bytes.
216    #[must_use]
217    pub fn binary_len(&self) -> usize {
218        self.atoms.iter().map(|a| a.binary_len()).sum()
219    }
220
221    /// Returns `true` if any atom in this layout is a multi-chunk `Bytes<N>`
222    /// (`N > 31`) whose field-element order differs between FAB and ZKIR v3.
223    #[must_use]
224    pub fn needs_chunk_reordering(&self) -> bool {
225        self.atoms.iter().any(|a| a.is_multi_chunk_bytes())
226    }
227
228    /// Convert a flat slice of field-element slots for this layout between
229    /// [`ChunkOrder::MsbFirst`] (FAB) and [`ChunkOrder::LsbFirst`] (ZKIR v3).
230    ///
231    /// Reverses the sub-slice belonging to each multi-chunk `Bytes<N>` (`N > 31`)
232    /// atom when `from != to`, while leaving single-slot atoms (including the two
233    /// separate limb atoms of foreign fields) in place.
234    ///
235    /// Returns `None` if `slots.len() != self.field_slots()`.
236    #[must_use]
237    pub fn reorder_field_slots<T: Clone>(
238        &self,
239        slots: &[T],
240        from: ChunkOrder,
241        to: ChunkOrder,
242    ) -> Option<Vec<T>> {
243        if slots.len() != self.field_slots() {
244            return None;
245        }
246        if from == to || !self.needs_chunk_reordering() {
247            return Some(slots.to_vec());
248        }
249        let mut out = Vec::with_capacity(slots.len());
250        let mut offset = 0;
251        for atom in &self.atoms {
252            let n = atom.field_slots();
253            let slice = &slots[offset..offset + n];
254            if atom.is_multi_chunk_bytes() {
255                out.extend(slice.iter().rev().cloned());
256            } else {
257                out.extend_from_slice(slice);
258            }
259            offset += n;
260        }
261        Some(out)
262    }
263}
264
265fn push_foreign_split(split: ForeignFieldSplit, out: &mut Vec<AtomLayout>) {
266    out.push(AtomLayout::Bytes {
267        length: split.low_bytes,
268    });
269    out.push(AtomLayout::Bytes {
270        length: split.high_bytes,
271    });
272}
273
274fn push_descriptor_atoms(descriptor: &TypeDescriptor, out: &mut Vec<AtomLayout>) -> Option<()> {
275    match descriptor {
276        TypeDescriptor::Boolean | TypeDescriptor::Enum { .. } => {
277            out.push(AtomLayout::Bytes { length: 1 });
278        }
279        TypeDescriptor::Field | TypeDescriptor::JubjubScalar => {
280            out.push(AtomLayout::Field);
281        }
282        TypeDescriptor::Secp256k1Base
283        | TypeDescriptor::Secp256k1Scalar
284        | TypeDescriptor::Secp256r1Base
285        | TypeDescriptor::Secp256r1Scalar
286        | TypeDescriptor::Curve25519Base => {
287            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
288        }
289        TypeDescriptor::Curve25519Scalar => {
290            push_foreign_split(ForeignFieldSplit::SPLIT_204, out);
291        }
292        TypeDescriptor::JubjubPoint => {
293            out.push(AtomLayout::Field);
294            out.push(AtomLayout::Field);
295        }
296        TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
297            // x (24 + 8), y (24 + 8), identity flag (Field)
298            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
299            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
300            out.push(AtomLayout::Field);
301        }
302        TypeDescriptor::Curve25519Point => {
303            // Edwards (x, y), each a Curve25519Base (24 + 8) pair; no identity flag.
304            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
305            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
306        }
307        TypeDescriptor::Uint {
308            maxval,
309            alignment_bytes,
310        } => {
311            let length = uint_byte_width(maxval, *alignment_bytes)?;
312            out.push(AtomLayout::Bytes { length });
313        }
314        TypeDescriptor::Bytes { length } => {
315            out.push(AtomLayout::Bytes { length: *length });
316        }
317        TypeDescriptor::Counter => {
318            out.push(AtomLayout::Bytes { length: 8 });
319        }
320        TypeDescriptor::Opaque { ts_type } => {
321            if ts_type == "JubjubPoint" {
322                out.push(AtomLayout::Field);
323                out.push(AtomLayout::Field);
324            } else {
325                out.push(AtomLayout::Compress);
326            }
327        }
328        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
329            push_descriptor_atoms(of, out)?;
330        }
331        TypeDescriptor::Contract { .. } => {
332            out.push(AtomLayout::Bytes { length: 32 });
333        }
334        TypeDescriptor::Tuple { types } => {
335            for ty in types {
336                push_descriptor_atoms(ty, out)?;
337            }
338        }
339        TypeDescriptor::Vector { length, elt_type } => {
340            if *length == 0 {
341                return Some(());
342            }
343            let mut elem_atoms = Vec::new();
344            push_descriptor_atoms(elt_type, &mut elem_atoms)?;
345            let count = usize::try_from(*length).ok()?;
346            out.reserve(elem_atoms.len().checked_mul(count)?);
347            for _ in 0..count {
348                out.extend_from_slice(&elem_atoms);
349            }
350        }
351        TypeDescriptor::Struct { elements, .. } => {
352            for field in elements {
353                push_descriptor_atoms(&field.field_type, out)?;
354            }
355        }
356        TypeDescriptor::Map { .. }
357        | TypeDescriptor::Set { .. }
358        | TypeDescriptor::List { .. }
359        | TypeDescriptor::MerkleTree { .. }
360        | TypeDescriptor::HistoricMerkleTree { .. }
361        | TypeDescriptor::Unknown => return None,
362    }
363    Some(())
364}
365
366/// Compute the FAB `Bytes` atom width for a `Uint { maxval, alignment_bytes }`.
367///
368/// If `alignment_bytes` is explicitly provided and non-zero, it is returned
369/// directly. Otherwise follows the standard runtime convention:
370/// `<= u8::MAX` → 1, `<= u16::MAX` → 2, `<= u32::MAX` → 4, `<= u64::MAX` → 8,
371/// `<= u128::MAX` → 16, or minimal bytes for wider non-negative bounds.
372/// Returns `None` for negative `maxval`.
373#[must_use]
374pub fn uint_byte_width(maxval: &IntLit, alignment_bytes: Option<u32>) -> Option<u32> {
375    if maxval.0 < I256::ZERO {
376        return None;
377    }
378    if let Some(explicit) = alignment_bytes
379        && explicit > 0
380    {
381        return Some(explicit);
382    }
383    if let Some(max) = maxval.as_u128() {
384        let width = if max <= u128::from(u8::MAX) {
385            1
386        } else if max <= u128::from(u16::MAX) {
387            2
388        } else if max <= u128::from(u32::MAX) {
389            4
390        } else if max <= u128::from(u64::MAX) {
391            8
392        } else {
393            16
394        };
395        return Some(width);
396    }
397    // Non-negative value > u128::MAX: compute minimal byte width from bit length.
398    let bits = 256u32.saturating_sub(maxval.0.leading_zeros());
399    Some(bits.div_ceil(8).max(1))
400}
401
402/// Number of native field elements required to store `byte_len` raw bytes.
403#[must_use]
404pub const fn bytes_field_slots(byte_len: u32) -> usize {
405    byte_len.div_ceil(FR_BYTES_STORED) as usize
406}
407
408/// Split a raw byte buffer into 32-byte little-endian field-element limbs
409/// (each carrying up to [`FR_BYTES_STORED`] = 31 bytes) in the requested [`ChunkOrder`].
410#[must_use]
411pub fn bytes_to_field_chunks(bytes: &[u8], order: ChunkOrder) -> Vec<[u8; 32]> {
412    let chunk_size = FR_BYTES_STORED as usize;
413    let mut chunks: Vec<[u8; 32]> = bytes
414        .chunks(chunk_size)
415        .map(|slice| {
416            let mut limb = [0u8; 32];
417            limb[..slice.len()].copy_from_slice(slice);
418            limb
419        })
420        .collect();
421    if order == ChunkOrder::MsbFirst {
422        chunks.reverse();
423    }
424    chunks
425}
426
427/// Reassemble `byte_len` raw bytes from 32-byte little-endian field-element limbs
428/// ordered according to `order`.
429///
430/// Validates both chunk count and that unused upper bytes in every limb are zero.
431#[must_use]
432pub fn field_chunks_to_bytes(
433    chunks: &[[u8; 32]],
434    byte_len: u32,
435    order: ChunkOrder,
436) -> Option<Vec<u8>> {
437    let expected = bytes_field_slots(byte_len);
438    if chunks.len() != expected {
439        return None;
440    }
441    let total = byte_len as usize;
442    if total == 0 {
443        return Some(Vec::new());
444    }
445    let chunk_size = FR_BYTES_STORED as usize;
446    let mut out = vec![0u8; total];
447    for lsb_idx in 0..expected {
448        let src_idx = match order {
449            ChunkOrder::LsbFirst => lsb_idx,
450            ChunkOrder::MsbFirst => expected - 1 - lsb_idx,
451        };
452        let start = lsb_idx * chunk_size;
453        let width = (total - start).min(chunk_size);
454        let limb = &chunks[src_idx];
455        if limb[width..].iter().any(|&b| b != 0) {
456            return None;
457        }
458        out[start..start + width].copy_from_slice(&limb[..width]);
459    }
460    Some(out)
461}
462
463/// Reorder a slice of field-element chunks belonging to a single `Bytes<N>` atom
464/// between [`ChunkOrder::MsbFirst`] and [`ChunkOrder::LsbFirst`].
465#[must_use]
466pub fn reorder_chunks<T: Clone>(chunks: &[T], from: ChunkOrder, to: ChunkOrder) -> Vec<T> {
467    if from == to {
468        chunks.to_vec()
469    } else {
470        chunks.iter().rev().cloned().collect()
471    }
472}
473
474/// Prime modulus of a non-native [`FieldType`], or `None` for the native BLS12-381 `Field`.
475#[must_use]
476pub const fn foreign_field_modulus(field_type: FieldType) -> Option<U256> {
477    match field_type {
478        FieldType::Field => None,
479        FieldType::JubjubScalar => Some(JUBJUB_SCALAR_MODULUS),
480        FieldType::Secp256k1Base => Some(SECP256K1_BASE_MODULUS),
481        FieldType::Secp256k1Scalar => Some(SECP256K1_SCALAR_MODULUS),
482        FieldType::Secp256r1Base => Some(SECP256R1_BASE_MODULUS),
483        FieldType::Secp256r1Scalar => Some(SECP256R1_SCALAR_MODULUS),
484        FieldType::Curve25519Base => Some(CURVE25519_BASE_MODULUS),
485        FieldType::Curve25519Scalar => Some(CURVE25519_SCALAR_MODULUS),
486    }
487}
488
489/// Two-atom limb split for a foreign [`FieldType`], or `None` for single-atom
490/// fields (`Field`, `JubjubScalar`).
491#[must_use]
492pub const fn foreign_field_split(field_type: FieldType) -> Option<ForeignFieldSplit> {
493    match field_type {
494        FieldType::Field | FieldType::JubjubScalar => None,
495        FieldType::Curve25519Scalar => Some(ForeignFieldSplit::SPLIT_204),
496        FieldType::Secp256k1Base
497        | FieldType::Secp256k1Scalar
498        | FieldType::Secp256r1Base
499        | FieldType::Secp256r1Scalar
500        | FieldType::Curve25519Base => Some(ForeignFieldSplit::SPLIT_192),
501    }
502}
503
504/// Apply the ZKIR/FAB `-1 mod p` rotation to a two-atom foreign field element
505/// (`0 -> p - 1`, `v -> v - 1`). Returns `None` if `field_type` is not a
506/// two-atom foreign field or `value >= p`.
507#[must_use]
508pub fn rotate_foreign_to_wire(field_type: FieldType, value: U256) -> Option<U256> {
509    foreign_field_split(field_type)?;
510    let modulus = foreign_field_modulus(field_type)?;
511    if value >= modulus {
512        return None;
513    }
514    let max = modulus - U256::ONE;
515    Some(if value == U256::ZERO {
516        max
517    } else {
518        value - U256::ONE
519    })
520}
521
522/// Undo the ZKIR/FAB `-1 mod p` rotation on a two-atom foreign field element
523/// (`p - 1 -> 0`, `w -> w + 1`). Returns `None` if `field_type` is not a
524/// two-atom foreign field or `wire >= p`.
525#[must_use]
526pub fn rotate_foreign_from_wire(field_type: FieldType, wire: U256) -> Option<U256> {
527    foreign_field_split(field_type)?;
528    let modulus = foreign_field_modulus(field_type)?;
529    if wire >= modulus {
530        return None;
531    }
532    let max = modulus - U256::ONE;
533    Some(if wire == max {
534        U256::ZERO
535    } else {
536        wire + U256::ONE
537    })
538}
539
540/// Rotate a foreign field element by `-1 mod p` and split it into its fixed-width
541/// little-endian `(low_bytes, high_bytes)` limbs (`[24, 8]` or `[26, 7]`).
542#[must_use]
543pub fn split_foreign_limbs(field_type: FieldType, value: U256) -> Option<(Vec<u8>, Vec<u8>)> {
544    let split = foreign_field_split(field_type)?;
545    let rotated = rotate_foreign_to_wire(field_type, value)?;
546    let low_mask = (U256::ONE << split.low_bits) - U256::ONE;
547    let low = rotated & low_mask;
548    let high = rotated >> split.low_bits;
549    let low_le = low.to_le_bytes()[..split.low_bytes as usize].to_vec();
550    let high_le = high.to_le_bytes()[..split.high_bytes as usize].to_vec();
551    Some((low_le, high_le))
552}
553
554/// Reassemble little-endian `(low_le, high_le)` foreign-field limb bytes and
555/// undo the `-1 mod p` rotation.
556#[must_use]
557pub fn join_foreign_limbs(field_type: FieldType, low_le: &[u8], high_le: &[u8]) -> Option<U256> {
558    let split = foreign_field_split(field_type)?;
559    if low_le.len() > split.low_bytes as usize || high_le.len() > split.high_bytes as usize {
560        return None;
561    }
562    let mut low_buf = [0u8; 32];
563    low_buf[..low_le.len()].copy_from_slice(low_le);
564    let low = U256::from_le_bytes(low_buf);
565    if low >= (U256::ONE << split.low_bits) {
566        return None;
567    }
568    let mut high_buf = [0u8; 32];
569    high_buf[..high_le.len()].copy_from_slice(high_le);
570    let high = U256::from_le_bytes(high_buf);
571    // Reject values that would overflow 256 bits on shift.
572    if high >= (U256::ONE << (256 - split.low_bits)) {
573        return None;
574    }
575    let wire = (high << split.low_bits) | low;
576    rotate_foreign_from_wire(field_type, wire)
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use crate::ir::StructField;
583
584    #[test]
585    fn bytes_chunking_msb_vs_lsb_32_bytes() {
586        let mut raw = [0u8; 32];
587        for (i, b) in raw.iter_mut().enumerate() {
588            #[allow(clippy::cast_possible_truncation)]
589            {
590                *b = (i as u8) + 1;
591            }
592        }
593
594        let fab = bytes_to_field_chunks(&raw, ChunkOrder::MsbFirst);
595        let zkir = bytes_to_field_chunks(&raw, ChunkOrder::LsbFirst);
596        assert_eq!(fab.len(), 2);
597        assert_eq!(zkir.len(), 2);
598
599        // FAB MsbFirst: slot 0 has byte[31] (= 32), slot 1 has bytes[0..31] (= 1..=31).
600        assert_eq!(fab[0][0], 32);
601        assert!(fab[0][1..].iter().all(|&b| b == 0));
602        assert_eq!(&fab[1][..31], &raw[..31]);
603        assert_eq!(fab[1][31], 0);
604
605        // ZKIR v3 LsbFirst: exact reverse.
606        assert_eq!(zkir[0], fab[1]);
607        assert_eq!(zkir[1], fab[0]);
608        assert_eq!(
609            reorder_chunks(&fab, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst),
610            zkir
611        );
612
613        // Round-trip reassembly in both orders.
614        assert_eq!(
615            field_chunks_to_bytes(&fab, 32, ChunkOrder::MsbFirst).as_deref(),
616            Some(&raw[..])
617        );
618        assert_eq!(
619            field_chunks_to_bytes(&zkir, 32, ChunkOrder::LsbFirst).as_deref(),
620            Some(&raw[..])
621        );
622    }
623
624    #[test]
625    fn bytes_chunking_edge_lengths() {
626        // Bytes<0> → 0 field slots.
627        assert_eq!(bytes_field_slots(0), 0);
628        assert_eq!(
629            bytes_to_field_chunks(&[], ChunkOrder::MsbFirst),
630            Vec::<[u8; 32]>::new()
631        );
632        assert_eq!(
633            field_chunks_to_bytes(&[], 0, ChunkOrder::LsbFirst),
634            Some(Vec::new())
635        );
636
637        // Bytes<31> → 1 field slot (identical in MSB and LSB).
638        let b31 = [0x5au8; 31];
639        let msb31 = bytes_to_field_chunks(&b31, ChunkOrder::MsbFirst);
640        let lsb31 = bytes_to_field_chunks(&b31, ChunkOrder::LsbFirst);
641        assert_eq!(msb31.len(), 1);
642        assert_eq!(msb31, lsb31);
643        assert_eq!(
644            field_chunks_to_bytes(&msb31, 31, ChunkOrder::MsbFirst).as_deref(),
645            Some(&b31[..])
646        );
647
648        // Bytes<64> → 3 field slots: [62..64], [31..62], [0..31] in FAB.
649        let b64: Vec<u8> = (0u8..64).collect();
650        let msb64 = bytes_to_field_chunks(&b64, ChunkOrder::MsbFirst);
651        let lsb64 = bytes_to_field_chunks(&b64, ChunkOrder::LsbFirst);
652        assert_eq!(msb64.len(), 3);
653        assert_eq!(&msb64[0][..2], &[62, 63]);
654        assert!(msb64[0][2..].iter().all(|&b| b == 0));
655        assert_eq!(&msb64[1][..31], &b64[31..62]);
656        assert_eq!(&msb64[2][..31], &b64[0..31]);
657        assert_eq!(
658            field_chunks_to_bytes(&msb64, 64, ChunkOrder::MsbFirst),
659            Some(b64.clone())
660        );
661        assert_eq!(
662            field_chunks_to_bytes(&lsb64, 64, ChunkOrder::LsbFirst),
663            Some(b64)
664        );
665
666        // Reject dirty padding bytes in MSB chunk.
667        let mut bad = msb64;
668        bad[0][2] = 1;
669        assert_eq!(field_chunks_to_bytes(&bad, 64, ChunkOrder::MsbFirst), None);
670    }
671
672    #[test]
673    fn uint_byte_widths_match_runtime_convention() {
674        assert_eq!(uint_byte_width(&IntLit::from_u128(0), None), Some(1));
675        assert_eq!(uint_byte_width(&IntLit::from_u128(255), None), Some(1));
676        assert_eq!(uint_byte_width(&IntLit::from_u128(256), None), Some(2));
677        assert_eq!(
678            uint_byte_width(&IntLit::from_u128(u128::from(u16::MAX)), None),
679            Some(2)
680        );
681        assert_eq!(
682            uint_byte_width(&IntLit::from_u128(u128::from(u32::MAX)), None),
683            Some(4)
684        );
685        assert_eq!(
686            uint_byte_width(&IntLit::from_u128(u128::from(u64::MAX)), None),
687            Some(8)
688        );
689        assert_eq!(
690            uint_byte_width(&IntLit::from_u128(u128::MAX), None),
691            Some(16)
692        );
693        // Explicit alignment-bytes overrides power-of-2 bucket.
694        assert_eq!(
695            uint_byte_width(&IntLit::from_u128(16_777_215), Some(3)),
696            Some(3)
697        );
698        // Negative maxval is rejected.
699        assert_eq!(uint_byte_width(&IntLit::from_i128(-1), None), None);
700    }
701
702    #[test]
703    fn foreign_field_rotation_and_limb_splits() {
704        for ft in [
705            FieldType::Secp256k1Base,
706            FieldType::Secp256k1Scalar,
707            FieldType::Secp256r1Base,
708            FieldType::Secp256r1Scalar,
709            FieldType::Curve25519Base,
710            FieldType::Curve25519Scalar,
711        ] {
712            let modulus = foreign_field_modulus(ft).unwrap();
713            let split = foreign_field_split(ft).unwrap();
714            if ft == FieldType::Curve25519Scalar {
715                assert_eq!((split.low_bytes, split.high_bytes), (26, 7));
716            } else {
717                assert_eq!((split.low_bytes, split.high_bytes), (24, 8));
718            }
719
720            // 0 rotates to modulus - 1, and back to 0.
721            assert_eq!(rotate_foreign_to_wire(ft, U256::ZERO), Some(modulus - 1));
722            assert_eq!(rotate_foreign_from_wire(ft, modulus - 1), Some(U256::ZERO));
723
724            // Test 0, 1, 42, modulus - 1 through full limb split + join.
725            for val in [U256::ZERO, U256::ONE, U256::from(42u64), modulus - 1] {
726                let (lo, hi) = split_foreign_limbs(ft, val).unwrap();
727                assert_eq!(lo.len(), split.low_bytes as usize);
728                assert_eq!(hi.len(), split.high_bytes as usize);
729                assert_eq!(join_foreign_limbs(ft, &lo, &hi), Some(val));
730            }
731
732            // Out-of-range value (>= modulus) is rejected.
733            assert_eq!(rotate_foreign_to_wire(ft, modulus), None);
734        }
735
736        // Native Field and JubjubScalar are single-atom (no split).
737        assert_eq!(foreign_field_split(FieldType::Field), None);
738        assert_eq!(foreign_field_split(FieldType::JubjubScalar), None);
739    }
740
741    #[test]
742    fn curve_point_and_compound_field_layouts() {
743        let jj = FieldLayout::from_descriptor(&TypeDescriptor::JubjubPoint).unwrap();
744        assert_eq!(jj.atom_count(), 2);
745        assert_eq!(jj.field_slots(), 2);
746        assert!(!jj.needs_chunk_reordering());
747
748        let secp = FieldLayout::from_descriptor(&TypeDescriptor::Secp256k1Point).unwrap();
749        assert_eq!(secp.atom_count(), 5);
750        assert_eq!(secp.field_slots(), 5);
751        assert_eq!(
752            secp.atoms,
753            vec![
754                AtomLayout::Bytes { length: 24 },
755                AtomLayout::Bytes { length: 8 },
756                AtomLayout::Bytes { length: 24 },
757                AtomLayout::Bytes { length: 8 },
758                AtomLayout::Field,
759            ]
760        );
761        assert!(!secp.needs_chunk_reordering());
762
763        let p256 = FieldLayout::from_descriptor(&TypeDescriptor::Secp256r1Point).unwrap();
764        assert_eq!(p256, secp);
765
766        let c25519 = FieldLayout::from_descriptor(&TypeDescriptor::Curve25519Point).unwrap();
767        assert_eq!(c25519.atom_count(), 4);
768        assert_eq!(c25519.field_slots(), 4);
769
770        // Compound struct mixing single-slot and multi-chunk Bytes<32> atoms.
771        let note = TypeDescriptor::Struct {
772            name: "Note".to_owned(),
773            elements: vec![
774                StructField {
775                    name: "owner".to_owned(),
776                    field_type: TypeDescriptor::Bytes { length: 32 },
777                },
778                StructField {
779                    name: "amount".to_owned(),
780                    field_type: TypeDescriptor::Uint {
781                        maxval: IntLit::from_u128(u128::from(u64::MAX)),
782                        alignment_bytes: None,
783                    },
784                },
785                StructField {
786                    name: "pk".to_owned(),
787                    field_type: TypeDescriptor::Secp256k1Base,
788                },
789            ],
790        };
791        let layout = FieldLayout::from_descriptor(&note).unwrap();
792        assert_eq!(layout.atom_count(), 4);
793        assert_eq!(layout.field_slots(), 5);
794        assert!(layout.needs_chunk_reordering());
795
796        // Slot order in FAB: [owner_msb, owner_lsb, amount, pk_lo, pk_hi]
797        let fab_slots = [10u32, 20, 30, 40, 50];
798        let zkir_slots = layout
799            .reorder_field_slots(&fab_slots, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst)
800            .unwrap();
801        // Only owner's 2 chunks swap; amount and pk limbs stay in order.
802        assert_eq!(zkir_slots, vec![20, 10, 30, 40, 50]);
803        assert_eq!(
804            layout
805                .reorder_field_slots(&zkir_slots, ChunkOrder::LsbFirst, ChunkOrder::MsbFirst)
806                .unwrap(),
807            fab_slots
808        );
809
810        // Non-flat container returns None.
811        assert_eq!(
812            FieldLayout::from_descriptor(&TypeDescriptor::Map {
813                key: Box::new(TypeDescriptor::Field),
814                value: Box::new(TypeDescriptor::Counter),
815            }),
816            None
817        );
818    }
819}