Skip to main content

moonproof_contracts/utils/
zswap_utils.rs

1//! Port of
2//! `@midnight-ntwrk/midnight-js-contracts/src/utils/zswap-utils.ts`.
3//!
4//! Defines the [`EncryptionPublicKeyResolver`] closure signature, the
5//! two well-known constants that are load-bearing for the
6//! shielded-burn-address path
7//! ([`SHIELDED_BURN_COIN_PUBLIC_KEY`] and
8//! [`BURN_ENCRYPTION_PUBLIC_KEY`]), the
9//! [`CompactZswapLocalState`] / [`CompactZswapOutput`] shape that
10//! mirrors the TS `compact-runtime` `ZswapLocalState`, and the
11//! [`zswap_state_to_offer`] / [`create_zswap_output`] translators
12//! that turn that state into a ledger-typed `UnprovenOffer`.
13
14use 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
32/// Re-export of the underlying wallet-side zswap state — kept so
33/// existing call sites that need the wallet's view of received coins
34/// (`coins`, `pending_outputs`, `merkle_tree`, etc.) can still reach
35/// it. The compact-runtime side uses
36/// [`CompactZswapLocalState`] instead.
37pub use moonproof_ledger::zswap::local::State as ZswapWalletState;
38
39/// The shielded-burn coin public key — all zeros, 32 bytes. Matches
40/// TS `SHIELDED_BURN_COIN_PUBLIC_KEY = '0'.repeat(64)`. Coins sent
41/// here are unspendable because the corresponding coin secret key is
42/// the null key.
43pub const SHIELDED_BURN_COIN_PUBLIC_KEY: CoinPublicKey = CoinPublicKey([0u8; 32]);
44
45/// Burn address encryption public key. Derived via SHA-256
46/// (`"midnight:burn-encryption-key:{i}"` with `i=9`, the first `i` that
47/// maps to a valid Jubjub curve point). Matches TS
48/// `BURN_ENCRYPTION_PUBLIC_KEY` exactly. The specific key doesn't
49/// matter for spend-ability (the coin secret key is null), but the
50/// value must be on-curve so output encryption succeeds.
51///
52/// Byte-level value: `f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65`.
53pub const BURN_ENCRYPTION_PUBLIC_KEY: EncPublicKey = EncPublicKey(const_hex_decode(
54    b"f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65",
55));
56
57/// Compile-time hex decoder for 64-char hex strings. Panics at const
58/// time if the input isn't exactly 64 valid hex chars — so a typo
59/// surfaces at build time, not as a silent data corruption.
60const 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
72/// One-hex-char to `u8`. Panics on non-hex input (compile-time
73/// validation for the constant above).
74const 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
83/// Resolves a [`CoinPublicKey`] to the [`EncPublicKey`] used to seal
84/// outputs addressed to that coin key.
85///
86/// Returning `None` means "I don't know this recipient" — the caller
87/// (typically [`zswap_state_to_offer`]) treats that as a hard error
88/// because a zswap output with no known encryption key can't be
89/// constructed.
90///
91/// Port of TS `EncryptionPublicKeyResolver`.
92pub type EncryptionPublicKeyResolver =
93    Box<dyn Fn(CoinPublicKey) -> Option<EncPublicKey> + Send + Sync>;
94
95/// Construct an [`EncryptionPublicKeyResolver`] that resolves:
96///
97/// 1. The wallet's own coin public key → the wallet's encryption key.
98/// 2. The well-known [`SHIELDED_BURN_COIN_PUBLIC_KEY`] → the well-known
99///    [`BURN_ENCRYPTION_PUBLIC_KEY`].
100/// 3. Any additional caller-supplied mappings.
101///
102/// Port of TS `createEncryptionPublicKeyResolver`. The Rust port drops
103/// the TS "normalise to hex via `parseCoinPublicKeyToHex`" step
104/// because the Rust `CoinPublicKey` is a fixed-width `[u8; 32]`
105/// newtype — equality is byte-level by construction, no parsing
106/// required.
107#[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
128// CompactZswapLocalState / CompactZswapOutput live in
129// `moonproof_runtime::zswap_local` so the IR executor can build them
130// without depending on the heavy host crate. Re-export here so existing
131// `host::utils::zswap_utils::CompactZswap*` call sites keep working.
132pub use moonproof_runtime::zswap_local::{CompactZswapLocalState, CompactZswapOutput};
133
134/// Filter a [`CompactZswapLocalState`]'s outputs to the subset owned
135/// by `receiver_coin_public_key`. Port of TS `zswapStateToNewCoins` —
136/// the wallet calls this after executing a circuit so it can start
137/// watching for the produced coins.
138#[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
166// =====================================================================
167// Output construction
168// =====================================================================
169
170/// Convert our 32-byte [`EncPublicKey`] newtype into the ledger's
171/// [`moonproof_ledger::transient_crypto::encryption::PublicKey`] by
172/// deserializing the raw bytes. Returns a deserialize error if the
173/// bytes don't decode as a valid Jubjub group element (off-curve).
174fn 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
187/// Convert our [`CoinPublicKey`] newtype into the ledger's typed
188/// `coin::PublicKey`.
189fn 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
195/// Build a single ledger-typed [`Output`] for a circuit-emitted coin
196/// move. Port of TS `createZswapOutput`.
197///
198/// - For contract-recipient outputs, calls
199///   `Output::new_contract_owned`. No encryption key is needed —
200///   contracts read coin info directly out of the transcript.
201/// - For user-recipient outputs, looks up the recipient's
202///   encryption public key via the resolver, then calls
203///   `Output::new`. Errors with [`ContractRuntimeError::Provider`]
204///   when the resolver can't produce a key.
205///
206/// The `segment` parameter defaults to `0` per TS's
207/// `DEFAULT_SEGMENT_NUMBER` constant; the call site reaches the
208/// non-zero path only via the optional `segment` arg on
209/// [`zswap_state_to_offer`] (currently always `None`).
210pub 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// =====================================================================
245// zswap_state_to_offer — the main translator
246// =====================================================================
247
248/// Optional pair `(contract_address, zswap_chain_state)` threaded
249/// into [`zswap_state_to_offer`] when the call needs to spend
250/// contract-owned inputs. Mirrors the TS
251/// `addressAndChainStateTuple` parameter.
252#[derive(Debug, Clone, Copy)]
253pub struct ContractInputContext<'a> {
254    pub contract_address: ContractAddress,
255    pub zswap_chain_state: &'a ZswapChainState<InMemoryDB>,
256}
257
258/// Default segment number used by [`zswap_state_to_offer`] for every
259/// output / input / transient it constructs. Matches TS
260/// `DEFAULT_SEGMENT_NUMBER = 0`.
261pub const DEFAULT_SEGMENT_NUMBER: u16 = 0;
262
263/// Translate a [`CompactZswapLocalState`] into a ledger-typed
264/// [`Offer`]. Port of TS `zswapStateToOffer`.
265///
266/// Walks the state's outputs and inputs, classifying each as a pure
267/// output (recipient ≠ caller and no matching input), pure input
268/// (matching `coin_info` on-chain but no co-located output), or
269/// transient (matching co-located input + output that cancels out).
270/// Returns `Ok(None)` when the state has no outputs / inputs /
271/// transients — the empty case (matches TS `undefined` return).
272///
273/// # Errors
274///
275/// - When an output addresses a user the resolver doesn't know
276///   about: [`ContractRuntimeError::Provider`].
277/// - When a contract-owned input is supplied but no
278///   `ContractInputContext` was provided to anchor it against the
279///   chain state: [`ContractRuntimeError::Provider`].
280pub 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    // Build outputs first, keyed by serialized coin_info so we can
289    // detect input/output collisions and promote them to transients.
290    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    // Build the ChainState's post-block-update view that
299    // `Input::new_contract_owned` needs to anchor inputs. The TS
300    // version calls `zswapChainState.postBlockUpdate(new Date())`;
301    // the Rust analogue is `post_block_update(now)`.
302    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    // Walk inputs. Each input either matches an output (→ transient,
314    // remove from output_map) or stands alone (→ input).
315    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
363/// The segment a guaranteed Zswap item is built for.
364pub const GUARANTEED_SEGMENT_NUMBER: u16 = 0;
365
366/// One call's shielded activity, the input to
367/// [`zswap_calls_to_segmented_offer`].
368#[derive(Clone, Copy)]
369pub struct ZswapCallContribution<'a> {
370    /// The contract whose circuit ran. `None` only for a state whose
371    /// owner is unknown, which can pair inputs into transients but not
372    /// spend a settled coin.
373    pub contract_address: Option<ContractAddress>,
374    pub zswap_local_state: &'a CompactZswapLocalState,
375    /// The owner's own view of the commitment tree, needed only to spend
376    /// a coin settled on chain.
377    pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
378    pub partitioned_transcript: PartitionedTranscriptRef<'a>,
379}
380
381/// A transaction's shielded offers, one per segment kind.
382pub struct SegmentedOffers {
383    pub guaranteed: Option<Offer<ProofPreimage, InMemoryDB>>,
384    /// Built for the segment passed to
385    /// [`zswap_calls_to_segmented_offer`].
386    pub fallible: Option<Offer<ProofPreimage, InMemoryDB>>,
387}
388
389/// A call's transcript, split into its guaranteed and fallible halves.
390pub type PartitionedTranscriptRef<'a> = (
391    Option<&'a Transcript<InMemoryDB>>,
392    Option<&'a Transcript<InMemoryDB>>,
393);
394
395/// Which segment kind a coin movement belongs to.
396#[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
411/// The segment of the first transcript half that claims an item.
412/// Guaranteed takes precedence over fallible, across every transcript
413/// the owner produced: its local state accumulates over its calls, so a
414/// later call reports coins only an earlier call's transcript claims.
415fn 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
448/// The ledger routes an output by the union of a transcript's claimed
449/// receives and spends: a contract-owned output is a receive, a
450/// user-bound one a spend.
451fn 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
476/// One owner's shielded activity across the call tree: coins unioned by
477/// identity, since each call's local state is a view of one growing
478/// accumulator, and every transcript the owner produced.
479struct 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        // Only a spend of a settled coin needs the chain state, so the call
504        // reporting that spend is not necessarily the one that carried it.
505        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
551/// Build a transaction's guaranteed and fallible shielded offers from
552/// the shielded activity of every call in its call tree. Port of
553/// midnight-js 5's `zswapCallsToSegmentedOffer`.
554///
555/// A coin sent to a contract is credited only if that contract claims
556/// the receive in the same transaction, so a callee's coins reach the
557/// offers as the root's do, and each contract-owned input is bound to
558/// the contract that spent it. Routing follows the ledger's own
559/// (`midnight-ledger/ledger/src/construct.rs`), applied per owner:
560///
561/// - an output goes where a transcript claims its commitment as a
562///   receive or a spend;
563/// - an input goes where a transcript claims its nullifier;
564/// - an input that pairs with an output of the same coin and owner,
565///   anywhere in the tree, becomes a transient in the output's segment.
566///
567/// The fallible offer is built for `fallible_segment`, the segment of
568/// the intent carrying the calls.
569///
570/// # Errors
571///
572/// - A coin movement no transcript half claims while both halves exist.
573/// - One commitment claimed in different segments by two owners.
574/// - A settled coin spent without a known owner or owner chain state.
575/// - An output to a user the resolver has no encryption key for.
576pub 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    // Outputs first, so that a coin created and spent in the same
590    // transaction is known by the time its input folds into a transient.
591    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
608/// The offers [`zswap_calls_to_segmented_offer`] fills, one owner at a
609/// time.
610struct 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    /// Bucket an owner's outputs, keyed by commitment: one coin sent by
623    /// one contract and received by another collapses to a single offer
624    /// output, since the ledger rejects a repeated commitment.
625    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                // A guaranteed call cannot contain a fallible one, so both
635                // sides of a send/receive pair must agree.
636                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    /// Bucket an owner's inputs: each pairs into a transient with an
670    /// output of the same coin and owner anywhere in the tree, or is a
671    /// settled coin spent against the owner's commitment tree.
672    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            // A settled coin proves against the commitment tree as its
691            // owner sees it, and its nullifier binds that owner.
692            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    /// Replace the output `commitment` names with a transient spending it.
747    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        // The transient's input proves against a tree holding only its own
765        // output, at index 0
766        // (`zswap/src/construct.rs::new_from_contract_owned_output`); the
767        // reported `mt_index` is a position among the transaction's
768        // commitments and names the wrong leaf there.
769        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
784/// The output an input of unknown owner pairs with, found by coin
785/// contents alone. Several candidates cannot be told apart.
786fn 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
810/// Check that every coin the offers address to a contract is claimed as
811/// received by that contract, per segment, exactly as many times as the
812/// offers carry it. The ledger enforces the same equality after proving
813/// but reports only an error code; checking here names both sides.
814/// Port of midnight-js 5's `assertReceivesMatchClaims`.
815///
816/// `calls` pairs each call's contract with its partitioned transcript.
817///
818/// # Errors
819///
820/// When the offered and claimed counts differ for some coin.
821pub 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/// Equality key for matching an [`Input`] against an [`Output`]
884/// produced by the same circuit execution. Mirrors the TS
885/// `serializeCoinInfo` / `serializeQualifiedShieldedCoinInfo` pattern
886/// of "drop `mt_index`, hash the rest".
887#[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// =====================================================================
912// encryption_public_key_resolver_for_zswap_state
913// =====================================================================
914
915/// Construct an [`EncryptionPublicKeyResolver`] for a
916/// [`CompactZswapLocalState`], validating that the state's coin
917/// public key matches the wallet's (otherwise the wallet can't decrypt
918/// produced outputs). Port of TS
919/// `encryptionPublicKeyResolverForZswapState`.
920#[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    // Silence dead_code warning when only some code paths use it.
948    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        // SHIELDED_BURN_COIN_PUBLIC_KEY is the all-zeros 32-byte key.
958        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        // Reference bytes from the TS constant.
965        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    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver precedence::wallet key takes precedence over additional-mapping override for the wallet cpk`
1015    /// ports: `enc-pub-key-resolver.test.ts::createEncryptionPublicKeyResolver and encryptionPublicKeyResolverForZswapState normalize mappings`
1016    /// ports: `enc-pub-key-resolver.test.ts::deployContract forwards additionalCoinEncPublicKeyMappings to submitDeployTx`
1017    /// ports: `enc-pub-key-resolver.test.ts::createCircuitCallTxInterface includes additional mappings from TransactionContext in call options`
1018    /// (the Rust port pipes `additional_coin_enc_public_key_mappings`
1019    /// through `deploy_contract` → `unproven_deploy_tx` and `call_tx` →
1020    /// `unproven_call_tx` via the same struct field — the TS forwarding
1021    /// tests are reduced to the typed-field plumbing this test
1022    /// covers, plus the precedence assertion below.)
1023    ///
1024    /// Security-critical: the upstream TS comment cites issue #745.
1025    /// A DApp-supplied mapping must NOT be able to redirect the
1026    /// wallet's own outputs to an attacker-controlled key, even if
1027    /// the mapping explicitly tries to override the wallet cpk →
1028    /// wallet epk binding.
1029    #[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        // A DApp-supplied mapping that attempts to hijack the wallet
1036        // cpk → its own epk binding.
1037        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        // The resolver must still return the wallet's real epk —
1044        // not the malicious one.
1045        assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
1046        assert_ne!(resolver(wallet_coin_key), Some(malicious_epk));
1047    }
1048
1049    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver precedence::burn encryption key takes precedence over additional-mapping override for the burn cpk`
1050    #[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        // A DApp-supplied mapping that tries to redirect the burn
1057        // address to a key the attacker controls — would let stolen
1058        // funds be spent if it took effect.
1059        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    // -----------------------------------------------------------------
1072    // Ports of the remaining `utils/zswap-utils.test.ts` cases that
1073    // operate on Rust-side types. The TS variant exercises
1074    // `serializeCoinInfo` / `deserializeCoinInfo` (a TS-specific JSON
1075    // serializer with bigint round-tripping) — those don't have a
1076    // Rust port because Rust callers operate on typed `CoinInfo`
1077    // values directly. The remaining test categories — empty-state,
1078    // matched input/output → transient, contract-input requires
1079    // chain-state, etc. — all port over.
1080    // -----------------------------------------------------------------
1081
1082    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        // Use the native shielded token type.
1101        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    /// ports: `utils/zswap-utils.test.ts::should return undefined offer for empty zswap state - changed in ledger 6`
1113    #[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    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver::should return undefined for unknown coin public key`
1130    /// — exercised through the create-output path.
1131    ///
1132    /// `create_zswap_output` errors when the recipient is a user
1133    /// whose CPK the resolver can't map to an EPK.
1134    #[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    /// ports: `utils/zswap-utils.test.ts::should not require encryption key for contract-owned outputs`
1157    ///
1158    /// Contract-owned outputs skip the resolver — they store the
1159    /// `coin_info` verbatim in the public transcript so the receiving
1160    /// contract can read it without decryption.
1161    #[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        // Should not error even though the resolver doesn't know this
1172        // contract address — contracts don't need an encryption key.
1173        let out = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap();
1174        // Contract address must round-trip into the output's
1175        // contract_address slot.
1176        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    /// `zswap_state_to_offer` errors loudly when a non-transient
1184    /// input has no anchoring chain state — input commitments need
1185    /// the zswap chain state's merkle tree to construct the input's
1186    /// merkle proof.
1187    #[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        // An input with no co-located output and no contract context.
1191        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    /// ports: `utils/zswap-utils.test.ts::should return only coins meant for provided wallet in zswapStateToNewCoins`
1216    #[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    /// End-to-end: derive `ZswapSecretKeys` from the genesis seed
1244    /// (the same path the live integration test uses), encrypt a
1245    /// coin to the wallet's `enc_public_key()` after a 32-byte
1246    /// `EncPublicKey` round-trip (the same path
1247    /// `create_zswap_output` exercises), and decrypt with the
1248    /// wallet's `encryption_secret_key`. This is the strongest
1249    /// possible local proof that the indexer's wallet-relevance
1250    /// scan SHOULD pick up our mint outputs.
1251    ///
1252    /// If this test passes but the live wallet-indexer fails to
1253    /// surface our mint via `shieldedTransactions`, the bug is
1254    /// definitely on the harness side (wallet-indexer
1255    /// staleness/scan), not in our pipeline.
1256    #[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        // Same seed shape as the genesis wallet — 32 bytes,
1264        // `0x00..01` ending in 0x01.
1265        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        // The path our live test uses to build wallet_enc_key.
1271        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        // Round-trip through to_ledger_enc_public_key — same as
1281        // `create_zswap_output`.
1282        let target_epk = to_ledger_enc_public_key(&wallet_enc_key).expect("round-trip wallet epk");
1283        // Sanity: round-tripped EPK equals the original.
1284        assert_eq!(zswap_keys.enc_public_key(), target_epk);
1285
1286        // Encrypt a CoinInfo to the round-tripped EPK — what
1287        // `Output::new(... Some(target_epk))` does internally via
1288        // `CoinCiphertext::new(rng, coin, target_epk)`.
1289        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        // Decrypt with the wallet's secret key — what the
1302        // indexer's `can_decrypt_v8` does to flag a transaction as
1303        // relevant for our viewing key.
1304        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    /// Round-tripping an `encryption::PublicKey` through
1321    /// `EncPublicKey`'s 32-byte storage and back must preserve
1322    /// decryption correctness — i.e. a coin encrypted to the
1323    /// round-tripped public key must decrypt with the original
1324    /// secret key. Without this guarantee the indexer's viewing-key
1325    /// match would silently fail for every output the call-tx
1326    /// pipeline emits, masking a critical bug as "wallet didn't see
1327    /// the coin".
1328    #[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        // Serialize → 32 bytes → wrap in our newtype.
1338        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        // Round-trip through to_ledger_enc_public_key.
1351        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        // Encrypt a coin to the round-tripped public key.
1355        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        // Decrypt with the ORIGINAL secret key — this is what the
1367        // indexer's wallet-relevance scan does.
1368        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    /// `encryption_public_key_resolver_for_zswap_state` rejects a
1385    /// state whose `coin_public_key` doesn't match the wallet's —
1386    /// matches TS's `Unable to lookup encryption public key
1387    /// (Unsupported coin)` error.
1388    #[test]
1389    fn encryption_resolver_for_zswap_state_rejects_mismatched_cpk() {
1390        let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
1391        // The resolver type doesn't impl Debug (it's a Box<dyn Fn>),
1392        // so we can't `.unwrap_err()` directly. Match on the error
1393        // variant instead.
1394        let result = encryption_public_key_resolver_for_zswap_state(
1395            &state,
1396            dummy_coin_public_key(0xBB), // mismatched
1397            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    /// ports: `utils/zswap-utils.test.ts::should create correct number of outputs when no inputs`
1410    ///
1411    /// One output, no inputs, no chain-state context → offer carries
1412    /// exactly one output and zero inputs / transients.
1413    #[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    /// ports: `utils/zswap-utils.test.ts::should handle zero value outputs correctly`
1439    ///
1440    /// A zero-value output is still a valid output — the offer
1441    /// carries it without erroring, and the contract-recipient
1442    /// branch doesn't consult the resolver (so a zero-value
1443    /// contract-owned output round-trips even with no resolver
1444    /// mapping for that contract address).
1445    #[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    /// ports: `utils/zswap-utils.test.ts::should create transient for single matching input-output pair`
1468    ///
1469    /// When `inputs` and `outputs` share a coin (same nonce / type /
1470    /// value), the offer collapses both into a single Transient
1471    /// instead of a (input, output) pair. This avoids consulting the
1472    /// chain state for the input — transients carry their own proof
1473    /// via the co-located output.
1474    #[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        // Same coin appears as both an input (qualified with
1480        // mt_index) and an output to a contract recipient.
1481        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        // No ContractInputContext required — the matching output
1500        // lets `zswap_state_to_offer` route through the transient
1501        // path before consulting the chain state.
1502        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    /// ports: `utils/zswap-utils.test.ts::should create transient with zero delta for zero value matching pair`
1523    ///
1524    /// Zero-value matching input/output pairs still produce a
1525    /// transient — the value is zero on both sides, so the delta is
1526    /// zero, but the transient still records the coin's nonce/type
1527    /// so the kernel can audit the spend.
1528    #[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}