1use std::collections::HashMap;
15
16use moonproof_ledger::base_crypto::hash::HashOutput;
17use moonproof_ledger::coin_structure::coin::{
18 Info as CoinInfo, QualifiedInfo as QualifiedCoinInfo,
19};
20use moonproof_ledger::coin_structure::contract::ContractAddress;
21use moonproof_ledger::coin_structure::transfer::Recipient;
22use moonproof_ledger::onchain_runtime::transcript::Transcript;
23use moonproof_ledger::storage::db::InMemoryDB;
24use moonproof_ledger::transient_crypto::proofs::ProofPreimage;
25use moonproof_ledger::zswap::ledger::State as ZswapChainState;
26use moonproof_ledger::zswap::{Input, Offer, Output, Transient};
27use rand::{CryptoRng, Rng};
28
29use crate::error::{ContractRuntimeError, Result};
30use crate::types::{CoinPublicKey, EncPublicKey};
31
32pub use moonproof_ledger::zswap::local::State as ZswapWalletState;
38
39pub const SHIELDED_BURN_COIN_PUBLIC_KEY: CoinPublicKey = CoinPublicKey([0u8; 32]);
44
45pub const BURN_ENCRYPTION_PUBLIC_KEY: EncPublicKey = EncPublicKey(const_hex_decode(
54 b"f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65",
55));
56
57const fn const_hex_decode(s: &[u8; 64]) -> [u8; 32] {
61 let mut out = [0u8; 32];
62 let mut i = 0;
63 while i < 32 {
64 let hi = hex_nibble(s[i * 2]);
65 let lo = hex_nibble(s[i * 2 + 1]);
66 out[i] = (hi << 4) | lo;
67 i += 1;
68 }
69 out
70}
71
72const fn hex_nibble(c: u8) -> u8 {
75 match c {
76 b'0'..=b'9' => c - b'0',
77 b'a'..=b'f' => c - b'a' + 10,
78 b'A'..=b'F' => c - b'A' + 10,
79 _ => panic!("invalid hex character"),
80 }
81}
82
83pub type EncryptionPublicKeyResolver =
93 Box<dyn Fn(CoinPublicKey) -> Option<EncPublicKey> + Send + Sync>;
94
95#[expect(
108 clippy::implicit_hasher,
109 reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
110)]
111pub fn create_encryption_public_key_resolver(
112 wallet_coin_public_key: CoinPublicKey,
113 wallet_encryption_public_key: EncPublicKey,
114 additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
115) -> EncryptionPublicKeyResolver {
116 let additional = additional.unwrap_or_default();
117 Box::new(move |coin_public_key: CoinPublicKey| {
118 if coin_public_key == wallet_coin_public_key {
119 Some(wallet_encryption_public_key)
120 } else if coin_public_key == SHIELDED_BURN_COIN_PUBLIC_KEY {
121 Some(BURN_ENCRYPTION_PUBLIC_KEY)
122 } else {
123 additional.get(&coin_public_key).copied()
124 }
125 })
126}
127
128pub use moonproof_runtime::zswap_local::{CompactZswapLocalState, CompactZswapOutput};
133
134#[must_use]
139pub fn zswap_state_to_new_coins(
140 receiver_coin_public_key: &CoinPublicKey,
141 zswap_state: &CompactZswapLocalState,
142) -> Vec<CoinInfo> {
143 zswap_state
144 .outputs
145 .iter()
146 .filter_map(|out| match &out.recipient {
147 Recipient::User(pk) => {
148 if pk_matches(pk, receiver_coin_public_key) {
149 Some(out.coin_info)
150 } else {
151 None
152 }
153 }
154 Recipient::Contract(_) => None,
155 })
156 .collect()
157}
158
159fn pk_matches(
160 ledger_pk: &moonproof_ledger::coin_structure::coin::PublicKey,
161 moonproof_pk: &CoinPublicKey,
162) -> bool {
163 ledger_pk.0 .0 == moonproof_pk.0
164}
165
166fn to_ledger_enc_public_key(
175 epk: &EncPublicKey,
176) -> Result<moonproof_ledger::transient_crypto::encryption::PublicKey> {
177 use moonproof_ledger::serialize::Deserializable;
178 let mut cursor = &epk.0[..];
179 moonproof_ledger::transient_crypto::encryption::PublicKey::deserialize(&mut cursor, 0).map_err(
180 |e| ContractRuntimeError::Deserialize {
181 context: "EncPublicKey -> encryption::PublicKey",
182 source: e,
183 },
184 )
185}
186
187fn to_ledger_coin_public_key(
190 cpk: &CoinPublicKey,
191) -> moonproof_ledger::coin_structure::coin::PublicKey {
192 moonproof_ledger::coin_structure::coin::PublicKey(HashOutput(cpk.0))
193}
194
195pub fn create_zswap_output<R: Rng + CryptoRng>(
211 rng: &mut R,
212 output: &CompactZswapOutput,
213 resolver: &EncryptionPublicKeyResolver,
214 segment: Option<u16>,
215) -> Result<Output<ProofPreimage, InMemoryDB>> {
216 match &output.recipient {
217 Recipient::Contract(contract) => {
218 Output::new_contract_owned(rng, &output.coin_info, segment, *contract).map_err(|e| {
219 ContractRuntimeError::Provider {
220 provider: "create_zswap_output::contract",
221 message: format!("Output::new_contract_owned failed: {e:?}"),
222 }
223 })
224 }
225 Recipient::User(pk) => {
226 let cpk = CoinPublicKey(pk.0 .0);
227 let epk_bytes = resolver(cpk).ok_or_else(|| ContractRuntimeError::Provider {
228 provider: "create_zswap_output::user",
229 message: "Unable to resolve encryption public key for recipient. \
230 Provide a mapping via the encryption_public_key_resolver."
231 .to_owned(),
232 })?;
233 let epk = to_ledger_enc_public_key(&epk_bytes)?;
234 Output::new(rng, &output.coin_info, segment, pk, Some(epk)).map_err(|e| {
235 ContractRuntimeError::Provider {
236 provider: "create_zswap_output::user",
237 message: format!("Output::new failed: {e:?}"),
238 }
239 })
240 }
241 }
242}
243
244#[derive(Debug, Clone, Copy)]
253pub struct ContractInputContext<'a> {
254 pub contract_address: ContractAddress,
255 pub zswap_chain_state: &'a ZswapChainState<InMemoryDB>,
256}
257
258pub const DEFAULT_SEGMENT_NUMBER: u16 = 0;
262
263pub fn zswap_state_to_offer<R: Rng + CryptoRng>(
281 rng: &mut R,
282 state: &CompactZswapLocalState,
283 resolver: &EncryptionPublicKeyResolver,
284 contract_input_ctx: Option<ContractInputContext<'_>>,
285) -> Result<Option<Offer<ProofPreimage, InMemoryDB>>> {
286 use std::collections::HashMap as StdHashMap;
287
288 let mut output_map: StdHashMap<CoinInfoKey, Output<ProofPreimage, InMemoryDB>> =
291 StdHashMap::new();
292 for entry in &state.outputs {
293 let key = CoinInfoKey::from(&entry.coin_info);
294 let out = create_zswap_output(rng, entry, resolver, Some(DEFAULT_SEGMENT_NUMBER))?;
295 output_map.insert(key, out);
296 }
297
298 let rehashed_chain_state = contract_input_ctx.as_ref().map(|c| {
303 moonproof_ledger::zswap_post_block_update(
304 c.zswap_chain_state,
305 moonproof_ledger::base_crypto::time::Timestamp::from_secs(
306 moonproof_utils::rt::SystemTime::now()
307 .duration_since(moonproof_utils::rt::UNIX_EPOCH)
308 .map_or(0, |d| d.as_secs()),
309 ),
310 )
311 });
312
313 let mut input_vec: Vec<Input<ProofPreimage, InMemoryDB>> = Vec::new();
316 let mut transient_vec: Vec<Transient<ProofPreimage, InMemoryDB>> = Vec::new();
317 for qcoin in &state.inputs {
318 let key = CoinInfoKey::from_qualified(qcoin);
319 if let Some(matched_output) = output_map.remove(&key) {
320 let transient = Transient::new_from_contract_owned_output(
321 rng,
322 qcoin,
323 Some(DEFAULT_SEGMENT_NUMBER),
324 matched_output,
325 )
326 .map_err(|e| ContractRuntimeError::Provider {
327 provider: "zswap_state_to_offer::transient",
328 message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
329 })?;
330 transient_vec.push(transient);
331 } else {
332 let ctx = contract_input_ctx
333 .as_ref()
334 .ok_or(ContractRuntimeError::Provider {
335 provider: "zswap_state_to_offer::input",
336 message: "input has no co-located output and no \
337 ContractInputContext was provided — non-transient \
338 inputs require an anchored chain state"
339 .to_owned(),
340 })?;
341 let chain_state = rehashed_chain_state
342 .as_ref()
343 .expect("rehashed chain state present whenever ctx is");
344 let input = Input::new_contract_owned(
345 rng,
346 qcoin,
347 Some(DEFAULT_SEGMENT_NUMBER),
348 ctx.contract_address,
349 &chain_state.coin_coms,
350 )
351 .map_err(|e| ContractRuntimeError::Provider {
352 provider: "zswap_state_to_offer::input",
353 message: format!("Input::new_contract_owned failed: {e:?}"),
354 })?;
355 input_vec.push(input);
356 }
357 }
358
359 let outputs: Vec<Output<ProofPreimage, InMemoryDB>> = output_map.into_values().collect();
360 Ok(Offer::new(input_vec, outputs, transient_vec))
361}
362
363pub const GUARANTEED_SEGMENT_NUMBER: u16 = 0;
365
366#[derive(Clone, Copy)]
369pub struct ZswapCallContribution<'a> {
370 pub contract_address: Option<ContractAddress>,
374 pub zswap_local_state: &'a CompactZswapLocalState,
375 pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
378 pub partitioned_transcript: PartitionedTranscriptRef<'a>,
379}
380
381pub struct SegmentedOffers {
383 pub guaranteed: Option<Offer<ProofPreimage, InMemoryDB>>,
384 pub fallible: Option<Offer<ProofPreimage, InMemoryDB>>,
387}
388
389pub type PartitionedTranscriptRef<'a> = (
391 Option<&'a Transcript<InMemoryDB>>,
392 Option<&'a Transcript<InMemoryDB>>,
393);
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
397enum SegmentKind {
398 Guaranteed,
399 Fallible,
400}
401
402impl SegmentKind {
403 fn number(self, fallible_segment: u16) -> u16 {
404 match self {
405 SegmentKind::Guaranteed => GUARANTEED_SEGMENT_NUMBER,
406 SegmentKind::Fallible => fallible_segment,
407 }
408 }
409}
410
411fn segment_for_match(
416 claims: impl Fn(&Transcript<InMemoryDB>) -> bool,
417 transcripts: &[PartitionedTranscriptRef<'_>],
418 what: impl FnOnce() -> String,
419) -> Result<SegmentKind> {
420 if transcripts
421 .iter()
422 .any(|(guaranteed, _)| guaranteed.is_some_and(&claims))
423 {
424 return Ok(SegmentKind::Guaranteed);
425 }
426 if transcripts
427 .iter()
428 .any(|(_, fallible)| fallible.is_some_and(&claims))
429 {
430 return Ok(SegmentKind::Fallible);
431 }
432 if transcripts
433 .iter()
434 .any(|(guaranteed, fallible)| guaranteed.is_some() && fallible.is_some())
435 {
436 return Err(ContractRuntimeError::Provider {
437 provider: "zswap_calls_to_segmented_offer",
438 message: format!(
439 "{} is not present in either segment of the partitioned transcript; the local \
440 zswap state does not match the contract's declared effects",
441 what()
442 ),
443 });
444 }
445 Ok(SegmentKind::Guaranteed)
446}
447
448fn segment_for_commitment(
452 commitment: &moonproof_ledger::coin_structure::coin::Commitment,
453 transcripts: &[PartitionedTranscriptRef<'_>],
454) -> Result<SegmentKind> {
455 segment_for_match(
456 |t| {
457 t.effects.claimed_shielded_receives.member(commitment)
458 || t.effects.claimed_shielded_spends.member(commitment)
459 },
460 transcripts,
461 || format!("shielded commitment {}", hex::encode(commitment.0 .0)),
462 )
463}
464
465fn segment_for_nullifier(
466 nullifier: &moonproof_ledger::coin_structure::coin::Nullifier,
467 transcripts: &[PartitionedTranscriptRef<'_>],
468) -> Result<SegmentKind> {
469 segment_for_match(
470 |t| t.effects.claimed_nullifiers.member(nullifier),
471 transcripts,
472 || format!("shielded nullifier {}", hex::encode(nullifier.0 .0)),
473 )
474}
475
476struct OwnerActivity<'a> {
480 owner: Option<ContractAddress>,
481 chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
482 outputs: indexmap::IndexMap<
483 moonproof_ledger::coin_structure::coin::Commitment,
484 &'a CompactZswapOutput,
485 >,
486 inputs: indexmap::IndexMap<(CoinInfoKey, u64), QualifiedCoinInfo>,
487 transcripts: Vec<PartitionedTranscriptRef<'a>>,
488}
489
490fn group_by_owner<'a>(contributions: &[ZswapCallContribution<'a>]) -> Vec<OwnerActivity<'a>> {
491 let mut owners: indexmap::IndexMap<Option<ContractAddress>, OwnerActivity<'a>> =
492 indexmap::IndexMap::new();
493 for contribution in contributions {
494 let activity = owners
495 .entry(contribution.contract_address)
496 .or_insert_with(|| OwnerActivity {
497 owner: contribution.contract_address,
498 chain_state: None,
499 outputs: indexmap::IndexMap::new(),
500 inputs: indexmap::IndexMap::new(),
501 transcripts: Vec::new(),
502 });
503 if activity.chain_state.is_none() {
506 activity.chain_state = contribution.zswap_chain_state;
507 }
508 activity
509 .transcripts
510 .push(contribution.partitioned_transcript);
511 for output in &contribution.zswap_local_state.outputs {
512 activity
513 .outputs
514 .insert(output.coin_info.commitment(&output.recipient), output);
515 }
516 for input in &contribution.zswap_local_state.inputs {
517 activity
518 .inputs
519 .insert((CoinInfoKey::from_qualified(input), input.mt_index), *input);
520 }
521 }
522 owners.into_values().collect()
523}
524
525#[derive(Default)]
526struct SegmentBucket {
527 inputs: indexmap::IndexMap<
528 moonproof_ledger::coin_structure::coin::Nullifier,
529 Input<ProofPreimage, InMemoryDB>,
530 >,
531 outputs: indexmap::IndexMap<
532 moonproof_ledger::coin_structure::coin::Commitment,
533 Output<ProofPreimage, InMemoryDB>,
534 >,
535 transients: indexmap::IndexMap<
536 moonproof_ledger::coin_structure::coin::Commitment,
537 Transient<ProofPreimage, InMemoryDB>,
538 >,
539}
540
541impl SegmentBucket {
542 fn into_offer(self) -> Option<Offer<ProofPreimage, InMemoryDB>> {
543 Offer::new(
544 self.inputs.into_values().collect(),
545 self.outputs.into_values().collect(),
546 self.transients.into_values().collect(),
547 )
548 }
549}
550
551pub fn zswap_calls_to_segmented_offer<R: Rng + CryptoRng>(
577 rng: &mut R,
578 contributions: &[ZswapCallContribution<'_>],
579 resolver: &EncryptionPublicKeyResolver,
580 fallible_segment: u16,
581) -> Result<SegmentedOffers> {
582 let activities = group_by_owner(contributions);
583 let mut offers = OfferAssembly {
584 fallible_segment,
585 buckets: std::collections::HashMap::new(),
586 segment_of_output: std::collections::HashMap::new(),
587 commitments_by_coin: std::collections::HashMap::new(),
588 };
589 for activity in &activities {
592 offers.add_outputs(rng, activity, resolver)?;
593 }
594 for activity in &activities {
595 offers.add_inputs(rng, activity)?;
596 }
597 let mut buckets = offers.buckets;
598 Ok(SegmentedOffers {
599 guaranteed: buckets
600 .remove(&SegmentKind::Guaranteed)
601 .and_then(SegmentBucket::into_offer),
602 fallible: buckets
603 .remove(&SegmentKind::Fallible)
604 .and_then(SegmentBucket::into_offer),
605 })
606}
607
608struct OfferAssembly {
611 fallible_segment: u16,
612 buckets: std::collections::HashMap<SegmentKind, SegmentBucket>,
613 segment_of_output:
614 std::collections::HashMap<moonproof_ledger::coin_structure::coin::Commitment, SegmentKind>,
615 commitments_by_coin: std::collections::HashMap<
616 CoinInfoKey,
617 Vec<moonproof_ledger::coin_structure::coin::Commitment>,
618 >,
619}
620
621impl OfferAssembly {
622 fn add_outputs<R: Rng + CryptoRng>(
626 &mut self,
627 rng: &mut R,
628 activity: &OwnerActivity<'_>,
629 resolver: &EncryptionPublicKeyResolver,
630 ) -> Result<()> {
631 for (commitment, output) in &activity.outputs {
632 let segment = segment_for_commitment(commitment, &activity.transcripts)?;
633 if let Some(already) = self.segment_of_output.get(commitment) {
634 if *already != segment {
637 return Err(ContractRuntimeError::Provider {
638 provider: "zswap_calls_to_segmented_offer",
639 message: format!(
640 "shielded commitment {} is claimed in the {already:?} segment by one \
641 call and the {segment:?} segment by another; the calls' transcripts \
642 disagree",
643 hex::encode(commitment.0 .0)
644 ),
645 });
646 }
647 continue;
648 }
649 self.segment_of_output.insert(*commitment, segment);
650 self.commitments_by_coin
651 .entry(CoinInfoKey::from(&output.coin_info))
652 .or_default()
653 .push(*commitment);
654 let built = create_zswap_output(
655 rng,
656 output,
657 resolver,
658 Some(segment.number(self.fallible_segment)),
659 )?;
660 self.buckets
661 .entry(segment)
662 .or_default()
663 .outputs
664 .insert(*commitment, built);
665 }
666 Ok(())
667 }
668
669 fn add_inputs<R: Rng + CryptoRng>(
673 &mut self,
674 rng: &mut R,
675 activity: &OwnerActivity<'_>,
676 ) -> Result<()> {
677 let mut rehashed: Option<ZswapChainState<InMemoryDB>> = None;
678 for qcoin in activity.inputs.values() {
679 let coin = CoinInfo::from(qcoin);
680 let own_commitment = match activity.owner {
681 Some(address) => Some(coin.commitment(&Recipient::Contract(address))),
682 None => sole_commitment_for(&coin, &self.commitments_by_coin)?,
683 };
684 if let Some((commitment, segment)) = own_commitment
685 .and_then(|c| self.segment_of_output.get(&c).map(|segment| (c, *segment)))
686 {
687 self.add_transient(rng, &coin, commitment, segment)?;
688 continue;
689 }
690 let Some(address) = activity.owner else {
693 return Err(ContractRuntimeError::Provider {
694 provider: "zswap_calls_to_segmented_offer",
695 message: "a call that spends a settled shielded coin must name the contract \
696 that spent it, since the nullifier binds the spender"
697 .to_owned(),
698 });
699 };
700 let chain_state =
701 activity
702 .chain_state
703 .ok_or_else(|| ContractRuntimeError::Provider {
704 provider: "zswap_calls_to_segmented_offer",
705 message: format!(
706 "contract {} spends a shielded coin with no co-located output, and no \
707 anchoring chain state (ContractInputContext) was provided; non-transient \
708 inputs require an anchored chain state",
709 moonproof_runtime::state::contract_address_to_hex(&address)
710 ),
711 })?;
712 let tree = rehashed.get_or_insert_with(|| {
713 moonproof_ledger::zswap_post_block_update(
714 chain_state,
715 moonproof_ledger::base_crypto::time::Timestamp::from_secs(
716 moonproof_utils::rt::SystemTime::now()
717 .duration_since(moonproof_utils::rt::UNIX_EPOCH)
718 .map_or(0, |d| d.as_secs()),
719 ),
720 )
721 });
722 let nullifier = coin.nullifier(
723 &moonproof_ledger::coin_structure::transfer::SenderEvidence::Contract(address),
724 );
725 let segment = segment_for_nullifier(&nullifier, &activity.transcripts)?;
726 let input = Input::new_contract_owned(
727 rng,
728 qcoin,
729 Some(segment.number(self.fallible_segment)),
730 address,
731 &tree.coin_coms,
732 )
733 .map_err(|e| ContractRuntimeError::Provider {
734 provider: "zswap_calls_to_segmented_offer",
735 message: format!("Input::new_contract_owned failed: {e:?}"),
736 })?;
737 self.buckets
738 .entry(segment)
739 .or_default()
740 .inputs
741 .insert(nullifier, input);
742 }
743 Ok(())
744 }
745
746 fn add_transient<R: Rng + CryptoRng>(
748 &mut self,
749 rng: &mut R,
750 coin: &CoinInfo,
751 commitment: moonproof_ledger::coin_structure::coin::Commitment,
752 segment: SegmentKind,
753 ) -> Result<()> {
754 let bucket = self.buckets.entry(segment).or_default();
755 let output = bucket.outputs.shift_remove(&commitment).ok_or_else(|| {
756 ContractRuntimeError::Provider {
757 provider: "zswap_calls_to_segmented_offer",
758 message: format!(
759 "no bucketed output for transient commitment {}",
760 hex::encode(commitment.0 .0)
761 ),
762 }
763 })?;
764 let transient = Transient::new_from_contract_owned_output(
770 rng,
771 &coin.qualify(0),
772 Some(segment.number(self.fallible_segment)),
773 output,
774 )
775 .map_err(|e| ContractRuntimeError::Provider {
776 provider: "zswap_calls_to_segmented_offer",
777 message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
778 })?;
779 bucket.transients.insert(commitment, transient);
780 Ok(())
781 }
782}
783
784fn sole_commitment_for(
787 coin: &CoinInfo,
788 commitments_by_coin: &std::collections::HashMap<
789 CoinInfoKey,
790 Vec<moonproof_ledger::coin_structure::coin::Commitment>,
791 >,
792) -> Result<Option<moonproof_ledger::coin_structure::coin::Commitment>> {
793 match commitments_by_coin
794 .get(&CoinInfoKey::from(coin))
795 .map(Vec::as_slice)
796 {
797 None | Some([]) => Ok(None),
798 Some([only]) => Ok(Some(*only)),
799 Some(candidates) => Err(ContractRuntimeError::Provider {
800 provider: "zswap_calls_to_segmented_offer",
801 message: format!(
802 "ambiguous transient: {} outputs carry the coin of an input whose spending \
803 contract is unknown, so the pair cannot be identified",
804 candidates.len()
805 ),
806 }),
807 }
808}
809
810pub fn assert_receives_match_claims(
822 calls: &[(ContractAddress, PartitionedTranscriptRef<'_>)],
823 offers: &SegmentedOffers,
824) -> Result<()> {
825 type Key = (
826 u8,
827 moonproof_ledger::coin_structure::coin::Commitment,
828 ContractAddress,
829 );
830 let mut counts: indexmap::IndexMap<Key, (usize, usize)> = indexmap::IndexMap::new();
831 for (segment, offer) in [(0u8, &offers.guaranteed), (1u8, &offers.fallible)] {
832 let Some(offer) = offer else { continue };
833 let outputs = offer
834 .outputs
835 .iter()
836 .map(|o| (o.coin_com, o.contract_address.as_ref().map(|a| **a)));
837 let transients = offer
838 .transient
839 .iter()
840 .map(|t| (t.coin_com, t.contract_address.as_ref().map(|a| **a)));
841 for (commitment, address) in outputs.chain(transients) {
842 if let Some(address) = address {
843 counts.entry((segment, commitment, address)).or_default().0 += 1;
844 }
845 }
846 }
847 for (address, (guaranteed, fallible)) in calls {
848 for (segment, half) in [(0u8, guaranteed), (1u8, fallible)] {
849 let Some(transcript) = half else { continue };
850 for commitment in transcript.effects.claimed_shielded_receives.iter() {
851 counts
852 .entry((segment, **commitment, *address))
853 .or_default()
854 .1 += 1;
855 }
856 }
857 }
858 let differences: Vec<String> = counts
859 .iter()
860 .filter(|(_, (offered, claimed))| offered != claimed)
861 .map(|((segment, commitment, address), (offered, claimed))| {
862 format!(
863 " segment {segment} / {} / {}: offered {offered}, claimed {claimed}",
864 hex::encode(commitment.0 .0),
865 moonproof_runtime::state::contract_address_to_hex(address)
866 )
867 })
868 .collect();
869 if differences.is_empty() {
870 return Ok(());
871 }
872 Err(ContractRuntimeError::Provider {
873 provider: "assert_receives_match_claims",
874 message: format!(
875 "a shielded coin addressed to a contract must be claimed as received by that \
876 contract as many times as the offers carry it, and these do not match; the ledger \
877 rejects such a transaction after proving. Offer count vs claim count:\n{}",
878 differences.join("\n")
879 ),
880 })
881}
882
883#[derive(Debug, Clone, Hash, PartialEq, Eq)]
888struct CoinInfoKey {
889 nonce: HashOutput,
890 type_bytes: [u8; 32],
891 value: u128,
892}
893
894impl CoinInfoKey {
895 fn from(info: &CoinInfo) -> Self {
896 Self {
897 nonce: info.nonce.0,
898 type_bytes: info.type_.0 .0,
899 value: info.value,
900 }
901 }
902 fn from_qualified(info: &QualifiedCoinInfo) -> Self {
903 Self {
904 nonce: info.nonce.0,
905 type_bytes: info.type_.0 .0,
906 value: info.value,
907 }
908 }
909}
910
911#[expect(
921 clippy::implicit_hasher,
922 reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
923)]
924pub fn encryption_public_key_resolver_for_zswap_state(
925 zswap_state: &CompactZswapLocalState,
926 wallet_coin_public_key: CoinPublicKey,
927 wallet_encryption_public_key: EncPublicKey,
928 additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
929) -> Result<EncryptionPublicKeyResolver> {
930 if zswap_state.coin_public_key != wallet_coin_public_key {
931 return Err(ContractRuntimeError::Provider {
932 provider: "encryption_public_key_resolver_for_zswap_state",
933 message: "Unable to lookup encryption public key (Unsupported coin) — \
934 zswap state's coin_public_key doesn't match the wallet's"
935 .to_owned(),
936 });
937 }
938 Ok(create_encryption_public_key_resolver(
939 wallet_coin_public_key,
940 wallet_encryption_public_key,
941 additional,
942 ))
943}
944
945#[allow(dead_code)]
946fn _unused_to_ledger_coin_public_key_anchor() {
947 let _ = to_ledger_coin_public_key;
949}
950
951#[cfg(test)]
952mod tests {
953 use super::*;
954
955 #[test]
956 fn burn_constants_match_ts_exactly() {
957 assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.0, [0u8; 32]);
959 assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.to_hex(), "0".repeat(64));
960 }
961
962 #[test]
963 fn burn_encryption_key_matches_ts_byte_sequence() {
964 let expected =
966 hex::decode("f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65")
967 .unwrap();
968 assert_eq!(BURN_ENCRYPTION_PUBLIC_KEY.0.as_ref(), expected.as_slice());
969 }
970
971 #[test]
972 fn resolver_returns_wallet_key_for_self_lookup() {
973 let wallet_coin_key = CoinPublicKey([0x11; 32]);
974 let wallet_enc_key = EncPublicKey([0x22; 32]);
975 let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
976 assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
977 }
978
979 #[test]
980 fn resolver_resolves_shielded_burn_address() {
981 let wallet_coin_key = CoinPublicKey([0x11; 32]);
982 let wallet_enc_key = EncPublicKey([0x22; 32]);
983 let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
984 assert_eq!(
985 resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
986 Some(BURN_ENCRYPTION_PUBLIC_KEY),
987 );
988 }
989
990 #[test]
991 fn resolver_honours_additional_mappings() {
992 let wallet_coin_key = CoinPublicKey([0x11; 32]);
993 let wallet_enc_key = EncPublicKey([0x22; 32]);
994 let other_coin_key = CoinPublicKey([0x33; 32]);
995 let other_enc_key = EncPublicKey([0x44; 32]);
996 let mut additional = HashMap::new();
997 additional.insert(other_coin_key, other_enc_key);
998 let resolver = create_encryption_public_key_resolver(
999 wallet_coin_key,
1000 wallet_enc_key,
1001 Some(additional),
1002 );
1003 assert_eq!(resolver(other_coin_key), Some(other_enc_key));
1004 }
1005
1006 #[test]
1007 fn resolver_returns_none_for_unknown_key() {
1008 let wallet_coin_key = CoinPublicKey([0x11; 32]);
1009 let wallet_enc_key = EncPublicKey([0x22; 32]);
1010 let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
1011 assert_eq!(resolver(CoinPublicKey([0xff; 32])), None);
1012 }
1013
1014 #[test]
1030 fn wallet_key_precedence_blocks_additional_mapping_hijack() {
1031 let wallet_coin_key = CoinPublicKey([0x11; 32]);
1032 let wallet_enc_key = EncPublicKey([0x22; 32]);
1033 let malicious_epk = EncPublicKey([0xEE; 32]);
1034 let mut malicious_mapping = HashMap::new();
1035 malicious_mapping.insert(wallet_coin_key, malicious_epk);
1038 let resolver = create_encryption_public_key_resolver(
1039 wallet_coin_key,
1040 wallet_enc_key,
1041 Some(malicious_mapping),
1042 );
1043 assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
1046 assert_ne!(resolver(wallet_coin_key), Some(malicious_epk));
1047 }
1048
1049 #[test]
1051 fn burn_key_precedence_blocks_additional_mapping_hijack() {
1052 let wallet_coin_key = CoinPublicKey([0x11; 32]);
1053 let wallet_enc_key = EncPublicKey([0x22; 32]);
1054 let malicious_epk = EncPublicKey([0xEE; 32]);
1055 let mut malicious_mapping = HashMap::new();
1056 malicious_mapping.insert(SHIELDED_BURN_COIN_PUBLIC_KEY, malicious_epk);
1060 let resolver = create_encryption_public_key_resolver(
1061 wallet_coin_key,
1062 wallet_enc_key,
1063 Some(malicious_mapping),
1064 );
1065 assert_eq!(
1066 resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
1067 Some(BURN_ENCRYPTION_PUBLIC_KEY),
1068 );
1069 }
1070
1071 use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce};
1083 use moonproof_ledger::coin_structure::transfer::Recipient;
1084 use rand::rngs::StdRng;
1085 use rand::SeedableRng;
1086
1087 fn dummy_coin_public_key(nonce: u8) -> CoinPublicKey {
1088 CoinPublicKey([nonce; 32])
1089 }
1090
1091 fn dummy_contract_address(
1092 nonce: u8,
1093 ) -> moonproof_ledger::coin_structure::contract::ContractAddress {
1094 moonproof_ledger::coin_structure::contract::ContractAddress(
1095 moonproof_ledger::base_crypto::hash::HashOutput([nonce; 32]),
1096 )
1097 }
1098
1099 fn dummy_coin_info(value: u128, nonce_byte: u8) -> CoinInfo {
1100 CoinInfo {
1102 nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput(
1103 [nonce_byte; 32],
1104 )),
1105 type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
1106 moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
1107 ),
1108 value,
1109 }
1110 }
1111
1112 #[test]
1114 fn empty_zswap_state_returns_no_offer() {
1115 let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
1116 let resolver = create_encryption_public_key_resolver(
1117 dummy_coin_public_key(0xAA),
1118 EncPublicKey([0x11; 32]),
1119 None,
1120 );
1121 let mut rng = StdRng::seed_from_u64(0);
1122 let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap();
1123 assert!(
1124 offer.is_none(),
1125 "empty zswap state must produce no offer (TS returns undefined)"
1126 );
1127 }
1128
1129 #[test]
1135 fn create_zswap_output_errors_for_unknown_user_recipient() {
1136 let wallet_coin_key = dummy_coin_public_key(0xAA);
1137 let wallet_enc_key = EncPublicKey([0x11; 32]);
1138 let unknown_pk = moonproof_ledger::coin_structure::coin::PublicKey(
1139 moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
1140 );
1141 let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
1142
1143 let output = CompactZswapOutput {
1144 coin_info: dummy_coin_info(50, 1),
1145 recipient: Recipient::User(unknown_pk),
1146 };
1147 let mut rng = StdRng::seed_from_u64(1);
1148 let err = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap_err();
1149 let msg = format!("{err}");
1150 assert!(
1151 msg.contains("Unable to resolve encryption public key"),
1152 "{msg}"
1153 );
1154 }
1155
1156 #[test]
1162 fn contract_owned_output_does_not_consult_resolver() {
1163 let wallet_coin_key = dummy_coin_public_key(0xAA);
1164 let wallet_enc_key = EncPublicKey([0x11; 32]);
1165 let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
1166 let output = CompactZswapOutput {
1167 coin_info: dummy_coin_info(100, 2),
1168 recipient: Recipient::Contract(dummy_contract_address(0xCC)),
1169 };
1170 let mut rng = StdRng::seed_from_u64(2);
1171 let out = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap();
1174 let stored = out
1177 .contract_address
1178 .as_ref()
1179 .expect("contract-owned output must carry the contract address");
1180 assert_eq!(**stored, dummy_contract_address(0xCC));
1181 }
1182
1183 #[test]
1188 fn zswap_state_to_offer_errors_when_input_has_no_chain_state() {
1189 let mut state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
1190 state
1192 .inputs
1193 .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
1194 nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32])),
1195 type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
1196 moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
1197 ),
1198 value: 100,
1199 mt_index: 0,
1200 });
1201 let resolver = create_encryption_public_key_resolver(
1202 dummy_coin_public_key(0xAA),
1203 EncPublicKey([0x11; 32]),
1204 None,
1205 );
1206 let mut rng = StdRng::seed_from_u64(3);
1207 let err = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap_err();
1208 let msg = format!("{err}");
1209 assert!(
1210 msg.contains("ContractInputContext"),
1211 "expected the diagnostic to mention ContractInputContext, got: {msg}"
1212 );
1213 }
1214
1215 #[test]
1217 fn zswap_state_to_new_coins_filters_to_recipient() {
1218 let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
1219 moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
1220 );
1221 let wallet_coin_key = CoinPublicKey([0xAA; 32]);
1222 let other_pk = moonproof_ledger::coin_structure::coin::PublicKey(
1223 moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
1224 );
1225 let mut state = CompactZswapLocalState::empty(wallet_coin_key);
1226 state.outputs.push(CompactZswapOutput {
1227 coin_info: dummy_coin_info(10, 1),
1228 recipient: Recipient::User(wallet_pk),
1229 });
1230 state.outputs.push(CompactZswapOutput {
1231 coin_info: dummy_coin_info(20, 2),
1232 recipient: Recipient::User(other_pk),
1233 });
1234 state.outputs.push(CompactZswapOutput {
1235 coin_info: dummy_coin_info(30, 3),
1236 recipient: Recipient::Contract(dummy_contract_address(0xCC)),
1237 });
1238 let new_coins = zswap_state_to_new_coins(&wallet_coin_key, &state);
1239 assert_eq!(new_coins.len(), 1);
1240 assert_eq!(new_coins[0].value, 10);
1241 }
1242
1243 #[test]
1257 fn zswap_secret_keys_pipeline_round_trips_encryption() {
1258 use moonproof_ledger::serialize::Serializable;
1259 use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
1260 use rand::rngs::StdRng;
1261 use rand::SeedableRng;
1262
1263 let mut seed_bytes = [0u8; 32];
1266 seed_bytes[31] = 0x01;
1267 let seed = ZswapSeed::from(seed_bytes);
1268 let zswap_keys = ZswapSecretKeys::from(seed);
1269
1270 let mut bytes = Vec::with_capacity(32);
1272 zswap_keys
1273 .enc_public_key()
1274 .serialize(&mut bytes)
1275 .expect("serialize wallet enc_public_key");
1276 assert_eq!(bytes.len(), 32);
1277 let arr: [u8; 32] = bytes.try_into().unwrap();
1278 let wallet_enc_key = EncPublicKey(arr);
1279
1280 let target_epk = to_ledger_enc_public_key(&wallet_enc_key).expect("round-trip wallet epk");
1283 assert_eq!(zswap_keys.enc_public_key(), target_epk);
1285
1286 let mut rng = StdRng::seed_from_u64(0x1234_5678);
1290 let coin = moonproof_ledger::coin_structure::coin::Info {
1291 nonce: moonproof_ledger::coin_structure::coin::Nonce(
1292 moonproof_ledger::base_crypto::hash::HashOutput([0xAB; 32]),
1293 ),
1294 type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
1295 moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
1296 ),
1297 value: 1_000_000,
1298 };
1299 let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, target_epk);
1300
1301 let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
1305 ciphertext.into();
1306 let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
1307 zswap_keys.encryption_secret_key.decrypt(&ledger_ciph);
1308 let decrypted = decrypted.expect(
1309 "decryption with the wallet's encryption_secret_key must succeed against a \
1310 ciphertext encrypted to the round-tripped enc_public_key — if this fails, \
1311 the bug is in our pipeline; if this passes but the live test fails, the \
1312 bug is in the harness's wallet-indexer scan",
1313 );
1314 assert_eq!(
1315 decrypted, coin,
1316 "decrypted coin info must match the encrypted plaintext"
1317 );
1318 }
1319
1320 #[test]
1329 fn enc_pubkey_byte_roundtrip_preserves_decryption() {
1330 use moonproof_ledger::serialize::Serializable;
1331 use rand::rngs::StdRng;
1332 use rand::SeedableRng;
1333 let mut rng = StdRng::seed_from_u64(0xABCD);
1334 let sk = moonproof_ledger::transient_crypto::encryption::SecretKey::new(&mut rng);
1335 let pk_orig = sk.public_key();
1336
1337 let mut bytes = Vec::new();
1339 pk_orig
1340 .serialize(&mut bytes)
1341 .expect("serialize encryption public key");
1342 assert_eq!(
1343 bytes.len(),
1344 32,
1345 "encryption::PublicKey must serialize to exactly 32 bytes"
1346 );
1347 let arr: [u8; 32] = bytes.try_into().unwrap();
1348 let epk = EncPublicKey(arr);
1349
1350 let pk_round = to_ledger_enc_public_key(&epk).expect("round-trip");
1352 assert_eq!(pk_orig, pk_round, "round-tripped public key must match");
1353
1354 let coin = moonproof_ledger::coin_structure::coin::Info {
1356 nonce: moonproof_ledger::coin_structure::coin::Nonce(
1357 moonproof_ledger::base_crypto::hash::HashOutput([0x11; 32]),
1358 ),
1359 type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
1360 moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
1361 ),
1362 value: 12345,
1363 };
1364 let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, pk_round);
1365
1366 let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
1369 ciphertext.into();
1370 let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
1371 sk.decrypt(&ledger_ciph);
1372 let decrypted = decrypted.expect(
1373 "decryption with the original secret key must succeed against a \
1374 ciphertext encrypted to the round-tripped public key — without \
1375 this guarantee, the indexer can't surface our coin via \
1376 shieldedTransactions",
1377 );
1378 assert_eq!(
1379 decrypted, coin,
1380 "decrypted coin must match the encrypted plaintext"
1381 );
1382 }
1383
1384 #[test]
1389 fn encryption_resolver_for_zswap_state_rejects_mismatched_cpk() {
1390 let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
1391 let result = encryption_public_key_resolver_for_zswap_state(
1395 &state,
1396 dummy_coin_public_key(0xBB), EncPublicKey([0x11; 32]),
1398 None,
1399 );
1400 match result {
1401 Ok(_) => panic!("mismatched coin public keys must error"),
1402 Err(err) => {
1403 let msg = format!("{err}");
1404 assert!(msg.contains("Unsupported coin"), "{msg}");
1405 }
1406 }
1407 }
1408
1409 #[test]
1414 fn zswap_state_to_offer_creates_outputs_only_when_no_inputs() {
1415 let wallet_coin_key = dummy_coin_public_key(0xAA);
1416 let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
1417 moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
1418 );
1419 let mut state = CompactZswapLocalState::empty(wallet_coin_key);
1420 state.outputs.push(CompactZswapOutput {
1421 coin_info: dummy_coin_info(100, 1),
1422 recipient: Recipient::User(wallet_pk),
1423 });
1424 let resolver = create_encryption_public_key_resolver(
1425 wallet_coin_key,
1426 BURN_ENCRYPTION_PUBLIC_KEY,
1427 None,
1428 );
1429 let mut rng = StdRng::seed_from_u64(0x10);
1430 let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
1431 .unwrap()
1432 .expect("non-empty state must produce an offer");
1433 assert_eq!(offer.outputs.len(), 1, "exactly one output");
1434 assert_eq!(offer.inputs.len(), 0, "no inputs without anchored context");
1435 assert_eq!(offer.transient.len(), 0, "no transients without inputs");
1436 }
1437
1438 #[test]
1446 fn zswap_state_to_offer_handles_zero_value_contract_output() {
1447 let wallet_coin_key = dummy_coin_public_key(0xAA);
1448 let mut state = CompactZswapLocalState::empty(wallet_coin_key);
1449 state.outputs.push(CompactZswapOutput {
1450 coin_info: dummy_coin_info(0, 7),
1451 recipient: Recipient::Contract(dummy_contract_address(0xCC)),
1452 });
1453 let resolver = create_encryption_public_key_resolver(
1454 wallet_coin_key,
1455 BURN_ENCRYPTION_PUBLIC_KEY,
1456 None,
1457 );
1458 let mut rng = StdRng::seed_from_u64(0x11);
1459 let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
1460 .unwrap()
1461 .expect("zero-value output is still a valid output");
1462 assert_eq!(offer.outputs.len(), 1);
1463 assert_eq!(offer.inputs.len(), 0);
1464 assert_eq!(offer.transient.len(), 0);
1465 }
1466
1467 #[test]
1475 fn zswap_state_to_offer_creates_transient_for_matching_pair() {
1476 let wallet_coin_key = dummy_coin_public_key(0xAA);
1477 let coin = dummy_coin_info(100, 5);
1478 let mut state = CompactZswapLocalState::empty(wallet_coin_key);
1479 state
1482 .inputs
1483 .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
1484 nonce: coin.nonce,
1485 type_: coin.type_,
1486 value: coin.value,
1487 mt_index: 0,
1488 });
1489 state.outputs.push(CompactZswapOutput {
1490 coin_info: coin,
1491 recipient: Recipient::Contract(dummy_contract_address(0xCC)),
1492 });
1493 let resolver = create_encryption_public_key_resolver(
1494 wallet_coin_key,
1495 BURN_ENCRYPTION_PUBLIC_KEY,
1496 None,
1497 );
1498 let mut rng = StdRng::seed_from_u64(0x12);
1499 let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
1503 .unwrap()
1504 .expect("matched input/output pair produces an offer");
1505 assert_eq!(
1506 offer.transient.len(),
1507 1,
1508 "co-located input + output collapses to one transient"
1509 );
1510 assert_eq!(
1511 offer.inputs.len(),
1512 0,
1513 "no leftover input — the input matched the output"
1514 );
1515 assert_eq!(
1516 offer.outputs.len(),
1517 0,
1518 "no leftover output — the output matched the input"
1519 );
1520 }
1521
1522 #[test]
1529 fn zswap_state_to_offer_creates_transient_for_zero_value_matching_pair() {
1530 let wallet_coin_key = dummy_coin_public_key(0xAA);
1531 let coin = dummy_coin_info(0, 9);
1532 let mut state = CompactZswapLocalState::empty(wallet_coin_key);
1533 state
1534 .inputs
1535 .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
1536 nonce: coin.nonce,
1537 type_: coin.type_,
1538 value: coin.value,
1539 mt_index: 0,
1540 });
1541 state.outputs.push(CompactZswapOutput {
1542 coin_info: coin,
1543 recipient: Recipient::Contract(dummy_contract_address(0xCC)),
1544 });
1545 let resolver = create_encryption_public_key_resolver(
1546 wallet_coin_key,
1547 BURN_ENCRYPTION_PUBLIC_KEY,
1548 None,
1549 );
1550 let mut rng = StdRng::seed_from_u64(0x13);
1551 let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
1552 .unwrap()
1553 .expect("zero-value matched pair still produces an offer");
1554 assert_eq!(offer.transient.len(), 1);
1555 assert_eq!(offer.inputs.len(), 0);
1556 assert_eq!(offer.outputs.len(), 0);
1557 }
1558}