use std::collections::BTreeMap;
use std::sync::Arc;
use ethnum::U256;
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_runtime_ir::ir::TypeDescriptor;
use moonproof_runtime_ir::RuntimeValue as Value;
use super::error::{IrDriverError, Result};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum VmVal {
Null,
Bool(bool),
Int(i128),
Bytes32([u8; 32]),
Bytes(Arc<[u8]>),
Str(Arc<str>),
Array(Arc<[VmVal]>),
Object(Arc<[(Arc<str>, VmVal)]>),
}
impl VmVal {
#[must_use]
pub(crate) fn from_runtime_value(value: &Value) -> Self {
match value {
Value::Null => Self::Null,
Value::Bool(b) => Self::Bool(*b),
Value::Int(n) => Self::Int(*n),
Value::Bytes(b) => Self::from_bytes_slice(b),
Value::String(s) => Self::Str(Arc::from(s.as_str())),
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(Self::from_runtime_value(item));
}
Self::Array(Arc::from(out))
}
Value::Object(map) => {
let mut out = Vec::with_capacity(map.len());
for (k, v) in map {
out.push((Arc::from(k.as_str()), Self::from_runtime_value(v)));
}
Self::Object(Arc::from(out))
}
}
}
#[must_use]
pub(crate) fn from_owned_runtime_value(value: Value) -> Self {
match value {
Value::Null => Self::Null,
Value::Bool(b) => Self::Bool(b),
Value::Int(n) => Self::Int(n),
Value::Bytes(b) => Self::from_bytes_vec(b),
Value::String(s) => Self::Str(Arc::from(s)),
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(Self::from_owned_runtime_value(item));
}
Self::Array(Arc::from(out))
}
Value::Object(map) => {
let mut out = Vec::with_capacity(map.len());
for (k, v) in map {
out.push((Arc::from(k), Self::from_owned_runtime_value(v)));
}
Self::Object(Arc::from(out))
}
}
}
#[must_use]
pub(crate) fn into_runtime_value(self) -> Value {
match self {
Self::Null => Value::Null,
Self::Bool(b) => Value::Bool(b),
Self::Int(n) => Value::Int(n),
Self::Bytes32(b) => Value::Bytes(b.to_vec()),
Self::Bytes(b) => Value::Bytes(b.to_vec()),
Self::Str(s) => Value::String(s.as_ref().to_owned()),
Self::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items.iter() {
out.push(item.to_runtime_value());
}
Value::Array(out)
}
Self::Object(fields) => {
let mut map = BTreeMap::new();
for (k, v) in fields.iter() {
map.insert(k.as_ref().to_owned(), v.to_runtime_value());
}
Value::Object(map)
}
}
}
#[must_use]
pub(crate) fn to_runtime_value(&self) -> Value {
match self {
Self::Null => Value::Null,
Self::Bool(b) => Value::Bool(*b),
Self::Int(n) => Value::Int(*n),
Self::Bytes32(b) => Value::Bytes(b.to_vec()),
Self::Bytes(b) => Value::Bytes(b.to_vec()),
Self::Str(s) => Value::String(s.as_ref().to_owned()),
Self::Array(items) => Value::Array(items.iter().map(Self::to_runtime_value).collect()),
Self::Object(fields) => {
let mut map = BTreeMap::new();
for (k, v) in fields.iter() {
map.insert(k.as_ref().to_owned(), v.to_runtime_value());
}
Value::Object(map)
}
}
}
#[inline]
#[must_use]
pub(crate) fn from_bytes_slice(bytes: &[u8]) -> Self {
if let Ok(arr) = <[u8; 32]>::try_from(bytes) {
Self::Bytes32(arr)
} else {
Self::Bytes(Arc::from(bytes))
}
}
#[inline]
#[must_use]
pub(crate) fn from_bytes_vec(bytes: Vec<u8>) -> Self {
if bytes.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Self::Bytes32(arr)
} else {
Self::Bytes(Arc::from(bytes))
}
}
#[inline]
#[must_use]
pub(crate) fn from_uint(n: u128) -> Self {
match u64::try_from(n) {
Ok(v) => Self::Int(i128::from(v)),
Err(_) => Self::Str(Arc::from(n.to_string())),
}
}
#[inline]
#[must_use]
pub(crate) fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_bool_coerced(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
Self::Int(0) => Some(false),
Self::Int(1) => Some(true),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_u64(&self) -> Option<u64> {
match self {
Self::Int(n) => u64::try_from(*n).ok(),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_u128(&self) -> Option<u128> {
match self {
Self::Int(n) => u128::try_from(*n).ok(),
_ => None,
}
}
#[inline]
pub(crate) fn as_u128_parsed(&self) -> Result<u128> {
match self {
Self::Int(n) if *n >= 0 => Ok((*n).cast_unsigned()),
Self::Str(s) => s
.parse()
.map_err(|e| IrDriverError::TypeMismatch(format!("not a u128: {s} ({e})"))),
other => Err(IrDriverError::TypeMismatch(format!(
"expected u128-shaped value, got {}",
other.to_runtime_value()
))),
}
}
pub(crate) fn as_u256(&self, what: &str) -> Result<U256> {
match self {
Self::Bytes32(b) => Ok(U256::from_le_bytes(*b)),
Self::Bytes(b) => {
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);
Ok(U256::from_le_bytes(le))
}
Self::Int(n) if *n >= 0 => Ok(U256::from((*n).cast_unsigned())),
Self::Str(s) => {
let trimmed = s.trim();
let parsed = if let Some(hex_str) = trimmed
.strip_prefix("0x")
.or_else(|| trimmed.strip_prefix("0X"))
{
U256::from_str_radix(hex_str, 16)
} else {
U256::from_str_radix(trimmed, 10)
};
parsed.map_err(|e| {
IrDriverError::TypeMismatch(format!("{what} string parse failed: {s:?} ({e})"))
})
}
other => Err(IrDriverError::TypeMismatch(format!(
"{what} expects bytes, integer or numeric string, got {}",
other.to_runtime_value()
))),
}
}
#[inline]
#[must_use]
pub(crate) fn as_fr_fast(&self) -> Option<Fr> {
match self {
Self::Bytes32(b) => Fr::from_le_bytes(b),
Self::Bytes(b) => Fr::from_le_bytes(b),
Self::Int(n) if *n >= 0 => Some(Fr::from((*n).cast_unsigned())),
Self::Str(s) => s.parse::<u128>().ok().map(Fr::from),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_bytes(&self) -> Option<&[u8]> {
match self {
Self::Bytes32(b) => Some(b.as_slice()),
Self::Bytes(b) => Some(b.as_ref()),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_str(&self) -> Option<&str> {
match self {
Self::Str(s) => Some(s.as_ref()),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_array(&self) -> Option<&[VmVal]> {
match self {
Self::Array(items) => Some(items.as_ref()),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn as_object(&self) -> Option<&[(Arc<str>, VmVal)]> {
match self {
Self::Object(fields) => Some(fields.as_ref()),
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn get_field(&self, name: &str, hint_idx: Option<usize>) -> Option<&VmVal> {
let fields = self.as_object()?;
if let Some(i) = hint_idx {
if let Some((k, v)) = fields.get(i) {
if k.as_ref() == name {
return Some(v);
}
}
}
fields
.iter()
.find(|(k, _)| k.as_ref() == name)
.map(|(_, v)| v)
}
#[must_use]
pub(crate) fn structural_eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Null, Self::Null) => true,
(Self::Bool(a), Self::Bool(b)) => a == b,
(Self::Int(a), Self::Int(b)) => a == b,
(Self::Bytes32(a), Self::Bytes32(b)) => a == b,
(Self::Bytes32(a), Self::Bytes(b)) | (Self::Bytes(b), Self::Bytes32(a)) => {
a.as_slice() == b.as_ref()
}
(Self::Bytes(a), Self::Bytes(b)) => a == b,
(Self::Str(a), Self::Str(b)) => a == b,
(Self::Array(a), Self::Array(b)) => {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.structural_eq(y))
}
(Self::Object(a), Self::Object(b)) => {
if a.len() != b.len() {
return false;
}
if a.iter()
.zip(b.iter())
.all(|((ka, _), (kb, _))| ka.as_ref() == kb.as_ref())
{
return a
.iter()
.zip(b.iter())
.all(|((_, va), (_, vb))| va.structural_eq(vb));
}
a.iter().all(|(ka, va)| {
b.iter()
.find(|(kb, _)| kb.as_ref() == ka.as_ref())
.is_some_and(|(_, vb)| va.structural_eq(vb))
})
}
_ => false,
}
}
}
pub(crate) fn default_vm_val(descriptor: &TypeDescriptor) -> Result<VmVal> {
match descriptor {
TypeDescriptor::Boolean => Ok(VmVal::Bool(false)),
TypeDescriptor::Uint { .. } | TypeDescriptor::Counter => Ok(VmVal::Int(0)),
TypeDescriptor::Bytes { length: 32 } | TypeDescriptor::Field => {
Ok(VmVal::Bytes32([0u8; 32]))
}
TypeDescriptor::Bytes { length } => {
Ok(VmVal::Bytes(Arc::from(vec![0u8; *length as usize])))
}
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => default_vm_val(of),
TypeDescriptor::Struct { elements, .. } => {
let mut fields = Vec::with_capacity(elements.len());
for f in elements {
fields.push((Arc::from(f.name.as_str()), default_vm_val(&f.field_type)?));
}
Ok(VmVal::Object(Arc::from(fields)))
}
TypeDescriptor::Tuple { types } => {
let mut arr = Vec::with_capacity(types.len());
for t in types {
arr.push(default_vm_val(t)?);
}
Ok(VmVal::Array(Arc::from(arr)))
}
TypeDescriptor::Vector { elt_type, length } => {
let len = *length as usize;
if len == 0 {
return Ok(VmVal::Array(Arc::from([] as [VmVal; 0])));
}
let elem = default_vm_val(elt_type)?;
Ok(VmVal::Array(Arc::from(vec![elem; len])))
}
TypeDescriptor::Enum { elements, .. } => elements
.first()
.map(|s| VmVal::Str(Arc::from(s.as_str())))
.ok_or_else(|| IrDriverError::InvalidIr("enum descriptor has no variants".into())),
TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
"string" => Ok(VmVal::Str(Arc::from(""))),
"Uint8Array" => Ok(VmVal::Bytes(Arc::from([] as [u8; 0]))),
other => Err(IrDriverError::unimplemented(format!(
"default_value for Opaque<{other}>"
))),
},
TypeDescriptor::JubjubScalar
| TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base
| TypeDescriptor::Curve25519Scalar
| TypeDescriptor::JubjubPoint
| TypeDescriptor::Secp256k1Point
| TypeDescriptor::Secp256r1Point
| TypeDescriptor::Curve25519Point => {
let av = super::descriptor::encode_default(descriptor)?;
let v = super::descriptor::decode_aligned_value(descriptor, &av.value.0, &mut 0)?;
Ok(VmVal::from_owned_runtime_value(v))
}
other => Err(IrDriverError::unimplemented(format!(
"default_value for descriptor {other:?}"
))),
}
}