webylib 0.3.20

Webcash HD wallet library — bearer e-cash with BIP32-style key derivation, SQLite storage, AES-256-GCM encryption, and full C FFI for cross-platform SDKs
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Wallet engine — pluggable-storage HD wallet for Webcash.
//!
//! # Architecture
//!
//! - **`store`** — Storage trait: `SqliteStore` (native) or `MemStore` (WASM).
//! - **`operations`** — Insert, pay, merge, recover, check, balance.
//! - **`encryption`** — Database-level and seed-level encryption.
//! - **`snapshot`** — JSON export/import for backup and recovery.
//! - **`schema`** — SQLite schema init (native only).

#[cfg(not(target_arch = "wasm32"))]
pub mod encryption;
#[cfg(target_arch = "wasm32")]
pub mod idb;
pub mod operations;
#[cfg(not(target_arch = "wasm32"))]
pub mod schema;
pub mod snapshot;
pub mod store;

use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
#[cfg(not(target_arch = "wasm32"))]
use crate::server::ServerClientTrait;
use crate::server::{NetworkMode, ServerClient, ServerConfig};

#[cfg(not(target_arch = "wasm32"))]
use crate::passkey::{EncryptionConfig, PasskeyEncryption};
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Mutex;

pub use operations::{CheckResult, RecoveryResult, WalletStats};
pub use snapshot::{SpentHashSnapshot, UnspentOutputSnapshot, WalletSnapshot};
pub use store::Store;

/// Webcash wallet with pluggable storage backend.
pub struct Wallet {
    pub(crate) path: PathBuf,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) store: Box<dyn Store + Send + Sync>,
    #[cfg(target_arch = "wasm32")]
    pub(crate) store: Box<dyn Store>,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) server_client: tokio::sync::Mutex<Box<dyn ServerClientTrait + Send>>,
    #[cfg(target_arch = "wasm32")]
    pub(crate) server_client: ServerClient,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) passkey_encryption: Option<Mutex<PasskeyEncryption>>,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) is_encrypted: bool,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) temp_db_path: Option<PathBuf>,
    pub(crate) network: NetworkMode,
}

// ── Native constructors ──────────────────────────────────────────

