moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Read-only projections over [`ShieldedState`] — `available_coins`,
//! `pending_coins`, `total_coins`, and `wallet_balance`.
//!
//! Port of
//! `@midnight-ntwrk/wallet-sdk-shielded-wallet/v1/CoinsAndBalances.ts`.
//!
//! ## Semantics (matches the TS reference)
//!
//! - An **available** coin is one that the chain has confirmed
//!   ([`moonproof_ledger::zswap::local::State::coins`]) AND whose nullifier is
//!   not in [`moonproof_ledger::zswap::local::State::pending_spends`]. Once we
//!   issue a local spend for a coin, it's no longer available — the
//!   balance "freezes" it until the chain confirms or rejects the spend.
//! - A **pending** coin is one we've watched-for via
//!   [`ShieldedState::watch_for`] — i.e. a coin we expect to receive
//!   (often a change output) but whose commitment the indexer hasn't
//!   yet yielded. It sits in [`moonproof_ledger::zswap::local::State::pending_outputs`]
//!   keyed by commitment.
//! - Wallet balance is the sum of available + pending coin values per
//!   [`moonproof_ledger::coin_structure::coin::ShieldedTokenType`], split into
//!   `available` and `pending` running totals. Zero entries are
//!   suppressed (match the TS reference, which omits empty token keys).
//!
//! Commitments and nullifiers are recomputed on demand from the coin's
//! `nonce` + the wallet's keys — a single persistent-hash each. The TS
//! reference caches these in a `CoinHashesMap`; moonproof skips the
//! cache because the cost is trivial and the cache is UI-scope, not
//! load-bearing.

use std::borrow::Cow;
use std::collections::HashSet;

use indexmap::IndexMap;
use moonproof_ledger::coin_structure::coin::{
    Commitment, Info as CoinInfo, Nonce, Nullifier, QualifiedInfo, ShieldedTokenType,
};
use moonproof_ledger::coin_structure::transfer::{Recipient, SenderEvidence};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;

use crate::shielded::state::ShieldedState;

/// Running totals for one shielded token — used in wallet-wide balance
/// summaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ShieldedBalanceSummary {
    pub available: u128,
    pub pending: u128,
}

impl ShieldedBalanceSummary {
    /// Combined total (`available + pending`), saturating on u128
    /// overflow. Realistic Midnight supplies never approach `u128::MAX`
    /// so saturation is a defensive default.
    #[inline]
    #[must_use]
    pub fn total(self) -> u128 {
        self.available.saturating_add(self.pending)
    }
}

/// A confirmed, unspent coin paired with its derived hashes.
#[derive(Debug, Clone)]
pub struct ShieldedCoin {
    pub coin: QualifiedInfo,
    pub commitment: Commitment,
    pub nullifier: Nullifier,
}

/// Alias matching the TS reference's `AvailableCoin`.
pub type AvailableCoin = ShieldedCoin;

/// A coin we've emitted to ourselves but whose commitment the indexer
/// hasn't yet confirmed. We don't have an `mt_index` yet, so there's
/// no [`QualifiedInfo`]; we expose the plain [`CoinInfo`] and its
/// pre-computed commitment.
#[derive(Debug, Clone)]
pub struct PendingCoin {
    pub coin: CoinInfo,
    pub commitment: Commitment,
}

/// Available coins (confirmed, not locally spent), in the order
/// [`moonproof_ledger::zswap::local::State::coins`] iterates them. Order is
/// deterministic under the underlying trie.
#[must_use]
pub fn available_coins(state: &ShieldedState, secret_keys: &ZswapSecretKeys) -> Vec<AvailableCoin> {
    let pending_spent_nonces: HashSet<Nonce> = state
        .local()
        .pending_spends
        .iter()
        .map(|(_, sp)| sp.nonce)
        .collect();

    let mut out = Vec::with_capacity(state.local().coins.size());
    for (nullifier, qci) in state.local().coins.iter() {
        if pending_spent_nonces.contains(&qci.nonce) {
            continue;
        }
        let coin = *qci;
        let commitment = coin_commitment(&qci_as_info(&coin), state.coin_public_key());
        out.push(ShieldedCoin {
            coin,
            commitment,
            nullifier,
        });
    }
    let _ = secret_keys; // signature mirrors TS (which takes keys for the hash cache we skip)
    out
}

/// Pending coins — outputs we watched for that haven't yet been
/// confirmed on-chain. One entry per distinct [`Commitment`] in
/// `pending_outputs`.
#[must_use]
pub fn pending_coins(state: &ShieldedState) -> Vec<PendingCoin> {
    let mut out = Vec::with_capacity(state.local().pending_outputs.size());
    for (commitment, coin) in state.local().pending_outputs.iter() {
        out.push(PendingCoin {
            coin: *coin,
            commitment,
        });
    }
    out
}

/// Available + pending coins, in that order.
#[must_use]
pub fn total_coins(
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
) -> (Vec<AvailableCoin>, Vec<PendingCoin>) {
    (available_coins(state, secret_keys), pending_coins(state))
}

/// Sum coin values per token type, split into available / pending.
///
/// The returned [`IndexMap`] preserves insertion order, which matches
/// the TS reference's reliance on deterministic iteration for snapshot
/// tests. Tokens with zero totals are **included** if they appeared in
/// either bucket at some point; fully-zero tokens never appear because
/// they're never inserted.
#[must_use]
pub fn wallet_balance(
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
) -> IndexMap<ShieldedTokenType, ShieldedBalanceSummary> {
    let mut totals: IndexMap<ShieldedTokenType, ShieldedBalanceSummary> = IndexMap::new();
    for c in available_coins(state, secret_keys) {
        let entry = totals.entry(c.coin.type_).or_default();
        entry.available = entry.available.saturating_add(c.coin.value);
    }
    for p in pending_coins(state) {
        let entry = totals.entry(p.coin.type_).or_default();
        entry.pending = entry.pending.saturating_add(p.coin.value);
    }
    totals
}

