Skip to main content

moonproof_contracts/providers/
node_client_midnight.rs

1//! Concrete [`MidnightProvider`] wrapping a
2//! [`moonproof_node_client::NodeClient`]. Submits a finalized wire-
3//! format transaction and waits until the requested [`SubmissionStage`]
4//! is reached (default: [`SubmissionStage::InBlock`]).
5//!
6//! The returned [`TransactionId`] carries the **Midnight transaction
7//! hash** (sha256 of the tagged-serialized tx bytes) — the same hash
8//! the indexer indexes by, so
9//! [`super::PublicDataProvider::watch_for_tx_data`] can look up the
10//! finalized tx immediately after submission returns.
11//!
12//! # Why NOT the Substrate extrinsic hash
13//!
14//! Midnight txs are submitted wrapped in a Substrate extrinsic. The
15//! Substrate layer computes its own extrinsic hash (what
16//! `SubmissionEvent::InBlock.tx_hash` carries). That hash is
17//! **different** from the inner Midnight tx hash the indexer tracks —
18//! returning the extrinsic hash would cause `watch_for_tx_data` to
19//! poll indefinitely because the indexer never sees that hash. We
20//! compute the Midnight tx hash locally from the bytes we submitted,
21//! which matches the indexer's `hash` field 1:1.
22
23use std::sync::Arc;
24
25use moonproof_macros::async_trait;
26use moonproof_node_client::{NodeClient, SubmissionStage};
27
28use crate::error::Result;
29use crate::providers::midnight::MidnightProvider;
30use crate::types::TransactionId;
31
32/// Concrete [`MidnightProvider`] backed by any [`NodeClient`] impl.
33/// Generic on `C` so callers can drop in the feature-gated
34/// [`moonproof_node_client::PolkadotNodeClient`] or their own fake.
35pub struct NodeClientMidnightProvider<C: NodeClient + 'static> {
36    client: Arc<C>,
37    wait_stage: SubmissionStage,
38}
39
40impl<C: NodeClient + 'static> std::fmt::Debug for NodeClientMidnightProvider<C> {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("NodeClientMidnightProvider")
43            .field("wait_stage", &self.wait_stage.as_tag())
44            .finish_non_exhaustive()
45    }
46}
47
48impl<C: NodeClient + 'static> Clone for NodeClientMidnightProvider<C> {
49    fn clone(&self) -> Self {
50        Self {
51            client: Arc::clone(&self.client),
52            wait_stage: self.wait_stage,
53        }
54    }
55}
56
57impl<C: NodeClient + 'static> NodeClientMidnightProvider<C> {
58    /// Default: wait for [`SubmissionStage::InBlock`] before returning
59    /// from `submit_tx`. Matches the TS reference's
60    /// `sendMidnightTransactionAndWait('InBlock')` default.
61    #[must_use]
62    pub fn new(client: Arc<C>) -> Self {
63        Self {
64            client,
65            wait_stage: SubmissionStage::InBlock,
66        }
67    }
68
69    /// Configure which [`SubmissionStage`] to block on before
70    /// returning. Used by callers that need stronger finality
71    /// ([`SubmissionStage::Finalized`]) or quicker acks
72    /// ([`SubmissionStage::Submitted`]).
73    #[must_use]
74    pub fn with_wait_stage(mut self, stage: SubmissionStage) -> Self {
75        self.wait_stage = stage;
76        self
77    }
78}
79
80#[async_trait]
81impl<C: NodeClient + 'static> MidnightProvider for NodeClientMidnightProvider<C> {
82    async fn submit_tx(&self, tx: crate::tx_phase::FinalizedTx) -> Result<TransactionId> {
83        let finalized_tx_bytes = tx.to_tagged_bytes()?;
84        // Compute the Midnight tx hash from the bytes we're about to
85        // submit. This is the same hash the indexer will record, so
86        // downstream `watch_for_tx_data` lookups can find the tx.
87        let midnight_hash = compute_midnight_tx_hash(&finalized_tx_bytes);
88        let _event = self
89            .client
90            .send_and_wait_for(finalized_tx_bytes, self.wait_stage)
91            .await
92            .map_err(|e| crate::error::ContractRuntimeError::Provider {
93                provider: "midnight",
94                message: format!("send_and_wait_for({}): {e}", self.wait_stage.as_tag()),
95            })?;
96        Ok(TransactionId::new(midnight_hash))
97    }
98}
99
100/// Compute the Midnight transaction hash as a lower-case hex string
101/// (no `0x` prefix). Equivalent to
102/// `Transaction::transaction_hash()` because the ledger defines that
103/// method as `sha256(tagged_serialize(self))` — and
104/// `finalized_tx_bytes` is exactly those tagged-serialized bytes.
105/// Skipping the `tagged_deserialize → Transaction → transaction_hash()`
106/// round trip avoids requiring well-formed bytes (so unit tests can
107/// pass arbitrary fixture bytes and still get a deterministic id).
108fn compute_midnight_tx_hash(bytes: &[u8]) -> String {
109    moonproof_utils::sha256_hex(bytes)
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use async_trait::async_trait;
116    use futures::stream::{self, BoxStream, StreamExt};
117    use moonproof_node_client::{Genesis, NodeClientError, SerializedTransaction, SubmissionEvent};
118    use std::sync::Mutex;
119
120    /// In-memory [`NodeClient`] that returns a scripted event sequence
121    /// for one call. Lets us exercise the `submit_tx` happy path + the
122    /// stage-selection logic without a running harness.
123    #[derive(Debug)]
124    struct ScriptedClient {
125        events: Mutex<Option<Vec<SubmissionEvent>>>,
126    }
127
128    impl ScriptedClient {
129        fn new(events: Vec<SubmissionEvent>) -> Self {
130            Self {
131                events: Mutex::new(Some(events)),
132            }
133        }
134    }
135
136    #[async_trait]
137    impl NodeClient for ScriptedClient {
138        async fn send_midnight_transaction(
139            &self,
140            _tx: SerializedTransaction,
141        ) -> std::result::Result<
142            BoxStream<'static, std::result::Result<SubmissionEvent, NodeClientError>>,
143            NodeClientError,
144        > {
145            let events = self
146                .events
147                .lock()
148                .expect("lock poisoned")
149                .take()
150                .expect("ScriptedClient only supports one submission");
151            Ok(stream::iter(events.into_iter().map(Ok)).boxed())
152        }
153
154        async fn get_genesis(&self) -> std::result::Result<Genesis, NodeClientError> {
155            Ok(Genesis::default())
156        }
157    }
158
159    fn submitted_event() -> SubmissionEvent {
160        SubmissionEvent::Submitted {
161            tx: vec![1],
162            tx_hash: "0xhash".into(),
163        }
164    }
165
166    fn in_block_event() -> SubmissionEvent {
167        SubmissionEvent::InBlock {
168            tx: vec![1],
169            block_hash: "0xblk".into(),
170            block_height: 7,
171            tx_hash: "0xhash".into(),
172        }
173    }
174
175    /// Precomputed `sha256([0, 0, 0, 0])` as lower-case hex — the
176    /// hash our fake 4-byte payload produces through
177    /// Build an empty `FinalizedTx` for the unit tests below — `submit_tx`
178    /// only forwards bytes + computes their hash, so the contents are
179    /// irrelevant; only the round-trip behaviour is exercised.
180    fn empty_finalized_tx() -> crate::tx_phase::FinalizedTx {
181        use rand::SeedableRng;
182        let unproven: moonproof_ledger::ledger::structure::Transaction<
183            moonproof_ledger::signatures::Signature,
184            moonproof_ledger::ledger::structure::ProofPreimageMarker,
185            moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
186            moonproof_ledger::storage::db::InMemoryDB,
187        > = moonproof_ledger::ledger::structure::Transaction::from_intents(
188            "local-test",
189            moonproof_ledger::storage::storage::HashMap::new(),
190        );
191        // Empty tx has no preimages — the dummy prover never gets
192        // its trait methods called.
193        let unproven_typed = crate::tx_phase::UnprovenTx::new(unproven);
194        let proven = futures::executor::block_on(crate::providers::ProofProvider::prove_tx(
195            &crate::test_helpers::PassThroughProof,
196            unproven_typed,
197            &crate::providers::ProveTxConfig::default(),
198        ))
199        .expect("PassThroughProof on empty tx");
200        let sealed = proven
201            .into_inner()
202            .seal(rand::rngs::StdRng::seed_from_u64(1));
203        crate::tx_phase::FinalizedTx::new(sealed)
204    }
205
206    #[tokio::test]
207    async fn submit_tx_returns_midnight_tx_hash_of_submitted_bytes() {
208        let client = Arc::new(ScriptedClient::new(vec![
209            submitted_event(),
210            in_block_event(),
211        ]));
212        let provider = NodeClientMidnightProvider::new(client);
213        let tx = empty_finalized_tx();
214        let expected_hash = compute_midnight_tx_hash(tx.as_bytes().unwrap());
215        let id = provider.submit_tx(tx).await.unwrap();
216        assert_eq!(
217            id.as_str(),
218            &expected_hash,
219            "TransactionId must carry the Midnight tx hash (sha256 of \
220             the finalized tx bytes), not the Substrate extrinsic hash"
221        );
222    }
223
224    #[tokio::test]
225    async fn with_wait_stage_submitted_returns_midnight_tx_hash() {
226        let client = Arc::new(ScriptedClient::new(vec![
227            submitted_event(),
228            in_block_event(),
229        ]));
230        let provider =
231            NodeClientMidnightProvider::new(client).with_wait_stage(SubmissionStage::Submitted);
232        let tx = empty_finalized_tx();
233        let expected_hash = compute_midnight_tx_hash(tx.as_bytes().unwrap());
234        let id = provider.submit_tx(tx).await.unwrap();
235        assert_eq!(id.as_str(), &expected_hash);
236    }
237
238    #[test]
239    fn debug_reports_wait_stage() {
240        let client = Arc::new(ScriptedClient::new(Vec::new()));
241        let provider = NodeClientMidnightProvider::new(client);
242        let dbg = format!("{provider:?}");
243        assert!(dbg.contains("InBlock"), "{dbg}");
244    }
245
246    #[test]
247    fn clone_preserves_wait_stage() {
248        let client = Arc::new(ScriptedClient::new(Vec::new()));
249        let provider =
250            NodeClientMidnightProvider::new(client).with_wait_stage(SubmissionStage::Finalized);
251        let cloned = provider.clone();
252        assert_eq!(cloned.wait_stage, SubmissionStage::Finalized);
253    }
254}