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;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ShieldedBalanceSummary {
pub available: u128,
pub pending: u128,
}
impl ShieldedBalanceSummary {
#[inline]
#[must_use]
pub fn total(self) -> u128 {
self.available.saturating_add(self.pending)
}
}
#[derive(Debug, Clone)]
pub struct ShieldedCoin {
pub coin: QualifiedInfo,
pub commitment: Commitment,
pub nullifier: Nullifier,
}
pub type AvailableCoin = ShieldedCoin;
#[derive(Debug, Clone)]
pub struct PendingCoin {
pub coin: CoinInfo,
pub commitment: Commitment,
}
#[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; out
}
#[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
}
#[must_use]
pub fn total_coins(
state: &ShieldedState,
secret_keys: &ZswapSecretKeys,
) -> (Vec<AvailableCoin>, Vec<PendingCoin>) {
(available_coins(state, secret_keys), pending_coins(state))
}
#[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
}
fn qci_as_info(qci: &QualifiedInfo) -> CoinInfo {
CoinInfo {
nonce: qci.nonce,
type_: qci.type_,
value: qci.value,
}
}
fn coin_commitment(
coin: &CoinInfo,
coin_public_key: moonproof_ledger::coin_structure::coin::PublicKey,
) -> Commitment {
coin.commitment(&Recipient::User(coin_public_key))
}
#[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);
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");
}
}