moonproof-runtime-ir 0.2.0

Rust consumer for compactc's contract.mpir — language-agnostic Compact contract IR. Loads, validates, and (eventually) interprets the IR to drive moonproof's contract runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! Pure, dependency-free single source of truth for FAB `AlignedValue` ↔ ZKIR v3
//! field-element layout.
//!
//! This module encodes the canonical atom and field-element geometry for every
//! flat [`TypeDescriptor`] without depending on any ledger or proving crate:
//!
//! - **`Bytes<N>` chunking**: each native BLS12-381 scalar field element stores
//!   at most [`FR_BYTES_STORED`] (31) arbitrary bytes. Multi-chunk `Bytes<N>`
//!   values occupy `ceil(N / 31)` field elements (`0` for `Bytes<0>`), emitted
//!   MSB-chunk-first in FAB [`ChunkOrder::MsbFirst`] and LSB-chunk-first in
//!   ZKIR v3 [`ChunkOrder::LsbFirst`].
//! - **`Uint` byte widths**: respects explicit `alignment-bytes` when present,
//!   otherwise derives the standard `{1, 2, 4, 8, 16}`-byte alignment width from
//!   `maxval` (or minimal byte width for wider bounds).
//! - **Foreign-field limb splits & `-1 mod p` rotation**: two-atom foreign
//!   fields store `(v - 1) mod p` split into `[24, 8]` bytes (192-bit low limb)
//!   for secp256k1 / secp256r1 / Curve25519 base fields, and `[26, 7]` bytes
//!   (204-bit low limb) for Curve25519's scalar field.
//! - **Curve points**:
//!   - `JubjubPoint`: 2 native `Field` slots (`x`, `y`).
//!   - `Secp256k1Point` / `Secp256r1Point`: 5 slots (`x_lo`, `x_hi`, `y_lo`,
//!     `y_hi`, native `Field` identity flag).
//!   - `Curve25519Point`: 4 slots (`x_lo`, `x_hi`, `y_lo`, `y_hi`; Edwards
//!     identity `(0, 1)` needs no flag).

use ethnum::{I256, U256};

use crate::ir::{FieldType, IntLit, TypeDescriptor};

/// Maximum number of arbitrary raw bytes that fit unconditionally inside one
/// native BLS12-381 scalar field element (`Fr`).
pub const FR_BYTES_STORED: u32 = 31;

/// Canonical little-endian byte width of a native BLS12-381 scalar field element.
pub const FR_BYTES: u32 = 32;

/// Order of the Jubjub scalar field.
pub const JUBJUB_SCALAR_MODULUS: U256 = U256::from_words(
    0x0E7D_B4EA_6533_AFA9_0667_3B01_0134_3B00,
    0xA668_2093_CCC8_1082_D097_0E5E_D6F7_2CB7,
);

/// Order of the secp256k1 base field (`2^256 - 2^32 - 977`).
pub const SECP256K1_BASE_MODULUS: U256 = U256::from_words(
    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFE_FFFF_FC2F,
);

/// Order of the secp256k1 scalar field.
pub const SECP256K1_SCALAR_MODULUS: U256 = U256::from_words(
    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
    0xBAAE_DCE6_AF48_A03B_BFD2_5E8C_D036_4141,
);

/// Order of the secp256r1 (P-256) base field (`2^256 - 2^224 + 2^192 + 2^96 - 1`).
pub const SECP256R1_BASE_MODULUS: U256 = U256::from_words(
    0xFFFF_FFFF_0000_0001_0000_0000_0000_0000,
    0x0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
);

/// Order of the secp256r1 (P-256) scalar field.
pub const SECP256R1_SCALAR_MODULUS: U256 = U256::from_words(
    0xFFFF_FFFF_0000_0000_FFFF_FFFF_FFFF_FFFF,
    0xBCE6_FAAD_A717_9E84_F3B9_CAC2_FC63_2551,
);

/// Order of the Curve25519 base field (`2^255 - 19`).
pub const CURVE25519_BASE_MODULUS: U256 = U256::from_words(
    0x7FFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
    0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFED,
);

