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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Persistent [`moonproof_wallet::WalletSnapshot`] storage on redb.
//!
//! Sits on top of the same redb file as [`super::DiskPrivateStateProvider`]
//! and [`super::DiskTransactionHistoryStorage`] — single artefact that
//! holds contract private state, signing keys, transaction history, and
//! the wallet snapshot itself. Backup / restore is one file copy.
//!
//! # Layout
//!
//! Adds one static table — `moonproof:wallet_snapshots` — keyed
//! `account_hash(16) || b"snapshot"`. Each wallet account stores at
//! most one snapshot row; saving overwrites. The snapshot bytes are
//! encrypted with the same per-account AES-256-GCM envelope used by
//! the sibling stores, so the cipher is derived once per process.
//!
//! # Why not put the snapshot in `private_states`?
//!
//! Two reasons:
//!
//! 1. The `PrivateStateProvider` API is scoped per `ContractAddress`.
//!    Wallet snapshots aren't contract-scoped, and forcing a sentinel
//!    address would silently mix wallet rows with contract rows in
//!    every iteration / clear path.
//! 2. Some wallet GUIs want to render snapshot metadata
//!    (network id, last sync time) without decrypting every contract
//!    private state — keeping the snapshot in its own table lets
//!    callers iterate without touching the contract rows.

use std::path::PathBuf;
use std::sync::Arc;

use moonproof_wallet::WalletError;
use moonproof_wallet::WalletSnapshot;
use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
use tokio::sync::RwLock;

use crate::providers::disk_private_state::{open_or_share_database, PrivateStoragePassword};
use crate::providers::storage_encryption::{parse_envelope, Cipher, Salt};

pub(crate) const TABLE: TableDefinition<&[u8], &[u8]> =
    TableDefinition::new("moonproof:wallet_snapshots");
const KEY_TAG_SNAPSHOT: &[u8] = b"snapshot";

/// Configuration for [`WalletStore::open`].
pub struct WalletStoreConfig {
    pub db_path: PathBuf,
    pub account_id: String,
    pub password: Arc<dyn PrivateStoragePassword>,
}

impl std::fmt::Debug for WalletStoreConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WalletStoreConfig")
            .field("db_path", &self.db_path)
            .field("account_id", &self.account_id)
            .finish_non_exhaustive()
    }
}

/// Redb-backed wallet-snapshot store.
#[derive(Clone)]
pub struct WalletStore {
    inner: Arc<Inner>,
}

struct Inner {
    db: Arc<Database>,
    account_hash: [u8; 16],
    password: Arc<dyn PrivateStoragePassword>,
    cipher_cache: RwLock<Option<CachedCipher>>,
}

#[derive(Clone)]
struct CachedCipher {
    cipher: Cipher,
    salt: Salt,
}

impl std::fmt::Debug for WalletStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WalletStore")
            .field("account_hash", &hex::encode(self.inner.account_hash))
            .finish_non_exhaustive()
    }
}

