use std::sync::Arc;
use moonproof_ledger::base_crypto::fab::AlignedValue;
use moonproof_runtime_ir::ir::{FieldType, TypeDescriptor};
use moonproof_runtime_ir::RuntimeValue as Value;
use super::error::{IrDriverError, Result};
use super::vm_val::VmVal;
pub fn encode_literal(descriptor: &TypeDescriptor, value: &Value) -> Result<AlignedValue> {
match descriptor {
TypeDescriptor::Uint { maxval, .. } => encode_uint(maxval, value),
TypeDescriptor::Bytes { length } => encode_bytes(*length, value),
TypeDescriptor::Boolean => encode_bool(value),
TypeDescriptor::Field => encode_field(value),
TypeDescriptor::JubjubScalar => {
super::curve::encode_field_type(FieldType::JubjubScalar, value)
}
TypeDescriptor::Secp256k1Base => {
super::curve::encode_field_type(FieldType::Secp256k1Base, value)
}
TypeDescriptor::Secp256k1Scalar => {
super::curve::encode_field_type(FieldType::Secp256k1Scalar, value)
}
TypeDescriptor::Secp256r1Base => {
super::curve::encode_field_type(FieldType::Secp256r1Base, value)
}
TypeDescriptor::Secp256r1Scalar => {
super::curve::encode_field_type(FieldType::Secp256r1Scalar, value)
}
TypeDescriptor::Curve25519Base => {
super::curve::encode_field_type(FieldType::Curve25519Base, value)
}
TypeDescriptor::Curve25519Scalar => {
super::curve::encode_field_type(FieldType::Curve25519Scalar, value)
}
TypeDescriptor::JubjubPoint => super::curve::encode_jubjub_point(value),
TypeDescriptor::Secp256k1Point => super::curve::encode_weierstrass_point(
FieldType::Secp256k1Base,
value,
"Secp256k1Point",
),
TypeDescriptor::Secp256r1Point => super::curve::encode_weierstrass_point(
FieldType::Secp256r1Base,
value,
"Secp256r1Point",
),
TypeDescriptor::Curve25519Point => super::curve::encode_curve25519_point(value),
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => encode_literal(of, value),
TypeDescriptor::Counter => encode_uint(
&moonproof_runtime_ir::ir::IntLit::from_u128(u128::from(u64::MAX)),
value,
),
TypeDescriptor::Struct { elements, name } => encode_struct(name, elements, value),
TypeDescriptor::Tuple { types } => encode_tuple(types, value),
TypeDescriptor::Vector { elt_type, length } => encode_vector(elt_type, *length, value),
TypeDescriptor::Enum { elements, name } => encode_enum(name, elements, value),
TypeDescriptor::Opaque { ts_type } => encode_opaque(ts_type, value),
TypeDescriptor::Contract { .. } => {
encode_literal(&TypeDescriptor::contract_address(), value)
}
TypeDescriptor::Map { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::MerkleTree { .. }
| TypeDescriptor::HistoricMerkleTree { .. }
| TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
"encode_literal not implemented for descriptor {descriptor:?}"
))),
}
}
fn encode_opaque(ts_type: &str, value: &Value) -> Result<AlignedValue> {
match ts_type {
"string" => {
let s = value.as_str().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected string for Opaque<string>, got {value}"
))
})?;
Ok(AlignedValue::from(s.as_bytes().to_vec()))
}
"Uint8Array" => {
let bytes = value.as_bytes().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected Bytes for Opaque<Uint8Array>, got {value}"
))
})?;
Ok(AlignedValue::from(bytes.to_vec()))
}
"JubjubPoint" => {
let obj = value.as_object().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected object for Opaque<JubjubPoint>, got {value}"
))
})?;
let x = obj.get("x").ok_or_else(|| {
IrDriverError::TypeMismatch("Opaque<JubjubPoint> missing field 'x'".into())
})?;
let y = obj.get("y").ok_or_else(|| {
IrDriverError::TypeMismatch("Opaque<JubjubPoint> missing field 'y'".into())
})?;
let x_av = encode_field(x)?;
let y_av = encode_field(y)?;
Ok(AlignedValue::concat([&x_av, &y_av]))
}
other => Err(IrDriverError::unimplemented(format!(
"encode_literal Opaque<{other}>"
))),
}
}
fn encode_struct(
name: &str,
elements: &[moonproof_runtime_ir::ir::StructField],
value: &Value,
) -> Result<AlignedValue> {
let obj = value.as_object().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected object for struct {name}, got {value}"))
})?;
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(elements.len());
for field in elements {
let field_v = obj.get(&field.name).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"struct {name} missing field '{}'; got keys {:?}",
field.name,
obj.keys().collect::<Vec<_>>()
))
})?;
atoms.push(encode_literal(&field.field_type, field_v)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
fn encode_tuple(types: &[TypeDescriptor], value: &Value) -> Result<AlignedValue> {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected array for tuple, got {value}"))
})?;
if arr.len() != types.len() {
return Err(IrDriverError::TypeMismatch(format!(
"tuple arity mismatch: expected {}, got {}",
types.len(),
arr.len()
)));
}
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(types.len());
for (t, v) in types.iter().zip(arr.iter()) {
atoms.push(encode_literal(t, v)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
fn encode_vector(elt_type: &TypeDescriptor, length: u32, value: &Value) -> Result<AlignedValue> {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
})?;
if u32::try_from(arr.len()) != Ok(length) {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected {length}, got {}",
arr.len()
)));
}
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(length as usize);
for v in arr {
atoms.push(encode_literal(elt_type, v)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
fn encode_enum(name: &str, elements: &[String], value: &Value) -> Result<AlignedValue> {
let variant = value.as_str().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected enum-variant string for {name}, got {value}"
))
})?;
let index = elements.iter().position(|v| v == variant).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"enum {name}: variant '{variant}' not in {elements:?}"
))
})?;
let index_u8 = u8::try_from(index).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"enum {name} variant index {index} exceeds u8 — wire encoding assumes ≤256 variants"
))
})?;
Ok(AlignedValue::from(index_u8))
}
pub fn encode_default(descriptor: &TypeDescriptor) -> Result<AlignedValue> {
match descriptor {
TypeDescriptor::Boolean => Ok(AlignedValue::from(false)),
TypeDescriptor::Uint { maxval, .. } => encode_uint(maxval, &Value::Int(0)),
TypeDescriptor::Counter => Ok(AlignedValue::from(0u64)),
TypeDescriptor::Bytes { length } => {
encode_bytes(*length, &Value::Bytes(vec![0u8; *length as usize]))
}
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => encode_default(of),
TypeDescriptor::Struct { elements, .. } => {
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(elements.len());
for field in elements {
atoms.push(encode_default(&field.field_type)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
TypeDescriptor::Tuple { types } => {
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(types.len());
for t in types {
atoms.push(encode_default(t)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
TypeDescriptor::Vector { elt_type, length } => {
let mut atoms: Vec<AlignedValue> = Vec::with_capacity(*length as usize);
for _ in 0..*length {
atoms.push(encode_default(elt_type)?);
}
Ok(AlignedValue::concat(atoms.iter()))
}
TypeDescriptor::Enum { .. } => Ok(AlignedValue::from(0u8)),
TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
"string" | "Uint8Array" => Ok(AlignedValue::from(Vec::<u8>::new())),
"JubjubPoint" => encode_default(&TypeDescriptor::JubjubPoint),
other => Err(IrDriverError::unimplemented(format!(
"encode_default for Opaque<{other}>"
))),
},
TypeDescriptor::Field => encode_field(&Value::Int(0)),
TypeDescriptor::JubjubScalar
| TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base
| TypeDescriptor::Curve25519Scalar => encode_literal(descriptor, &Value::Int(0)),
TypeDescriptor::JubjubPoint => {
let x = encode_field(&Value::Int(0))?;
let y = encode_field(&Value::Int(1))?;
Ok(AlignedValue::concat([&x, &y]))
}
TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), Value::Int(0));
obj.insert("y".to_owned(), Value::Int(0));
obj.insert("identity".to_owned(), Value::Bool(true));
encode_literal(descriptor, &Value::Object(obj))
}
TypeDescriptor::Curve25519Point => {
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), Value::Int(0));
obj.insert("y".to_owned(), Value::Int(1));
super::curve::encode_curve25519_point(&Value::Object(obj))
}
TypeDescriptor::Contract { .. } => encode_default(&TypeDescriptor::contract_address()),
TypeDescriptor::Map { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::MerkleTree { .. }
| TypeDescriptor::HistoricMerkleTree { .. }
| TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
"encode_default for descriptor {descriptor:?} (container types have no flat default)"
))),
}
}
pub fn encode_uint(
maxval: &moonproof_runtime_ir::ir::IntLit,
value: &Value,
) -> Result<AlignedValue> {
let max = maxval
.as_u128()
.ok_or_else(|| IrDriverError::TypeMismatch(format!("Uint maxval {maxval} out of u128")))?;
let v = json_as_u128(value)?;
let exceeds = || IrDriverError::TypeMismatch(format!("value {v} exceeds Uint maxval {max}"));
if v > max {
return Err(exceeds());
}
if max <= u128::from(u8::MAX) {
Ok(AlignedValue::from(u8::try_from(v).map_err(|_| exceeds())?))
} else if max <= u128::from(u16::MAX) {
Ok(AlignedValue::from(u16::try_from(v).map_err(|_| exceeds())?))
} else if max <= u128::from(u32::MAX) {
Ok(AlignedValue::from(u32::try_from(v).map_err(|_| exceeds())?))
} else if max <= u128::from(u64::MAX) {
Ok(AlignedValue::from(u64::try_from(v).map_err(|_| exceeds())?))
} else {
Ok(AlignedValue::from(v))
}
}
pub fn encode_field(value: &Value) -> Result<AlignedValue> {
let fr = if let Some(b) = value.as_bytes() {
moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(b).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"Field value out of range: {} bytes does not fit in Fr",
b.len()
))
})?
} else if let Some(n) = value.as_u128() {
moonproof_ledger::transient_crypto::curve::Fr::from(n)
} else if let Some(s) = value.as_str() {
let n: u128 = s.parse().map_err(|e| {
IrDriverError::TypeMismatch(format!("Field decimal-string parse failed: '{s}' ({e})"))
})?;
moonproof_ledger::transient_crypto::curve::Fr::from(n)
} else {
return Err(IrDriverError::TypeMismatch(format!(
"Field expects bytes or numeric, got {value}"
)));
};
Ok(AlignedValue::from(fr))
}
pub fn encode_bytes(length: u32, value: &Value) -> Result<AlignedValue> {
let owned: Vec<u8>;
let bytes: &[u8] = if let Some(b) = value.as_bytes() {
b
} else if let Some(s) = value.as_str() {
let trimmed = s
.strip_prefix("0x")
.or_else(|| s.strip_prefix("0X"))
.unwrap_or(s);
owned = hex::decode(trimmed).map_err(|e| {
IrDriverError::TypeMismatch(format!(
"Bytes<{length}> string is not valid hex: {s:?} ({e})"
))
})?;
owned.as_slice()
} else {
return Err(IrDriverError::TypeMismatch(format!(
"expected Bytes for Bytes<{length}>, got {value}"
)));
};
if bytes.len() != length as usize {
return Err(IrDriverError::TypeMismatch(format!(
"Bytes<{length}> received {} bytes",
bytes.len()
)));
}
bytes_aligned_value(length, bytes)
}
fn bytes_aligned_value(length: u32, bytes: &[u8]) -> Result<AlignedValue> {
use moonproof_ledger::base_crypto::fab::{
Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
};
let mut atom_bytes = bytes.to_vec();
while atom_bytes.last() == Some(&0) {
atom_bytes.pop();
}
let value = FabValue(vec![ValueAtom(atom_bytes)]);
let alignment = Alignment::singleton(AlignmentAtom::Bytes { length });
AlignedValue::new(value, alignment).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"Bytes<{length}> AlignedValue construction failed (alignment/value mismatch)"
))
})
}
pub fn encode_bool(value: &Value) -> Result<AlignedValue> {
let b = value
.as_bool()
.ok_or_else(|| IrDriverError::TypeMismatch(format!("expected bool, got {value}")))?;
Ok(AlignedValue::from(b))
}
pub fn decode_aligned_value(
descriptor: &TypeDescriptor,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<Value> {
match descriptor {
TypeDescriptor::Boolean => {
let atom = consume(atoms, cursor, descriptor)?;
let n = u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("bool atom decode: {e:?}")))?;
Ok(Value::Bool(n != 0))
}
TypeDescriptor::Uint { maxval, .. } => {
let atom = consume(atoms, cursor, descriptor)?;
decode_uint(maxval, atom)
}
TypeDescriptor::Counter => {
let atom = consume(atoms, cursor, descriptor)?;
let n = u64::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("counter→u64 decode: {e:?}")))?;
Ok(Value::Int(i128::from(n)))
}
TypeDescriptor::Bytes { length } => {
let atom = consume(atoms, cursor, descriptor)?;
let mut buf = atom.0.clone();
buf.resize(*length as usize, 0);
Ok(Value::Bytes(buf))
}
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
decode_aligned_value(of, atoms, cursor)
}
TypeDescriptor::Struct { elements, .. } => {
let mut obj = std::collections::BTreeMap::<String, Value>::new();
for field in elements {
let v = decode_aligned_value(&field.field_type, atoms, cursor)?;
obj.insert(field.name.clone(), v);
}
Ok(Value::Object(obj))
}
TypeDescriptor::Tuple { types } => {
if types.is_empty() {
return Ok(Value::Array(Vec::new()));
}
let mut arr = Vec::with_capacity(types.len());
for t in types {
arr.push(decode_aligned_value(t, atoms, cursor)?);
}
Ok(Value::Array(arr))
}
TypeDescriptor::Vector { elt_type, length } => {
let mut arr = Vec::with_capacity(*length as usize);
for _ in 0..*length {
arr.push(decode_aligned_value(elt_type, atoms, cursor)?);
}
Ok(Value::Array(arr))
}
TypeDescriptor::Enum { elements, name } => {
let atom = consume(atoms, cursor, descriptor)?;
decode_enum(name, elements, atom)
}
TypeDescriptor::Opaque { ts_type } => decode_opaque(ts_type, descriptor, atoms, cursor),
TypeDescriptor::Field | TypeDescriptor::JubjubScalar => {
let atom = consume(atoms, cursor, descriptor)?;
let mut buf = atom.0.clone();
buf.resize(32, 0);
Ok(Value::Bytes(buf))
}
TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base
| TypeDescriptor::Curve25519Scalar => decode_foreign_field(descriptor, atoms, cursor),
TypeDescriptor::JubjubPoint
| TypeDescriptor::Curve25519Point
| TypeDescriptor::Secp256k1Point
| TypeDescriptor::Secp256r1Point => decode_point(descriptor, atoms, cursor),
TypeDescriptor::Contract { .. } => {
decode_aligned_value(&TypeDescriptor::contract_address(), atoms, cursor)
}
TypeDescriptor::Map { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::MerkleTree { .. }
| TypeDescriptor::HistoricMerkleTree { .. }
| TypeDescriptor::Unknown => Err(IrDriverError::unimplemented(format!(
"decode_aligned_value for descriptor {descriptor:?}"
))),
}
}
fn decode_uint(
maxval: &moonproof_runtime_ir::ir::IntLit,
atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
) -> Result<Value> {
let max = maxval
.as_u128()
.ok_or_else(|| IrDriverError::TypeMismatch(format!("Uint maxval out of u128: {maxval}")))?;
let n: u128 = if max <= u128::from(u8::MAX) {
u128::from(
u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u8 decode: {e:?}")))?,
)
} else if max <= u128::from(u16::MAX) {
u128::from(
u16::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u16 decode: {e:?}")))?,
)
} else if max <= u128::from(u32::MAX) {
u128::from(
u32::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u32 decode: {e:?}")))?,
)
} else if max <= u128::from(u64::MAX) {
u128::from(
u64::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u64 decode: {e:?}")))?,
)
} else {
u128::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u128 decode: {e:?}")))?
};
match u64::try_from(n) {
Ok(n) => Ok(Value::Int(i128::from(n))),
Err(_) => Ok(Value::String(n.to_string())),
}
}
fn decode_enum(
name: &str,
elements: &[String],
atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
) -> Result<Value> {
let idx = u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("enum→u8 decode: {e:?}")))?;
elements
.get(usize::from(idx))
.map(|s| Value::String(s.clone()))
.ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"enum {name}: index {idx} out of range (variants: {elements:?})"
))
})
}
fn decode_foreign_field(
descriptor: &TypeDescriptor,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<Value> {
let field_type = FieldType::of_descriptor(descriptor).ok_or_else(|| {
IrDriverError::TypeMismatch(format!("{descriptor:?} is not a foreign field"))
})?;
let low = consume(atoms, cursor, descriptor)?.clone();
let high = consume(atoms, cursor, descriptor)?.clone();
let v =
super::curve::decode_foreign_field(field_type, &low, &high, &format!("{field_type:?}"))?;
Ok(Value::Bytes(v.to_le_bytes().to_vec()))
}
fn decode_opaque(
ts_type: &str,
descriptor: &TypeDescriptor,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<Value> {
match ts_type {
"string" => {
let atom = consume(atoms, cursor, descriptor)?;
let s = std::str::from_utf8(&atom.0).map_err(|e| {
IrDriverError::TypeMismatch(format!("Opaque<string> not valid UTF-8: {e}"))
})?;
Ok(Value::String(s.to_owned()))
}
"Uint8Array" => {
let atom = consume(atoms, cursor, descriptor)?;
Ok(Value::Bytes(atom.0.clone()))
}
"JubjubPoint" => {
let x_atom = consume(atoms, cursor, descriptor)?;
let y_atom = consume(atoms, cursor, descriptor)?;
let mut x_buf = x_atom.0.clone();
x_buf.resize(32, 0);
let mut y_buf = y_atom.0.clone();
y_buf.resize(32, 0);
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), Value::Bytes(x_buf));
obj.insert("y".to_owned(), Value::Bytes(y_buf));
Ok(Value::Object(obj))
}
other => Err(IrDriverError::unimplemented(format!(
"decode_aligned_value Opaque<{other}>"
))),
}
}
fn decode_point(
descriptor: &TypeDescriptor,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<Value> {
match descriptor {
TypeDescriptor::JubjubPoint => {
let x = decode_aligned_value(&TypeDescriptor::Field, atoms, cursor)?;
let y = decode_aligned_value(&TypeDescriptor::Field, atoms, cursor)?;
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), x);
obj.insert("y".to_owned(), y);
Ok(Value::Object(obj))
}
TypeDescriptor::Curve25519Point => {
let x = decode_aligned_value(&TypeDescriptor::Curve25519Base, atoms, cursor)?;
let y = decode_aligned_value(&TypeDescriptor::Curve25519Base, atoms, cursor)?;
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), x);
obj.insert("y".to_owned(), y);
Ok(Value::Object(obj))
}
TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
let base = if matches!(descriptor, TypeDescriptor::Secp256k1Point) {
TypeDescriptor::Secp256k1Base
} else {
TypeDescriptor::Secp256r1Base
};
let x = decode_aligned_value(&base, atoms, cursor)?;
let y = decode_aligned_value(&base, atoms, cursor)?;
let flag = consume(atoms, cursor, descriptor)?;
let identity = u8::try_from(flag).map_err(|e| {
IrDriverError::TypeMismatch(format!("{descriptor:?} identity decode: {e:?}"))
})? != 0;
let mut obj = std::collections::BTreeMap::new();
obj.insert("x".to_owned(), x);
obj.insert("y".to_owned(), y);
obj.insert("identity".to_owned(), Value::Bool(identity));
Ok(Value::Object(obj))
}
_ => Err(IrDriverError::TypeMismatch(format!(
"{descriptor:?} is not a curve point"
))),
}
}
fn consume<'a>(
atoms: &'a [moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
descriptor: &TypeDescriptor,
) -> Result<&'a moonproof_ledger::base_crypto::fab::ValueAtom> {
let atom = atoms.get(*cursor).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"AlignedValue ran out of atoms decoding {descriptor:?} (cursor={}, atoms={})",
*cursor,
atoms.len()
))
})?;
*cursor += 1;
Ok(atom)
}
pub fn decode_aligned_value_full(
descriptor: &TypeDescriptor,
av: &moonproof_ledger::base_crypto::fab::AlignedValue,
) -> Result<Value> {
let mut cursor = 0;
let v = decode_aligned_value(descriptor, &av.value.0, &mut cursor)?;
if cursor != av.value.0.len() {
return Err(IrDriverError::TypeMismatch(format!(
"AlignedValue had {} atoms but descriptor consumed {cursor}",
av.value.0.len()
)));
}
Ok(v)
}
pub fn json_as_u128(value: &Value) -> Result<u128> {
if let Some(n) = value.as_u128() {
return Ok(n);
}
if let Some(s) = value.as_str() {
return s
.parse()
.map_err(|e| IrDriverError::TypeMismatch(format!("not a u128: {s} ({e})")));
}
Err(IrDriverError::TypeMismatch(format!(
"expected u128-shaped value, got {value}"
)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UintWidth {
U8,
U16,
U32,
U64,
U128,
}
impl UintWidth {
const fn byte_len(self) -> u32 {
match self {
Self::U8 => 1,
Self::U16 => 2,
Self::U32 => 4,
Self::U64 => 8,
Self::U128 => 16,
}
}
}
#[derive(Debug, Clone)]
enum FabNode {
Bool,
Uint {
max: u128,
width: UintWidth,
},
Bytes {
length: u32,
},
Field,
ForeignField(FieldType),
JubjubPoint,
WeierstrassPoint {
base: FieldType,
name: &'static str,
},
Curve25519Point,
Enum {
name: String,
elements: Vec<Arc<str>>,
},
OpaqueString,
OpaqueBytes,
OpaqueJubjubPoint,
Struct {
name: String,
fields: Vec<(Arc<str>, FabNode)>,
},
Tuple(Vec<FabNode>),
Vector {
length: u32,
elem: Box<FabNode>,
},
EmptyVector,
}
#[derive(Debug, Clone)]
pub struct FabPlan {
alignment: moonproof_ledger::base_crypto::fab::Alignment,
root: FabNode,
all_field_atoms: bool,
}
#[derive(Debug, Clone)]
pub struct CircuitInputPlan {
alignment: moonproof_ledger::base_crypto::fab::Alignment,
args: Vec<(String, FabNode)>,
}
impl FabPlan {
#[must_use]
pub fn compile(descriptor: &TypeDescriptor) -> Option<Self> {
let mut segments = Vec::new();
let root = compile_fab_node(descriptor, &mut segments)?;
let all_field_atoms = !segments.is_empty() && root.is_pure_field();
Some(Self {
alignment: moonproof_ledger::base_crypto::fab::Alignment(segments),
root,
all_field_atoms,
})
}
#[must_use]
pub fn alignment(&self) -> &moonproof_ledger::base_crypto::fab::Alignment {
&self.alignment
}
#[must_use]
pub fn max_aligned_size(&self) -> usize {
use moonproof_ledger::transient_crypto::fab::AlignmentExt;
self.alignment.max_aligned_size()
}
pub fn encode(&self, value: &Value) -> Result<AlignedValue> {
use moonproof_ledger::base_crypto::fab::Value as FabValue;
let mut atoms = Vec::with_capacity(self.alignment.0.len());
self.root.encode_into(value, &mut atoms)?;
AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
IrDriverError::TypeMismatch(
"FabPlan AlignedValue construction failed (alignment/value mismatch)".into(),
)
})
}
pub(crate) fn encode_vm_val(&self, value: &VmVal) -> Result<AlignedValue> {
use moonproof_ledger::base_crypto::fab::Value as FabValue;
let mut atoms = Vec::with_capacity(self.alignment.0.len());
self.root.encode_vm_val_into(value, &mut atoms)?;
AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
IrDriverError::TypeMismatch(
"FabPlan AlignedValue construction failed (alignment/value mismatch)".into(),
)
})
}
pub(crate) fn decode_to_vm_val(&self, av: &AlignedValue) -> Result<VmVal> {
let mut cursor = 0;
let val = self.root.decode_vm_val(&av.value.0, &mut cursor)?;
if cursor != av.value.0.len() {
return Err(IrDriverError::TypeMismatch(format!(
"AlignedValue had {} atoms but FabPlan consumed {cursor}",
av.value.0.len()
)));
}
Ok(val)
}
pub(crate) fn try_encode_vm_val_frs(
&self,
value: &VmVal,
out: &mut Vec<moonproof_ledger::transient_crypto::curve::Fr>,
) -> Option<Result<()>> {
if !self.all_field_atoms {
return None;
}
out.reserve(self.alignment.0.len());
Some(self.root.encode_vm_val_frs_into(value, out))
}
}
impl CircuitInputPlan {
#[must_use]
pub fn compile(arguments: &[moonproof_runtime_ir::ir::Argument]) -> Option<Self> {
let mut segments = Vec::new();
let mut args = Vec::with_capacity(arguments.len());
for arg in arguments {
let node = compile_fab_node(&arg.arg_type, &mut segments)?;
args.push((arg.name.clone(), node));
}
Some(Self {
alignment: moonproof_ledger::base_crypto::fab::Alignment(segments),
args,
})
}
pub fn encode<S: std::hash::BuildHasher>(
&self,
circuit_name: &str,
arg_values: &std::collections::HashMap<String, Value, S>,
) -> Result<AlignedValue> {
use moonproof_ledger::base_crypto::fab::Value as FabValue;
if self.args.is_empty() {
return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
}
let mut atoms = Vec::with_capacity(self.alignment.0.len());
for (name, node) in &self.args {
let v = arg_values
.get(name)
.ok_or_else(|| IrDriverError::ArgCount {
context: format!("circuit '{circuit_name}' arg '{name}'"),
expected: self.args.len(),
got: arg_values.len(),
})?;
node.encode_into(v, &mut atoms)?;
}
AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"circuit '{circuit_name}' input AlignedValue construction failed"
))
})
}
pub(crate) fn encode_vm_vals(
&self,
circuit_name: &str,
arg_values: &[VmVal],
) -> Result<AlignedValue> {
use moonproof_ledger::base_crypto::fab::Value as FabValue;
if self.args.is_empty() {
return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
}
if arg_values.len() != self.args.len() {
return Err(IrDriverError::ArgCount {
context: format!("circuit '{circuit_name}'"),
expected: self.args.len(),
got: arg_values.len(),
});
}
let mut atoms = Vec::with_capacity(self.alignment.0.len());
for ((_, node), v) in self.args.iter().zip(arg_values.iter()) {
node.encode_vm_val_into(v, &mut atoms)?;
}
AlignedValue::new(FabValue(atoms), self.alignment.clone()).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"circuit '{circuit_name}' input AlignedValue construction failed"
))
})
}
}
fn compile_curve_fab_node(
descriptor: &TypeDescriptor,
segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
) -> Option<FabNode> {
use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
let push_atom = |segs: &mut Vec<AlignmentSegment>, atom: AlignmentAtom| {
segs.push(AlignmentSegment::Atom(atom));
};
let push_split = |segs: &mut Vec<AlignmentSegment>, lo: u32, hi: u32| {
push_atom(segs, AlignmentAtom::Bytes { length: lo });
push_atom(segs, AlignmentAtom::Bytes { length: hi });
};
match descriptor {
TypeDescriptor::JubjubScalar => {
push_atom(segments, AlignmentAtom::Field);
Some(FabNode::ForeignField(FieldType::JubjubScalar))
}
TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base => {
let ft = FieldType::of_descriptor(descriptor)?;
push_split(segments, 24, 8);
Some(FabNode::ForeignField(ft))
}
TypeDescriptor::Curve25519Scalar => {
push_split(segments, 26, 7);
Some(FabNode::ForeignField(FieldType::Curve25519Scalar))
}
TypeDescriptor::JubjubPoint => {
push_atom(segments, AlignmentAtom::Field);
push_atom(segments, AlignmentAtom::Field);
Some(FabNode::JubjubPoint)
}
TypeDescriptor::Secp256k1Point => {
push_split(segments, 24, 8);
push_split(segments, 24, 8);
push_atom(segments, AlignmentAtom::Field);
Some(FabNode::WeierstrassPoint {
base: FieldType::Secp256k1Base,
name: "Secp256k1Point",
})
}
TypeDescriptor::Secp256r1Point => {
push_split(segments, 24, 8);
push_split(segments, 24, 8);
push_atom(segments, AlignmentAtom::Field);
Some(FabNode::WeierstrassPoint {
base: FieldType::Secp256r1Base,
name: "Secp256r1Point",
})
}
TypeDescriptor::Curve25519Point => {
push_split(segments, 24, 8);
push_split(segments, 24, 8);
Some(FabNode::Curve25519Point)
}
_ => None,
}
}
fn compile_compound_fab_node(
descriptor: &TypeDescriptor,
segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
) -> Option<FabNode> {
use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
match descriptor {
TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
"string" => {
segments.push(AlignmentSegment::Atom(AlignmentAtom::Compress));
Some(FabNode::OpaqueString)
}
"Uint8Array" => {
segments.push(AlignmentSegment::Atom(AlignmentAtom::Compress));
Some(FabNode::OpaqueBytes)
}
"JubjubPoint" => {
segments.push(AlignmentSegment::Atom(AlignmentAtom::Field));
segments.push(AlignmentSegment::Atom(AlignmentAtom::Field));
Some(FabNode::OpaqueJubjubPoint)
}
_ => None,
},
TypeDescriptor::Struct { name, elements } => {
let mut fields = Vec::with_capacity(elements.len());
for field in elements {
let node = compile_fab_node(&field.field_type, segments)?;
fields.push((Arc::from(field.name.as_str()), node));
}
Some(FabNode::Struct {
name: name.clone(),
fields,
})
}
TypeDescriptor::Tuple { types } => {
let mut nodes = Vec::with_capacity(types.len());
for ty in types {
nodes.push(compile_fab_node(ty, segments)?);
}
Some(FabNode::Tuple(nodes))
}
TypeDescriptor::Vector { length, elt_type } => {
if *length == 0 {
return Some(FabNode::EmptyVector);
}
let mut elem_segs = Vec::new();
let elem = compile_fab_node(elt_type, &mut elem_segs)?;
let count = usize::try_from(*length).ok()?;
segments.reserve(elem_segs.len().checked_mul(count)?);
for _ in 0..count {
segments.extend_from_slice(&elem_segs);
}
Some(FabNode::Vector {
length: *length,
elem: Box::new(elem),
})
}
_ => None,
}
}
fn compile_fab_node(
descriptor: &TypeDescriptor,
segments: &mut Vec<moonproof_ledger::base_crypto::fab::AlignmentSegment>,
) -> Option<FabNode> {
use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};
let push_atom = |segs: &mut Vec<AlignmentSegment>, atom: AlignmentAtom| {
segs.push(AlignmentSegment::Atom(atom));
};
match descriptor {
TypeDescriptor::Boolean => {
push_atom(segments, AlignmentAtom::Bytes { length: 1 });
Some(FabNode::Bool)
}
TypeDescriptor::Uint { maxval, .. } => {
let max = maxval.as_u128()?;
let width = if max <= u128::from(u8::MAX) {
UintWidth::U8
} else if max <= u128::from(u16::MAX) {
UintWidth::U16
} else if max <= u128::from(u32::MAX) {
UintWidth::U32
} else if max <= u128::from(u64::MAX) {
UintWidth::U64
} else {
UintWidth::U128
};
push_atom(
segments,
AlignmentAtom::Bytes {
length: width.byte_len(),
},
);
Some(FabNode::Uint { max, width })
}
TypeDescriptor::Counter => {
push_atom(segments, AlignmentAtom::Bytes { length: 8 });
Some(FabNode::Uint {
max: u128::from(u64::MAX),
width: UintWidth::U64,
})
}
TypeDescriptor::Bytes { length } => {
push_atom(segments, AlignmentAtom::Bytes { length: *length });
Some(FabNode::Bytes { length: *length })
}
TypeDescriptor::Field => {
push_atom(segments, AlignmentAtom::Field);
Some(FabNode::Field)
}
TypeDescriptor::JubjubScalar
| TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base
| TypeDescriptor::Curve25519Scalar
| TypeDescriptor::JubjubPoint
| TypeDescriptor::Secp256k1Point
| TypeDescriptor::Secp256r1Point
| TypeDescriptor::Curve25519Point => compile_curve_fab_node(descriptor, segments),
TypeDescriptor::Enum { name, elements } => {
push_atom(segments, AlignmentAtom::Bytes { length: 1 });
Some(FabNode::Enum {
name: name.clone(),
elements: elements.iter().map(|s| Arc::from(s.as_str())).collect(),
})
}
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
compile_fab_node(of, segments)
}
TypeDescriptor::Contract { .. } => {
compile_fab_node(&TypeDescriptor::contract_address(), segments)
}
TypeDescriptor::Opaque { .. }
| TypeDescriptor::Struct { .. }
| TypeDescriptor::Tuple { .. }
| TypeDescriptor::Vector { .. } => compile_compound_fab_node(descriptor, segments),
TypeDescriptor::Map { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::MerkleTree { .. }
| TypeDescriptor::HistoricMerkleTree { .. }
| TypeDescriptor::Unknown => None,
}
}
fn push_le_trimmed(bytes: &[u8], atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>) {
let mut end = bytes.len();
while end > 0 && bytes[end - 1] == 0 {
end -= 1;
}
atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(
bytes[..end].to_vec(),
));
}
fn encode_bytes_into(
length: u32,
value: &Value,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
let owned: Vec<u8>;
let bytes: &[u8] = if let Some(b) = value.as_bytes() {
b
} else if let Some(s) = value.as_str() {
let trimmed = s
.strip_prefix("0x")
.or_else(|| s.strip_prefix("0X"))
.unwrap_or(s);
owned = hex::decode(trimmed).map_err(|e| {
IrDriverError::TypeMismatch(format!(
"Bytes<{length}> string is not valid hex: {s:?} ({e})"
))
})?;
owned.as_slice()
} else {
return Err(IrDriverError::TypeMismatch(format!(
"expected Bytes for Bytes<{length}>, got {value}"
)));
};
if bytes.len() != length as usize {
return Err(IrDriverError::TypeMismatch(format!(
"Bytes<{length}> received {} bytes",
bytes.len()
)));
}
push_le_trimmed(bytes, atoms);
Ok(())
}
fn encode_enum_names(name: &str, elements: &[Arc<str>], variant: &str) -> Result<u8> {
let index = elements
.iter()
.position(|v| v.as_ref() == variant)
.ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"enum {name}: variant '{variant}' not in {elements:?}"
))
})?;
u8::try_from(index).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"enum {name} variant index {index} exceeds u8 — wire encoding assumes ≤256 variants"
))
})
}
fn encode_vm_bytes_into(
length: u32,
value: &VmVal,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
let owned: Vec<u8>;
let bytes: &[u8] = if let Some(b) = value.as_bytes() {
b
} else if let Some(s) = value.as_str() {
let trimmed = s
.strip_prefix("0x")
.or_else(|| s.strip_prefix("0X"))
.unwrap_or(s);
owned = hex::decode(trimmed).map_err(|e| {
IrDriverError::TypeMismatch(format!(
"Bytes<{length}> string is not valid hex: {s:?} ({e})"
))
})?;
owned.as_slice()
} else {
return Err(IrDriverError::TypeMismatch(format!(
"expected Bytes for Bytes<{length}>, got {}",
value.to_runtime_value()
)));
};
if bytes.len() != length as usize {
return Err(IrDriverError::TypeMismatch(format!(
"Bytes<{length}> received {} bytes",
bytes.len()
)));
}
push_le_trimmed(bytes, atoms);
Ok(())
}
fn encode_vm_field_into(
value: &VmVal,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
use moonproof_ledger::transient_crypto::curve::Fr;
let fr = if let Some(b) = value.as_bytes() {
Fr::from_le_bytes(b).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"Field value out of range: {} bytes does not fit in Fr",
b.len()
))
})?
} else if let Some(n) = value.as_u128() {
Fr::from(n)
} else if let Some(s) = value.as_str() {
let n: u128 = s.parse().map_err(|e| {
IrDriverError::TypeMismatch(format!("Field decimal-string parse failed: '{s}' ({e})"))
})?;
Fr::from(n)
} else {
return Err(IrDriverError::TypeMismatch(format!(
"Field expects bytes or numeric, got {}",
value.to_runtime_value()
)));
};
push_le_trimmed(&fr.as_le_bytes(), atoms);
Ok(())
}
fn consume_fab_atom<'a>(
atoms: &'a [moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
what: &str,
) -> Result<&'a moonproof_ledger::base_crypto::fab::ValueAtom> {
let atom = atoms.get(*cursor).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"AlignedValue ran out of atoms decoding {what} (cursor={}, atoms={})",
*cursor,
atoms.len()
))
})?;
*cursor += 1;
Ok(atom)
}
fn decode_atom_bytes32(atom: &moonproof_ledger::base_crypto::fab::ValueAtom) -> VmVal {
let mut buf = [0u8; 32];
let n = atom.0.len().min(32);
buf[..n].copy_from_slice(&atom.0[..n]);
VmVal::Bytes32(buf)
}
fn decode_vm_uint(
width: UintWidth,
atom: &moonproof_ledger::base_crypto::fab::ValueAtom,
) -> Result<VmVal> {
let n: u128 = match width {
UintWidth::U8 => u128::from(
u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u8 decode: {e:?}")))?,
),
UintWidth::U16 => u128::from(
u16::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u16 decode: {e:?}")))?,
),
UintWidth::U32 => u128::from(
u32::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u32 decode: {e:?}")))?,
),
UintWidth::U64 => u128::from(
u64::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u64 decode: {e:?}")))?,
),
UintWidth::U128 => u128::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("uint→u128 decode: {e:?}")))?,
};
Ok(VmVal::from_uint(n))
}
impl FabNode {
fn encode_compound_into(
&self,
value: &Value,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
match self {
Self::Struct { name, fields } => {
let obj = value.as_object().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected object for struct {name}, got {value}"
))
})?;
for (field_name, field_node) in fields {
let field_v = obj.get(field_name.as_ref()).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"struct {name} missing field '{field_name}'; got keys {:?}",
obj.keys().collect::<Vec<_>>()
))
})?;
field_node.encode_into(field_v, atoms)?;
}
Ok(())
}
Self::Tuple(nodes) => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected array for tuple, got {value}"))
})?;
if arr.len() != nodes.len() {
return Err(IrDriverError::TypeMismatch(format!(
"tuple arity mismatch: expected {}, got {}",
nodes.len(),
arr.len()
)));
}
for (node, v) in nodes.iter().zip(arr.iter()) {
node.encode_into(v, atoms)?;
}
Ok(())
}
Self::Vector { length, elem } => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
})?;
if u32::try_from(arr.len()) != Ok(*length) {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected {length}, got {}",
arr.len()
)));
}
for v in arr {
elem.encode_into(v, atoms)?;
}
Ok(())
}
Self::EmptyVector => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected array for vector, got {value}"))
})?;
if !arr.is_empty() {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected 0, got {}",
arr.len()
)));
}
Ok(())
}
_ => unreachable!("only called for compound variants"),
}
}
fn encode_into(
&self,
value: &Value,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
match self {
Self::Bool => {
let b = value.as_bool().ok_or_else(|| {
IrDriverError::TypeMismatch(format!("expected bool, got {value}"))
})?;
atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(if b {
vec![1]
} else {
Vec::new()
}));
Ok(())
}
Self::Uint { max, width } => {
let v = json_as_u128(value)?;
if v > *max {
return Err(IrDriverError::TypeMismatch(format!(
"value {v} exceeds Uint maxval {max}"
)));
}
let le = v.to_le_bytes();
push_le_trimmed(&le[..width.byte_len() as usize], atoms);
Ok(())
}
Self::Bytes { length } => encode_bytes_into(*length, value, atoms),
Self::Field => {
atoms.extend(encode_field(value)?.value.0);
Ok(())
}
Self::ForeignField(ft) => {
atoms.extend(super::curve::encode_field_type(*ft, value)?.value.0);
Ok(())
}
Self::JubjubPoint => {
atoms.extend(super::curve::encode_jubjub_point(value)?.value.0);
Ok(())
}
Self::WeierstrassPoint { base, name } => {
atoms.extend(
super::curve::encode_weierstrass_point(*base, value, name)?
.value
.0,
);
Ok(())
}
Self::Curve25519Point => {
atoms.extend(super::curve::encode_curve25519_point(value)?.value.0);
Ok(())
}
Self::Enum { name, elements } => {
let variant = value.as_str().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected enum-variant string for {name}, got {value}"
))
})?;
let idx = encode_enum_names(name, elements, variant)?;
push_le_trimmed(&[idx], atoms);
Ok(())
}
Self::OpaqueString => {
atoms.extend(encode_opaque("string", value)?.value.0);
Ok(())
}
Self::OpaqueBytes => {
atoms.extend(encode_opaque("Uint8Array", value)?.value.0);
Ok(())
}
Self::OpaqueJubjubPoint => {
atoms.extend(encode_opaque("JubjubPoint", value)?.value.0);
Ok(())
}
Self::Struct { .. } | Self::Tuple(_) | Self::Vector { .. } | Self::EmptyVector => {
self.encode_compound_into(value, atoms)
}
}
}
fn encode_vm_compound_into(
&self,
value: &VmVal,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
match self {
Self::Struct { name, fields } => {
let Some(obj_fields) = value.as_object() else {
return Err(IrDriverError::TypeMismatch(format!(
"expected object for struct {name}, got {}",
value.to_runtime_value()
)));
};
for (idx, (field_name, field_node)) in fields.iter().enumerate() {
let field_v = value.get_field(field_name, Some(idx)).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"struct {name} missing field '{field_name}'; got keys {:?}",
obj_fields
.iter()
.map(|(k, _)| k.as_ref())
.collect::<Vec<_>>()
))
})?;
field_node.encode_vm_val_into(field_v, atoms)?;
}
Ok(())
}
Self::Tuple(nodes) => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected array for tuple, got {}",
value.to_runtime_value()
))
})?;
if arr.len() != nodes.len() {
return Err(IrDriverError::TypeMismatch(format!(
"tuple arity mismatch: expected {}, got {}",
nodes.len(),
arr.len()
)));
}
for (node, v) in nodes.iter().zip(arr.iter()) {
node.encode_vm_val_into(v, atoms)?;
}
Ok(())
}
Self::Vector { length, elem } => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected array for vector, got {}",
value.to_runtime_value()
))
})?;
if u32::try_from(arr.len()) != Ok(*length) {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected {length}, got {}",
arr.len()
)));
}
for v in arr {
elem.encode_vm_val_into(v, atoms)?;
}
Ok(())
}
Self::EmptyVector => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected array for vector, got {}",
value.to_runtime_value()
))
})?;
if !arr.is_empty() {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected 0, got {}",
arr.len()
)));
}
Ok(())
}
_ => unreachable!("only called for compound variants"),
}
}
fn encode_vm_val_into(
&self,
value: &VmVal,
atoms: &mut Vec<moonproof_ledger::base_crypto::fab::ValueAtom>,
) -> Result<()> {
match self {
Self::Bool => {
let b = value.as_bool().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected bool, got {}",
value.to_runtime_value()
))
})?;
atoms.push(moonproof_ledger::base_crypto::fab::ValueAtom(if b {
vec![1]
} else {
Vec::new()
}));
Ok(())
}
Self::Uint { max, width } => {
let v = value.as_u128_parsed()?;
if v > *max {
return Err(IrDriverError::TypeMismatch(format!(
"value {v} exceeds Uint maxval {max}"
)));
}
let le = v.to_le_bytes();
push_le_trimmed(&le[..width.byte_len() as usize], atoms);
Ok(())
}
Self::Bytes { length } => encode_vm_bytes_into(*length, value, atoms),
Self::Field => encode_vm_field_into(value, atoms),
Self::Enum { name, elements } => {
let variant = value.as_str().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected enum-variant string for {name}, got {}",
value.to_runtime_value()
))
})?;
let idx = encode_enum_names(name, elements, variant)?;
push_le_trimmed(&[idx], atoms);
Ok(())
}
Self::OpaqueString => {
let s = value.as_str().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected string for Opaque<string>, got {}",
value.to_runtime_value()
))
})?;
push_le_trimmed(s.as_bytes(), atoms);
Ok(())
}
Self::OpaqueBytes => {
let b = value.as_bytes().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected Bytes for Opaque<Uint8Array>, got {}",
value.to_runtime_value()
))
})?;
push_le_trimmed(b, atoms);
Ok(())
}
Self::OpaqueJubjubPoint | Self::JubjubPoint => {
let x = value.get_field("x", Some(0)).ok_or_else(|| {
IrDriverError::TypeMismatch("JubjubPoint missing field 'x'".into())
})?;
let y = value.get_field("y", Some(1)).ok_or_else(|| {
IrDriverError::TypeMismatch("JubjubPoint missing field 'y'".into())
})?;
encode_vm_field_into(x, atoms)?;
encode_vm_field_into(y, atoms)
}
Self::ForeignField(ft) => {
let rv = value.to_runtime_value();
atoms.extend(super::curve::encode_field_type(*ft, &rv)?.value.0);
Ok(())
}
Self::WeierstrassPoint { base, name } => {
let rv = value.to_runtime_value();
atoms.extend(
super::curve::encode_weierstrass_point(*base, &rv, name)?
.value
.0,
);
Ok(())
}
Self::Curve25519Point => {
let rv = value.to_runtime_value();
atoms.extend(super::curve::encode_curve25519_point(&rv)?.value.0);
Ok(())
}
Self::Struct { .. } | Self::Tuple(_) | Self::Vector { .. } | Self::EmptyVector => {
self.encode_vm_compound_into(value, atoms)
}
}
}
fn decode_vm_val(
&self,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<VmVal> {
match self {
Self::Bool => {
let atom = consume_fab_atom(atoms, cursor, "Boolean")?;
let n = u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("bool atom decode: {e:?}")))?;
Ok(VmVal::Bool(n != 0))
}
Self::Uint { width, .. } => {
let atom = consume_fab_atom(atoms, cursor, "Uint")?;
decode_vm_uint(*width, atom)
}
Self::Bytes { length: 32 } | Self::Field => {
let atom = consume_fab_atom(atoms, cursor, "Bytes32/Field")?;
Ok(decode_atom_bytes32(atom))
}
Self::Bytes { length } => {
let atom = consume_fab_atom(atoms, cursor, "Bytes")?;
let mut buf = atom.0.clone();
buf.resize(*length as usize, 0);
Ok(VmVal::from_bytes_vec(buf))
}
Self::ForeignField(FieldType::JubjubScalar) => {
let atom = consume_fab_atom(atoms, cursor, "JubjubScalar")?;
Ok(decode_atom_bytes32(atom))
}
Self::ForeignField(ft) => {
let low = consume_fab_atom(atoms, cursor, "ForeignField.low")?;
let high = consume_fab_atom(atoms, cursor, "ForeignField.high")?;
let v = super::curve::decode_foreign_field(*ft, low, high, &format!("{ft:?}"))?;
Ok(VmVal::Bytes32(v.to_le_bytes()))
}
Self::JubjubPoint
| Self::OpaqueJubjubPoint
| Self::Curve25519Point
| Self::WeierstrassPoint { .. } => self.decode_vm_point(atoms, cursor),
Self::Enum { name, elements } => {
let atom = consume_fab_atom(atoms, cursor, name)?;
let idx = u8::try_from(atom)
.map_err(|e| IrDriverError::TypeMismatch(format!("enum→u8 decode: {e:?}")))?;
elements
.get(usize::from(idx))
.map(|s| VmVal::Str(Arc::clone(s)))
.ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"enum {name}: index {idx} out of range (variants: {elements:?})"
))
})
}
Self::OpaqueString => {
let atom = consume_fab_atom(atoms, cursor, "Opaque<string>")?;
let s = std::str::from_utf8(&atom.0).map_err(|e| {
IrDriverError::TypeMismatch(format!("Opaque<string> not valid UTF-8: {e}"))
})?;
Ok(VmVal::Str(Arc::from(s)))
}
Self::OpaqueBytes => {
let atom = consume_fab_atom(atoms, cursor, "Opaque<Uint8Array>")?;
Ok(VmVal::from_bytes_slice(&atom.0))
}
Self::Struct { fields, .. } => {
let mut out = Vec::with_capacity(fields.len());
for (field_name, field_node) in fields {
let v = field_node.decode_vm_val(atoms, cursor)?;
out.push((Arc::clone(field_name), v));
}
Ok(VmVal::Object(Arc::from(out)))
}
Self::Tuple(nodes) => {
if nodes.is_empty() {
return Ok(VmVal::Array(Arc::from([] as [VmVal; 0])));
}
let mut out = Vec::with_capacity(nodes.len());
for node in nodes {
out.push(node.decode_vm_val(atoms, cursor)?);
}
Ok(VmVal::Array(Arc::from(out)))
}
Self::Vector { length, elem } => {
let len = *length as usize;
let mut out = Vec::with_capacity(len);
for _ in 0..len {
out.push(elem.decode_vm_val(atoms, cursor)?);
}
Ok(VmVal::Array(Arc::from(out)))
}
Self::EmptyVector => Ok(VmVal::Array(Arc::from([] as [VmVal; 0]))),
}
}
fn decode_vm_point(
&self,
atoms: &[moonproof_ledger::base_crypto::fab::ValueAtom],
cursor: &mut usize,
) -> Result<VmVal> {
match self {
Self::JubjubPoint | Self::OpaqueJubjubPoint => {
let x = decode_atom_bytes32(consume_fab_atom(atoms, cursor, "JubjubPoint.x")?);
let y = decode_atom_bytes32(consume_fab_atom(atoms, cursor, "JubjubPoint.y")?);
Ok(VmVal::Object(Arc::from([
(Arc::from("x"), x),
(Arc::from("y"), y),
])))
}
Self::Curve25519Point => {
let x_lo = consume_fab_atom(atoms, cursor, "Curve25519Point.x.lo")?;
let x_hi = consume_fab_atom(atoms, cursor, "Curve25519Point.x.hi")?;
let x = super::curve::decode_foreign_field(
FieldType::Curve25519Base,
x_lo,
x_hi,
"Curve25519Base",
)?;
let y_lo = consume_fab_atom(atoms, cursor, "Curve25519Point.y.lo")?;
let y_hi = consume_fab_atom(atoms, cursor, "Curve25519Point.y.hi")?;
let y = super::curve::decode_foreign_field(
FieldType::Curve25519Base,
y_lo,
y_hi,
"Curve25519Base",
)?;
Ok(VmVal::Object(Arc::from([
(Arc::from("x"), VmVal::Bytes32(x.to_le_bytes())),
(Arc::from("y"), VmVal::Bytes32(y.to_le_bytes())),
])))
}
Self::WeierstrassPoint { base, name } => {
let x_lo = consume_fab_atom(atoms, cursor, name)?;
let x_hi = consume_fab_atom(atoms, cursor, name)?;
let x = super::curve::decode_foreign_field(*base, x_lo, x_hi, name)?;
let y_lo = consume_fab_atom(atoms, cursor, name)?;
let y_hi = consume_fab_atom(atoms, cursor, name)?;
let y = super::curve::decode_foreign_field(*base, y_lo, y_hi, name)?;
let flag = consume_fab_atom(atoms, cursor, name)?;
let identity = u8::try_from(flag).map_err(|e| {
IrDriverError::TypeMismatch(format!("{name} identity decode: {e:?}"))
})? != 0;
Ok(VmVal::Object(Arc::from([
(Arc::from("x"), VmVal::Bytes32(x.to_le_bytes())),
(Arc::from("y"), VmVal::Bytes32(y.to_le_bytes())),
(Arc::from("identity"), VmVal::Bool(identity)),
])))
}
_ => unreachable!("only called for point variants"),
}
}
fn is_pure_field(&self) -> bool {
match self {
Self::Field => true,
Self::Struct { fields, .. } => fields.iter().all(|(_, n)| n.is_pure_field()),
Self::Tuple(nodes) => nodes.iter().all(Self::is_pure_field),
Self::Vector { elem, .. } => elem.is_pure_field(),
_ => false,
}
}
fn encode_vm_val_frs_into(
&self,
value: &VmVal,
out: &mut Vec<moonproof_ledger::transient_crypto::curve::Fr>,
) -> Result<()> {
use moonproof_ledger::transient_crypto::curve::Fr;
match self {
Self::Field => {
let fr = if let Some(b) = value.as_bytes() {
Fr::from_le_bytes(b).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"Field value out of range: {} bytes does not fit in Fr",
b.len()
))
})?
} else if let Some(n) = value.as_u128() {
Fr::from(n)
} else if let Some(s) = value.as_str() {
let n: u128 = s.parse().map_err(|e| {
IrDriverError::TypeMismatch(format!(
"Field decimal-string parse failed: '{s}' ({e})"
))
})?;
Fr::from(n)
} else {
return Err(IrDriverError::TypeMismatch(format!(
"Field expects bytes or numeric, got {}",
value.to_runtime_value()
)));
};
out.push(fr);
Ok(())
}
Self::Struct { name, fields } => {
let Some(obj_fields) = value.as_object() else {
return Err(IrDriverError::TypeMismatch(format!(
"expected object for struct {name}, got {}",
value.to_runtime_value()
)));
};
for (idx, (field_name, field_node)) in fields.iter().enumerate() {
let field_v = value.get_field(field_name, Some(idx)).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"struct {name} missing field '{field_name}'; got keys {:?}",
obj_fields
.iter()
.map(|(k, _)| k.as_ref())
.collect::<Vec<_>>()
))
})?;
field_node.encode_vm_val_frs_into(field_v, out)?;
}
Ok(())
}
Self::Tuple(nodes) => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected array for tuple, got {}",
value.to_runtime_value()
))
})?;
if arr.len() != nodes.len() {
return Err(IrDriverError::TypeMismatch(format!(
"tuple arity mismatch: expected {}, got {}",
nodes.len(),
arr.len()
)));
}
for (node, v) in nodes.iter().zip(arr.iter()) {
node.encode_vm_val_frs_into(v, out)?;
}
Ok(())
}
Self::Vector { length, elem } => {
let arr = value.as_array().ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"expected array for vector, got {}",
value.to_runtime_value()
))
})?;
if u32::try_from(arr.len()) != Ok(*length) {
return Err(IrDriverError::TypeMismatch(format!(
"vector length mismatch: expected {length}, got {}",
arr.len()
)));
}
for v in arr {
elem.encode_vm_val_frs_into(v, out)?;
}
Ok(())
}
_ => unreachable!("is_pure_field verified"),
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use moonproof_runtime_ir::ir::{IntLit, StructField};
use super::*;
fn assert_plan_matches_encode_literal(desc: &TypeDescriptor, val: &Value) {
let plan = FabPlan::compile(desc).expect("descriptor should compile to FabPlan");
let expected = encode_literal(desc, val).expect("encode_literal should succeed");
let actual = plan.encode(val).expect("FabPlan::encode should succeed");
assert_eq!(actual, expected, "FabPlan mismatch for {desc:?} / {val:?}");
let vm_val = VmVal::from_runtime_value(val);
let actual_vm = plan
.encode_vm_val(&vm_val)
.expect("FabPlan::encode_vm_val should succeed");
assert_eq!(
actual_vm, expected,
"FabPlan::encode_vm_val mismatch for {desc:?} / {val:?}"
);
let decoded_expected = decode_aligned_value_full(desc, &expected)
.expect("decode_aligned_value_full should succeed");
let decoded_vm = plan
.decode_to_vm_val(&expected)
.expect("FabPlan::decode_to_vm_val should succeed")
.into_runtime_value();
assert_eq!(
decoded_vm, decoded_expected,
"FabPlan::decode_to_vm_val mismatch for {desc:?}"
);
let mut frs = Vec::new();
if let Some(res) = plan.try_encode_vm_val_frs(&vm_val, &mut frs) {
use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
use moonproof_ledger::transient_crypto::repr::FieldRepr;
res.expect("try_encode_vm_val_frs should succeed");
let expected_frs = ValueReprAlignedValue(expected).field_vec();
assert_eq!(
frs, expected_frs,
"try_encode_vm_val_frs mismatch for {desc:?}"
);
}
}
#[test]
fn fab_plan_matches_encode_literal_for_primitives() {
assert_plan_matches_encode_literal(&TypeDescriptor::Boolean, &Value::Bool(false));
assert_plan_matches_encode_literal(&TypeDescriptor::Boolean, &Value::Bool(true));
for (max, v) in [
(0u128, Value::Int(0)),
(255, Value::Int(0)),
(255, Value::Int(255)),
(65535, Value::Int(256)),
(u128::from(u32::MAX), Value::Int(0x1234_5678)),
(u128::from(u64::MAX), Value::Int(i128::from(u64::MAX))),
(u128::MAX, Value::String(u128::MAX.to_string())),
] {
assert_plan_matches_encode_literal(
&TypeDescriptor::Uint {
maxval: IntLit::from_u128(max),
alignment_bytes: None,
},
&v,
);
}
assert_plan_matches_encode_literal(&TypeDescriptor::Counter, &Value::Int(42));
assert_plan_matches_encode_literal(
&TypeDescriptor::Bytes { length: 32 },
&Value::Bytes(vec![0u8; 32]),
);
assert_plan_matches_encode_literal(
&TypeDescriptor::Bytes { length: 4 },
&Value::Bytes(vec![0xaa, 0xbb, 0, 0]),
);
assert_plan_matches_encode_literal(&TypeDescriptor::Field, &Value::Int(0));
assert_plan_matches_encode_literal(&TypeDescriptor::Field, &Value::Int(123_456));
assert_plan_matches_encode_literal(&TypeDescriptor::Secp256k1Base, &Value::Int(0));
assert_plan_matches_encode_literal(&TypeDescriptor::Curve25519Scalar, &Value::Int(99));
assert_plan_matches_encode_literal(
&TypeDescriptor::Enum {
name: "Color".to_owned(),
elements: vec!["Red".to_owned(), "Green".to_owned(), "Blue".to_owned()],
},
&Value::String("Green".to_owned()),
);
assert_plan_matches_encode_literal(
&TypeDescriptor::Opaque {
ts_type: "string".to_owned(),
},
&Value::String("hello\0\0".to_owned()),
);
assert_plan_matches_encode_literal(
&TypeDescriptor::Opaque {
ts_type: "Uint8Array".to_owned(),
},
&Value::Bytes(vec![1, 2, 0, 0]),
);
}
#[test]
fn fab_plan_matches_encode_literal_for_compounds() {
assert_plan_matches_encode_literal(
&TypeDescriptor::Vector {
length: 0,
elt_type: Box::new(TypeDescriptor::Unknown),
},
&Value::Array(Vec::new()),
);
let compound = TypeDescriptor::Struct {
name: "Envelope".to_owned(),
elements: vec![
StructField {
name: "flag".to_owned(),
field_type: TypeDescriptor::Boolean,
},
StructField {
name: "payload".to_owned(),
field_type: TypeDescriptor::Tuple {
types: vec![
TypeDescriptor::Uint {
maxval: IntLit::from_u128(255),
alignment_bytes: None,
},
TypeDescriptor::Bytes { length: 32 },
],
},
},
StructField {
name: "items".to_owned(),
field_type: TypeDescriptor::Vector {
length: 2,
elt_type: Box::new(TypeDescriptor::Field),
},
},
],
};
let mut obj = BTreeMap::new();
obj.insert("flag".to_owned(), Value::Bool(true));
obj.insert(
"payload".to_owned(),
Value::Array(vec![Value::Int(7), Value::Bytes(vec![0x5a; 32])]),
);
obj.insert(
"items".to_owned(),
Value::Array(vec![Value::Int(10), Value::Int(20)]),
);
assert_plan_matches_encode_literal(&compound, &Value::Object(obj));
}
#[test]
fn json_as_u128_accepts_int_above_u64_max() {
let signed_input = i128::from(u64::MAX) + 1;
let expected_u128 = u128::from(u64::MAX) + 1;
assert_eq!(
json_as_u128(&Value::Int(signed_input)).unwrap(),
expected_u128
);
assert_eq!(
json_as_u128(&Value::Int(i128::MAX)).unwrap(),
u128::try_from(i128::MAX).unwrap()
);
assert!(json_as_u128(&Value::Int(-1)).is_err());
let u128_ty = TypeDescriptor::Uint {
maxval: IntLit::from_u128(u128::MAX),
alignment_bytes: None,
};
assert_plan_matches_encode_literal(&u128_ty, &Value::Int(signed_input));
}
}