moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Encoding for Compact's foreign-field and curve-point types.
//!
//! compactc 0.33 promoted `JubjubScalar`, `Secp256k1Base`,
//! `Secp256k1Scalar`, `JubjubPoint` and `Secp256k1Point` from opaque
//! builtins to standard-library types with their own alignments. The
//! layouts here mirror `compact/runtime/src/compact-types.ts` atom for
//! atom — that file is the reference implementation, and the secp
//! encoding in particular is not guessable:
//!
//! - A secp field element occupies **two** atoms, `bytes:24` holding the
//!   low 192 bits and `bytes:8` the high 64, because it does not fit a
//!   single native field element.
//! - The ZKIR representation stores the value **rotated down by one**:
//!   `0` is written as `modulus - 1`, and every other `v` as `v - 1`.
//!   Decoding rotates back. Skipping the rotation produces values that
//!   are off by one everywhere except at the wrap point, which no
//!   round-trip test through a single implementation would catch.

use ethnum::U256;
use moonproof_ledger::base_crypto::fab::{
    AlignedValue, Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
};
use moonproof_ledger::foreign_curve::{AffinePoint, ForeignCurve};
use moonproof_runtime_ir::ir::FieldType;

use moonproof_runtime_ir::RuntimeValue as Value;

use super::error::{IrDriverError, Result};

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

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

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

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

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

/// Order of the Curve25519 prime-order subgroup
/// (`2^252 + 27742317777372353535851937790883648493`).
pub const CURVE25519_SCALAR_MODULUS: U256 = U256::from_words(
    0x1000_0000_0000_0000_0000_0000_0000_0000,
    0x14DE_F9DE_A2F7_9CD6_5812_631A_5CF5_D3ED,
);

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

/// How a foreign field element splits into its two atoms: the bits
/// the low atom carries, and the byte widths of the low and high atoms.
/// Every foreign field splits at bit 192 (`bytes:24` + `bytes:8`)
/// except Curve25519's scalar field, which compact-runtime packs as
/// five 51-bit limbs and so splits at bit 204 (`bytes:26` + `bytes:7`).
#[derive(Debug, Clone, Copy)]
struct LimbSplit {
    low_bits: u32,
    low_len: u32,
    high_len: u32,
}

const SPLIT_192: LimbSplit = LimbSplit {
    low_bits: 192,
    low_len: 24,
    high_len: 8,
};

const SPLIT_204: LimbSplit = LimbSplit {
    low_bits: 204,
    low_len: 26,
    high_len: 7,
};

/// The two-atom layout of `field_type`, or `None` for the fields that
/// occupy a single native field atom.
fn limb_split(field_type: FieldType) -> Option<LimbSplit> {
    match field_type {
        FieldType::Field | FieldType::JubjubScalar => None,
        FieldType::Curve25519Scalar => Some(SPLIT_204),
        FieldType::Secp256k1Base
        | FieldType::Secp256k1Scalar
        | FieldType::Secp256r1Base
        | FieldType::Secp256r1Scalar
        | FieldType::Curve25519Base => Some(SPLIT_192),
    }
}

/// Maximum representable value of a foreign field, i.e. `modulus - 1`.
fn max_value(modulus: U256) -> U256 {
    modulus - U256::ONE
}

/// Read a `Value` as a `U256`. Accepts the canonical little-endian byte
/// form, an integer, and the decimal-string form arithmetic results
/// promote to once they exceed `u128`.
pub fn value_as_u256(value: &Value, what: &str) -> Result<U256> {
    if let Some(b) = value.as_bytes() {
        if b.len() > 32 {
            return Err(IrDriverError::TypeMismatch(format!(
                "{what} expects at most 32 bytes, got {}",
                b.len()
            )));
        }
        let mut le = [0u8; 32];
        le[..b.len()].copy_from_slice(b);
        return Ok(U256::from_le_bytes(le));
    }
    if let Some(n) = value.as_u128() {
        return Ok(U256::from(n));
    }
    if let Some(s) = value.as_str() {
        let trimmed = s.trim();
        let parsed = if let Some(hex) = trimmed
            .strip_prefix("0x")
            .or_else(|| trimmed.strip_prefix("0X"))
        {
            U256::from_str_radix(hex, 16)
        } else {
            U256::from_str_radix(trimmed, 10)
        };
        return parsed.map_err(|e| {
            IrDriverError::TypeMismatch(format!("{what} string parse failed: {s:?} ({e})"))
        });
    }
    Err(IrDriverError::TypeMismatch(format!(
        "{what} expects bytes, integer or numeric string, got {value}"
    )))
}

