Skip to main content

moonproof_node_client/
client.rs

1//! The [`NodeClient`] trait — the abstract interface every concrete node
2//! adapter implements.
3//!
4//! This is deliberately thin: two async methods plus a convenience
5//! `send_and_wait_for` helper. Mirrors the TS `NodeClient.Service` interface
6//! from `midnight-wallet/packages/node-client/src/effect/NodeClient.ts`.
7
8use futures::stream::{BoxStream, StreamExt};
9use moonproof_macros::async_trait;
10
11use crate::error::NodeClientError;
12use crate::event::{SubmissionEvent, SubmissionStage};
13
14/// Transparent newtype wrapper around Midnight transaction bytes.
15///
16/// Matches the TS `SerializedTransaction` opaque type — the same bytes you
17/// get back from `moonproof_wallet::unshielded::ledger_adapter::serialize_transaction`.
18pub type SerializedTransaction = Vec<u8>;
19
20/// Initial-chain-state bootstrap data returned by [`NodeClient::get_genesis`].
21#[derive(Debug, Clone, Default)]
22pub struct Genesis {
23    /// Midnight transactions extracted from the genesis block's `midnight.sendMnTransaction`
24    /// extrinsics, in the order they appear. Used to seed a local ledger replay
25    /// without full-history sync.
26    pub transactions: Vec<SerializedTransaction>,
27}
28
29/// Client for the Midnight node's submission RPC.
30///
31/// Concrete impls live alongside this trait. The default is the
32/// subxt-backed `PolkadotNodeClient` (added behind a feature flag so the
33/// pure-logic layer remains Substrate-free and testable without a full
34/// toolchain).
35#[async_trait]
36pub trait NodeClient: Send + Sync {
37    /// Submit a Midnight transaction and stream every subsequent status
38    /// event until the stream terminates with [`SubmissionEvent::Finalized`],
39    /// a terminal error, or the caller drops the stream.
40    ///
41    /// The implementation is responsible for:
42    ///
43    /// - Connecting to the node (if not already connected).
44    /// - Wrapping `tx` in an unsigned Substrate extrinsic
45    ///   (`midnight.send_mn_transaction(tx)`).
46    /// - Subscribing to `author_submitAndWatchExtrinsic`.
47    /// - Translating each returned status into a [`SubmissionEvent`] or a
48    ///   terminating [`NodeClientError`] — use
49    ///   [`crate::status::SubmissionOutcome::from_status`] for the pure
50    ///   mapping.
51    async fn send_midnight_transaction(
52        &self,
53        tx: SerializedTransaction,
54    ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>;
55
56    /// Fetch the genesis block and extract its embedded Midnight transactions.
57    ///
58    /// Corresponds to TS `getGenesis()` — used for initial-state bootstrap.
59    async fn get_genesis(&self) -> Result<Genesis, NodeClientError>;
60
61    /// The chain's genesis block hash, `0x`-prefixed hex. Identifies
62    /// the chain *instance*: two runs of a local-dev chain have
63    /// different genesis hashes even though both call themselves
64    /// `localdev`. Snapshot stores use this to refuse resuming state
65    /// captured against a chain that no longer exists. `None` when
66    /// the client can't know it (offline test doubles).
67    fn genesis_hash_hex(&self) -> Option<String> {
68        None
69    }
70
71    /// Submit a transaction and return the first event matching `stage`, or
72    /// propagate the first error the stream reports.
73    ///
74    /// Default impl drives the stream; concrete clients rarely need to
75    /// override. Mirrors TS `sendMidnightTransactionAndWait`.
76    async fn send_and_wait_for(
77        &self,
78        tx: SerializedTransaction,
79        stage: SubmissionStage,
80    ) -> Result<SubmissionEvent, NodeClientError> {
81        let mut stream = self.send_midnight_transaction(tx.clone()).await?;
82        while let Some(item) = stream.next().await {
83            let event = item?;
84            if event.stage() == stage {
85                return Ok(event);
86            }
87        }
88        Err(NodeClientError::TransactionProgress {
89            message: format!(
90                "stream ended without reaching desired stage '{stage}' and no other error was reported"
91            ),
92            tx_data: tx,
93            desired_stage: stage,
94        })
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::event::SubmissionEvent;
102    use futures::stream;
103
104    /// Minimal in-memory client whose `send_midnight_transaction` returns a
105    /// scripted event sequence. Exercises the default `send_and_wait_for`
106    /// without any network. `NodeClientError` isn't `Clone` (boxed `source`),
107    /// so events are drained via `Mutex::take` on first call — each test
108    /// only submits once.
109    struct FakeClient {
110        events: std::sync::Mutex<Option<Vec<Result<SubmissionEvent, NodeClientError>>>>,
111    }
112
113    impl FakeClient {
114        fn with_events(events: Vec<Result<SubmissionEvent, NodeClientError>>) -> Self {
115            Self {
116                events: std::sync::Mutex::new(Some(events)),
117            }
118        }
119    }
120
121    #[async_trait]
122    impl NodeClient for FakeClient {
123        async fn send_midnight_transaction(
124            &self,
125            _tx: SerializedTransaction,
126        ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>
127        {
128            let events = self
129                .events
130                .lock()
131                .expect("events mutex poisoned")
132                .take()
133                .expect("FakeClient.send_midnight_transaction called more than once");
134            Ok(stream::iter(events).boxed())
135        }
136
137        async fn get_genesis(&self) -> Result<Genesis, NodeClientError> {
138            Ok(Genesis::default())
139        }
140    }
141
142    fn submitted() -> SubmissionEvent {
143        SubmissionEvent::Submitted {
144            tx: vec![1, 2],
145            tx_hash: "0xa".into(),
146        }
147    }
148
149    fn in_block() -> SubmissionEvent {
150        SubmissionEvent::InBlock {
151            tx: vec![1, 2],
152            block_hash: "0xblk".into(),
153            block_height: 5,
154            tx_hash: "0xa".into(),
155        }
156    }
157
158    fn finalized() -> SubmissionEvent {
159        SubmissionEvent::Finalized {
160            tx: vec![1, 2],
161            block_hash: "0xfin".into(),
162            block_height: 6,
163            tx_hash: "0xa".into(),
164        }
165    }
166
167    #[tokio::test]
168    async fn send_and_wait_for_submitted_returns_first_match() {
169        let client =
170            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
171        let ev = client
172            .send_and_wait_for(vec![1, 2], SubmissionStage::Submitted)
173            .await
174            .unwrap();
175        assert_eq!(ev.stage(), SubmissionStage::Submitted);
176    }
177
178    #[tokio::test]
179    async fn send_and_wait_for_in_block_skips_earlier_stages() {
180        let client =
181            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
182        let ev = client
183            .send_and_wait_for(vec![1, 2], SubmissionStage::InBlock)
184            .await
185            .unwrap();
186        assert_eq!(ev.stage(), SubmissionStage::InBlock);
187        assert_eq!(ev.block(), Some(("0xblk", 5)));
188    }
189
190    #[tokio::test]
191    async fn send_and_wait_for_finalized_drains_stream() {
192        let client =
193            FakeClient::with_events(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
194        let ev = client
195            .send_and_wait_for(vec![1, 2], SubmissionStage::Finalized)
196            .await
197            .unwrap();
198        assert_eq!(ev.stage(), SubmissionStage::Finalized);
199    }
200
201    #[tokio::test]
202    async fn send_and_wait_for_propagates_first_error() {
203        let err = NodeClientError::TransactionInvalid {
204            tx_data: vec![1, 2],
205            source: None,
206        };
207        let client = FakeClient::with_events(vec![Ok(submitted()), Err(err)]);
208        let result = client
209            .send_and_wait_for(vec![1, 2], SubmissionStage::Finalized)
210            .await;
211        assert!(matches!(
212            result,
213            Err(NodeClientError::TransactionInvalid { .. })
214        ));
215    }
216
217    #[tokio::test]
218    async fn send_and_wait_for_reports_progress_error_if_stream_ends_early() {
219        // Stream completes after Submitted without ever reaching InBlock.
220        let client = FakeClient::with_events(vec![Ok(submitted())]);
221        let result = client
222            .send_and_wait_for(vec![1, 2], SubmissionStage::InBlock)
223            .await;
224        match result {
225            Err(NodeClientError::TransactionProgress {
226                desired_stage,
227                tx_data,
228                ..
229            }) => {
230                assert_eq!(desired_stage, SubmissionStage::InBlock);
231                assert_eq!(tx_data, vec![1, 2]);
232            }
233            other => panic!("expected TransactionProgress, got {other:?}"),
234        }
235    }
236}