moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Wallet-side balancer for contract-call transactions whose shielded
//! offer is intentionally unbalanced — typically because the contract
//! body emitted an `Output(Contract(self))` (Compact's
//! `receiveShielded(coin)`) without a matching input.  The wallet must
//! supply the user-owned inputs (and any change output) that close the
//! per-token deltas before the tx can land at the chain.
//!
//! Port of
//! `midnight-wallet/packages/shielded-wallet/src/v1/Transacting.ts::
//! balanceTransaction` (and its underlying `getBalanceRecipe` →
//! `prepareOffer` flow). Mirrors the canonical reference shape:
//!
//! 1. Read [`Transaction::balance`] to get per-`(TokenType, segment)`
//!    deltas.
//! 2. For each segment with a shielded imbalance, run the existing
//!    [`crate::balancer::balance`] primitive (already the Rust port of
//!    the reference's `getBalanceRecipe`) to pick coins + emit change.
//! 3. Materialize the chosen recipe into a `ZswapOffer<ProofPreimage>`
//!    via [`build_shielded_offer`] — the same primitive
//!    `Transacting.ts::#prepareOffer` calls under the hood (`spendCoins`
//!    + recipient outputs).
//! 4. Wrap the offer into a fresh [`Transaction`] and
//!    [`Transaction::merge`] it onto the original.
//!
//! Returns `Ok((tx, state))` unchanged when the input tx already
//! balances — matches the reference's `if (areBalanced) return
//! [undefined, state];` branch.

use std::collections::BTreeMap;

use moonproof_ledger::coin_structure::coin::{ShieldedTokenType, TokenType};
use moonproof_ledger::ledger::structure::Transaction;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use rand::{CryptoRng, Rng};

use crate::balancer::{balance, BalanceRequest, Imbalances, SmallestFirstSelector};
use crate::error::{Result, WalletError};
use crate::shielded::ledger_adapter::{build_shielded_offer, ShieldedSignedTransaction};
use crate::shielded::state::ShieldedState;
use crate::shielded::transacting::{
    candidate_inputs as shielded_candidate_inputs,
    token_type_from_wallet_string as shielded_token_type_from_wallet_string,
    token_type_to_wallet_string as shielded_token_type_to_wallet_string, ShieldedOutputSpec,
    ShieldedTransferRecipe, SHIELDED_COST_MODEL,
};
use crate::types::{Amount, TokenType as WalletTokenType};

/// Balance an unproven contract-call [`Transaction`] against the
/// caller's [`ShieldedState`].  Returns the merged tx (with the
/// balancing offer attached at the appropriate segments) plus the
/// updated state (coins moved into `pending_spends`, change outputs
/// watched-for).
///
/// When the input tx is already balanced for every shielded
/// `(TokenType, segment)` pair this returns the input tx and state
/// unchanged.
///
/// Errors:
/// - [`WalletError::InsufficientFunds`] if the candidate pool can't
///   close a deficit for some shielded token.
/// - [`WalletError::ShieldedOffer`] / [`WalletError::Serialization`]
///   propagated from the merge / offer-build path.
pub fn balance_contract_call_tx<R>(
    rng: &mut R,
    state: ShieldedState,
    secret_keys: &ZswapSecretKeys,
    tx: ShieldedSignedTransaction,
    network_id: &str,
) -> Result<(ShieldedSignedTransaction, ShieldedState)>
where
    R: Rng + CryptoRng,
{
    let raw_imbalances = tx.balance(None).map_err(|e| {
        WalletError::ShieldedOffer(format!(
            "Transaction::balance failed while reading shielded imbalances: {e:?}"
        ))
    })?;
    let (balancing, state) =
        build_shielded_balancing_tx(rng, state, secret_keys, &raw_imbalances, network_id)?;
    let Some(balancing) = balancing else {
        return Ok((tx, state));
    };
    let tx = tx.merge(&balancing).map_err(|e| {
        WalletError::ShieldedOffer(format!(
            "Transaction::merge of the shielded balancing tx failed: {e:?}"
        ))
    })?;
    Ok((tx, state))
}

