moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Concrete [`MidnightProvider`] wrapping a
//! [`moonproof_node_client::NodeClient`]. Submits a finalized wire-
//! format transaction and waits until the requested [`SubmissionStage`]
//! is reached (default: [`SubmissionStage::InBlock`]).
//!
//! The returned [`TransactionId`] carries the **Midnight transaction
//! hash** (sha256 of the tagged-serialized tx bytes) — the same hash
//! the indexer indexes by, so
//! [`super::PublicDataProvider::watch_for_tx_data`] can look up the
//! finalized tx immediately after submission returns.
//!
//! # Why NOT the Substrate extrinsic hash
//!
//! Midnight txs are submitted wrapped in a Substrate extrinsic. The
//! Substrate layer computes its own extrinsic hash (what
//! `SubmissionEvent::InBlock.tx_hash` carries). That hash is
//! **different** from the inner Midnight tx hash the indexer tracks —
//! returning the extrinsic hash would cause `watch_for_tx_data` to
//! poll indefinitely because the indexer never sees that hash. We
//! compute the Midnight tx hash locally from the bytes we submitted,
//! which matches the indexer's `hash` field 1:1.

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;

/// Concrete [`MidnightProvider`] backed by any [`NodeClient`] impl.
/// Generic on `C` so callers can drop in the feature-gated
/// [`moonproof_node_client::PolkadotNodeClient`] or their own fake.
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> {
    /// Default: wait for [`SubmissionStage::InBlock`] before returning
    /// from `submit_tx`. Matches the TS reference's
    /// `sendMidnightTransactionAndWait('InBlock')` default.
    #[must_use]
    pub fn new(client: Arc<C>) -> Self {
        Self {
            client,
            wait_stage: SubmissionStage::InBlock,
        }
    }

    /// Configure which [`SubmissionStage`] to block on before
    /// returning. Used by callers that need stronger finality
    /// ([`SubmissionStage::Finalized`]) or quicker acks
    /// ([`SubmissionStage::Submitted`]).
    #[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()?;
        // Compute the Midnight tx hash from the bytes we're about to
        // submit. This is the same hash the indexer will record, so
        // downstream `watch_for_tx_data` lookups can find the tx.
        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))
    }
}

/// Compute the Midnight transaction hash as a lower-case hex string
/// (no `0x` prefix). Equivalent to
/// `Transaction::transaction_hash()` because the ledger defines that
/// method as `sha256(tagged_serialize(self))` — and
/// `finalized_tx_bytes` is exactly those tagged-serialized bytes.
/// Skipping the `tagged_deserialize → Transaction → transaction_hash()`
/// round trip avoids requiring well-formed bytes (so unit tests can
/// pass arbitrary fixture bytes and still get a deterministic id).
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;

    /// In-memory [`NodeClient`] that returns a scripted event sequence
    /// for one call. Lets us exercise the `submit_tx` happy path + the
    /// stage-selection logic without a running harness.
    #[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(),
        }
    }

    /// Precomputed `sha256([0, 0, 0, 0])` as lower-case hex — the
    /// hash our fake 4-byte payload produces through
    /// Build an empty `FinalizedTx` for the unit tests below — `submit_tx`
    /// only forwards bytes + computes their hash, so the contents are
    /// irrelevant; only the round-trip behaviour is exercised.
    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(),
        );
        // Empty tx has no preimages — the dummy prover never gets
        // its trait methods called.
        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);
    }
}