1mod convert;
12mod migrations;
13mod query;
14
15
16use std::path::{Path, PathBuf};
17
18use anyhow::Context;
19use bitcoin::Txid;
20use bitcoin::secp256k1::PublicKey;
21use chrono::DateTime;
22use lightning_invoice::Bolt11Invoice;
23use log::debug;
24use rusqlite::Connection;
25
26use ark::{Vtxo, VtxoId};
27use ark::lightning::{PaymentHash, Preimage};
28use ark::vtxo::Full;
29use bitcoin_ext::BlockDelta;
30
31use crate::WalletProperties;
32use crate::actions::{WalletActionCheckpoint, WalletActionId};
33use crate::exit::ExitTxOrigin;
34use crate::movement::{Movement, MovementId, MovementStatus, MovementSubsystem, PaymentMethod};
35use crate::persist::{BarkPersister, RoundStateId, StoredRoundState, Unlocked};
36use crate::persist::models::{
37 LightningReceive, PaidInvoice, PendingBoard, PendingOffboard, StoredExit,
38};
39use crate::round::RoundState;
40use crate::vtxo::{VtxoState, VtxoStateKind, WalletVtxo};
41
42#[derive(Clone)]
45pub struct SqliteClient {
46 connection_string: PathBuf,
47}
48
49impl SqliteClient {
50 pub fn open(db_file: impl AsRef<Path>) -> anyhow::Result<SqliteClient> {
52 let path = db_file.as_ref().to_path_buf();
53
54 debug!("Opening database at {}", path.display());
55 let mut conn = rusqlite::Connection::open(&path)
56 .with_context(|| format!("Error connecting to database {}", path.display()))?;
57
58 let migrations = migrations::MigrationContext::new();
59 migrations.do_all_migrations(&mut conn)?;
60
61 Ok( Self { connection_string: path })
62 }
63
64 fn connect(&self) -> anyhow::Result<Connection> {
65 rusqlite::Connection::open(&self.connection_string)
66 .with_context(|| format!("Error connecting to database {}", self.connection_string.display()))
67 }
68}
69
70#[async_trait]
71impl BarkPersister for SqliteClient {
72 async fn init_wallet(&self, properties: &WalletProperties) -> anyhow::Result<()> {
73 let mut conn = self.connect()?;
74 let tx = conn.transaction()?;
75
76 query::set_properties(&tx, properties)?;
77
78 tx.commit()?;
79 Ok(())
80 }
81
82 #[cfg(feature = "onchain-bdk")]
83 async fn initialize_bdk_wallet(&self) -> anyhow::Result<bdk_wallet::ChangeSet> {
84 let mut conn = self.connect()?;
85 Ok(bdk_wallet::WalletPersister::initialize(&mut conn)?)
86 }
87
88 #[cfg(feature = "onchain-bdk")]
89 async fn store_bdk_wallet_changeset(&self, changeset: &bdk_wallet::ChangeSet) -> anyhow::Result<()> {
90 let mut conn = self.connect()?;
91 bdk_wallet::WalletPersister::persist(&mut conn, changeset)?;
92 Ok(())
93 }
94
95 async fn read_properties(&self) -> anyhow::Result<Option<WalletProperties>> {
96 let conn = self.connect()?;
97 Ok(query::fetch_properties(&conn)?)
98 }
99
100 async fn set_server_pubkey(&self, server_pubkey: PublicKey) -> anyhow::Result<()> {
101 let conn = self.connect()?;
102 query::set_server_pubkey(&conn, &server_pubkey)?;
103 Ok(())
104 }
105
106 async fn set_server_mailbox_pubkey(&self, server_mailbox_pubkey: PublicKey) -> anyhow::Result<()> {
107 let conn = self.connect()?;
108 query::set_server_mailbox_pubkey(&conn, &server_mailbox_pubkey)?;
109 Ok(())
110 }
111
112 async fn create_new_movement(&self,
113 status: MovementStatus,
114 subsystem: &MovementSubsystem,
115 time: DateTime<chrono::Local>,
116 ) -> anyhow::Result<MovementId> {
117 let mut conn = self.connect()?;
118 let tx = conn.transaction()?;
119 let movement_id = query::create_new_movement(&tx, status, subsystem, time)?;
120 tx.commit()?;
121 Ok(movement_id)
122 }
123
124 async fn update_movement(&self, movement: &Movement) -> anyhow::Result<()> {
125 let mut conn = self.connect()?;
126 let tx = conn.transaction()?;
127 query::update_movement(&tx, movement)?;
128 tx.commit()?;
129 Ok(())
130 }
131
132 async fn get_movement_by_id(&self, movement_id: MovementId) -> anyhow::Result<Movement> {
133 let conn = self.connect()?;
134 query::get_movement_by_id(&conn, movement_id)
135 }
136
137 async fn get_all_movements(&self) -> anyhow::Result<Vec<Movement>> {
138 let conn = self.connect()?;
139 query::get_all_movements(&conn)
140 }
141
142 async fn get_movements_by_payment_method(
143 &self,
144 payment_method: &PaymentMethod,
145 ) -> anyhow::Result<Vec<Movement>> {
146 let conn = self.connect()?;
147 query::get_movements_by_payment_method(&conn, payment_method)
148 }
149
150 async fn store_pending_board(
151 &self,
152 vtxo: &Vtxo<Full>,
153 funding_tx: &bitcoin::Transaction,
154 movement_id: MovementId,
155 ) -> anyhow::Result<()> {
156 let mut conn = self.connect()?;
157 let tx = conn.transaction()?;
158 query::store_new_pending_board(&tx, vtxo, funding_tx, movement_id)?;
159 tx.commit()?;
160 Ok(())
161 }
162
163 async fn remove_pending_board(&self, vtxo_id: &VtxoId) -> anyhow::Result<()> {
164 let mut conn = self.connect()?;
165 let tx = conn.transaction()?;
166 query::remove_pending_board(&tx, vtxo_id)?;
167 tx.commit()?;
168 Ok(())
169 }
170
171 async fn get_all_pending_board_ids(&self) -> anyhow::Result<Vec<VtxoId>> {
172 let conn = self.connect()?;
173 query::get_all_pending_boards_ids(&conn)
174 }
175
176 async fn get_pending_board_by_vtxo_id(&self, vtxo_id: VtxoId) -> anyhow::Result<Option<PendingBoard>> {
177 let conn = self.connect()?;
178 query::get_pending_board_by_vtxo_id(&conn, vtxo_id)
179 }
180
181 async fn store_round_state(&self, round_state: &RoundState) -> anyhow::Result<RoundStateId> {
182 let conn = self.connect()?;
183 query::store_round_state(&conn, round_state)
184 }
185
186 async fn update_round_state(&self, state: &StoredRoundState) -> anyhow::Result<()> {
187 let conn = self.connect()?;
188 query::update_round_state(&conn, state)?;
189 Ok(())
190 }
191
192 async fn remove_round_state(&self, round_state: &StoredRoundState) -> anyhow::Result<()> {
193 let conn = self.connect()?;
194 query::remove_round_state(&conn, round_state.id())?;
195 Ok(())
196 }
197
198 async fn get_round_state_by_id(&self, id: RoundStateId) -> anyhow::Result<Option<StoredRoundState<Unlocked>>> {
199 let conn = self.connect()?;
200 query::get_round_state_by_id(&conn, id)
201 }
202
203 async fn get_pending_round_state_ids(&self) -> anyhow::Result<Vec<RoundStateId>> {
204 let conn = self.connect()?;
205 query::get_pending_round_state_ids(&conn)
206 }
207
208 async fn store_vtxos(
209 &self,
210 vtxos: &[(&Vtxo<Full>, &VtxoState)],
211 ) -> anyhow::Result<()> {
212 let mut conn = self.connect()?;
213 let tx = conn.transaction()?;
214
215 for (vtxo, state) in vtxos {
216 query::store_vtxo_with_initial_state(&tx, vtxo, state)?;
217 }
218 tx.commit()?;
219 Ok(())
220 }
221
222 async fn get_wallet_vtxo(&self, id: VtxoId) -> anyhow::Result<Option<WalletVtxo>> {
223 let conn = self.connect()?;
224 query::get_wallet_vtxo_by_id(&conn, id)
225 }
226
227 async fn get_all_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
228 let conn = self.connect()?;
229 query::get_all_vtxos(&conn)
230 }
231
232 async fn get_vtxos_by_state(&self, state: &[VtxoStateKind]) -> anyhow::Result<Vec<WalletVtxo>> {
234 let conn = self.connect()?;
235 query::get_vtxos_by_state(&conn, state)
236 }
237
238 async fn has_spent_vtxo(&self, id: VtxoId) -> anyhow::Result<bool> {
239 let conn = self.connect()?;
240 let state : Option<VtxoState> = query::get_vtxo_state(&conn, id)?;
241 let result = state.map(|s| s == VtxoState::Spent).unwrap_or(false);
242 Ok(result)
243 }
244
245 async fn get_full_vtxo(&self, id: VtxoId) -> anyhow::Result<Option<Vtxo<Full>>> {
246 let conn = self.connect()?;
247 query::get_full_vtxo_by_id(&conn, id)
248 }
249
250 async fn get_full_vtxos(&self, ids: &[VtxoId]) -> anyhow::Result<Vec<Vtxo<Full>>> {
251 let conn = self.connect()?;
252 query::get_full_vtxos_by_ids(&conn, ids)
253 }
254
255 async fn remove_vtxo(&self, id: VtxoId) -> anyhow::Result<Option<Vtxo<Full>>> {
256 let mut conn = self.connect()?;
257 let tx = conn.transaction().context("Failed to start transaction")?;
258 let result = query::delete_vtxo(&tx, id);
259 tx.commit().context("Failed to commit transaction")?;
260 result
261 }
262
263 async fn store_vtxo_key(&self, index: u32, public_key: PublicKey) -> anyhow::Result<()> {
264 let conn = self.connect()?;
265 query::store_vtxo_key(&conn, index, public_key)
266 }
267
268 async fn get_last_vtxo_key_index(&self) -> anyhow::Result<Option<u32>> {
269 let conn = self.connect()?;
270 query::get_last_vtxo_key_index(&conn)
271 }
272
273 async fn get_public_key_idx(&self, public_key: &PublicKey) -> anyhow::Result<Option<u32>> {
274 let conn = self.connect()?;
275 query::get_public_key_idx(&conn, public_key)
276 }
277
278 async fn get_mailbox_checkpoint(&self) -> anyhow::Result<u64> {
279 let conn = self.connect()?;
280 query::get_mailbox_checkpoint(&conn)
281 }
282
283 async fn store_mailbox_checkpoint(&self, checkpoint: u64) -> anyhow::Result<()> {
284 let conn = self.connect()?;
285 query::store_mailbox_checkpoint(&conn, checkpoint)?;
286 Ok(())
287 }
288
289 async fn store_lightning_receive(
291 &self,
292 payment_hash: PaymentHash,
293 preimage: Preimage,
294 invoice: &Bolt11Invoice,
295 htlc_recv_cltv_delta: BlockDelta,
296 ) -> anyhow::Result<()> {
297 let conn = self.connect()?;
298 query::store_lightning_receive(
299 &conn, payment_hash, preimage, invoice, htlc_recv_cltv_delta,
300 )?;
301 Ok(())
302 }
303
304 async fn upsert_wallet_action_checkpoint(
305 &self,
306 id: &WalletActionId,
307 checkpoint: &WalletActionCheckpoint,
308 ) -> anyhow::Result<()> {
309 let conn = self.connect()?;
310 query::upsert_wallet_action_checkpoint(&conn, id, checkpoint)
311 }
312
313 async fn get_wallet_action_checkpoint(
314 &self,
315 id: &WalletActionId,
316 ) -> anyhow::Result<Option<WalletActionCheckpoint>> {
317 let conn = self.connect()?;
318 query::get_wallet_action_checkpoint(&conn, id)
319 }
320
321 async fn get_all_wallet_action_checkpoints(
322 &self,
323 ) -> anyhow::Result<Vec<WalletActionCheckpoint>> {
324 let conn = self.connect()?;
325 query::get_all_wallet_action_checkpoints(&conn)
326 }
327
328 async fn remove_wallet_action_checkpoint(
329 &self,
330 id: &WalletActionId,
331 ) -> anyhow::Result<()> {
332 let conn = self.connect()?;
333 query::remove_wallet_action_checkpoint(&conn, id)
334 }
335
336 async fn record_paid_invoice(
337 &self,
338 payment_hash: PaymentHash,
339 preimage: Preimage,
340 ) -> anyhow::Result<()> {
341 let conn = self.connect()?;
342 query::record_paid_invoice(&conn, payment_hash, preimage)
343 }
344
345 async fn get_paid_invoice(
346 &self,
347 payment_hash: PaymentHash,
348 ) -> anyhow::Result<Option<PaidInvoice>> {
349 let conn = self.connect()?;
350 query::get_paid_invoice(&conn, payment_hash)
351 }
352
353 async fn get_all_pending_lightning_receives(&self) -> anyhow::Result<Vec<LightningReceive>> {
354 let conn = self.connect()?;
355 query::get_all_pending_lightning_receives(&conn)
356 }
357
358 async fn set_preimage_revealed(&self, payment_hash: PaymentHash) -> anyhow::Result<()> {
359 let conn = self.connect()?;
360 query::set_preimage_revealed(&conn, payment_hash)?;
361 Ok(())
362 }
363
364 async fn update_lightning_receive(
365 &self,
366 payment_hash: PaymentHash,
367 htlc_vtxo_ids: &[VtxoId],
368 movement_id: MovementId,
369 ) -> anyhow::Result<()> {
370 let conn = self.connect()?;
371 query::update_lightning_receive(&conn, payment_hash, htlc_vtxo_ids, movement_id)?;
372 Ok(())
373 }
374
375 async fn fetch_lightning_receive_by_payment_hash(
377 &self,
378 payment_hash: PaymentHash,
379 ) -> anyhow::Result<Option<LightningReceive>> {
380 let conn = self.connect()?;
381 query::fetch_lightning_receive_by_payment_hash(&conn, payment_hash)
382 }
383
384 async fn finish_pending_lightning_receive(&self, payment_hash: PaymentHash) -> anyhow::Result<()> {
385 let conn = self.connect()?;
386 query::finish_pending_lightning_receive(&conn, payment_hash)?;
387 Ok(())
388 }
389
390 async fn store_exit_vtxo_entry(&self, exit: &StoredExit) -> anyhow::Result<()> {
391 let mut conn = self.connect()?;
392 let tx = conn.transaction()?;
393 query::store_exit_vtxo_entry(&tx, exit)?;
394 tx.commit()?;
395 Ok(())
396 }
397
398 async fn remove_exit_vtxo_entry(&self, id: &VtxoId) -> anyhow::Result<()> {
399 let mut conn = self.connect()?;
400 let tx = conn.transaction()?;
401 query::remove_exit_vtxo_entry(&tx, &id)?;
402 tx.commit()?;
403 Ok(())
404 }
405
406 async fn get_exit_vtxo_entries(&self) -> anyhow::Result<Vec<StoredExit>> {
407 let conn = self.connect()?;
408 query::get_exit_vtxo_entries(&conn)
409 }
410
411 async fn store_exit_child_tx(
412 &self,
413 exit_txid: Txid,
414 child_tx: &bitcoin::Transaction,
415 origin: ExitTxOrigin,
416 ) -> anyhow::Result<()> {
417 let mut conn = self.connect()?;
418 let tx = conn.transaction()?;
419 query::store_exit_child_tx(&tx, exit_txid, child_tx, origin)?;
420 tx.commit()?;
421 Ok(())
422 }
423
424 async fn get_exit_child_tx(
425 &self,
426 exit_txid: Txid,
427 ) -> anyhow::Result<Option<(bitcoin::Transaction, ExitTxOrigin)>> {
428 let conn = self.connect()?;
429 query::get_exit_child_tx(&conn, exit_txid)
430 }
431
432 async fn update_vtxo_state_checked(
433 &self,
434 vtxo_id: VtxoId,
435 new_state: VtxoState,
436 allowed_old_states: &[VtxoStateKind]
437 ) -> anyhow::Result<WalletVtxo> {
438 let conn = self.connect()?;
439 query::update_vtxo_state_checked(&conn, vtxo_id, new_state, allowed_old_states)
440 }
441
442 async fn update_vtxo_states_checked(
443 &self,
444 vtxo_ids: &[VtxoId],
445 new_state: VtxoState,
446 allowed_old_states: &[VtxoStateKind],
447 ) -> anyhow::Result<()> {
448 let mut conn = self.connect()?;
449 let tx = conn.transaction()?;
450 query::update_vtxo_states_checked(&tx, vtxo_ids, new_state, allowed_old_states)?;
451 tx.commit()?;
452 Ok(())
453 }
454
455 async fn store_pending_offboard(
456 &self,
457 pending: &PendingOffboard,
458 ) -> anyhow::Result<()> {
459 let mut conn = self.connect()?;
460 let tx = conn.transaction()?;
461 query::store_pending_offboard(&tx, pending)?;
462 tx.commit()?;
463 Ok(())
464 }
465
466 async fn get_pending_offboards(&self) -> anyhow::Result<Vec<PendingOffboard>> {
467 let conn = self.connect()?;
468 query::get_all_pending_offboards(&conn)
469 }
470
471 async fn remove_pending_offboard(&self, movement_id: MovementId) -> anyhow::Result<()> {
472 let mut conn = self.connect()?;
473 let tx = conn.transaction()?;
474 query::remove_pending_offboard(&tx, movement_id)?;
475 tx.commit()?;
476 Ok(())
477 }
478}
479
480#[cfg(any(test, doc))]
481pub mod helpers {
482 use std::path::PathBuf;
483 use std::str::FromStr;
484
485 use rusqlite::Connection;
486
487 #[cfg(any(test, feature = "rand"))]
494 pub fn in_memory_db() -> (PathBuf, Connection) {
495 use rand::{distr, RngExt};
496
497 let mut rng = rand::rng();
503 let filename: String = (&mut rng).sample_iter(distr::Alphanumeric)
504 .take(16).map(char::from).collect();
505
506 let connection_string = format!("file:{}?mode=memory&cache=shared", filename);
507 let pathbuf = PathBuf::from_str(&connection_string).unwrap();
508
509 let conn = Connection::open(pathbuf.clone()).unwrap();
510 (pathbuf.clone(), conn)
511 }
512}
513
514#[cfg(test)]
515mod test {
516 use ark::ProtocolEncoding;
517 use ark::test_util::VTXO_VECTORS;
518
519 use crate::{persist::sqlite::helpers::in_memory_db, vtxo::VtxoState};
520
521 use super::*;
522
523 #[tokio::test]
524 async fn test_add_and_retrieve_vtxos() {
525 let vtxo_1 = &VTXO_VECTORS.board_vtxo;
526 let vtxo_2 = &VTXO_VECTORS.arkoor_htlc_out_vtxo;
527 let vtxo_3 = &VTXO_VECTORS.round2_vtxo;
528
529 let (cs, conn) = in_memory_db();
530 let db = SqliteClient::open(cs).unwrap();
531
532 db.store_vtxos(&[
533 (vtxo_1, &VtxoState::Spendable), (vtxo_2, &VtxoState::Spendable)
534 ]).await.unwrap();
535
536 let vtxo_1_db = db.get_wallet_vtxo(vtxo_1.id()).await.expect("No error").expect("A vtxo was found");
539 assert_eq!(vtxo_1_db.vtxo, vtxo_1.to_bare());
540
541 let vtxo_1_full = db.get_full_vtxo(vtxo_1.id()).await.unwrap().unwrap();
543 assert_eq!(vtxo_1_full.serialize(), vtxo_1.serialize());
544
545 assert!(db.get_wallet_vtxo(vtxo_3.id()).await.expect("No error").is_none());
547
548 let vtxos = db.get_vtxos_by_state(&[VtxoStateKind::Spendable]).await.unwrap();
550 assert_eq!(vtxos.len(), 2);
551 assert!(vtxos.iter().any(|v| v.vtxo == vtxo_1.to_bare()));
552 assert!(vtxos.iter().any(|v| v.vtxo == vtxo_2.to_bare()));
553 assert!(!vtxos.iter().any(|v| v.vtxo == vtxo_3.to_bare()));
554
555 db.update_vtxo_state_checked(
557 vtxo_1.id(), VtxoState::Spent, &VtxoStateKind::UNSPENT_STATES,
558 ).await.unwrap();
559
560 let vtxos = db.get_vtxos_by_state(&[VtxoStateKind::Spendable]).await.unwrap();
561 assert_eq!(vtxos.len(), 1);
562
563 db.store_vtxos(&[(vtxo_3, &VtxoState::Spendable)]).await.unwrap();
565
566 let vtxos = db.get_vtxos_by_state(&[VtxoStateKind::Spendable]).await.unwrap();
567 assert_eq!(vtxos.len(), 2);
568 assert!(vtxos.iter().any(|v| v.vtxo == vtxo_2.to_bare()));
569 assert!(vtxos.iter().any(|v| v.vtxo == vtxo_3.to_bare()));
570
571 conn.close().unwrap();
572 }
573
574 #[tokio::test]
575 #[cfg(feature = "onchain-bdk")]
576 async fn test_create_wallet_then_load() {
577 use bdk_wallet::chain::DescriptorExt;
578
579 let (connection_string, conn) = in_memory_db();
580
581 let db = SqliteClient::open(connection_string).unwrap();
582 let network = bitcoin::Network::Testnet;
583
584 let seed = bip39::Mnemonic::generate(12).unwrap().to_seed("");
585 let xpriv = bitcoin::bip32::Xpriv::new_master(network, &seed).unwrap();
586
587 let desc = format!("tr({}/84'/0'/0'/*)", xpriv);
588
589 let _ = db.initialize_bdk_wallet().await.unwrap();
591 let mut created = bdk_wallet::Wallet::create_single(desc.clone())
592 .network(network)
593 .create_wallet_no_persist()
594 .unwrap();
595 db.store_bdk_wallet_changeset(&created.take_staged().unwrap()).await.unwrap();
596
597 let loaded = {
598 let changeset = db.initialize_bdk_wallet().await.unwrap();
599 bdk_wallet::Wallet::load()
600 .descriptor(bdk_wallet::KeychainKind::External, Some(desc.clone()))
601 .extract_keys()
602 .check_network(network)
603 .load_wallet_no_persist(changeset)
604 .unwrap()
605 };
606
607 assert!(loaded.is_some());
608 assert_eq!(
609 created.public_descriptor(bdk_wallet::KeychainKind::External).descriptor_id(),
610 loaded.unwrap().public_descriptor(bdk_wallet::KeychainKind::External).descriptor_id()
611 );
612
613 conn.close().unwrap();
616 }
617
618 #[tokio::test]
619 async fn differential_bark_persister_suite() {
620 let (cs, _conn) = helpers::in_memory_db();
621 let sqlite = SqliteClient::open(cs).unwrap();
622 let memory = crate::persist::adaptor::StorageAdaptorWrapper::new(
623 crate::persist::adaptor::memory::MemoryStorageAdaptor::new(),
624 );
625 crate::persist::test_suite::run_all(&sqlite, &memory).await;
626 }
627}