Skip to main content

moonproof_runtime/
cross_contract.rs

1//! Cross-contract calls: a circuit that calls a circuit of another
2//! deployed contract.
3//!
4//! The caller's IR names the callee's contract type and circuit; the
5//! callee's code and deployed state come from the host, which binds
6//! each address it is asked about to a [`CalleeContract`]. Execution
7//! follows compact-runtime 0.21's `crossContractCall`: the callee runs
8//! against its deployed state with no witnesses of its own, and the
9//! caller records the callee's result and a fresh communication
10//! commitment randomness as private transcript outputs, then claims the
11//! call through `kernel.claimContractCall`.
12//!
13//! The interpreter is synchronous and the callee's state lives on
14//! chain, so a run that reaches an address the session has no binding
15//! for stops with [`CallTreeOutcome::CalleeRequired`]. The host binds
16//! it and runs again. Witness results from earlier runs are replayed,
17//! so the host's witnesses fire once per call site across all runs, as
18//! they would in a single run.
19
20use std::collections::HashMap;
21use std::sync::{Arc, Mutex};
22
23use moonproof_ledger::base_crypto::fab::AlignedValue;
24use moonproof_ledger::coin_structure::contract::ContractAddress;
25use moonproof_ledger::onchain_runtime::ops::Op;
26use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
27use moonproof_ledger::onchain_runtime::state::{ContractState, EntryPointBuf};
28use moonproof_ledger::storage::db::InMemoryDB;
29use moonproof_ledger::transient_crypto::curve::Fr;
30use moonproof_runtime_ir::ir::{ContractCircuitSig, MoonIr, TypeDescriptor};
31use moonproof_runtime_ir::RuntimeValue as Value;
32use rand::rngs::StdRng;
33use sha2::{Digest, Sha256};
34
35use crate::executable::ExecuteCircuitResult;
36use crate::ir::error::{IrDriverError, Result};
37use crate::ir::index::IrIndex;
38use crate::ir::witnesses::{WitnessResult, Witnesses};
39use crate::types::VerifierKey;
40use crate::zswap_local::CompactZswapLocalState;
41
42/// The code deployed at a callee address and its deployed state.
43#[derive(Debug, Clone)]
44pub struct CalleeContract {
45    /// The callee's runtime IR.
46    pub ir: Arc<MoonIr>,
47    /// The callee's state at the block the transaction is built against.
48    pub state: ContractState<InMemoryDB>,
49    /// The verifier keys the callee's code was compiled to, by circuit
50    /// name. A call is bound only when the deployed operation's key
51    /// matches the called circuit's, and every other circuit both sides
52    /// have agrees too (compact-runtime's `checkImplementation`).
53    pub verifier_keys: HashMap<String, VerifierKey>,
54}
55
56/// One call to a callee circuit made while executing a call tree.
57#[derive(Debug, Clone)]
58pub struct CalleeCall {
59    pub contract_address: ContractAddress,
60    /// The contract whose circuit made the call.
61    pub caller: ContractAddress,
62    pub circuit_id: String,
63    /// The callee's state when the call began: its deployed state on
64    /// the first call to it, the state an earlier call left otherwise.
65    pub initial_contract_state: ContractState<InMemoryDB>,
66    pub next_contract_state: ContractState<InMemoryDB>,
67    pub input: AlignedValue,
68    pub output: AlignedValue,
69    pub public_transcript: Vec<Op<ResultModeGather, InMemoryDB>>,
70    pub popeq_read_results: Vec<AlignedValue>,
71    pub private_transcript_outputs: Vec<AlignedValue>,
72    /// The callee's coin operations so far, accumulated across every
73    /// call to the same address in the tree.
74    pub zswap_local_state: CompactZswapLocalState,
75    /// The randomness the caller committed to this call's input and
76    /// output with. The call's proof must reuse it.
77    pub communication_commitment_rand: Fr,
78    /// What the callee claimed and moved.
79    pub effects: moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
80}
81
82/// A completed call tree.
83#[derive(Debug, Clone)]
84pub struct CallTreeResult {
85    /// The circuit the host called.
86    pub root: ExecuteCircuitResult,
87    /// Every cross-contract call, in the order the calls returned:
88    /// a callee precedes its caller, so the root's own call, were it
89    /// listed, would come last.
90    pub callees: Vec<CalleeCall>,
91}
92
93/// The outcome of one run of a call tree.
94#[derive(Debug, Clone)]
95pub enum CallTreeOutcome {
96    Executed(Box<CallTreeResult>),
97    /// The run reached a call to an address the session has no binding
98    /// for. Bind it with [`CrossContractSession::bind_callee`] and run
99    /// again.
100    CalleeRequired(ContractAddress),
101}
102
103#[derive(Debug, Clone)]
104struct RecordedWitness {
105    name: String,
106    args: Value,
107    private_state: Value,
108    result: WitnessResult,
109}
110
111/// The state a call tree keeps between runs: the callees bound so far
112/// and the witness results already observed.
113#[derive(Debug, Default)]
114pub struct CrossContractSession {
115    callees: HashMap<ContractAddress, Arc<CalleeContract>>,
116    callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
117    witness_tape: Vec<RecordedWitness>,
118}
119
120impl CrossContractSession {
121    #[must_use]
122    pub fn new() -> Self {
123        Self::default()
124    }
125
126    pub fn bind_callee(&mut self, address: ContractAddress, callee: CalleeContract) {
127        let index = Arc::new(IrIndex::build(&callee.ir));
128        self.callees.insert(address, Arc::new(callee));
129        self.callee_indices.insert(address, index);
130    }
131
132    #[must_use]
133    pub fn callee(&self, address: &ContractAddress) -> Option<&CalleeContract> {
134        self.callees.get(address).map(AsRef::as_ref)
135    }
136
137    pub(crate) fn start_run(
138        &mut self,
139        witnesses: Arc<dyn Witnesses>,
140        rng: StdRng,
141    ) -> (CallTreeRun, Arc<TapedWitnesses>) {
142        let taped = Arc::new(TapedWitnesses {
143            inner: witnesses,
144            tape: Mutex::new(Tape {
145                recorded: std::mem::take(&mut self.witness_tape),
146                replayed: 0,
147            }),
148        });
149        let run = CallTreeRun {
150            callees: self.callees.clone(),
151            callee_indices: self.callee_indices.clone(),
152            states: HashMap::new(),
153            zswap: HashMap::new(),
154            active: Vec::new(),
155            calls: Vec::new(),
156            required: None,
157            rng,
158        };
159        (run, taped)
160    }
161
162    pub(crate) fn finish_run(&mut self, taped: &TapedWitnesses) -> Result<()> {
163        let mut tape = taped
164            .tape
165            .lock()
166            .map_err(|_| IrDriverError::Witness("witness tape lock poisoned".to_owned()))?;
167        self.witness_tape = std::mem::take(&mut tape.recorded);
168        Ok(())
169    }
170}
171
172/// Per-run bookkeeping the interpreter threads through every frame of a
173/// call tree.
174#[derive(Debug)]
175pub struct CallTreeRun {
176    pub(crate) callees: HashMap<ContractAddress, Arc<CalleeContract>>,
177    pub(crate) callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
178    /// Callee states as earlier calls in this run left them.
179    pub(crate) states: HashMap<ContractAddress, ContractState<InMemoryDB>>,
180    pub(crate) zswap: HashMap<ContractAddress, CompactZswapLocalState>,
181    /// The contracts executing, the root first.
182    pub(crate) active: Vec<ContractAddress>,
183    pub(crate) calls: Vec<CalleeCall>,
184    pub(crate) required: Option<ContractAddress>,
185    pub(crate) rng: StdRng,
186}
187
188#[derive(Debug)]
189struct Tape {
190    recorded: Vec<RecordedWitness>,
191    replayed: usize,
192}
193
194/// The root's witnesses, recording each result so a later run of the
195/// same tree replays it instead of asking the host again.
196#[derive(Debug)]
197pub(crate) struct TapedWitnesses {
198    inner: Arc<dyn Witnesses>,
199    tape: Mutex<Tape>,
200}
201
202impl Witnesses for TapedWitnesses {
203    fn invoke(
204        &self,
205        witness_name: &str,
206        args: &Value,
207        private_state: &Value,
208    ) -> Result<WitnessResult> {
209        let mut tape = self
210            .tape
211            .lock()
212            .map_err(|_| IrDriverError::Witness("witness tape lock poisoned".to_owned()))?;
213        if let Some(recorded) = tape.recorded.get(tape.replayed) {
214            // A run is deterministic up to the call that stopped the
215            // previous one, so a replay that disagrees is a bug in the
216            // executor rather than in the host's witnesses.
217            if recorded.name != witness_name
218                || &recorded.args != args
219                || &recorded.private_state != private_state
220            {
221                return Err(IrDriverError::Witness(format!(
222                    "re-running the call tree reached witness '{witness_name}' where the \
223                     previous run called '{}'",
224                    recorded.name
225                )));
226            }
227            let result = recorded.result.clone();
228            tape.replayed += 1;
229            return Ok(result);
230        }
231        let result = self.inner.invoke(witness_name, args, private_state)?;
232        tape.recorded.push(RecordedWitness {
233            name: witness_name.to_owned(),
234            args: args.clone(),
235            private_state: private_state.clone(),
236            result: result.clone(),
237        });
238        tape.replayed += 1;
239        Ok(result)
240    }
241}
242
243/// The witnesses a callee runs with. A callee has no private state, so
244/// it may make coin operations (whose kernel hooks are witnesses in the
245/// IR) and nothing else, as in compact-runtime.
246#[derive(Debug)]
247pub(crate) struct CalleeWitnesses {
248    pub(crate) callee: ContractAddress,
249}
250
251impl Witnesses for CalleeWitnesses {
252    fn invoke(
253        &self,
254        witness_name: &str,
255        _args: &Value,
256        private_state: &Value,
257    ) -> Result<WitnessResult> {
258        match witness_name {
259            "createZswapInput" | "createZswapOutput" => Ok(WitnessResult {
260                observed: Value::Array(Vec::new()),
261                next_private_state: private_state.clone(),
262            }),
263            other => Err(IrDriverError::CrossContract(format!(
264                "callee {} invoked witness '{other}'; a cross-contract callee cannot call \
265                 witnesses",
266                crate::state::contract_address_to_hex(&self.callee)
267            ))),
268        }
269    }
270}
271
272/// `sha256` of a tagged-serialized verifier key: compact-runtime's
273/// `verifierKeyHashOf`, and the digest a contract key location embeds.
274fn verifier_key_hash(bytes: &[u8]) -> [u8; 32] {
275    Sha256::digest(bytes).into()
276}
277
278fn deployed_verifier_key_hash(
279    state: &ContractState<InMemoryDB>,
280    circuit: &str,
281) -> Option<[u8; 32]> {
282    let entry: EntryPointBuf = circuit.as_bytes().into();
283    let op = state.operations.get(&entry)?;
284    moonproof_ledger::operation_verifier_key_bytes(&op).map(|vk| verifier_key_hash(&vk))
285}
286
287/// The resolved code is the code deployed at the address: the called
288/// circuit's key matches the deployed one, and so does every other
289/// circuit the two sides share.
290///
291/// When both the deployed operation and the resolved module carry no
292/// verifier keys (as in an offline simulator running from embedded
293/// `contract.mpir` without `.verifier` files on disk), the operation's
294/// presence is still required and [`check_conformance`] still verifies the
295/// circuit signature.
296pub(crate) fn check_implementation(
297    callee: &CalleeContract,
298    circuit: &str,
299    describe: &dyn Fn() -> String,
300) -> Result<()> {
301    let entry: EntryPointBuf = circuit.as_bytes().into();
302    let op = callee.state.operations.get(&entry).ok_or_else(|| {
303        IrDriverError::CrossContract(format!(
304            "{}: the deployed contract has no operation for this circuit",
305            describe()
306        ))
307    })?;
308    let Some(deployed) =
309        moonproof_ledger::operation_verifier_key_bytes(&op).map(|vk| verifier_key_hash(&vk))
310    else {
311        if callee.verifier_keys.is_empty() {
312            return Ok(());
313        }
314        return Err(IrDriverError::CrossContract(format!(
315            "{}: the deployed contract has no operation for this circuit, or its operation \
316             carries no verifier key",
317            describe()
318        )));
319    };
320    let expected = callee.verifier_keys.get(circuit).ok_or_else(|| {
321        IrDriverError::CrossContract(format!(
322            "{}: the resolved code carries no verifier key for circuit '{circuit}', but the \
323             deployed contract's is {}",
324            describe(),
325            hex::encode(deployed)
326        ))
327    })?;
328    let mismatch = |name: &str, expected: [u8; 32], actual: [u8; 32]| {
329        IrDriverError::CrossContract(format!(
330            "{}: the verifier key for circuit '{name}' is {} in the resolved code but {} on \
331             chain",
332            describe(),
333            hex::encode(expected),
334            hex::encode(actual)
335        ))
336    };
337    let expected = verifier_key_hash(expected.as_bytes());
338    if expected != deployed {
339        return Err(mismatch(circuit, expected, deployed));
340    }
341    for (name, key) in &callee.verifier_keys {
342        if name == circuit {
343            continue;
344        }
345        if let Some(deployed) = deployed_verifier_key_hash(&callee.state, name) {
346            let expected = verifier_key_hash(key.as_bytes());
347            if expected != deployed {
348                return Err(mismatch(name, expected, deployed));
349            }
350        }
351    }
352    Ok(())
353}
354
355/// The resolved code implements every circuit the caller's contract
356/// type declares, each provable and with the declared signature
357/// (compact-runtime's `checkConformance`).
358pub(crate) fn check_conformance(
359    declared: &[ContractCircuitSig],
360    callee: &MoonIr,
361    describe: &dyn Fn() -> String,
362) -> Result<()> {
363    for sig in declared {
364        let violation = |what: String| {
365            IrDriverError::CrossContract(format!(
366                "{}: the resolved code does not implement the contract type: {what}",
367                describe()
368            ))
369        };
370        let Some(circuit) = callee
371            .circuits
372            .iter()
373            .find(|c| c.exported && c.name == sig.name)
374        else {
375            return Err(violation(format!(
376                "it does not implement circuit '{}'",
377                sig.name
378            )));
379        };
380        if !circuit.proof {
381            return Err(violation(format!(
382                "circuit '{}' is not provable, so it has no proof to match the call",
383                sig.name
384            )));
385        }
386        if circuit.arguments.len() != sig.argument_types.len() {
387            return Err(violation(format!(
388                "circuit '{}' takes a different number of arguments",
389                sig.name
390            )));
391        }
392        for (i, (arg, declared)) in circuit
393            .arguments
394            .iter()
395            .zip(&sig.argument_types)
396            .enumerate()
397        {
398            if !signature_types_equal(declared, &arg.arg_type) {
399                return Err(violation(format!(
400                    "circuit '{}' argument {i} has a different type",
401                    sig.name
402                )));
403            }
404        }
405        if !signature_types_equal(&sig.result_type, &circuit.result_type) {
406            return Err(violation(format!(
407                "circuit '{}' returns a different type",
408                sig.name
409            )));
410        }
411    }
412    Ok(())
413}
414
415/// compact-runtime's `signatureTypesEqual`: a vector and a tuple over
416/// the same element types are one type, a `Uint` is its bound, and two
417/// contract types are equal when they declare the same circuits.
418pub(crate) fn signature_types_equal(a: &TypeDescriptor, b: &TypeDescriptor) -> bool {
419    use TypeDescriptor as T;
420    if let Some(a_elements) = sequence_elements(a) {
421        let Some(b_elements) = sequence_elements(b) else {
422            return false;
423        };
424        return a_elements.len() == b_elements.len()
425            && a_elements
426                .iter()
427                .zip(&b_elements)
428                .all(|(x, y)| signature_types_equal(x, y));
429    }
430    match (a, b) {
431        (T::Uint { maxval: x, .. }, T::Uint { maxval: y, .. }) => x == y,
432        (
433            T::Enum {
434                name: n1,
435                elements: e1,
436            },
437            T::Enum {
438                name: n2,
439                elements: e2,
440            },
441        ) => n1 == n2 && e1 == e2,
442        (
443            T::Struct {
444                name: n1,
445                elements: e1,
446            },
447            T::Struct {
448                name: n2,
449                elements: e2,
450            },
451        ) => {
452            n1 == n2
453                && e1.len() == e2.len()
454                && e1.iter().zip(e2).all(|(x, y)| {
455                    x.name == y.name && signature_types_equal(&x.field_type, &y.field_type)
456                })
457        }
458        (T::Alias { name: n1, of: o1 }, T::Alias { name: n2, of: o2 }) => {
459            n1 == n2 && signature_types_equal(o1, o2)
460        }
461        (T::Contract { circuits: c1, .. }, T::Contract { circuits: c2, .. }) => {
462            c1.len() == c2.len()
463                && c1.iter().all(|x| {
464                    c2.iter().any(|y| {
465                        x.name == y.name
466                            && x.argument_types.len() == y.argument_types.len()
467                            && x.argument_types
468                                .iter()
469                                .zip(&y.argument_types)
470                                .all(|(p, q)| signature_types_equal(p, q))
471                            && signature_types_equal(&x.result_type, &y.result_type)
472                    })
473                })
474        }
475        _ => a == b,
476    }
477}
478
479fn sequence_elements(t: &TypeDescriptor) -> Option<Vec<&TypeDescriptor>> {
480    match t {
481        TypeDescriptor::Vector { length, elt_type } => {
482            Some(std::iter::repeat_n(elt_type.as_ref(), *length as usize).collect())
483        }
484        TypeDescriptor::Tuple { types } => Some(types.iter().collect()),
485        _ => None,
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use moonproof_runtime_ir::ir::{IntLit, StructField};
493
494    fn uint(max: u128, bytes: Option<u32>) -> TypeDescriptor {
495        TypeDescriptor::Uint {
496            maxval: IntLit::from_u128(max),
497            alignment_bytes: bytes,
498        }
499    }
500
501    #[test]
502    fn a_vector_and_a_tuple_over_the_same_elements_are_one_type() {
503        let vector = TypeDescriptor::Vector {
504            length: 2,
505            elt_type: Box::new(TypeDescriptor::Field),
506        };
507        let tuple = TypeDescriptor::Tuple {
508            types: vec![TypeDescriptor::Field, TypeDescriptor::Field],
509        };
510        assert!(signature_types_equal(&vector, &tuple));
511        assert!(signature_types_equal(&tuple, &vector));
512        let shorter = TypeDescriptor::Tuple {
513            types: vec![TypeDescriptor::Field],
514        };
515        assert!(!signature_types_equal(&vector, &shorter));
516        assert!(!signature_types_equal(&vector, &TypeDescriptor::Field));
517    }
518
519    #[test]
520    fn a_uint_is_its_bound() {
521        assert!(signature_types_equal(&uint(255, Some(1)), &uint(255, None)));
522        assert!(!signature_types_equal(&uint(255, None), &uint(65535, None)));
523    }
524
525    #[test]
526    fn structs_compare_by_name_and_fields() {
527        let s = |name: &str, field: &str| TypeDescriptor::Struct {
528            name: name.to_owned(),
529            elements: vec![StructField {
530                name: field.to_owned(),
531                field_type: TypeDescriptor::Field,
532            }],
533        };
534        assert!(signature_types_equal(&s("P", "x"), &s("P", "x")));
535        assert!(!signature_types_equal(&s("P", "x"), &s("Q", "x")));
536        assert!(!signature_types_equal(&s("P", "x"), &s("P", "y")));
537    }
538
539    #[test]
540    fn contract_types_compare_by_circuits_not_name() {
541        let c = |name: &str, result: TypeDescriptor| TypeDescriptor::Contract {
542            name: name.to_owned(),
543            circuits: vec![ContractCircuitSig {
544                name: "add".to_owned(),
545                argument_types: vec![TypeDescriptor::Field],
546                result_type: result,
547            }],
548        };
549        assert!(signature_types_equal(
550            &c("A", TypeDescriptor::Field),
551            &c("B", TypeDescriptor::Field)
552        ));
553        assert!(!signature_types_equal(
554            &c("A", TypeDescriptor::Field),
555            &c("A", TypeDescriptor::Boolean)
556        ));
557    }
558
559    #[test]
560    fn replayed_witnesses_are_not_asked_again() {
561        #[derive(Debug, Default)]
562        struct Counting(Mutex<u32>);
563        impl Witnesses for Counting {
564            fn invoke(&self, _: &str, _: &Value, state: &Value) -> Result<WitnessResult> {
565                let mut n = self.0.lock().unwrap();
566                *n += 1;
567                Ok(WitnessResult {
568                    observed: Value::Int(i128::from(*n)),
569                    next_private_state: state.clone(),
570                })
571            }
572        }
573        let host = Arc::new(Counting::default());
574        let mut session = CrossContractSession::new();
575        let seed = <StdRng as rand::SeedableRng>::seed_from_u64(1);
576
577        let (_, taped) = session.start_run(host.clone(), seed.clone());
578        let first = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
579        session.finish_run(&taped).unwrap();
580
581        let (_, taped) = session.start_run(host.clone(), seed);
582        let replayed = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
583        let fresh = taped.invoke("w", &Value::Null, &Value::Null).unwrap();
584        assert_eq!(replayed.observed, first.observed);
585        assert_eq!(fresh.observed, Value::Int(2));
586        assert_eq!(*host.0.lock().unwrap(), 2);
587    }
588
589    #[test]
590    fn a_replay_that_diverges_is_refused() {
591        let mut session = CrossContractSession::new();
592        let seed = <StdRng as rand::SeedableRng>::seed_from_u64(1);
593        let host: Arc<dyn Witnesses> = Arc::new(CalleeWitnesses {
594            callee: ContractAddress::default(),
595        });
596        let (_, taped) = session.start_run(host.clone(), seed.clone());
597        taped
598            .invoke("createZswapOutput", &Value::Null, &Value::Null)
599            .unwrap();
600        session.finish_run(&taped).unwrap();
601        let (_, taped) = session.start_run(host, seed);
602        assert!(matches!(
603            taped.invoke("createZswapInput", &Value::Null, &Value::Null),
604            Err(IrDriverError::Witness(_))
605        ));
606    }
607
608    #[test]
609    fn a_callee_may_only_make_coin_operations() {
610        let w = CalleeWitnesses {
611            callee: ContractAddress::default(),
612        };
613        assert!(w
614            .invoke("createZswapOutput", &Value::Null, &Value::Null)
615            .is_ok());
616        assert!(matches!(
617            w.invoke("secretKey", &Value::Null, &Value::Null),
618            Err(IrDriverError::CrossContract(_))
619        ));
620    }
621}