use moonproof_ledger::base_crypto::fab::AlignedValue;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::{PublicAddress, TokenType};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::construct::{
partition_transcripts, ContractCallPrototype, PreTranscript,
};
use moonproof_ledger::ledger::structure::{
ContractDeploy, Intent, LedgerParameters, MaintenanceUpdate, ProofPreimageMarker,
};
use moonproof_ledger::ledger::structure::{Transaction, UnshieldedOffer, UtxoOutput, UtxoSpend};
use moonproof_ledger::onchain_runtime::communication_commitment;
use moonproof_ledger::onchain_runtime::context::ClaimedUnshieldedSpendsKey;
use moonproof_ledger::onchain_runtime::context::QueryContext;
use moonproof_ledger::onchain_runtime::ops::Op;
use moonproof_ledger::onchain_runtime::result_mode::{ResultModeGather, ResultModeVerify};
use moonproof_ledger::onchain_runtime::state::{ContractOperation, ContractState};
use moonproof_ledger::onchain_runtime::transcript::Transcript;
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_ledger::zswap::ledger::State as ZswapChainState;
use rand::{CryptoRng, Rng};
use crate::error::{ContractRuntimeError, Result};
use crate::types::CircuitId;
use crate::utils::zswap_utils::{
assert_receives_match_claims, zswap_calls_to_segmented_offer, CompactZswapLocalState,
EncryptionPublicKeyResolver, ZswapCallContribution,
};
#[must_use]
pub fn ttl_one_hour(current_time: Timestamp) -> Timestamp {
current_time + moonproof_ledger::base_crypto::time::Duration::from_secs(60 * 60)
}
pub fn one_intent_at_segment_one<R: Rng + CryptoRng + ?Sized>(
rng: &mut R,
calls: Vec<ContractCallPrototype<InMemoryDB>>,
updates: Vec<MaintenanceUpdate<InMemoryDB>>,
deploys: Vec<ContractDeploy<InMemoryDB>>,
tblock: Timestamp,
) -> moonproof_ledger::storage::storage::HashMap<
u16,
Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
InMemoryDB,
> {
let intents = moonproof_ledger::storage::storage::HashMap::<
u16,
Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
InMemoryDB,
>::new();
intents.insert(
1,
Intent::new(
rng,
None,
None,
calls,
updates,
deploys,
None,
ttl_one_hour(tblock),
),
)
}
pub fn build_contract_deploy<R: Rng + CryptoRng>(
rng: &mut R,
initial_state: ContractState<InMemoryDB>,
) -> Result<(
ContractDeploy<InMemoryDB>,
ContractAddress,
ContractState<InMemoryDB>,
)> {
if let Some(limit) = moonproof_ledger::MAX_CONTRACT_OPERATIONS {
let operations = initial_state.operations.size() as u64;
if operations > limit {
return Err(ContractRuntimeError::Provider {
provider: "ledger_utils::build_contract_deploy",
message: format!(
"contract declares {operations} operations; the ledger accepts at most \
{limit} per contract, so split it into several contracts"
),
});
}
}
let deploy = ContractDeploy::new(rng, initial_state.clone());
let address = deploy.address();
Ok((deploy, address, initial_state))
}
pub fn required_operation(
state: &ContractState<InMemoryDB>,
circuit_id: &CircuitId,
) -> Result<ContractOperation> {
let key: moonproof_ledger::onchain_runtime::state::EntryPointBuf =
circuit_id.as_str().as_bytes().into();
state
.operations
.get(&key)
.map(|op| (*op).clone())
.ok_or_else(|| ContractRuntimeError::Provider {
provider: "ledger_utils::required_operation",
message: format!(
"operation '{}' is undefined for contract state",
circuit_id.as_str()
),
})
}
pub struct ContractCallPrototypeInputs {
pub contract_address: ContractAddress,
pub circuit_id: CircuitId,
pub initial_contract_state: ContractState<InMemoryDB>,
pub input: AlignedValue,
pub output: AlignedValue,
pub public_transcript_ops: Vec<Op<ResultModeGather, InMemoryDB>>,
pub private_transcript_outputs: Vec<AlignedValue>,
pub communication_commitment_rand: Fr,
pub popeq_read_results: Vec<AlignedValue>,
pub ledger_parameters: LedgerParameters,
}
pub fn build_contract_call_prototype(
inputs: ContractCallPrototypeInputs,
) -> Result<moonproof_ledger::ledger::construct::ContractCallPrototype<InMemoryDB>> {
let ledger_parameters = inputs.ledger_parameters;
let call = ContractCallParts {
contract_address: inputs.contract_address,
circuit_id: inputs.circuit_id,
initial_contract_state: inputs.initial_contract_state,
caller: None,
input: inputs.input,
output: inputs.output,
public_transcript_ops: inputs.public_transcript_ops,
private_transcript_outputs: inputs.private_transcript_outputs,
communication_commitment_rand: inputs.communication_commitment_rand,
popeq_read_results: inputs.popeq_read_results,
};
build_contract_call_prototypes(vec![call], &ledger_parameters, Timestamp::from_secs(0))?
.pop()
.ok_or_else(|| ContractRuntimeError::Provider {
provider: "ledger_utils::partition_transcripts",
message: "partition_transcripts returned an empty result vector".to_owned(),
})
}
pub struct ContractCallParts {
pub contract_address: ContractAddress,
pub circuit_id: CircuitId,
pub initial_contract_state: ContractState<InMemoryDB>,
pub caller: Option<ContractAddress>,
pub input: AlignedValue,
pub output: AlignedValue,
pub public_transcript_ops: Vec<Op<ResultModeGather, InMemoryDB>>,
pub private_transcript_outputs: Vec<AlignedValue>,
pub communication_commitment_rand: Fr,
pub popeq_read_results: Vec<AlignedValue>,
}
pub fn build_contract_call_prototypes(
calls: Vec<ContractCallParts>,
ledger_parameters: &LedgerParameters,
tblock: Timestamp,
) -> Result<Vec<moonproof_ledger::ledger::construct::ContractCallPrototype<InMemoryDB>>> {
struct Prepared {
call: ContractCallParts,
op: ContractOperation,
key_location: moonproof_ledger::transient_crypto::proofs::KeyLocation,
}
let mut prepared = Vec::with_capacity(calls.len());
let mut pre_transcripts = Vec::with_capacity(calls.len());
for mut call in calls {
let op = required_operation(&call.initial_contract_state, &call.circuit_id)?;
let location = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
crate::key_location::ContractKeyLocation::for_operation(
call.contract_address,
&call.circuit_id,
&op,
)?
.encode()
} else {
call.circuit_id.as_str().to_owned()
};
let key_location = moonproof_ledger::transient_crypto::proofs::KeyLocation(
std::borrow::Cow::Owned(location),
);
let program = verify_mode_program(
std::mem::take(&mut call.public_transcript_ops),
std::mem::take(&mut call.popeq_read_results),
)?;
let mut context = QueryContext::new(
call.initial_contract_state.data.clone(),
call.contract_address,
);
context.call_context.tblock = tblock;
context.call_context.balance = call.initial_contract_state.balance.clone();
context.call_context.caller = call
.caller
.map(moonproof_ledger::coin_structure::coin::PublicAddress::Contract);
pre_transcripts.push(PreTranscript::<InMemoryDB> {
context,
program,
comm_comm: Some(communication_commitment(
call.input.clone(),
call.output.clone(),
call.communication_commitment_rand,
)),
});
prepared.push(Prepared {
call,
op,
key_location,
});
}
let partitioned = partition_transcripts::<InMemoryDB>(&pre_transcripts, ledger_parameters)
.map_err(|e| ContractRuntimeError::Provider {
provider: "ledger_utils::partition_transcripts",
message: format!("partition_transcripts failed: {e:?}"),
})?;
if partitioned.len() != prepared.len() {
return Err(ContractRuntimeError::Provider {
provider: "ledger_utils::partition_transcripts",
message: format!(
"partition_transcripts returned {} transcript pairs for {} calls",
partitioned.len(),
prepared.len()
),
});
}
Ok(prepared
.into_iter()
.zip(partitioned)
.map(
|(p, (guaranteed_public_transcript, fallible_public_transcript))| {
moonproof_ledger::ledger::construct::ContractCallPrototype {
address: p.call.contract_address,
entry_point: p.call.circuit_id.as_str().as_bytes().into(),
op: p.op,
guaranteed_public_transcript,
fallible_public_transcript,
private_transcript_outputs: p.call.private_transcript_outputs,
input: p.call.input,
output: p.call.output,
communication_commitment_rand: p.call.communication_commitment_rand,
key_location: p.key_location,
}
},
)
.collect())
}
fn verify_mode_program(
ops: Vec<Op<ResultModeGather, InMemoryDB>>,
popeq_read_results: Vec<AlignedValue>,
) -> Result<Vec<Op<ResultModeVerify, InMemoryDB>>> {
let mut popeq_iter = popeq_read_results.into_iter();
let mut popeq_drained = false;
let verify_mode_ops: Vec<Op<ResultModeVerify, InMemoryDB>> = ops
.into_iter()
.map(|op| {
op.translate::<ResultModeVerify, _>(|()| {
if let Some(v) = popeq_iter.next() {
v
} else {
popeq_drained = true;
AlignedValue::from(())
}
})
})
.filter(|op| match op {
Op::Idx { path, .. } => !path.is_empty(),
Op::Ins { n, .. } => *n != 0,
_ => true,
})
.collect();
if popeq_drained {
return Err(ContractRuntimeError::Provider {
provider: "ledger_utils::build_contract_call_prototype",
message: "circuit emitted more Op::Popeq ops than the executable's \
popeq_read_results supplied — every Popeq must be paired \
with a gather-mode read result"
.to_owned(),
});
}
let leftover = popeq_iter.count();
if leftover > 0 {
return Err(ContractRuntimeError::Provider {
provider: "ledger_utils::build_contract_call_prototype",
message: format!(
"executable supplied {leftover} more popeq_read_results than the \
circuit consumed; pair each Op::Popeq with exactly one read result"
),
});
}
Ok(verify_mode_ops)
}
pub fn user_addressed_unshielded_outputs(
transcript: Option<&Transcript<InMemoryDB>>,
) -> Result<Vec<UtxoOutput>> {
let Some(transcript) = transcript else {
return Ok(Vec::new());
};
let mut outputs = Vec::new();
for entry in transcript.effects.claimed_unshielded_spends.iter() {
let (key, value) = &*entry;
let ClaimedUnshieldedSpendsKey(token_type, address) = &**key;
let PublicAddress::User(owner) = address else {
continue;
};
let type_ = match token_type {
TokenType::Unshielded(token) => *token,
TokenType::Dust => continue,
TokenType::Shielded(token) => {
return Err(ContractRuntimeError::Provider {
provider: "ledger_utils::user_addressed_unshielded_outputs",
message: format!(
"a transcript claims an unshielded spend of shielded token {} to a \
user; no unshielded output can carry a shielded token",
hex::encode(token.0 .0)
),
});
}
};
outputs.push(UtxoOutput {
value: **value,
owner: *owner,
type_,
});
}
Ok(outputs)
}
pub struct AssembledCall<'a> {
pub prototype: ContractCallPrototype<InMemoryDB>,
pub zswap_local_state: &'a CompactZswapLocalState,
pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
}
const FIRST_RANDOM_SEGMENT: u16 = 2;
pub fn create_unproven_ledger_call_tx<R: Rng + CryptoRng>(
rng: &mut R,
calls: Vec<AssembledCall<'_>>,
resolver: &EncryptionPublicKeyResolver,
network_id: &str,
ttl: Timestamp,
) -> Result<Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>> {
let segment = rng.gen_range(FIRST_RANDOM_SEGMENT..u16::MAX);
let mut guaranteed_outputs = Vec::new();
let mut fallible_outputs = Vec::new();
for call in &calls {
guaranteed_outputs.extend(user_addressed_unshielded_outputs(
call.prototype.guaranteed_public_transcript.as_ref(),
)?);
fallible_outputs.extend(user_addressed_unshielded_outputs(
call.prototype.fallible_public_transcript.as_ref(),
)?);
}
let contributions: Vec<ZswapCallContribution<'_>> = calls
.iter()
.map(|call| ZswapCallContribution {
contract_address: Some(call.prototype.address),
zswap_local_state: call.zswap_local_state,
zswap_chain_state: call.zswap_chain_state,
partitioned_transcript: (
call.prototype.guaranteed_public_transcript.as_ref(),
call.prototype.fallible_public_transcript.as_ref(),
),
})
.collect();
let offers = zswap_calls_to_segmented_offer(rng, &contributions, resolver, segment)?;
let claims: Vec<_> = contributions
.iter()
.filter_map(|c| c.contract_address.map(|a| (a, c.partitioned_transcript)))
.collect();
assert_receives_match_claims(&claims, &offers)?;
let intent = Intent::new(
rng,
unshielded_offer(guaranteed_outputs),
unshielded_offer(fallible_outputs),
calls.into_iter().map(|call| call.prototype).collect(),
Vec::new(),
Vec::new(),
None,
ttl,
);
let intents = moonproof_ledger::storage::storage::HashMap::new().insert(segment, intent);
let fallible_coins = match offers.fallible {
Some(offer) => moonproof_ledger::storage::storage::HashMap::new().insert(segment, offer),
None => moonproof_ledger::storage::storage::HashMap::new(),
};
Ok(Transaction::new(
network_id.to_owned(),
intents,
offers.guaranteed,
fallible_coins,
))
}
fn unshielded_offer(
mut outputs: Vec<UtxoOutput>,
) -> Option<UnshieldedOffer<Signature, InMemoryDB>> {
outputs.sort();
(!outputs.is_empty()).then(|| UnshieldedOffer {
inputs: Vec::<UtxoSpend>::new().into(),
outputs: outputs.into(),
signatures: Vec::<Signature>::new().into(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::onchain_runtime::state::{
ContractMaintenanceAuthority, EntryPointBuf, StateValue,
};
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use rand::rngs::StdRng;
use rand::SeedableRng;
fn fixture_verifier_key() -> Vec<u8> {
let keys = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
"keys"
} else {
"keys-v2"
};
let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.pop();
p.push(format!(
"test-fixtures/contracts/counter/{keys}/increment.verifier"
));
std::fs::read(p).unwrap()
}
fn dummy_contract_state_with_circuit(circuit_id: &str) -> ContractState<InMemoryDB> {
let vk = fixture_verifier_key();
let op = moonproof_ledger::contract_operation(Some(
moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_slice()).unwrap(),
));
let op_key: EntryPointBuf = circuit_id.as_bytes().into();
ContractState::<InMemoryDB>::new(
StateValue::Null,
StorageHashMap::new().insert(op_key, op),
ContractMaintenanceAuthority::default(),
)
}
#[test]
fn deploy_over_the_operations_cap_is_refused() {
let Some(limit) = moonproof_ledger::MAX_CONTRACT_OPERATIONS else {
return;
};
let state_with = |n: u64| {
let ops = (0..n).fold(StorageHashMap::new(), |ops, i| {
let key: EntryPointBuf = format!("op{i}").as_bytes().into();
ops.insert(key, moonproof_ledger::contract_operation(None))
});
ContractState::<InMemoryDB>::new(
StateValue::Null,
ops,
ContractMaintenanceAuthority::default(),
)
};
let mut rng = StdRng::seed_from_u64(3);
assert!(build_contract_deploy(&mut rng, state_with(limit)).is_ok());
assert!(build_contract_deploy(&mut rng, state_with(limit + 1)).is_err());
}
#[test]
fn ttl_one_hour_advances_exactly_one_hour() {
let base = Timestamp::from_secs(1_700_000_000);
let ttl = ttl_one_hour(base);
assert_eq!(
ttl,
base + moonproof_ledger::base_crypto::time::Duration::from_secs(3600)
);
}
#[test]
fn build_contract_deploy_returns_derived_address_matching_deploy() {
let mut rng = StdRng::seed_from_u64(0xDEAD);
let state = dummy_contract_state_with_circuit("noop");
let (deploy, address, returned_state) = build_contract_deploy(&mut rng, state).unwrap();
assert_eq!(deploy.address(), address);
let mut bytes = Vec::new();
moonproof_ledger::serialize::tagged_serialize(&returned_state, &mut bytes).unwrap();
assert_ne!(bytes, [] as [u8; 0]);
}
#[test]
fn required_operation_finds_declared_circuit() {
let state = dummy_contract_state_with_circuit("increment");
let op = required_operation(&state, &CircuitId::new("increment")).unwrap();
let _ = format!("{op:?}");
}
#[test]
fn required_operation_errors_on_missing_circuit() {
let state = dummy_contract_state_with_circuit("increment");
let err = required_operation(&state, &CircuitId::new("missing")).unwrap_err();
matches!(err, ContractRuntimeError::Provider { .. });
assert!(format!("{err}").contains("missing"));
}
#[test]
fn build_contract_call_prototype_populates_all_fields() {
let state = dummy_contract_state_with_circuit("increment");
let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
let mut rng = StdRng::seed_from_u64(1);
let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
let inputs = ContractCallPrototypeInputs {
contract_address: address,
circuit_id: CircuitId::new("increment"),
initial_contract_state: state,
input: AlignedValue::from(0u8),
output: AlignedValue::from(0u8),
public_transcript_ops: Vec::new(),
private_transcript_outputs: Vec::new(),
communication_commitment_rand: rand,
popeq_read_results: Vec::new(),
ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
};
let prototype = build_contract_call_prototype(inputs).unwrap();
assert_eq!(prototype.address, address);
assert_eq!(prototype.entry_point.as_ref(), b"increment");
let expected_location = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
format!(
"contract:{}/increment?vk={}",
"33".repeat(32),
hex::encode(crate::key_location::hash_verifier_key(
&fixture_verifier_key()
))
)
} else {
"increment".to_owned()
};
assert_eq!(prototype.key_location.0, expected_location);
}
#[test]
fn a_call_to_an_operation_without_a_verifier_key_is_refused() {
if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
return;
}
let op_key: EntryPointBuf = b"increment".as_slice().into();
let state = ContractState::<InMemoryDB>::new(
StateValue::Null,
StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
ContractMaintenanceAuthority::default(),
);
let mut rng = StdRng::seed_from_u64(1);
let inputs = ContractCallPrototypeInputs {
contract_address: ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(
[0x33; 32],
)),
circuit_id: CircuitId::new("increment"),
initial_contract_state: state,
input: AlignedValue::from(0u8),
output: AlignedValue::from(0u8),
public_transcript_ops: Vec::new(),
private_transcript_outputs: Vec::new(),
communication_commitment_rand: rng.r#gen(),
popeq_read_results: Vec::new(),
ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
};
assert!(build_contract_call_prototype(inputs).is_err());
}
#[test]
fn build_contract_call_prototype_rejects_excess_popeq_results() {
let state = dummy_contract_state_with_circuit("increment");
let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
let mut rng = StdRng::seed_from_u64(1);
let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
let inputs = ContractCallPrototypeInputs {
contract_address: address,
circuit_id: CircuitId::new("increment"),
initial_contract_state: state,
input: AlignedValue::from(0u8),
output: AlignedValue::from(0u8),
public_transcript_ops: Vec::new(),
private_transcript_outputs: Vec::new(),
communication_commitment_rand: rand,
popeq_read_results: vec![AlignedValue::from(7u64)],
ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
};
let err = build_contract_call_prototype(inputs).unwrap_err();
let msg = format!("{err}");
assert!(msg.contains("more popeq_read_results"), "{msg}");
}
#[test]
fn build_contract_call_prototype_rejects_missing_popeq_result() {
use moonproof_ledger::onchain_runtime::ops::Op;
let state = dummy_contract_state_with_circuit("increment");
let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
let mut rng = StdRng::seed_from_u64(1);
let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
let popeq: Op<ResultModeGather, InMemoryDB> = Op::Popeq {
cached: false,
result: (),
};
let inputs = ContractCallPrototypeInputs {
contract_address: address,
circuit_id: CircuitId::new("increment"),
initial_contract_state: state,
input: AlignedValue::from(0u8),
output: AlignedValue::from(0u8),
public_transcript_ops: vec![popeq],
private_transcript_outputs: Vec::new(),
communication_commitment_rand: rand,
popeq_read_results: Vec::new(),
ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
};
let err = build_contract_call_prototype(inputs).unwrap_err();
let msg = format!("{err}");
assert!(msg.contains("more Op::Popeq"), "{msg}");
}
use crate::types::{CoinPublicKey, EncPublicKey};
use crate::utils::zswap_utils::{create_encryption_public_key_resolver, CompactZswapOutput};
use moonproof_ledger::base_crypto::cost_model::RunningCost;
use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::coin_structure::coin::{
Commitment, Info as CoinInfo, Nullifier, QualifiedInfo, ShieldedTokenType,
UnshieldedTokenType, UserAddress,
};
use moonproof_ledger::coin_structure::transfer::Recipient;
use moonproof_ledger::onchain_runtime::context::Effects;
type UnprovenTransaction =
Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>;
fn address(byte: u8) -> ContractAddress {
ContractAddress(HashOutput([byte; 32]))
}
fn user(byte: u8) -> UserAddress {
UserAddress(HashOutput([byte; 32]))
}
fn unshielded_token() -> UnshieldedTokenType {
UnshieldedTokenType(HashOutput([0xA5; 32]))
}
fn shielded_token() -> ShieldedTokenType {
ShieldedTokenType(HashOutput([0x5A; 32]))
}
fn transcript(effects: Effects<InMemoryDB>) -> Transcript<InMemoryDB> {
Transcript {
gas: RunningCost::ZERO,
effects,
program: moonproof_ledger::storage::storage::Array::new(),
version: None,
}
}
fn spends(entries: &[(TokenType, PublicAddress, u128)]) -> Transcript<InMemoryDB> {
let mut effects = Effects::<InMemoryDB>::default();
for (token, address, value) in entries {
effects.claimed_unshielded_spends = effects
.claimed_unshielded_spends
.insert(ClaimedUnshieldedSpendsKey(*token, *address), *value);
}
transcript(effects)
}
fn shielded(
receives: &[Commitment],
sends: &[Commitment],
nullifiers: &[Nullifier],
) -> Transcript<InMemoryDB> {
let mut effects = Effects::<InMemoryDB>::default();
for c in receives {
effects.claimed_shielded_receives = effects.claimed_shielded_receives.insert(*c);
}
for c in sends {
effects.claimed_shielded_spends = effects.claimed_shielded_spends.insert(*c);
}
for n in nullifiers {
effects.claimed_nullifiers = effects.claimed_nullifiers.insert(*n);
}
transcript(effects)
}
fn prototype(
at: ContractAddress,
guaranteed: Option<Transcript<InMemoryDB>>,
fallible: Option<Transcript<InMemoryDB>>,
) -> ContractCallPrototype<InMemoryDB> {
ContractCallPrototype {
address: at,
entry_point: b"circuit".as_slice().into(),
op: moonproof_ledger::contract_operation(None),
guaranteed_public_transcript: guaranteed,
fallible_public_transcript: fallible,
private_transcript_outputs: Vec::new(),
input: AlignedValue::from(()),
output: AlignedValue::from(()),
communication_commitment_rand: Fr::from(0u64),
key_location: moonproof_ledger::transient_crypto::proofs::KeyLocation(
std::borrow::Cow::Borrowed("circuit"),
),
}
}
fn empty_local_state() -> CompactZswapLocalState {
CompactZswapLocalState::empty(CoinPublicKey([0x11; 32]))
}
fn local_state(
inputs: Vec<QualifiedInfo>,
outputs: Vec<CompactZswapOutput>,
) -> CompactZswapLocalState {
CompactZswapLocalState {
inputs,
outputs,
..empty_local_state()
}
}
fn coin(value: u128, nonce: u8) -> CoinInfo {
CoinInfo {
nonce: moonproof_ledger::coin_structure::coin::Nonce(HashOutput([nonce; 32])),
type_: shielded_token(),
value,
}
}
fn to_contract(info: CoinInfo, at: ContractAddress) -> CompactZswapOutput {
CompactZswapOutput {
coin_info: info,
recipient: Recipient::Contract(at),
}
}
fn settled_for(
owner: ContractAddress,
value: u128,
nonce: u8,
) -> (ZswapChainState<InMemoryDB>, QualifiedInfo, Nullifier) {
let info = coin(value, nonce);
let mut rng = StdRng::seed_from_u64(u64::from(nonce));
let output =
moonproof_ledger::zswap::Output::new_contract_owned(&mut rng, &info, None, owner)
.unwrap();
let offer =
moonproof_ledger::zswap::Offer::new(Vec::new(), vec![output], Vec::new()).unwrap();
let (state, indices) = ZswapChainState::<InMemoryDB>::new()
.try_apply(&offer, None)
.unwrap();
let commitment = info.commitment(&Recipient::Contract(owner));
let index = *indices.get(&commitment).unwrap();
let nullifier = info.nullifier(
&moonproof_ledger::coin_structure::transfer::SenderEvidence::Contract(owner),
);
(state, info.qualify(index), nullifier)
}
fn assemble(calls: Vec<AssembledCall<'_>>) -> Result<UnprovenTransaction> {
let resolver = create_encryption_public_key_resolver(
CoinPublicKey([0x11; 32]),
crate::utils::zswap_utils::BURN_ENCRYPTION_PUBLIC_KEY,
None,
);
create_unproven_ledger_call_tx(
&mut StdRng::seed_from_u64(9),
calls,
&resolver,
"local-test",
Timestamp::from_secs(3_600),
)
}
fn call<'a>(
prototype: ContractCallPrototype<InMemoryDB>,
zswap_local_state: &'a CompactZswapLocalState,
zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
) -> AssembledCall<'a> {
AssembledCall {
prototype,
zswap_local_state,
zswap_chain_state,
}
}
fn standard(
tx: &UnprovenTransaction,
) -> &moonproof_ledger::ledger::structure::StandardTransaction<
Signature,
ProofPreimageMarker,
PedersenRandomness,
InMemoryDB,
> {
match tx {
Transaction::Standard(stx) => stx,
other @ Transaction::ClaimRewards(_) => {
panic!("expected a standard transaction, got {other:?}")
}
}
}
fn only_intent(
tx: &UnprovenTransaction,
) -> (
u16,
Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
) {
let stx = standard(tx);
assert_eq!(stx.intents.size(), 1);
let entry = stx.intents.iter().next().unwrap();
(*entry.0, (*entry.1).clone())
}
fn outputs_of(offer: Option<&UnshieldedOffer<Signature, InMemoryDB>>) -> Vec<UtxoOutput> {
offer.map_or_else(Vec::new, |o| Vec::from(&o.outputs))
}
fn guaranteed_commitments(tx: &UnprovenTransaction) -> Vec<Commitment> {
standard(tx)
.guaranteed_coins
.as_ref()
.map_or_else(Vec::new, |o| {
o.outputs.iter().map(|out| out.coin_com).collect()
})
}
fn guaranteed_nullifiers(tx: &UnprovenTransaction) -> Vec<Nullifier> {
standard(tx)
.guaranteed_coins
.as_ref()
.map_or_else(Vec::new, |o| {
o.inputs.iter().map(|inp| inp.nullifier).collect()
})
}
fn fallible_offer(
tx: &UnprovenTransaction,
) -> Option<
moonproof_ledger::zswap::Offer<
moonproof_ledger::transient_crypto::proofs::ProofPreimage,
InMemoryDB,
>,
> {
let stx = standard(tx);
assert!(stx.fallible_coins.size() <= 1);
stx.fallible_coins
.iter()
.next()
.map(|entry| (*entry.1).clone())
}
#[test]
fn user_outputs_of_no_transcript_are_empty() {
assert_eq!(
user_addressed_unshielded_outputs(None).unwrap(),
[] as [UtxoOutput; 0]
);
}
#[test]
fn user_outputs_of_no_spends_are_empty() {
let t = spends(&[]);
assert_eq!(
user_addressed_unshielded_outputs(Some(&t)).unwrap(),
[] as [UtxoOutput; 0]
);
}
#[test]
fn a_user_addressed_unshielded_spend_is_an_output() {
let t = spends(&[(
TokenType::Unshielded(unshielded_token()),
PublicAddress::User(user(1)),
100,
)]);
assert_eq!(
user_addressed_unshielded_outputs(Some(&t)).unwrap(),
vec![UtxoOutput {
value: 100,
owner: user(1),
type_: unshielded_token(),
}]
);
}
#[test]
fn a_user_addressed_shielded_spend_is_refused() {
let t = spends(&[(
TokenType::Shielded(shielded_token()),
PublicAddress::User(user(2)),
50,
)]);
let err = user_addressed_unshielded_outputs(Some(&t)).unwrap_err();
assert!(format!("{err}").contains("shielded token"), "{err}");
}
#[test]
fn contract_addressed_spends_are_not_user_outputs() {
let t = spends(&[(
TokenType::Unshielded(unshielded_token()),
PublicAddress::Contract(address(3)),
100,
)]);
assert_eq!(
user_addressed_unshielded_outputs(Some(&t)).unwrap(),
[] as [UtxoOutput; 0]
);
}
#[test]
fn dust_spends_are_not_user_outputs() {
let t = spends(&[(TokenType::Dust, PublicAddress::User(user(1)), 100)]);
assert_eq!(
user_addressed_unshielded_outputs(Some(&t)).unwrap(),
[] as [UtxoOutput; 0]
);
}
#[test]
fn mixed_spends_keep_only_user_addressed_unshielded_ones() {
let t = spends(&[
(
TokenType::Unshielded(unshielded_token()),
PublicAddress::User(user(1)),
100,
),
(
TokenType::Unshielded(unshielded_token()),
PublicAddress::Contract(address(3)),
300,
),
(TokenType::Dust, PublicAddress::User(user(1)), 400),
]);
assert_eq!(
user_addressed_unshielded_outputs(Some(&t)).unwrap(),
vec![UtxoOutput {
value: 100,
owner: user(1),
type_: unshielded_token(),
}]
);
}
fn user_spend(owner: UserAddress, value: u128) -> Transcript<InMemoryDB> {
spends(&[(
TokenType::Unshielded(unshielded_token()),
PublicAddress::User(owner),
value,
)])
}
#[test]
fn no_transcripts_attach_no_unshielded_offers() {
let state = empty_local_state();
let tx = assemble(vec![call(prototype(address(1), None, None), &state, None)]).unwrap();
let (_, intent) = only_intent(&tx);
assert!(intent.guaranteed_unshielded_offer.is_none());
assert!(intent.fallible_unshielded_offer.is_none());
}
#[test]
fn a_guaranteed_user_spend_attaches_a_guaranteed_offer() {
let state = empty_local_state();
let tx = assemble(vec![call(
prototype(address(1), Some(user_spend(user(1), 500)), None),
&state,
None,
)])
.unwrap();
let (_, intent) = only_intent(&tx);
assert_eq!(
outputs_of(intent.guaranteed_unshielded_offer.as_deref()),
vec![UtxoOutput {
value: 500,
owner: user(1),
type_: unshielded_token(),
}]
);
assert!(intent.fallible_unshielded_offer.is_none());
}
#[test]
fn a_fallible_user_spend_attaches_a_fallible_offer() {
let state = empty_local_state();
let tx = assemble(vec![call(
prototype(
address(1),
Some(spends(&[])),
Some(user_spend(user(2), 300)),
),
&state,
None,
)])
.unwrap();
let (_, intent) = only_intent(&tx);
assert!(intent.guaranteed_unshielded_offer.is_none());
assert_eq!(
outputs_of(intent.fallible_unshielded_offer.as_deref()),
vec![UtxoOutput {
value: 300,
owner: user(2),
type_: unshielded_token(),
}]
);
}
#[test]
fn contract_addressed_spends_attach_no_offer() {
let state = empty_local_state();
let to_contract = spends(&[(
TokenType::Unshielded(unshielded_token()),
PublicAddress::Contract(address(9)),
100,
)]);
let tx = assemble(vec![call(
prototype(address(1), Some(to_contract), None),
&state,
None,
)])
.unwrap();
let (_, intent) = only_intent(&tx);
assert!(intent.guaranteed_unshielded_offer.is_none());
assert!(intent.fallible_unshielded_offer.is_none());
}
#[test]
fn both_segments_get_their_own_offer() {
let state = empty_local_state();
let tx = assemble(vec![call(
prototype(
address(1),
Some(user_spend(user(1), 100)),
Some(user_spend(user(2), 200)),
),
&state,
None,
)])
.unwrap();
let (_, intent) = only_intent(&tx);
assert_eq!(
outputs_of(intent.guaranteed_unshielded_offer.as_deref()).len(),
1
);
assert_eq!(
outputs_of(intent.fallible_unshielded_offer.as_deref())[0].owner,
user(2)
);
}
fn two_call_tree(
callee: (
Option<Transcript<InMemoryDB>>,
Option<Transcript<InMemoryDB>>,
),
root: (
Option<Transcript<InMemoryDB>>,
Option<Transcript<InMemoryDB>>,
),
) -> Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
let state = empty_local_state();
let tx = assemble(vec![
call(prototype(address(2), callee.0, callee.1), &state, None),
call(prototype(address(1), root.0, root.1), &state, None),
])
.unwrap();
only_intent(&tx).1
}
#[test]
fn a_callee_only_guaranteed_spend_reaches_the_offer() {
let intent = two_call_tree(
(Some(user_spend(user(4), 100)), None),
(Some(spends(&[])), None),
);
assert_eq!(
outputs_of(intent.guaranteed_unshielded_offer.as_deref()),
vec![UtxoOutput {
value: 100,
owner: user(4),
type_: unshielded_token(),
}]
);
}
#[test]
fn a_callee_only_fallible_spend_reaches_the_offer() {
let intent = two_call_tree(
(Some(spends(&[])), Some(user_spend(user(4), 250))),
(Some(spends(&[])), None),
);
assert!(intent.guaranteed_unshielded_offer.is_none());
assert_eq!(
outputs_of(intent.fallible_unshielded_offer.as_deref())[0].value,
250
);
}
#[test]
fn callee_and_root_spends_share_one_offer_sorted() {
let intent = two_call_tree(
(Some(user_spend(user(7), 100)), None),
(Some(user_spend(user(3), 200)), None),
);
let outputs = outputs_of(intent.guaranteed_unshielded_offer.as_deref());
assert_eq!(outputs.len(), 2);
assert!(outputs.is_sorted(), "{outputs:?}");
assert!(outputs.iter().any(|o| o.owner == user(7) && o.value == 100));
assert!(outputs.iter().any(|o| o.owner == user(3) && o.value == 200));
}
#[test]
fn each_call_takes_a_random_segment_so_calls_merge() {
let state = empty_local_state();
let resolver = create_encryption_public_key_resolver(
CoinPublicKey([0x11; 32]),
EncPublicKey([0u8; 32]),
None,
);
let mut rng = StdRng::seed_from_u64(41);
let mut build = || {
create_unproven_ledger_call_tx(
&mut rng,
vec![call(prototype(address(1), None, None), &state, None)],
&resolver,
"local-test",
Timestamp::from_secs(3_600),
)
.unwrap()
};
let first = build();
let second = build();
let (a, _) = only_intent(&first);
let (b, _) = only_intent(&second);
assert!(a >= FIRST_RANDOM_SEGMENT && b >= FIRST_RANDOM_SEGMENT);
assert_ne!(a, b);
let merged = first.merge(&second).expect("two calls merge");
assert_eq!(standard(&merged).intents.size(), 2);
}
#[test]
fn a_fallibly_claimed_user_output_goes_to_the_fallible_offer() {
let wallet = CoinPublicKey([0x11; 32]);
let info = coin(4967, 1);
let commitment = info.commitment(&Recipient::User(
moonproof_ledger::coin_structure::coin::PublicKey(HashOutput(wallet.0)),
));
let state = local_state(
Vec::new(),
vec![CompactZswapOutput {
coin_info: info,
recipient: Recipient::User(moonproof_ledger::coin_structure::coin::PublicKey(
HashOutput(wallet.0),
)),
}],
);
let tx = assemble(vec![call(
prototype(
address(1),
Some(shielded(&[], &[], &[])),
Some(shielded(&[], &[commitment], &[])),
),
&state,
None,
)])
.unwrap();
let (segment, _) = only_intent(&tx);
let stx = standard(&tx);
assert!(stx.guaranteed_coins.is_none());
assert!(stx.fallible_coins.get(&segment).is_some());
let fallible = fallible_offer(&tx).unwrap();
assert_eq!(
fallible
.outputs
.iter()
.map(|o| o.coin_com)
.collect::<Vec<_>>(),
vec![commitment]
);
}
#[test]
fn a_guaranteed_user_output_stays_guaranteed() {
let wallet = moonproof_ledger::coin_structure::coin::PublicKey(HashOutput([0x11; 32]));
let info = coin(100, 2);
let commitment = info.commitment(&Recipient::User(wallet));
let state = local_state(
Vec::new(),
vec![CompactZswapOutput {
coin_info: info,
recipient: Recipient::User(wallet),
}],
);
let tx = assemble(vec![call(
prototype(address(1), Some(shielded(&[], &[commitment], &[])), None),
&state,
None,
)])
.unwrap();
assert_eq!(guaranteed_commitments(&tx), vec![commitment]);
assert!(fallible_offer(&tx).is_none());
}
#[test]
fn a_fallibly_claimed_input_goes_to_the_fallible_offer() {
let owner = address(1);
let (chain, qcoin, nullifier) = settled_for(owner, 500, 3);
let state = local_state(vec![qcoin], Vec::new());
let tx = assemble(vec![call(
prototype(
owner,
Some(shielded(&[], &[], &[])),
Some(shielded(&[], &[], &[nullifier])),
),
&state,
Some(&chain),
)])
.unwrap();
assert!(standard(&tx).guaranteed_coins.is_none());
let fallible = fallible_offer(&tx).unwrap();
assert_eq!(
fallible
.inputs
.iter()
.map(|i| i.nullifier)
.collect::<Vec<_>>(),
vec![nullifier]
);
}
#[test]
fn a_respent_contract_coin_becomes_a_fallible_transient() {
let owner = address(1);
let (chain, qcoin, nullifier) = settled_for(owner, 1000, 4);
let info = CoinInfo::from(&qcoin);
let commitment = info.commitment(&Recipient::Contract(owner));
let state = local_state(vec![qcoin], vec![to_contract(info, owner)]);
let tx = assemble(vec![call(
prototype(
owner,
Some(shielded(&[], &[], &[])),
Some(shielded(&[commitment], &[], &[nullifier])),
),
&state,
Some(&chain),
)])
.unwrap();
let fallible = fallible_offer(&tx).unwrap();
assert_eq!(fallible.inputs.len(), 0);
assert_eq!(fallible.outputs.len(), 0);
let transients: Vec<_> = fallible.transient.iter().collect();
assert_eq!(transients.len(), 1);
assert_eq!(transients[0].nullifier, nullifier);
}
#[test]
fn a_callee_spends_against_its_own_chain_state() {
let callee = address(2);
let (chain, qcoin, nullifier) = settled_for(callee, 1000, 5);
let callee_state = local_state(vec![qcoin], Vec::new());
let root_state = empty_local_state();
let tx = assemble(vec![
call(
prototype(callee, Some(shielded(&[], &[], &[nullifier])), None),
&callee_state,
Some(&chain),
),
call(
prototype(address(1), Some(shielded(&[], &[], &[])), None),
&root_state,
None,
),
])
.unwrap();
assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
}
#[test]
fn the_deepest_callee_spends_and_a_middle_callee_receives() {
let (a, b, c) = (address(1), address(2), address(3));
let (chain, qcoin, nullifier) = settled_for(c, 1000, 6);
let received = coin(50, 7);
let received_commitment = received.commitment(&Recipient::Contract(b));
let c_state = local_state(vec![qcoin], Vec::new());
let b_state = local_state(Vec::new(), vec![to_contract(received, b)]);
let a_state = empty_local_state();
let tx = assemble(vec![
call(
prototype(c, Some(shielded(&[], &[], &[nullifier])), None),
&c_state,
Some(&chain),
),
call(
prototype(b, Some(shielded(&[received_commitment], &[], &[])), None),
&b_state,
None,
),
call(
prototype(a, Some(shielded(&[], &[], &[])), None),
&a_state,
None,
),
])
.unwrap();
assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
assert_eq!(guaranteed_commitments(&tx), vec![received_commitment]);
}
#[test]
fn a_callee_reached_twice_keeps_both_calls_coins() {
let (a, b, c) = (address(1), address(2), address(3));
let (chain, qcoin, nullifier) = settled_for(b, 1000, 8);
let received = coin(50, 9);
let received_commitment = received.commitment(&Recipient::Contract(b));
let first_b = local_state(vec![qcoin], Vec::new());
let second_b = local_state(Vec::new(), vec![to_contract(received, b)]);
let empty = empty_local_state();
let tx = assemble(vec![
call(
prototype(b, Some(shielded(&[], &[], &[nullifier])), None),
&first_b,
Some(&chain),
),
call(
prototype(c, Some(shielded(&[], &[], &[])), None),
&empty,
None,
),
call(
prototype(b, Some(shielded(&[received_commitment], &[], &[])), None),
&second_b,
None,
),
call(
prototype(a, Some(shielded(&[], &[], &[])), None),
&empty,
None,
),
])
.unwrap();
assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
assert_eq!(guaranteed_commitments(&tx), vec![received_commitment]);
}
#[test]
fn a_callees_coins_split_between_guaranteed_and_fallible() {
let callee = address(2);
let guaranteed_coin = coin(10, 10);
let fallible_coin = coin(20, 11);
let g = guaranteed_coin.commitment(&Recipient::Contract(callee));
let f = fallible_coin.commitment(&Recipient::Contract(callee));
let callee_state = local_state(
Vec::new(),
vec![
to_contract(guaranteed_coin, callee),
to_contract(fallible_coin, callee),
],
);
let root_state = empty_local_state();
let tx = assemble(vec![
call(
prototype(
callee,
Some(shielded(&[g], &[], &[])),
Some(shielded(&[f], &[], &[])),
),
&callee_state,
None,
),
call(
prototype(address(1), Some(shielded(&[], &[], &[])), None),
&root_state,
None,
),
])
.unwrap();
assert_eq!(guaranteed_commitments(&tx), vec![g]);
let fallible = fallible_offer(&tx).unwrap();
assert_eq!(
fallible
.outputs
.iter()
.map(|o| o.coin_com)
.collect::<Vec<_>>(),
vec![f]
);
}
#[test]
fn a_coin_sent_and_received_in_the_tree_is_one_output() {
let (root, callee) = (address(1), address(2));
let info = coin(50, 12);
let commitment = info.commitment(&Recipient::Contract(callee));
let callee_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
let tx = assemble(vec![
call(
prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
&callee_state,
None,
),
call(
prototype(root, Some(shielded(&[], &[commitment], &[])), None),
&root_state,
None,
),
])
.unwrap();
assert_eq!(guaranteed_commitments(&tx), vec![commitment]);
}
fn mismatch(calls: Vec<AssembledCall<'_>>) -> String {
format!("{}", assemble(calls).unwrap_err())
}
fn claim_key(segment: u8, commitment: Commitment, at: ContractAddress) -> String {
format!(
"segment {segment} / {} / {}",
hex::encode(commitment.0 .0),
moonproof_runtime::state::contract_address_to_hex(&at)
)
}
#[test]
fn an_unclaimed_contract_coin_is_refused() {
let (root, callee) = (address(1), address(2));
let info = coin(50, 13);
let commitment = info.commitment(&Recipient::Contract(callee));
let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
let empty = empty_local_state();
let message = mismatch(vec![
call(
prototype(callee, Some(shielded(&[], &[], &[])), None),
&empty,
None,
),
call(
prototype(root, Some(shielded(&[], &[commitment], &[])), None),
&root_state,
None,
),
]);
assert!(
message.contains(&format!(
"{}: offered 1, claimed 0",
claim_key(0, commitment, callee)
)),
"{message}"
);
}
#[test]
fn a_receive_claim_without_an_offer_is_refused() {
let (root, callee) = (address(1), address(2));
let commitment = coin(50, 14).commitment(&Recipient::Contract(callee));
let empty = empty_local_state();
let message = mismatch(vec![
call(
prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
&empty,
None,
),
call(
prototype(root, Some(shielded(&[], &[], &[])), None),
&empty,
None,
),
]);
assert!(
message.contains(&format!(
"{}: offered 0, claimed 1",
claim_key(0, commitment, callee)
)),
"{message}"
);
}
#[test]
fn a_coin_claimed_twice_is_refused() {
let (root, callee) = (address(1), address(2));
let info = coin(50, 15);
let commitment = info.commitment(&Recipient::Contract(callee));
let callee_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
let empty = empty_local_state();
let message = mismatch(vec![
call(
prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
&callee_state,
None,
),
call(
prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
&empty,
None,
),
call(
prototype(root, Some(shielded(&[], &[], &[])), None),
&empty,
None,
),
]);
assert!(
message.contains(&format!(
"{}: offered 1, claimed 2",
claim_key(0, commitment, callee)
)),
"{message}"
);
}
#[test]
fn a_coin_offered_and_claimed_in_different_segments_is_refused() {
let (root, callee) = (address(1), address(2));
let info = coin(50, 16);
let commitment = info.commitment(&Recipient::Contract(callee));
let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
let empty = empty_local_state();
let message = mismatch(vec![
call(
prototype(
callee,
Some(shielded(&[], &[], &[])),
Some(shielded(&[commitment], &[], &[])),
),
&empty,
None,
),
call(
prototype(root, Some(shielded(&[], &[commitment], &[])), None),
&root_state,
None,
),
]);
assert!(
message.contains(&format!(
"{}: offered 1, claimed 0",
claim_key(0, commitment, callee)
)),
"{message}"
);
assert!(
message.contains(&format!(
"{}: offered 0, claimed 1",
claim_key(1, commitment, callee)
)),
"{message}"
);
}
}