/// Order of the Curve25519 prime-order scalar subgroup.
pub const CURVE25519_SCALAR_MODULUS: U256 = U256::from_words(
    0x1000_0000_0000_0000_0000_0000_0000_0000,
    0x14DE_F9DE_A2F7_9CD6_5812_631A_5CF5_D3ED,
);

/// Ordering of 31-byte field-element chunks for multi-chunk `Bytes<N>` atoms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChunkOrder {
    /// FAB `AlignedValue` / `FieldRepr` order: most-significant chunk first
    /// (e.g. `Bytes<32>` → `[bytes[31..32], bytes[0..31]]`).
    MsbFirst,
    /// ZKIR v3 circuit input/output order: least-significant chunk first
    /// (e.g. `Bytes<32>` → `[bytes[0..31], bytes[31..32]]`).
    LsbFirst,
}

/// Two-atom limb split geometry for a foreign field element.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ForeignFieldSplit {
    /// Number of bits held in the low limb atom.
    pub low_bits: u32,
    /// Byte width of the low limb `Bytes` atom.
    pub low_bytes: u32,
    /// Byte width of the high limb `Bytes` atom.
    pub high_bytes: u32,
}

impl ForeignFieldSplit {
    /// Standard 192/64-bit split (`bytes:24` + `bytes:8`) used by secp256k1,
    /// secp256r1, and Curve25519 base fields.
    pub const SPLIT_192: Self = Self {
        low_bits: 192,
        low_bytes: 24,
        high_bytes: 8,
    };

    /// 204/49-bit split (`bytes:26` + `bytes:7`) used by Curve25519's scalar
    /// field (five 51-bit internal limbs).
    pub const SPLIT_204: Self = Self {
        low_bits: 204,
        low_bytes: 26,
        high_bytes: 7,
    };
}

/// Single FAB alignment atom in the flattened representation of a type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AtomLayout {
    /// Fixed-length byte atom (`AlignmentAtom::Bytes { length }`).
    Bytes { length: u32 },
    /// Native BLS12-381 scalar field element (`AlignmentAtom::Field`).
    Field,
    /// Dynamically-sized opaque value compressed via `transient_commit`
    /// (`AlignmentAtom::Compress`).
    Compress,
}

impl AtomLayout {
    /// Number of native field elements this atom occupies in ZKIR / `FieldRepr`.
    #[must_use]
    pub const fn field_slots(self) -> usize {
        match self {
            Self::Field | Self::Compress => 1,
            Self::Bytes { length } => length.div_ceil(FR_BYTES_STORED) as usize,
        }
    }

    /// Binary hash representation length in bytes (matches FAB `AlignmentAtom::bin_len`).
    #[must_use]
    pub const fn binary_len(self) -> usize {
        match self {
            Self::Field | Self::Compress => FR_BYTES as usize,
            Self::Bytes { length } => length as usize,
        }
    }

    /// Returns `true` if this atom spans more than one field element and therefore
    /// depends on [`ChunkOrder`] when converting between FAB and ZKIR v3.
    #[must_use]
    pub const fn is_multi_chunk_bytes(self) -> bool {
        matches!(self, Self::Bytes { length } if length > FR_BYTES_STORED)
    }
}

/// Flattened FAB atom sequence and ZKIR field-element geometry for a [`TypeDescriptor`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldLayout {
    /// Ordered sequence of FAB alignment atoms comprising this type.
    pub atoms: Vec<AtomLayout>,
}

impl FieldLayout {
    /// Construct an empty layout (zero atoms, zero field slots).
    #[must_use]
    pub const fn empty() -> Self {
        Self { atoms: Vec::new() }
    }

    /// Derive the flattened layout of a [`FieldType`].
    #[must_use]
    pub fn from_field_type(field_type: FieldType) -> Self {
        match foreign_field_split(field_type) {
            None => Self {
                atoms: vec![AtomLayout::Field],
            },
            Some(split) => Self {
                atoms: vec![
                    AtomLayout::Bytes {
                        length: split.low_bytes,
                    },
                    AtomLayout::Bytes {
                        length: split.high_bytes,
                    },
                ],
            },
        }
    }

