moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Pluggable capability traits over the facade's prove + submit
//! steps. Mirror of midnight-wallet/packages/capabilities/src/{proving,
//! submission}/.
//!
//! The facade's existing free functions
//! ([`super::submission::finalize_recipe`] and
//! [`super::submission::submit_finalized`]) take concrete generic
//! parameters (`P: ProvingProvider`, `C: NodeClient`) and
//! monomorphize at the call site. That's the right shape for
//! infrastructure code that owns a single proof backend, but it
//! forces every dApp to make a compile-time choice.
//!
//! These traits give callers a runtime-pluggable form: hold a
//! `Box<dyn ProvingCapability>` in a wallet-state struct, swap
//! implementations at construction time, mock in tests.
//!
//! ## Adapters
//!
//! - [`LedgerProvingCapability`] wraps any `P: ProvingProvider` (e.g.
//!   `moonproof_proof_backend`'s local or HTTP provider).
//! - [`NodeSubmissionCapability`] wraps any `C: NodeClient` (e.g.
//!   `moonproof_node_client`'s polkadot wrapper).
//!
//! ## When to skip
//!
//! For tests / one-shot scripts that build, prove, and submit in one
//! statically-known path, the existing generic free functions are
//! lighter. Reach for the trait when you need to compose at runtime.

use futures::stream::{FuturesUnordered, Stream};
use futures::StreamExt;
use moonproof_ledger::transient_crypto::proofs::ProvingProvider;
use moonproof_macros::async_trait;
use moonproof_node_client::{NodeClient, SubmissionEvent};

use crate::error::{Result, WalletError};
use crate::facade::submission::{
    finalize_recipe, submit_finalized, FinalizedTransactionRecipe, SubmissionOptions,
};
use crate::facade::transfer::UnprovenTransactionRecipe;

// ---------------------------------------------------------------------------
// Proving
// ---------------------------------------------------------------------------

/// Pluggable proving step. Takes the facade's pre-prove recipe,
/// returns the post-prove sealed recipe.
///
/// Implementations are usually a thin wrapper over a ledger
/// `ProvingProvider`; see [`LedgerProvingCapability`] for the
/// canonical adapter. Mock implementations in tests can return
/// pre-baked sealed recipes without invoking the real prover.
///
/// `?Send` returned future: upstream's `ProvingProvider::prove`
/// is itself `?Send` (per its `#[allow(async_fn_in_trait)]`), and
/// we forward that future verbatim through the canonical adapter.
/// Single-thread tokio runtimes (the CLI default) handle this
/// fine; multi-thread callers that need to send the future across
/// threads should wrap it via `LocalSet` or similar.
#[async_trait(?Send)]
pub trait ProvingCapability: Send + Sync {
    async fn prove(&self, recipe: &UnprovenTransactionRecipe)
        -> Result<FinalizedTransactionRecipe>;
}

/// Adapter that lifts any [`ProvingProvider`] into a
/// [`ProvingCapability`]. The adapter is `Clone` only when `P` is —
/// callers that need `Arc` share semantics should wrap the adapter
/// in `Arc<dyn ProvingCapability>`.
#[derive(Debug, Clone)]
pub struct LedgerProvingCapability<P>
where
    P: ProvingProvider + Clone + Send + Sync,
{
    provider: P,
}

impl<P> LedgerProvingCapability<P>
where
    P: ProvingProvider + Clone + Send + Sync,
{
    pub fn new(provider: P) -> Self {
        Self { provider }
    }
}

#[async_trait(?Send)]
impl<P> ProvingCapability for LedgerProvingCapability<P>
where
    P: ProvingProvider + Clone + Send + Sync + 'static,
{
    async fn prove(
        &self,
        recipe: &UnprovenTransactionRecipe,
    ) -> Result<FinalizedTransactionRecipe> {
        finalize_recipe(recipe, self.provider.clone()).await
    }
}

// ---------------------------------------------------------------------------
// Submission
// ---------------------------------------------------------------------------

/// Pluggable submission step. Takes the wire-format bytes and waits
/// for the requested submission stage.
///
/// Mirror of TS `SubmissionService<T>`. Implementations decouple the
/// wallet from a specific node client — production code wires
/// [`NodeSubmissionCapability`] over `moonproof_node_client`; tests
/// can return canned [`SubmissionEvent`]s.
#[async_trait]
pub trait SubmissionCapability: Send + Sync {
    async fn submit(&self, bytes: Vec<u8>, options: SubmissionOptions) -> Result<SubmissionEvent>;
}

/// Adapter that lifts any [`NodeClient`] into a
/// [`SubmissionCapability`].
#[derive(Debug, Clone)]
pub struct NodeSubmissionCapability<C>
where
    C: NodeClient + Send + Sync,
{
    client: C,
}

impl<C> NodeSubmissionCapability<C>
where
    C: NodeClient + Send + Sync,
{
    pub fn new(client: C) -> Self {
        Self { client }
    }
}

#[async_trait]
impl<C> SubmissionCapability for NodeSubmissionCapability<C>
where
    C: NodeClient + Send + Sync + 'static,
{
    async fn submit(&self, bytes: Vec<u8>, options: SubmissionOptions) -> Result<SubmissionEvent> {
        submit_finalized(&self.client, bytes, options).await
    }
}

