moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Cross-contract calls: a circuit that calls a circuit of another
//! deployed contract.
//!
//! The caller's IR names the callee's contract type and circuit; the
//! callee's code and deployed state come from the host, which binds
//! each address it is asked about to a [`CalleeContract`]. Execution
//! follows compact-runtime 0.21's `crossContractCall`: the callee runs
//! against its deployed state with no witnesses of its own, and the
//! caller records the callee's result and a fresh communication
//! commitment randomness as private transcript outputs, then claims the
//! call through `kernel.claimContractCall`.
//!
//! The interpreter is synchronous and the callee's state lives on
//! chain, so a run that reaches an address the session has no binding
//! for stops with [`CallTreeOutcome::CalleeRequired`]. The host binds
//! it and runs again. Witness results from earlier runs are replayed,
//! so the host's witnesses fire once per call site across all runs, as
//! they would in a single run.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use moonproof_ledger::base_crypto::fab::AlignedValue;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::ops::Op;
use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
use moonproof_ledger::onchain_runtime::state::{ContractState, EntryPointBuf};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_runtime_ir::ir::{ContractCircuitSig, MoonIr, TypeDescriptor};
use moonproof_runtime_ir::RuntimeValue as Value;
use rand::rngs::StdRng;
use sha2::{Digest, Sha256};

use crate::executable::ExecuteCircuitResult;
use crate::ir::error::{IrDriverError, Result};
use crate::ir::index::IrIndex;
use crate::ir::witnesses::{WitnessResult, Witnesses};
use crate::types::VerifierKey;
use crate::zswap_local::CompactZswapLocalState;

/// The code deployed at a callee address and its deployed state.
#[derive(Debug, Clone)]
pub struct CalleeContract {
    /// The callee's runtime IR.
    pub ir: Arc<MoonIr>,
    /// The callee's state at the block the transaction is built against.
    pub state: ContractState<InMemoryDB>,
    /// The verifier keys the callee's code was compiled to, by circuit
    /// name. A call is bound only when the deployed operation's key
    /// matches the called circuit's, and every other circuit both sides
    /// have agrees too (compact-runtime's `checkImplementation`).
    pub verifier_keys: HashMap<String, VerifierKey>,
}

/// One call to a callee circuit made while executing a call tree.
#[derive(Debug, Clone)]
pub struct CalleeCall {
    pub contract_address: ContractAddress,
    /// The contract whose circuit made the call.
    pub caller: ContractAddress,
    pub circuit_id: String,
    /// The callee's state when the call began: its deployed state on
    /// the first call to it, the state an earlier call left otherwise.
    pub initial_contract_state: ContractState<InMemoryDB>,
    pub next_contract_state: ContractState<InMemoryDB>,
    pub input: AlignedValue,
    pub output: AlignedValue,
    pub public_transcript: Vec<Op<ResultModeGather, InMemoryDB>>,
    pub popeq_read_results: Vec<AlignedValue>,
    pub private_transcript_outputs: Vec<AlignedValue>,
    /// The callee's coin operations so far, accumulated across every
    /// call to the same address in the tree.
    pub zswap_local_state: CompactZswapLocalState,
    /// The randomness the caller committed to this call's input and
    /// output with. The call's proof must reuse it.
    pub communication_commitment_rand: Fr,
    /// What the callee claimed and moved.
    pub effects: moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
}

/// A completed call tree.
#[derive(Debug, Clone)]
pub struct CallTreeResult {
    /// The circuit the host called.
    pub root: ExecuteCircuitResult,
    /// Every cross-contract call, in the order the calls returned:
    /// a callee precedes its caller, so the root's own call, were it
    /// listed, would come last.
    pub callees: Vec<CalleeCall>,
}

/// The outcome of one run of a call tree.
#[derive(Debug, Clone)]
pub enum CallTreeOutcome {
    Executed(Box<CallTreeResult>),
    /// The run reached a call to an address the session has no binding
    /// for. Bind it with [`CrossContractSession::bind_callee`] and run
    /// again.
    CalleeRequired(ContractAddress),
}

#[derive(Debug, Clone)]
struct RecordedWitness {
    name: String,
    args: Value,
    private_state: Value,
    result: WitnessResult,
}