    /// Derive the flattened FAB / ZKIR layout of a [`TypeDescriptor`].
    ///
    /// Returns `None` for non-flat container types (`Map`, `Set`, `List`,
    /// `MerkleTree`, `HistoricMerkleTree`), `Unknown`, or invalid `Uint` bounds.
    #[must_use]
    pub fn from_descriptor(descriptor: &TypeDescriptor) -> Option<Self> {
        let mut atoms = Vec::new();
        push_descriptor_atoms(descriptor, &mut atoms)?;
        Some(Self { atoms })
    }

    /// Number of FAB alignment atoms.
    #[must_use]
    pub fn atom_count(&self) -> usize {
        self.atoms.len()
    }

    /// Total number of native BLS12-381 field elements occupied by this type.
    #[must_use]
    pub fn field_slots(&self) -> usize {
        self.atoms.iter().map(|a| a.field_slots()).sum()
    }

    /// Total binary hash representation length in bytes.
    #[must_use]
    pub fn binary_len(&self) -> usize {
        self.atoms.iter().map(|a| a.binary_len()).sum()
    }

    /// Returns `true` if any atom in this layout is a multi-chunk `Bytes<N>`
    /// (`N > 31`) whose field-element order differs between FAB and ZKIR v3.
    #[must_use]
    pub fn needs_chunk_reordering(&self) -> bool {
        self.atoms.iter().any(|a| a.is_multi_chunk_bytes())
    }

    /// Convert a flat slice of field-element slots for this layout between
    /// [`ChunkOrder::MsbFirst`] (FAB) and [`ChunkOrder::LsbFirst`] (ZKIR v3).
    ///
    /// Reverses the sub-slice belonging to each multi-chunk `Bytes<N>` (`N > 31`)
    /// atom when `from != to`, while leaving single-slot atoms (including the two
    /// separate limb atoms of foreign fields) in place.
    ///
    /// Returns `None` if `slots.len() != self.field_slots()`.
    #[must_use]
    pub fn reorder_field_slots<T: Clone>(
        &self,
        slots: &[T],
        from: ChunkOrder,
        to: ChunkOrder,
    ) -> Option<Vec<T>> {
        if slots.len() != self.field_slots() {
            return None;
        }
        if from == to || !self.needs_chunk_reordering() {
            return Some(slots.to_vec());
        }
        let mut out = Vec::with_capacity(slots.len());
        let mut offset = 0;
        for atom in &self.atoms {
            let n = atom.field_slots();
            let slice = &slots[offset..offset + n];
            if atom.is_multi_chunk_bytes() {
                out.extend(slice.iter().rev().cloned());
            } else {
                out.extend_from_slice(slice);
            }
            offset += n;
        }
        Some(out)
    }
}

fn push_foreign_split(split: ForeignFieldSplit, out: &mut Vec<AtomLayout>) {
    out.push(AtomLayout::Bytes {
        length: split.low_bytes,
    });
    out.push(AtomLayout::Bytes {
        length: split.high_bytes,
    });
}

