Skip to main content

lexe/unstable/
wallet_db.rs

1//! Lexe wallet database.
2
3use std::io;
4
5use anyhow::Context;
6use lexe_common::api::auth::BearerAuthToken;
7use lexe_node_client::client::{GatewayClient, NodeClient};
8use tracing::{debug, warn};
9
10use super::{
11    ffs::{DiskFs, Ffs, fsext},
12    payments_db::{self, PaymentsDb},
13};
14use crate::{config::WalletUserDbConfig, types::command::PaymentSyncSummary};
15
16/// Persistent wallet database which can be used with [`LexeWallet`].
17///
18/// [`LexeWallet`]: crate::wallet::LexeWallet
19pub struct WalletDb<F> {
20    #[allow(dead_code)] // TODO(max): Remove once stable
21    user_db_config: WalletUserDbConfig,
22
23    payments_db: PaymentsDb<F>,
24    payment_sync_lock: tokio::sync::Mutex<()>,
25
26    /// `check_address` synced block heights, one file per address.
27    check_address_ffs: F,
28}
29
30// TODO(max): Rework Ffs so this impl can be generic across all Ffs impls.
31// The user should just be able to give us a Ffs impl set to some base path
32// which is the lexe_data_dir. From there we should be able to create sub-Ffs's
33// for the wallet env, user, payments db, etc. Probably instead of one level of
34// directory it should be prefix-based. As the Ffs is currently designed, end
35// users have to manually create all the subdivisions, all the way down to e.g.
36// `payments_db`, which is tedious and error-prone. Also, it might need to be
37// renamed, since it won't be flat anymore.
38impl WalletDb<DiskFs> {
39    /// Create a fresh [`WalletDb`], deleting any existing data for this user.
40    pub fn fresh(user_db_config: WalletUserDbConfig) -> anyhow::Result<Self> {
41        let payments_ffs =
42            DiskFs::create_clean_dir_all(user_db_config.payments_db_dir())
43                .context("Could not create payments ffs")?;
44        let check_address_ffs =
45            DiskFs::create_clean_dir_all(user_db_config.check_address_db_dir())
46                .context("Could not create check_address ffs")?;
47
48        // Delete the old payments_db dir just in case it exists.
49        for old_dir in user_db_config.old_payment_db_dirs() {
50            match fsext::remove_dir_all_idempotent(&old_dir) {
51                Ok(true) => debug!("Deleted old payments_db dir: {old_dir:?}"),
52                Ok(false) => (),
53                Err(e) => warn!(?old_dir, "Couldn't delete old dir: {e:#}"),
54            }
55        }
56
57        Ok(Self {
58            user_db_config,
59            payments_db: PaymentsDb::empty(payments_ffs),
60            payment_sync_lock: tokio::sync::Mutex::new(()),
61            check_address_ffs,
62        })
63    }
64
65    /// Load an existing [`WalletDb`]. Returns [`None`] if no local data exists.
66    pub fn load(
67        user_db_config: WalletUserDbConfig,
68    ) -> anyhow::Result<Option<Self>> {
69        if !user_db_config.user_db_dir().exists() {
70            return Ok(None);
71        }
72
73        let payments_ffs =
74            DiskFs::create_dir_all(user_db_config.payments_db_dir())
75                .context("Could not create payments ffs")?;
76        let check_address_ffs =
77            DiskFs::create_dir_all(user_db_config.check_address_db_dir())
78                .context("Could not create check_address ffs")?;
79
80        let payments_db = PaymentsDb::read(payments_ffs)
81            .context("Failed to load payments db")?;
82
83        // If the payments_db contains 0 payments, the user may have just
84        // upgraded to the latest format. Delete the old dirs just in case.
85        let num_payments = payments_db.num_payments();
86        if num_payments == 0 {
87            for old_dir in user_db_config.old_payment_db_dirs() {
88                match fsext::remove_dir_all_idempotent(&old_dir) {
89                    Ok(true) =>
90                        debug!("Deleted old payments_db dir: {old_dir:?}"),
91                    Ok(false) => (),
92                    Err(e) => warn!(?old_dir, "Couldn't delete old dir: {e:#}"),
93                }
94            }
95        }
96
97        // Try to delete old provision_db since provision history is now on the
98        // backend.
99        let old_provision_db_dir = user_db_config.old_provision_db_dir();
100        match fsext::remove_dir_all_idempotent(&old_provision_db_dir) {
101            Ok(true) =>
102                debug!("Deleted old provision_db dir: {old_provision_db_dir:?}"),
103            Ok(false) => (),
104            Err(e) =>
105                warn!(?old_provision_db_dir, "Couldn't delete old dir: {e:#}"),
106        }
107
108        let num_pending = payments_db.num_pending();
109        let latest_updated_index = payments_db.latest_updated_index();
110        let last_synced_at = payments_db.last_synced_at();
111        debug!(
112            %num_payments, %num_pending, ?latest_updated_index, ?last_synced_at,
113            "Loaded WalletDb."
114        );
115
116        Ok(Some(Self {
117            user_db_config,
118            payments_db,
119            payment_sync_lock: tokio::sync::Mutex::new(()),
120            check_address_ffs,
121        }))
122    }
123
124    /// Load an existing [`WalletDb`], or create a fresh one if none exists.
125    pub fn load_or_fresh(
126        user_db_config: WalletUserDbConfig,
127    ) -> anyhow::Result<Self> {
128        let maybe_db = Self::load(user_db_config.clone())
129            .context("Failed to load wallet db")?;
130
131        let db = match maybe_db {
132            Some(d) => d,
133            None => Self::fresh(user_db_config)
134                .context("Failed to create fresh wallet db")?,
135        };
136
137        Ok(db)
138    }
139
140    /// Get the user database configuration.
141    #[allow(dead_code)] // TODO(max): Remove once stable
142    pub fn user_db_config(&self) -> &WalletUserDbConfig {
143        &self.user_db_config
144    }
145
146    /// Get a reference to the payments database.
147    pub fn payments_db(&self) -> &PaymentsDb<DiskFs> {
148        &self.payments_db
149    }
150
151    /// The `synced_block_height` from `address`'s last `check_address`, or
152    /// `None` if none is recorded.
153    pub(crate) fn address_synced_block_height(
154        &self,
155        address: &str,
156    ) -> Option<u32> {
157        let buf = match self.check_address_ffs.read(address) {
158            Ok(buf) => buf,
159            Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
160            Err(e) => {
161                warn!(
162                    %address,
163                    "Failed to read synced block height; \
164                     checking from scratch: {e:#}"
165                );
166                return None;
167            }
168        };
169        let maybe_height = String::from_utf8(buf)
170            .ok()
171            .and_then(|height| height.parse::<u32>().ok());
172        if maybe_height.is_none() {
173            warn!(
174                %address,
175                "Corrupt synced block height; checking from scratch"
176            );
177        }
178        maybe_height
179    }
180
181    /// Persist `address`'s `synced_block_height`.
182    pub(crate) fn set_address_synced_block_height(
183        &self,
184        address: &str,
185        synced_block_height: u32,
186    ) -> anyhow::Result<()> {
187        // A racing write can only leave an older, lower height, which costs
188        // at most a redundant check, so no lock is needed.
189        self.check_address_ffs
190            .write(address, synced_block_height.to_string().as_bytes())
191            .context("Failed to write synced block height")
192    }
193
194    /// Sync payments from the node to the local payments database.
195    ///
196    /// Only wakes the node if there are actually updates to fetch.
197    ///
198    /// If another sync is already in progress, waits for it to complete
199    /// before starting a new one.
200    pub async fn sync_payments(
201        &self,
202        gateway_client: &GatewayClient,
203        node_client: &NodeClient,
204        auth: BearerAuthToken,
205        batch_size: u16,
206    ) -> anyhow::Result<PaymentSyncSummary> {
207        let _lock = self.payment_sync_lock.lock().await;
208        payments_db::sync_payments(
209            &self.payments_db,
210            gateway_client,
211            node_client,
212            auth,
213            batch_size,
214        )
215        .await
216    }
217
218    /// Like [`sync_payments`](Self::sync_payments), but syncs from the node
219    /// without first asking the gateway whether there are updates.
220    pub async fn force_sync_payments(
221        &self,
222        node_client: &NodeClient,
223        batch_size: u16,
224    ) -> anyhow::Result<PaymentSyncSummary> {
225        let _lock = self.payment_sync_lock.lock().await;
226        payments_db::force_sync_payments(
227            &self.payments_db,
228            node_client,
229            batch_size,
230        )
231        .await
232    }
233}
234
235#[cfg(test)]
236mod test {
237    use lexe_common::{ByteArray, env::DeployEnv, ln::network::Network};
238
239    use super::*;
240    use crate::{
241        config::{WalletEnv, WalletEnvDbConfig},
242        types::auth::UserPk,
243    };
244
245    fn user_db_config(lexe_data_dir: &std::path::Path) -> WalletUserDbConfig {
246        let wallet_env = WalletEnv {
247            deploy_env: DeployEnv::Dev,
248            network: Network::Regtest,
249            use_sgx: false,
250        };
251        let env_db_config =
252            WalletEnvDbConfig::new(wallet_env, lexe_data_dir.to_owned());
253        WalletUserDbConfig::new(env_db_config, UserPk::from_array([42; 32]))
254    }
255
256    /// Each address's synced block height round-trips through its own file.
257    #[test]
258    fn address_synced_block_height_roundtrip() {
259        let tempdir = tempfile::tempdir().unwrap();
260        let config = user_db_config(tempdir.path());
261        let address1 = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
262        let address2 =
263            "bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3";
264
265        let db = WalletDb::fresh(config.clone()).unwrap();
266        assert_eq!(db.address_synced_block_height(address1), None);
267        db.set_address_synced_block_height(address1, 800_000)
268            .unwrap();
269        assert_eq!(db.address_synced_block_height(address1), Some(800_000));
270        assert_eq!(db.address_synced_block_height(address2), None);
271
272        let db = WalletDb::load(config).unwrap().unwrap();
273        assert_eq!(db.address_synced_block_height(address1), Some(800_000));
274        assert_eq!(db.address_synced_block_height(address2), None);
275    }
276
277    /// A corrupt height file reads as no height.
278    #[test]
279    fn address_synced_block_height_corrupt_file() {
280        let tempdir = tempfile::tempdir().unwrap();
281        let config = user_db_config(tempdir.path());
282        let address = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
283
284        let db = WalletDb::fresh(config).unwrap();
285        db.check_address_ffs
286            .write(address, b"not a height")
287            .unwrap();
288        assert_eq!(db.address_synced_block_height(address), None);
289    }
290}