/// The standalone transaction that closes every shielded imbalance in
/// `imbalances` (as [`Transaction::balance`] reports them) from this
/// wallet's coins: the guaranteed offer for segment 0, a fallible offer
/// for each other segment, each with its change, and any surplus
/// collected back to the wallet. Returns `None` when nothing is
/// imbalanced, so the caller has no leg to prove.
///
/// Port of midnight-wallet's shielded `balanceTransaction`: fallible
/// segments are balanced first, then the guaranteed one, each against
/// the coins the previous segments left unbooked. The spends are booked
/// and the change watched for in the returned state.
///
/// Errors:
/// - [`WalletError::InsufficientFunds`] if the wallet's coins can't
///   close a deficit for some shielded token.
/// - [`WalletError::ShieldedOffer`] from building an offer.
pub fn build_shielded_balancing_tx<R>(
    rng: &mut R,
    state: ShieldedState,
    secret_keys: &ZswapSecretKeys,
    imbalances: &BTreeMap<(TokenType, u16), i128>,
    network_id: &str,
) -> Result<(Option<ShieldedSignedTransaction>, ShieldedState)>
where
    R: Rng + CryptoRng,
{
    let mut by_segment = group_shielded_imbalances_by_segment(imbalances);
    if by_segment.is_empty() {
        return Ok((None, state));
    }
    // Fallible segments first, the guaranteed one last.
    by_segment.sort_by_key(|(segment, _)| (*segment == 0, *segment));

    let mut state = state;
    let mut guaranteed = None;
    let mut fallible: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    for (segment, segment_imbalances) in by_segment {
        let candidate_pool = shielded_candidate_inputs(&state, secret_keys);
        let our_coin_pk = crate::address::ShieldedCoinPublicKey(state.coin_public_key().0 .0);
        let our_enc_pk_bytes = encode_enc_pk(&state.encryption_public_key())?;
        let our_enc_pk = crate::address::ShieldedEncryptionPublicKey(our_enc_pk_bytes);

        // Reference's `getBalanceRecipe` consumes the imbalance map +
        // candidate coins. Output factory mirrors `prepareOffer`'s
        // `createShieldedCoinInfo` for change — change goes to the
        // caller's own keys.
        let placeholder_fee_token = WalletTokenType::new("shielded-fee-placeholder");
        let recipe = balance(BalanceRequest {
            coins: candidate_pool,
            initial_imbalances: segment_imbalances,
            target_imbalances: Imbalances::new(),
            cost_model: SHIELDED_COST_MODEL,
            fee_token: placeholder_fee_token,
            selector: &SmallestFirstSelector,
            create_output: |r| {
                let value = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
                let tt = shielded_token_type_from_wallet_string(&r.token_type).unwrap_or(
                    ShieldedTokenType(moonproof_ledger::transient_crypto::hash::HashOutput(
                        [0u8; 32],
                    )),
                );
                let coin = moonproof_ledger::coin_structure::coin::Info::new(rng, value, tt);
                ShieldedOutputSpec::new(coin, our_coin_pk.clone(), our_enc_pk.clone())
            },
            is_coin_equal: |a, b| a.qci.nonce == b.qci.nonce,
        })?;

        let transfer_recipe = ShieldedTransferRecipe {
            inputs: recipe.inputs.into_iter().map(|c| c.qci).collect(),
            recipient_outputs: Vec::new(),
            change_outputs: recipe.outputs,
        };
        let materialized =
            build_shielded_offer(rng, state.clone(), secret_keys, &transfer_recipe, segment)?;
        let Some((offer, next_state)) = materialized else {
            continue;
        };
        state = next_state;
        if segment == 0 {
            guaranteed = Some(offer);
        } else {
            fallible = fallible.insert(segment, offer);
        }
    }

    if guaranteed.is_none() && fallible.size() == 0 {
        return Ok((None, state));
    }
    let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
    let balancing: ShieldedSignedTransaction =
        Transaction::new(network_id, intents, guaranteed, fallible);
    Ok((Some(balancing), state))
}

/// Reduce the raw `(TokenType, segment) -> i128` imbalance map to the
/// per-segment `Imbalances` the balancer accepts, keeping only shielded
/// (zswap) tokens. Mirrors `Transacting.ts`'s segment partitioning
/// where the balancer runs once per (segment, token) pair.
fn group_shielded_imbalances_by_segment(
    raw: &BTreeMap<(TokenType, u16), i128>,
) -> Vec<(u16, Imbalances)> {
    let mut by_segment: BTreeMap<u16, Imbalances> = BTreeMap::new();
    for ((token, segment), value) in raw {
        if *value == 0 {
            continue;
        }
        let TokenType::Shielded(stt) = token else {
            continue;
        };
        let wallet_token = shielded_token_type_to_wallet_string(stt);
        let amount = Amount::from(*value);
        let imb = by_segment.entry(*segment).or_default();
        let existing = imb.get(&wallet_token);
        imb.set(wallet_token, existing + amount);
    }
    by_segment.into_iter().collect()
}