fn push_descriptor_atoms(descriptor: &TypeDescriptor, out: &mut Vec<AtomLayout>) -> Option<()> {
    match descriptor {
        TypeDescriptor::Boolean | TypeDescriptor::Enum { .. } => {
            out.push(AtomLayout::Bytes { length: 1 });
        }
        TypeDescriptor::Field | TypeDescriptor::JubjubScalar => {
            out.push(AtomLayout::Field);
        }
        TypeDescriptor::Secp256k1Base
        | TypeDescriptor::Secp256k1Scalar
        | TypeDescriptor::Secp256r1Base
        | TypeDescriptor::Secp256r1Scalar
        | TypeDescriptor::Curve25519Base => {
            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
        }
        TypeDescriptor::Curve25519Scalar => {
            push_foreign_split(ForeignFieldSplit::SPLIT_204, out);
        }
        TypeDescriptor::JubjubPoint => {
            out.push(AtomLayout::Field);
            out.push(AtomLayout::Field);
        }
        TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
            // x (24 + 8), y (24 + 8), identity flag (Field)
            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
            out.push(AtomLayout::Field);
        }
        TypeDescriptor::Curve25519Point => {
            // Edwards (x, y), each a Curve25519Base (24 + 8) pair; no identity flag.
            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
            push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
        }
        TypeDescriptor::Uint {
            maxval,
            alignment_bytes,
        } => {
            let length = uint_byte_width(maxval, *alignment_bytes)?;
            out.push(AtomLayout::Bytes { length });
        }
        TypeDescriptor::Bytes { length } => {
            out.push(AtomLayout::Bytes { length: *length });
        }
        TypeDescriptor::Counter => {
            out.push(AtomLayout::Bytes { length: 8 });
        }
        TypeDescriptor::Opaque { ts_type } => {
            if ts_type == "JubjubPoint" {
                out.push(AtomLayout::Field);
                out.push(AtomLayout::Field);
            } else {
                out.push(AtomLayout::Compress);
            }
        }
        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
            push_descriptor_atoms(of, out)?;
        }
        TypeDescriptor::Contract { .. } => {
            out.push(AtomLayout::Bytes { length: 32 });
        }
        TypeDescriptor::Tuple { types } => {
            for ty in types {
                push_descriptor_atoms(ty, out)?;
            }
        }
        TypeDescriptor::Vector { length, elt_type } => {
            if *length == 0 {
                return Some(());
            }
            let mut elem_atoms = Vec::new();
            push_descriptor_atoms(elt_type, &mut elem_atoms)?;
            let count = usize::try_from(*length).ok()?;
            out.reserve(elem_atoms.len().checked_mul(count)?);
            for _ in 0..count {
                out.extend_from_slice(&elem_atoms);
            }
        }
        TypeDescriptor::Struct { elements, .. } => {
            for field in elements {
                push_descriptor_atoms(&field.field_type, out)?;
            }
        }
        TypeDescriptor::Map { .. }
        | TypeDescriptor::Set { .. }
        | TypeDescriptor::List { .. }
        | TypeDescriptor::MerkleTree { .. }
        | TypeDescriptor::HistoricMerkleTree { .. }
        | TypeDescriptor::Unknown => return None,
    }
    Some(())
}

/// Compute the FAB `Bytes` atom width for a `Uint { maxval, alignment_bytes }`.
///
/// If `alignment_bytes` is explicitly provided and non-zero, it is returned
/// directly. Otherwise follows the standard runtime convention:
/// `<= u8::MAX` → 1, `<= u16::MAX` → 2, `<= u32::MAX` → 4, `<= u64::MAX` → 8,
/// `<= u128::MAX` → 16, or minimal bytes for wider non-negative bounds.
/// Returns `None` for negative `maxval`.
#[must_use]
pub fn uint_byte_width(maxval: &IntLit, alignment_bytes: Option<u32>) -> Option<u32> {
    if maxval.0 < I256::ZERO {
        return None;
    }
    if let Some(explicit) = alignment_bytes
        && explicit > 0
    {
        return Some(explicit);
    }
    if let Some(max) = maxval.as_u128() {
        let width = if max <= u128::from(u8::MAX) {
            1
        } else if max <= u128::from(u16::MAX) {
            2
        } else if max <= u128::from(u32::MAX) {
            4
        } else if max <= u128::from(u64::MAX) {
            8
        } else {
            16
        };
        return Some(width);
    }
    // Non-negative value > u128::MAX: compute minimal byte width from bit length.
    let bits = 256u32.saturating_sub(maxval.0.leading_zeros());
    Some(bits.div_ceil(8).max(1))
}

/// Number of native field elements required to store `byte_len` raw bytes.
#[must_use]
pub const fn bytes_field_slots(byte_len: u32) -> usize {
    byte_len.div_ceil(FR_BYTES_STORED) as usize
}

/// Split a raw byte buffer into 32-byte little-endian field-element limbs
/// (each carrying up to [`FR_BYTES_STORED`] = 31 bytes) in the requested [`ChunkOrder`].
#[must_use]
pub fn bytes_to_field_chunks(bytes: &[u8], order: ChunkOrder) -> Vec<[u8; 32]> {
    let chunk_size = FR_BYTES_STORED as usize;
    let mut chunks: Vec<[u8; 32]> = bytes
        .chunks(chunk_size)
        .map(|slice| {
            let mut limb = [0u8; 32];
            limb[..slice.len()].copy_from_slice(slice);
            limb
        })
        .collect();
    if order == ChunkOrder::MsbFirst {
        chunks.reverse();
    }
    chunks
}

