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;
#[derive(Debug, Clone)]
pub struct CalleeContract {
pub ir: Arc<MoonIr>,
pub state: ContractState<InMemoryDB>,
pub verifier_keys: HashMap<String, VerifierKey>,
}
#[derive(Debug, Clone)]
pub struct CalleeCall {
pub contract_address: ContractAddress,
pub caller: ContractAddress,
pub circuit_id: String,
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>,
pub zswap_local_state: CompactZswapLocalState,
pub communication_commitment_rand: Fr,
pub effects: moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
}
#[derive(Debug, Clone)]
pub struct CallTreeResult {
pub root: ExecuteCircuitResult,
pub callees: Vec<CalleeCall>,
}
#[derive(Debug, Clone)]
pub enum CallTreeOutcome {
Executed(Box<CallTreeResult>),
CalleeRequired(ContractAddress),
}
#[derive(Debug, Clone)]
struct RecordedWitness {
name: String,
args: Value,
private_state: Value,
result: WitnessResult,
}
#[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(())
}
}
#[derive(Debug)]
pub struct CallTreeRun {
pub(crate) callees: HashMap<ContractAddress, Arc<CalleeContract>>,
pub(crate) callee_indices: HashMap<ContractAddress, Arc<IrIndex>>,
pub(crate) states: HashMap<ContractAddress, ContractState<InMemoryDB>>,
pub(crate) zswap: HashMap<ContractAddress, CompactZswapLocalState>,
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,
}
#[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) {
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)
}
}
#[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)
))),
}
}
}
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))
}
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(())
}
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(())
}
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(_))
));
}
}