moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Finalize + serialize + submit pipeline for facade recipes.
//!
//! Port of the `WalletFacade.finalizeRecipe` / `submitTransaction`
//! pipeline in `@midnight-ntwrk/wallet-sdk-facade/src/index.ts`.
//!
//! # Responsibilities
//!
//! 1. [`finalize_recipe`] — run the caller-supplied proving provider
//!    against the recipe's pre-prove transaction, then seal the
//!    binding commitment. Produces a [`FinalizedTransactionRecipe`]
//!    carrying the wire-format transaction.
//! 2. [`serialize_finalized`] — tagged-serialize a
//!    [`FinalizedTransactionRecipe`] into the byte form
//!    `pallet_midnight.send_mn_transaction` accepts.
//! 3. [`submit_finalized`] — drive the bytes through a
//!    [`moonproof_node_client::NodeClient`] and wait for the requested
//!    [`SubmissionStage`]. Returns the resulting
//!    [`SubmissionEvent`].
//! 4. [`fetch_chain_parameters`] — pull the chain's current
//!    [`LedgerParameters`] from an indexer endpoint, decoded into the
//!    [`ChainParameters`] bundle moonproof's builders expect. Replaces
//!    the integration tests' `fetch_chain_dust_parameters` helper.

use moonproof_indexer_client::{HttpIndexerClient, PublicDataProvider};
use moonproof_ledger::ledger::error::TransactionProvingError;
use moonproof_ledger::ledger::structure::{LedgerParameters, ProofMarker, Transaction};
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::commitment::PureGeneratorPedersen;
use moonproof_ledger::transient_crypto::proofs::ProvingProvider;
use moonproof_node_client::{NodeClient, SubmissionEvent, SubmissionStage};
use rand::rngs::OsRng;

use crate::abstractions::ProtocolVersion;
use crate::error::{Result, WalletError};
use crate::facade::transfer::UnprovenTransactionRecipe;

/// The wire-format transaction shape — post-prove, post-seal.
pub type FinalizedTransaction =
    Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>;

/// Chain parameters needed to build recipes that match the live chain.
#[derive(Debug, Clone)]
pub struct ChainParameters {
    /// The tip block's ledger parameters: its dust parameters, cost
    /// model and the fee prices transactions are priced against.
    pub ledger_parameters: LedgerParameters,
    /// Chain tip timestamp, seconds since UNIX epoch. Derived from
    /// `block.timestamp / 1000` (the indexer reports milliseconds).
    pub chain_time_secs: u64,
    /// Protocol version of the tip block, as the indexer reports it.
    pub protocol_version: ProtocolVersion,
    /// Height of the tip block.
    pub block_height: i64,
    /// The dust trees' roots after the tip block, when the indexer
    /// reports them.
    pub dust_roots: Option<crate::dust::DustTreeRoots>,
}

/// Output of [`finalize_recipe`] — a transaction in the wire format
/// the node's `send_mn_transaction` extrinsic accepts.
#[derive(Debug, Clone)]
pub struct FinalizedTransactionRecipe {
    pub transaction: FinalizedTransaction,
}

/// Options shaping a submission attempt.
#[derive(Debug, Clone, Copy)]
pub struct SubmissionOptions {
    /// When [`submit_finalized`] should return: the first event
    /// matching this stage is returned. Defaults to
    /// [`SubmissionStage::InBlock`], which is the point at which the
    /// chain has accepted the transaction.
    pub stage: SubmissionStage,
}

impl Default for SubmissionOptions {
    #[inline]
    fn default() -> Self {
        Self {
            stage: SubmissionStage::InBlock,
        }
    }
}