/// The state a call tree keeps between runs: the callees bound so far
/// and the witness results already observed.
#[derive(Debug, Default)]
pub struct CrossContractSession {
    callees: HashMap<ContractAddress, Arc<CalleeContract>>,
    callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
    witness_tape: Vec<RecordedWitness>,
}

impl CrossContractSession {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    pub fn bind_callee(&mut self, address: ContractAddress, callee: CalleeContract) {
        let index = Arc::new(IrIndex::build(&callee.ir));
        self.callees.insert(address, Arc::new(callee));
        self.callee_indices.insert(address, index);
    }

    #[must_use]
    pub fn callee(&self, address: &ContractAddress) -> Option<&CalleeContract> {
        self.callees.get(address).map(AsRef::as_ref)
    }

    pub(crate) fn start_run(
        &mut self,
        witnesses: Arc<dyn Witnesses>,
        rng: StdRng,
    ) -> (CallTreeRun, Arc<TapedWitnesses>) {
        let taped = Arc::new(TapedWitnesses {
            inner: witnesses,
            tape: Mutex::new(Tape {
                recorded: std::mem::take(&mut self.witness_tape),
                replayed: 0,
            }),
        });
        let run = CallTreeRun {
            callees: self.callees.clone(),
            callee_indices: self.callee_indices.clone(),
            states: HashMap::new(),
            zswap: HashMap::new(),
            active: Vec::new(),
            calls: Vec::new(),
            required: None,
            rng,
        };
        (run, taped)
    }

    pub(crate) fn finish_run(&mut self, taped: &TapedWitnesses) -> Result<()> {
        let mut tape = taped
            .tape
            .lock()
            .map_err(|_| IrDriverError::Witness("witness tape lock poisoned".to_owned()))?;
        self.witness_tape = std::mem::take(&mut tape.recorded);
        Ok(())
    }
}

/// Per-run bookkeeping the interpreter threads through every frame of a
/// call tree.
#[derive(Debug)]
pub struct CallTreeRun {
    pub(crate) callees: HashMap<ContractAddress, Arc<CalleeContract>>,
    pub(crate) callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
    /// Callee states as earlier calls in this run left them.
    pub(crate) states: HashMap<ContractAddress, ContractState<InMemoryDB>>,
    pub(crate) zswap: HashMap<ContractAddress, CompactZswapLocalState>,
    /// The contracts executing, the root first.
    pub(crate) active: Vec<ContractAddress>,
    pub(crate) calls: Vec<CalleeCall>,
    pub(crate) required: Option<ContractAddress>,
    pub(crate) rng: StdRng,
}

#[derive(Debug)]
struct Tape {
    recorded: Vec<RecordedWitness>,
    replayed: usize,
}

/// The root's witnesses, recording each result so a later run of the
/// same tree replays it instead of asking the host again.
#[derive(Debug)]
pub(crate) struct TapedWitnesses {
    inner: Arc<dyn Witnesses>,
    tape: Mutex<Tape>,
}

impl Witnesses for TapedWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        args: &Value,
        private_state: &Value,
    ) -> Result<WitnessResult> {
        let mut tape = self
            .tape
            .lock()
            .map_err(|_| IrDriverError::Witness("witness tape lock poisoned".to_owned()))?;
        if let Some(recorded) = tape.recorded.get(tape.replayed) {
            // A run is deterministic up to the call that stopped the
            // previous one, so a replay that disagrees is a bug in the
            // executor rather than in the host's witnesses.
            if recorded.name != witness_name
                || &recorded.args != args
                || &recorded.private_state != private_state
            {
                return Err(IrDriverError::Witness(format!(
                    "re-running the call tree reached witness '{witness_name}' where the \
                     previous run called '{}'",
                    recorded.name
                )));
            }
            let result = recorded.result.clone();
            tape.replayed += 1;
            return Ok(result);
        }
        let result = self.inner.invoke(witness_name, args, private_state)?;
        tape.recorded.push(RecordedWitness {
            name: witness_name.to_owned(),
            args: args.clone(),
            private_state: private_state.clone(),
            result: result.clone(),
        });
        tape.replayed += 1;
        Ok(result)
    }
}

