moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Fan-in of the three sub-wallet subscription streams into facade
//! state.
//!
//! Port of the `RxJS` `combineLatest([shielded.state, unshielded.state,
//! dust.state, pending])` fan-in in
//! `@midnight-ntwrk/wallet-sdk-facade/src/index.ts::WalletFacade.state`.
//!
//! Moonproof's indexer subscriptions aren't `RxJS` streams but async
//! iterators yielded by
//! [`moonproof_indexer_client`]. The fan-in logic, however, is the
//! same shape — each sub-wallet's state is advanced by its own replay
//! function, and the facade owns progress tracking for the unshielded
//! sub-wallet (which lacks a state-level progress field).
//!
//! # What this module does NOT own
//!
//! The long-lived "sync forever in the background" loop belongs to a
//! future `runtime` module. This module exposes **one drain per
//! sub-wallet**: pure functions that fold a batch of ticks into the
//! facade state and return the new state. The caller decides when to
//! drain — in a one-shot catch-up (the pattern the integration tests
//! use) or in a long-running worker task (future runtime).

use moonproof_indexer_client::{ShieldedTxRaw, UnshieldedTxRaw};
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::{DustSecretKey, DustStateChanges};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;

use crate::dust::{replay_hex_events, SyncProgressUpdate as DustSyncProgressUpdate};
use crate::error::Result;
use crate::facade::state::FacadeState;
use crate::shielded::replay_relevant_transactions;
use crate::unshielded::replay_unshielded_subscription;

/// Fold a batch of unshielded subscription ticks into the facade's
/// unshielded sub-state. Advances the facade-owned unshielded
/// [`SyncProgress`] with progress ticks and the highest transaction
/// id seen so far.
///
/// The facade owns the unshielded progress (the sub-wallet state
/// machine is intentionally progress-agnostic — see `unshielded/state.rs`).
pub fn fold_unshielded_ticks<I>(
    state: FacadeState,
    owner_bytes: [u8; 32],
    ticks: I,
) -> Result<FacadeState>
where
    I: IntoIterator<Item = UnshieldedTxRaw>,
{
    let ticks: Vec<UnshieldedTxRaw> = ticks.into_iter().collect();

    // First pass: aggregate progress from the batch. Progress ticks
    // report a `highestTransactionId`; transaction ticks carry their
    // own id we use as the applied-index bump.
    let mut progress = state.unshielded_progress();
    let mut highest_applied = progress.applied_index;
    for t in &ticks {
        if t.is_progress() {
            if let Some(h) = t.highest_transaction_id {
                let h_u64 = u64::try_from(h.max(0)).unwrap_or(0);
                progress.highest_index = progress.highest_index.max(h_u64);
                progress.highest_relevant_index = progress.highest_relevant_index.max(h_u64);
            }
        } else if let Some(id) = t.transaction_id {
            let id_u64 = u64::try_from(id.max(0)).unwrap_or(0);
            highest_applied = highest_applied.max(id_u64);
            progress.highest_relevant_wallet_index =
                progress.highest_relevant_wallet_index.max(id_u64);
        }
    }
    progress.applied_index = progress.applied_index.max(highest_applied);
    progress.is_connected = true;

    // Second pass: advance the sub-wallet state in place without cloning.
    let mut state = state;
    let prev_unshielded = std::mem::replace(
        &mut state.unshielded,
        crate::unshielded::UnshieldedState::empty(),
    );
    state.unshielded = replay_unshielded_subscription(prev_unshielded, owner_bytes, ticks)?;

    Ok(state.with_unshielded_progress(progress))
}

/// Fold a batch of dust ledger events into the facade's dust
/// sub-state. Returns the updated facade AND the per-tx
/// [`DustStateChanges`] (useful for downstream tx-history hooks).
pub fn fold_dust_events(
    mut state: FacadeState,
    secret_key: &DustSecretKey,
    event_hex_blobs: &[String],
    current_time: Timestamp,
) -> Result<(FacadeState, Vec<DustStateChanges>)> {
    let (next_dust, changes) = if event_hex_blobs.is_empty() {
        (state.dust, Vec::new())
    } else {
        replay_hex_events(state.dust, secret_key, event_hex_blobs, current_time)?
    };

    // Advance dust progress. We don't have per-event ids here (the
    // replay consumes raw Event blobs); the indexer-subscription-level
    // caller that owns the id stream should set
    // `DustState::update_progress` separately before calling this
    // drain. Here we just flip `is_connected = true` to signal that
    // the replay batch succeeded.
    state.dust = next_dust.update_progress(DustSyncProgressUpdate::new().with_is_connected(true));

    Ok((state, changes))
}

/// Fold a batch of shielded subscription ticks into the facade's
/// shielded sub-state. The shielded sub-wallet state machine already
/// owns a [`SyncProgress`], so this helper just delegates to
/// [`replay_relevant_transactions`] and flips `is_connected = true`.
///
/// The integration tests own the higher-level "drain until caught up"
/// loop — see
/// `tests/shielded_submission_integration.rs::drain_shielded_subscription`.
pub fn fold_shielded_ticks<I>(
    mut state: FacadeState,
    secret_keys: &ZswapSecretKeys,
    ticks: I,
) -> Result<FacadeState>
where
    I: IntoIterator<Item = ShieldedTxRaw>,
{
    let next_shielded = replay_relevant_transactions(state.shielded, secret_keys, ticks)?;
    state.shielded = next_shielded.with_progress_update(None, None, None, None, Some(true));
    Ok(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use crate::dust::DustState;
    use crate::shielded::ShieldedState;
    use crate::unshielded::UnshieldedState;
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};

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

    fn dust_params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 1_000,
            generation_decay_rate: 1,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn empty_facade() -> FacadeState {
        let sh = ShieldedState::init_empty(&zswap_keys(0x01), NetworkId::Undeployed);
        let du = DustState::init_empty(
            dust_params(),
            &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
            NetworkId::Undeployed,
        );
        FacadeState::new(sh, UnshieldedState::empty(), du, NetworkId::Undeployed)
    }

    #[test]
    fn empty_unshielded_drain_leaves_state_untouched_but_sets_connected() {
        let f = empty_facade();
        let owner = [0u8; 32];
        let result = fold_unshielded_ticks(f, owner, std::iter::empty()).unwrap();
        // No ticks = no applied index change. But is_connected flips
        // true because we did successfully "finish" a (zero-tick) batch.
        assert!(result.unshielded_progress().is_connected);
        assert_eq!(result.unshielded_progress().applied_index, 0);
    }

    #[test]
    fn empty_dust_drain_leaves_state_untouched_but_sets_connected() {
        let f = empty_facade();
        let sk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let (result, changes) = fold_dust_events(f, &sk, &[], Timestamp::from_secs(0)).unwrap();
        assert!(changes.is_empty());
        assert!(result.progress().dust.is_connected);
    }

    #[test]
    fn empty_shielded_drain_leaves_state_untouched_but_sets_connected() {
        let f = empty_facade();
        let keys = zswap_keys(0x01);
        let result = fold_shielded_ticks(f, &keys, std::iter::empty()).unwrap();
        assert!(result.progress().shielded.is_connected);
    }
}