moonproof_contracts/providers/
node_client_midnight.rs1use 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
32pub 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 #[must_use]
62 pub fn new(client: Arc<C>) -> Self {
63 Self {
64 client,
65 wait_stage: SubmissionStage::InBlock,
66 }
67 }
68
69 #[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 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
100fn 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 #[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 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 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}