/// Build a `Bytes{length}`-aligned atom from the low `length` bytes of
/// `n`, stripping trailing zeros the way `ValueAtom::from([u8; N])`
/// does.
fn limb_atom(n: U256, length: u32) -> (ValueAtom, AlignmentAtom) {
    let le = n.to_le_bytes();
    let mut bytes = le[..length as usize].to_vec();
    while bytes.last() == Some(&0) {
        bytes.pop();
    }
    (ValueAtom(bytes), AlignmentAtom::Bytes { length })
}

/// Encode a two-atom foreign field element, applying the ZKIR
/// rotation. Mirrors compact-runtime's `ForeignField8_24.toValue` and
/// `CompactTypeCurve25519Scalar.toValue`.
fn encode_foreign_field(field_type: FieldType, value: &Value, what: &str) -> Result<AlignedValue> {
    let (Some(modulus), Some(split)) = (modulus_of(field_type), limb_split(field_type)) else {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what}: {field_type:?} is not a two-atom foreign field"
        )));
    };
    let v = value_as_u256(value, what)?;
    let max = max_value(modulus);
    if v > max {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what} value out of range (max {max})"
        )));
    }
    // The ZKIR representation subtracts 1 from the value, wrapping 0 to
    // the maximum.
    let rotated = if v == U256::ZERO { max } else { v - U256::ONE };

    let low = rotated & ((U256::ONE << split.low_bits) - U256::ONE);
    let high = rotated >> split.low_bits;
    let (low_atom, low_align) = limb_atom(low, split.low_len);
    let (high_atom, high_align) = limb_atom(high, split.high_len);

    AlignedValue::new(
        FabValue(vec![low_atom, high_atom]),
        Alignment(vec![
            moonproof_ledger::base_crypto::fab::AlignmentSegment::Atom(low_align),
            moonproof_ledger::base_crypto::fab::AlignmentSegment::Atom(high_align),
        ]),
    )
    .ok_or_else(|| IrDriverError::TypeMismatch(format!("{what} AlignedValue construction failed")))
}

/// Decode a two-atom foreign field element, undoing the ZKIR rotation.
/// Mirrors compact-runtime's `ForeignField8_24.fromValue`.
pub fn decode_foreign_field(
    field_type: FieldType,
    low: &ValueAtom,
    high: &ValueAtom,
    what: &str,
) -> Result<U256> {
    let (Some(modulus), Some(split)) = (modulus_of(field_type), limb_split(field_type)) else {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what}: {field_type:?} is not a two-atom foreign field"
        )));
    };
    let low = atom_to_u256(low);
    let high = atom_to_u256(high);
    if low >= (U256::ONE << split.low_bits) {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what} low limb exceeds {} bits",
            split.low_bits
        )));
    }
    let raw = (high << split.low_bits) | low;
    let max = max_value(modulus);
    let v = if raw == max {
        U256::ZERO
    } else {
        raw + U256::ONE
    };
    if v > max {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what} value out of range (max {max})"
        )));
    }
    Ok(v)
}

/// Interpret a value atom's little-endian bytes as a `U256`.
pub fn atom_to_u256(atom: &ValueAtom) -> U256 {
    let mut le = [0u8; 32];
    let n = atom.0.len().min(32);
    le[..n].copy_from_slice(&atom.0[..n]);
    U256::from_le_bytes(le)
}

