bark/persist/
mod.rs

1//! Persistence abstractions for Bark wallets.
2//!
3//! This module defines the [BarkPersister] trait and related data models used by the
4//! wallet to store and retrieve state. Implementors can provide their own storage backends
5//! (e.g., SQLite, PostgreSQL, in-memory, mobile key/value stores) by implementing the
6//! [BarkPersister] trait.
7//!
8//! Design goals
9//! - Clear separation between wallet logic and storage.
10//! - Transactional semantics where appropriate (round state transitions, movement recording).
11//! - Portability across different platforms and environments.
12//!
13//! Typical usage
14//! - Applications construct a concrete persister (for example, a SQLite-backed client) and
15//!   pass it to the [crate::Wallet]. The [crate::Wallet] only depends on this trait for reads/writes.
16//! - Custom wallet implementations can reuse this trait to remain compatible with Bark
17//!   storage expectations without depending on a specific database.
18//! - A default rusqlite implementation is provided by [sqlite::SqliteClient].
19
20pub mod models;
21pub mod sqlite;
22
23
24use std::fmt;
25
26use bitcoin::{Amount, Transaction, Txid};
27use bitcoin::secp256k1::PublicKey;
28use chrono::DateTime;
29use lightning_invoice::Bolt11Invoice;
30#[cfg(feature = "onchain_bdk")]
31use bdk_wallet::ChangeSet;
32
33use ark::{Vtxo, VtxoId};
34use ark::lightning::{Invoice, PaymentHash, Preimage};
35use bitcoin_ext::BlockDelta;
36
37use crate::WalletProperties;
38use crate::exit::models::ExitTxOrigin;
39use crate::movement::{Movement, MovementId, MovementStatus, MovementSubsystem};
40use crate::persist::models::{PendingLightningSend, LightningReceive, StoredExit};
41use crate::round::{RoundState, UnconfirmedRound};
42use crate::vtxo::state::{VtxoState, VtxoStateKind, WalletVtxo};
43
44/// Identifier for a stored [RoundState].
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct RoundStateId(pub u32);
47
48impl fmt::Display for RoundStateId {
49	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50	    fmt::Display::fmt(&self.0, f)
51	}
52}
53
54pub struct StoredRoundState {
55	pub id: RoundStateId,
56	pub state: RoundState,
57}
58
59/// Storage interface for Bark wallets.
60///
61/// Implement this trait to plug a custom persistence backend. The wallet uses it to:
62/// - Initialize and read wallet properties and configuration.
63/// - Record movements (spends/receives), recipients, and enforce [Vtxo] state transitions.
64/// - Manage round lifecycles (attempts, pending confirmation, confirmations/cancellations).
65/// - Persist ephemeral protocol artifacts (e.g., secret nonces) transactionally.
66/// - Track Lightning receives and preimage revelation.
67/// - Track exit-related data and associated child transactions.
68/// - Persist the last synchronized Ark block height.
69///
70/// Feature integration:
71/// - With the `onchain_bdk` feature, methods are provided to initialize and persist a BDK
72///   wallet ChangeSet in the same storage.
73///
74/// Notes for implementors:
75/// - Ensure that operations that change multiple records (e.g., registering a movement,
76///   storing round state transitions) are executed transactionally.
77/// - Enforce state integrity by verifying allowed_old_states before updating a [Vtxo] state.
78/// - If your backend is not thread-safe, prefer a short-lived connection per call or use
79///   an internal pool with checked-out connections per operation.
80/// - Return precise errors so callers can surface actionable diagnostics.
81pub trait BarkPersister: Send + Sync + 'static {
82	/// Initialize a wallet in storage with the provided properties.
83	///
84	/// Call exactly once per wallet database. Subsequent calls should fail to prevent
85	/// accidental re-initialization.
86	///
87	/// Parameters:
88	/// - properties: WalletProperties to persist (e.g., network, descriptors, metadata).
89	///
90	/// Returns:
91	/// - `Ok(())` on success.
92	///
93	/// Errors:
94	/// - Returns an error if the wallet is already initialized or if persistence fails.
95	fn init_wallet(&self, properties: &WalletProperties) -> anyhow::Result<()>;
96
97	/// Initialize the onchain BDK wallet and return any previously stored ChangeSet.
98	///
99	/// Must be called before storing any new BDK changesets to bootstrap the BDK state.
100	///
101	/// Feature: only available with `onchain_bdk`.
102	///
103	/// Returns:
104	/// - `Ok(ChangeSet)` containing the previously persisted BDK state (possibly empty).
105	///
106	/// Errors:
107	/// - Returns an error if the BDK state cannot be created or loaded.
108	#[cfg(feature = "onchain_bdk")]
109	fn initialize_bdk_wallet(&self) -> anyhow::Result<ChangeSet>;
110
111	/// Persist an incremental BDK ChangeSet.
112	///
113	/// The changeset should be applied atomically. Callers typically obtain the changeset
114	/// from a BDK wallet instance after mutating wallet state (e.g., sync).
115	///
116	/// Feature: only available with `onchain_bdk`.
117	///
118	/// Parameters:
119	/// - changeset: The BDK ChangeSet to persist.
120	///
121	/// Errors:
122	/// - Returns an error if the changeset cannot be written.
123	#[cfg(feature = "onchain_bdk")]
124	fn store_bdk_wallet_changeset(&self, changeset: &ChangeSet) -> anyhow::Result<()>;
125
126	/// Read wallet properties from storage.
127	///
128	/// Returns:
129	/// - `Ok(Some(WalletProperties))` if the wallet has been initialized.
130	/// - `Ok(None)` if no wallet exists yet.
131	///
132	/// Errors:
133	/// - Returns an error on I/O or deserialization failures.
134	fn read_properties(&self) -> anyhow::Result<Option<WalletProperties>>;
135
136	/// Check whether a recipient identifier already exists.
137	///
138	/// Useful to avoid storing duplicate recipients for the same logical payee or duplicated
139	/// lightning invoice payments (unsafe)
140	///
141	/// Parameters:
142	/// - recipient: A recipient identifier (e.g., invoice).
143	///
144	/// Returns:
145	/// - `Ok(true)` if the recipient exists,
146	/// - `Ok(false)` otherwise.
147	///
148	/// Errors:
149	/// - Returns an error if the lookup fails.
150	fn check_recipient_exists(&self, recipient: &str) -> anyhow::Result<bool>;
151
152	/// Creates a new movement in the given state, ready to be updated.
153	///
154	/// Parameters:
155	/// - status: The desired status for the new movement.
156	/// - subsystem: The subsystem that created the movement.
157	/// - time: The time the movement should be marked as created.
158	///
159	/// Returns:
160	/// - `Ok(MovementId)` of the newly created movement.
161	///
162	/// Errors:
163	/// - Returns an error if the movement is unable to be created.
164	fn create_new_movement(&self,
165		status: MovementStatus,
166		subsystem: &MovementSubsystem,
167		time: DateTime<chrono::Utc>,
168	) -> anyhow::Result<MovementId>;
169
170	/// Persists the given movement state.
171	///
172	/// Parameters:
173	/// - movement: The movement and its associated data to be persisted.
174	///
175	/// Errors:
176	/// - Returns an error if updating the movement fails for any reason.
177	fn update_movement(&self, movement: &Movement) -> anyhow::Result<()>;
178
179	/// Gets the movement with the given [MovementId].
180	///
181	/// Parameters:
182	/// - movement_id: The ID of the movement to retrieve.
183	///
184	/// Returns:
185	/// - `Ok(Movement)` if the movement exists.
186	///
187	/// Errors:
188	/// - If the movement does not exist.
189	/// - If retrieving the movement fails.
190	fn get_movement(&self, movement_id: MovementId) -> anyhow::Result<Movement>;
191
192	/// Gets every stored movement.
193	///
194	/// Returns:
195	/// - `Ok(Vec<Movement>)` containing all movements, empty if none exist.
196	///
197	/// Errors:
198	/// - If retrieving the movements fails.
199	fn get_movements(&self) -> anyhow::Result<Vec<Movement>>;
200
201	/// Store a pending board.
202	///
203	/// Parameters:
204	/// - vtxo: The [Vtxo] to store.
205	/// - funding_txid: The funding [Txid].
206	/// - movement_id: The [MovementId] associated with this board.
207	///
208	/// Errors:
209	/// - Returns an error if the board cannot be stored.
210	fn store_pending_board(
211		&self,
212		vtxo_id: VtxoId,
213		funding_tx: &Transaction,
214		movement_id: MovementId,
215	) -> anyhow::Result<()>;
216
217	/// Remove a pending board.
218	///
219	/// Parameters:
220	/// - vtxo_id: The [VtxoId] to remove.
221	///
222	/// Errors:
223	/// - Returns an error if the board cannot be removed.
224	fn remove_pending_board(&self, vtxo_id: &VtxoId) -> anyhow::Result<()>;
225
226	/// Get the [VtxoId] for each pending board.
227	///
228	/// Returns:
229	/// - `Ok(Vec<VtxoId>)` possibly empty.
230	///
231	/// Errors:
232	/// - Returns an error if the query fails.
233	fn get_all_pending_board_ids(&self) -> anyhow::Result<Vec<VtxoId>>;
234
235	/// Get the [MovementId] associated with the pending board corresponding to the given [VtxoId].
236	///
237	/// Returns:
238	/// - `Ok(MovementId)` if a matching board exists
239	///
240	/// Errors:
241	/// - Returns an error if the query fails.
242	fn get_pending_board_movement_id(&self, vtxo_id: VtxoId) -> anyhow::Result<MovementId>;
243
244	/// Store a new ongoing round state and lock the VTXOs in round
245	///
246	/// Parameters:
247	/// - `round_state`: the state to store
248	///
249	/// Returns:
250	/// - `RoundStateId`: the storaged ID of the new state
251	///
252	/// Errors:
253	/// - returns an error of the new round state could not be stored or the VTXOs
254	///   couldn't be marked as locked
255	fn store_round_state_lock_vtxos(&self, round_state: &RoundState) -> anyhow::Result<RoundStateId>;
256
257	/// Update an existing stored pending round state
258	///
259	/// Parameters:
260	/// - `round_state`: the round state to update
261	///
262	/// Errors:
263	/// - returns an error of the existing round state could not be found or updated
264	fn update_round_state(&self, round_state: &StoredRoundState) -> anyhow::Result<()>;
265
266	/// Remove a pending round state from the db and releases the locked VTXOs
267	///
268	/// Parameters:
269	/// - `round_state`: the round state to remove
270	///
271	/// Errors:
272	/// - returns an error of the existing round state could not be found or removed
273	fn remove_round_state(&self, round_state: &StoredRoundState) -> anyhow::Result<()>;
274
275	/// Load all pending round states from the db
276	///
277	/// Returns:
278	/// - `Vec<StoredRoundState>`: unordered vector with all stored round states
279	///
280	/// Errors:
281	/// - returns an error of the states could not be succesfully retrieved
282	fn load_round_states(&self) -> anyhow::Result<Vec<StoredRoundState>>;
283
284	/// Store a recovered past round
285	fn store_recovered_round(&self, round: &UnconfirmedRound) -> anyhow::Result<()>;
286
287	/// Remove a recovered past round
288	fn remove_recovered_round(&self, funding_txid: Txid) -> anyhow::Result<()>;
289
290	/// Load the recovered past rounds
291	fn load_recovered_rounds(&self) -> anyhow::Result<Vec<UnconfirmedRound>>;
292
293	/// Stores the given VTXOs in the given [VtxoState].
294	fn store_vtxos(
295		&self,
296		vtxos: &[(&Vtxo, &VtxoState)],
297	) -> anyhow::Result<()>;
298
299	/// Fetch a wallet [Vtxo] with its current state by ID.
300	///
301	/// Parameters:
302	/// - id: [VtxoId] to look up.
303	///
304	/// Returns:
305	/// - `Ok(Some(WalletVtxo))` if found,
306	/// - `Ok(None)` otherwise.
307	///
308	/// Errors:
309	/// - Returns an error if the lookup fails.
310	fn get_wallet_vtxo(&self, id: VtxoId) -> anyhow::Result<Option<WalletVtxo>>;
311
312	/// Fetch all wallet VTXOs in the database.
313	///
314	/// Returns:
315	/// - `Ok(Vec<WalletVtxo>)` possibly empty.
316	///
317	/// Errors:
318	/// - Returns an error if the query fails.
319	fn get_all_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>>;
320
321	/// Fetch all wallet VTXOs whose state matches any of the provided kinds.
322	///
323	/// Parameters:
324	/// - state: Slice of `VtxoStateKind` filters.
325	///
326	/// Returns:
327	/// - `Ok(Vec<WalletVtxo>)` possibly empty.
328	///
329	/// Errors:
330	/// - Returns an error if the query fails.
331	fn get_vtxos_by_state(&self, state: &[VtxoStateKind]) -> anyhow::Result<Vec<WalletVtxo>>;
332
333	/// Remove a [Vtxo] by ID.
334	///
335	/// Parameters:
336	/// - id: `VtxoId` to remove.
337	///
338	/// Returns:
339	/// - `Ok(Some(Vtxo))` with the removed [Vtxo] data if it existed,
340	/// - `Ok(None)` otherwise.
341	///
342	/// Errors:
343	/// - Returns an error if the delete operation fails.
344	fn remove_vtxo(&self, id: VtxoId) -> anyhow::Result<Option<Vtxo>>;
345
346	/// Check whether a [Vtxo] is already marked spent.
347	///
348	/// Parameters:
349	/// - id: VtxoId to check.
350	///
351	/// Returns:
352	/// - `Ok(true)` if spent,
353	/// - `Ok(false)` if not found or not spent.
354	///
355	/// Errors:
356	/// - Returns an error if the lookup fails.
357	fn has_spent_vtxo(&self, id: VtxoId) -> anyhow::Result<bool>;
358
359	/// Store a newly derived/assigned [Vtxo] public key index mapping.
360	///
361	/// Parameters:
362	/// - index: Derivation index.
363	/// - public_key: PublicKey at that index.
364	///
365	/// Errors:
366	/// - Returns an error if the mapping cannot be stored.
367	fn store_vtxo_key(&self, index: u32, public_key: PublicKey) -> anyhow::Result<()>;
368
369	/// Get the last revealed/used [Vtxo] key index.
370	///
371	/// Returns:
372	/// - `Ok(Some(u32))` if a key was stored
373	/// - `Ok(None)` otherwise.
374	///
375	/// Errors:
376	/// - Returns an error if the query fails.
377	fn get_last_vtxo_key_index(&self) -> anyhow::Result<Option<u32>>;
378
379	/// Retrieves the derivation index of the provided [PublicKey] from the database
380	///
381	/// Returns:
382	/// - `Ok(Some(u32))` if the key was stored.
383	/// - `Ok(None)` if the key was not stored.
384	///
385	/// Errors:
386	/// - Returns an error if the query fails.
387	fn get_public_key_idx(&self, public_key: &PublicKey) -> anyhow::Result<Option<u32>>;
388
389	/// Store a new pending lightning send.
390	///
391	/// Parameters:
392	/// - invoice: The invoice of the pending lightning send.
393	/// - amount: The amount of the pending lightning send.
394	/// - vtxos: The vtxos of the pending lightning send.
395	///
396	/// Errors:
397	/// - Returns an error if the pending lightning send cannot be stored.
398	fn store_new_pending_lightning_send(
399		&self,
400		invoice: &Invoice,
401		amount: &Amount,
402		vtxos: &[VtxoId],
403		movement_id: MovementId,
404	) -> anyhow::Result<PendingLightningSend>;
405
406	/// Get all pending lightning sends.
407	///
408	/// Returns:
409	/// - `Ok(Vec<PendingLightningSend>)` possibly empty.
410	///
411	/// Errors:
412	/// - Returns an error if the query fails.
413	fn get_all_pending_lightning_send(&self) -> anyhow::Result<Vec<PendingLightningSend>>;
414
415	/// Remove a pending lightning send.
416	///
417	/// Parameters:
418	/// - payment_hash: The [PaymentHash] of the pending lightning send to remove.
419	///
420	/// Errors:
421	/// - Returns an error if the pending lightning send cannot be removed.
422	fn remove_pending_lightning_send(&self, payment_hash: PaymentHash) -> anyhow::Result<()>;
423
424	/// Store an incoming Lightning receive record.
425	///
426	/// Parameters:
427	/// - payment_hash: Unique payment hash.
428	/// - preimage: Payment preimage (kept until disclosure).
429	/// - invoice: The associated BOLT11 invoice.
430	/// - htlc_recv_cltv_delta: The CLTV delta for the HTLC VTXO.
431	///
432	/// Errors:
433	/// - Returns an error if the receive cannot be stored.
434	fn store_lightning_receive(
435		&self,
436		payment_hash: PaymentHash,
437		preimage: Preimage,
438		invoice: &Bolt11Invoice,
439		htlc_recv_cltv_delta: BlockDelta,
440	) -> anyhow::Result<()>;
441
442	/// Returns a list of all pending lightning receives
443	///
444	/// Returns:
445	/// - `Ok(Vec<LightningReceive>)` possibly empty.
446	///
447	/// Errors:
448	/// - Returns an error if the query fails.
449	fn get_all_pending_lightning_receives(&self) -> anyhow::Result<Vec<LightningReceive>>;
450
451	/// Mark a Lightning receive preimage as revealed (e.g., after settlement).
452	///
453	/// Parameters:
454	/// - payment_hash: The payment hash identifying the receive.
455	///
456	/// Errors:
457	/// - Returns an error if the update fails or the receive does not exist.
458	fn set_preimage_revealed(&self, payment_hash: PaymentHash) -> anyhow::Result<()>;
459
460	/// Set the VTXO IDs and [MovementId] for a [LightningReceive].
461	///
462	/// Parameters:
463	/// - payment_hash: The payment hash identifying the receive.
464	/// - htlc_vtxo_ids: The VTXO IDs to set.
465	/// - movement_id: The movement ID associated with the invoice.
466	///
467	/// Errors:
468	/// - Returns an error if the update fails or the receive does not exist.
469	fn update_lightning_receive(
470		&self,
471		payment_hash: PaymentHash,
472		htlc_vtxo_ids: &[VtxoId],
473		movement_id: MovementId,
474	) -> anyhow::Result<()>;
475
476	/// Fetch a Lightning receive by its payment hash.
477	///
478	/// Parameters:
479	/// - payment_hash: The payment hash to look up.
480	///
481	/// Returns:
482	/// - `Ok(Some(LightningReceive))` if found,
483	/// - `Ok(None)` otherwise.
484	///
485	/// Errors:
486	/// - Returns an error if the lookup fails.
487	fn fetch_lightning_receive_by_payment_hash(
488		&self,
489		payment_hash: PaymentHash,
490	) -> anyhow::Result<Option<LightningReceive>>;
491
492	/// Remove a Lightning receive by its payment hash.
493	///
494	/// Parameters:
495	/// - payment_hash: The payment hash of the record to remove.
496	///
497	/// Errors:
498	/// - Returns an error if the removal fails.
499	fn remove_pending_lightning_receive(&self, payment_hash: PaymentHash) -> anyhow::Result<()>;
500
501	/// Store an entry indicating a [Vtxo] is being exited.
502	///
503	/// Parameters:
504	/// - exit: StoredExit describing the exit operation.
505	///
506	/// Errors:
507	/// - Returns an error if the entry cannot be stored.
508	fn store_exit_vtxo_entry(&self, exit: &StoredExit) -> anyhow::Result<()>;
509
510	/// Remove an exit entry for a given [Vtxo] ID.
511	///
512	/// Parameters:
513	/// - id: VtxoId to remove from exit tracking.
514	///
515	/// Errors:
516	/// - Returns an error if the removal fails.
517	fn remove_exit_vtxo_entry(&self, id: &VtxoId) -> anyhow::Result<()>;
518
519	/// List all VTXOs currently tracked as being exited.
520	///
521	/// Returns:
522	/// - `Ok(Vec<StoredExit>)` possibly empty.
523	///
524	/// Errors:
525	/// - Returns an error if the query fails.
526	fn get_exit_vtxo_entries(&self) -> anyhow::Result<Vec<StoredExit>>;
527
528	/// Store a child transaction related to an exit transaction.
529	///
530	/// Parameters:
531	/// - exit_txid: The parent exit transaction ID.
532	/// - child_tx: The child bitcoin Transaction to store.
533	/// - origin: Metadata describing where the child came from (ExitTxOrigin).
534	///
535	/// Errors:
536	/// - Returns an error if the transaction cannot be stored.
537	fn store_exit_child_tx(
538		&self,
539		exit_txid: Txid,
540		child_tx: &Transaction,
541		origin: ExitTxOrigin,
542	) -> anyhow::Result<()>;
543
544	/// Retrieve a stored child transaction for a given exit transaction ID.
545	///
546	/// Parameters:
547	/// - exit_txid: The parent exit transaction ID.
548	///
549	/// Returns:
550	/// - `Ok(Some((Transaction, ExitTxOrigin)))` if found,
551	/// - `Ok(None)` otherwise.
552	///
553	/// Errors:
554	/// - Returns an error if the lookup fails.
555	fn get_exit_child_tx(
556		&self,
557		exit_txid: Txid,
558	) -> anyhow::Result<Option<(Transaction, ExitTxOrigin)>>;
559
560	/// Updates the state of the VTXO corresponding to the given [VtxoId], provided that their
561	/// current state is one of the given `allowed_states`.
562	///
563	/// # Parameters
564	/// - `vtxo_id`: The ID of the [Vtxo] to update.
565	/// - `state`: The new state to be set for the specified [Vtxo].
566	/// - `allowed_states`: An iterable collection of allowed states ([VtxoStateKind]) that the
567	///   [Vtxo] must currently be in for their state to be updated to the new `state`.
568	///
569	/// # Returns
570	/// - `Ok(WalletVtxo)` if the state update is successful.
571	/// - `Err(anyhow::Error)` if the VTXO fails to meet the required conditions,
572	///    or if another error occurs during the operation.
573	///
574	/// # Errors
575	/// - Returns an error if the current state is not within the `allowed_states`.
576	/// - Returns an error for any other issues encountered during the operation.
577	fn update_vtxo_state_checked(
578		&self,
579		vtxo_id: VtxoId,
580		new_state: VtxoState,
581		allowed_old_states: &[VtxoStateKind],
582	) -> anyhow::Result<WalletVtxo>;
583}