moonproof_node_client/
client.rs1use futures::stream::{BoxStream, StreamExt};
9use moonproof_macros::async_trait;
10
11use crate::error::NodeClientError;
12use crate::event::{SubmissionEvent, SubmissionStage};
13
14pub type SerializedTransaction = Vec<u8>;
19
20#[derive(Debug, Clone, Default)]
22pub struct Genesis {
23 pub transactions: Vec<SerializedTransaction>,
27}
28
29#[async_trait]
36pub trait NodeClient: Send + Sync {
37 async fn send_midnight_transaction(
52 &self,
53 tx: SerializedTransaction,
54 ) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>;
55
56 async fn get_genesis(&self) -> Result<Genesis, NodeClientError>;
60
61 fn genesis_hash_hex(&self) -> Option<String> {
68 None
69 }
70
71 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 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 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}