/// Encode a value that lives in a native field atom, range-checked
/// against `modulus`. Used for `JubjubScalar`, which shares `Field`'s
/// single-atom layout but not its range.
fn encode_native_field_bounded(modulus: U256, value: &Value, what: &str) -> Result<AlignedValue> {
    let v = value_as_u256(value, what)?;
    let max = max_value(modulus);
    if v > max {
        return Err(IrDriverError::TypeMismatch(format!(
            "{what} value out of range (max {max})"
        )));
    }
    let le = v.to_le_bytes();
    let fr =
        moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(&le).ok_or_else(|| {
            IrDriverError::TypeMismatch(format!("{what} value does not fit the native field"))
        })?;
    Ok(AlignedValue::from(fr))
}

/// Encode a foreign-field literal for `field_type`.
pub fn encode_field_type(field_type: FieldType, value: &Value) -> Result<AlignedValue> {
    match field_type {
        FieldType::Field => super::descriptor::encode_field(value),
        FieldType::JubjubScalar => {
            encode_native_field_bounded(JUBJUB_SCALAR_MODULUS, value, "JubjubScalar")
        }
        other => encode_foreign_field(other, value, &format!("{other:?}")),
    }
}

/// Encode a `JubjubPoint` — two native field atoms, `x` then `y`.
pub fn encode_jubjub_point(value: &Value) -> Result<AlignedValue> {
    let (x, y) = point_xy(value, "JubjubPoint")?;
    let x_av = super::descriptor::encode_field(&x)?;
    let y_av = super::descriptor::encode_field(&y)?;
    Ok(AlignedValue::concat([&x_av, &y_av]))
}

/// Encode a short-Weierstrass point (`Secp256k1Point`,
/// `Secp256r1Point`) — `x` and `y` each as a `base` limb pair, then a
/// native field atom holding the identity flag. The identity writes
/// zero coordinates whatever the value carries, as
/// `CompactTypeSecp256k1Point.toValue` does.
pub fn encode_weierstrass_point(
    base: FieldType,
    value: &Value,
    what: &str,
) -> Result<AlignedValue> {
    let obj = value.as_object().ok_or_else(|| {
        IrDriverError::TypeMismatch(format!("expected object for {what}, got {value}"))
    })?;
    let identity = obj
        .get("identity")
        .ok_or_else(|| IrDriverError::TypeMismatch(format!("{what} missing field 'identity'")))?;
    let is_identity = identity.as_bool().ok_or_else(|| {
        IrDriverError::TypeMismatch(format!(
            "{what} 'identity' must be a boolean, got {identity}"
        ))
    })?;
    let (x, y) = if is_identity {
        (Value::Int(0), Value::Int(0))
    } else {
        point_xy(value, what)?
    };

    let x_av = encode_foreign_field(base, &x, &format!("{what}.x"))?;
    let y_av = encode_foreign_field(base, &y, &format!("{what}.y"))?;
    let flag = moonproof_ledger::transient_crypto::curve::Fr::from(u128::from(is_identity));
    let flag_av = AlignedValue::from(flag);
    Ok(AlignedValue::concat([&x_av, &y_av, &flag_av]))
}

/// Encode a `Curve25519Point` — `x` then `y`, each a `Curve25519Base`
/// limb pair. Edwards coordinates cover the identity, so no flag.
pub fn encode_curve25519_point(value: &Value) -> Result<AlignedValue> {
    let (x, y) = point_xy(value, "Curve25519Point")?;
    let x_av = encode_foreign_field(FieldType::Curve25519Base, &x, "Curve25519Point.x")?;
    let y_av = encode_foreign_field(FieldType::Curve25519Base, &y, "Curve25519Point.y")?;
    Ok(AlignedValue::concat([&x_av, &y_av]))
}

