use std::sync::Arc;
use moonproof_ledger::base_crypto::fab::AlignedValue;
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::signatures::SigningKey;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext, InitializeResult};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrDriverError, IrExecutable, Witnesses};
#[derive(Debug, Default)]
struct GenericWitnesses;
impl Witnesses for GenericWitnesses {
fn invoke(
&self,
witness_name: &str,
_args: &moonproof_runtime_ir::RuntimeValue,
private_state: &moonproof_runtime_ir::RuntimeValue,
) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
let observed = match witness_name {
"tmpCallRand" => moonproof_runtime_ir::RuntimeValue::Bytes(vec![0u8; 32]),
"tmpDoCall" | "createZswapOutput" | "createZswapInput" => {
moonproof_runtime_ir::RuntimeValue::Array(Vec::new())
}
other if other.starts_with("local") || other.starts_with("get") => {
moonproof_runtime_ir::RuntimeValue::Int(0_i128)
}
_ => moonproof_runtime_ir::RuntimeValue::Bytes(vec![0u8; 32]),
};
Ok(moonproof_runtime::witnesses::WitnessResult {
observed,
next_private_state: private_state.clone(),
})
}
}
fn fixture_path(name: &str) -> std::path::PathBuf {
let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.pop();
p.push("runtime-ir");
p.push(format!("tests/fixtures/{name}.cbor"));
p
}
fn dummy_signing_key() -> SigningKey {
moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).expect("32 bytes parse")
}
fn dummy_coin_public_key() -> CoinPublicKey {
CoinPublicKey([0u8; 32])
}
fn dummy_contract_address() -> ContractAddress {
ContractAddress(HashOutput([0x77u8; 32]))
}
async fn initialize(name: &str) -> InitializeResult {
let exec = IrExecutable::from_path(fixture_path(name), Arc::new(GenericWitnesses))
.unwrap_or_else(|e| panic!("{name} IR loads: {e}"));
exec.initialize(
ConstructorContext {
initial_private_state: moonproof_runtime_ir::RuntimeValue::Null,
initial_zswap_local_state: CompactZswapLocalState::empty(dummy_coin_public_key()),
coin_public_key: dummy_coin_public_key(),
signing_key: dummy_signing_key(),
time: None,
},
moonproof_runtime_ir::RuntimeValue::Null,
)
.await
.unwrap_or_else(|e| panic!("{name} initialize: {e}"))
}
#[tokio::test]
async fn ir_composable_burn_initialize_succeeds() {
let _ = initialize("composable_burn").await;
}
#[tokio::test]
async fn ir_composable_inner_initialize_succeeds() {
let _ = initialize("composable_inner").await;
}
#[tokio::test]
async fn ir_composable_relay_initialize_succeeds() {
let _ = initialize("composable_relay").await;
}
#[tokio::test]
async fn ir_composable_inner_set_runs_until_authority_assert() {
let exec =
IrExecutable::from_path(fixture_path("composable_inner"), Arc::new(GenericWitnesses))
.unwrap();
let init = initialize("composable_inner").await;
let call_ctx = CircuitCallContext {
contract_address: dummy_contract_address(),
contract_state: init.initial_contract_state,
private_state: moonproof_runtime_ir::RuntimeValue::Null,
ledger_parameters: INITIAL_PARAMETERS.clone(),
coin_public_key: dummy_coin_public_key(),
tblock: Timestamp::from_secs(0),
};
let f = ::moonproof_runtime_ir::RuntimeValue::String("payload".to_string());
let err = exec
.execute_circuit("set", call_ctx, f)
.await
.expect_err("set should hit the authority assert with a fake secretKey");
let msg = format!("{err}");
assert!(
msg.contains("must be authority") || msg.contains("authority"),
"expected authority-assert failure, got: {msg}"
);
}
#[tokio::test]
async fn ir_composable_burn_advances_state() {
let exec = IrExecutable::from_path(fixture_path("composable_burn"), Arc::new(GenericWitnesses))
.unwrap();
let init = initialize("composable_burn").await;
let coin = {
let mut obj = ::std::collections::BTreeMap::new();
obj.insert(
"nonce".to_string(),
::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x11u8; 32]),
);
obj.insert(
"color".to_string(),
::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x22u8; 32]),
);
obj.insert(
"value".to_string(),
::moonproof_runtime_ir::RuntimeValue::Int(1_000),
);
::moonproof_runtime_ir::RuntimeValue::Object(obj)
};
let call_ctx = CircuitCallContext {
contract_address: dummy_contract_address(),
contract_state: init.initial_contract_state,
private_state: moonproof_runtime_ir::RuntimeValue::Null,
ledger_parameters: INITIAL_PARAMETERS.clone(),
coin_public_key: dummy_coin_public_key(),
tblock: Timestamp::from_secs(0),
};
let result = exec
.execute_circuit("burn", call_ctx, coin)
.await
.expect("composable_burn.burn executes");
assert!(
result.public_transcript.len() >= 9,
"burn must emit ≥9 public-transcript ops; got {}",
result.public_transcript.len()
);
assert_eq!(
result.popeq_read_results.len(),
1,
"burn's kernel.self() read must produce exactly one popeq result"
);
assert_eq!(
result.private_transcript_outputs.len(),
1,
"burn's createZswapOutput witness must fire exactly once"
);
let _ = AlignedValue::from(0u8); }
#[tokio::test]
async fn ir_composable_inner_set_advances_state_with_matching_authority() {
use moonproof_ledger::base_crypto::fab::{
Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
};
use moonproof_ledger::base_crypto::hash::{persistent_commit, HashOutput};
use moonproof_ledger::onchain_runtime::context::QueryContext;
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::onchain_runtime::ops::Op;
use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
use moonproof_ledger::onchain_runtime::state::{AlignedValueChecked, StateValue};
use moonproof_ledger::storage::arena::Sp;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
let value_av = AlignedValue::new(
FabValue(vec![ValueAtom(b"mdn:ex:ci".to_vec())]),
Alignment::singleton(AlignmentAtom::Bytes { length: 9 }),
)
.expect("Bytes<9> AlignedValue");
let opening = HashOutput([0u8; 32]);
let HashOutput(expected_authority) =
persistent_commit(&ValueReprAlignedValue(value_av), opening);
let exec =
IrExecutable::from_path(fixture_path("composable_inner"), Arc::new(GenericWitnesses))
.unwrap();
let mut init = initialize("composable_inner").await;
let patch_ops: Vec<Op<ResultModeGather, InMemoryDB>> = vec![
Op::Push {
storage: false,
value: StateValue::Cell(Sp::new(AlignedValueChecked::from(0u8))),
},
Op::Push {
storage: true,
value: StateValue::Cell(Sp::new(
AlignedValueChecked::try_from(AlignedValue::from(expected_authority))
.expect("bytes atoms are always canonical"),
)),
},
Op::Ins {
cached: false,
n: 1.try_into().unwrap(),
},
];
let qctx = QueryContext::new(
init.initial_contract_state.data.clone(),
dummy_contract_address(),
);
let patched = qctx
.query::<ResultModeGather>(&patch_ops, None, &INITIAL_COST_MODEL)
.expect("authority-cell patch ops succeed");
init.initial_contract_state.data = patched.context.state;
let mut before = Vec::new();
moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut before)
.unwrap();
let call_ctx = CircuitCallContext {
contract_address: dummy_contract_address(),
contract_state: init.initial_contract_state,
private_state: moonproof_runtime_ir::RuntimeValue::Null,
ledger_parameters: INITIAL_PARAMETERS.clone(),
coin_public_key: dummy_coin_public_key(),
tblock: Timestamp::from_secs(0),
};
let v_arg = ::moonproof_runtime_ir::RuntimeValue::String("post-authority-payload".to_string());
let result = exec
.execute_circuit("set", call_ctx, v_arg)
.await
.expect("set should succeed once authority matches");
let mut after = Vec::new();
moonproof_ledger::serialize::tagged_serialize(&result.next_contract_state, &mut after).unwrap();
assert_ne!(
before, after,
"composable_inner.set must advance the on-chain `value` field once authority matches"
);
assert!(
after.len() >= before.len() / 2,
"post-set state ({} bytes) shrank suspiciously vs pre-state ({} bytes)",
after.len(),
before.len(),
);
}
#[tokio::test]
async fn ir_composable_relay_send_to_burn_advances_state() {
let exec =
IrExecutable::from_path(fixture_path("composable_relay"), Arc::new(GenericWitnesses))
.unwrap();
let init = initialize("composable_relay").await;
let coin = {
let mut obj = ::std::collections::BTreeMap::new();
obj.insert(
"nonce".to_string(),
::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x11u8; 32]),
);
obj.insert(
"color".to_string(),
::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x22u8; 32]),
);
obj.insert(
"value".to_string(),
::moonproof_runtime_ir::RuntimeValue::Int(1_000),
);
::moonproof_runtime_ir::RuntimeValue::Object(obj)
};
let call_ctx = CircuitCallContext {
contract_address: dummy_contract_address(),
contract_state: init.initial_contract_state,
private_state: moonproof_runtime_ir::RuntimeValue::Null,
ledger_parameters: INITIAL_PARAMETERS.clone(),
coin_public_key: dummy_coin_public_key(),
tblock: Timestamp::from_secs(0),
};
let result = exec
.execute_circuit("send_to_burn", call_ctx, coin)
.await
.expect("composable_relay.send_to_burn executes");
assert!(result.public_transcript.len() >= 20);
assert!(result.popeq_read_results.len() >= 3);
assert!(result.private_transcript_outputs.len() >= 2);
}