/// The witnesses a callee runs with. A callee has no private state, so
/// it may make coin operations (whose kernel hooks are witnesses in the
/// IR) and nothing else, as in compact-runtime.
#[derive(Debug)]
pub(crate) struct CalleeWitnesses {
    pub(crate) callee: ContractAddress,
}

impl Witnesses for CalleeWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &Value,
        private_state: &Value,
    ) -> Result<WitnessResult> {
        match witness_name {
            "createZswapInput" | "createZswapOutput" => Ok(WitnessResult {
                observed: Value::Array(Vec::new()),
                next_private_state: private_state.clone(),
            }),
            other => Err(IrDriverError::CrossContract(format!(
                "callee {} invoked witness '{other}'; a cross-contract callee cannot call \
                 witnesses",
                crate::state::contract_address_to_hex(&self.callee)
            ))),
        }
    }
}

/// `sha256` of a tagged-serialized verifier key: compact-runtime's
/// `verifierKeyHashOf`, and the digest a contract key location embeds.
fn verifier_key_hash(bytes: &[u8]) -> [u8; 32] {
    Sha256::digest(bytes).into()
}

fn deployed_verifier_key_hash(
    state: &ContractState<InMemoryDB>,
    circuit: &str,
) -> Option<[u8; 32]> {
    let entry: EntryPointBuf = circuit.as_bytes().into();
    let op = state.operations.get(&entry)?;
    moonproof_ledger::operation_verifier_key_bytes(&op).map(|vk| verifier_key_hash(&vk))
}

/// The resolved code is the code deployed at the address: the called
/// circuit's key matches the deployed one, and so does every other
/// circuit the two sides share.
///
/// When both the deployed operation and the resolved module carry no
/// verifier keys (as in an offline simulator running from embedded
/// `contract.mpir` without `.verifier` files on disk), the operation's
/// presence is still required and [`check_conformance`] still verifies the
/// circuit signature.
pub(crate) fn check_implementation(
    callee: &CalleeContract,
    circuit: &str,
    describe: &dyn Fn() -> String,
) -> Result<()> {
    let entry: EntryPointBuf = circuit.as_bytes().into();
    let op = callee.state.operations.get(&entry).ok_or_else(|| {
        IrDriverError::CrossContract(format!(
            "{}: the deployed contract has no operation for this circuit",
            describe()
        ))
    })?;
    let Some(deployed) =
        moonproof_ledger::operation_verifier_key_bytes(&op).map(|vk| verifier_key_hash(&vk))
    else {
        if callee.verifier_keys.is_empty() {
            return Ok(());
        }
        return Err(IrDriverError::CrossContract(format!(
            "{}: the deployed contract has no operation for this circuit, or its operation \
             carries no verifier key",
            describe()
        )));
    };
    let expected = callee.verifier_keys.get(circuit).ok_or_else(|| {
        IrDriverError::CrossContract(format!(
            "{}: the resolved code carries no verifier key for circuit '{circuit}', but the \
             deployed contract's is {}",
            describe(),
            hex::encode(deployed)
        ))
    })?;
    let mismatch = |name: &str, expected: [u8; 32], actual: [u8; 32]| {
        IrDriverError::CrossContract(format!(
            "{}: the verifier key for circuit '{name}' is {} in the resolved code but {} on \
             chain",
            describe(),
            hex::encode(expected),
            hex::encode(actual)
        ))
    };
    let expected = verifier_key_hash(expected.as_bytes());
    if expected != deployed {
        return Err(mismatch(circuit, expected, deployed));
    }
    for (name, key) in &callee.verifier_keys {
        if name == circuit {
            continue;
        }
        if let Some(deployed) = deployed_verifier_key_hash(&callee.state, name) {
            let expected = verifier_key_hash(key.as_bytes());
            if expected != deployed {
                return Err(mismatch(name, expected, deployed));
            }
        }
    }
    Ok(())
}

