use std::collections::HashMap;
use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::coin_structure::coin::{
Info as CoinInfo, QualifiedInfo as QualifiedCoinInfo,
};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::coin_structure::transfer::Recipient;
use moonproof_ledger::onchain_runtime::transcript::Transcript;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::proofs::ProofPreimage;
use moonproof_ledger::zswap::ledger::State as ZswapChainState;
use moonproof_ledger::zswap::{Input, Offer, Output, Transient};
use rand::{CryptoRng, Rng};
use crate::error::{ContractRuntimeError, Result};
use crate::types::{CoinPublicKey, EncPublicKey};
pub use moonproof_ledger::zswap::local::State as ZswapWalletState;
pub const SHIELDED_BURN_COIN_PUBLIC_KEY: CoinPublicKey = CoinPublicKey([0u8; 32]);
pub const BURN_ENCRYPTION_PUBLIC_KEY: EncPublicKey = EncPublicKey(const_hex_decode(
b"f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65",
));
const fn const_hex_decode(s: &[u8; 64]) -> [u8; 32] {
let mut out = [0u8; 32];
let mut i = 0;
while i < 32 {
let hi = hex_nibble(s[i * 2]);
let lo = hex_nibble(s[i * 2 + 1]);
out[i] = (hi << 4) | lo;
i += 1;
}
out
}
const fn hex_nibble(c: u8) -> u8 {
match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'f' => c - b'a' + 10,
b'A'..=b'F' => c - b'A' + 10,
_ => panic!("invalid hex character"),
}
}
pub type EncryptionPublicKeyResolver =
Box<dyn Fn(CoinPublicKey) -> Option<EncPublicKey> + Send + Sync>;
#[expect(
clippy::implicit_hasher,
reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
)]
pub fn create_encryption_public_key_resolver(
wallet_coin_public_key: CoinPublicKey,
wallet_encryption_public_key: EncPublicKey,
additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
) -> EncryptionPublicKeyResolver {
let additional = additional.unwrap_or_default();
Box::new(move |coin_public_key: CoinPublicKey| {
if coin_public_key == wallet_coin_public_key {
Some(wallet_encryption_public_key)
} else if coin_public_key == SHIELDED_BURN_COIN_PUBLIC_KEY {
Some(BURN_ENCRYPTION_PUBLIC_KEY)
} else {
additional.get(&coin_public_key).copied()
}
})
}
pub use moonproof_runtime::zswap_local::{CompactZswapLocalState, CompactZswapOutput};
#[must_use]
pub fn zswap_state_to_new_coins(
receiver_coin_public_key: &CoinPublicKey,
zswap_state: &CompactZswapLocalState,
) -> Vec<CoinInfo> {
zswap_state
.outputs
.iter()
.filter_map(|out| match &out.recipient {
Recipient::User(pk) => {
if pk_matches(pk, receiver_coin_public_key) {
Some(out.coin_info)
} else {
None
}
}
Recipient::Contract(_) => None,
})
.collect()
}
fn pk_matches(
ledger_pk: &moonproof_ledger::coin_structure::coin::PublicKey,
moonproof_pk: &CoinPublicKey,
) -> bool {
ledger_pk.0 .0 == moonproof_pk.0
}
fn to_ledger_enc_public_key(
epk: &EncPublicKey,
) -> Result<moonproof_ledger::transient_crypto::encryption::PublicKey> {
use moonproof_ledger::serialize::Deserializable;
let mut cursor = &epk.0[..];
moonproof_ledger::transient_crypto::encryption::PublicKey::deserialize(&mut cursor, 0).map_err(
|e| ContractRuntimeError::Deserialize {
context: "EncPublicKey -> encryption::PublicKey",
source: e,
},
)
}
fn to_ledger_coin_public_key(
cpk: &CoinPublicKey,
) -> moonproof_ledger::coin_structure::coin::PublicKey {
moonproof_ledger::coin_structure::coin::PublicKey(HashOutput(cpk.0))
}
pub fn create_zswap_output<R: Rng + CryptoRng>(
rng: &mut R,
output: &CompactZswapOutput,
resolver: &EncryptionPublicKeyResolver,
segment: Option<u16>,
) -> Result<Output<ProofPreimage, InMemoryDB>> {
match &output.recipient {
Recipient::Contract(contract) => {
Output::new_contract_owned(rng, &output.coin_info, segment, *contract).map_err(|e| {
ContractRuntimeError::Provider {
provider: "create_zswap_output::contract",
message: format!("Output::new_contract_owned failed: {e:?}"),
}
})
}
Recipient::User(pk) => {
let cpk = CoinPublicKey(pk.0 .0);
let epk_bytes = resolver(cpk).ok_or_else(|| ContractRuntimeError::Provider {
provider: "create_zswap_output::user",
message: "Unable to resolve encryption public key for recipient. \
Provide a mapping via the encryption_public_key_resolver."
.to_owned(),
})?;
let epk = to_ledger_enc_public_key(&epk_bytes)?;
Output::new(rng, &output.coin_info, segment, pk, Some(epk)).map_err(|e| {
ContractRuntimeError::Provider {
provider: "create_zswap_output::user",
message: format!("Output::new failed: {e:?}"),
}
})
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ContractInputContext<'a> {
pub contract_address: ContractAddress,
pub zswap_chain_state: &'a ZswapChainState<InMemoryDB>,
}
pub const DEFAULT_SEGMENT_NUMBER: u16 = 0;
pub fn zswap_state_to_offer<R: Rng + CryptoRng>(
rng: &mut R,
state: &CompactZswapLocalState,
resolver: &EncryptionPublicKeyResolver,
contract_input_ctx: Option<ContractInputContext<'_>>,
) -> Result<Option<Offer<ProofPreimage, InMemoryDB>>> {
use std::collections::HashMap as StdHashMap;
let mut output_map: StdHashMap<CoinInfoKey, Output<ProofPreimage, InMemoryDB>> =
StdHashMap::new();
for entry in &state.outputs {
let key = CoinInfoKey::from(&entry.coin_info);
let out = create_zswap_output(rng, entry, resolver, Some(DEFAULT_SEGMENT_NUMBER))?;
output_map.insert(key, out);
}
let rehashed_chain_state = contract_input_ctx.as_ref().map(|c| {
moonproof_ledger::zswap_post_block_update(
c.zswap_chain_state,
moonproof_ledger::base_crypto::time::Timestamp::from_secs(
moonproof_utils::rt::SystemTime::now()
.duration_since(moonproof_utils::rt::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()),
),
)
});
let mut input_vec: Vec<Input<ProofPreimage, InMemoryDB>> = Vec::new();
let mut transient_vec: Vec<Transient<ProofPreimage, InMemoryDB>> = Vec::new();
for qcoin in &state.inputs {
let key = CoinInfoKey::from_qualified(qcoin);
if let Some(matched_output) = output_map.remove(&key) {
let transient = Transient::new_from_contract_owned_output(
rng,
qcoin,
Some(DEFAULT_SEGMENT_NUMBER),
matched_output,
)
.map_err(|e| ContractRuntimeError::Provider {
provider: "zswap_state_to_offer::transient",
message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
})?;
transient_vec.push(transient);
} else {
let ctx = contract_input_ctx
.as_ref()
.ok_or(ContractRuntimeError::Provider {
provider: "zswap_state_to_offer::input",
message: "input has no co-located output and no \
ContractInputContext was provided — non-transient \
inputs require an anchored chain state"
.to_owned(),
})?;
let chain_state = rehashed_chain_state
.as_ref()
.expect("rehashed chain state present whenever ctx is");
let input = Input::new_contract_owned(
rng,
qcoin,
Some(DEFAULT_SEGMENT_NUMBER),
ctx.contract_address,
&chain_state.coin_coms,
)
.map_err(|e| ContractRuntimeError::Provider {
provider: "zswap_state_to_offer::input",
message: format!("Input::new_contract_owned failed: {e:?}"),
})?;
input_vec.push(input);
}
}
let outputs: Vec<Output<ProofPreimage, InMemoryDB>> = output_map.into_values().collect();
Ok(Offer::new(input_vec, outputs, transient_vec))
}
pub const GUARANTEED_SEGMENT_NUMBER: u16 = 0;
#[derive(Clone, Copy)]
pub struct ZswapCallContribution<'a> {
pub contract_address: Option<ContractAddress>,
pub zswap_local_state: &'a CompactZswapLocalState,
pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
pub partitioned_transcript: PartitionedTranscriptRef<'a>,
}
pub struct SegmentedOffers {
pub guaranteed: Option<Offer<ProofPreimage, InMemoryDB>>,
pub fallible: Option<Offer<ProofPreimage, InMemoryDB>>,
}
pub type PartitionedTranscriptRef<'a> = (
Option<&'a Transcript<InMemoryDB>>,
Option<&'a Transcript<InMemoryDB>>,
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SegmentKind {
Guaranteed,
Fallible,
}
impl SegmentKind {
fn number(self, fallible_segment: u16) -> u16 {
match self {
SegmentKind::Guaranteed => GUARANTEED_SEGMENT_NUMBER,
SegmentKind::Fallible => fallible_segment,
}
}
}
fn segment_for_match(
claims: impl Fn(&Transcript<InMemoryDB>) -> bool,
transcripts: &[PartitionedTranscriptRef<'_>],
what: impl FnOnce() -> String,
) -> Result<SegmentKind> {
if transcripts
.iter()
.any(|(guaranteed, _)| guaranteed.is_some_and(&claims))
{
return Ok(SegmentKind::Guaranteed);
}
if transcripts
.iter()
.any(|(_, fallible)| fallible.is_some_and(&claims))
{
return Ok(SegmentKind::Fallible);
}
if transcripts
.iter()
.any(|(guaranteed, fallible)| guaranteed.is_some() && fallible.is_some())
{
return Err(ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!(
"{} is not present in either segment of the partitioned transcript; the local \
zswap state does not match the contract's declared effects",
what()
),
});
}
Ok(SegmentKind::Guaranteed)
}
fn segment_for_commitment(
commitment: &moonproof_ledger::coin_structure::coin::Commitment,
transcripts: &[PartitionedTranscriptRef<'_>],
) -> Result<SegmentKind> {
segment_for_match(
|t| {
t.effects.claimed_shielded_receives.member(commitment)
|| t.effects.claimed_shielded_spends.member(commitment)
},
transcripts,
|| format!("shielded commitment {}", hex::encode(commitment.0 .0)),
)
}
fn segment_for_nullifier(
nullifier: &moonproof_ledger::coin_structure::coin::Nullifier,
transcripts: &[PartitionedTranscriptRef<'_>],
) -> Result<SegmentKind> {
segment_for_match(
|t| t.effects.claimed_nullifiers.member(nullifier),
transcripts,
|| format!("shielded nullifier {}", hex::encode(nullifier.0 .0)),
)
}
struct OwnerActivity<'a> {
owner: Option<ContractAddress>,
chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
outputs: indexmap::IndexMap<
moonproof_ledger::coin_structure::coin::Commitment,
&'a CompactZswapOutput,
>,
inputs: indexmap::IndexMap<(CoinInfoKey, u64), QualifiedCoinInfo>,
transcripts: Vec<PartitionedTranscriptRef<'a>>,
}
fn group_by_owner<'a>(contributions: &[ZswapCallContribution<'a>]) -> Vec<OwnerActivity<'a>> {
let mut owners: indexmap::IndexMap<Option<ContractAddress>, OwnerActivity<'a>> =
indexmap::IndexMap::new();
for contribution in contributions {
let activity = owners
.entry(contribution.contract_address)
.or_insert_with(|| OwnerActivity {
owner: contribution.contract_address,
chain_state: None,
outputs: indexmap::IndexMap::new(),
inputs: indexmap::IndexMap::new(),
transcripts: Vec::new(),
});
if activity.chain_state.is_none() {
activity.chain_state = contribution.zswap_chain_state;
}
activity
.transcripts
.push(contribution.partitioned_transcript);
for output in &contribution.zswap_local_state.outputs {
activity
.outputs
.insert(output.coin_info.commitment(&output.recipient), output);
}
for input in &contribution.zswap_local_state.inputs {
activity
.inputs
.insert((CoinInfoKey::from_qualified(input), input.mt_index), *input);
}
}
owners.into_values().collect()
}
#[derive(Default)]
struct SegmentBucket {
inputs: indexmap::IndexMap<
moonproof_ledger::coin_structure::coin::Nullifier,
Input<ProofPreimage, InMemoryDB>,
>,
outputs: indexmap::IndexMap<
moonproof_ledger::coin_structure::coin::Commitment,
Output<ProofPreimage, InMemoryDB>,
>,
transients: indexmap::IndexMap<
moonproof_ledger::coin_structure::coin::Commitment,
Transient<ProofPreimage, InMemoryDB>,
>,
}
impl SegmentBucket {
fn into_offer(self) -> Option<Offer<ProofPreimage, InMemoryDB>> {
Offer::new(
self.inputs.into_values().collect(),
self.outputs.into_values().collect(),
self.transients.into_values().collect(),
)
}
}
pub fn zswap_calls_to_segmented_offer<R: Rng + CryptoRng>(
rng: &mut R,
contributions: &[ZswapCallContribution<'_>],
resolver: &EncryptionPublicKeyResolver,
fallible_segment: u16,
) -> Result<SegmentedOffers> {
let activities = group_by_owner(contributions);
let mut offers = OfferAssembly {
fallible_segment,
buckets: std::collections::HashMap::new(),
segment_of_output: std::collections::HashMap::new(),
commitments_by_coin: std::collections::HashMap::new(),
};
for activity in &activities {
offers.add_outputs(rng, activity, resolver)?;
}
for activity in &activities {
offers.add_inputs(rng, activity)?;
}
let mut buckets = offers.buckets;
Ok(SegmentedOffers {
guaranteed: buckets
.remove(&SegmentKind::Guaranteed)
.and_then(SegmentBucket::into_offer),
fallible: buckets
.remove(&SegmentKind::Fallible)
.and_then(SegmentBucket::into_offer),
})
}
struct OfferAssembly {
fallible_segment: u16,
buckets: std::collections::HashMap<SegmentKind, SegmentBucket>,
segment_of_output:
std::collections::HashMap<moonproof_ledger::coin_structure::coin::Commitment, SegmentKind>,
commitments_by_coin: std::collections::HashMap<
CoinInfoKey,
Vec<moonproof_ledger::coin_structure::coin::Commitment>,
>,
}
impl OfferAssembly {
fn add_outputs<R: Rng + CryptoRng>(
&mut self,
rng: &mut R,
activity: &OwnerActivity<'_>,
resolver: &EncryptionPublicKeyResolver,
) -> Result<()> {
for (commitment, output) in &activity.outputs {
let segment = segment_for_commitment(commitment, &activity.transcripts)?;
if let Some(already) = self.segment_of_output.get(commitment) {
if *already != segment {
return Err(ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!(
"shielded commitment {} is claimed in the {already:?} segment by one \
call and the {segment:?} segment by another; the calls' transcripts \
disagree",
hex::encode(commitment.0 .0)
),
});
}
continue;
}
self.segment_of_output.insert(*commitment, segment);
self.commitments_by_coin
.entry(CoinInfoKey::from(&output.coin_info))
.or_default()
.push(*commitment);
let built = create_zswap_output(
rng,
output,
resolver,
Some(segment.number(self.fallible_segment)),
)?;
self.buckets
.entry(segment)
.or_default()
.outputs
.insert(*commitment, built);
}
Ok(())
}
fn add_inputs<R: Rng + CryptoRng>(
&mut self,
rng: &mut R,
activity: &OwnerActivity<'_>,
) -> Result<()> {
let mut rehashed: Option<ZswapChainState<InMemoryDB>> = None;
for qcoin in activity.inputs.values() {
let coin = CoinInfo::from(qcoin);
let own_commitment = match activity.owner {
Some(address) => Some(coin.commitment(&Recipient::Contract(address))),
None => sole_commitment_for(&coin, &self.commitments_by_coin)?,
};
if let Some((commitment, segment)) = own_commitment
.and_then(|c| self.segment_of_output.get(&c).map(|segment| (c, *segment)))
{
self.add_transient(rng, &coin, commitment, segment)?;
continue;
}
let Some(address) = activity.owner else {
return Err(ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: "a call that spends a settled shielded coin must name the contract \
that spent it, since the nullifier binds the spender"
.to_owned(),
});
};
let chain_state =
activity
.chain_state
.ok_or_else(|| ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!(
"contract {} spends a shielded coin with no co-located output, and no \
anchoring chain state (ContractInputContext) was provided; non-transient \
inputs require an anchored chain state",
moonproof_runtime::state::contract_address_to_hex(&address)
),
})?;
let tree = rehashed.get_or_insert_with(|| {
moonproof_ledger::zswap_post_block_update(
chain_state,
moonproof_ledger::base_crypto::time::Timestamp::from_secs(
moonproof_utils::rt::SystemTime::now()
.duration_since(moonproof_utils::rt::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()),
),
)
});
let nullifier = coin.nullifier(
&moonproof_ledger::coin_structure::transfer::SenderEvidence::Contract(address),
);
let segment = segment_for_nullifier(&nullifier, &activity.transcripts)?;
let input = Input::new_contract_owned(
rng,
qcoin,
Some(segment.number(self.fallible_segment)),
address,
&tree.coin_coms,
)
.map_err(|e| ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!("Input::new_contract_owned failed: {e:?}"),
})?;
self.buckets
.entry(segment)
.or_default()
.inputs
.insert(nullifier, input);
}
Ok(())
}
fn add_transient<R: Rng + CryptoRng>(
&mut self,
rng: &mut R,
coin: &CoinInfo,
commitment: moonproof_ledger::coin_structure::coin::Commitment,
segment: SegmentKind,
) -> Result<()> {
let bucket = self.buckets.entry(segment).or_default();
let output = bucket.outputs.shift_remove(&commitment).ok_or_else(|| {
ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!(
"no bucketed output for transient commitment {}",
hex::encode(commitment.0 .0)
),
}
})?;
let transient = Transient::new_from_contract_owned_output(
rng,
&coin.qualify(0),
Some(segment.number(self.fallible_segment)),
output,
)
.map_err(|e| ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
})?;
bucket.transients.insert(commitment, transient);
Ok(())
}
}
fn sole_commitment_for(
coin: &CoinInfo,
commitments_by_coin: &std::collections::HashMap<
CoinInfoKey,
Vec<moonproof_ledger::coin_structure::coin::Commitment>,
>,
) -> Result<Option<moonproof_ledger::coin_structure::coin::Commitment>> {
match commitments_by_coin
.get(&CoinInfoKey::from(coin))
.map(Vec::as_slice)
{
None | Some([]) => Ok(None),
Some([only]) => Ok(Some(*only)),
Some(candidates) => Err(ContractRuntimeError::Provider {
provider: "zswap_calls_to_segmented_offer",
message: format!(
"ambiguous transient: {} outputs carry the coin of an input whose spending \
contract is unknown, so the pair cannot be identified",
candidates.len()
),
}),
}
}
pub fn assert_receives_match_claims(
calls: &[(ContractAddress, PartitionedTranscriptRef<'_>)],
offers: &SegmentedOffers,
) -> Result<()> {
type Key = (
u8,
moonproof_ledger::coin_structure::coin::Commitment,
ContractAddress,
);
let mut counts: indexmap::IndexMap<Key, (usize, usize)> = indexmap::IndexMap::new();
for (segment, offer) in [(0u8, &offers.guaranteed), (1u8, &offers.fallible)] {
let Some(offer) = offer else { continue };
let outputs = offer
.outputs
.iter()
.map(|o| (o.coin_com, o.contract_address.as_ref().map(|a| **a)));
let transients = offer
.transient
.iter()
.map(|t| (t.coin_com, t.contract_address.as_ref().map(|a| **a)));
for (commitment, address) in outputs.chain(transients) {
if let Some(address) = address {
counts.entry((segment, commitment, address)).or_default().0 += 1;
}
}
}
for (address, (guaranteed, fallible)) in calls {
for (segment, half) in [(0u8, guaranteed), (1u8, fallible)] {
let Some(transcript) = half else { continue };
for commitment in transcript.effects.claimed_shielded_receives.iter() {
counts
.entry((segment, **commitment, *address))
.or_default()
.1 += 1;
}
}
}
let differences: Vec<String> = counts
.iter()
.filter(|(_, (offered, claimed))| offered != claimed)
.map(|((segment, commitment, address), (offered, claimed))| {
format!(
" segment {segment} / {} / {}: offered {offered}, claimed {claimed}",
hex::encode(commitment.0 .0),
moonproof_runtime::state::contract_address_to_hex(address)
)
})
.collect();
if differences.is_empty() {
return Ok(());
}
Err(ContractRuntimeError::Provider {
provider: "assert_receives_match_claims",
message: format!(
"a shielded coin addressed to a contract must be claimed as received by that \
contract as many times as the offers carry it, and these do not match; the ledger \
rejects such a transaction after proving. Offer count vs claim count:\n{}",
differences.join("\n")
),
})
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct CoinInfoKey {
nonce: HashOutput,
type_bytes: [u8; 32],
value: u128,
}
impl CoinInfoKey {
fn from(info: &CoinInfo) -> Self {
Self {
nonce: info.nonce.0,
type_bytes: info.type_.0 .0,
value: info.value,
}
}
fn from_qualified(info: &QualifiedCoinInfo) -> Self {
Self {
nonce: info.nonce.0,
type_bytes: info.type_.0 .0,
value: info.value,
}
}
}
#[expect(
clippy::implicit_hasher,
reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
)]
pub fn encryption_public_key_resolver_for_zswap_state(
zswap_state: &CompactZswapLocalState,
wallet_coin_public_key: CoinPublicKey,
wallet_encryption_public_key: EncPublicKey,
additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
) -> Result<EncryptionPublicKeyResolver> {
if zswap_state.coin_public_key != wallet_coin_public_key {
return Err(ContractRuntimeError::Provider {
provider: "encryption_public_key_resolver_for_zswap_state",
message: "Unable to lookup encryption public key (Unsupported coin) — \
zswap state's coin_public_key doesn't match the wallet's"
.to_owned(),
});
}
Ok(create_encryption_public_key_resolver(
wallet_coin_public_key,
wallet_encryption_public_key,
additional,
))
}
#[allow(dead_code)]
fn _unused_to_ledger_coin_public_key_anchor() {
let _ = to_ledger_coin_public_key;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn burn_constants_match_ts_exactly() {
assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.0, [0u8; 32]);
assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.to_hex(), "0".repeat(64));
}
#[test]
fn burn_encryption_key_matches_ts_byte_sequence() {
let expected =
hex::decode("f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65")
.unwrap();
assert_eq!(BURN_ENCRYPTION_PUBLIC_KEY.0.as_ref(), expected.as_slice());
}
#[test]
fn resolver_returns_wallet_key_for_self_lookup() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
}
#[test]
fn resolver_resolves_shielded_burn_address() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
assert_eq!(
resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
Some(BURN_ENCRYPTION_PUBLIC_KEY),
);
}
#[test]
fn resolver_honours_additional_mappings() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let other_coin_key = CoinPublicKey([0x33; 32]);
let other_enc_key = EncPublicKey([0x44; 32]);
let mut additional = HashMap::new();
additional.insert(other_coin_key, other_enc_key);
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
wallet_enc_key,
Some(additional),
);
assert_eq!(resolver(other_coin_key), Some(other_enc_key));
}
#[test]
fn resolver_returns_none_for_unknown_key() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
assert_eq!(resolver(CoinPublicKey([0xff; 32])), None);
}
#[test]
fn wallet_key_precedence_blocks_additional_mapping_hijack() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let malicious_epk = EncPublicKey([0xEE; 32]);
let mut malicious_mapping = HashMap::new();
malicious_mapping.insert(wallet_coin_key, malicious_epk);
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
wallet_enc_key,
Some(malicious_mapping),
);
assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
assert_ne!(resolver(wallet_coin_key), Some(malicious_epk));
}
#[test]
fn burn_key_precedence_blocks_additional_mapping_hijack() {
let wallet_coin_key = CoinPublicKey([0x11; 32]);
let wallet_enc_key = EncPublicKey([0x22; 32]);
let malicious_epk = EncPublicKey([0xEE; 32]);
let mut malicious_mapping = HashMap::new();
malicious_mapping.insert(SHIELDED_BURN_COIN_PUBLIC_KEY, malicious_epk);
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
wallet_enc_key,
Some(malicious_mapping),
);
assert_eq!(
resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
Some(BURN_ENCRYPTION_PUBLIC_KEY),
);
}
use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce};
use moonproof_ledger::coin_structure::transfer::Recipient;
use rand::rngs::StdRng;
use rand::SeedableRng;
fn dummy_coin_public_key(nonce: u8) -> CoinPublicKey {
CoinPublicKey([nonce; 32])
}
fn dummy_contract_address(
nonce: u8,
) -> moonproof_ledger::coin_structure::contract::ContractAddress {
moonproof_ledger::coin_structure::contract::ContractAddress(
moonproof_ledger::base_crypto::hash::HashOutput([nonce; 32]),
)
}
fn dummy_coin_info(value: u128, nonce_byte: u8) -> CoinInfo {
CoinInfo {
nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput(
[nonce_byte; 32],
)),
type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
),
value,
}
}
#[test]
fn empty_zswap_state_returns_no_offer() {
let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
let resolver = create_encryption_public_key_resolver(
dummy_coin_public_key(0xAA),
EncPublicKey([0x11; 32]),
None,
);
let mut rng = StdRng::seed_from_u64(0);
let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap();
assert!(
offer.is_none(),
"empty zswap state must produce no offer (TS returns undefined)"
);
}
#[test]
fn create_zswap_output_errors_for_unknown_user_recipient() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let wallet_enc_key = EncPublicKey([0x11; 32]);
let unknown_pk = moonproof_ledger::coin_structure::coin::PublicKey(
moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
);
let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
let output = CompactZswapOutput {
coin_info: dummy_coin_info(50, 1),
recipient: Recipient::User(unknown_pk),
};
let mut rng = StdRng::seed_from_u64(1);
let err = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("Unable to resolve encryption public key"),
"{msg}"
);
}
#[test]
fn contract_owned_output_does_not_consult_resolver() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let wallet_enc_key = EncPublicKey([0x11; 32]);
let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
let output = CompactZswapOutput {
coin_info: dummy_coin_info(100, 2),
recipient: Recipient::Contract(dummy_contract_address(0xCC)),
};
let mut rng = StdRng::seed_from_u64(2);
let out = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap();
let stored = out
.contract_address
.as_ref()
.expect("contract-owned output must carry the contract address");
assert_eq!(**stored, dummy_contract_address(0xCC));
}
#[test]
fn zswap_state_to_offer_errors_when_input_has_no_chain_state() {
let mut state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
state
.inputs
.push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32])),
type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
),
value: 100,
mt_index: 0,
});
let resolver = create_encryption_public_key_resolver(
dummy_coin_public_key(0xAA),
EncPublicKey([0x11; 32]),
None,
);
let mut rng = StdRng::seed_from_u64(3);
let err = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("ContractInputContext"),
"expected the diagnostic to mention ContractInputContext, got: {msg}"
);
}
#[test]
fn zswap_state_to_new_coins_filters_to_recipient() {
let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
);
let wallet_coin_key = CoinPublicKey([0xAA; 32]);
let other_pk = moonproof_ledger::coin_structure::coin::PublicKey(
moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
);
let mut state = CompactZswapLocalState::empty(wallet_coin_key);
state.outputs.push(CompactZswapOutput {
coin_info: dummy_coin_info(10, 1),
recipient: Recipient::User(wallet_pk),
});
state.outputs.push(CompactZswapOutput {
coin_info: dummy_coin_info(20, 2),
recipient: Recipient::User(other_pk),
});
state.outputs.push(CompactZswapOutput {
coin_info: dummy_coin_info(30, 3),
recipient: Recipient::Contract(dummy_contract_address(0xCC)),
});
let new_coins = zswap_state_to_new_coins(&wallet_coin_key, &state);
assert_eq!(new_coins.len(), 1);
assert_eq!(new_coins[0].value, 10);
}
#[test]
fn zswap_secret_keys_pipeline_round_trips_encryption() {
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
use rand::rngs::StdRng;
use rand::SeedableRng;
let mut seed_bytes = [0u8; 32];
seed_bytes[31] = 0x01;
let seed = ZswapSeed::from(seed_bytes);
let zswap_keys = ZswapSecretKeys::from(seed);
let mut bytes = Vec::with_capacity(32);
zswap_keys
.enc_public_key()
.serialize(&mut bytes)
.expect("serialize wallet enc_public_key");
assert_eq!(bytes.len(), 32);
let arr: [u8; 32] = bytes.try_into().unwrap();
let wallet_enc_key = EncPublicKey(arr);
let target_epk = to_ledger_enc_public_key(&wallet_enc_key).expect("round-trip wallet epk");
assert_eq!(zswap_keys.enc_public_key(), target_epk);
let mut rng = StdRng::seed_from_u64(0x1234_5678);
let coin = moonproof_ledger::coin_structure::coin::Info {
nonce: moonproof_ledger::coin_structure::coin::Nonce(
moonproof_ledger::base_crypto::hash::HashOutput([0xAB; 32]),
),
type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
),
value: 1_000_000,
};
let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, target_epk);
let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
ciphertext.into();
let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
zswap_keys.encryption_secret_key.decrypt(&ledger_ciph);
let decrypted = decrypted.expect(
"decryption with the wallet's encryption_secret_key must succeed against a \
ciphertext encrypted to the round-tripped enc_public_key — if this fails, \
the bug is in our pipeline; if this passes but the live test fails, the \
bug is in the harness's wallet-indexer scan",
);
assert_eq!(
decrypted, coin,
"decrypted coin info must match the encrypted plaintext"
);
}
#[test]
fn enc_pubkey_byte_roundtrip_preserves_decryption() {
use moonproof_ledger::serialize::Serializable;
use rand::rngs::StdRng;
use rand::SeedableRng;
let mut rng = StdRng::seed_from_u64(0xABCD);
let sk = moonproof_ledger::transient_crypto::encryption::SecretKey::new(&mut rng);
let pk_orig = sk.public_key();
let mut bytes = Vec::new();
pk_orig
.serialize(&mut bytes)
.expect("serialize encryption public key");
assert_eq!(
bytes.len(),
32,
"encryption::PublicKey must serialize to exactly 32 bytes"
);
let arr: [u8; 32] = bytes.try_into().unwrap();
let epk = EncPublicKey(arr);
let pk_round = to_ledger_enc_public_key(&epk).expect("round-trip");
assert_eq!(pk_orig, pk_round, "round-tripped public key must match");
let coin = moonproof_ledger::coin_structure::coin::Info {
nonce: moonproof_ledger::coin_structure::coin::Nonce(
moonproof_ledger::base_crypto::hash::HashOutput([0x11; 32]),
),
type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
),
value: 12345,
};
let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, pk_round);
let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
ciphertext.into();
let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
sk.decrypt(&ledger_ciph);
let decrypted = decrypted.expect(
"decryption with the original secret key must succeed against a \
ciphertext encrypted to the round-tripped public key — without \
this guarantee, the indexer can't surface our coin via \
shieldedTransactions",
);
assert_eq!(
decrypted, coin,
"decrypted coin must match the encrypted plaintext"
);
}
#[test]
fn encryption_resolver_for_zswap_state_rejects_mismatched_cpk() {
let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
let result = encryption_public_key_resolver_for_zswap_state(
&state,
dummy_coin_public_key(0xBB), EncPublicKey([0x11; 32]),
None,
);
match result {
Ok(_) => panic!("mismatched coin public keys must error"),
Err(err) => {
let msg = format!("{err}");
assert!(msg.contains("Unsupported coin"), "{msg}");
}
}
}
#[test]
fn zswap_state_to_offer_creates_outputs_only_when_no_inputs() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
);
let mut state = CompactZswapLocalState::empty(wallet_coin_key);
state.outputs.push(CompactZswapOutput {
coin_info: dummy_coin_info(100, 1),
recipient: Recipient::User(wallet_pk),
});
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
BURN_ENCRYPTION_PUBLIC_KEY,
None,
);
let mut rng = StdRng::seed_from_u64(0x10);
let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
.unwrap()
.expect("non-empty state must produce an offer");
assert_eq!(offer.outputs.len(), 1, "exactly one output");
assert_eq!(offer.inputs.len(), 0, "no inputs without anchored context");
assert_eq!(offer.transient.len(), 0, "no transients without inputs");
}
#[test]
fn zswap_state_to_offer_handles_zero_value_contract_output() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let mut state = CompactZswapLocalState::empty(wallet_coin_key);
state.outputs.push(CompactZswapOutput {
coin_info: dummy_coin_info(0, 7),
recipient: Recipient::Contract(dummy_contract_address(0xCC)),
});
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
BURN_ENCRYPTION_PUBLIC_KEY,
None,
);
let mut rng = StdRng::seed_from_u64(0x11);
let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
.unwrap()
.expect("zero-value output is still a valid output");
assert_eq!(offer.outputs.len(), 1);
assert_eq!(offer.inputs.len(), 0);
assert_eq!(offer.transient.len(), 0);
}
#[test]
fn zswap_state_to_offer_creates_transient_for_matching_pair() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let coin = dummy_coin_info(100, 5);
let mut state = CompactZswapLocalState::empty(wallet_coin_key);
state
.inputs
.push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
nonce: coin.nonce,
type_: coin.type_,
value: coin.value,
mt_index: 0,
});
state.outputs.push(CompactZswapOutput {
coin_info: coin,
recipient: Recipient::Contract(dummy_contract_address(0xCC)),
});
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
BURN_ENCRYPTION_PUBLIC_KEY,
None,
);
let mut rng = StdRng::seed_from_u64(0x12);
let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
.unwrap()
.expect("matched input/output pair produces an offer");
assert_eq!(
offer.transient.len(),
1,
"co-located input + output collapses to one transient"
);
assert_eq!(
offer.inputs.len(),
0,
"no leftover input — the input matched the output"
);
assert_eq!(
offer.outputs.len(),
0,
"no leftover output — the output matched the input"
);
}
#[test]
fn zswap_state_to_offer_creates_transient_for_zero_value_matching_pair() {
let wallet_coin_key = dummy_coin_public_key(0xAA);
let coin = dummy_coin_info(0, 9);
let mut state = CompactZswapLocalState::empty(wallet_coin_key);
state
.inputs
.push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
nonce: coin.nonce,
type_: coin.type_,
value: coin.value,
mt_index: 0,
});
state.outputs.push(CompactZswapOutput {
coin_info: coin,
recipient: Recipient::Contract(dummy_contract_address(0xCC)),
});
let resolver = create_encryption_public_key_resolver(
wallet_coin_key,
BURN_ENCRYPTION_PUBLIC_KEY,
None,
);
let mut rng = StdRng::seed_from_u64(0x13);
let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
.unwrap()
.expect("zero-value matched pair still produces an offer");
assert_eq!(offer.transient.len(), 1);
assert_eq!(offer.inputs.len(), 0);
assert_eq!(offer.outputs.len(), 0);
}
}