use std::collections::BTreeMap;
use moonproof_ledger::base_crypto::fab::{AlignedValue, Alignment, Value as FabValue, ValueAtom};
use moonproof_runtime_ir::ir::TypeDescriptor;
use moonproof_runtime_ir::value::RuntimeValue;
use crate::ir::error::{IrDriverError, Result};
use crate::ledger::{AtomBuffer, HistoricMerkleTreeSnapshot, MerkleTreeSnapshot};
pub use crate::ir::descriptor::{
decode_aligned_value, decode_aligned_value_full, encode_bool, encode_bytes, encode_default,
encode_field, encode_literal, encode_uint, json_as_u128,
};
pub fn walk_counter(buf: &AtomBuffer) -> Result<RuntimeValue> {
walk_atom_buffer(&TypeDescriptor::Counter, buf)
}
pub fn walk_cell(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
walk_atom_buffer(d, buf)
}
pub fn walk_map(
key: &TypeDescriptor,
value: &TypeDescriptor,
entries: &[(AtomBuffer, AtomBuffer)],
) -> Result<RuntimeValue> {
let mut obj = BTreeMap::new();
for (k_buf, v_buf) in entries {
let k_val = walk_atom_buffer(key, k_buf)?;
let v_val = if v_buf.atoms.is_empty() {
RuntimeValue::Null
} else {
walk_atom_buffer(value, v_buf)?
};
obj.insert(stringify_key(&k_val), v_val);
}
Ok(RuntimeValue::Object(obj))
}
pub fn walk_set(d: &TypeDescriptor, entries: &[AtomBuffer]) -> Result<RuntimeValue> {
let mut arr = Vec::with_capacity(entries.len());
for buf in entries {
arr.push(walk_atom_buffer(d, buf)?);
}
Ok(RuntimeValue::Array(arr))
}
pub fn walk_list(d: &TypeDescriptor, entries: &[AtomBuffer]) -> Result<RuntimeValue> {
let mut arr = Vec::with_capacity(entries.len());
for buf in entries {
arr.push(walk_atom_buffer(d, buf)?);
}
Ok(RuntimeValue::Array(arr))
}
pub fn walk_merkle_tree(snap: &MerkleTreeSnapshot) -> RuntimeValue {
let mut obj = BTreeMap::new();
obj.insert("root".to_owned(), RuntimeValue::Bytes(snap.root.clone()));
obj.insert(
"height".to_owned(),
RuntimeValue::Int(i128::from(snap.height)),
);
RuntimeValue::Object(obj)
}
pub fn walk_historic_merkle_tree(snap: &HistoricMerkleTreeSnapshot) -> RuntimeValue {
let mut obj = BTreeMap::new();
obj.insert("live".to_owned(), walk_merkle_tree(&snap.live));
obj.insert(
"history".to_owned(),
RuntimeValue::Array(snap.history.iter().map(walk_merkle_tree).collect()),
);
RuntimeValue::Object(obj)
}
fn walk_atom_buffer(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
let mut cursor = 0;
let v = decode_aligned_value(d, &buf.atoms, &mut cursor)?;
if cursor != buf.atoms.len() {
return Err(IrDriverError::TypeMismatch(format!(
"AtomBuffer had {} atoms but descriptor consumed {cursor}",
buf.atoms.len()
)));
}
Ok(v)
}
pub fn atom_buffer_to_aligned(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<AlignedValue> {
let v = walk_atom_buffer(d, buf)?;
encode_literal(d, &v)
}
pub fn aligned_value_from_atoms(
atoms: &[Vec<u8>],
alignment: Alignment,
) -> std::result::Result<AlignedValue, &'static str> {
let value = FabValue(atoms.iter().map(|a| ValueAtom(a.clone())).collect());
AlignedValue::new(value, alignment).ok_or("alignment / value mismatch")
}
fn stringify_key(v: &RuntimeValue) -> String {
match v {
RuntimeValue::Null => "null".to_owned(),
RuntimeValue::Bool(b) => b.to_string(),
RuntimeValue::Int(i) => i.to_string(),
RuntimeValue::Bytes(b) => hex::encode(b),
RuntimeValue::String(s) => s.clone(),
RuntimeValue::Array(_) | RuntimeValue::Object(_) => {
serde_json::to_string(&serde_json::Value::from(v.clone())).unwrap_or_default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_runtime_ir::ir::{IntLit, StructField};
fn buf(parts: &[&[u8]]) -> AtomBuffer {
AtomBuffer::from_byte_buffers(parts.iter().map(|a| a.to_vec()).collect())
}
#[test]
fn cell_boolean_round_trip() {
let b = buf(&[&[1u8]]);
assert_eq!(
walk_cell(&TypeDescriptor::Boolean, &b).unwrap(),
RuntimeValue::Bool(true)
);
}
#[test]
fn counter_decodes_to_int() {
let b = buf(&[&[42u8]]);
assert_eq!(walk_counter(&b).unwrap(), RuntimeValue::Int(42));
}
#[test]
fn cell_field_decodes_to_bytes() {
let mut bytes = vec![0u8; 32];
bytes[0] = 0xab;
let b = buf(&[&bytes]);
let v = walk_cell(&TypeDescriptor::Field, &b).unwrap();
match v {
RuntimeValue::Bytes(out) => {
assert_eq!(out.len(), 32);
assert_eq!(out[0], 0xab);
}
other => panic!("expected Bytes, got {other:?}"),
}
}
#[test]
fn cell_struct_lowers_to_object() {
let d = TypeDescriptor::Struct {
name: "Foo".into(),
elements: vec![
StructField {
name: "active".into(),
field_type: TypeDescriptor::Boolean,
},
StructField {
name: "count".into(),
field_type: TypeDescriptor::Counter,
},
],
};
let b = buf(&[&[1u8], &[7u8]]);
let v = walk_cell(&d, &b).unwrap();
match v {
RuntimeValue::Object(o) => {
assert_eq!(o.get("active"), Some(&RuntimeValue::Bool(true)));
assert_eq!(o.get("count"), Some(&RuntimeValue::Int(7)));
}
other => panic!("expected Object, got {other:?}"),
}
}
#[test]
fn enum_decodes_to_variant_string() {
let d = TypeDescriptor::Enum {
name: "State".into(),
elements: vec!["Idle".into(), "Active".into(), "Done".into()],
};
let b = buf(&[&[1u8]]);
assert_eq!(
walk_cell(&d, &b).unwrap(),
RuntimeValue::String("Active".into())
);
}
#[test]
fn vector_decodes_to_array() {
let d = TypeDescriptor::Vector {
length: 3,
elt_type: Box::new(TypeDescriptor::Boolean),
};
let b = buf(&[&[], &[1u8], &[]]);
assert_eq!(
walk_cell(&d, &b).unwrap(),
RuntimeValue::Array(vec![
RuntimeValue::Bool(false),
RuntimeValue::Bool(true),
RuntimeValue::Bool(false),
])
);
}
#[test]
fn alias_passes_through() {
let d = TypeDescriptor::Alias {
name: "MyBool".into(),
of: Box::new(TypeDescriptor::Boolean),
};
let b = buf(&[&[1u8]]);
assert_eq!(walk_cell(&d, &b).unwrap(), RuntimeValue::Bool(true));
}
#[test]
fn uint_with_alignment_decodes_to_int() {
let d = TypeDescriptor::Uint {
maxval: IntLit::from_u128(0xffff),
alignment_bytes: Some(2),
};
let b = buf(&[&[0xef, 0xbe]]);
assert_eq!(walk_cell(&d, &b).unwrap(), RuntimeValue::Int(0xbeef));
}
#[test]
fn walk_map_stringifies_keys_and_handles_null_values() {
let entries = vec![
(
AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
),
(
AtomBuffer::from_byte_buffers(vec![vec![2u8]]),
AtomBuffer::from_byte_buffers(Vec::new()),
),
];
let v = walk_map(&TypeDescriptor::Counter, &TypeDescriptor::Boolean, &entries).unwrap();
match v {
RuntimeValue::Object(o) => {
assert_eq!(o.get("1"), Some(&RuntimeValue::Bool(true)));
assert_eq!(o.get("2"), Some(&RuntimeValue::Null));
}
other => panic!("expected Object, got {other:?}"),
}
}
#[test]
fn walk_set_emits_array() {
let entries = vec![
AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
AtomBuffer::from_byte_buffers(vec![vec![2u8]]),
];
let v = walk_set(&TypeDescriptor::Counter, &entries).unwrap();
assert_eq!(
v,
RuntimeValue::Array(vec![RuntimeValue::Int(1), RuntimeValue::Int(2)])
);
}
#[test]
fn walk_list_emits_array() {
let entries = vec![
AtomBuffer::from_byte_buffers(vec![vec![10u8]]),
AtomBuffer::from_byte_buffers(vec![vec![20u8]]),
AtomBuffer::from_byte_buffers(vec![vec![30u8]]),
];
let v = walk_list(&TypeDescriptor::Counter, &entries).unwrap();
assert_eq!(
v,
RuntimeValue::Array(vec![
RuntimeValue::Int(10),
RuntimeValue::Int(20),
RuntimeValue::Int(30),
])
);
}
#[test]
fn walk_merkle_tree_emits_root_height() {
let snap = MerkleTreeSnapshot {
root: vec![0xaa, 0xbb],
height: 3,
};
let v = walk_merkle_tree(&snap);
match v {
RuntimeValue::Object(o) => {
assert_eq!(o.get("root"), Some(&RuntimeValue::Bytes(vec![0xaa, 0xbb])));
assert_eq!(o.get("height"), Some(&RuntimeValue::Int(3)));
}
other => panic!("expected Object, got {other:?}"),
}
}
#[test]
fn walk_historic_merkle_tree_includes_history() {
let snap = HistoricMerkleTreeSnapshot {
live: MerkleTreeSnapshot {
root: vec![1],
height: 1,
},
history: vec![MerkleTreeSnapshot {
root: vec![2],
height: 1,
}],
};
let v = walk_historic_merkle_tree(&snap);
match v {
RuntimeValue::Object(o) => {
assert!(matches!(o.get("live"), Some(RuntimeValue::Object(_))));
assert!(matches!(o.get("history"), Some(RuntimeValue::Array(_))));
}
other => panic!("expected Object, got {other:?}"),
}
}
#[test]
fn round_trip_atom_buffer_to_aligned() {
let b = buf(&[&[1u8]]);
let av = atom_buffer_to_aligned(&TypeDescriptor::Boolean, &b).unwrap();
let v = decode_aligned_value_full(&TypeDescriptor::Boolean, &av).unwrap();
assert_eq!(v, RuntimeValue::Bool(true));
}
}