/// The resolved code implements every circuit the caller's contract
/// type declares, each provable and with the declared signature
/// (compact-runtime's `checkConformance`).
pub(crate) fn check_conformance(
    declared: &[ContractCircuitSig],
    callee: &MoonIr,
    describe: &dyn Fn() -> String,
) -> Result<()> {
    for sig in declared {
        let violation = |what: String| {
            IrDriverError::CrossContract(format!(
                "{}: the resolved code does not implement the contract type: {what}",
                describe()
            ))
        };
        let Some(circuit) = callee
            .circuits
            .iter()
            .find(|c| c.exported && c.name == sig.name)
        else {
            return Err(violation(format!(
                "it does not implement circuit '{}'",
                sig.name
            )));
        };
        if !circuit.proof {
            return Err(violation(format!(
                "circuit '{}' is not provable, so it has no proof to match the call",
                sig.name
            )));
        }
        if circuit.arguments.len() != sig.argument_types.len() {
            return Err(violation(format!(
                "circuit '{}' takes a different number of arguments",
                sig.name
            )));
        }
        for (i, (arg, declared)) in circuit
            .arguments
            .iter()
            .zip(&sig.argument_types)
            .enumerate()
        {
            if !signature_types_equal(declared, &arg.arg_type) {
                return Err(violation(format!(
                    "circuit '{}' argument {i} has a different type",
                    sig.name
                )));
            }
        }
        if !signature_types_equal(&sig.result_type, &circuit.result_type) {
            return Err(violation(format!(
                "circuit '{}' returns a different type",
                sig.name
            )));
        }
    }
    Ok(())
}

/// compact-runtime's `signatureTypesEqual`: a vector and a tuple over
/// the same element types are one type, a `Uint` is its bound, and two
/// contract types are equal when they declare the same circuits.
pub(crate) fn signature_types_equal(a: &TypeDescriptor, b: &TypeDescriptor) -> bool {
    use TypeDescriptor as T;
    if let Some(a_elements) = sequence_elements(a) {
        let Some(b_elements) = sequence_elements(b) else {
            return false;
        };
        return a_elements.len() == b_elements.len()
            && a_elements
                .iter()
                .zip(&b_elements)
                .all(|(x, y)| signature_types_equal(x, y));
    }
    match (a, b) {
        (T::Uint { maxval: x, .. }, T::Uint { maxval: y, .. }) => x == y,
        (
            T::Enum {
                name: n1,
                elements: e1,
            },
            T::Enum {
                name: n2,
                elements: e2,
            },
        ) => n1 == n2 && e1 == e2,
        (
            T::Struct {
                name: n1,
                elements: e1,
            },
            T::Struct {
                name: n2,
                elements: e2,
            },
        ) => {
            n1 == n2
                && e1.len() == e2.len()
                && e1.iter().zip(e2).all(|(x, y)| {
                    x.name == y.name && signature_types_equal(&x.field_type, &y.field_type)
                })
        }
        (T::Alias { name: n1, of: o1 }, T::Alias { name: n2, of: o2 }) => {
            n1 == n2 && signature_types_equal(o1, o2)
        }
        (T::Contract { circuits: c1, .. }, T::Contract { circuits: c2, .. }) => {
            c1.len() == c2.len()
                && c1.iter().all(|x| {
                    c2.iter().any(|y| {
                        x.name == y.name
                            && x.argument_types.len() == y.argument_types.len()
                            && x.argument_types
                                .iter()
                                .zip(&y.argument_types)
                                .all(|(p, q)| signature_types_equal(p, q))
                            && signature_types_equal(&x.result_type, &y.result_type)
                    })
                })
        }
        _ => a == b,
    }
}

