Skip to main content

moonproof_runtime/walker/
mod.rs

1//! Single-source data walker for descriptor ↔ [`RuntimeValue`] ↔
2//! `AlignedValue` round trips.
3//!
4//! The atom-flat descriptors (Boolean / Counter / Field / Uint / Bytes
5//! / Opaque / Vector / Tuple / Struct / Enum / Cell / Alias) are
6//! covered by [`crate::ir::descriptor`] — bidirectional, fully
7//! typed. This module re-exports those primitives under the `walker`
8//! name and adds the storage-shape helpers (Map / Set / List /
9//! `MerkleTree` / `HistoricMerkleTree`) that the descriptor module can't
10//! cover because they aren't atom-flat.
11//!
12//! Convention is the one [`crate::ir::descriptor::decode_aligned_value`]
13//! uses across the codebase: `Bytes<N>` / `Field` /
14//! `Opaque<Uint8Array>` decode into `RuntimeValue::String(hex)`,
15//! `Counter` / small `Uint<…>` into `RuntimeValue::Int`, big `Uint<…>`
16//! into `RuntimeValue::String(decimal)`, structs into objects keyed
17//! by IR field name, enums into the variant-name string. Generated
18//! code on every binding language (Rust, TypeScript via napi/wasm,
19//! Swift/Python/etc via uniffi) projects from there into language-
20//! idiomatic typed shapes.
21
22use std::collections::BTreeMap;
23
24use moonproof_ledger::base_crypto::fab::{AlignedValue, Alignment, Value as FabValue, ValueAtom};
25use moonproof_runtime_ir::ir::TypeDescriptor;
26use moonproof_runtime_ir::value::RuntimeValue;
27
28use crate::ir::error::{IrDriverError, Result};
29use crate::ledger::{AtomBuffer, HistoricMerkleTreeSnapshot, MerkleTreeSnapshot};
30
31// Re-export the atom-flat walker primitives.
32pub use crate::ir::descriptor::{
33    decode_aligned_value, decode_aligned_value_full, encode_bool, encode_bytes, encode_default,
34    encode_field, encode_literal, encode_uint, json_as_u128,
35};
36
37// =========================================================================
38// Storage-shape helpers
39//
40// Each helper accepts the [`AtomBuffer`] / snapshot the [`crate::ledger`]
41// module produces and returns a [`RuntimeValue`] using the same
42// stringification conventions [`decode_aligned_value`] uses for
43// scalar atoms.
44// =========================================================================
45
46/// Walk a `Counter` snapshot. Always 8-byte unsigned.
47pub fn walk_counter(buf: &AtomBuffer) -> Result<RuntimeValue> {
48    walk_atom_buffer(&TypeDescriptor::Counter, buf)
49}
50
51/// Walk a `Cell<T>` snapshot — typed by the inner descriptor.
52pub fn walk_cell(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
53    walk_atom_buffer(d, buf)
54}
55
56/// Walk a `Map<K, V>` snapshot. Keys are projected through the key
57/// descriptor and stringified for the resulting object's keys; values
58/// project through the value descriptor (an empty atom buffer in the
59/// value slot becomes [`RuntimeValue::Null`], matching the way
60/// `Set<T>` is on-chain encoded as `Map<T, Null>`).
61pub fn walk_map(
62    key: &TypeDescriptor,
63    value: &TypeDescriptor,
64    entries: &[(AtomBuffer, AtomBuffer)],
65) -> Result<RuntimeValue> {
66    let mut obj = BTreeMap::new();
67    for (k_buf, v_buf) in entries {
68        let k_val = walk_atom_buffer(key, k_buf)?;
69        let v_val = if v_buf.atoms.is_empty() {
70            RuntimeValue::Null
71        } else {
72            walk_atom_buffer(value, v_buf)?
73        };
74        obj.insert(stringify_key(&k_val), v_val);
75    }
76    Ok(RuntimeValue::Object(obj))
77}
78
79/// Walk a `Set<T>` snapshot.
80pub fn walk_set(d: &TypeDescriptor, entries: &[AtomBuffer]) -> Result<RuntimeValue> {
81    let mut arr = Vec::with_capacity(entries.len());
82    for buf in entries {
83        arr.push(walk_atom_buffer(d, buf)?);
84    }
85    Ok(RuntimeValue::Array(arr))
86}
87
88/// Walk a `List<T>` snapshot.
89pub fn walk_list(d: &TypeDescriptor, entries: &[AtomBuffer]) -> Result<RuntimeValue> {
90    let mut arr = Vec::with_capacity(entries.len());
91    for buf in entries {
92        arr.push(walk_atom_buffer(d, buf)?);
93    }
94    Ok(RuntimeValue::Array(arr))
95}
96
97/// Walk a `MerkleTree<depth, T>` snapshot into a
98/// `{ root: bytes, height: int }` object — byte-honest.
99pub fn walk_merkle_tree(snap: &MerkleTreeSnapshot) -> RuntimeValue {
100    let mut obj = BTreeMap::new();
101    obj.insert("root".to_owned(), RuntimeValue::Bytes(snap.root.clone()));
102    obj.insert(
103        "height".to_owned(),
104        RuntimeValue::Int(i128::from(snap.height)),
105    );
106    RuntimeValue::Object(obj)
107}
108
109/// Walk a `HistoricMerkleTree<depth, T>` snapshot into a
110/// `{ live: MerkleTree, history: [MerkleTree] }` object.
111pub fn walk_historic_merkle_tree(snap: &HistoricMerkleTreeSnapshot) -> RuntimeValue {
112    let mut obj = BTreeMap::new();
113    obj.insert("live".to_owned(), walk_merkle_tree(&snap.live));
114    obj.insert(
115        "history".to_owned(),
116        RuntimeValue::Array(snap.history.iter().map(walk_merkle_tree).collect()),
117    );
118    RuntimeValue::Object(obj)
119}
120
121// =========================================================================
122// Internal: dispatch through descriptor::decode_aligned_value
123// =========================================================================
124
125fn walk_atom_buffer(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<RuntimeValue> {
126    // `AtomBuffer.atoms: Vec<ValueAtom>` already, so pass the slice
127    // straight through to `decode_aligned_value` — no per-atom byte
128    // clone (used to be `iter().map(|b| ValueAtom(b.clone()))`).
129    let mut cursor = 0;
130    let v = decode_aligned_value(d, &buf.atoms, &mut cursor)?;
131    if cursor != buf.atoms.len() {
132        return Err(IrDriverError::TypeMismatch(format!(
133            "AtomBuffer had {} atoms but descriptor consumed {cursor}",
134            buf.atoms.len()
135        )));
136    }
137    Ok(v)
138}
139
140/// Reconstruct an [`AlignedValue`] from an [`AtomBuffer`] (i.e. the
141/// shape [`crate::ledger`] produces). Useful for callers that need to
142/// pass a ledger snapshot back into [`encode_literal`] or any other
143/// surface that wants `AlignedValue`. Alignment metadata is rebuilt
144/// from `descriptor` so the result matches what the encoder would
145/// have produced for the same logical value.
146pub fn atom_buffer_to_aligned(d: &TypeDescriptor, buf: &AtomBuffer) -> Result<AlignedValue> {
147    // Decode then re-encode; preserves the descriptor-typed alignment
148    // even when the on-the-wire buffer dropped trailing zeros.
149    let v = walk_atom_buffer(d, buf)?;
150    encode_literal(d, &v)
151}
152
153/// Build an [`AlignedValue`] directly from a raw atom slice and an
154/// alignment singleton. Skips the round-trip when the caller already
155/// knows the descriptor and just needs to wrap raw atoms.
156pub fn aligned_value_from_atoms(
157    atoms: &[Vec<u8>],
158    alignment: Alignment,
159) -> std::result::Result<AlignedValue, &'static str> {
160    let value = FabValue(atoms.iter().map(|a| ValueAtom(a.clone())).collect());
161    AlignedValue::new(value, alignment).ok_or("alignment / value mismatch")
162}
163
164fn stringify_key(v: &RuntimeValue) -> String {
165    match v {
166        RuntimeValue::Null => "null".to_owned(),
167        RuntimeValue::Bool(b) => b.to_string(),
168        RuntimeValue::Int(i) => i.to_string(),
169        RuntimeValue::Bytes(b) => hex::encode(b),
170        RuntimeValue::String(s) => s.clone(),
171        RuntimeValue::Array(_) | RuntimeValue::Object(_) => {
172            serde_json::to_string(&serde_json::Value::from(v.clone())).unwrap_or_default()
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use moonproof_runtime_ir::ir::{IntLit, StructField};
181
182    fn buf(parts: &[&[u8]]) -> AtomBuffer {
183        AtomBuffer::from_byte_buffers(parts.iter().map(|a| a.to_vec()).collect())
184    }
185
186    #[test]
187    fn cell_boolean_round_trip() {
188        let b = buf(&[&[1u8]]);
189        assert_eq!(
190            walk_cell(&TypeDescriptor::Boolean, &b).unwrap(),
191            RuntimeValue::Bool(true)
192        );
193    }
194
195    #[test]
196    fn counter_decodes_to_int() {
197        let b = buf(&[&[42u8]]);
198        assert_eq!(walk_counter(&b).unwrap(), RuntimeValue::Int(42));
199    }
200
201    #[test]
202    fn cell_field_decodes_to_bytes() {
203        let mut bytes = vec![0u8; 32];
204        bytes[0] = 0xab;
205        let b = buf(&[&bytes]);
206        let v = walk_cell(&TypeDescriptor::Field, &b).unwrap();
207        match v {
208            RuntimeValue::Bytes(out) => {
209                assert_eq!(out.len(), 32);
210                assert_eq!(out[0], 0xab);
211            }
212            other => panic!("expected Bytes, got {other:?}"),
213        }
214    }
215
216    #[test]
217    fn cell_struct_lowers_to_object() {
218        let d = TypeDescriptor::Struct {
219            name: "Foo".into(),
220            elements: vec![
221                StructField {
222                    name: "active".into(),
223                    field_type: TypeDescriptor::Boolean,
224                },
225                StructField {
226                    name: "count".into(),
227                    field_type: TypeDescriptor::Counter,
228                },
229            ],
230        };
231        let b = buf(&[&[1u8], &[7u8]]);
232        let v = walk_cell(&d, &b).unwrap();
233        match v {
234            RuntimeValue::Object(o) => {
235                assert_eq!(o.get("active"), Some(&RuntimeValue::Bool(true)));
236                assert_eq!(o.get("count"), Some(&RuntimeValue::Int(7)));
237            }
238            other => panic!("expected Object, got {other:?}"),
239        }
240    }
241
242    #[test]
243    fn enum_decodes_to_variant_string() {
244        let d = TypeDescriptor::Enum {
245            name: "State".into(),
246            elements: vec!["Idle".into(), "Active".into(), "Done".into()],
247        };
248        let b = buf(&[&[1u8]]);
249        assert_eq!(
250            walk_cell(&d, &b).unwrap(),
251            RuntimeValue::String("Active".into())
252        );
253    }
254
255    #[test]
256    fn vector_decodes_to_array() {
257        let d = TypeDescriptor::Vector {
258            length: 3,
259            elt_type: Box::new(TypeDescriptor::Boolean),
260        };
261        let b = buf(&[&[], &[1u8], &[]]);
262        assert_eq!(
263            walk_cell(&d, &b).unwrap(),
264            RuntimeValue::Array(vec![
265                RuntimeValue::Bool(false),
266                RuntimeValue::Bool(true),
267                RuntimeValue::Bool(false),
268            ])
269        );
270    }
271
272    #[test]
273    fn alias_passes_through() {
274        let d = TypeDescriptor::Alias {
275            name: "MyBool".into(),
276            of: Box::new(TypeDescriptor::Boolean),
277        };
278        let b = buf(&[&[1u8]]);
279        assert_eq!(walk_cell(&d, &b).unwrap(), RuntimeValue::Bool(true));
280    }
281
282    #[test]
283    fn uint_with_alignment_decodes_to_int() {
284        let d = TypeDescriptor::Uint {
285            maxval: IntLit::from_u128(0xffff),
286            alignment_bytes: Some(2),
287        };
288        let b = buf(&[&[0xef, 0xbe]]);
289        assert_eq!(walk_cell(&d, &b).unwrap(), RuntimeValue::Int(0xbeef));
290    }
291
292    #[test]
293    fn walk_map_stringifies_keys_and_handles_null_values() {
294        let entries = vec![
295            // (key=1, value=true)
296            (
297                AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
298                AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
299            ),
300            // (key=2, value=Null) — the shape `Set<T>`-as-`Map<T,Null>`
301            // produces in `read_set_atoms`: zero atoms in the value slot.
302            (
303                AtomBuffer::from_byte_buffers(vec![vec![2u8]]),
304                AtomBuffer::from_byte_buffers(Vec::new()),
305            ),
306        ];
307        let v = walk_map(&TypeDescriptor::Counter, &TypeDescriptor::Boolean, &entries).unwrap();
308        match v {
309            RuntimeValue::Object(o) => {
310                assert_eq!(o.get("1"), Some(&RuntimeValue::Bool(true)));
311                assert_eq!(o.get("2"), Some(&RuntimeValue::Null));
312            }
313            other => panic!("expected Object, got {other:?}"),
314        }
315    }
316
317    #[test]
318    fn walk_set_emits_array() {
319        let entries = vec![
320            AtomBuffer::from_byte_buffers(vec![vec![1u8]]),
321            AtomBuffer::from_byte_buffers(vec![vec![2u8]]),
322        ];
323        let v = walk_set(&TypeDescriptor::Counter, &entries).unwrap();
324        assert_eq!(
325            v,
326            RuntimeValue::Array(vec![RuntimeValue::Int(1), RuntimeValue::Int(2)])
327        );
328    }
329
330    #[test]
331    fn walk_list_emits_array() {
332        let entries = vec![
333            AtomBuffer::from_byte_buffers(vec![vec![10u8]]),
334            AtomBuffer::from_byte_buffers(vec![vec![20u8]]),
335            AtomBuffer::from_byte_buffers(vec![vec![30u8]]),
336        ];
337        let v = walk_list(&TypeDescriptor::Counter, &entries).unwrap();
338        assert_eq!(
339            v,
340            RuntimeValue::Array(vec![
341                RuntimeValue::Int(10),
342                RuntimeValue::Int(20),
343                RuntimeValue::Int(30),
344            ])
345        );
346    }
347
348    #[test]
349    fn walk_merkle_tree_emits_root_height() {
350        let snap = MerkleTreeSnapshot {
351            root: vec![0xaa, 0xbb],
352            height: 3,
353        };
354        let v = walk_merkle_tree(&snap);
355        match v {
356            RuntimeValue::Object(o) => {
357                assert_eq!(o.get("root"), Some(&RuntimeValue::Bytes(vec![0xaa, 0xbb])));
358                assert_eq!(o.get("height"), Some(&RuntimeValue::Int(3)));
359            }
360            other => panic!("expected Object, got {other:?}"),
361        }
362    }
363
364    #[test]
365    fn walk_historic_merkle_tree_includes_history() {
366        let snap = HistoricMerkleTreeSnapshot {
367            live: MerkleTreeSnapshot {
368                root: vec![1],
369                height: 1,
370            },
371            history: vec![MerkleTreeSnapshot {
372                root: vec![2],
373                height: 1,
374            }],
375        };
376        let v = walk_historic_merkle_tree(&snap);
377        match v {
378            RuntimeValue::Object(o) => {
379                assert!(matches!(o.get("live"), Some(RuntimeValue::Object(_))));
380                assert!(matches!(o.get("history"), Some(RuntimeValue::Array(_))));
381            }
382            other => panic!("expected Object, got {other:?}"),
383        }
384    }
385
386    #[test]
387    fn round_trip_atom_buffer_to_aligned() {
388        // Boolean atom round-trips: AtomBuffer → AlignedValue → atoms
389        // should match (after the descriptor re-encodes alignment).
390        let b = buf(&[&[1u8]]);
391        let av = atom_buffer_to_aligned(&TypeDescriptor::Boolean, &b).unwrap();
392        let v = decode_aligned_value_full(&TypeDescriptor::Boolean, &av).unwrap();
393        assert_eq!(v, RuntimeValue::Bool(true));
394    }
395}