#[cfg(not(target_arch = "wasm32"))]
impl Wallet {
    pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::open_with_passkey(path, false).await
    }

    pub async fn open_with_passkey<P: AsRef<Path>>(path: P, enable_passkey: bool) -> Result<Self> {
        use rusqlite::Connection;

        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let (connection, is_encrypted, temp_db_path) =
            if enable_passkey && Self::is_database_encrypted(&path)? {
                let temp_path = Self::decrypt_database_for_runtime(&path).await?;
                let connection = Connection::open(&temp_path)?;
                (connection, true, Some(temp_path))
            } else if enable_passkey {
                let connection = Connection::open(&path)?;
                (connection, true, None)
            } else {
                let connection = Connection::open(&path)?;
                (connection, false, None)
            };

        schema::initialize_schema(&connection)?;

        let passkey_encryption = if enable_passkey {
            let config = EncryptionConfig {
                app_identifier: "com.webycash.webylib".to_string(),
                service_name: format!(
                    "WalletEncryption_{}",
                    path.file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("default")
                ),
                require_auth_every_use: true,
                auth_timeout_seconds: 0,
                allow_device_passcode_fallback: true,
            };
            PasskeyEncryption::new(config).ok().map(Mutex::new)
        } else {
            None
        };

        let server_client: Box<dyn ServerClientTrait + Send> = Box::new(ServerClient::new()?);
        let store: Box<dyn Store + Send + Sync> =
            Box::new(store::sqlite::SqliteStore(Mutex::new(connection)));

        let wallet = Wallet {
            path,
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption,
            is_encrypted,
            temp_db_path,
            network: NetworkMode::Production,
        };
        let _ = wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    pub async fn open_with_network<P: AsRef<Path>>(path: P, network: NetworkMode) -> Result<Self> {
        use rusqlite::Connection;

        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client: Box<dyn ServerClientTrait + Send> =
            Box::new(ServerClient::with_config(config)?);

        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let connection = Connection::open(&path)?;
        schema::initialize_schema(&connection)?;

        let store: Box<dyn Store + Send + Sync> =
            Box::new(store::sqlite::SqliteStore(Mutex::new(connection)));

        let wallet = Wallet {
            path,
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption: None,
            is_encrypted: false,
            temp_db_path: None,
            network,
        };
        wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    pub async fn open_with_seed<P: AsRef<Path>>(path: P, seed: &[u8; 32]) -> Result<Self> {
        let wallet = Self::open(path).await?;
        let hex = hex::encode(seed);
        let existing = wallet.master_secret_hex()?;
        if existing != hex {
            let stats = wallet.stats().await?;
            if stats.total_webcash > 0 {
                return Err(Error::wallet(
                    "Wallet already has a different master secret with existing transactions",
                ));
            }
            wallet.store_master_secret(&hex).await?;
        }
        Ok(wallet)
    }

    pub fn open_memory() -> Result<Self> {
        Self::open_memory_with_network(NetworkMode::Production)
    }

    pub fn open_memory_with_network(network: NetworkMode) -> Result<Self> {
        use rusqlite::Connection;

        let connection = Connection::open_in_memory()?;
        schema::initialize_schema(&connection)?;

        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client: Box<dyn ServerClientTrait + Send> =
            Box::new(ServerClient::with_config(config)?);

        let store: Box<dyn Store + Send + Sync> =
            Box::new(store::sqlite::SqliteStore(Mutex::new(connection)));

        let wallet = Wallet {
            path: PathBuf::from(":memory:"),
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption: None,
            is_encrypted: false,
            temp_db_path: None,
            network,
        };
        wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    /// Open a wallet backed by a JSON file. Creates the file if it doesn't exist.
    pub fn open_json<P: AsRef<Path>>(path: P, network: NetworkMode) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let json_store = store::json::JsonStore::open(path.clone())?;
        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client: Box<dyn ServerClientTrait + Send> =
            Box::new(ServerClient::with_config(config)?);
        let store: Box<dyn Store + Send + Sync> = Box::new(json_store);

        let wallet = Wallet {
            path,
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption: None,
            is_encrypted: false,
            temp_db_path: None,
            network,
        };
        wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    /// Create an in-memory JSON wallet (no file persistence).
    /// Use `to_json()` to retrieve the state.
    pub fn open_json_memory(network: NetworkMode) -> Result<Self> {
        let json_store = store::json::JsonStore::new(None);
        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client: Box<dyn ServerClientTrait + Send> =
            Box::new(ServerClient::with_config(config)?);
        let store: Box<dyn Store + Send + Sync> = Box::new(json_store);

        let wallet = Wallet {
            path: PathBuf::from(":json-memory:"),
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption: None,
            is_encrypted: false,
            temp_db_path: None,
            network,
        };
        wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    /// Create from a JSON string (in-memory, no file persistence).
    pub fn from_json_native(json: &str, network: NetworkMode) -> Result<Self> {
        let json_store = store::json::JsonStore::from_json(json, None)?;
        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client: Box<dyn ServerClientTrait + Send> =
            Box::new(ServerClient::with_config(config)?);
        let store: Box<dyn Store + Send + Sync> = Box::new(json_store);

        Ok(Wallet {
            path: PathBuf::from(":json-memory:"),
            store,
            server_client: tokio::sync::Mutex::new(server_client),
            passkey_encryption: None,
            is_encrypted: false,
            temp_db_path: None,
            network,
        })
    }

    pub async fn close(mut self) -> Result<()> {
        if self.is_encrypted {
            // SQLite holds an open file handle on `self.path`. If we encrypt
            // the file while the connection is still alive, the connection's
            // drop can flush its journal/WAL back to the path and clobber the
            // encrypted JSON we just wrote. Swap the store with an in-memory
            // JSON store so the SQLite connection drops here, BEFORE we read
            // and rewrite the file in encrypt_database().
            let dummy: Box<dyn Store + Send + Sync> = Box::new(store::json::JsonStore::new(None));
            let old_store = std::mem::replace(&mut self.store, dummy);
            drop(old_store);
            self.encrypt_database().await?;
        }
        if let Some(passkey_mutex) = self.passkey_encryption.take() {
            let mut passkey = passkey_mutex
                .into_inner()
                .map_err(|_| Error::wallet("Failed to acquire passkey lock during close"))?;
            passkey.clear_cached_keys();
        }
        Ok(())
    }
}

// ── WASM constructors ────────────────────────────────────────────

#[cfg(target_arch = "wasm32")]
impl Wallet {
    /// Create a wallet with in-memory storage (for WASM).
    pub fn new_memory(network: NetworkMode) -> Result<Self> {
        let store: Box<dyn Store> = Box::new(store::mem::MemStore::new());
        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client = ServerClient::with_config(config)?;
        let wallet = Wallet {
            path: PathBuf::from(":memory:"),
            store,
            server_client,
            network,
        };
        wallet.get_or_generate_master_secret()?;
        Ok(wallet)
    }

    /// Create from JSON state (loaded from IndexedDB by JS).
    pub fn from_json(json: &str, network: NetworkMode) -> Result<Self> {
        let store: Box<dyn Store> = Box::new(store::mem::MemStore::from_json(json)?);
        let config = ServerConfig {
            network: network.clone(),
            timeout_seconds: 30,
        };
        let server_client = ServerClient::with_config(config)?;
        Ok(Wallet {
            path: PathBuf::from(":memory:"),
            store,
            server_client,
            network,
        })
    }
}

// ── Shared methods ───────────────────────────────────────────────

impl Wallet {
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn network(&self) -> &NetworkMode {
        &self.network
    }

    /// Serialize wallet state to JSON.
    /// Works with MemStore (WASM) and JsonStore (native).
    pub fn to_json(&self) -> Result<String> {
        #[cfg(target_arch = "wasm32")]
        {
            let mem = self
                .store
                .as_any()
                .downcast_ref::<store::mem::MemStore>()
                .ok_or_else(|| Error::wallet("Store does not support JSON serialization"))?;
            return mem.to_json();
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            if let Some(json_store) = self.store.as_any().downcast_ref::<store::json::JsonStore>() {
                return json_store.to_json();
            }
            Err(Error::wallet(
                "Store does not support JSON serialization (use JsonStore or MemStore)",
            ))
        }
    }
}

// ── IndexedDB persistence (WASM) ───────────────────────────────

#[cfg(target_arch = "wasm32")]
impl Wallet {
    /// Save current wallet state to IndexedDB.
    pub async fn save_to_idb(&self, key: &str) -> Result<()> {
        let json = self.to_json()?;
        let network_str = match &self.network {
            NetworkMode::Production => "production",
            NetworkMode::Testnet => "testnet",
            NetworkMode::Custom(u) => u.as_str(),
        };
        idb::save(network_str, key, &json).await
    }

    /// Load wallet state from IndexedDB. Returns None if not found.
    pub async fn open_from_idb(network: NetworkMode, key: &str) -> Result<Option<Self>> {
        let network_str = match &network {
            NetworkMode::Production => "production",
            NetworkMode::Testnet => "testnet",
            NetworkMode::Custom(u) => u.as_str(),
        };
        match idb::load(network_str, key).await? {
            Some(json) => Ok(Some(Self::from_json(&json, network)?)),
            None => Ok(None),
        }
    }

    /// Delete wallet state from IndexedDB.
    pub async fn delete_from_idb(network: &NetworkMode, key: &str) -> Result<()> {
        let network_str = match network {
            NetworkMode::Production => "production",
            NetworkMode::Testnet => "testnet",
            NetworkMode::Custom(u) => u.as_str(),
        };
        idb::delete(network_str, key).await
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for Wallet {
    fn drop(&mut self) {
        if self.is_encrypted {
            if let Some(temp_path) = &self.temp_db_path {
                let _ = std::fs::remove_file(temp_path);
            }
        }
    }
}