Skip to main content

moonproof_runtime/ir/
descriptor.rs

1//! Descriptor → `AlignedValue` helpers.
2//!
3//! The IR's `descriptors` table assigns numeric IDs to every type that
4//! appears at a runtime boundary. Encoding a JSON literal into an
5//! `AlignedValue` (Compact's wire-format atom) requires knowing the
6//! target descriptor: a `Uint<16>` literal of `5` is one byte sequence;
7//! a `Uint<64>` literal of `5` is a different one. This module is the
8//! mapping from descriptor + JSON value to `AlignedValue`.
9
10use std::sync::Arc;
11
12use moonproof_ledger::base_crypto::fab::AlignedValue;
13use moonproof_runtime_ir::ir::{FieldType, TypeDescriptor};
14use moonproof_runtime_ir::RuntimeValue as Value;
15
16use super::error::{IrDriverError, Result};
17use super::vm_val::VmVal;
18
19/// Convert a JSON literal to an `AlignedValue` typed by `descriptor`.
20///
21/// Compound shapes (`Struct`, `Tuple`, `Vector`, `Cell`) recursively
22/// concat their elements' `AlignedValues`. `Enum` looks up the variant
23/// name in the descriptor's element list and encodes the index as a
24/// 1-byte aligned value (Compact's enums fit in a u8). `Counter` is
25/// a u64 cell. Container types (Map, Set, List, `MerkleTree`,
26/// `HistoricMerkleTree`) have no flat `AlignedValue` encoding — they
27/// live as `StateValue::{Map,BoundedMerkleTree}` slots, not as
28/// circuit-arg-shaped values.
29pub fn encode_literal(descriptor: &TypeDescriptor, value: &Value) -> Result<AlignedValue> {
30    match descriptor {
31        TypeDescriptor::Uint { maxval, .. } => encode_uint(maxval, value),
32        TypeDescriptor::Bytes { length } => encode_bytes(*length, value),
33        TypeDescriptor::Boolean => encode_bool(value),
34        TypeDescriptor::Field => encode_field(value),
35        TypeDescriptor::JubjubScalar => {
36            super::curve::encode_field_type(FieldType::JubjubScalar, value)
37        }
38        TypeDescriptor::Secp256k1Base => {
39            super::curve::encode_field_type(FieldType::Secp256k1Base, value)
40        }
41        TypeDescriptor::Secp256k1Scalar => {
42            super::curve::encode_field_type(FieldType::Secp256k1Scalar, value)
43        }
44        TypeDescriptor::Secp256r1Base => {
45            super::curve::encode_field_type(FieldType::Secp256r1Base, value)
46        }
47        TypeDescriptor::Secp256r1Scalar => {
48            super::curve::encode_field_type(FieldType::Secp256r1Scalar, value)
49        }
50        TypeDescriptor::Curve25519Base => {
51            super::curve::encode_field_type(FieldType::Curve25519Base, value)
52        }
53        TypeDescriptor::Curve25519Scalar => {
54            super::curve::encode_field_type(FieldType::Curve25519Scalar, value)
55        }
56        TypeDescriptor::JubjubPoint => super::curve::encode_jubjub_point(value),
57        TypeDescriptor::Secp256k1Point => super::curve::encode_weierstrass_point(
58            FieldType::Secp256k1Base,
59            value,
60            "Secp256k1Point",
61        ),
62        TypeDescriptor::Secp256r1Point => super::curve::encode_weierstrass_point(
63            FieldType::Secp256r1Base,
64            value,
65            "Secp256r1Point",
66        ),
67        TypeDescriptor::Curve25519Point => super::curve::encode_curve25519_point(value),
68        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => encode_literal(of, value),
69        TypeDescriptor::Counter => encode_uint(
70            &moonproof_runtime_ir::ir::IntLit::from_u128(u128::from(u64::MAX)),
71            value,
72        ),
73        TypeDescriptor::Struct { elements, name } => encode_struct(name, elements, value),
74        TypeDescriptor::Tuple { types } => encode_tuple(types, value),
75        TypeDescriptor::Vector { elt_type, length } => encode_vector(elt_type, *length, value),
76        TypeDescriptor::Enum { elements, name } => encode_enum(name, elements, value),
77        TypeDescriptor::Opaque { ts_type } => encode_opaque(ts_type, value),
78        TypeDescriptor::Contract { .. } => {
79            encode_literal(&TypeDescriptor::contract_address(), value)
80        }
81        TypeDescriptor::Map { .. }
82        | TypeDescriptor::Set { .. }
83        | TypeDescriptor::List { .. }
84        | TypeDescriptor::MerkleTree { .. }
85        | TypeDescriptor::HistoricMerkleTree { .. }
86        | TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
87            "encode_literal not implemented for descriptor {descriptor:?}"
88        ))),
89    }
90}
91
92/// Encode an `Opaque<tsType>` literal. Two shapes are supported:
93///
94/// - `tsType="string"` — JSON is a UTF-8 string; encoded bytes are
95///   `string.as_bytes()`. Matches `CompactTypeOpaqueString.toValue`
96///   in `@midnight-ntwrk/compact-runtime`.
97/// - `tsType="Uint8Array"` — JSON is a hex string (matching the
98///   `Bytes<N>` convention); encoded bytes are `hex::decode(s)`.
99///   Matches the standard library's `Opaque<"Uint8Array">` usage
100///   (e.g. `zerocash.compact`'s `ciphertexts` ledger field, or any
101///   contract storing raw byte buffers).
102///
103/// Both produce a single `ValueAtom` — alignment `Compress` — so the
104/// on-chain VM treats them identically once encoded; the difference
105/// is only in the JSON representation at the call boundary.
106fn encode_opaque(ts_type: &str, value: &Value) -> Result<AlignedValue> {
107    match ts_type {
108        "string" => {
109            let s = value.as_str().ok_or_else(|| {
110                IrDriverError::TypeMismatch(format!(
111                    "expected string for Opaque<string>, got {value}"
112                ))
113            })?;
114            // `Vec<u8>` is the right input — `&[u8]: Clone` doesn't
115            // hold so the standard `From<&T>` chain doesn't apply.
116            Ok(AlignedValue::from(s.as_bytes().to_vec()))
117        }
118        "Uint8Array" => {
119            let bytes = value.as_bytes().ok_or_else(|| {
120                IrDriverError::TypeMismatch(format!(
121                    "expected Bytes for Opaque<Uint8Array>, got {value}"
122                ))
123            })?;
124            Ok(AlignedValue::from(bytes.to_vec()))
125        }
126        // `Opaque<'JubjubPoint'>` is laid out as two Field atoms — see
127        // upstream `compact/runtime/src/compact-types.ts::CompactTypeJubjubPoint.alignment`.
128        // RuntimeValue shape mirrors the TS struct: `Object { x: Bytes, y: Bytes }`.
129        "JubjubPoint" => {
130            let obj = value.as_object().ok_or_else(|| {
131                IrDriverError::TypeMismatch(format!(
132                    "expected object for Opaque<JubjubPoint>, got {value}"
133                ))
134            })?;
135            let x = obj.get("x").ok_or_else(|| {
136                IrDriverError::TypeMismatch("Opaque<JubjubPoint> missing field 'x'".into())
137            })?;
138            let y = obj.get("y").ok_or_else(|| {
139                IrDriverError::TypeMismatch("Opaque<JubjubPoint> missing field 'y'".into())
140            })?;
141            let x_av = encode_field(x)?;
142            let y_av = encode_field(y)?;
143            Ok(AlignedValue::concat([&x_av, &y_av]))
144        }
145        other => Err(IrDriverError::unimplemented(format!(
146            "encode_literal Opaque<{other}>"
147        ))),
148    }
149}
150
151/// Encode each struct field in declaration order and concatenate.
152fn encode_struct(
153    name: &str,
154    elements: &[moonproof_runtime_ir::ir::StructField],
155    value: &Value,
156) -> Result<AlignedValue> {
157    let obj = value.as_object().ok_or_else(|| {
158        IrDriverError::TypeMismatch(format!("expected object for struct {name}, got {value}"))
159    })?;
160    let mut atoms: Vec<AlignedValue> = Vec::with_capacity(elements.len());
161    for field in elements {
162        let field_v = obj.get(&field.name).ok_or_else(|| {
163            IrDriverError::TypeMismatch(format!(
164                "struct {name} missing field '{}'; got keys {:?}",
165                field.name,
166                obj.keys().collect::<Vec<_>>()
167            ))
168        })?;
169        atoms.push(encode_literal(&field.field_type, field_v)?);
170    }
171    Ok(AlignedValue::concat(atoms.iter()))
172}
173
174/// Encode tuple elements positionally and concatenate.
175fn encode_tuple(types: &[TypeDescriptor], value: &Value) -> Result<AlignedValue> {
176    let arr = value.as_array().ok_or_else(|| {
177        IrDriverError::TypeMismatch(format!("expected array for tuple, got {value}"))
178    })?;
179    if arr.len() != types.len() {
180        return Err(IrDriverError::TypeMismatch(format!(
181            "tuple arity mismatch: expected {}, got {}",
182            types.len(),
183            arr.len()
184        )));
185    }
186    let mut atoms: Vec<AlignedValue> = Vec::with_capacity(types.len());
187    for (t, v) in types.iter().zip(arr.iter()) {
188        atoms.push(encode_literal(t, v)?);
189    }
190    Ok(AlignedValue::concat(atoms.iter()))
191}
192
193/// Encode a fixed-length vector. Element count must match `length`.
194fn encode_vector(elt_type: &TypeDescriptor, length: u32, value: &Value) -> Result<AlignedValue> {
195    let arr = value.as_array().ok_or_else(|| {
196        IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
197    })?;
198    if u32::try_from(arr.len()) != Ok(length) {
199        return Err(IrDriverError::TypeMismatch(format!(
200            "vector length mismatch: expected {length}, got {}",
201            arr.len()
202        )));
203    }
204    let mut atoms: Vec<AlignedValue> = Vec::with_capacity(length as usize);
205    for v in arr {
206        atoms.push(encode_literal(elt_type, v)?);
207    }
208    Ok(AlignedValue::concat(atoms.iter()))
209}
210
211/// Encode an enum by looking up the variant name in the descriptor's
212/// element list. Compact enums fit in a single byte (256 variants
213/// max) — encode as `u8`. Variant must match by string name.
214fn encode_enum(name: &str, elements: &[String], value: &Value) -> Result<AlignedValue> {
215    let variant = value.as_str().ok_or_else(|| {
216        IrDriverError::TypeMismatch(format!(
217            "expected enum-variant string for {name}, got {value}"
218        ))
219    })?;
220    let index = elements.iter().position(|v| v == variant).ok_or_else(|| {
221        IrDriverError::TypeMismatch(format!(
222            "enum {name}: variant '{variant}' not in {elements:?}"
223        ))
224    })?;
225    let index_u8 = u8::try_from(index).map_err(|_| {
226        IrDriverError::TypeMismatch(format!(
227            "enum {name} variant index {index} exceeds u8 — wire encoding assumes ≤256 variants"
228        ))
229    })?;
230    Ok(AlignedValue::from(index_u8))
231}
232
233/// Produce the wire-format zero `AlignedValue` for any descriptor —
234/// the value `{vm: null, type: ...}` carries in IR pushdowns. Recurses
235/// through compound types so a default `Either` is `(false, default
236/// ZswapCoinPublicKey, default ContractAddress)`, etc.
237pub fn encode_default(descriptor: &TypeDescriptor) -> Result<AlignedValue> {
238    match descriptor {
239        TypeDescriptor::Boolean => Ok(AlignedValue::from(false)),
240        TypeDescriptor::Uint { maxval, .. } => encode_uint(maxval, &Value::Int(0)),
241        TypeDescriptor::Counter => Ok(AlignedValue::from(0u64)),
242        TypeDescriptor::Bytes { length } => {
243            encode_bytes(*length, &Value::Bytes(vec![0u8; *length as usize]))
244        }
245        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => encode_default(of),
246        TypeDescriptor::Struct { elements, .. } => {
247            let mut atoms: Vec<AlignedValue> = Vec::with_capacity(elements.len());
248            for field in elements {
249                atoms.push(encode_default(&field.field_type)?);
250            }
251            Ok(AlignedValue::concat(atoms.iter()))
252        }
253        TypeDescriptor::Tuple { types } => {
254            let mut atoms: Vec<AlignedValue> = Vec::with_capacity(types.len());
255            for t in types {
256                atoms.push(encode_default(t)?);
257            }
258            Ok(AlignedValue::concat(atoms.iter()))
259        }
260        TypeDescriptor::Vector { elt_type, length } => {
261            let mut atoms: Vec<AlignedValue> = Vec::with_capacity(*length as usize);
262            for _ in 0..*length {
263                atoms.push(encode_default(elt_type)?);
264            }
265            Ok(AlignedValue::concat(atoms.iter()))
266        }
267        TypeDescriptor::Enum { .. } => Ok(AlignedValue::from(0u8)),
268        TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
269            "string" | "Uint8Array" => Ok(AlignedValue::from(Vec::<u8>::new())),
270            "JubjubPoint" => encode_default(&TypeDescriptor::JubjubPoint),
271            other => Err(IrDriverError::unimplemented(format!(
272                "encode_default for Opaque<{other}>"
273            ))),
274        },
275        TypeDescriptor::Field => encode_field(&Value::Int(0)),
276        // Zero in each foreign field. The secp encoders rotate that to
277        // `modulus - 1` on the wire, which is what upstream writes.
278        TypeDescriptor::JubjubScalar
279        | TypeDescriptor::Secp256k1Base
280        | TypeDescriptor::Secp256k1Scalar
281        | TypeDescriptor::Secp256r1Base
282        | TypeDescriptor::Secp256r1Scalar
283        | TypeDescriptor::Curve25519Base
284        | TypeDescriptor::Curve25519Scalar => encode_literal(descriptor, &Value::Int(0)),
285        // The Edwards identity is (0, 1), per `EmbeddedGroupAffine::identity`
286        // in transient-crypto and `print-typescript.ss`'s default. (0, 0) is
287        // not a curve point at all.
288        TypeDescriptor::JubjubPoint => {
289            let x = encode_field(&Value::Int(0))?;
290            let y = encode_field(&Value::Int(1))?;
291            Ok(AlignedValue::concat([&x, &y]))
292        }
293        // A Weierstrass identity is the point at infinity, flagged rather
294        // than coordinate-encoded.
295        TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
296            let mut obj = std::collections::BTreeMap::new();
297            obj.insert("x".to_owned(), Value::Int(0));
298            obj.insert("y".to_owned(), Value::Int(0));
299            obj.insert("identity".to_owned(), Value::Bool(true));
300            encode_literal(descriptor, &Value::Object(obj))
301        }
302        // Curve25519 is an Edwards curve: the identity is (0, 1).
303        TypeDescriptor::Curve25519Point => {
304            let mut obj = std::collections::BTreeMap::new();
305            obj.insert("x".to_owned(), Value::Int(0));
306            obj.insert("y".to_owned(), Value::Int(1));
307            super::curve::encode_curve25519_point(&Value::Object(obj))
308        }
309        TypeDescriptor::Contract { .. } => encode_default(&TypeDescriptor::contract_address()),
310        TypeDescriptor::Map { .. }
311        | TypeDescriptor::Set { .. }
312        | TypeDescriptor::List { .. }
313        | TypeDescriptor::MerkleTree { .. }
314        | TypeDescriptor::HistoricMerkleTree { .. }
315        | TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
316            "encode_default for descriptor {descriptor:?} (container types have no flat default)"
317        ))),
318    }
319}
320
321/// Encode a Uint literal sized by its `maxval`. Picks the alignment
322/// width matching the JS backend's `_descriptor_N`-emit convention:
323/// `≤ u8::MAX` → 1 byte, `≤ u16::MAX` → 2 bytes, `≤ u32::MAX` → 4
324/// bytes, `≤ u64::MAX` → 8 bytes, otherwise 16 bytes.
325pub fn encode_uint(
326    maxval: &moonproof_runtime_ir::ir::IntLit,
327    value: &Value,
328) -> Result<AlignedValue> {
329    let max = maxval
330        .as_u128()
331        .ok_or_else(|| IrDriverError::TypeMismatch(format!("Uint maxval {maxval} out of u128")))?;
332    let v = json_as_u128(value)?;
333    let exceeds = || IrDriverError::TypeMismatch(format!("value {v} exceeds Uint maxval {max}"));
334    if v > max {
335        return Err(exceeds());
336    }
337    if max <= u128::from(u8::MAX) {
338        Ok(AlignedValue::from(u8::try_from(v).map_err(|_| exceeds())?))
339    } else if max <= u128::from(u16::MAX) {
340        Ok(AlignedValue::from(u16::try_from(v).map_err(|_| exceeds())?))
341    } else if max <= u128::from(u32::MAX) {
342        Ok(AlignedValue::from(u32::try_from(v).map_err(|_| exceeds())?))
343    } else if max <= u128::from(u64::MAX) {
344        Ok(AlignedValue::from(u64::try_from(v).map_err(|_| exceeds())?))
345    } else {
346        // Use the native 128-bit encoding via the From impl, which
347        // produces a 16-byte alignment.
348        Ok(AlignedValue::from(v))
349    }
350}
351
352/// Encode a `Field` literal as an `AlignedValue` with
353/// `AlignmentAtom::Field` (matches the upstream `Aligned for Fr` impl
354/// in `transient-crypto/src/curve.rs:291`).
355///
356/// JSON representation for Field is a hex-encoded little-endian byte
357/// string of the underlying `Fr` (32 bytes for BLS12-381's scalar
358/// field). This matches what `Expression::CastFromBytes` produces:
359/// the input bytes are read little-endian (per
360/// `compact-runtime/dist/casts.js::convertBytesToField`), zero-padded
361/// to 32 bytes, and the result is the same hex string.
362pub fn encode_field(value: &Value) -> Result<AlignedValue> {
363    // Canonical: `RuntimeValue::Bytes` (32-byte LE BLS scalar repr).
364    // `Int` / decimal `String` accepted for arithmetic results
365    // (`Expression::Binop` on Field operands; the >u64::MAX path
366    // promotes to decimal-string).
367    let fr = if let Some(b) = value.as_bytes() {
368        moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(b).ok_or_else(|| {
369            IrDriverError::TypeMismatch(format!(
370                "Field value out of range: {} bytes does not fit in Fr",
371                b.len()
372            ))
373        })?
374    } else if let Some(n) = value.as_u128() {
375        moonproof_ledger::transient_crypto::curve::Fr::from(n)
376    } else if let Some(s) = value.as_str() {
377        let n: u128 = s.parse().map_err(|e| {
378            IrDriverError::TypeMismatch(format!("Field decimal-string parse failed: '{s}' ({e})"))
379        })?;
380        moonproof_ledger::transient_crypto::curve::Fr::from(n)
381    } else {
382        return Err(IrDriverError::TypeMismatch(format!(
383            "Field expects bytes or numeric, got {value}"
384        )));
385    };
386    Ok(AlignedValue::from(fr))
387}
388
389/// Encode a fixed-length Bytes literal. Accepts hex-encoded strings.
390///
391/// The encoded `AlignedValue` is built directly from `Value` +
392/// `Alignment::singleton(AlignmentAtom::Bytes { length: N })` so any
393/// declared length is supported (the JS path's
394/// `_descriptor_N.toValue(...)` produces the same shape for arbitrary
395/// `N`). The `ValueAtom::from([u8; N])` impl strips trailing zeros, so
396/// we produce the same wire bytes by mirroring that strip rule on the
397/// raw vec.
398pub fn encode_bytes(length: u32, value: &Value) -> Result<AlignedValue> {
399    let owned: Vec<u8>;
400    let bytes: &[u8] = if let Some(b) = value.as_bytes() {
401        b
402    } else if let Some(s) = value.as_str() {
403        let trimmed = s
404            .strip_prefix("0x")
405            .or_else(|| s.strip_prefix("0X"))
406            .unwrap_or(s);
407        owned = hex::decode(trimmed).map_err(|e| {
408            IrDriverError::TypeMismatch(format!(
409                "Bytes<{length}> string is not valid hex: {s:?} ({e})"
410            ))
411        })?;
412        owned.as_slice()
413    } else {
414        return Err(IrDriverError::TypeMismatch(format!(
415            "expected Bytes for Bytes<{length}>, got {value}"
416        )));
417    };
418    if bytes.len() != length as usize {
419        return Err(IrDriverError::TypeMismatch(format!(
420            "Bytes<{length}> received {} bytes",
421            bytes.len()
422        )));
423    }
424    bytes_aligned_value(length, bytes)
425}
426
427/// Build a `Bytes<length>`-shaped `AlignedValue` from a length-N byte
428/// slice. Mirrors `ValueAtom::from([u8; N])`'s trailing-zero strip
429/// (`base-crypto/src/fab/conversions.rs:272-279`).
430fn bytes_aligned_value(length: u32, bytes: &[u8]) -> Result<AlignedValue> {
431    use moonproof_ledger::base_crypto::fab::{
432        Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
433    };
434    let mut atom_bytes = bytes.to_vec();
435    while atom_bytes.last() == Some(&0) {
436        atom_bytes.pop();
437    }
438    let value = FabValue(vec![ValueAtom(atom_bytes)]);
439    let alignment = Alignment::singleton(AlignmentAtom::Bytes { length });
440    AlignedValue::new(value, alignment).ok_or_else(|| {
441        IrDriverError::TypeMismatch(format!(
442            "Bytes<{length}> AlignedValue construction failed (alignment/value mismatch)"
443        ))
444    })
445}
446
447/// Encode a boolean literal.
448pub fn encode_bool(value: &Value) -> Result<AlignedValue> {
449    let b = value
450        .as_bool()
451        .ok_or_else(|| IrDriverError::TypeMismatch(format!("expected bool, got {value}")))?;
452    Ok(AlignedValue::from(b))
453}
454
455/// Decode an `AlignedValue` to a JSON value typed by `descriptor` —
456/// the inverse of [`encode_literal`]. Used both to decode circuit
457/// arguments back into JSON-shaped local bindings and to surface
458/// popeq read results (Cell.read, Map.lookup, etc.) inside the
459/// interpreter.
460///
461/// The `atoms` cursor advances by however many `ValueAtom`s the
462/// descriptor consumes — primitives consume 1, structs consume the
463/// sum of their field consumption.
464pub fn decode_aligned_value(
465    descriptor: &TypeDescriptor,
466    atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
467    cursor: &mut usize,
468) -> Result<Value> {
469    match descriptor {
470        TypeDescriptor::Boolean => {
471            let atom = consume(atoms, cursor, descriptor)?;
472            let n = u8::try_from(atom)
473                .map_err(|e| IrDriverError::TypeMismatch(format!("bool atom decode: {e:?}")))?;
474            Ok(Value::Bool(n != 0))
475        }
476        TypeDescriptor::Uint { maxval, .. } => {
477            let atom = consume(atoms, cursor, descriptor)?;
478            decode_uint(maxval, atom)
479        }
480        TypeDescriptor::Counter => {
481            let atom = consume(atoms, cursor, descriptor)?;
482            let n = u64::try_from(atom)
483                .map_err(|e| IrDriverError::TypeMismatch(format!("counter→u64 decode: {e:?}")))?;
484            Ok(Value::Int(i128::from(n)))
485        }
486        TypeDescriptor::Bytes { length } => {
487            let atom = consume(atoms, cursor, descriptor)?;
488            // ValueAtom strips trailing zeros — re-pad to declared N
489            // before returning the byte-honest `Bytes` variant.
490            let mut buf = atom.0.clone();
491            buf.resize(*length as usize, 0);
492            Ok(Value::Bytes(buf))
493        }
494        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
495            decode_aligned_value(of, atoms, cursor)
496        }
497        TypeDescriptor::Struct { elements, .. } => {
498            let mut obj = std::collections::BTreeMap::<String, Value>::new();
499            for field in elements {
500                let v = decode_aligned_value(&field.field_type, atoms, cursor)?;
501                obj.insert(field.name.clone(), v);
502            }
503            Ok(Value::Object(obj))
504        }
505        TypeDescriptor::Tuple { types } => {
506            if types.is_empty() {
507                return Ok(Value::Array(Vec::new()));
508            }
509            let mut arr = Vec::with_capacity(types.len());
510            for t in types {
511                arr.push(decode_aligned_value(t, atoms, cursor)?);
512            }
513            Ok(Value::Array(arr))
514        }
515        TypeDescriptor::Vector { elt_type, length } => {
516            let mut arr = Vec::with_capacity(*length as usize);
517            for _ in 0..*length {
518                arr.push(decode_aligned_value(elt_type, atoms, cursor)?);
519            }
520            Ok(Value::Array(arr))
521        }
522        TypeDescriptor::Enum { elements, name } => {
523            let atom = consume(atoms, cursor, descriptor)?;
524            decode_enum(name, elements, atom)
525        }
526        TypeDescriptor::Opaque { ts_type } => decode_opaque(ts_type, descriptor, atoms, cursor),
527        TypeDescriptor::Field | TypeDescriptor::JubjubScalar => {
528            let atom = consume(atoms, cursor, descriptor)?;
529            // 32-byte LE repr (BLS scalar Fr). ValueAtom strips
530            // trailing zeros — re-pad to 32 before emitting.
531            let mut buf = atom.0.clone();
532            buf.resize(32, 0);
533            Ok(Value::Bytes(buf))
534        }
535        // A foreign field element spans two atoms and is stored rotated;
536        // `decode_foreign_field` undoes both.
537        TypeDescriptor::Secp256k1Base
538        | TypeDescriptor::Secp256k1Scalar
539        | TypeDescriptor::Secp256r1Base
540        | TypeDescriptor::Secp256r1Scalar
541        | TypeDescriptor::Curve25519Base
542        | TypeDescriptor::Curve25519Scalar => decode_foreign_field(descriptor, atoms, cursor),
543        TypeDescriptor::JubjubPoint
544        | TypeDescriptor::Curve25519Point
545        | TypeDescriptor::Secp256k1Point
546        | TypeDescriptor::Secp256r1Point => decode_point(descriptor, atoms, cursor),
547        TypeDescriptor::Contract { .. } => {
548            decode_aligned_value(&TypeDescriptor::contract_address(), atoms, cursor)
549        }
550        TypeDescriptor::Map { .. }
551        | TypeDescriptor::Set { .. }
552        | TypeDescriptor::List { .. }
553        | TypeDescriptor::MerkleTree { .. }
554        | TypeDescriptor::HistoricMerkleTree { .. }
555        | TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
556            "decode_aligned_value for descriptor {descriptor:?}"
557        ))),
558    }
559}
560
561fn decode_uint(
562    maxval: &moonproof_runtime_ir::ir::IntLit,
563    atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
564) -> Result<Value> {
565    let max = maxval
566        .as_u128()
567        .ok_or_else(|| IrDriverError::TypeMismatch(format!("Uint maxval out of u128: {maxval}")))?;
568    let n: u128 = if max <= u128::from(u8::MAX) {
569        u128::from(
570            u8::try_from(atom)
571                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u8 decode: {e:?}")))?,
572        )
573    } else if max <= u128::from(u16::MAX) {
574        u128::from(
575            u16::try_from(atom)
576                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u16 decode: {e:?}")))?,
577        )
578    } else if max <= u128::from(u32::MAX) {
579        u128::from(
580            u32::try_from(atom)
581                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u32 decode: {e:?}")))?,
582        )
583    } else if max <= u128::from(u64::MAX) {
584        u128::from(
585            u64::try_from(atom)
586                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u64 decode: {e:?}")))?,
587        )
588    } else {
589        u128::try_from(atom)
590            .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u128 decode: {e:?}")))?
591    };
592    match u64::try_from(n) {
593        Ok(n) => Ok(Value::Int(i128::from(n))),
594        Err(_) => Ok(Value::String(n.to_string())),
595    }
596}
597
598fn decode_enum(
599    name: &str,
600    elements: &[String],
601    atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
602) -> Result<Value> {
603    let idx = u8::try_from(atom)
604        .map_err(|e| IrDriverError::TypeMismatch(format!("enum→u8 decode: {e:?}")))?;
605    elements
606        .get(usize::from(idx))
607        .map(|s| Value::String(s.clone()))
608        .ok_or_else(|| {
609            IrDriverError::TypeMismatch(format!(
610                "enum {name}: index {idx} out of range (variants: {elements:?})"
611            ))
612        })
613}
614
615fn decode_foreign_field(
616    descriptor: &TypeDescriptor,
617    atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
618    cursor: &mut usize,
619) -> Result<Value> {
620    let field_type = FieldType::of_descriptor(descriptor).ok_or_else(|| {
621        IrDriverError::TypeMismatch(format!("{descriptor:?} is not a foreign field"))
622    })?;
623    let low = consume(atoms, cursor, descriptor)?.clone();
624    let high = consume(atoms, cursor, descriptor)?.clone();
625    let v =
626        super::curve::decode_foreign_field(field_type, &low, &high, &format!("{field_type:?}"))?;
627    Ok(Value::Bytes(v.to_le_bytes().to_vec()))
628}
629
630fn decode_opaque(
631    ts_type: &str,
632    descriptor: &TypeDescriptor,
633    atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
634    cursor: &mut usize,
635) -> Result<Value> {
636    match ts_type {
637        "string" => {
638            let atom = consume(atoms, cursor, descriptor)?;
639            let s = std::str::from_utf8(&atom.0).map_err(|e| {
640                IrDriverError::TypeMismatch(format!("Opaque<string> not valid UTF-8: {e}"))
641            })?;
642            Ok(Value::String(s.to_owned()))
643        }
644        "Uint8Array" => {
645            // Raw byte buffer — byte-honest. No length declared,
646            // so atom bytes are returned verbatim (no padding).
647            let atom = consume(atoms, cursor, descriptor)?;
648            Ok(Value::Bytes(atom.0.clone()))
649        }
650        // `Opaque<'JubjubPoint'>` consumes two consecutive Field atoms and
651        // reassembles them into `Object { x: Bytes, y: Bytes }`. Mirrors
652        // upstream `CompactTypeJubjubPoint.fromValue`.
653        "JubjubPoint" => {
654            let x_atom = consume(atoms, cursor, descriptor)?;
655            let y_atom = consume(atoms, cursor, descriptor)?;
656            let mut x_buf = x_atom.0.clone();
657            x_buf.resize(32, 0);
658            let mut y_buf = y_atom.0.clone();
659            y_buf.resize(32, 0);
660            let mut obj = std::collections::BTreeMap::new();
661            obj.insert("x".to_owned(), Value::Bytes(x_buf));
662            obj.insert("y".to_owned(), Value::Bytes(y_buf));
663            Ok(Value::Object(obj))
664        }
665        other => Err(IrDriverError::unimplemented(format!(
666            "decode_aligned_value Opaque<{other}>"
667        ))),
668    }
669}
670
671fn decode_point(
672    descriptor: &TypeDescriptor,
673    atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
674    cursor: &mut usize,
675) -> Result<Value> {
676    match descriptor {
677        TypeDescriptor::JubjubPoint => {
678            let x = decode_aligned_value(&TypeDescriptor::Field, atoms, cursor)?;
679            let y = decode_aligned_value(&TypeDescriptor::Field, atoms, cursor)?;
680            let mut obj = std::collections::BTreeMap::new();
681            obj.insert("x".to_owned(), x);
682            obj.insert("y".to_owned(), y);
683            Ok(Value::Object(obj))
684        }
685        TypeDescriptor::Curve25519Point => {
686            let x = decode_aligned_value(&TypeDescriptor::Curve25519Base, atoms, cursor)?;
687            let y = decode_aligned_value(&TypeDescriptor::Curve25519Base, atoms, cursor)?;
688            let mut obj = std::collections::BTreeMap::new();
689            obj.insert("x".to_owned(), x);
690            obj.insert("y".to_owned(), y);
691            Ok(Value::Object(obj))
692        }
693        TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
694            let base = if matches!(descriptor, TypeDescriptor::Secp256k1Point) {
695                TypeDescriptor::Secp256k1Base
696            } else {
697                TypeDescriptor::Secp256r1Base
698            };
699            let x = decode_aligned_value(&base, atoms, cursor)?;
700            let y = decode_aligned_value(&base, atoms, cursor)?;
701            let flag = consume(atoms, cursor, descriptor)?;
702            let identity = u8::try_from(flag).map_err(|e| {
703                IrDriverError::TypeMismatch(format!("{descriptor:?} identity decode: {e:?}"))
704            })? != 0;
705            let mut obj = std::collections::BTreeMap::new();
706            obj.insert("x".to_owned(), x);
707            obj.insert("y".to_owned(), y);
708            obj.insert("identity".to_owned(), Value::Bool(identity));
709            Ok(Value::Object(obj))
710        }
711        _ => Err(IrDriverError::TypeMismatch(format!(
712            "{descriptor:?} is not a curve point"
713        ))),
714    }
715}
716
717fn consume<'a>(
718    atoms: &'a [moonproof_ledger::base_crypto::fab::ValueAtom],
719    cursor: &mut usize,
720    descriptor: &TypeDescriptor,
721) -> Result<&'a moonproof_ledger::base_crypto::fab::ValueAtom> {
722    let atom = atoms.get(*cursor).ok_or_else(|| {
723        IrDriverError::TypeMismatch(format!(
724            "AlignedValue ran out of atoms decoding {descriptor:?} (cursor={}, atoms={})",
725            *cursor,
726            atoms.len()
727        ))
728    })?;
729    *cursor += 1;
730    Ok(atom)
731}
732
733/// Convenience wrapper: decode a complete `AlignedValue` against a
734/// descriptor and verify exact atom count.
735pub fn decode_aligned_value_full(
736    descriptor: &TypeDescriptor,
737    av: &moonproof_ledger::base_crypto::fab::AlignedValue,
738) -> Result<Value> {
739    let mut cursor = 0;
740    let v = decode_aligned_value(descriptor, &av.value.0, &mut cursor)?;
741    if cursor != av.value.0.len() {
742        return Err(IrDriverError::TypeMismatch(format!(
743            "AlignedValue had {} atoms but descriptor consumed {cursor}",
744            av.value.0.len()
745        )));
746    }
747    Ok(v)
748}
749
750/// Decode a JSON value as `u128`. Accepts unsigned numbers and
751/// decimal strings (matching the IR's big-int convention).
752pub fn json_as_u128(value: &Value) -> Result<u128> {
753    if let Some(n) = value.as_u128() {
754        return Ok(n);
755    }
756    if let Some(s) = value.as_str() {
757        return s
758            .parse()
759            .map_err(|e| IrDriverError::TypeMismatch(format!("not a u128: {s} ({e})")));
760    }
761    Err(IrDriverError::TypeMismatch(format!(
762        "expected u128-shaped value, got {value}"
763    )))
764}
765
766// ===========================================================================
767// Pre-compiled FAB encoding plans (cached Alignment + zero-concat atom writer)
768// ===========================================================================
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
771enum UintWidth {
772    U8,
773    U16,
774    U32,
775    U64,
776    U128,
777}
778
779impl UintWidth {
780    const fn byte_len(self) -> u32 {
781        match self {
782            Self::U8 => 1,
783            Self::U16 => 2,
784            Self::U32 => 4,
785            Self::U64 => 8,
786            Self::U128 => 16,
787        }
788    }
789}
790
791#[derive(Debug, Clone)]
792enum FabNode {
793    Bool,
794    Uint {
795        max: u128,
796        width: UintWidth,
797    },
798    Bytes {
799        length: u32,
800    },
801    Field,
802    ForeignField(FieldType),
803    JubjubPoint,
804    WeierstrassPoint {
805        base: FieldType,
806        name: &'static str,
807    },
808    Curve25519Point,
809    Enum {
810        name: String,
811        elements: Vec<Arc<str>>,
812    },
813    OpaqueString,
814    OpaqueBytes,
815    OpaqueJubjubPoint,
816    Struct {
817        name: String,
818        fields: Vec<(Arc<str>, FabNode)>,
819    },
820    Tuple(Vec<FabNode>),
821    Vector {
822        length: u32,
823        elem: Box<FabNode>,
824    },
825    EmptyVector,
826}
827
828/// Pre-compiled FAB `AlignedValue` encoder for a [`TypeDescriptor`].
829///
830/// Computing the flat [`Alignment`](moonproof_ledger::base_crypto::fab::Alignment)
831/// and resolving wrapper descriptors (`Alias`, `Cell`, `Contract`, `Uint` widths)
832/// once at IR load time lets hot-path encoding write atoms straight into a single
833/// pre-sized `Vec<ValueAtom>`, skipping intermediate `AlignedValue` allocations
834/// and `AlignedValue::concat` copies.
835#[derive(Debug, Clone)]
836pub struct FabPlan {
837    alignment: moonproof_ledger::base_crypto::fab::Alignment,
838    root: FabNode,
839    all_field_atoms: bool,
840}
841
842/// Pre-compiled encoder for a circuit's full argument tuple (`encode_input`).
843#[derive(Debug, Clone)]
844pub struct CircuitInputPlan {
845    alignment: moonproof_ledger::base_crypto::fab::Alignment,
846    args: Vec<(String, FabNode)>,
847}
848
849impl FabPlan {
850    /// Compile a flat [`TypeDescriptor`] into a reusable [`FabPlan`].
851    ///
852    /// Returns `None` for non-flat container descriptors (`Map`, `Set`,
853    /// `List`, `MerkleTree`, `HistoricMerkleTree`), `Unknown`, invalid `Uint`
854    /// bounds, or unsupported `Opaque` tags so callers can fall back to
855    /// [`encode_literal`] for exact error reporting.
856    #[must_use]
857    pub fn compile(descriptor: &TypeDescriptor) -> Option<Self> {
858        let mut segments = Vec::new();
859        let root = compile_fab_node(descriptor, &mut segments)?;
860        let all_field_atoms = !segments.is_empty() && root.is_pure_field();
861        Some(Self {
862            alignment: moonproof_ledger::base_crypto::fab::Alignment(segments),
863            root,
864            all_field_atoms,
865        })
866    }
867
868    /// Cached flat alignment for this descriptor.
869    #[must_use]
870    pub fn alignment(&self) -> &moonproof_ledger::base_crypto::fab::Alignment {
871        &self.alignment
872    }
873
874    /// Maximum aligned byte size of values matching this plan.
875    #[must_use]
876    pub fn max_aligned_size(&self) -> usize {
877        use moonproof_ledger::transient_crypto::fab::AlignmentExt;
878        self.alignment.max_aligned_size()
879    }
880
881    /// Encode `value` directly into a single flat [`AlignedValue`].
882    pub fn encode(&self, value: &Value) -> Result<AlignedValue> {
883        use moonproof_ledger::base_crypto::fab::Value as FabValue;
884        let mut atoms = Vec::with_capacity(self.alignment.0.len());
885        self.root.encode_into(value, &mut atoms)?;
886        AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
887            IrDriverError::TypeMismatch(
888                "FabPlan AlignedValue construction failed (alignment/value mismatch)".into(),
889            )
890        })
891    }
892
893    /// Encode a compact [`VmVal`] directly into a single flat [`AlignedValue`]
894    /// without intermediate [`RuntimeValue`] or `BTreeMap` allocations.
895    pub(crate) fn encode_vm_val(&self, value: &VmVal) -> Result<AlignedValue> {
896        use moonproof_ledger::base_crypto::fab::Value as FabValue;
897        let mut atoms = Vec::with_capacity(self.alignment.0.len());
898        self.root.encode_vm_val_into(value, &mut atoms)?;
899        AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
900            IrDriverError::TypeMismatch(
901                "FabPlan AlignedValue construction failed (alignment/value mismatch)".into(),
902            )
903        })
904    }
905
906    /// Decode a complete [`AlignedValue`] directly into a compact [`VmVal`],
907    /// verifying exact atom consumption.
908    pub(crate) fn decode_to_vm_val(&self, av: &AlignedValue) -> Result<VmVal> {
909        let mut cursor = 0;
910        let val = self.root.decode_vm_val(&av.value.0, &mut cursor)?;
911        if cursor != av.value.0.len() {
912            return Err(IrDriverError::TypeMismatch(format!(
913                "AlignedValue had {} atoms but FabPlan consumed {cursor}",
914                av.value.0.len()
915            )));
916        }
917        Ok(val)
918    }
919
920    /// Fast path for `transientHash` / `transientCommit` on pure-`Field`
921    /// descriptors (`Field`, `Tuple<Field, ..>`, `Vector<N, Field>`, `Struct`
922    /// of `Field`s): writes `Fr` elements directly without building an
923    /// intermediate [`AlignedValue`]. Returns `None` if this plan contains
924    /// non-`Field` atoms.
925    pub(crate) fn try_encode_vm_val_frs(
926        &self,
927        value: &VmVal,
928        out: &mut Vec<moonproof_ledger::transient_crypto::curve::Fr>,
929    ) -> Option<Result<()>> {
930        if !self.all_field_atoms {
931            return None;
932        }
933        out.reserve(self.alignment.0.len());
934        Some(self.root.encode_vm_val_frs_into(value, out))
935    }
936}
937
938impl CircuitInputPlan {
939    /// Compile all arguments of a circuit into a single flat encoder.
940    #[must_use]
941    pub fn compile(arguments: &[moonproof_runtime_ir::ir::Argument]) -> Option<Self> {
942        let mut segments = Vec::new();
943        let mut args = Vec::with_capacity(arguments.len());
944        for arg in arguments {
945            let node = compile_fab_node(&arg.arg_type, &mut segments)?;
946            args.push((arg.name.clone(), node));
947        }
948        Some(Self {
949            alignment: moonproof_ledger::base_crypto::fab::Alignment(segments),
950            args,
951        })
952    }
953
954    /// Encode all circuit arguments into a single concatenated [`AlignedValue`].
955    pub fn encode<S: std::hash::BuildHasher>(
956        &self,
957        circuit_name: &str,
958        arg_values: &std::collections::HashMap<String, Value, S>,
959    ) -> Result<AlignedValue> {
960        use moonproof_ledger::base_crypto::fab::Value as FabValue;
961        if self.args.is_empty() {
962            return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
963        }
964        let mut atoms = Vec::with_capacity(self.alignment.0.len());
965        for (name, node) in &self.args {
966            let v = arg_values
967                .get(name)
968                .ok_or_else(|| IrDriverError::ArgCount {
969                    context: format!("circuit '{circuit_name}' arg '{name}'"),
970                    expected: self.args.len(),
971                    got: arg_values.len(),
972                })?;
973            node.encode_into(v, &mut atoms)?;
974        }
975        AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
976            IrDriverError::TypeMismatch(format!(
977                "circuit '{circuit_name}' input AlignedValue construction failed"
978            ))
979        })
980    }
981
982    /// Encode positional [`VmVal`] circuit arguments directly into a single
983    /// concatenated [`AlignedValue`].
984    pub(crate) fn encode_vm_vals(
985        &self,
986        circuit_name: &str,
987        arg_values: &[VmVal],
988    ) -> Result<AlignedValue> {
989        use moonproof_ledger::base_crypto::fab::Value as FabValue;
990        if self.args.is_empty() {
991            return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
992        }
993        if arg_values.len() != self.args.len() {
994            return Err(IrDriverError::ArgCount {
995                context: format!("circuit '{circuit_name}'"),
996                expected: self.args.len(),
997                got: arg_values.len(),
998            });
999        }
1000        let mut atoms = Vec::with_capacity(self.alignment.0.len());
1001        for ((_, node), v) in self.args.iter().zip(arg_values.iter()) {
1002            node.encode_vm_val_into(v, &mut atoms)?;
1003        }
1004        AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
1005            IrDriverError::TypeMismatch(format!(
1006                "circuit '{circuit_name}' input AlignedValue construction failed"
1007            ))
1008        })
1009    }
1010}
1011
1012fn compile_curve_fab_node(
1013    descriptor: &TypeDescriptor,
1014    segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
1015) -> Option<FabNode> {
1016    use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
1017    let push_atom = |segs: &mut Vec<AlignmentSegment>, atom: AlignmentAtom| {
1018        segs.push(AlignmentSegment::Atom(atom));
1019    };
1020    let push_split = |segs: &mut Vec<AlignmentSegment>, lo: u32, hi: u32| {
1021        push_atom(segs, AlignmentAtom::Bytes { length: lo });
1022        push_atom(segs, AlignmentAtom::Bytes { length: hi });
1023    };
1024    match descriptor {
1025        TypeDescriptor::JubjubScalar => {
1026            push_atom(segments, AlignmentAtom::Field);
1027            Some(FabNode::ForeignField(FieldType::JubjubScalar))
1028        }
1029        TypeDescriptor::Secp256k1Base
1030        | TypeDescriptor::Secp256k1Scalar
1031        | TypeDescriptor::Secp256r1Base
1032        | TypeDescriptor::Secp256r1Scalar
1033        | TypeDescriptor::Curve25519Base => {
1034            let ft = FieldType::of_descriptor(descriptor)?;
1035            push_split(segments, 24, 8);
1036            Some(FabNode::ForeignField(ft))
1037        }
1038        TypeDescriptor::Curve25519Scalar => {
1039            push_split(segments, 26, 7);
1040            Some(FabNode::ForeignField(FieldType::Curve25519Scalar))
1041        }
1042        TypeDescriptor::JubjubPoint => {
1043            push_atom(segments, AlignmentAtom::Field);
1044            push_atom(segments, AlignmentAtom::Field);
1045            Some(FabNode::JubjubPoint)
1046        }
1047        TypeDescriptor::Secp256k1Point => {
1048            push_split(segments, 24, 8);
1049            push_split(segments, 24, 8);
1050            push_atom(segments, AlignmentAtom::Field);
1051            Some(FabNode::WeierstrassPoint {
1052                base: FieldType::Secp256k1Base,
1053                name: "Secp256k1Point",
1054            })
1055        }
1056        TypeDescriptor::Secp256r1Point => {
1057            push_split(segments, 24, 8);
1058            push_split(segments, 24, 8);
1059            push_atom(segments, AlignmentAtom::Field);
1060            Some(FabNode::WeierstrassPoint {
1061                base: FieldType::Secp256r1Base,
1062                name: "Secp256r1Point",
1063            })
1064        }
1065        TypeDescriptor::Curve25519Point => {
1066            push_split(segments, 24, 8);
1067            push_split(segments, 24, 8);
1068            Some(FabNode::Curve25519Point)
1069        }
1070        _ => None,
1071    }
1072}
1073
1074fn compile_compound_fab_node(
1075    descriptor: &TypeDescriptor,
1076    segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
1077) -> Option<FabNode> {
1078    use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
1079    match descriptor {
1080        TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
1081            "string" => {
1082                segments.push(AlignmentSegment::Atom(AlignmentAtom::Compress));
1083                Some(FabNode::OpaqueString)
1084            }
1085            "Uint8Array" => {
1086                segments.push(AlignmentSegment::Atom(AlignmentAtom::Compress));
1087                Some(FabNode::OpaqueBytes)
1088            }
1089            "JubjubPoint" => {
1090                segments.push(AlignmentSegment::Atom(AlignmentAtom::Field));
1091                segments.push(AlignmentSegment::Atom(AlignmentAtom::Field));
1092                Some(FabNode::OpaqueJubjubPoint)
1093            }
1094            _ => None,
1095        },
1096        TypeDescriptor::Struct { name, elements } => {
1097            let mut fields = Vec::with_capacity(elements.len());
1098            for field in elements {
1099                let node = compile_fab_node(&field.field_type, segments)?;
1100                fields.push((Arc::from(field.name.as_str()), node));
1101            }
1102            Some(FabNode::Struct {
1103                name: name.clone(),
1104                fields,
1105            })
1106        }
1107        TypeDescriptor::Tuple { types } => {
1108            let mut nodes = Vec::with_capacity(types.len());
1109            for ty in types {
1110                nodes.push(compile_fab_node(ty, segments)?);
1111            }
1112            Some(FabNode::Tuple(nodes))
1113        }
1114        TypeDescriptor::Vector { length, elt_type } => {
1115            if *length == 0 {
1116                return Some(FabNode::EmptyVector);
1117            }
1118            let mut elem_segs = Vec::new();
1119            let elem = compile_fab_node(elt_type, &mut elem_segs)?;
1120            let count = usize::try_from(*length).ok()?;
1121            segments.reserve(elem_segs.len().checked_mul(count)?);
1122            for _ in 0..count {
1123                segments.extend_from_slice(&elem_segs);
1124            }
1125            Some(FabNode::Vector {
1126                length: *length,
1127                elem: Box::new(elem),
1128            })
1129        }
1130        _ => None,
1131    }
1132}
1133
1134fn compile_fab_node(
1135    descriptor: &TypeDescriptor,
1136    segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
1137) -> Option<FabNode> {
1138    use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
1139    let push_atom = |segs: &mut Vec<AlignmentSegment>, atom: AlignmentAtom| {
1140        segs.push(AlignmentSegment::Atom(atom));
1141    };
1142
1143    match descriptor {
1144        TypeDescriptor::Boolean => {
1145            push_atom(segments, AlignmentAtom::Bytes { length: 1 });
1146            Some(FabNode::Bool)
1147        }
1148        TypeDescriptor::Uint { maxval, .. } => {
1149            let max = maxval.as_u128()?;
1150            let width = if max <= u128::from(u8::MAX) {
1151                UintWidth::U8
1152            } else if max <= u128::from(u16::MAX) {
1153                UintWidth::U16
1154            } else if max <= u128::from(u32::MAX) {
1155                UintWidth::U32
1156            } else if max <= u128::from(u64::MAX) {
1157                UintWidth::U64
1158            } else {
1159                UintWidth::U128
1160            };
1161            push_atom(
1162                segments,
1163                AlignmentAtom::Bytes {
1164                    length: width.byte_len(),
1165                },
1166            );
1167            Some(FabNode::Uint { max, width })
1168        }
1169        TypeDescriptor::Counter => {
1170            push_atom(segments, AlignmentAtom::Bytes { length: 8 });
1171            Some(FabNode::Uint {
1172                max: u128::from(u64::MAX),
1173                width: UintWidth::U64,
1174            })
1175        }
1176        TypeDescriptor::Bytes { length } => {
1177            push_atom(segments, AlignmentAtom::Bytes { length: *length });
1178            Some(FabNode::Bytes { length: *length })
1179        }
1180        TypeDescriptor::Field => {
1181            push_atom(segments, AlignmentAtom::Field);
1182            Some(FabNode::Field)
1183        }
1184        TypeDescriptor::JubjubScalar
1185        | TypeDescriptor::Secp256k1Base
1186        | TypeDescriptor::Secp256k1Scalar
1187        | TypeDescriptor::Secp256r1Base
1188        | TypeDescriptor::Secp256r1Scalar
1189        | TypeDescriptor::Curve25519Base
1190        | TypeDescriptor::Curve25519Scalar
1191        | TypeDescriptor::JubjubPoint
1192        | TypeDescriptor::Secp256k1Point
1193        | TypeDescriptor::Secp256r1Point
1194        | TypeDescriptor::Curve25519Point => compile_curve_fab_node(descriptor, segments),
1195        TypeDescriptor::Enum { name, elements } => {
1196            push_atom(segments, AlignmentAtom::Bytes { length: 1 });
1197            Some(FabNode::Enum {
1198                name: name.clone(),
1199                elements: elements.iter().map(|s| Arc::from(s.as_str())).collect(),
1200            })
1201        }
1202        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
1203            compile_fab_node(of, segments)
1204        }
1205        TypeDescriptor::Contract { .. } => {
1206            compile_fab_node(&TypeDescriptor::contract_address(), segments)
1207        }
1208        TypeDescriptor::Opaque { .. }
1209        | TypeDescriptor::Struct { .. }
1210        | TypeDescriptor::Tuple { .. }
1211        | TypeDescriptor::Vector { .. } => compile_compound_fab_node(descriptor, segments),
1212        TypeDescriptor::Map { .. }
1213        | TypeDescriptor::Set { .. }
1214        | TypeDescriptor::List { .. }
1215        | TypeDescriptor::MerkleTree { .. }
1216        | TypeDescriptor::HistoricMerkleTree { .. }
1217        | TypeDescriptor::Unknown => None,
1218    }
1219}
1220
1221fn push_le_trimmed(bytes: &[u8], atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>) {
1222    let mut end = bytes.len();
1223    while end > 0 && bytes[end - 1] == 0 {
1224        end -= 1;
1225    }
1226    atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(
1227        bytes[..end].to_vec(),
1228    ));
1229}
1230
1231fn encode_bytes_into(
1232    length: u32,
1233    value: &Value,
1234    atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1235) -> Result<()> {
1236    let owned: Vec<u8>;
1237    let bytes: &[u8] = if let Some(b) = value.as_bytes() {
1238        b
1239    } else if let Some(s) = value.as_str() {
1240        let trimmed = s
1241            .strip_prefix("0x")
1242            .or_else(|| s.strip_prefix("0X"))
1243            .unwrap_or(s);
1244        owned = hex::decode(trimmed).map_err(|e| {
1245            IrDriverError::TypeMismatch(format!(
1246                "Bytes<{length}> string is not valid hex: {s:?} ({e})"
1247            ))
1248        })?;
1249        owned.as_slice()
1250    } else {
1251        return Err(IrDriverError::TypeMismatch(format!(
1252            "expected Bytes for Bytes<{length}>, got {value}"
1253        )));
1254    };
1255    if bytes.len() != length as usize {
1256        return Err(IrDriverError::TypeMismatch(format!(
1257            "Bytes<{length}> received {} bytes",
1258            bytes.len()
1259        )));
1260    }
1261    push_le_trimmed(bytes, atoms);
1262    Ok(())
1263}
1264
1265fn encode_enum_names(name: &str, elements: &[Arc<str>], variant: &str) -> Result<u8> {
1266    let index = elements
1267        .iter()
1268        .position(|v| v.as_ref() == variant)
1269        .ok_or_else(|| {
1270            IrDriverError::TypeMismatch(format!(
1271                "enum {name}: variant '{variant}' not in {elements:?}"
1272            ))
1273        })?;
1274    u8::try_from(index).map_err(|_| {
1275        IrDriverError::TypeMismatch(format!(
1276            "enum {name} variant index {index} exceeds u8 — wire encoding assumes ≤256 variants"
1277        ))
1278    })
1279}
1280
1281fn encode_vm_bytes_into(
1282    length: u32,
1283    value: &VmVal,
1284    atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1285) -> Result<()> {
1286    let owned: Vec<u8>;
1287    let bytes: &[u8] = if let Some(b) = value.as_bytes() {
1288        b
1289    } else if let Some(s) = value.as_str() {
1290        let trimmed = s
1291            .strip_prefix("0x")
1292            .or_else(|| s.strip_prefix("0X"))
1293            .unwrap_or(s);
1294        owned = hex::decode(trimmed).map_err(|e| {
1295            IrDriverError::TypeMismatch(format!(
1296                "Bytes<{length}> string is not valid hex: {s:?} ({e})"
1297            ))
1298        })?;
1299        owned.as_slice()
1300    } else {
1301        return Err(IrDriverError::TypeMismatch(format!(
1302            "expected Bytes for Bytes<{length}>, got {}",
1303            value.to_runtime_value()
1304        )));
1305    };
1306    if bytes.len() != length as usize {
1307        return Err(IrDriverError::TypeMismatch(format!(
1308            "Bytes<{length}> received {} bytes",
1309            bytes.len()
1310        )));
1311    }
1312    push_le_trimmed(bytes, atoms);
1313    Ok(())
1314}
1315
1316fn encode_vm_field_into(
1317    value: &VmVal,
1318    atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1319) -> Result<()> {
1320    use moonproof_ledger::transient_crypto::curve::Fr;
1321    let fr = if let Some(b) = value.as_bytes() {
1322        Fr::from_le_bytes(b).ok_or_else(|| {
1323            IrDriverError::TypeMismatch(format!(
1324                "Field value out of range: {} bytes does not fit in Fr",
1325                b.len()
1326            ))
1327        })?
1328    } else if let Some(n) = value.as_u128() {
1329        Fr::from(n)
1330    } else if let Some(s) = value.as_str() {
1331        let n: u128 = s.parse().map_err(|e| {
1332            IrDriverError::TypeMismatch(format!("Field decimal-string parse failed: '{s}' ({e})"))
1333        })?;
1334        Fr::from(n)
1335    } else {
1336        return Err(IrDriverError::TypeMismatch(format!(
1337            "Field expects bytes or numeric, got {}",
1338            value.to_runtime_value()
1339        )));
1340    };
1341    push_le_trimmed(&fr.as_le_bytes(), atoms);
1342    Ok(())
1343}
1344
1345fn consume_fab_atom<'a>(
1346    atoms: &'a [moonproof_ledger::base_crypto::fab::ValueAtom],
1347    cursor: &mut usize,
1348    what: &str,
1349) -> Result<&'a moonproof_ledger::base_crypto::fab::ValueAtom> {
1350    let atom = atoms.get(*cursor).ok_or_else(|| {
1351        IrDriverError::TypeMismatch(format!(
1352            "AlignedValue ran out of atoms decoding {what} (cursor={}, atoms={})",
1353            *cursor,
1354            atoms.len()
1355        ))
1356    })?;
1357    *cursor += 1;
1358    Ok(atom)
1359}
1360
1361fn decode_atom_bytes32(atom: &moonproof_ledger::base_crypto::fab::ValueAtom) -> VmVal {
1362    let mut buf = [0u8; 32];
1363    let n = atom.0.len().min(32);
1364    buf[..n].copy_from_slice(&atom.0[..n]);
1365    VmVal::Bytes32(buf)
1366}
1367
1368fn decode_vm_uint(
1369    width: UintWidth,
1370    atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
1371) -> Result<VmVal> {
1372    let n: u128 = match width {
1373        UintWidth::U8 => u128::from(
1374            u8::try_from(atom)
1375                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u8 decode: {e:?}")))?,
1376        ),
1377        UintWidth::U16 => u128::from(
1378            u16::try_from(atom)
1379                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u16 decode: {e:?}")))?,
1380        ),
1381        UintWidth::U32 => u128::from(
1382            u32::try_from(atom)
1383                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u32 decode: {e:?}")))?,
1384        ),
1385        UintWidth::U64 => u128::from(
1386            u64::try_from(atom)
1387                .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u64 decode: {e:?}")))?,
1388        ),
1389        UintWidth::U128 => u128::try_from(atom)
1390            .map_err(|e| IrDriverError::TypeMismatch(format!("uint→u128 decode: {e:?}")))?,
1391    };
1392    Ok(VmVal::from_uint(n))
1393}
1394
1395impl FabNode {
1396    fn encode_compound_into(
1397        &self,
1398        value: &Value,
1399        atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1400    ) -> Result<()> {
1401        match self {
1402            Self::Struct { name, fields } => {
1403                let obj = value.as_object().ok_or_else(|| {
1404                    IrDriverError::TypeMismatch(format!(
1405                        "expected object for struct {name}, got {value}"
1406                    ))
1407                })?;
1408                for (field_name, field_node) in fields {
1409                    let field_v = obj.get(field_name.as_ref()).ok_or_else(|| {
1410                        IrDriverError::TypeMismatch(format!(
1411                            "struct {name} missing field '{field_name}'; got keys {:?}",
1412                            obj.keys().collect::<Vec<_>>()
1413                        ))
1414                    })?;
1415                    field_node.encode_into(field_v, atoms)?;
1416                }
1417                Ok(())
1418            }
1419            Self::Tuple(nodes) => {
1420                let arr = value.as_array().ok_or_else(|| {
1421                    IrDriverError::TypeMismatch(format!("expected array for tuple, got {value}"))
1422                })?;
1423                if arr.len() != nodes.len() {
1424                    return Err(IrDriverError::TypeMismatch(format!(
1425                        "tuple arity mismatch: expected {}, got {}",
1426                        nodes.len(),
1427                        arr.len()
1428                    )));
1429                }
1430                for (node, v) in nodes.iter().zip(arr.iter()) {
1431                    node.encode_into(v, atoms)?;
1432                }
1433                Ok(())
1434            }
1435            Self::Vector { length, elem } => {
1436                let arr = value.as_array().ok_or_else(|| {
1437                    IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
1438                })?;
1439                if u32::try_from(arr.len()) != Ok(*length) {
1440                    return Err(IrDriverError::TypeMismatch(format!(
1441                        "vector length mismatch: expected {length}, got {}",
1442                        arr.len()
1443                    )));
1444                }
1445                for v in arr {
1446                    elem.encode_into(v, atoms)?;
1447                }
1448                Ok(())
1449            }
1450            Self::EmptyVector => {
1451                let arr = value.as_array().ok_or_else(|| {
1452                    IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
1453                })?;
1454                if !arr.is_empty() {
1455                    return Err(IrDriverError::TypeMismatch(format!(
1456                        "vector length mismatch: expected 0, got {}",
1457                        arr.len()
1458                    )));
1459                }
1460                Ok(())
1461            }
1462            _ => unreachable!("only called for compound variants"),
1463        }
1464    }
1465
1466    fn encode_into(
1467        &self,
1468        value: &Value,
1469        atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1470    ) -> Result<()> {
1471        match self {
1472            Self::Bool => {
1473                let b = value.as_bool().ok_or_else(|| {
1474                    IrDriverError::TypeMismatch(format!("expected bool, got {value}"))
1475                })?;
1476                atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(if b {
1477                    vec![1]
1478                } else {
1479                    Vec::new()
1480                }));
1481                Ok(())
1482            }
1483            Self::Uint { max, width } => {
1484                let v = json_as_u128(value)?;
1485                if v > *max {
1486                    return Err(IrDriverError::TypeMismatch(format!(
1487                        "value {v} exceeds Uint maxval {max}"
1488                    )));
1489                }
1490                let le = v.to_le_bytes();
1491                push_le_trimmed(&le[..width.byte_len() as usize], atoms);
1492                Ok(())
1493            }
1494            Self::Bytes { length } => encode_bytes_into(*length, value, atoms),
1495            Self::Field => {
1496                atoms.extend(encode_field(value)?.value.0);
1497                Ok(())
1498            }
1499            Self::ForeignField(ft) => {
1500                atoms.extend(super::curve::encode_field_type(*ft, value)?.value.0);
1501                Ok(())
1502            }
1503            Self::JubjubPoint => {
1504                atoms.extend(super::curve::encode_jubjub_point(value)?.value.0);
1505                Ok(())
1506            }
1507            Self::WeierstrassPoint { base, name } => {
1508                atoms.extend(
1509                    super::curve::encode_weierstrass_point(*base, value, name)?
1510                        .value
1511                        .0,
1512                );
1513                Ok(())
1514            }
1515            Self::Curve25519Point => {
1516                atoms.extend(super::curve::encode_curve25519_point(value)?.value.0);
1517                Ok(())
1518            }
1519            Self::Enum { name, elements } => {
1520                let variant = value.as_str().ok_or_else(|| {
1521                    IrDriverError::TypeMismatch(format!(
1522                        "expected enum-variant string for {name}, got {value}"
1523                    ))
1524                })?;
1525                let idx = encode_enum_names(name, elements, variant)?;
1526                push_le_trimmed(&[idx], atoms);
1527                Ok(())
1528            }
1529            Self::OpaqueString => {
1530                atoms.extend(encode_opaque("string", value)?.value.0);
1531                Ok(())
1532            }
1533            Self::OpaqueBytes => {
1534                atoms.extend(encode_opaque("Uint8Array", value)?.value.0);
1535                Ok(())
1536            }
1537            Self::OpaqueJubjubPoint => {
1538                atoms.extend(encode_opaque("JubjubPoint", value)?.value.0);
1539                Ok(())
1540            }
1541            Self::Struct { .. } | Self::Tuple(_) | Self::Vector { .. } | Self::EmptyVector => {
1542                self.encode_compound_into(value, atoms)
1543            }
1544        }
1545    }
1546
1547    fn encode_vm_compound_into(
1548        &self,
1549        value: &VmVal,
1550        atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1551    ) -> Result<()> {
1552        match self {
1553            Self::Struct { name, fields } => {
1554                let Some(obj_fields) = value.as_object() else {
1555                    return Err(IrDriverError::TypeMismatch(format!(
1556                        "expected object for struct {name}, got {}",
1557                        value.to_runtime_value()
1558                    )));
1559                };
1560                for (idx, (field_name, field_node)) in fields.iter().enumerate() {
1561                    let field_v = value.get_field(field_name, Some(idx)).ok_or_else(|| {
1562                        IrDriverError::TypeMismatch(format!(
1563                            "struct {name} missing field '{field_name}'; got keys {:?}",
1564                            obj_fields
1565                                .iter()
1566                                .map(|(k, _)| k.as_ref())
1567                                .collect::<Vec<_>>()
1568                        ))
1569                    })?;
1570                    field_node.encode_vm_val_into(field_v, atoms)?;
1571                }
1572                Ok(())
1573            }
1574            Self::Tuple(nodes) => {
1575                let arr = value.as_array().ok_or_else(|| {
1576                    IrDriverError::TypeMismatch(format!(
1577                        "expected array for tuple, got {}",
1578                        value.to_runtime_value()
1579                    ))
1580                })?;
1581                if arr.len() != nodes.len() {
1582                    return Err(IrDriverError::TypeMismatch(format!(
1583                        "tuple arity mismatch: expected {}, got {}",
1584                        nodes.len(),
1585                        arr.len()
1586                    )));
1587                }
1588                for (node, v) in nodes.iter().zip(arr.iter()) {
1589                    node.encode_vm_val_into(v, atoms)?;
1590                }
1591                Ok(())
1592            }
1593            Self::Vector { length, elem } => {
1594                let arr = value.as_array().ok_or_else(|| {
1595                    IrDriverError::TypeMismatch(format!(
1596                        "expected array for vector, got {}",
1597                        value.to_runtime_value()
1598                    ))
1599                })?;
1600                if u32::try_from(arr.len()) != Ok(*length) {
1601                    return Err(IrDriverError::TypeMismatch(format!(
1602                        "vector length mismatch: expected {length}, got {}",
1603                        arr.len()
1604                    )));
1605                }
1606                for v in arr {
1607                    elem.encode_vm_val_into(v, atoms)?;
1608                }
1609                Ok(())
1610            }
1611            Self::EmptyVector => {
1612                let arr = value.as_array().ok_or_else(|| {
1613                    IrDriverError::TypeMismatch(format!(
1614                        "expected array for vector, got {}",
1615                        value.to_runtime_value()
1616                    ))
1617                })?;
1618                if !arr.is_empty() {
1619                    return Err(IrDriverError::TypeMismatch(format!(
1620                        "vector length mismatch: expected 0, got {}",
1621                        arr.len()
1622                    )));
1623                }
1624                Ok(())
1625            }
1626            _ => unreachable!("only called for compound variants"),
1627        }
1628    }
1629
1630    fn encode_vm_val_into(
1631        &self,
1632        value: &VmVal,
1633        atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
1634    ) -> Result<()> {
1635        match self {
1636            Self::Bool => {
1637                let b = value.as_bool().ok_or_else(|| {
1638                    IrDriverError::TypeMismatch(format!(
1639                        "expected bool, got {}",
1640                        value.to_runtime_value()
1641                    ))
1642                })?;
1643                atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(if b {
1644                    vec![1]
1645                } else {
1646                    Vec::new()
1647                }));
1648                Ok(())
1649            }
1650            Self::Uint { max, width } => {
1651                let v = value.as_u128_parsed()?;
1652                if v > *max {
1653                    return Err(IrDriverError::TypeMismatch(format!(
1654                        "value {v} exceeds Uint maxval {max}"
1655                    )));
1656                }
1657                let le = v.to_le_bytes();
1658                push_le_trimmed(&le[..width.byte_len() as usize], atoms);
1659                Ok(())
1660            }
1661            Self::Bytes { length } => encode_vm_bytes_into(*length, value, atoms),
1662            Self::Field => encode_vm_field_into(value, atoms),
1663            Self::Enum { name, elements } => {
1664                let variant = value.as_str().ok_or_else(|| {
1665                    IrDriverError::TypeMismatch(format!(
1666                        "expected enum-variant string for {name}, got {}",
1667                        value.to_runtime_value()
1668                    ))
1669                })?;
1670                let idx = encode_enum_names(name, elements, variant)?;
1671                push_le_trimmed(&[idx], atoms);
1672                Ok(())
1673            }
1674            Self::OpaqueString => {
1675                let s = value.as_str().ok_or_else(|| {
1676                    IrDriverError::TypeMismatch(format!(
1677                        "expected string for Opaque<string>, got {}",
1678                        value.to_runtime_value()
1679                    ))
1680                })?;
1681                push_le_trimmed(s.as_bytes(), atoms);
1682                Ok(())
1683            }
1684            Self::OpaqueBytes => {
1685                let b = value.as_bytes().ok_or_else(|| {
1686                    IrDriverError::TypeMismatch(format!(
1687                        "expected Bytes for Opaque<Uint8Array>, got {}",
1688                        value.to_runtime_value()
1689                    ))
1690                })?;
1691                push_le_trimmed(b, atoms);
1692                Ok(())
1693            }
1694            Self::OpaqueJubjubPoint | Self::JubjubPoint => {
1695                let x = value.get_field("x", Some(0)).ok_or_else(|| {
1696                    IrDriverError::TypeMismatch("JubjubPoint missing field 'x'".into())
1697                })?;
1698                let y = value.get_field("y", Some(1)).ok_or_else(|| {
1699                    IrDriverError::TypeMismatch("JubjubPoint missing field 'y'".into())
1700                })?;
1701                encode_vm_field_into(x, atoms)?;
1702                encode_vm_field_into(y, atoms)
1703            }
1704            Self::ForeignField(ft) => {
1705                let rv = value.to_runtime_value();
1706                atoms.extend(super::curve::encode_field_type(*ft, &rv)?.value.0);
1707                Ok(())
1708            }
1709            Self::WeierstrassPoint { base, name } => {
1710                let rv = value.to_runtime_value();
1711                atoms.extend(
1712                    super::curve::encode_weierstrass_point(*base, &rv, name)?
1713                        .value
1714                        .0,
1715                );
1716                Ok(())
1717            }
1718            Self::Curve25519Point => {
1719                let rv = value.to_runtime_value();
1720                atoms.extend(super::curve::encode_curve25519_point(&rv)?.value.0);
1721                Ok(())
1722            }
1723            Self::Struct { .. } | Self::Tuple(_) | Self::Vector { .. } | Self::EmptyVector => {
1724                self.encode_vm_compound_into(value, atoms)
1725            }
1726        }
1727    }
1728
1729    fn decode_vm_val(
1730        &self,
1731        atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
1732        cursor: &mut usize,
1733    ) -> Result<VmVal> {
1734        match self {
1735            Self::Bool => {
1736                let atom = consume_fab_atom(atoms, cursor, "Boolean")?;
1737                let n = u8::try_from(atom)
1738                    .map_err(|e| IrDriverError::TypeMismatch(format!("bool atom decode: {e:?}")))?;
1739                Ok(VmVal::Bool(n != 0))
1740            }
1741            Self::Uint { width, .. } => {
1742                let atom = consume_fab_atom(atoms, cursor, "Uint")?;
1743                decode_vm_uint(*width, atom)
1744            }
1745            Self::Bytes { length: 32 } | Self::Field => {
1746                let atom = consume_fab_atom(atoms, cursor, "Bytes32/Field")?;
1747                Ok(decode_atom_bytes32(atom))
1748            }
1749            Self::Bytes { length } => {
1750                let atom = consume_fab_atom(atoms, cursor, "Bytes")?;
1751                let mut buf = atom.0.clone();
1752                buf.resize(*length as usize, 0);
1753                Ok(VmVal::from_bytes_vec(buf))
1754            }
1755            Self::ForeignField(FieldType::JubjubScalar) => {
1756                let atom = consume_fab_atom(atoms, cursor, "JubjubScalar")?;
1757                Ok(decode_atom_bytes32(atom))
1758            }
1759            Self::ForeignField(ft) => {
1760                let low = consume_fab_atom(atoms, cursor, "ForeignField.low")?;
1761                let high = consume_fab_atom(atoms, cursor, "ForeignField.high")?;
1762                let v = super::curve::decode_foreign_field(*ft, low, high, &format!("{ft:?}"))?;
1763                Ok(VmVal::Bytes32(v.to_le_bytes()))
1764            }
1765            Self::JubjubPoint
1766            | Self::OpaqueJubjubPoint
1767            | Self::Curve25519Point
1768            | Self::WeierstrassPoint { .. } => self.decode_vm_point(atoms, cursor),
1769            Self::Enum { name, elements } => {
1770                let atom = consume_fab_atom(atoms, cursor, name)?;
1771                let idx = u8::try_from(atom)
1772                    .map_err(|e| IrDriverError::TypeMismatch(format!("enum→u8 decode: {e:?}")))?;
1773                elements
1774                    .get(usize::from(idx))
1775                    .map(|s| VmVal::Str(Arc::clone(s)))
1776                    .ok_or_else(|| {
1777                        IrDriverError::TypeMismatch(format!(
1778                            "enum {name}: index {idx} out of range (variants: {elements:?})"
1779                        ))
1780                    })
1781            }
1782            Self::OpaqueString => {
1783                let atom = consume_fab_atom(atoms, cursor, "Opaque<string>")?;
1784                let s = std::str::from_utf8(&atom.0).map_err(|e| {
1785                    IrDriverError::TypeMismatch(format!("Opaque<string> not valid UTF-8: {e}"))
1786                })?;
1787                Ok(VmVal::Str(Arc::from(s)))
1788            }
1789            Self::OpaqueBytes => {
1790                let atom = consume_fab_atom(atoms, cursor, "Opaque<Uint8Array>")?;
1791                Ok(VmVal::from_bytes_slice(&atom.0))
1792            }
1793            Self::Struct { fields, .. } => {
1794                let mut out = Vec::with_capacity(fields.len());
1795                for (field_name, field_node) in fields {
1796                    let v = field_node.decode_vm_val(atoms, cursor)?;
1797                    out.push((Arc::clone(field_name), v));
1798                }
1799                Ok(VmVal::Object(Arc::from(out)))
1800            }
1801            Self::Tuple(nodes) => {
1802                if nodes.is_empty() {
1803                    return Ok(VmVal::Array(Arc::from([] as [VmVal; 0])));
1804                }
1805                let mut out = Vec::with_capacity(nodes.len());
1806                for node in nodes {
1807                    out.push(node.decode_vm_val(atoms, cursor)?);
1808                }
1809                Ok(VmVal::Array(Arc::from(out)))
1810            }
1811            Self::Vector { length, elem } => {
1812                let len = *length as usize;
1813                let mut out = Vec::with_capacity(len);
1814                for _ in 0..len {
1815                    out.push(elem.decode_vm_val(atoms, cursor)?);
1816                }
1817                Ok(VmVal::Array(Arc::from(out)))
1818            }
1819            Self::EmptyVector => Ok(VmVal::Array(Arc::from([] as [VmVal; 0]))),
1820        }
1821    }
1822
1823    fn decode_vm_point(
1824        &self,
1825        atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
1826        cursor: &mut usize,
1827    ) -> Result<VmVal> {
1828        match self {
1829            Self::JubjubPoint | Self::OpaqueJubjubPoint => {
1830                let x = decode_atom_bytes32(consume_fab_atom(atoms, cursor, "JubjubPoint.x")?);
1831                let y = decode_atom_bytes32(consume_fab_atom(atoms, cursor, "JubjubPoint.y")?);
1832                Ok(VmVal::Object(Arc::from([
1833                    (Arc::from("x"), x),
1834                    (Arc::from("y"), y),
1835                ])))
1836            }
1837            Self::Curve25519Point => {
1838                let x_lo = consume_fab_atom(atoms, cursor, "Curve25519Point.x.lo")?;
1839                let x_hi = consume_fab_atom(atoms, cursor, "Curve25519Point.x.hi")?;
1840                let x = super::curve::decode_foreign_field(
1841                    FieldType::Curve25519Base,
1842                    x_lo,
1843                    x_hi,
1844                    "Curve25519Base",
1845                )?;
1846                let y_lo = consume_fab_atom(atoms, cursor, "Curve25519Point.y.lo")?;
1847                let y_hi = consume_fab_atom(atoms, cursor, "Curve25519Point.y.hi")?;
1848                let y = super::curve::decode_foreign_field(
1849                    FieldType::Curve25519Base,
1850                    y_lo,
1851                    y_hi,
1852                    "Curve25519Base",
1853                )?;
1854                Ok(VmVal::Object(Arc::from([
1855                    (Arc::from("x"), VmVal::Bytes32(x.to_le_bytes())),
1856                    (Arc::from("y"), VmVal::Bytes32(y.to_le_bytes())),
1857                ])))
1858            }
1859            Self::WeierstrassPoint { base, name } => {
1860                let x_lo = consume_fab_atom(atoms, cursor, name)?;
1861                let x_hi = consume_fab_atom(atoms, cursor, name)?;
1862                let x = super::curve::decode_foreign_field(*base, x_lo, x_hi, name)?;
1863                let y_lo = consume_fab_atom(atoms, cursor, name)?;
1864                let y_hi = consume_fab_atom(atoms, cursor, name)?;
1865                let y = super::curve::decode_foreign_field(*base, y_lo, y_hi, name)?;
1866                let flag = consume_fab_atom(atoms, cursor, name)?;
1867                let identity = u8::try_from(flag).map_err(|e| {
1868                    IrDriverError::TypeMismatch(format!("{name} identity decode: {e:?}"))
1869                })? != 0;
1870                Ok(VmVal::Object(Arc::from([
1871                    (Arc::from("x"), VmVal::Bytes32(x.to_le_bytes())),
1872                    (Arc::from("y"), VmVal::Bytes32(y.to_le_bytes())),
1873                    (Arc::from("identity"), VmVal::Bool(identity)),
1874                ])))
1875            }
1876            _ => unreachable!("only called for point variants"),
1877        }
1878    }
1879
1880    fn is_pure_field(&self) -> bool {
1881        match self {
1882            Self::Field => true,
1883            Self::Struct { fields, .. } => fields.iter().all(|(_, n)| n.is_pure_field()),
1884            Self::Tuple(nodes) => nodes.iter().all(Self::is_pure_field),
1885            Self::Vector { elem, .. } => elem.is_pure_field(),
1886            _ => false,
1887        }
1888    }
1889
1890    fn encode_vm_val_frs_into(
1891        &self,
1892        value: &VmVal,
1893        out: &mut Vec<moonproof_ledger::transient_crypto::curve::Fr>,
1894    ) -> Result<()> {
1895        use moonproof_ledger::transient_crypto::curve::Fr;
1896        match self {
1897            Self::Field => {
1898                let fr = if let Some(b) = value.as_bytes() {
1899                    Fr::from_le_bytes(b).ok_or_else(|| {
1900                        IrDriverError::TypeMismatch(format!(
1901                            "Field value out of range: {} bytes does not fit in Fr",
1902                            b.len()
1903                        ))
1904                    })?
1905                } else if let Some(n) = value.as_u128() {
1906                    Fr::from(n)
1907                } else if let Some(s) = value.as_str() {
1908                    let n: u128 = s.parse().map_err(|e| {
1909                        IrDriverError::TypeMismatch(format!(
1910                            "Field decimal-string parse failed: '{s}' ({e})"
1911                        ))
1912                    })?;
1913                    Fr::from(n)
1914                } else {
1915                    return Err(IrDriverError::TypeMismatch(format!(
1916                        "Field expects bytes or numeric, got {}",
1917                        value.to_runtime_value()
1918                    )));
1919                };
1920                out.push(fr);
1921                Ok(())
1922            }
1923            Self::Struct { name, fields } => {
1924                let Some(obj_fields) = value.as_object() else {
1925                    return Err(IrDriverError::TypeMismatch(format!(
1926                        "expected object for struct {name}, got {}",
1927                        value.to_runtime_value()
1928                    )));
1929                };
1930                for (idx, (field_name, field_node)) in fields.iter().enumerate() {
1931                    let field_v = value.get_field(field_name, Some(idx)).ok_or_else(|| {
1932                        IrDriverError::TypeMismatch(format!(
1933                            "struct {name} missing field '{field_name}'; got keys {:?}",
1934                            obj_fields
1935                                .iter()
1936                                .map(|(k, _)| k.as_ref())
1937                                .collect::<Vec<_>>()
1938                        ))
1939                    })?;
1940                    field_node.encode_vm_val_frs_into(field_v, out)?;
1941                }
1942                Ok(())
1943            }
1944            Self::Tuple(nodes) => {
1945                let arr = value.as_array().ok_or_else(|| {
1946                    IrDriverError::TypeMismatch(format!(
1947                        "expected array for tuple, got {}",
1948                        value.to_runtime_value()
1949                    ))
1950                })?;
1951                if arr.len() != nodes.len() {
1952                    return Err(IrDriverError::TypeMismatch(format!(
1953                        "tuple arity mismatch: expected {}, got {}",
1954                        nodes.len(),
1955                        arr.len()
1956                    )));
1957                }
1958                for (node, v) in nodes.iter().zip(arr.iter()) {
1959                    node.encode_vm_val_frs_into(v, out)?;
1960                }
1961                Ok(())
1962            }
1963            Self::Vector { length, elem } => {
1964                let arr = value.as_array().ok_or_else(|| {
1965                    IrDriverError::TypeMismatch(format!(
1966                        "expected array for vector, got {}",
1967                        value.to_runtime_value()
1968                    ))
1969                })?;
1970                if u32::try_from(arr.len()) != Ok(*length) {
1971                    return Err(IrDriverError::TypeMismatch(format!(
1972                        "vector length mismatch: expected {length}, got {}",
1973                        arr.len()
1974                    )));
1975                }
1976                for v in arr {
1977                    elem.encode_vm_val_frs_into(v, out)?;
1978                }
1979                Ok(())
1980            }
1981            _ => unreachable!("is_pure_field verified"),
1982        }
1983    }
1984}
1985
1986#[cfg(test)]
1987mod tests {
1988    use std::collections::BTreeMap;
1989
1990    use moonproof_runtime_ir::ir::{IntLit, StructField};
1991
1992    use super::*;
1993
1994    fn assert_plan_matches_encode_literal(desc: &TypeDescriptor, val: &Value) {
1995        let plan = FabPlan::compile(desc).expect("descriptor should compile to FabPlan");
1996        let expected = encode_literal(desc, val).expect("encode_literal should succeed");
1997        let actual = plan.encode(val).expect("FabPlan::encode should succeed");
1998        assert_eq!(actual, expected, "FabPlan mismatch for {desc:?} / {val:?}");
1999        let vm_val = VmVal::from_runtime_value(val);
2000        let actual_vm = plan
2001            .encode_vm_val(&vm_val)
2002            .expect("FabPlan::encode_vm_val should succeed");
2003        assert_eq!(
2004            actual_vm, expected,
2005            "FabPlan::encode_vm_val mismatch for {desc:?} / {val:?}"
2006        );
2007        let decoded_expected = decode_aligned_value_full(desc, &expected)
2008            .expect("decode_aligned_value_full should succeed");
2009        let decoded_vm = plan
2010            .decode_to_vm_val(&expected)
2011            .expect("FabPlan::decode_to_vm_val should succeed")
2012            .into_runtime_value();
2013        assert_eq!(
2014            decoded_vm, decoded_expected,
2015            "FabPlan::decode_to_vm_val mismatch for {desc:?}"
2016        );
2017        let mut frs = Vec::new();
2018        if let Some(res) = plan.try_encode_vm_val_frs(&vm_val, &mut frs) {
2019            use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
2020            use moonproof_ledger::transient_crypto::repr::FieldRepr;
2021            res.expect("try_encode_vm_val_frs should succeed");
2022            let expected_frs = ValueReprAlignedValue(expected).field_vec();
2023            assert_eq!(
2024                frs, expected_frs,
2025                "try_encode_vm_val_frs mismatch for {desc:?}"
2026            );
2027        }
2028    }
2029
2030    #[test]
2031    fn fab_plan_matches_encode_literal_for_primitives() {
2032        assert_plan_matches_encode_literal(&TypeDescriptor::Boolean, &Value::Bool(false));
2033        assert_plan_matches_encode_literal(&TypeDescriptor::Boolean, &Value::Bool(true));
2034
2035        for (max, v) in [
2036            (0u128, Value::Int(0)),
2037            (255, Value::Int(0)),
2038            (255, Value::Int(255)),
2039            (65535, Value::Int(256)),
2040            (u128::from(u32::MAX), Value::Int(0x1234_5678)),
2041            (u128::from(u64::MAX), Value::Int(i128::from(u64::MAX))),
2042            (u128::MAX, Value::String(u128::MAX.to_string())),
2043        ] {
2044            assert_plan_matches_encode_literal(
2045                &TypeDescriptor::Uint {
2046                    maxval: IntLit::from_u128(max),
2047                    alignment_bytes: None,
2048                },
2049                &v,
2050            );
2051        }
2052
2053        assert_plan_matches_encode_literal(&TypeDescriptor::Counter, &Value::Int(42));
2054        assert_plan_matches_encode_literal(
2055            &TypeDescriptor::Bytes { length: 32 },
2056            &Value::Bytes(vec![0u8; 32]),
2057        );
2058        assert_plan_matches_encode_literal(
2059            &TypeDescriptor::Bytes { length: 4 },
2060            &Value::Bytes(vec![0xaa, 0xbb, 0, 0]),
2061        );
2062        assert_plan_matches_encode_literal(&TypeDescriptor::Field, &Value::Int(0));
2063        assert_plan_matches_encode_literal(&TypeDescriptor::Field, &Value::Int(123_456));
2064        assert_plan_matches_encode_literal(&TypeDescriptor::Secp256k1Base, &Value::Int(0));
2065        assert_plan_matches_encode_literal(&TypeDescriptor::Curve25519Scalar, &Value::Int(99));
2066        assert_plan_matches_encode_literal(
2067            &TypeDescriptor::Enum {
2068                name: "Color".to_owned(),
2069                elements: vec!["Red".to_owned(), "Green".to_owned(), "Blue".to_owned()],
2070            },
2071            &Value::String("Green".to_owned()),
2072        );
2073        assert_plan_matches_encode_literal(
2074            &TypeDescriptor::Opaque {
2075                ts_type: "string".to_owned(),
2076            },
2077            &Value::String("hello\0\0".to_owned()),
2078        );
2079        assert_plan_matches_encode_literal(
2080            &TypeDescriptor::Opaque {
2081                ts_type: "Uint8Array".to_owned(),
2082            },
2083            &Value::Bytes(vec![1, 2, 0, 0]),
2084        );
2085    }
2086
2087    #[test]
2088    fn fab_plan_matches_encode_literal_for_compounds() {
2089        assert_plan_matches_encode_literal(
2090            &TypeDescriptor::Vector {
2091                length: 0,
2092                elt_type: Box::new(TypeDescriptor::Unknown),
2093            },
2094            &Value::Array(Vec::new()),
2095        );
2096
2097        let compound = TypeDescriptor::Struct {
2098            name: "Envelope".to_owned(),
2099            elements: vec![
2100                StructField {
2101                    name: "flag".to_owned(),
2102                    field_type: TypeDescriptor::Boolean,
2103                },
2104                StructField {
2105                    name: "payload".to_owned(),
2106                    field_type: TypeDescriptor::Tuple {
2107                        types: vec![
2108                            TypeDescriptor::Uint {
2109                                maxval: IntLit::from_u128(255),
2110                                alignment_bytes: None,
2111                            },
2112                            TypeDescriptor::Bytes { length: 32 },
2113                        ],
2114                    },
2115                },
2116                StructField {
2117                    name: "items".to_owned(),
2118                    field_type: TypeDescriptor::Vector {
2119                        length: 2,
2120                        elt_type: Box::new(TypeDescriptor::Field),
2121                    },
2122                },
2123            ],
2124        };
2125        let mut obj = BTreeMap::new();
2126        obj.insert("flag".to_owned(), Value::Bool(true));
2127        obj.insert(
2128            "payload".to_owned(),
2129            Value::Array(vec![Value::Int(7), Value::Bytes(vec![0x5a; 32])]),
2130        );
2131        obj.insert(
2132            "items".to_owned(),
2133            Value::Array(vec![Value::Int(10), Value::Int(20)]),
2134        );
2135        assert_plan_matches_encode_literal(&compound, &Value::Object(obj));
2136    }
2137
2138    #[test]
2139    fn json_as_u128_accepts_int_above_u64_max() {
2140        let signed_input = i128::from(u64::MAX) + 1;
2141        let expected_u128 = u128::from(u64::MAX) + 1;
2142        assert_eq!(
2143            json_as_u128(&Value::Int(signed_input)).unwrap(),
2144            expected_u128
2145        );
2146        assert_eq!(
2147            json_as_u128(&Value::Int(i128::MAX)).unwrap(),
2148            u128::try_from(i128::MAX).unwrap()
2149        );
2150        assert!(json_as_u128(&Value::Int(-1)).is_err());
2151
2152        let u128_ty = TypeDescriptor::Uint {
2153            maxval: IntLit::from_u128(u128::MAX),
2154            alignment_bytes: None,
2155        };
2156        assert_plan_matches_encode_literal(&u128_ty, &Value::Int(signed_input));
2157    }
2158}