/// Modulus of the field a [`FieldType`] names, or `None` for the
/// native field — whose arithmetic goes through `Fr` directly rather
/// than through an explicit modulus.
#[must_use]
pub fn modulus_of(field_type: FieldType) -> Option<U256> {
    match field_type {
        FieldType::Field => None,
        FieldType::JubjubScalar => Some(JUBJUB_SCALAR_MODULUS),
        FieldType::Secp256k1Base => Some(SECP256K1_BASE_MODULUS),
        FieldType::Secp256k1Scalar => Some(SECP256K1_SCALAR_MODULUS),
        FieldType::Secp256r1Base => Some(SECP256R1_BASE_MODULUS),
        FieldType::Secp256r1Scalar => Some(SECP256R1_SCALAR_MODULUS),
        FieldType::Curve25519Base => Some(CURVE25519_BASE_MODULUS),
        FieldType::Curve25519Scalar => Some(CURVE25519_SCALAR_MODULUS),
    }
}

/// The value `n` becomes when cast into `field_type`.
///
/// Compact defines `x as JubjubScalar` as `x` modulo the scalar field
/// (compact-runtime's `convertNumericToJubjubScalar`), and the circuit
/// reduces the same way, so a native-field value above the scalar
/// modulus is reduced rather than refused. Every other target must
/// already hold the value.
pub fn cast_to_field(field_type: FieldType, n: U256) -> Result<U256> {
    match (field_type, modulus_of(field_type)) {
        (FieldType::JubjubScalar, _) => Ok(n % JUBJUB_SCALAR_MODULUS),
        (_, Some(modulus)) if n >= modulus => Err(IrDriverError::VmOp(format!(
            "cast-to-field: {n} is not a member of {field_type:?}"
        ))),
        _ => Ok(n),
    }
}

/// Modular `+`, `-` and `*` in a foreign field.
///
/// Mirrors `built-ins.ts`'s `addField` / `subField` / `mulField` family:
/// every Compact field operation is modular, never a checked overflow.
/// Computed through `BigUint` so the `*` intermediate has room for the
/// full 512-bit product — a secp modulus sits close enough to `2^256`
/// that a 256-bit multiply would wrap before reduction.
pub fn modular_binop(modulus: U256, op: &str, left: U256, right: U256) -> Result<U256> {
    use num_bigint::BigUint;

    let m = BigUint::from_bytes_le(&modulus.to_le_bytes());
    let l = BigUint::from_bytes_le(&left.to_le_bytes()) % &m;
    let r = BigUint::from_bytes_le(&right.to_le_bytes()) % &m;

    let out = match op {
        "+" => (l + r) % &m,
        // Borrow the modulus rather than going negative: BigUint is
        // unsigned, so `l - r` would panic when r > l.
        "-" => (l + &m - r) % &m,
        "*" => (l * r) % &m,
        other => {
            return Err(IrDriverError::unimplemented(format!(
                "modular binop '{other}' (expected +, - or *)"
            )))
        }
    };

    let mut le = out.to_bytes_le();
    if le.len() > 32 {
        return Err(IrDriverError::TypeMismatch(
            "modular binop result exceeded 32 bytes".into(),
        ));
    }
    le.resize(32, 0);
    let mut buf = [0u8; 32];
    buf.copy_from_slice(&le);
    Ok(U256::from_le_bytes(buf))
}

/// Negation in a foreign field, `modulus - x` (and `0` for `0`).
/// Mirrors compact-runtime's `secp256k1BaseNeg` family.
pub fn field_neg(field_type: FieldType, x: U256) -> Result<U256> {
    let modulus = foreign_modulus(field_type, "neg")?;
    let x = x % modulus;
    Ok(if x == U256::ZERO { x } else { modulus - x })
}

/// Multiplicative inverse in a foreign field, refusing zero as
/// compact-runtime's `secp256k1BaseInv` family does. Every foreign
/// modulus is prime, so the inverse is `x^(modulus - 2)`.
pub fn field_inv(field_type: FieldType, x: U256) -> Result<U256> {
    use num_bigint::BigUint;

    let modulus = foreign_modulus(field_type, "inv")?;
    let m = BigUint::from_bytes_le(&modulus.to_le_bytes());
    let x = BigUint::from_bytes_le(&x.to_le_bytes()) % &m;
    if x == BigUint::ZERO {
        return Err(IrDriverError::VmOp(format!(
            "{field_type:?} has no inverse for 0"
        )));
    }
    let inv = x.modpow(&(&m - 2u32), &m);
    let mut le = inv.to_bytes_le();
    le.resize(32, 0);
    let mut buf = [0u8; 32];
    buf.copy_from_slice(&le);
    Ok(U256::from_le_bytes(buf))
}

