use std::collections::BTreeMap;
use std::sync::Arc;
use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::witnesses::WitnessResult;
use moonproof_runtime::{CompactZswapLocalState, IrDriverError, IrExecutable, Witnesses};
use moonproof_runtime_ir::RuntimeValue as Value;
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
#[derive(Debug)]
struct RegistryWitnesses;
impl Witnesses for RegistryWitnesses {
fn invoke(&self, name: &str, _a: &Value, ps: &Value) -> Result<WitnessResult, IrDriverError> {
let observed = match name {
"ageValue" => Value::Int(30),
"emailVerifiedFlag" => Value::Int(1),
"kycLevel" => Value::Int(3),
"personhoodSecret" => Value::Bytes(vec![0x22u8; 32]),
"residentCountry" | "nationalityCode" => Value::Bytes(vec![0x11u8; 32]),
"verifierIdHash" => Value::Bytes(vec![0x33u8; 32]),
"allowedCountryPath" => {
let mut inner = BTreeMap::new();
inner.insert("leaf".to_string(), Value::Bytes(vec![0x11u8; 32]));
let path: Vec<Value> = (0..8)
.map(|_| {
let mut sibling = BTreeMap::new();
sibling.insert("field".to_string(), Value::Bytes(vec![0u8; 32]));
let mut s = BTreeMap::new();
s.insert("sibling".to_string(), Value::Object(sibling));
s.insert("goes_left".to_string(), Value::Bool(false));
Value::Object(s)
})
.collect();
inner.insert("path".to_string(), Value::Array(path));
Value::Object(inner)
}
other => {
return Err(IrDriverError::Witness(format!(
"unexpected witness '{other}'"
)))
}
};
Ok(WitnessResult {
observed,
next_private_state: ps.clone(),
})
}
}
fn zero_pk() -> CoinPublicKey {
CoinPublicKey([0u8; 32])
}
fn ctor_ctx() -> ConstructorContext {
ConstructorContext {
initial_private_state: Value::Null,
initial_zswap_local_state: CompactZswapLocalState::empty(zero_pk()),
coin_public_key: zero_pk(),
signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).unwrap(),
time: None,
}
}
fn owner_either() -> Value {
let b = |v: Vec<u8>| {
let mut m = BTreeMap::new();
m.insert("bytes".to_string(), Value::Bytes(v));
Value::Object(m)
};
let mut o = BTreeMap::new();
o.insert("is_left".to_string(), Value::Bool(true));
o.insert("left".to_string(), Value::Bytes(vec![1u8; 32]));
o.insert("right".to_string(), b(vec![0u8; 32]));
Value::Object(o)
}
fn call_ctx(state: ContractState<InMemoryDB>) -> CircuitCallContext {
CircuitCallContext {
contract_address: ContractAddress(HashOutput([0x77u8; 32])),
contract_state: state,
private_state: Value::Null,
ledger_parameters: INITIAL_PARAMETERS.clone(),
coin_public_key: zero_pk(),
tblock: Timestamp::from_secs(0),
}
}
fn age_args() -> Value {
let mut m = BTreeMap::new();
m.insert("rootHash".to_string(), Value::Bytes(vec![2u8; 32]));
m.insert("threshold".to_string(), Value::Int(21));
Value::Object(m)
}
fn residency_args() -> Value {
let mut m = BTreeMap::new();
m.insert("rootHash".to_string(), Value::Bytes(vec![2u8; 32]));
m.insert("setHash".to_string(), Value::Bytes(vec![3u8; 32]));
Value::Object(m)
}
#[tokio::main]
async fn main() {
#[cfg(feature = "dhat-heap")]
let _profiler = dhat::Profiler::new_heap();
let which = std::env::args().nth(1).unwrap_or_else(|| "light".into());
let n: usize = std::env::args()
.nth(2)
.and_then(|s| s.parse().ok())
.unwrap_or(100);
let cbor = std::fs::read(
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../test-fixtures/contracts/predicate_registry/contract.mpir"),
)
.unwrap();
let exec = IrExecutable::from_cbor_slice(&cbor, Arc::new(RegistryWitnesses)).unwrap();
let init = exec.initialize(ctor_ctx(), owner_either()).await.unwrap();
let state = init.initial_contract_state.clone();
let _ = exec
.execute_circuit("attestAgeGte", call_ctx(state.clone()), age_args())
.await;
for _ in 0..n {
match which.as_str() {
"constructor" => {
let _ = exec.initialize(ctor_ctx(), owner_either()).await.unwrap();
}
"heavy" => {
let _ = exec
.execute_circuit(
"attestResidencyIn",
call_ctx(state.clone()),
residency_args(),
)
.await;
}
"glue" | "ispaused" => {
let _ = exec
.execute_circuit("isPaused", call_ctx(state.clone()), Value::Null)
.await
.unwrap();
}
"all" => {
let _ = exec.initialize(ctor_ctx(), owner_either()).await.unwrap();
let _ = exec
.execute_circuit("attestAgeGte", call_ctx(state.clone()), age_args())
.await;
let _ = exec
.execute_circuit(
"attestResidencyIn",
call_ctx(state.clone()),
residency_args(),
)
.await;
}
_ => {
let _ = exec
.execute_circuit("attestAgeGte", call_ctx(state.clone()), age_args())
.await
.unwrap();
}
}
}
eprintln!("dhat_exec: ran '{which}' × {n}");
}