Skip to main content

beekeeper/
storage.rs

1//! Filesystem-backed wallet storage used by the C++ wallet manager.
2//!
3//! The wallet manager calls into this struct over the `cxx` bridge
4//! whenever it needs to load, persist, probe, sync, or close a wallet file.
5//!
6//! There is no extension point for other backends — the storage is always
7//! this filesystem implementation, and in-memory mode is handled by
8//! selecting a different *C++* storage backend
9//! ([`ffi::new_beekeeper_holder_in_memory`](crate::ffi::new_beekeeper_holder_in_memory))
10//! rather than by swapping this struct.
11
12use std::{
13    fs,
14    path::{Path, PathBuf},
15};
16
17use crate::{
18    consts::{LEGACY_WALLET_DIR, LEGACY_WALLET_EXT},
19    errors::{BeekeeperError, Res},
20};
21
22/// Filesystem storage backend handed to C++ as a `Box<RustStorageProtocol>`.
23///
24/// Construct via [`new_rust_storage_protocol`].
25pub struct RustStorageProtocol {
26    wallet_dir: PathBuf,
27}
28
29/// Build a [`RustStorageProtocol`] rooted at `storage_root`.
30///
31/// Creates `<storage_root>/.beekeeper/` if missing (errors are swallowed —
32/// the directory may already exist and `cpp_save` will surface any real
33/// problem later). Free function (rather than `RustStorageProtocol::new`)
34/// because the signature must match what the `cxx` bridge expects.
35pub fn new_rust_storage_protocol(
36    storage_root: &str,
37) -> Box<RustStorageProtocol> {
38    let wallet_dir = Path::new(storage_root).join(LEGACY_WALLET_DIR);
39    fs::create_dir_all(&wallet_dir).ok();
40
41    Box::new(RustStorageProtocol { wallet_dir })
42}
43
44impl RustStorageProtocol {
45    pub(crate) fn cpp_load(&mut self, name: &str) -> Res<Vec<u8>> {
46        let path = self.wallet_path(name);
47        fs::read(path)
48            .map_err(|_| BeekeeperError::WalletNotFound { name: name.into() })
49    }
50
51    pub(crate) fn cpp_save(&mut self, name: &str, data: &[u8]) -> Res<()> {
52        let path = self.wallet_path(name);
53        fs::write(path, data).map_err(|_| BeekeeperError::WalletWriteFailed {
54            name: name.into(),
55        })
56    }
57
58    pub(crate) fn cpp_scan_dir(&mut self, name: &str) -> bool {
59        self.wallet_path(name).is_file()
60    }
61
62    pub(crate) fn cpp_sync(&mut self) {}
63
64    pub(crate) fn cpp_close(&mut self) {}
65
66    fn wallet_path(&self, name: &str) -> PathBuf {
67        self.wallet_dir.join(format!("{name}{LEGACY_WALLET_EXT}"))
68    }
69}