use futures::stream::{BoxStream, StreamExt};
use moonproof_macros::async_trait;
use crate::error::NodeClientError;
use crate::event::{SubmissionEvent, SubmissionStage};
pub type SerializedTransaction = Vec<u8>;
#[derive(Debug, Clone, Default)]
pub struct Genesis {
pub transactions: Vec<SerializedTransaction>,
}
#[async_trait]
pub trait NodeClient: Send + Sync {
async fn send_midnight_transaction(
&self,
tx: SerializedTransaction,
) -> Result<BoxStream<'static, Result<SubmissionEvent, NodeClientError>>, NodeClientError>;
async fn get_genesis(&self) -> Result<Genesis, NodeClientError>;
fn genesis_hash_hex(&self) -> Option<String> {
None
}
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;
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() {
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:?}"),
}
}
}