moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Long-lived sync coordinator on top of the facade.
//!
//! Port of `midnight-wallet/packages/wallet-sdk-runtime/src/Runtime.ts`.
//! The TS module owns the "sync forever in the background" loop +
//! protocol-version dispatch; moonproof's facade owns the *single*
//! batched drain (see [`crate::facade::sync`]). This module is the
//! glue: a state cell + watch channel + shutdown control around a
//! caller-supplied stepper.
//!
//! ## Design
//!
//! - [`WalletRuntime`] holds the live [`FacadeState`] behind an
//!   `Arc<tokio::sync::RwLock>`. Reads are cheap (clone); writes go
//!   through [`apply`](WalletRuntime::apply).
//! - Every successful apply broadcasts on a `tokio::sync::watch`
//!   channel — UIs subscribe via [`changes`](WalletRuntime::changes)
//!   and re-render on every advance.
//! - [`shutdown`](WalletRuntime::shutdown) signals every consumer
//!   via [`cancel_token`](WalletRuntime::cancel_token) so callers'
//!   sync tasks can wind down cleanly.
//!
//! ## Relation to [`crate::session`]
//!
//! [`crate::session::sync_wallet_fresh`] / [`crate::session::sync_wallet_resumable`]
//! are **bootstrap** helpers — they connect, drain history, and return
//! a fully-loaded [`FacadeState`]. Hand that state to
//! [`WalletRuntime::new`] and the runtime takes over from there:
//!
//! ```ignore
//! let initial = moonproof_wallet::session::sync_wallet_fresh(&session).await?;
//! let runtime = moonproof_wallet::runtime::WalletRuntime::new(initial);
//! // ... drive perpetual sync via runtime.apply ...
//! ```
//!
//! ## What this module does NOT own
//!
//! - The subscription drivers (`subscribe_blocks`, etc.) — those are
//!   indexer-client concerns. Callers wire them up and feed batches
//!   into [`apply`].
//! - Protocol version dispatch — surfaced via the facade's protocol
//!   version field; the runtime does not gate on it.
//!
//! ## Example
//!
//! ```ignore
//! use moonproof_wallet::runtime::WalletRuntime;
//! use moonproof_wallet::facade::{fold_unshielded_ticks};
//!
//! let runtime = WalletRuntime::new(initial_facade);
//! let cancel = runtime.cancel_token();
//! let owner = [0u8; 32];
//!
//! // Subscription driver — caller-owned task, cooperates with cancel.
//! let driver = {
//!     let runtime = runtime.clone();
//!     tokio::spawn(async move {
//!         while !cancel.is_cancelled() {
//!             let batch = pull_unshielded_batch().await?;
//!             runtime.apply(|state| fold_unshielded_ticks(state, owner, batch)).await?;
//!         }
//!         Ok::<_, anyhow::Error>(())
//!     })
//! };
//!
//! // UI subscriber.
//! let mut rx = runtime.changes();
//! while rx.changed().await.is_ok() {
//!     let snapshot = rx.borrow_and_update().clone();
//!     // re-render
//! }
//!
//! runtime.shutdown();
//! driver.await??;
//! ```

pub mod backoff;

pub use backoff::ExponentialBackoff;

use std::sync::Arc;

use moonproof_utils::StateCell;
use tokio::sync::watch;

use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;

/// Coordinator over a live [`FacadeState`]. Cheap to `clone` —
/// internally [`StateCell`]-shared.
///
/// State storage + change broadcast are delegated to
/// [`moonproof_utils::StateCell`] (the same primitive
/// [`moonproof_runtime::sync::Watcher`] uses for contract sync). The
/// only wallet-specific addition is the [`CancellationToken`] used
/// to signal shutdown across caller-driven subscription tasks.
#[derive(Debug, Clone)]
pub struct WalletRuntime {
    inner: Arc<Inner>,
}

#[derive(Debug)]
struct Inner {
    state: StateCell<FacadeState>,
    cancel: CancellationToken,
}

impl WalletRuntime {
    /// Wrap an initial state. Spawns no tasks — caller drives
    /// subscriptions and feeds batches through [`apply`].
    pub fn new(initial: FacadeState) -> Self {
        Self {
            inner: Arc::new(Inner {
                state: StateCell::new(initial),
                cancel: CancellationToken::new(),
            }),
        }
    }

    /// Cheap snapshot of the current state. Always returns a clone —
    /// the runtime never lends out internal references.
    pub async fn current(&self) -> FacadeState {
        self.inner.state.current().await
    }

    /// Current protocol version the held state is associated with.
    /// Cheap — reads under the state lock briefly and returns the
    /// `Copy` value. Use this to drive version-aware dispatch (e.g.
    /// "if v >= 2, use the new dust grace logic").
    pub async fn protocol_version(&self) -> crate::abstractions::ProtocolVersion {
        self.inner.state.current().await.protocol_version()
    }

    /// Subscribe to state changes. Each successful [`apply`]
    /// broadcasts the new state to every receiver. The receiver's
    /// initial value is the state at subscribe time — call
    /// `borrow_and_update` to read it.
    pub fn changes(&self) -> watch::Receiver<FacadeState> {
        self.inner.state.changes()
    }

    /// Atomically apply a fold function to the state. The function
    /// receives ownership of the previous state and returns a
    /// `Result<FacadeState>`; on `Ok` the runtime stores the new
    /// state and broadcasts it; on `Err` the previous state is
    /// preserved and the error is returned to the caller.
    pub async fn apply<F>(&self, f: F) -> Result<()>
    where
        F: FnOnce(FacadeState) -> Result<FacadeState>,
    {
        self.inner.state.apply::<_, WalletError>(f).await
    }