/// Drive the prover against `recipe.transaction` and seal the result.
/// Analogous to TS `finalizeTransaction` / `finalizeRecipe`.
///
/// `async` rather than sync — `ProvingProvider::prove` is itself
/// `async` (reqwest-backed SRS / proving-key fetch on a cache miss).
/// An earlier shape called `futures::executor::block_on(...)` here
/// which deadlocked when called from inside a tokio current-thread
/// runtime: the futures-rs executor doesn't drive tokio's IO
/// reactor, and the outer runtime can't make IO progress while a
/// task on it is spinning synchronously, so reqwest's HTTP requests
/// hung forever. Letting the caller's runtime drive the prove
/// future via `.await` fixes the deadlock.
///
/// `ProvingProvider::prove` is `?Send` (per upstream's deliberate
/// `#[allow(async_fn_in_trait)]`); this fn inherits the same
/// non-Send-ness. Callers needing to send the future across threads
/// should put it on a `LocalSet` or wrap in `spawn_blocking`.
///
/// # Errors
///
/// - [`WalletError::Serialization`] wrapping the underlying
///   [`TransactionProvingError`] when the prover rejects the recipe.
pub async fn finalize_recipe<P: ProvingProvider + Send + 'static>(
    recipe: &UnprovenTransactionRecipe,
    prover: P,
) -> Result<FinalizedTransactionRecipe> {
    // Off the async runtime: proving is CPU-bound, and on ledger 9 the
    // ledger's proving future is `!Send` (its resolver is an `async fn`
    // in trait), which would otherwise infect every axum handler and
    // binding that calls this.
    let transaction = recipe.transaction.clone();
    let post_prove = moonproof_prover::prove_offthread(move || async move {
        transaction.prove(prover, &INITIAL_COST_MODEL).await
    })
    .await
    .map_err(|e| WalletError::Serialization(format!("finalize_recipe: {e}")))?
    .map_err(|e: TransactionProvingError<InMemoryDB>| {
        WalletError::Serialization(format!("finalize_recipe: prove step failed: {e:?}"))
    })?;
    let finalized = post_prove.seal(OsRng);
    Ok(FinalizedTransactionRecipe {
        transaction: finalized,
    })
}

/// A proven, not-yet-bound transaction — the input the wallet's
/// `balanceTx` operates on. Matches the TS `UnboundTransaction`
/// (`Transaction<Signature, Proof, PreBinding>`): every circuit is
/// proven, the binding commitment is not yet sealed.
pub type ProvenTransaction = Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>;

/// Balance a proven, unbound transaction and return the sealed,
/// submittable [`FinalizedTransaction`].
///
/// This is moonproof's `WalletProvider.balanceTx`: the operation a
/// contract layer (midnight-js-contracts, or our own runtime) calls
/// after proving a contract deploy/call it built unbalanced. The wallet
/// closes the shielded and unshielded imbalances, pays the fee in Dust
/// when `options.pay_fees` is set, then proves only its own leg, seals
/// the already-proven base and merges the two
/// ([`crate::facade::balance_unbound_recipe`] then
/// [`crate::facade::finalize_unbound_recipe`]). The base is never
/// re-proven.
///
/// Returns the facade with the spends booked (so a later sync doesn't
/// double-count them) alongside the finalized transaction.
///
/// # Errors
/// - [`WalletError::InsufficientFunds`] if the wallet can't close an
///   imbalance or cover the fee.
/// - proving / merge / seal errors.
pub async fn balance_unbound_transaction<P: ProvingProvider + Send + 'static>(
    facade: crate::facade::FacadeState,
    base: ProvenTransaction,
    keys: &crate::facade::TransferSigningKeys<'_>,
    options: &crate::facade::TransferOptions,
    prover: P,
) -> Result<(crate::facade::FacadeState, FinalizedTransaction)> {
    let (recipe, booked) =
        crate::facade::balance_unbound_recipe(&mut OsRng, facade, base, keys, options)?;
    let finalized = crate::facade::finalize_unbound_recipe(recipe, prover).await?;
    Ok((booked, finalized))
}

/// Indexer-resolvable handles for a submitted transaction: the ledger
/// transaction hash plus its identifiers, all hex-encoded.
///
/// Both fields match what the indexer stores: `hash` equals
/// `transactions.hash`, and each entry in `identifiers` equals one of
/// `transactions.identifiers`. Either can be handed straight to a
/// `transactions(offset: { hash | identifier })` lookup — unlike the
/// Substrate extrinsic hash the node returns at submission time, which
/// lives in a different hash domain and the indexer never stores.
#[derive(Debug, Clone)]
pub struct FinalizedTxHandles {
    pub tx_hash: String,
    pub identifiers: Vec<String>,
}

/// Compute the [`FinalizedTxHandles`] from tagged-serialized finalized
/// transaction bytes (the wire form [`serialize_finalized`] and the
/// submission pipeline produce). Lets callers print the hash/identifier
/// the indexer indexes by, so `tx status` resolves a just-submitted tx.
pub fn finalized_tx_handles(bytes: &[u8]) -> Result<FinalizedTxHandles> {
    let tx: FinalizedTransaction = tagged_deserialize(bytes).map_err(|e| {
        WalletError::Serialization(format!("deserialize finalized tx for handles: {e}"))
    })?;
    Ok(FinalizedTxHandles {
        tx_hash: hex::encode(tx.transaction_hash().0 .0),
        identifiers: crate::facade::outcome::identifiers_hex(&tx)?,
    })
}

