1use 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#[derive(Debug, Clone)]
44pub struct CalleeContract {
45 pub ir: Arc<MoonIr>,
47 pub state: ContractState<InMemoryDB>,
49 pub verifier_keys: HashMap<String, VerifierKey>,
54}
55
56#[derive(Debug, Clone)]
58pub struct CalleeCall {
59 pub contract_address: ContractAddress,
60 pub caller: ContractAddress,
62 pub circuit_id: String,
63 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 pub zswap_local_state: CompactZswapLocalState,
75 pub communication_commitment_rand: Fr,
78 pub effects: moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
80}
81
82#[derive(Debug, Clone)]
84pub struct CallTreeResult {
85 pub root: ExecuteCircuitResult,
87 pub callees: Vec<CalleeCall>,
91}
92
93#[derive(Debug, Clone)]
95pub enum CallTreeOutcome {
96 Executed(Box<CallTreeResult>),
97 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#[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#[derive(Debug)]
175pub struct CallTreeRun {
176 pub(crate) callees: HashMap<ContractAddress, Arc<CalleeContract>>,
177 pub(crate) callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
178 pub(crate) states: HashMap<ContractAddress, ContractState<InMemoryDB>>,
180 pub(crate) zswap: HashMap<ContractAddress, CompactZswapLocalState>,
181 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#[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 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#[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
272fn 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
287pub(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
355pub(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
415pub(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}