/// Reassemble `byte_len` raw bytes from 32-byte little-endian field-element limbs
/// ordered according to `order`.
///
/// Validates both chunk count and that unused upper bytes in every limb are zero.
#[must_use]
pub fn field_chunks_to_bytes(
    chunks: &[[u8; 32]],
    byte_len: u32,
    order: ChunkOrder,
) -> Option<Vec<u8>> {
    let expected = bytes_field_slots(byte_len);
    if chunks.len() != expected {
        return None;
    }
    let total = byte_len as usize;
    if total == 0 {
        return Some(Vec::new());
    }
    let chunk_size = FR_BYTES_STORED as usize;
    let mut out = vec![0u8; total];
    for lsb_idx in 0..expected {
        let src_idx = match order {
            ChunkOrder::LsbFirst => lsb_idx,
            ChunkOrder::MsbFirst => expected - 1 - lsb_idx,
        };
        let start = lsb_idx * chunk_size;
        let width = (total - start).min(chunk_size);
        let limb = &chunks[src_idx];
        if limb[width..].iter().any(|&b| b != 0) {
            return None;
        }
        out[start..start + width].copy_from_slice(&limb[..width]);
    }
    Some(out)
}

/// Reorder a slice of field-element chunks belonging to a single `Bytes<N>` atom
/// between [`ChunkOrder::MsbFirst`] and [`ChunkOrder::LsbFirst`].
#[must_use]
pub fn reorder_chunks<T: Clone>(chunks: &[T], from: ChunkOrder, to: ChunkOrder) -> Vec<T> {
    if from == to {
        chunks.to_vec()
    } else {
        chunks.iter().rev().cloned().collect()
    }
}

/// Prime modulus of a non-native [`FieldType`], or `None` for the native BLS12-381 `Field`.
#[must_use]
pub const fn foreign_field_modulus(field_type: FieldType) -> Option<U256> {
    match field_type {
        FieldType::Field => None,
        FieldType::JubjubScalar => Some(JUBJUB_SCALAR_MODULUS),
        FieldType::Secp256k1Base => Some(SECP256K1_BASE_MODULUS),
        FieldType::Secp256k1Scalar => Some(SECP256K1_SCALAR_MODULUS),
        FieldType::Secp256r1Base => Some(SECP256R1_BASE_MODULUS),
        FieldType::Secp256r1Scalar => Some(SECP256R1_SCALAR_MODULUS),
        FieldType::Curve25519Base => Some(CURVE25519_BASE_MODULUS),
        FieldType::Curve25519Scalar => Some(CURVE25519_SCALAR_MODULUS),
    }
}

/// Two-atom limb split for a foreign [`FieldType`], or `None` for single-atom
/// fields (`Field`, `JubjubScalar`).
#[must_use]
pub const fn foreign_field_split(field_type: FieldType) -> Option<ForeignFieldSplit> {
    match field_type {
        FieldType::Field | FieldType::JubjubScalar => None,
        FieldType::Curve25519Scalar => Some(ForeignFieldSplit::SPLIT_204),
        FieldType::Secp256k1Base
        | FieldType::Secp256k1Scalar
        | FieldType::Secp256r1Base
        | FieldType::Secp256r1Scalar
        | FieldType::Curve25519Base => Some(ForeignFieldSplit::SPLIT_192),
    }
}

/// Apply the ZKIR/FAB `-1 mod p` rotation to a two-atom foreign field element
/// (`0 -> p - 1`, `v -> v - 1`). Returns `None` if `field_type` is not a
/// two-atom foreign field or `value >= p`.
#[must_use]
pub fn rotate_foreign_to_wire(field_type: FieldType, value: U256) -> Option<U256> {
    foreign_field_split(field_type)?;
    let modulus = foreign_field_modulus(field_type)?;
    if value >= modulus {
        return None;
    }
    let max = modulus - U256::ONE;
    Some(if value == U256::ZERO {
        max
    } else {
        value - U256::ONE
    })
}