/// Tagged-serialize a finalized recipe into the byte form
/// `pallet_midnight.send_mn_transaction` accepts.
pub fn serialize_finalized(recipe: &FinalizedTransactionRecipe) -> Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(4096);
    tagged_serialize(&recipe.transaction, &mut bytes).map_err(|e| {
        WalletError::Serialization(format!("tagged_serialize(finalized facade tx): {e}"))
    })?;
    Ok(bytes)
}

/// Submit `bytes` (the output of [`serialize_finalized`]) through the
/// supplied [`NodeClient`] and wait for the first event at
/// `options.stage`.
///
/// Mirrors TS `WalletFacade.submitTransaction` — except TS queues the
/// transaction in a pending-transactions service first; moonproof
/// defers that until a dedicated pending-tx module lands.
///
/// # Errors
///
/// - [`WalletError::Submission`] wrapping any
///   [`moonproof_node_client::NodeClientError`] from the submission.
pub async fn submit_finalized<C: NodeClient>(
    client: &C,
    bytes: Vec<u8>,
    options: SubmissionOptions,
) -> Result<SubmissionEvent> {
    client
        .send_and_wait_for(bytes, options.stage)
        .await
        .map_err(|e| WalletError::Submission(format_node_error_chain("submit_finalized", &e)))
}

/// Render a [`moonproof_node_client::NodeClientError`] including its
/// nested `source` chain. The default `Display` only renders the top
/// variant — the `TransactionInvalid { source: Some(_) }` payload
/// carries the actual chain rejection reason there.
pub(crate) fn format_node_error_chain(
    prefix: &str,
    err: &moonproof_node_client::NodeClientError,
) -> String {
    use std::error::Error;
    use std::fmt::Write as _;
    let mut s = format!("{prefix}: {err}");
    let mut current: Option<&dyn Error> = err.source();
    while let Some(c) = current {
        let _ = write!(s, "; caused by: {c}");
        current = c.source();
    }
    s
}

/// Fetch [`LedgerParameters`] from the indexer's `block(None)` query
/// and decode the dust + cost model into the moonproof-facing
/// [`ChainParameters`] shape.
///
/// This replaces the ad-hoc `fetch_chain_dust_parameters` helper
/// duplicated across the submission integration tests.
///
/// The indexer's `block.timestamp` is in **milliseconds** — we divide
/// by 1000 before returning.
pub async fn fetch_chain_parameters(indexer_url: &str) -> Result<ChainParameters> {
    let client = HttpIndexerClient::new(indexer_url).map_err(|e| {
        WalletError::Serialization(format!("parse indexer url `{indexer_url}`: {e}"))
    })?;
    let block = client
        .block(None)
        .await
        .map_err(|e| WalletError::Serialization(format!("indexer block(None): {e}")))?
        .ok_or_else(|| WalletError::Serialization("indexer returned no block".to_owned()))?;
    let bytes = hex::decode(&block.ledger_parameters)
        .map_err(|e| WalletError::Serialization(format!("ledger_parameters not valid hex: {e}")))?;
    let params: LedgerParameters = tagged_deserialize(&mut bytes.as_slice())
        .map_err(|e| WalletError::Serialization(format!("deserialize LedgerParameters: {e}")))?;
    let chain_time_millis: i64 = block.timestamp;
    let chain_time_secs = u64::try_from(chain_time_millis.max(0) / 1000).unwrap_or(0);
    let protocol_version = u64::try_from(block.protocol_version).map_err(|_| {
        WalletError::Serialization(format!(
            "indexer reported a negative protocol version {}",
            block.protocol_version
        ))
    })?;
    let dust_roots = match (
        block.dust_commitment_merkle_tree_root,
        block.dust_generation_merkle_tree_root,
    ) {
        (Some(commitment), Some(generation)) => Some(crate::dust::DustTreeRoots {
            commitment: commitment.to_ascii_lowercase(),
            generation: generation.to_ascii_lowercase(),
        }),
        _ => None,
    };
    Ok(ChainParameters {
        ledger_parameters: params,
        chain_time_secs,
        protocol_version: ProtocolVersion(protocol_version),
        block_height: block.height,
        dust_roots,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn submission_options_default_is_inblock() {
        assert_eq!(SubmissionOptions::default().stage, SubmissionStage::InBlock);
    }

    #[test]
    fn serialize_finalized_signature_compiles() {
        // The happy path is exercised end-to-end by
        // `tests/facade_submission_integration.rs`. This smoke test
        // keeps the function-pointer type stable so accidental
        // signature drift trips CI here rather than at integration-test
        // build time.
        let _: fn(&FinalizedTransactionRecipe) -> Result<Vec<u8>> = serialize_finalized;
    }
}