// --- Internal helpers --------------------------------------------------

fn qci_as_info(qci: &QualifiedInfo) -> CoinInfo {
    CoinInfo {
        nonce: qci.nonce,
        type_: qci.type_,
        value: qci.value,
    }
}

/// Re-compute the coin's commitment under this wallet's coin public key.
fn coin_commitment(
    coin: &CoinInfo,
    coin_public_key: moonproof_ledger::coin_structure::coin::PublicKey,
) -> Commitment {
    coin.commitment(&Recipient::User(coin_public_key))
}

/// Re-compute a coin's nullifier. Not currently used in this module
/// (nullifiers we return come from the state's own map), but kept
/// pub(crate) so tests can reuse the logic and so future code that
/// needs to pre-compute a spend's nullifier has a single derivation
/// path.
#[allow(dead_code)]
pub(crate) fn coin_nullifier(coin: &CoinInfo, secret_keys: &ZswapSecretKeys) -> Nullifier {
    coin.nullifier(&SenderEvidence::User(Cow::Borrowed(
        &secret_keys.coin_secret_key,
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::Seed as ZswapSeed;

    fn keys_from_byte(b: u8) -> ZswapSecretKeys {
        ZswapSecretKeys::from(ZswapSeed::from([b; 32]))
    }

    fn shielded_coin(nonce_byte: u8, type_byte: u8, value: u128) -> CoinInfo {
        CoinInfo {
            nonce: Nonce(HashOutput([nonce_byte; 32])),
            type_: ShieldedTokenType(HashOutput([type_byte; 32])),
            value,
        }
    }

    #[test]
    fn empty_state_has_no_coins_or_balance() {
        let keys = keys_from_byte(0x01);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        assert!(available_coins(&s, &keys).is_empty());
        assert!(pending_coins(&s).is_empty());
        assert!(wallet_balance(&s, &keys).is_empty());
    }

    #[test]
    fn watched_coin_shows_up_as_pending() {
        let keys = keys_from_byte(0x02);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let c = shielded_coin(0x10, 0xAA, 1_234);
        let after = s.watch_for(&c);
        let pending = pending_coins(&after);
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].coin.value, 1_234);
        // Available excludes pending — watched-for coins aren't yet
        // confirmed.
        assert!(available_coins(&after, &keys).is_empty());
    }

    #[test]
    fn wallet_balance_sums_pending_per_token() {
        let keys = keys_from_byte(0x03);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let c1 = shielded_coin(0x01, 0xAA, 100);
        let c2 = shielded_coin(0x02, 0xAA, 200);
        let c3 = shielded_coin(0x03, 0xBB, 50);
        let after = s.watch_for(&c1).watch_for(&c2).watch_for(&c3);
        let bal = wallet_balance(&after, &keys);
        let sum_a = bal
            .get(&ShieldedTokenType(HashOutput([0xAA; 32])))
            .copied()
            .unwrap_or_default();
        let sum_b = bal
            .get(&ShieldedTokenType(HashOutput([0xBB; 32])))
            .copied()
            .unwrap_or_default();
        assert_eq!(sum_a.pending, 300);
        assert_eq!(sum_a.available, 0);
        assert_eq!(sum_b.pending, 50);
        assert_eq!(sum_b.total(), 50);
    }

    #[test]
    fn balance_summary_total_is_available_plus_pending() {
        let s = ShieldedBalanceSummary {
            available: 100,
            pending: 23,
        };
        assert_eq!(s.total(), 123);
    }

    #[test]
    fn coin_nullifier_round_trips() {
        let keys = keys_from_byte(0x04);
        let c = shielded_coin(0x77, 0x88, 1);
        let n1 = coin_nullifier(&c, &keys);
        let n2 = coin_nullifier(&c, &keys);
        assert_eq!(n1, n2);
    }

    #[test]
    fn pending_coins_preserves_multiple_entries() {
        let keys = keys_from_byte(0x05);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let c1 = shielded_coin(0xA1, 0x55, 1);
        let c2 = shielded_coin(0xA2, 0x55, 2);
        let c3 = shielded_coin(0xA3, 0x55, 3);
        let after = s.watch_for(&c1).watch_for(&c2).watch_for(&c3);
        let out = pending_coins(&after);
        assert_eq!(out.len(), 3);
        let values: Vec<u128> = out.iter().map(|p| p.coin.value).collect();
        let mut sorted = values.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![1, 2, 3]);
    }

    #[test]
    fn total_coins_concatenates_available_and_pending() {
        let keys = keys_from_byte(0x06);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let c1 = shielded_coin(0x11, 0x22, 100);
        let c2 = shielded_coin(0x12, 0x22, 200);
        let after = s.watch_for(&c1).watch_for(&c2);
        let (av, pd) = total_coins(&after, &keys);
        assert!(av.is_empty());
        assert_eq!(pd.len(), 2);
    }

    #[test]
    fn wallet_balance_omits_fully_zero_tokens() {
        let keys = keys_from_byte(0x07);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let bal = wallet_balance(&s, &keys);
        assert!(bal.is_empty(), "no coins → no token entries");
    }
}