impl WalletStore {
    /// Open the wallet store. Initialises the snapshot table on first
    /// run. Idempotent on subsequent calls — shares the redb handle
    /// with sibling providers via the process-wide registry.
    pub fn open(config: WalletStoreConfig) -> Result<Self, WalletError> {
        if let Some(parent) = config.db_path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| WalletError::Serialization(format!("create_dir_all: {e}")))?;
            }
        }
        let db = open_or_share_database(&config.db_path)
            .map_err(|e| WalletError::Serialization(format!("open db: {e}")))?;
        let write = db
            .begin_write()
            .map_err(|e| WalletError::Serialization(format!("begin_write init: {e}")))?;
        {
            let _ = write
                .open_table(TABLE)
                .map_err(|e| WalletError::Serialization(format!("open table init: {e}")))?;
        }
        write
            .commit()
            .map_err(|e| WalletError::Serialization(format!("commit init: {e}")))?;
        let account_hash = hash_account_id(&config.account_id);
        Ok(Self {
            inner: Arc::new(Inner {
                db,
                account_hash,
                password: config.password,
                cipher_cache: RwLock::new(None),
            }),
        })
    }

    /// Persist `snapshot` for the configured account. Overwrites any
    /// existing snapshot. Returns the number of bytes written
    /// (post-encryption envelope size) for diagnostics.
    pub async fn save(&self, snapshot: &WalletSnapshot) -> Result<usize, WalletError> {
        let inner = self.inner.clone();
        let bytes = snapshot.to_bytes_compact()?;
        run_blocking(move || {
            let cached = inner.cipher_for_read_write()?;
            let envelope = encrypt_value(&cached.cipher, &bytes);
            let envelope_len = envelope.len();
            let key = key_for(&inner.account_hash);
            let write = inner
                .db
                .begin_write()
                .map_err(|e| WalletError::Serialization(format!("begin_write save: {e}")))?;
            {
                let mut table = write
                    .open_table(TABLE)
                    .map_err(|e| WalletError::Serialization(format!("open table save: {e}")))?;
                table
                    .insert(key.as_slice(), envelope.as_bytes())
                    .map_err(|e| WalletError::Serialization(format!("insert save: {e}")))?;
            }
            write
                .commit()
                .map_err(|e| WalletError::Serialization(format!("commit save: {e}")))?;
            Ok(envelope_len)
        })
        .await
    }

    /// Load the persisted snapshot, if any. Returns `Ok(None)` when
    /// no snapshot has been saved yet.
    pub async fn load(&self) -> Result<Option<WalletSnapshot>, WalletError> {
        let inner = self.inner.clone();
        run_blocking(move || {
            let cached = inner.cipher_for_read_write()?;
            let key = key_for(&inner.account_hash);
            let read = inner
                .db
                .begin_read()
                .map_err(|e| WalletError::Serialization(format!("begin_read load: {e}")))?;
            let table = read
                .open_table(TABLE)
                .map_err(|e| WalletError::Serialization(format!("open table load: {e}")))?;
            let Some(value) = table
                .get(key.as_slice())
                .map_err(|e| WalletError::Serialization(format!("lookup load: {e}")))?
            else {
                return Ok(None);
            };
            let envelope = std::str::from_utf8(value.value())
                .map_err(|_| WalletError::Serialization("non-utf8 envelope".to_owned()))?;
            let plain = decrypt(&cached, envelope)?;
            let snapshot = WalletSnapshot::from_bytes(&plain)?;
            Ok(Some(snapshot))
        })
        .await
    }

    /// Drop the persisted snapshot, if any. No-op if nothing is saved.
    pub async fn clear(&self) -> Result<(), WalletError> {
        let inner = self.inner.clone();
        run_blocking(move || {
            let key = key_for(&inner.account_hash);
            let write = inner
                .db
                .begin_write()
                .map_err(|e| WalletError::Serialization(format!("begin_write clear: {e}")))?;
            {
                let mut table = write
                    .open_table(TABLE)
                    .map_err(|e| WalletError::Serialization(format!("open table clear: {e}")))?;
                table
                    .remove(key.as_slice())
                    .map_err(|e| WalletError::Serialization(format!("remove clear: {e}")))?;
            }
            write
                .commit()
                .map_err(|e| WalletError::Serialization(format!("commit clear: {e}")))?;
            Ok(())
        })
        .await
    }
}

impl Inner {
    fn cipher_for_read_write(&self) -> Result<CachedCipher, WalletError> {
        let current = |c: &CachedCipher| {
            crate::providers::disk_private_state::salt_is_current(
                &self.db,
                &self.account_hash,
                &c.salt,
            )
            .map_err(|e| WalletError::Serialization(format!("account salt: {e}")))
        };
        if let Some(c) = self.cipher_cache.blocking_read().as_ref() {
            if current(c)? {
                return Ok(c.clone());
            }
        }
        let mut cache = self.cipher_cache.blocking_write();
        if let Some(c) = cache.as_ref() {
            if current(c)? {
                return Ok(c.clone());
            }
        }
        let pw = self
            .password
            .password()
            .map_err(|e| WalletError::Serialization(format!("password provider: {e}")))?;
        let (cipher, salt) =
            crate::providers::disk_private_state::account_cipher(&self.db, &self.account_hash, &pw)
                .map_err(|e| WalletError::Serialization(format!("account cipher: {e}")))?;
        let copy = CachedCipher {
            cipher: cipher.clone(),
            salt,
        };
        *cache = Some(CachedCipher { cipher, salt });
        Ok(copy)
    }
}

// Helpers ---------------------------------------------------------------

async fn run_blocking<T, F>(f: F) -> Result<T, WalletError>
where
    T: Send + 'static,
    F: FnOnce() -> Result<T, WalletError> + Send + 'static,
{
    tokio::task::spawn_blocking(f)
        .await
        .map_err(|e| WalletError::Serialization(format!("blocking task panic: {e}")))?
}

fn hash_account_id(s: &str) -> [u8; 16] {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(s.as_bytes());
    let mut out = [0u8; 16];
    out.copy_from_slice(&digest[..16]);
    out
}

fn key_for(account_hash: &[u8; 16]) -> Vec<u8> {
    let mut k = Vec::with_capacity(16 + KEY_TAG_SNAPSHOT.len());
    k.extend_from_slice(account_hash);
    k.extend_from_slice(KEY_TAG_SNAPSHOT);
    k
}