    /// Replace the state unconditionally. Useful for resets / rewinds
    /// that don't fit the fold pattern (e.g. a chain re-org wiped
    /// progress and the caller is reloading from a snapshot).
    pub async fn set(&self, state: FacadeState) {
        self.inner.state.set(state).await;
    }

    /// Cancellation token driver tasks should poll. Cloned once per
    /// task at spawn time — cheap.
    pub fn cancel_token(&self) -> CancellationToken {
        self.inner.cancel.clone()
    }

    /// Signal every consumer of [`cancel_token`] to wind down. After
    /// `shutdown` returns, new calls to [`apply`] still succeed (the
    /// runtime itself isn't dropped) — the cancel is a coordination
    /// signal, not a state lock.
    pub fn shutdown(&self) {
        self.inner.cancel.cancel();
    }
}

// ---------------------------------------------------------------------------
// Cancellation token — minimal port of tokio_util::sync::CancellationToken
// to avoid pulling the whole crate for one type. Same shape: clone
// shares state, cancel() is one-shot, is_cancelled() is fast.
// ---------------------------------------------------------------------------

/// Lightweight one-shot cancellation flag. `Clone` shares the same
/// flag (Arc-backed). Designed for cooperation between a runtime and
/// the tasks driving it.
#[derive(Debug, Clone)]
pub struct CancellationToken {
    inner: Arc<TokenInner>,
}

#[derive(Debug)]
struct TokenInner {
    cancelled: std::sync::atomic::AtomicBool,
    notify: tokio::sync::Notify,
}

impl CancellationToken {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(TokenInner {
                cancelled: std::sync::atomic::AtomicBool::new(false),
                notify: tokio::sync::Notify::new(),
            }),
        }
    }

    pub fn cancel(&self) {
        if !self
            .inner
            .cancelled
            .swap(true, std::sync::atomic::Ordering::SeqCst)
        {
            self.inner.notify.notify_waiters();
        }
    }

    pub fn is_cancelled(&self) -> bool {
        self.inner
            .cancelled
            .load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Awaits cancellation. Returns immediately if already cancelled.
    /// Compose with `tokio::select!` to race against subscription
    /// pulls.
    pub async fn cancelled(&self) {
        if self.is_cancelled() {
            return;
        }
        let notified = self.inner.notify.notified();
        if self.is_cancelled() {
            return;
        }
        notified.await;
    }

    /// Convenience: await `fut` racing against cancellation. Returns
    /// `None` if cancellation fired first.
    pub async fn run_until_cancelled<F, T>(&self, fut: F) -> Option<T>
    where
        F: std::future::Future<Output = T>,
    {
        tokio::select! {
            res = fut => Some(res),
            () = self.cancelled() => None,
        }
    }
}

impl Default for CancellationToken {
    fn default() -> Self {
        Self::new()
    }
}

// Re-export Duration so callers don't need a separate std import for
// the typical `WalletRuntime::new + ExponentialBackoff::new` setup.
pub use std::time::Duration as StdDuration;

#[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 as BcDuration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};

    fn empty_facade() -> FacadeState {
        let sh = ShieldedState::init_empty(
            &ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32])),
            NetworkId::Undeployed,
        );
        let du = DustState::init_empty(
            DustParameters {
                night_dust_ratio: 1_000,
                generation_decay_rate: 1,
                dust_grace_period: BcDuration::from_secs(60),
            },
            &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
            NetworkId::Undeployed,
        );
        FacadeState::new(sh, UnshieldedState::empty(), du, NetworkId::Undeployed)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn apply_broadcasts_to_subscribers() {
        let runtime = WalletRuntime::new(empty_facade());
        let mut rx = runtime.changes();
        // Drain initial value.
        let _ = rx.borrow_and_update().clone();

        runtime.apply(Ok).await.unwrap();
        rx.changed().await.unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn apply_preserves_state_on_error() {
        let runtime = WalletRuntime::new(empty_facade());
        let before = runtime.current().await;
        let result: Result<()> = runtime
            .apply(|_| Err(crate::error::WalletError::Serialization("boom".to_owned())))
            .await;
        assert!(result.is_err());
        let after = runtime.current().await;
        // States compare equal because nothing changed; cheap structural eq.
        assert_eq!(before.network_id().as_str(), after.network_id().as_str(),);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cancel_token_signals_waiters() {
        let runtime = WalletRuntime::new(empty_facade());
        let token = runtime.cancel_token();
        let task = {
            let token = token.clone();
            tokio::spawn(async move {
                token.cancelled().await;
                42
            })
        };
        runtime.shutdown();
        let result = task.await.unwrap();
        assert_eq!(result, 42);
        assert!(token.is_cancelled());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_until_cancelled_yields_none_on_cancel() {
        let runtime = WalletRuntime::new(empty_facade());
        let token = runtime.cancel_token();
        runtime.shutdown();
        let result: Option<i32> = token
            .run_until_cancelled(async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                7
            })
            .await;
        assert_eq!(result, None);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn shared_runtime_clones_share_state() {
        let runtime = WalletRuntime::new(empty_facade());
        let copy = runtime.clone();
        let token_a = runtime.cancel_token();
        let token_b = copy.cancel_token();
        copy.shutdown();
        assert!(token_a.is_cancelled());
        assert!(token_b.is_cancelled());
    }
}