Skip to main content

moonproof_contracts/providers/
private_state.rs

1//! Private-state provider trait — port of
2//! `@midnight-ntwrk/midnight-js-types/src/private-state-provider.ts`.
3//!
4//! Manages two parallel stores:
5//!
6//! 1. Per-`PrivateStateId` blobs of private state (contract-defined,
7//!    opaque to the runtime).
8//! 2. Per-contract-address signing keys — each deployed contract has
9//!    a single maintenance-authority signing key that the owner holds
10//!    locally.
11//!
12//! The TS interface uses `any` for the private-state payload; Rust
13//! uses `Vec<u8>` (the caller serialises their private state before
14//! storing it — moonproof doesn't tie the store to a specific
15//! serialisation format).
16
17use moonproof_macros::async_trait;
18
19use moonproof_ledger::coin_structure::contract::ContractAddress;
20use moonproof_ledger::signatures::SigningKey;
21
22use crate::error::Result;
23use crate::types::PrivateStateId;
24
25/// Upper bound on batch export / import sizes. Matches TS
26/// `MAX_EXPORT_STATES` (10000). Exceeding this is an error — the
27/// limit exists to prevent memory-exhaustion attacks.
28pub const MAX_EXPORT_STATES: usize = 10_000;
29
30/// Upper bound on batch export / import sizes for signing keys. Matches
31/// TS `MAX_EXPORT_SIGNING_KEYS`.
32pub const MAX_EXPORT_SIGNING_KEYS: usize = 10_000;
33
34/// Encrypted export of zero-or-more private states, matching the TS
35/// `PrivateStateExport` shape. Callers round-trip this through their
36/// own storage — file, cloud, etc. The `format` field is a magic
37/// string the importer verifies.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PrivateStateExport {
40    /// Format identifier — must be
41    /// `"midnight-private-state-export"`.
42    pub format: String,
43    /// Encrypted payload (base64-encoded AES-256-GCM JSON).
44    pub encrypted_payload: String,
45    /// Salt used for key derivation (32 bytes, hex-encoded = 64
46    /// chars).
47    pub salt: String,
48}
49
50/// Encrypted export of signing keys, mirroring
51/// [`PrivateStateExport`]. Separate type so the magic string can
52/// differ (`"midnight-signing-key-export"`).
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct SigningKeyExport {
55    pub format: String,
56    pub encrypted_payload: String,
57    pub salt: String,
58}
59
60/// Policy for resolving conflicts during import. Port of TS
61/// `'skip' | 'overwrite' | 'error'`.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63pub enum ImportConflictStrategy {
64    /// Keep existing, drop incoming.
65    Skip,
66    /// Replace existing with incoming.
67    Overwrite,
68    /// Return an error if any conflict is seen. TS default.
69    #[default]
70    Error,
71}
72
73/// Options for [`PrivateStateProvider::export_private_states`].
74#[derive(Debug, Clone, Default)]
75pub struct ExportPrivateStatesOptions {
76    /// Override password; if `None`, the provider's storage password
77    /// is used.
78    pub password: Option<String>,
79    /// Cap the number of exported entries. `None` = use
80    /// [`MAX_EXPORT_STATES`].
81    pub max_states: Option<usize>,
82}
83
84/// Options for [`PrivateStateProvider::import_private_states`].
85#[derive(Debug, Clone, Default)]
86pub struct ImportPrivateStatesOptions {
87    pub password: Option<String>,
88    pub conflict_strategy: ImportConflictStrategy,
89    pub max_states: Option<usize>,
90}
91
92/// Result of [`PrivateStateProvider::import_private_states`].
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub struct ImportPrivateStatesResult {
95    pub imported: usize,
96    pub skipped: usize,
97    pub overwritten: usize,
98}
99
100/// Options for [`PrivateStateProvider::export_signing_keys`].
101#[derive(Debug, Clone, Default)]
102pub struct ExportSigningKeysOptions {
103    pub password: Option<String>,
104    pub max_keys: Option<usize>,
105}
106
107/// Options for [`PrivateStateProvider::import_signing_keys`].
108#[derive(Debug, Clone, Default)]
109pub struct ImportSigningKeysOptions {
110    pub password: Option<String>,
111    pub conflict_strategy: ImportConflictStrategy,
112    pub max_keys: Option<usize>,
113}
114
115/// Result of [`PrivateStateProvider::import_signing_keys`].
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
117pub struct ImportSigningKeysResult {
118    pub imported: usize,
119    pub skipped: usize,
120    pub overwritten: usize,
121}
122
123/// Rust port of TS `PrivateStateProvider<PSI, PS>`.
124///
125/// The TS interface is generic in `PSI` (id type) and `PS` (state
126/// type); the Rust port fixes `PSI = PrivateStateId` and `PS = Vec<u8>`
127/// (opaque payload) because:
128///
129/// - The id type is always `string` in practice (TS generic only
130///   exists to allow literal-type narrowing).
131/// - The payload type is user-chosen but the provider stores it
132///   opaquely; callers that want structured access wrap this trait
133///   with a typed adapter at their boundary.
134#[async_trait]
135pub trait PrivateStateProvider: Send + Sync + std::fmt::Debug {
136    // --- Scoping -----------------------------------------------------
137
138    /// Set the contract address that subsequent operations are scoped
139    /// to. Port of TS `setContractAddress(address)`. Providers that
140    /// don't care about scoping can implement this as a no-op.
141    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()>;
142
143    // --- Private-state blob CRUD ------------------------------------
144
145    /// Store `state` at `private_state_id`.
146    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()>;
147
148    /// Retrieve the blob at `private_state_id`. Returns `Ok(None)` if
149    /// nothing is stored (TS convention returns `null`).
150    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>>;
151
152    /// Remove the blob at `private_state_id`. No-op if none was
153    /// stored.
154    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()>;
155
156    /// Remove every stored private-state blob.
157    async fn clear(&self) -> Result<()>;
158
159    // --- Signing-key CRUD -------------------------------------------
160
161    /// Store `signing_key` under `address`.
162    async fn set_signing_key(
163        &self,
164        address: &ContractAddress,
165        signing_key: SigningKey,
166    ) -> Result<()>;
167
168    /// Retrieve the signing key for `address`, if stored.
169    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>>;
170
171    /// Remove the signing key for `address`. No-op if none was stored.
172    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()>;
173
174    /// Remove every stored signing key.
175    async fn clear_signing_keys(&self) -> Result<()>;
176
177    // --- Export / import --------------------------------------------
178
179    /// Export all stored private-state blobs as an encrypted bundle.
180    /// Signing keys are NOT included — see
181    /// [`Self::export_signing_keys`].
182    async fn export_private_states(
183        &self,
184        options: &ExportPrivateStatesOptions,
185    ) -> Result<PrivateStateExport>;
186
187    /// Import a previously-exported bundle.
188    async fn import_private_states(
189        &self,
190        export: &PrivateStateExport,
191        options: &ImportPrivateStatesOptions,
192    ) -> Result<ImportPrivateStatesResult>;
193
194    /// Export all stored signing keys as an encrypted bundle.
195    async fn export_signing_keys(
196        &self,
197        options: &ExportSigningKeysOptions,
198    ) -> Result<SigningKeyExport>;
199
200    /// Import a previously-exported signing-key bundle.
201    async fn import_signing_keys(
202        &self,
203        export: &SigningKeyExport,
204        options: &ImportSigningKeysOptions,
205    ) -> Result<ImportSigningKeysResult>;
206}
207
208#[async_trait]
209impl<T: PrivateStateProvider + ?Sized> PrivateStateProvider for std::sync::Arc<T> {
210    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()> {
211        (**self).set_contract_address(address).await
212    }
213    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
214        (**self).set(private_state_id, state).await
215    }
216    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
217        (**self).get(private_state_id).await
218    }
219    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()> {
220        (**self).remove(private_state_id).await
221    }
222    async fn clear(&self) -> Result<()> {
223        (**self).clear().await
224    }
225    async fn set_signing_key(
226        &self,
227        address: &ContractAddress,
228        signing_key: SigningKey,
229    ) -> Result<()> {
230        (**self).set_signing_key(address, signing_key).await
231    }
232    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>> {
233        (**self).get_signing_key(address).await
234    }
235    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()> {
236        (**self).remove_signing_key(address).await
237    }
238    async fn clear_signing_keys(&self) -> Result<()> {
239        (**self).clear_signing_keys().await
240    }
241    async fn export_private_states(
242        &self,
243        options: &ExportPrivateStatesOptions,
244    ) -> Result<PrivateStateExport> {
245        (**self).export_private_states(options).await
246    }
247    async fn import_private_states(
248        &self,
249        export: &PrivateStateExport,
250        options: &ImportPrivateStatesOptions,
251    ) -> Result<ImportPrivateStatesResult> {
252        (**self).import_private_states(export, options).await
253    }
254    async fn export_signing_keys(
255        &self,
256        options: &ExportSigningKeysOptions,
257    ) -> Result<SigningKeyExport> {
258        (**self).export_signing_keys(options).await
259    }
260    async fn import_signing_keys(
261        &self,
262        export: &SigningKeyExport,
263        options: &ImportSigningKeysOptions,
264    ) -> Result<ImportSigningKeysResult> {
265        (**self).import_signing_keys(export, options).await
266    }
267}
268
269#[async_trait]
270impl<T: PrivateStateProvider + ?Sized> PrivateStateProvider for Box<T> {
271    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()> {
272        (**self).set_contract_address(address).await
273    }
274    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
275        (**self).set(private_state_id, state).await
276    }
277    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
278        (**self).get(private_state_id).await
279    }
280    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()> {
281        (**self).remove(private_state_id).await
282    }
283    async fn clear(&self) -> Result<()> {
284        (**self).clear().await
285    }
286    async fn set_signing_key(
287        &self,
288        address: &ContractAddress,
289        signing_key: SigningKey,
290    ) -> Result<()> {
291        (**self).set_signing_key(address, signing_key).await
292    }
293    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>> {
294        (**self).get_signing_key(address).await
295    }
296    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()> {
297        (**self).remove_signing_key(address).await
298    }
299    async fn clear_signing_keys(&self) -> Result<()> {
300        (**self).clear_signing_keys().await
301    }
302    async fn export_private_states(
303        &self,
304        options: &ExportPrivateStatesOptions,
305    ) -> Result<PrivateStateExport> {
306        (**self).export_private_states(options).await
307    }
308    async fn import_private_states(
309        &self,
310        export: &PrivateStateExport,
311        options: &ImportPrivateStatesOptions,
312    ) -> Result<ImportPrivateStatesResult> {
313        (**self).import_private_states(export, options).await
314    }
315    async fn export_signing_keys(
316        &self,
317        options: &ExportSigningKeysOptions,
318    ) -> Result<SigningKeyExport> {
319        (**self).export_signing_keys(options).await
320    }
321    async fn import_signing_keys(
322        &self,
323        export: &SigningKeyExport,
324        options: &ImportSigningKeysOptions,
325    ) -> Result<ImportSigningKeysResult> {
326        (**self).import_signing_keys(export, options).await
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn import_conflict_strategy_default_is_error() {
336        assert_eq!(
337            ImportConflictStrategy::default(),
338            ImportConflictStrategy::Error
339        );
340    }
341
342    #[test]
343    fn max_export_constants_match_ts() {
344        assert_eq!(MAX_EXPORT_STATES, 10_000);
345        assert_eq!(MAX_EXPORT_SIGNING_KEYS, 10_000);
346    }
347
348    #[test]
349    fn import_result_default_is_zero_imports() {
350        let r = ImportPrivateStatesResult::default();
351        assert_eq!(r.imported, 0);
352        assert_eq!(r.skipped, 0);
353        assert_eq!(r.overwritten, 0);
354    }
355
356    #[test]
357    fn export_options_default_is_none_password_and_max() {
358        let o = ExportPrivateStatesOptions::default();
359        assert!(o.password.is_none());
360        assert!(o.max_states.is_none());
361    }
362}