fn encode_enc_pk(
    pk: &moonproof_ledger::transient_crypto::encryption::PublicKey,
) -> Result<[u8; 32]> {
    use moonproof_ledger::serialize::Serializable;
    let mut buf = Vec::with_capacity(32);
    pk.serialize(&mut buf)
        .map_err(|e| WalletError::Serialization(format!("encryption PublicKey::serialize: {e}")))?;
    <[u8; 32]>::try_from(buf.as_slice()).map_err(|_| {
        WalletError::Serialization(format!(
            "encryption PublicKey serialized to {} bytes; expected 32",
            buf.len()
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce, ShieldedTokenType};
    use moonproof_ledger::coin_structure::contract::ContractAddress;
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::Seed as ZswapSeed;
    use moonproof_ledger::zswap::Output as ZswapOutput;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

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

    fn night_token() -> ShieldedTokenType {
        ShieldedTokenType(HashOutput([0u8; 32]))
    }

    fn dummy_contract() -> ContractAddress {
        ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0xCC; 32]))
    }

    fn seed_state_with_coin(keys: &ZswapSecretKeys, value: u128, nonce_byte: u8) -> ShieldedState {
        let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
        let info = CoinInfo {
            nonce: Nonce(HashOutput([nonce_byte; 32])),
            type_: night_token(),
            value,
        };
        local = local.insert_coin(keys, info).expect("insert_coin");
        ShieldedState::init(local, keys, NetworkId::Undeployed)
    }

    /// Build a contract-call-style Transaction whose only shielded
    /// content is an `Output(Contract(self))` of `value` NIGHT — the
    /// canonical shape `receiveShielded(coin)` produces.
    fn unbalanced_deposit_tx(rng: &mut StdRng, value: u128) -> ShieldedSignedTransaction {
        let coin = CoinInfo {
            nonce: Nonce(HashOutput([0x77; 32])),
            type_: night_token(),
            value,
        };
        let out =
            ZswapOutput::<_, InMemoryDB>::new_contract_owned(rng, &coin, Some(0), dummy_contract())
                .expect("new_contract_owned");
        let offer =
            moonproof_ledger::zswap::Offer::<_, InMemoryDB>::new(Vec::new(), vec![out], Vec::new())
                .expect("offer with one output");
        let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
        Transaction::new("local-test", intents, Some(offer), StorageHashMap::new())
    }

    #[test]
    fn balanced_input_returns_unchanged() {
        // No imbalances → balancer is a no-op.
        let mut rng = StdRng::seed_from_u64(0xAA);
        let keys = keys_from_byte(0x11);
        let state = seed_state_with_coin(&keys, 1_000, 0x55);
        let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
        let tx: ShieldedSignedTransaction =
            Transaction::new("local-test", intents, None, StorageHashMap::new());

        let (out_tx, _next_state) =
            balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
        // Empty tx round-trips clean — the balancer added nothing.
        match &out_tx {
            Transaction::Standard(stx) => {
                assert!(stx.guaranteed_coins.is_none());
                assert!(stx.fallible_coins.is_empty());
            }
            Transaction::ClaimRewards(_) => panic!("standard tx expected"),
        }
    }

    #[test]
    fn deposit_with_exact_value_balances_with_one_input_no_change() {
        let mut rng = StdRng::seed_from_u64(0xBB);
        let keys = keys_from_byte(0x22);
        let state = seed_state_with_coin(&keys, 1_500, 0x33);
        let tx = unbalanced_deposit_tx(&mut rng, 1_500);

        let (balanced_tx, next_state) =
            balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
        let stx = match &balanced_tx {
            Transaction::Standard(stx) => stx,
            Transaction::ClaimRewards(_) => panic!("standard tx expected"),
        };
        let offer = stx
            .guaranteed_coins
            .as_ref()
            .expect("merged tx must carry a guaranteed offer");
        assert_eq!(offer.inputs.len(), 1, "exactly one wallet-side input");
        assert_eq!(
            offer.outputs.len(),
            1,
            "the contract-emitted output stays in the merged offer"
        );
        assert_eq!(
            offer.transient.len(),
            0,
            "no co-located coin → no transient"
        );

        // ZswapLocalState::spend records the in-flight spend by
        // inserting into `pending_spends` but leaves `coins` intact —
        // the coin only leaves the live set once the indexer confirms
        // the tx. Mirrors midnight-ledger/zswap/src/local.rs::spend_from_tree.
        assert_eq!(
            next_state.local().pending_spends.size(),
            1,
            "the spent coin lives in pending_spends until tx confirmation"
        );
    }

    #[test]
    fn deposit_with_larger_coin_emits_change_output() {
        let mut rng = StdRng::seed_from_u64(0xCC);
        let keys = keys_from_byte(0x44);
        let state = seed_state_with_coin(&keys, 5_000, 0x66);
        let tx = unbalanced_deposit_tx(&mut rng, 1_000);

        let (balanced_tx, _next_state) =
            balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
        let stx = match &balanced_tx {
            Transaction::Standard(stx) => stx,
            Transaction::ClaimRewards(_) => panic!("standard tx expected"),
        };
        let offer = stx
            .guaranteed_coins
            .as_ref()
            .expect("merged tx must carry a guaranteed offer");
        assert_eq!(offer.inputs.len(), 1);
        assert_eq!(
            offer.outputs.len(),
            2,
            "contract output + wallet change output"
        );
    }

    #[test]
    fn deposit_with_no_coins_errors_insufficient_funds() {
        let mut rng = StdRng::seed_from_u64(0xDD);
        let keys = keys_from_byte(0x55);
        let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let tx = unbalanced_deposit_tx(&mut rng, 1_000);

        let err = balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap_err();
        assert!(
            matches!(err, WalletError::InsufficientFunds { .. }),
            "expected InsufficientFunds, got: {err:?}"
        );
    }
}