fn encrypt_value(cipher: &Cipher, plain_bytes: &[u8]) -> String {
    let mut rng = rand::thread_rng();
    let hex_payload = hex::encode(plain_bytes);
    cipher.encrypt(&mut rng, &hex_payload)
}

fn decrypt(cached: &CachedCipher, envelope: &str) -> Result<Vec<u8>, WalletError> {
    let parts = parse_envelope(envelope)
        .map_err(|e| WalletError::Serialization(format!("envelope: {e}")))?;
    let cipher = if parts.salt == cached.salt {
        cached.cipher.clone()
    } else {
        return Err(WalletError::Serialization(
            "envelope salt diverges from cached cipher (DB rotation in progress?)".to_owned(),
        ));
    };
    let plain_hex = cipher
        .decrypt(envelope)
        .map_err(|e| WalletError::Serialization(format!("decrypt: {e}")))?;
    hex::decode(&plain_hex).map_err(|_| WalletError::Serialization("non-hex plaintext".to_owned()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::disk_private_state::StaticPassword;
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
    use moonproof_wallet::abstractions::NetworkId;
    use moonproof_wallet::dust::DustState;
    use moonproof_wallet::facade::FacadeState;
    use moonproof_wallet::shielded::ShieldedState;
    use moonproof_wallet::unshielded::UnshieldedState;
    use moonproof_wallet::WalletSnapshot;
    use tempfile::TempDir;

    fn dust_params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 1_000,
            generation_decay_rate: 1,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn empty_facade() -> FacadeState {
        let zswap = ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32]));
        let dust = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        FacadeState::new(
            ShieldedState::init_empty(&zswap, NetworkId::Undeployed),
            UnshieldedState::empty(),
            DustState::init_empty(dust_params(), &dust, NetworkId::Undeployed),
            NetworkId::Undeployed,
        )
    }

    fn config(dir: &TempDir, account: &str) -> WalletStoreConfig {
        WalletStoreConfig {
            db_path: dir.path().join("wallet.redb"),
            account_id: account.to_owned(),
            password: Arc::new(StaticPassword::new("TheQuickBrownFox-12345!")),
        }
    }

    #[tokio::test]
    async fn save_then_load_round_trips_an_empty_facade() {
        let dir = TempDir::new().unwrap();
        let store = WalletStore::open(config(&dir, "alice")).unwrap();
        let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        let written = store.save(&snap).await.unwrap();
        assert!(written > 0);
        let loaded = store.load().await.unwrap().expect("snapshot present");
        assert_eq!(loaded.network_id, snap.network_id);
        assert_eq!(loaded.format_version, snap.format_version);
    }

    #[tokio::test]
    async fn load_returns_none_when_nothing_saved() {
        let dir = TempDir::new().unwrap();
        let store = WalletStore::open(config(&dir, "alice")).unwrap();
        assert!(store.load().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn save_overwrites_existing_snapshot() {
        let dir = TempDir::new().unwrap();
        let store = WalletStore::open(config(&dir, "alice")).unwrap();
        let snap1 = WalletSnapshot::capture(&empty_facade()).unwrap();
        store.save(&snap1).await.unwrap();
        // Take a fresh snapshot — same shape but exercise the
        // overwrite path.
        let snap2 = WalletSnapshot::capture(&empty_facade()).unwrap();
        store.save(&snap2).await.unwrap();
        assert!(store.load().await.unwrap().is_some());
    }

    #[tokio::test]
    async fn account_namespace_keeps_snapshots_isolated() {
        let dir = TempDir::new().unwrap();
        let alice = WalletStore::open(config(&dir, "alice")).unwrap();
        let bob = WalletStore::open(config(&dir, "bob")).unwrap();
        let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        alice.save(&snap).await.unwrap();
        assert!(alice.load().await.unwrap().is_some());
        assert!(bob.load().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn clear_drops_persisted_snapshot() {
        let dir = TempDir::new().unwrap();
        let store = WalletStore::open(config(&dir, "alice")).unwrap();
        let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        store.save(&snap).await.unwrap();
        store.clear().await.unwrap();
        assert!(store.load().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn data_persists_across_reopen() {
        let dir = TempDir::new().unwrap();
        let cfg = config(&dir, "alice");
        let path = cfg.db_path.clone();
        let pw = cfg.password.clone();
        let s1 = WalletStore::open(cfg).unwrap();
        let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        s1.save(&snap).await.unwrap();
        drop(s1);
        let s2 = WalletStore::open(WalletStoreConfig {
            db_path: path,
            account_id: "alice".to_owned(),
            password: pw,
        })
        .unwrap();
        assert!(s2.load().await.unwrap().is_some());
    }
}