fn foreign_modulus(field_type: FieldType, op: &str) -> Result<U256> {
    match (field_type, modulus_of(field_type)) {
        (FieldType::Field | FieldType::JubjubScalar, _) | (_, None) => Err(
            IrDriverError::TypeMismatch(format!("{op}: {field_type:?} is not a foreign field")),
        ),
        (_, Some(m)) => Ok(m),
    }
}

/// A point value as the affine coordinates [`foreign_curve`] takes.
/// A Weierstrass point flagged `identity` is the point at infinity.
///
/// [`foreign_curve`]: moonproof_ledger::foreign_curve
pub fn point_to_affine(curve: ForeignCurve, value: &Value, what: &str) -> Result<AffinePoint> {
    if curve != ForeignCurve::Curve25519 {
        let obj = value.as_object().ok_or_else(|| {
            IrDriverError::TypeMismatch(format!("expected object for {what}, got {value}"))
        })?;
        let identity = obj
            .get("identity")
            .and_then(Value::as_bool)
            .ok_or_else(|| {
                IrDriverError::TypeMismatch(format!("{what} needs a boolean 'identity'"))
            })?;
        if identity {
            return Ok(None);
        }
    }
    let (x, y) = point_xy(value, what)?;
    Ok(Some((
        value_as_u256(&x, what)?.to_le_bytes(),
        value_as_u256(&y, what)?.to_le_bytes(),
    )))
}

/// The point value for affine coordinates, shaped as
/// [`super::descriptor::decode_aligned_value`] shapes a decoded point.
#[must_use]
pub fn affine_to_value(curve: ForeignCurve, point: &AffinePoint) -> Value {
    let (x, y) = point.unwrap_or(([0u8; 32], [0u8; 32]));
    let mut obj = std::collections::BTreeMap::new();
    obj.insert("x".to_owned(), Value::Bytes(x.to_vec()));
    obj.insert("y".to_owned(), Value::Bytes(y.to_vec()));
    if curve != ForeignCurve::Curve25519 {
        obj.insert("identity".to_owned(), Value::Bool(point.is_none()));
    }
    Value::Object(obj)
}

/// The fixed-width byte string compact-runtime's `toBinaryRepr` hashes
/// for `keccak256` and `sha512`: each atom zero-padded to its width,
/// 32 bytes for a field atom and `length` for a bytes atom.
pub fn binary_repr(value: &AlignedValue) -> Result<Vec<u8>> {
    use moonproof_ledger::base_crypto::fab::AlignmentSegment;

    let mut out = Vec::new();
    if value.alignment.0.len() != value.value.0.len() {
        return Err(IrDriverError::TypeMismatch(
            "binary representation: alignment and value disagree in length".into(),
        ));
    }
    for (segment, atom) in value.alignment.0.iter().zip(value.value.0.iter()) {
        let width = match segment {
            AlignmentSegment::Atom(AlignmentAtom::Field) => 32,
            AlignmentSegment::Atom(AlignmentAtom::Bytes { length }) => *length as usize,
            AlignmentSegment::Atom(AlignmentAtom::Compress) => {
                return Err(IrDriverError::TypeMismatch(
                    "cannot take the binary representation of an opaque value".into(),
                ))
            }
            AlignmentSegment::Option(_) => {
                return Err(IrDriverError::TypeMismatch(
                    "binary representation of a non-atom alignment segment".into(),
                ))
            }
        };
        if atom.0.len() > width {
            return Err(IrDriverError::TypeMismatch(format!(
                "binary representation: atom of {} bytes in a {width}-byte slot",
                atom.0.len()
            )));
        }
        out.extend_from_slice(&atom.0);
        out.resize(out.len() + width - atom.0.len(), 0);
    }
    Ok(out)
}