/// Undo the ZKIR/FAB `-1 mod p` rotation on a two-atom foreign field element
/// (`p - 1 -> 0`, `w -> w + 1`). Returns `None` if `field_type` is not a
/// two-atom foreign field or `wire >= p`.
#[must_use]
pub fn rotate_foreign_from_wire(field_type: FieldType, wire: U256) -> Option<U256> {
    foreign_field_split(field_type)?;
    let modulus = foreign_field_modulus(field_type)?;
    if wire >= modulus {
        return None;
    }
    let max = modulus - U256::ONE;
    Some(if wire == max {
        U256::ZERO
    } else {
        wire + U256::ONE
    })
}

/// Rotate a foreign field element by `-1 mod p` and split it into its fixed-width
/// little-endian `(low_bytes, high_bytes)` limbs (`[24, 8]` or `[26, 7]`).
#[must_use]
pub fn split_foreign_limbs(field_type: FieldType, value: U256) -> Option<(Vec<u8>, Vec<u8>)> {
    let split = foreign_field_split(field_type)?;
    let rotated = rotate_foreign_to_wire(field_type, value)?;
    let low_mask = (U256::ONE << split.low_bits) - U256::ONE;
    let low = rotated & low_mask;
    let high = rotated >> split.low_bits;
    let low_le = low.to_le_bytes()[..split.low_bytes as usize].to_vec();
    let high_le = high.to_le_bytes()[..split.high_bytes as usize].to_vec();
    Some((low_le, high_le))
}

