Skip to main content

moonproof_contracts/
tx_phase.rs

1//! Typed transaction phase newtypes.
2//!
3//! The Midnight transaction pipeline runs a value through three
4//! distinct shapes:
5//!
6//! 1. [`UnprovenTx`] — wallet has assembled inputs/outputs and balanced
7//!    circuits; ZK proofs are not yet computed. Type-level shape:
8//!    `Transaction<Signature, ProofPreimageMarker, PedersenRandomness>`.
9//! 2. [`ProvenTx`] — every contract-call segment + every zswap input/
10//!    output has a ZK proof; Pedersen commitments are still in
11//!    randomness form. Type-level shape: `Transaction<Signature,
12//!    ProofMarker, PedersenRandomness>`.
13//! 3. [`FinalizedTx`] — sealed wire form with `PureGeneratorPedersen`
14//!    randomness committed; this is what the consensus node accepts.
15//!
16//! Providers exchange these typed values rather than tagged bytes, so
17//! handing a transaction of the wrong phase to a provider is a compile
18//! error rather than a runtime "`BAD_REQUEST`" from a downstream call.
19//!
20//! # Lazy bytes cache
21//!
22//! Each newtype carries a [`OnceCell`] that caches the
23//! tagged-serialized form. The first call to [`UnprovenTx::as_bytes`]
24//! / [`ProvenTx::as_bytes`] / [`FinalizedTx::as_bytes`] runs
25//! `tagged_serialize` once; later calls return the cached slice. The
26//! FFI surface is the only place the byte form is constructed
27//! eagerly: `from_tagged_bytes` deserializes into the typed value AND
28//! seeds the cache so the round-trip is free.
29
30use std::sync::OnceLock;
31
32use moonproof_ledger::ledger::structure::{ProofMarker, ProofPreimageMarker, Transaction};
33use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
34use moonproof_ledger::signatures::Signature;
35use moonproof_ledger::storage::db::InMemoryDB;
36use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
37
38use crate::error::{ContractRuntimeError, Result};
39
40/// Pre-prove transaction. Wallet has assembled inputs/outputs;
41/// circuits have been balanced; nothing is proven yet.
42///
43/// Construction:
44/// - From the typed value: [`UnprovenTx::new`].
45/// - From wire bytes (FFI boundary): [`UnprovenTx::from_tagged_bytes`].
46///
47/// # Phase-mismatch is a compile error
48///
49/// Wrong-phase tx into the wallet's `balance_tx` is rejected at
50/// compile time, not at runtime:
51///
52/// ```compile_fail
53/// use moonproof_runtime::providers::WalletProvider;
54/// use moonproof_runtime::tx_phase::UnprovenTx;
55///
56/// async fn passes_unproven_to_balance<W: WalletProvider>(w: &W, tx: UnprovenTx) {
57///     // mismatched types: expected `ProvenTx`, found `UnprovenTx`
58///     w.balance_tx(tx, None).await.unwrap();
59/// }
60/// ```
61#[derive(Debug)]
62pub struct UnprovenTx {
63    inner: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
64    cached_bytes: OnceLock<Vec<u8>>,
65}
66
67/// Post-prove, pre-bind transaction. ZK proofs computed for every
68/// circuit segment and zswap input/output. Pedersen commitments are
69/// still in randomness form; sealing has not happened yet.
70#[derive(Debug)]
71pub struct ProvenTx {
72    inner: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>,
73    cached_bytes: OnceLock<Vec<u8>>,
74}
75
76/// Sealed, wire-format transaction. `PureGeneratorPedersen` randomness
77/// committed; the node accepts this shape via
78/// `pallet_midnight.send_mn_transaction`.
79#[derive(Debug)]
80pub struct FinalizedTx {
81    inner: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>,
82    cached_bytes: OnceLock<Vec<u8>>,
83}
84
85// -- Constructors -------------------------------------------------------
86
87impl UnprovenTx {
88    /// Wrap a typed unproven transaction.
89    #[must_use]
90    pub fn new(
91        tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
92    ) -> Self {
93        Self {
94            inner: tx,
95            cached_bytes: OnceLock::new(),
96        }
97    }
98
99    /// Construct from tagged-serialized bytes. Used at the FFI
100    /// boundary where the caller speaks `Vec<u8>`. Seeds the bytes
101    /// cache so a subsequent [`Self::as_bytes`] is free.
102    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
103        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
104            ContractRuntimeError::Deserialize {
105                context: "UnprovenTx::from_tagged_bytes",
106                source,
107            }
108        })?;
109        let cache = OnceLock::new();
110        let _ = cache.set(bytes.to_vec());
111        Ok(Self {
112            inner,
113            cached_bytes: cache,
114        })
115    }
116
117    /// Borrow the typed inner value.
118    #[must_use]
119    pub fn as_inner(
120        &self,
121    ) -> &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
122        &self.inner
123    }
124
125    /// Move out the typed inner value.
126    #[must_use]
127    pub fn into_inner(
128        self,
129    ) -> Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
130        self.inner
131    }
132
133    /// Tagged-serialized bytes. Computed lazily on first call;
134    /// subsequent calls return the cached slice.
135    pub fn as_bytes(&self) -> Result<&[u8]> {
136        if let Some(b) = self.cached_bytes.get() {
137            return Ok(b.as_slice());
138        }
139        let mut buf = Vec::new();
140        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
141            ContractRuntimeError::Serialize {
142                context: "UnprovenTx::as_bytes",
143                source,
144            }
145        })?;
146        let _ = self.cached_bytes.set(buf);
147        Ok(self.cached_bytes.get().expect("just set").as_slice())
148    }
149
150    /// Tagged-serialized bytes as an owned `Vec<u8>` — convenience
151    /// for FFI surfaces that need ownership of the buffer.
152    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
153        Ok(self.as_bytes()?.to_vec())
154    }
155}
156
157impl Clone for UnprovenTx {
158    fn clone(&self) -> Self {
159        let cache = OnceLock::new();
160        if let Some(b) = self.cached_bytes.get() {
161            let _ = cache.set(b.clone());
162        }
163        Self {
164            inner: self.inner.clone(),
165            cached_bytes: cache,
166        }
167    }
168}
169
170impl ProvenTx {
171    #[must_use]
172    pub fn new(tx: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>) -> Self {
173        Self {
174            inner: tx,
175            cached_bytes: OnceLock::new(),
176        }
177    }
178
179    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
180        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
181            ContractRuntimeError::Deserialize {
182                context: "ProvenTx::from_tagged_bytes",
183                source,
184            }
185        })?;
186        let cache = OnceLock::new();
187        let _ = cache.set(bytes.to_vec());
188        Ok(Self {
189            inner,
190            cached_bytes: cache,
191        })
192    }
193
194    #[must_use]
195    pub fn as_inner(&self) -> &Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> {
196        &self.inner
197    }
198
199    #[must_use]
200    pub fn into_inner(self) -> Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> {
201        self.inner
202    }
203
204    pub fn as_bytes(&self) -> Result<&[u8]> {
205        if let Some(b) = self.cached_bytes.get() {
206            return Ok(b.as_slice());
207        }
208        let mut buf = Vec::new();
209        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
210            ContractRuntimeError::Serialize {
211                context: "ProvenTx::as_bytes",
212                source,
213            }
214        })?;
215        let _ = self.cached_bytes.set(buf);
216        Ok(self.cached_bytes.get().expect("just set").as_slice())
217    }
218
219    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
220        Ok(self.as_bytes()?.to_vec())
221    }
222}
223
224impl Clone for ProvenTx {
225    fn clone(&self) -> Self {
226        let cache = OnceLock::new();
227        if let Some(b) = self.cached_bytes.get() {
228            let _ = cache.set(b.clone());
229        }
230        Self {
231            inner: self.inner.clone(),
232            cached_bytes: cache,
233        }
234    }
235}
236
237impl FinalizedTx {
238    #[must_use]
239    pub fn new(tx: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>) -> Self {
240        Self {
241            inner: tx,
242            cached_bytes: OnceLock::new(),
243        }
244    }
245
246    pub fn from_tagged_bytes(bytes: &[u8]) -> Result<Self> {
247        let inner = tagged_deserialize(&mut &bytes[..]).map_err(|source| {
248            ContractRuntimeError::Deserialize {
249                context: "FinalizedTx::from_tagged_bytes",
250                source,
251            }
252        })?;
253        let cache = OnceLock::new();
254        let _ = cache.set(bytes.to_vec());
255        Ok(Self {
256            inner,
257            cached_bytes: cache,
258        })
259    }
260
261    #[must_use]
262    pub fn as_inner(
263        &self,
264    ) -> &Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> {
265        &self.inner
266    }
267
268    #[must_use]
269    pub fn into_inner(
270        self,
271    ) -> Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> {
272        self.inner
273    }
274
275    pub fn as_bytes(&self) -> Result<&[u8]> {
276        if let Some(b) = self.cached_bytes.get() {
277            return Ok(b.as_slice());
278        }
279        let mut buf = Vec::new();
280        tagged_serialize(&self.inner, &mut buf).map_err(|source| {
281            ContractRuntimeError::Serialize {
282                context: "FinalizedTx::as_bytes",
283                source,
284            }
285        })?;
286        let _ = self.cached_bytes.set(buf);
287        Ok(self.cached_bytes.get().expect("just set").as_slice())
288    }
289
290    pub fn to_tagged_bytes(&self) -> Result<Vec<u8>> {
291        Ok(self.as_bytes()?.to_vec())
292    }
293}
294
295impl Clone for FinalizedTx {
296    fn clone(&self) -> Self {
297        let cache = OnceLock::new();
298        if let Some(b) = self.cached_bytes.get() {
299            let _ = cache.set(b.clone());
300        }
301        Self {
302            inner: self.inner.clone(),
303            cached_bytes: cache,
304        }
305    }
306}
307
308// Phase round-trip + cache behaviour is exercised end-to-end by the
309// runtime's submit-tx integration tests (`submit_tx::tests::*`,
310// `submit_deploy_tx::tests::*`) that drive the prove → balance →
311// submit pipeline through the typed phases. Standalone unit tests
312// would need a fully-formed Transaction value; constructing one from
313// scratch pulls in too much ledger-crate setup to be worthwhile when
314// the integration tests already cover the behaviour.