/// Pull the `x` / `y` members out of a point-shaped value.
fn point_xy(value: &Value, what: &str) -> Result<(Value, Value)> {
    let obj = value.as_object().ok_or_else(|| {
        IrDriverError::TypeMismatch(format!("expected object for {what}, got {value}"))
    })?;
    let x = obj
        .get("x")
        .ok_or_else(|| IrDriverError::TypeMismatch(format!("{what} missing field 'x'")))?;
    let y = obj
        .get("y")
        .ok_or_else(|| IrDriverError::TypeMismatch(format!("{what} missing field 'y'")))?;
    Ok((x.clone(), y.clone()))
}

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

    #[test]
    fn jubjub_scalar_cast_reduces_modulo_the_scalar_field() {
        let m = JUBJUB_SCALAR_MODULUS;
        let cast = |n| cast_to_field(FieldType::JubjubScalar, n).unwrap();
        assert_eq!(cast(U256::from(7u8)), U256::from(7u8));
        assert_eq!(cast(m - U256::ONE), m - U256::ONE);
        assert_eq!(cast(m), U256::ZERO);
        assert_eq!(cast(m + U256::from(5u8)), U256::from(5u8));
    }

    #[test]
    fn foreign_field_cast_refuses_an_out_of_range_value() {
        let m = SECP256K1_BASE_MODULUS;
        assert!(cast_to_field(FieldType::Secp256k1Base, m).is_err());
        assert_eq!(
            cast_to_field(FieldType::Secp256k1Base, m - U256::ONE).unwrap(),
            m - U256::ONE
        );
    }

    /// The moduli are transcribed from
    /// `compact/runtime/src/constants.ts`; a typo in any limb would
    /// silently shift every range check, so pin them against the
    /// decimal values upstream documents.
    #[test]
    fn moduli_match_upstream_constants() {
        // 2^256 - 2^32 - 977, expressed as MAX - (2^32 + 976) so the
        // check does not restate the same hex limbs it is verifying.
        assert_eq!(
            SECP256K1_BASE_MODULUS,
            U256::MAX - U256::from((1u128 << 32) + 976),
            "secp256k1 base modulus must equal 2^256 - 2^32 - 977"
        );
        assert_eq!(
            SECP256K1_SCALAR_MODULUS.to_string(),
            "115792089237316195423570985008687907852837564279074904382605163141518161494337"
        );
        assert_eq!(
            JUBJUB_SCALAR_MODULUS.to_string(),
            "6554484396890773809930967563523245729705921265872317281365359162392183254199"
        );
    }

    /// Zero encodes as `modulus - 1` and round-trips back to zero.
    #[test]
    fn secp_rotation_wraps_zero_to_max() {
        let av = encode_foreign_field(FieldType::Secp256k1Base, &Value::Int(0), "Secp256k1Base")
            .unwrap();
        let atoms = &av.value.0;
        assert_eq!(atoms.len(), 2, "secp field occupies two atoms");
        let back = decode_foreign_field(
            FieldType::Secp256k1Base,
            &atoms[0],
            &atoms[1],
            "Secp256k1Base",
        )
        .unwrap();
        assert_eq!(back, U256::ZERO);
    }

    #[test]
    fn secp_round_trips_ordinary_values() {
        for v in [1u128, 2, 1 << 64, u128::from(u64::MAX)] {
            let av = encode_foreign_field(
                FieldType::Secp256k1Scalar,
                &Value::Int(i128::try_from(v).unwrap()),
                "Secp256k1Scalar",
            )
            .unwrap();
            let atoms = &av.value.0;
            let back = decode_foreign_field(
                FieldType::Secp256k1Scalar,
                &atoms[0],
                &atoms[1],
                "Secp256k1Scalar",
            )
            .unwrap();
            assert_eq!(back, U256::from(v), "round trip failed for {v}");
        }
    }

    #[test]
    fn secp_rejects_out_of_range() {
        let too_big = SECP256K1_BASE_MODULUS.to_string();
        let err = encode_foreign_field(
            FieldType::Secp256k1Base,
            &Value::String(too_big),
            "Secp256k1Base",
        );
        assert!(err.is_err(), "modulus itself must not be representable");
    }
}