use std::sync::Arc;
use moonproof_macros::async_trait;
use moonproof_node_client::{NodeClient, SubmissionStage};
use crate::error::Result;
use crate::providers::midnight::MidnightProvider;
use crate::types::TransactionId;
pub struct NodeClientMidnightProvider<C: NodeClient + 'static> {
client: Arc<C>,
wait_stage: SubmissionStage,
}
impl<C: NodeClient + 'static> std::fmt::Debug for NodeClientMidnightProvider<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NodeClientMidnightProvider")
.field("wait_stage", &self.wait_stage.as_tag())
.finish_non_exhaustive()
}
}
impl<C: NodeClient + 'static> Clone for NodeClientMidnightProvider<C> {
fn clone(&self) -> Self {
Self {
client: Arc::clone(&self.client),
wait_stage: self.wait_stage,
}
}
}
impl<C: NodeClient + 'static> NodeClientMidnightProvider<C> {
#[must_use]
pub fn new(client: Arc<C>) -> Self {
Self {
client,
wait_stage: SubmissionStage::InBlock,
}
}
#[must_use]
pub fn with_wait_stage(mut self, stage: SubmissionStage) -> Self {
self.wait_stage = stage;
self
}
}
#[async_trait]
impl<C: NodeClient + 'static> MidnightProvider for NodeClientMidnightProvider<C> {
async fn submit_tx(&self, tx: crate::tx_phase::FinalizedTx) -> Result<TransactionId> {
let finalized_tx_bytes = tx.to_tagged_bytes()?;
let midnight_hash = compute_midnight_tx_hash(&finalized_tx_bytes);
let _event = self
.client
.send_and_wait_for(finalized_tx_bytes, self.wait_stage)
.await
.map_err(|e| crate::error::ContractRuntimeError::Provider {
provider: "midnight",
message: format!("send_and_wait_for({}): {e}", self.wait_stage.as_tag()),
})?;
Ok(TransactionId::new(midnight_hash))
}
}
fn compute_midnight_tx_hash(bytes: &[u8]) -> String {
moonproof_utils::sha256_hex(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use futures::stream::{self, BoxStream, StreamExt};
use moonproof_node_client::{Genesis, NodeClientError, SerializedTransaction, SubmissionEvent};
use std::sync::Mutex;
#[derive(Debug)]
struct ScriptedClient {
events: Mutex<Option<Vec<SubmissionEvent>>>,
}
impl ScriptedClient {
fn new(events: Vec<SubmissionEvent>) -> Self {
Self {
events: Mutex::new(Some(events)),
}
}
}
#[async_trait]
impl NodeClient for ScriptedClient {
async fn send_midnight_transaction(
&self,
_tx: SerializedTransaction,
) -> std::result::Result<
BoxStream<'static, std::result::Result<SubmissionEvent, NodeClientError>>,
NodeClientError,
> {
let events = self
.events
.lock()
.expect("lock poisoned")
.take()
.expect("ScriptedClient only supports one submission");
Ok(stream::iter(events.into_iter().map(Ok)).boxed())
}
async fn get_genesis(&self) -> std::result::Result<Genesis, NodeClientError> {
Ok(Genesis::default())
}
}
fn submitted_event() -> SubmissionEvent {
SubmissionEvent::Submitted {
tx: vec![1],
tx_hash: "0xhash".into(),
}
}
fn in_block_event() -> SubmissionEvent {
SubmissionEvent::InBlock {
tx: vec![1],
block_hash: "0xblk".into(),
block_height: 7,
tx_hash: "0xhash".into(),
}
}
fn empty_finalized_tx() -> crate::tx_phase::FinalizedTx {
use rand::SeedableRng;
let unproven: moonproof_ledger::ledger::structure::Transaction<
moonproof_ledger::signatures::Signature,
moonproof_ledger::ledger::structure::ProofPreimageMarker,
moonproof_ledger::transient_crypto::commitment::PedersenRandomness,
moonproof_ledger::storage::db::InMemoryDB,
> = moonproof_ledger::ledger::structure::Transaction::from_intents(
"local-test",
moonproof_ledger::storage::storage::HashMap::new(),
);
let unproven_typed = crate::tx_phase::UnprovenTx::new(unproven);
let proven = futures::executor::block_on(crate::providers::ProofProvider::prove_tx(
&crate::test_helpers::PassThroughProof,
unproven_typed,
&crate::providers::ProveTxConfig::default(),
))
.expect("PassThroughProof on empty tx");
let sealed = proven
.into_inner()
.seal(rand::rngs::StdRng::seed_from_u64(1));
crate::tx_phase::FinalizedTx::new(sealed)
}
#[tokio::test]
async fn submit_tx_returns_midnight_tx_hash_of_submitted_bytes() {
let client = Arc::new(ScriptedClient::new(vec![
submitted_event(),
in_block_event(),
]));
let provider = NodeClientMidnightProvider::new(client);
let tx = empty_finalized_tx();
let expected_hash = compute_midnight_tx_hash(tx.as_bytes().unwrap());
let id = provider.submit_tx(tx).await.unwrap();
assert_eq!(
id.as_str(),
&expected_hash,
"TransactionId must carry the Midnight tx hash (sha256 of \
the finalized tx bytes), not the Substrate extrinsic hash"
);
}
#[tokio::test]
async fn with_wait_stage_submitted_returns_midnight_tx_hash() {
let client = Arc::new(ScriptedClient::new(vec![
submitted_event(),
in_block_event(),
]));
let provider =
NodeClientMidnightProvider::new(client).with_wait_stage(SubmissionStage::Submitted);
let tx = empty_finalized_tx();
let expected_hash = compute_midnight_tx_hash(tx.as_bytes().unwrap());
let id = provider.submit_tx(tx).await.unwrap();
assert_eq!(id.as_str(), &expected_hash);
}
#[test]
fn debug_reports_wait_stage() {
let client = Arc::new(ScriptedClient::new(Vec::new()));
let provider = NodeClientMidnightProvider::new(client);
let dbg = format!("{provider:?}");
assert!(dbg.contains("InBlock"), "{dbg}");
}
#[test]
fn clone_preserves_wait_stage() {
let client = Arc::new(ScriptedClient::new(Vec::new()));
let provider =
NodeClientMidnightProvider::new(client).with_wait_stage(SubmissionStage::Finalized);
let cloned = provider.clone();
assert_eq!(cloned.wait_stage, SubmissionStage::Finalized);
}
}