moonproof-node-client 0.2.1

Rust client for the Midnight node's Substrate submission RPC
Documentation
//! The [`NodeClient`] trait — the abstract interface every concrete node
//! adapter implements.
//!
//! This is deliberately thin: two async methods plus a convenience
//! `send_and_wait_for` helper. Mirrors the TS `NodeClient.Service` interface
//! from `midnight-wallet/packages/node-client/src/effect/NodeClient.ts`.

use futures::stream::{BoxStream, StreamExt};
use moonproof_macros::async_trait;

use crate::error::NodeClientError;
use crate::event::{SubmissionEvent, SubmissionStage};

/// Transparent newtype wrapper around Midnight transaction bytes.
///
/// Matches the TS `SerializedTransaction` opaque type — the same bytes you
/// get back from `moonproof_wallet::unshielded::ledger_adapter::serialize_transaction`.
pub type SerializedTransaction = Vec<u8>;

/// Initial-chain-state bootstrap data returned by [`NodeClient::get_genesis`].
#[derive(Debug, Clone, Default)]
pub struct Genesis {
    /// Midnight transactions extracted from the genesis block's `midnight.sendMnTransaction`
    /// extrinsics, in the order they appear. Used to seed a local ledger replay
    /// without full-history sync.
    pub transactions: Vec<SerializedTransaction>,
}