/// Reassemble little-endian `(low_le, high_le)` foreign-field limb bytes and
/// undo the `-1 mod p` rotation.
#[must_use]
pub fn join_foreign_limbs(field_type: FieldType, low_le: &[u8], high_le: &[u8]) -> Option<U256> {
    let split = foreign_field_split(field_type)?;
    if low_le.len() > split.low_bytes as usize || high_le.len() > split.high_bytes as usize {
        return None;
    }
    let mut low_buf = [0u8; 32];
    low_buf[..low_le.len()].copy_from_slice(low_le);
    let low = U256::from_le_bytes(low_buf);
    if low >= (U256::ONE << split.low_bits) {
        return None;
    }
    let mut high_buf = [0u8; 32];
    high_buf[..high_le.len()].copy_from_slice(high_le);
    let high = U256::from_le_bytes(high_buf);
    // Reject values that would overflow 256 bits on shift.
    if high >= (U256::ONE << (256 - split.low_bits)) {
        return None;
    }
    let wire = (high << split.low_bits) | low;
    rotate_foreign_from_wire(field_type, wire)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::StructField;

    #[test]
    fn bytes_chunking_msb_vs_lsb_32_bytes() {
        let mut raw = [0u8; 32];
        for (i, b) in raw.iter_mut().enumerate() {
            #[allow(clippy::cast_possible_truncation)]
            {
                *b = (i as u8) + 1;
            }
        }

        let fab = bytes_to_field_chunks(&raw, ChunkOrder::MsbFirst);
        let zkir = bytes_to_field_chunks(&raw, ChunkOrder::LsbFirst);
        assert_eq!(fab.len(), 2);
        assert_eq!(zkir.len(), 2);

        // FAB MsbFirst: slot 0 has byte[31] (= 32), slot 1 has bytes[0..31] (= 1..=31).
        assert_eq!(fab[0][0], 32);
        assert!(fab[0][1..].iter().all(|&b| b == 0));
        assert_eq!(&fab[1][..31], &raw[..31]);
        assert_eq!(fab[1][31], 0);

        // ZKIR v3 LsbFirst: exact reverse.
        assert_eq!(zkir[0], fab[1]);
        assert_eq!(zkir[1], fab[0]);
        assert_eq!(
            reorder_chunks(&fab, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst),
            zkir
        );

        // Round-trip reassembly in both orders.
        assert_eq!(
            field_chunks_to_bytes(&fab, 32, ChunkOrder::MsbFirst).as_deref(),
            Some(&raw[..])
        );
        assert_eq!(
            field_chunks_to_bytes(&zkir, 32, ChunkOrder::LsbFirst).as_deref(),
            Some(&raw[..])
        );
    }

    #[test]
    fn bytes_chunking_edge_lengths() {
        // Bytes<0> → 0 field slots.
        assert_eq!(bytes_field_slots(0), 0);
        assert_eq!(
            bytes_to_field_chunks(&[], ChunkOrder::MsbFirst),
            Vec::<[u8; 32]>::new()
        );
        assert_eq!(
            field_chunks_to_bytes(&[], 0, ChunkOrder::LsbFirst),
            Some(Vec::new())
        );

        // Bytes<31> → 1 field slot (identical in MSB and LSB).
        let b31 = [0x5au8; 31];
        let msb31 = bytes_to_field_chunks(&b31, ChunkOrder::MsbFirst);
        let lsb31 = bytes_to_field_chunks(&b31, ChunkOrder::LsbFirst);
        assert_eq!(msb31.len(), 1);
        assert_eq!(msb31, lsb31);
        assert_eq!(
            field_chunks_to_bytes(&msb31, 31, ChunkOrder::MsbFirst).as_deref(),
            Some(&b31[..])
        );

        // Bytes<64> → 3 field slots: [62..64], [31..62], [0..31] in FAB.
        let b64: Vec<u8> = (0u8..64).collect();
        let msb64 = bytes_to_field_chunks(&b64, ChunkOrder::MsbFirst);
        let lsb64 = bytes_to_field_chunks(&b64, ChunkOrder::LsbFirst);
        assert_eq!(msb64.len(), 3);
        assert_eq!(&msb64[0][..2], &[62, 63]);
        assert!(msb64[0][2..].iter().all(|&b| b == 0));
        assert_eq!(&msb64[1][..31], &b64[31..62]);
        assert_eq!(&msb64[2][..31], &b64[0..31]);
        assert_eq!(
            field_chunks_to_bytes(&msb64, 64, ChunkOrder::MsbFirst),
            Some(b64.clone())
        );
        assert_eq!(
            field_chunks_to_bytes(&lsb64, 64, ChunkOrder::LsbFirst),
            Some(b64)
        );

        // Reject dirty padding bytes in MSB chunk.
        let mut bad = msb64;
        bad[0][2] = 1;
        assert_eq!(field_chunks_to_bytes(&bad, 64, ChunkOrder::MsbFirst), None);
    }

    #[test]
    fn uint_byte_widths_match_runtime_convention() {
        assert_eq!(uint_byte_width(&IntLit::from_u128(0), None), Some(1));
        assert_eq!(uint_byte_width(&IntLit::from_u128(255), None), Some(1));
        assert_eq!(uint_byte_width(&IntLit::from_u128(256), None), Some(2));
        assert_eq!(
            uint_byte_width(&IntLit::from_u128(u128::from(u16::MAX)), None),
            Some(2)
        );
        assert_eq!(
            uint_byte_width(&IntLit::from_u128(u128::from(u32::MAX)), None),
            Some(4)
        );
        assert_eq!(
            uint_byte_width(&IntLit::from_u128(u128::from(u64::MAX)), None),
            Some(8)
        );
        assert_eq!(
            uint_byte_width(&IntLit::from_u128(u128::MAX), None),
            Some(16)
        );
        // Explicit alignment-bytes overrides power-of-2 bucket.
        assert_eq!(
            uint_byte_width(&IntLit::from_u128(16_777_215), Some(3)),
            Some(3)
        );
        // Negative maxval is rejected.
        assert_eq!(uint_byte_width(&IntLit::from_i128(-1), None), None);
    }

    #[test]
    fn foreign_field_rotation_and_limb_splits() {
        for ft in [
            FieldType::Secp256k1Base,
            FieldType::Secp256k1Scalar,
            FieldType::Secp256r1Base,
            FieldType::Secp256r1Scalar,
            FieldType::Curve25519Base,
            FieldType::Curve25519Scalar,
        ] {
            let modulus = foreign_field_modulus(ft).unwrap();
            let split = foreign_field_split(ft).unwrap();
            if ft == FieldType::Curve25519Scalar {
                assert_eq!((split.low_bytes, split.high_bytes), (26, 7));
            } else {
                assert_eq!((split.low_bytes, split.high_bytes), (24, 8));
            }

            // 0 rotates to modulus - 1, and back to 0.
            assert_eq!(rotate_foreign_to_wire(ft, U256::ZERO), Some(modulus - 1));
            assert_eq!(rotate_foreign_from_wire(ft, modulus - 1), Some(U256::ZERO));

            // Test 0, 1, 42, modulus - 1 through full limb split + join.
            for val in [U256::ZERO, U256::ONE, U256::from(42u64), modulus - 1] {
                let (lo, hi) = split_foreign_limbs(ft, val).unwrap();
                assert_eq!(lo.len(), split.low_bytes as usize);
                assert_eq!(hi.len(), split.high_bytes as usize);
                assert_eq!(join_foreign_limbs(ft, &lo, &hi), Some(val));
            }

            // Out-of-range value (>= modulus) is rejected.
            assert_eq!(rotate_foreign_to_wire(ft, modulus), None);
        }

        // Native Field and JubjubScalar are single-atom (no split).
        assert_eq!(foreign_field_split(FieldType::Field), None);
        assert_eq!(foreign_field_split(FieldType::JubjubScalar), None);
    }

    #[test]
    fn curve_point_and_compound_field_layouts() {
        let jj = FieldLayout::from_descriptor(&TypeDescriptor::JubjubPoint).unwrap();
        assert_eq!(jj.atom_count(), 2);
        assert_eq!(jj.field_slots(), 2);
        assert!(!jj.needs_chunk_reordering());

        let secp = FieldLayout::from_descriptor(&TypeDescriptor::Secp256k1Point).unwrap();
        assert_eq!(secp.atom_count(), 5);
        assert_eq!(secp.field_slots(), 5);
        assert_eq!(
            secp.atoms,
            vec![
                AtomLayout::Bytes { length: 24 },
                AtomLayout::Bytes { length: 8 },
                AtomLayout::Bytes { length: 24 },
                AtomLayout::Bytes { length: 8 },
                AtomLayout::Field,
            ]
        );
        assert!(!secp.needs_chunk_reordering());

        let p256 = FieldLayout::from_descriptor(&TypeDescriptor::Secp256r1Point).unwrap();
        assert_eq!(p256, secp);

        let c25519 = FieldLayout::from_descriptor(&TypeDescriptor::Curve25519Point).unwrap();
        assert_eq!(c25519.atom_count(), 4);
        assert_eq!(c25519.field_slots(), 4);

        // Compound struct mixing single-slot and multi-chunk Bytes<32> atoms.
        let note = TypeDescriptor::Struct {
            name: "Note".to_owned(),
            elements: vec![
                StructField {
                    name: "owner".to_owned(),
                    field_type: TypeDescriptor::Bytes { length: 32 },
                },
                StructField {
                    name: "amount".to_owned(),
                    field_type: TypeDescriptor::Uint {
                        maxval: IntLit::from_u128(u128::from(u64::MAX)),
                        alignment_bytes: None,
                    },
                },
                StructField {
                    name: "pk".to_owned(),
                    field_type: TypeDescriptor::Secp256k1Base,
                },
            ],
        };
        let layout = FieldLayout::from_descriptor(&note).unwrap();
        assert_eq!(layout.atom_count(), 4);
        assert_eq!(layout.field_slots(), 5);
        assert!(layout.needs_chunk_reordering());

        // Slot order in FAB: [owner_msb, owner_lsb, amount, pk_lo, pk_hi]
        let fab_slots = [10u32, 20, 30, 40, 50];
        let zkir_slots = layout
            .reorder_field_slots(&fab_slots, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst)
            .unwrap();
        // Only owner's 2 chunks swap; amount and pk limbs stay in order.
        assert_eq!(zkir_slots, vec![20, 10, 30, 40, 50]);
        assert_eq!(
            layout
                .reorder_field_slots(&zkir_slots, ChunkOrder::LsbFirst, ChunkOrder::MsbFirst)
                .unwrap(),
            fab_slots
        );

        // Non-flat container returns None.
        assert_eq!(
            FieldLayout::from_descriptor(&TypeDescriptor::Map {
                key: Box::new(TypeDescriptor::Field),
                value: Box::new(TypeDescriptor::Counter),
            }),
            None
        );
    }
}