fn sequence_elements(t: &TypeDescriptor) -> Option<Vec<&TypeDescriptor>> {
    match t {
        TypeDescriptor::Vector { length, elt_type } => {
            Some(std::iter::repeat_n(elt_type.as_ref(), *length as usize).collect())
        }
        TypeDescriptor::Tuple { types } => Some(types.iter().collect()),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_runtime_ir::ir::{IntLit, StructField};

    fn uint(max: u128, bytes: Option<u32>) -> TypeDescriptor {
        TypeDescriptor::Uint {
            maxval: IntLit::from_u128(max),
            alignment_bytes: bytes,
        }
    }

    #[test]
    fn a_vector_and_a_tuple_over_the_same_elements_are_one_type() {
        let vector = TypeDescriptor::Vector {
            length: 2,
            elt_type: Box::new(TypeDescriptor::Field),
        };
        let tuple = TypeDescriptor::Tuple {
            types: vec![TypeDescriptor::Field, TypeDescriptor::Field],
        };
        assert!(signature_types_equal(&vector, &tuple));
        assert!(signature_types_equal(&tuple, &vector));
        let shorter = TypeDescriptor::Tuple {
            types: vec![TypeDescriptor::Field],
        };
        assert!(!signature_types_equal(&vector, &shorter));
        assert!(!signature_types_equal(&vector, &TypeDescriptor::Field));
    }

    #[test]
    fn a_uint_is_its_bound() {
        assert!(signature_types_equal(&uint(255, Some(1)), &uint(255, None)));
        assert!(!signature_types_equal(&uint(255, None), &uint(65535, None)));
    }

    #[test]
    fn structs_compare_by_name_and_fields() {
        let s = |name: &str, field: &str| TypeDescriptor::Struct {
            name: name.to_owned(),
            elements: vec![StructField {
                name: field.to_owned(),
                field_type: TypeDescriptor::Field,
            }],
        };
        assert!(signature_types_equal(&s("P", "x"), &s("P", "x")));
        assert!(!signature_types_equal(&s("P", "x"), &s("Q", "x")));
        assert!(!signature_types_equal(&s("P", "x"), &s("P", "y")));
    }

    #[test]
    fn contract_types_compare_by_circuits_not_name() {
        let c = |name: &str, result: TypeDescriptor| TypeDescriptor::Contract {
            name: name.to_owned(),
            circuits: vec![ContractCircuitSig {
                name: "add".to_owned(),
                argument_types: vec![TypeDescriptor::Field],
                result_type: result,
            }],
        };
        assert!(signature_types_equal(
            &c("A", TypeDescriptor::Field),
            &c("B", TypeDescriptor::Field)
        ));
        assert!(!signature_types_equal(
            &c("A", TypeDescriptor::Field),
            &c("A", TypeDescriptor::Boolean)
        ));
    }

    #[test]
    fn replayed_witnesses_are_not_asked_again() {
        #[derive(Debug, Default)]
        struct Counting(Mutex<u32>);
        impl Witnesses for Counting {
            fn invoke(&self, _: &str, _: &Value, state: &Value) -> Result<WitnessResult> {
                let mut n = self.0.lock().unwrap();
                *n += 1;
                Ok(WitnessResult {
                    observed: Value::Int(i128::from(*n)),
                    next_private_state: state.clone(),
                })
            }
        }
        let host = Arc::new(Counting::default());
        let mut session = CrossContractSession::new();
        let seed = <StdRng as rand::SeedableRng>::seed_from_u64(1);

        let (_, taped) = session.start_run(host.clone(), seed.clone());
        let first = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
        session.finish_run(&taped).unwrap();

        let (_, taped) = session.start_run(host.clone(), seed);
        let replayed = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
        let fresh = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
        assert_eq!(replayed.observed, first.observed);
        assert_eq!(fresh.observed, Value::Int(2));
        assert_eq!(*host.0.lock().unwrap(), 2);
    }

    #[test]
    fn a_replay_that_diverges_is_refused() {
        let mut session = CrossContractSession::new();
        let seed = <StdRng as rand::SeedableRng>::seed_from_u64(1);
        let host: Arc<dyn Witnesses> = Arc::new(CalleeWitnesses {
            callee: ContractAddress::default(),
        });
        let (_, taped) = session.start_run(host.clone(), seed.clone());
        taped
            .invoke("createZswapOutput", &Value::Null, &Value::Null)
            .unwrap();
        session.finish_run(&taped).unwrap();
        let (_, taped) = session.start_run(host, seed);
        assert!(matches!(
            taped.invoke("createZswapInput", &Value::Null, &Value::Null),
            Err(IrDriverError::Witness(_))
        ));
    }

    #[test]
    fn a_callee_may_only_make_coin_operations() {
        let w = CalleeWitnesses {
            callee: ContractAddress::default(),
        };
        assert!(w
            .invoke("createZswapOutput", &Value::Null, &Value::Null)
            .is_ok());
        assert!(matches!(
            w.invoke("secretKey", &Value::Null, &Value::Null),
            Err(IrDriverError::CrossContract(_))
        ));
    }
}