// ---------------------------------------------------------------------------
// Mock helpers (tests + dApp simulators)
// ---------------------------------------------------------------------------

/// Test double — proves by handing back a caller-supplied recipe
/// without invoking a real prover. Mirror of typical TS
/// `provingService.mock(...)` helpers.
#[derive(Debug)]
pub struct MockProvingCapability {
    canned: std::sync::Mutex<Option<FinalizedTransactionRecipe>>,
}

impl MockProvingCapability {
    pub fn new(recipe: FinalizedTransactionRecipe) -> Self {
        Self {
            canned: std::sync::Mutex::new(Some(recipe)),
        }
    }
}

#[async_trait(?Send)]
impl ProvingCapability for MockProvingCapability {
    async fn prove(
        &self,
        _recipe: &UnprovenTransactionRecipe,
    ) -> Result<FinalizedTransactionRecipe> {
        self.canned
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
            .ok_or_else(|| {
                WalletError::Serialization(
                    "MockProvingCapability already consumed; construct with a fresh recipe per call"
                        .to_owned(),
                )
            })
    }
}

// ---------------------------------------------------------------------------
// Batch proving — bounded-parallelism convenience over ProvingCapability
// ---------------------------------------------------------------------------

/// Prove `recipes` through `capability` with at most `max_in_flight`
/// jobs running concurrently. Returns a [`Stream`] of results in
/// completion order (NOT input order — use indexed pairs in
/// `recipes` if order matters).
///
/// The underlying [`crate::ProverEngine`] already gates concurrent
/// proofs with a `num_cpus`-sized semaphore + rayon pool, so this
/// helper's `max_in_flight` is the **callers' own backpressure** —
/// useful when the wallet UI needs to keep a few prove jobs queued
/// without flooding the engine's queue with hundreds.
///
/// Pass `0` for `max_in_flight` to disable batching and run every
/// job concurrently (still bounded by the engine semaphore).
pub fn prove_batch<C, I>(
    capability: std::sync::Arc<C>,
    recipes: I,
    max_in_flight: usize,
) -> impl Stream<Item = Result<FinalizedTransactionRecipe>>
where
    C: ProvingCapability + 'static,
    I: IntoIterator<Item = UnprovenTransactionRecipe>,
{
    let recipes: Vec<UnprovenTransactionRecipe> = recipes.into_iter().collect();
    async_stream::stream! {
        // `?Send` boxed future: `ProvingCapability::prove` returns a
        // `?Send` future (it forwards upstream's `ProvingProvider`
        // future verbatim). Single-thread tokio runtimes drive this
        // fine; multi-thread runtimes need a `LocalSet` around the
        // returned stream.
        type ProveFuture = std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<FinalizedTransactionRecipe>>>,
        >;
        let mut iter = recipes.into_iter();
        let mut in_flight: FuturesUnordered<ProveFuture> = FuturesUnordered::new();
        let cap_limit = if max_in_flight == 0 { usize::MAX } else { max_in_flight };

        // Prime the queue.
        while in_flight.len() < cap_limit {
            let Some(recipe) = iter.next() else { break; };
            let cap = capability.clone();
            in_flight.push(Box::pin(async move { cap.prove(&recipe).await }) as ProveFuture);
        }

        while let Some(result) = in_flight.next().await {
            yield result;
            // Top up.
            if in_flight.len() < cap_limit {
                if let Some(recipe) = iter.next() {
                    let cap = capability.clone();
                    in_flight
                        .push(Box::pin(async move { cap.prove(&recipe).await }) as ProveFuture);
                }
            }
        }
    }
}

/// Test double — submits by returning a caller-supplied event without
/// touching the network.
#[derive(Debug)]
pub struct MockSubmissionCapability {
    canned: std::sync::Mutex<Option<SubmissionEvent>>,
}

impl MockSubmissionCapability {
    pub fn new(event: SubmissionEvent) -> Self {
        Self {
            canned: std::sync::Mutex::new(Some(event)),
        }
    }
}

/// Test double — proves by handing back caller-supplied recipes in
/// order. For the batch helper to be exercised against a queue of
/// many recipes.
#[derive(Debug)]
pub struct QueueProvingCapability {
    queue: std::sync::Mutex<Vec<FinalizedTransactionRecipe>>,
}

impl QueueProvingCapability {
    pub fn new(recipes: Vec<FinalizedTransactionRecipe>) -> Self {
        // Reverse so `pop` yields in input order.
        let mut q = recipes;
        q.reverse();
        Self {
            queue: std::sync::Mutex::new(q),
        }
    }
}

#[async_trait(?Send)]
impl ProvingCapability for QueueProvingCapability {
    async fn prove(
        &self,
        _recipe: &UnprovenTransactionRecipe,
    ) -> Result<FinalizedTransactionRecipe> {
        self.queue
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .pop()
            .ok_or_else(|| WalletError::Serialization("QueueProvingCapability empty".to_owned()))
    }
}

#[async_trait]
impl SubmissionCapability for MockSubmissionCapability {
    async fn submit(
        &self,
        _bytes: Vec<u8>,
        _options: SubmissionOptions,
    ) -> Result<SubmissionEvent> {
        self.canned
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
            .ok_or_else(|| {
                WalletError::Serialization(
                    "MockSubmissionCapability already consumed; construct with a fresh event per call"
                        .to_owned(),
                )
            })
    }
}