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};
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,
);
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,
);
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,
);
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,
);
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,
);
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,
);
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,
);
#[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,
};
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),
}
}
fn max_value(modulus: U256) -> U256 {
modulus - U256::ONE
}
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}"
)))
}
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 })
}
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})"
)));
}
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")))
}
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)
}
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)
}
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))
}
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:?}")),
}
}
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]))
}
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]))
}
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]))
}
#[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),
}
}
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),
}
}
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,
"-" => (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))
}
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 })
}
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),
}
}
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(),
)))
}
#[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)
}
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)
}
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
);
}
#[test]
fn moduli_match_upstream_constants() {
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"
);
}
#[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");
}
}