/// Client for the Midnight node's submission RPC.
///
/// Concrete impls live alongside this trait. The default is the
/// subxt-backed `PolkadotNodeClient` (added behind a feature flag so the
/// pure-logic layer remains Substrate-free and testable without a full
/// toolchain).
#[async_trait]
pub trait NodeClient: Send + Sync {
    /// Submit a Midnight transaction and stream every subsequent status
    /// event until the stream terminates with [`SubmissionEvent::Finalized`],
    /// a terminal error, or the caller drops the stream.
    ///
    /// The implementation is responsible for:
    ///
    /// - Connecting to the node (if not already connected).
    /// - Wrapping `tx` in an unsigned Substrate extrinsic
    ///   (`midnight.send_mn_transaction(tx)`).
    /// - Subscribing to `author_submitAndWatchExtrinsic`.
    /// - Translating each returned status into a [`SubmissionEvent`] or a
    ///   terminating [`NodeClientError`] — use
    ///   [`crate::status::SubmissionOutcome::from_status`] for the pure
    ///   mapping.
    async fn send_midnight_transaction(
        &self,
        tx: SerializedTransaction,
    ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>;

    /// Fetch the genesis block and extract its embedded Midnight transactions.
    ///
    /// Corresponds to TS `getGenesis()` — used for initial-state bootstrap.
    async fn get_genesis(&self) -> Result<Genesis, NodeClientError>;

    /// The chain's genesis block hash, `0x`-prefixed hex. Identifies
    /// the chain *instance*: two runs of a local-dev chain have
    /// different genesis hashes even though both call themselves
    /// `localdev`. Snapshot stores use this to refuse resuming state
    /// captured against a chain that no longer exists. `None` when
    /// the client can't know it (offline test doubles).
    fn genesis_hash_hex(&self) -> Option<String> {
        None
    }

    /// Submit a transaction and return the first event matching `stage`, or
    /// propagate the first error the stream reports.
    ///
    /// Default impl drives the stream; concrete clients rarely need to
    /// override. Mirrors TS `sendMidnightTransactionAndWait`.
    async fn send_and_wait_for(
        &self,
        tx: SerializedTransaction,
        stage: SubmissionStage,
    ) -> Result<SubmissionEvent, NodeClientError> {
        let mut stream = self.send_midnight_transaction(tx.clone()).await?;
        while let Some(item) = stream.next().await {
            let event = item?;
            if event.stage() == stage {
                return Ok(event);
            }
        }
        Err(NodeClientError::TransactionProgress {
            message: format!(
                "stream ended without reaching desired stage '{stage}' and no other error was reported"
            ),
            tx_data: tx,
            desired_stage: stage,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::SubmissionEvent;
    use futures::stream;

    /// Minimal in-memory client whose `send_midnight_transaction` returns a
    /// scripted event sequence. Exercises the default `send_and_wait_for`
    /// without any network. `NodeClientError` isn't `Clone` (boxed `source`),
    /// so events are drained via `Mutex::take` on first call — each test
    /// only submits once.
    struct FakeClient {
        events: std::sync::Mutex<Option<Vec<Result<SubmissionEvent, NodeClientError>>>>,
    }

    impl FakeClient {
        fn with_events(events: Vec<Result<SubmissionEvent, NodeClientError>>) -> Self {
            Self {
                events: std::sync::Mutex::new(Some(events)),
            }
        }
    }

    #[async_trait]
    impl NodeClient for FakeClient {
        async fn send_midnight_transaction(
            &self,
            _tx: SerializedTransaction,
        ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>
        {
            let events = self
                .events
                .lock()
                .expect("events mutex poisoned")
                .take()
                .expect("FakeClient.send_midnight_transaction called more than once");
            Ok(stream::iter(events).boxed())
        }

        async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
            Ok(Genesis::default())
        }
    }

    fn submitted() -> SubmissionEvent {
        SubmissionEvent::Submitted {
            tx: vec![1, 2],
            tx_hash: "0xa".into(),
        }
    }

    fn in_block() -> SubmissionEvent {
        SubmissionEvent::InBlock {
            tx: vec![1, 2],
            block_hash: "0xblk".into(),
            block_height: 5,
            tx_hash: "0xa".into(),
        }
    }

    fn finalized() -> SubmissionEvent {
        SubmissionEvent::Finalized {
            tx: vec![1, 2],
            block_hash: "0xfin".into(),
            block_height: 6,
            tx_hash: "0xa".into(),
        }
    }

    #[tokio::test]
    async fn send_and_wait_for_submitted_returns_first_match() {
        let client =
            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
        let ev = client
            .send_and_wait_for(vec![1, 2], SubmissionStage::Submitted)
            .await
            .unwrap();
        assert_eq!(ev.stage(), SubmissionStage::Submitted);
    }

    #[tokio::test]
    async fn send_and_wait_for_in_block_skips_earlier_stages() {
        let client =
            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
        let ev = client
            .send_and_wait_for(vec![1, 2], SubmissionStage::InBlock)
            .await
            .unwrap();
        assert_eq!(ev.stage(), SubmissionStage::InBlock);
        assert_eq!(ev.block(), Some(("0xblk", 5)));
    }

    #[tokio::test]
    async fn send_and_wait_for_finalized_drains_stream() {
        let client =
            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
        let ev = client
            .send_and_wait_for(vec![1, 2], SubmissionStage::Finalized)
            .await
            .unwrap();
        assert_eq!(ev.stage(), SubmissionStage::Finalized);
    }

    #[tokio::test]
    async fn send_and_wait_for_propagates_first_error() {
        let err = NodeClientError::TransactionInvalid {
            tx_data: vec![1, 2],
            source: None,
        };
        let client = FakeClient::with_events(vec![Ok(submitted()), Err(err)]);
        let result = client
            .send_and_wait_for(vec![1, 2], SubmissionStage::Finalized)
            .await;
        assert!(matches!(
            result,
            Err(NodeClientError::TransactionInvalid { .. })
        ));
    }

    #[tokio::test]
    async fn send_and_wait_for_reports_progress_error_if_stream_ends_early() {
        // Stream completes after Submitted without ever reaching InBlock.
        let client = FakeClient::with_events(vec![Ok(submitted())]);
        let result = client
            .send_and_wait_for(vec![1, 2], SubmissionStage::InBlock)
            .await;
        match result {
            Err(NodeClientError::TransactionProgress {
                desired_stage,
                tx_data,
                ..
            }) => {
                assert_eq!(desired_stage, SubmissionStage::InBlock);
                assert_eq!(tx_data, vec![1, 2]);
            }
            other => panic!("expected TransactionProgress, got {other:?}"),
        }
    }
}