moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! Single-source data walker for descriptor ↔ [`RuntimeValue`] ↔
//! `AlignedValue` round trips.
//!
//! The atom-flat descriptors (Boolean / Counter / Field / Uint / Bytes
//! / Opaque / Vector / Tuple / Struct / Enum / Cell / Alias) are
//! covered by [`crate::ir::descriptor`] — bidirectional, fully
//! typed. This module re-exports those primitives under the `walker`
//! name and adds the storage-shape helpers (Map / Set / List /
//! `MerkleTree` / `HistoricMerkleTree`) that the descriptor module can't
//! cover because they aren't atom-flat.
//!
//! Convention is the one [`crate::ir::descriptor::decode_aligned_value`]
//! uses across the codebase: `Bytes<N>` / `Field` /
//! `Opaque<Uint8Array>` decode into `RuntimeValue::String(hex)`,
//! `Counter` / small `Uint<…>` into `RuntimeValue::Int`, big `Uint<…>`
//! into `RuntimeValue::String(decimal)`, structs into objects keyed
//! by IR field name, enums into the variant-name string. Generated
//! code on every binding language (Rust, TypeScript via napi/wasm,
//! Swift/Python/etc via uniffi) projects from there into language-
//! idiomatic typed shapes.

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};

// Re-export the atom-flat walker primitives.
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,
};

// =========================================================================
// Storage-shape helpers
//
// Each helper accepts the [`AtomBuffer`] / snapshot the [`crate::ledger`]
// module produces and returns a [`RuntimeValue`] using the same
// stringification conventions [`decode_aligned_value`] uses for
// scalar atoms.
// =========================================================================

/// Walk a `Counter` snapshot. Always 8-byte unsigned.
pub fn walk_counter(buf: &AtomBuffer) -> Result<RuntimeValue> {
    walk_atom_buffer(&TypeDescriptor::Counter, buf)
}

/// Walk a `Cell<T>` snapshot — typed by the inner descriptor.
pub fn walk_cell(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
    walk_atom_buffer(d, buf)
}

/// Walk a `Map<K, V>` snapshot. Keys are projected through the key
/// descriptor and stringified for the resulting object's keys; values
/// project through the value descriptor (an empty atom buffer in the
/// value slot becomes [`RuntimeValue::Null`], matching the way
/// `Set<T>` is on-chain encoded as `Map<T, Null>`).
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))
}

/// Walk a `Set<T>` snapshot.
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))
}

/// Walk a `List<T>` snapshot.
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))
}

/// Walk a `MerkleTree<depth, T>` snapshot into a
/// `{ root: bytes, height: int }` object — byte-honest.
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)
}

/// Walk a `HistoricMerkleTree<depth, T>` snapshot into a
/// `{ live: MerkleTree, history: [MerkleTree] }` object.
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)
}

// =========================================================================
// Internal: dispatch through descriptor::decode_aligned_value
// =========================================================================

fn walk_atom_buffer(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
    // `AtomBuffer.atoms: Vec<ValueAtom>` already, so pass the slice
    // straight through to `decode_aligned_value` — no per-atom byte
    // clone (used to be `iter().map(|b| ValueAtom(b.clone()))`).
    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)
}

/// Reconstruct an [`AlignedValue`] from an [`AtomBuffer`] (i.e. the
/// shape [`crate::ledger`] produces). Useful for callers that need to
/// pass a ledger snapshot back into [`encode_literal`] or any other
/// surface that wants `AlignedValue`. Alignment metadata is rebuilt
/// from `descriptor` so the result matches what the encoder would
/// have produced for the same logical value.
pub fn atom_buffer_to_aligned(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<AlignedValue> {
    // Decode then re-encode; preserves the descriptor-typed alignment
    // even when the on-the-wire buffer dropped trailing zeros.
    let v = walk_atom_buffer(d, buf)?;
    encode_literal(d, &v)
}

/// Build an [`AlignedValue`] directly from a raw atom slice and an
/// alignment singleton. Skips the round-trip when the caller already
/// knows the descriptor and just needs to wrap raw atoms.
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![
            // (key=1, value=true)
            (
                AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
                AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
            ),
            // (key=2, value=Null) — the shape `Set<T>`-as-`Map<T,Null>`
            // produces in `read_set_atoms`: zero atoms in the value slot.
            (
                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() {
        // Boolean atom round-trips: AtomBuffer → AlignedValue → atoms
        // should match (after the descriptor re-encodes alignment).
        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));
    }
}