bark-wallet 0.1.3

Wallet library and CLI for the bitcoin Ark protocol built by Second
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Persistence-focused data models.
//!
//! This module defines serializable types that mirror core in-memory structures but are tailored
//! for durable storage and retrieval via a BarkPersister implementation.
//!
//! Intent
//! - Keep storage concerns decoupled from runtime types used by protocol logic.
//! - Provide stable, serde-friendly representations for database backends.
//! - Enable forward/backward compatibility when schema migrations occur.

use std::borrow::Cow;
use std::fmt;

use bitcoin::{Amount, Transaction};
use bitcoin::secp256k1::{Keypair, PublicKey};
use lightning_invoice::Bolt11Invoice;

use ark::{Vtxo, VtxoId, VtxoPolicy, VtxoRequest};
use ark::vtxo::Full;
use ark::mailbox::MailboxIdentifier;
use ark::musig::DangerousSecretNonce;
use ark::tree::signed::{UnlockHash, VtxoTreeSpec};
use ark::lightning::{Invoice, PaymentHash, Preimage};
use ark::rounds::RoundSeq;
use bitcoin_ext::BlockDelta;

use crate::WalletVtxo;
use crate::exit::{ExitState, ExitTxOrigin, ExitVtxo};
use crate::movement::MovementId;
use crate::round::{AttemptState, RoundFlowState, RoundParticipation, RoundState, RoundStateGuard};
use crate::vtxo::VtxoState;

/// VTXO with state history for persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerdeVtxo {
	#[serde(with = "ark::encode::serde")]
	pub vtxo: Vtxo<Full>,
	/// VTXO states, sorted from oldest to newest.
	pub states: Vec<VtxoState>,
}

#[derive(Debug, thiserror::Error)]
#[error("vtxo has no state")]
pub struct MissingStateError;

impl SerdeVtxo {
	pub fn current_state(&self) -> Option<&VtxoState> {
		self.states.last()
	}

	pub fn to_wallet_vtxo(&self) -> Result<WalletVtxo, MissingStateError> {
		Ok(WalletVtxo {
			vtxo: self.vtxo.clone(),
			state: self.current_state().cloned().ok_or(MissingStateError)?,
		})
	}
}

/// VTXO key mapping for persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerdeVtxoKey {
	pub index: u32,
	pub public_key: PublicKey,
}

/// Identifier for a stored [RoundState].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RoundStateId(pub u32);

impl RoundStateId {
	pub fn to_bytes(&self) -> [u8; 4] {
		self.0.to_be_bytes()
	}
}

impl fmt::Display for RoundStateId {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
	    fmt::Display::fmt(&self.0, f)
	}
}

#[allow(unused)]
pub struct Locked(RoundStateGuard);

pub struct Unlocked;

pub struct StoredRoundState<G = Locked> {
	id: RoundStateId,
	state: RoundState,
	_guard: G
}

impl<G> StoredRoundState<G> {
	pub fn id(&self) -> RoundStateId {
		self.id
	}

	pub fn state(&self) -> &RoundState {
		&self.state
	}
}

impl StoredRoundState<Unlocked> {
	pub fn new(id: RoundStateId, state: RoundState) -> Self {
		Self { id, state, _guard: Unlocked }
	}

	pub fn lock(self, guard: RoundStateGuard) -> StoredRoundState {
		StoredRoundState { id: self.id, state: self.state, _guard: Locked(guard) }
	}
}

impl StoredRoundState {
	pub fn state_mut(&mut self) -> &mut RoundState {
		&mut self.state
	}

	pub fn unlock(self) -> StoredRoundState<Unlocked> {
		StoredRoundState { id: self.id, state: self.state, _guard: Unlocked }
	}
}

/// Persisted representation of a pending board.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingBoard {
	/// This is the [bitcoin::Transaction] that has to
	/// be confirmed onchain for the board to succeed.
	#[serde(with = "bitcoin_ext::serde::encodable")]
	pub funding_tx: Transaction,
	/// The id of VTXOs being boarded.
	///
	/// Currently, this is always a vector of length 1
	pub vtxos: Vec<VtxoId>,
	/// The amount of the board.
	#[serde(with = "bitcoin::amount::serde::as_sat")]
	pub amount: Amount,
	/// The [MovementId] associated with this board.
	pub movement_id: MovementId,
}

/// Persisted representation of a pending offboard.
///
/// Created when an offboard swap is performed, tracked until the
/// offboard transaction confirms on-chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingOffboard {
	/// The [MovementId] associated with this offboard.
	pub movement_id: MovementId,
	/// The txid of the offboard transaction.
	pub offboard_txid: bitcoin::Txid,
	/// The full signed offboard transaction.
	pub offboard_tx: Transaction,
	/// The VTXOs consumed by this offboard.
	pub vtxo_ids: Vec<VtxoId>,
	/// The destination address of the offboard.
	pub destination: String,
	/// When this pending offboard was created.
	pub created_at: chrono::DateTime<chrono::Local>,
}

/// Persisted representation of a lightning send.
///
/// Created after the HTLCs from client to server are constructed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LightningSend {
	/// The Lightning invoice being paid.
	pub invoice: Invoice,
	/// The amount being sent.
	#[serde(with = "bitcoin::amount::serde::as_sat")]
	pub amount: Amount,
	/// The fee paid for making the lightning payment.
	pub fee: Amount,
	/// The open HTLCs that are used for this payment.
	pub htlc_vtxos: Vec<WalletVtxo>,
	/// The movement associated with this payment.
	pub movement_id: MovementId,
	/// The payment preimage, serving as proof of payment.
	///
	/// Combined with [`finished_at`](Self::finished_at), determines the payment state:
	/// - `None` + `finished_at: None` → Pending (in-flight)
	/// - `None` + `finished_at: Some(_)` → Failed
	/// - `Some(_)` + `finished_at: Some(_)` → Succeeded
	pub preimage: Option<Preimage>,
	/// When the payment reached a terminal state (succeeded or failed).
	pub finished_at: Option<chrono::DateTime<chrono::Local>>,
}

/// Persisted representation of an incoming Lightning payment.
///
/// Stores the invoice and related cryptographic material (e.g., payment hash and preimage)
/// and tracks whether the preimage has been revealed.
///
/// Note: the record should be removed when the receive is completed or failed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LightningReceive {
	pub payment_hash: PaymentHash,
	pub payment_preimage: Preimage,
	pub invoice: Bolt11Invoice,
	pub preimage_revealed_at: Option<chrono::DateTime<chrono::Local>>,
	pub htlc_vtxos: Vec<WalletVtxo>,
	pub htlc_recv_cltv_delta: BlockDelta,
	pub movement_id: Option<MovementId>,
	pub finished_at: Option<chrono::DateTime<chrono::Local>>,
}

/// Persistable view of an [ExitVtxo].
///
/// `StoredExit` is a lightweight data transfer object tailored for storage backends. It captures
/// the VTXO ID, the current state, and the full history of the unilateral exit.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoredExit {
	/// Identifier of the VTXO being exited.
	pub vtxo_id: VtxoId,
	/// Current exit state.
	pub state: ExitState,
	/// Historical states for auditability.
	pub history: Vec<ExitState>,
}

impl StoredExit {
	/// Builds a persistable snapshot from an [ExitVtxo].
	pub fn new(exit: &ExitVtxo) -> Self {
		Self {
			vtxo_id: exit.id(),
			state: exit.state().clone(),
			history: exit.history().clone(),
		}
	}
}

/// Exit child transaction for persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerdeExitChildTx {
	#[serde(with = "bitcoin_ext::serde::encodable")]
	pub child_tx: Transaction,
	pub origin: ExitTxOrigin,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
struct SerdeVtxoRequest<'a> {
	#[serde(with = "bitcoin::amount::serde::as_sat")]
	amount: Amount,
	#[serde(with = "ark::encode::serde")]
	policy: Cow<'a, VtxoPolicy>,
}

impl<'a> From<&'a VtxoRequest> for SerdeVtxoRequest<'a> {
	fn from(v: &'a VtxoRequest) -> Self {
		Self {
			amount: v.amount,
			policy: Cow::Borrowed(&v.policy),
		}
	}
}

impl<'a> From<SerdeVtxoRequest<'a>> for VtxoRequest {
	fn from(v: SerdeVtxoRequest<'a>) -> Self {
		VtxoRequest {
			amount: v.amount,
			policy: v.policy.into_owned(),
		}
	}
}

/// Model for [RoundParticipation]
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SerdeRoundParticipation<'a> {
	#[serde(with = "ark::encode::serde::cow::vec")]
	inputs: Cow<'a, [Vtxo<Full>]>,
	outputs: Vec<SerdeVtxoRequest<'a>>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	unblinded_mailbox_id: Option<MailboxIdentifier>,
}

impl<'a> From<&'a RoundParticipation> for SerdeRoundParticipation<'a> {
	fn from(v: &'a RoundParticipation) -> Self {
	    Self {
			inputs: Cow::Borrowed(&v.inputs),
			outputs: v.outputs.iter().map(|v| v.into()).collect(),
			unblinded_mailbox_id: v.unblinded_mailbox_id,
		}
	}
}

impl<'a> From<SerdeRoundParticipation<'a>> for RoundParticipation {
	fn from(v: SerdeRoundParticipation<'a>) -> Self {
		Self {
			inputs: v.inputs.into_owned(),
			outputs: v.outputs.into_iter().map(|v| v.into()).collect(),
			unblinded_mailbox_id: v.unblinded_mailbox_id,
		}
	}
}

/// Model for [AttemptState]
#[derive(Debug, Serialize, Deserialize)]
enum SerdeAttemptState<'a> {
	AwaitingAttempt,
	AwaitingUnsignedVtxoTree {
		cosign_keys: Cow<'a, [Keypair]>,
		secret_nonces: Cow<'a, [Vec<DangerousSecretNonce>]>,
		unlock_hash: UnlockHash,
	},
	AwaitingFinishedRound {
		#[serde(with = "bitcoin_ext::serde::encodable::cow")]
		unsigned_round_tx: Cow<'a, Transaction>,
		#[serde(with = "ark::encode::serde")]
		vtxos_spec: Cow<'a, VtxoTreeSpec>,
		unlock_hash: UnlockHash,
	},
}

impl<'a> From<&'a AttemptState> for SerdeAttemptState<'a> {
	fn from(state: &'a AttemptState) -> Self {
		match state {
			AttemptState::AwaitingAttempt => SerdeAttemptState::AwaitingAttempt,
			AttemptState::AwaitingUnsignedVtxoTree { cosign_keys, secret_nonces, unlock_hash } => {
				SerdeAttemptState::AwaitingUnsignedVtxoTree {
					cosign_keys: Cow::Borrowed(cosign_keys),
					secret_nonces: Cow::Borrowed(secret_nonces),
					unlock_hash: *unlock_hash,
				}
			},
			AttemptState::AwaitingFinishedRound { unsigned_round_tx, vtxos_spec, unlock_hash } => {
				SerdeAttemptState::AwaitingFinishedRound {
					unsigned_round_tx: Cow::Borrowed(unsigned_round_tx),
					vtxos_spec: Cow::Borrowed(vtxos_spec),
					unlock_hash: *unlock_hash,
				}
			},
		}
	}
}

impl<'a> From<SerdeAttemptState<'a>> for AttemptState {
	fn from(state: SerdeAttemptState<'a>) -> Self {
		match state {
			SerdeAttemptState::AwaitingAttempt => AttemptState::AwaitingAttempt,
			SerdeAttemptState::AwaitingUnsignedVtxoTree { cosign_keys, secret_nonces, unlock_hash } => {
				AttemptState::AwaitingUnsignedVtxoTree {
					cosign_keys: cosign_keys.into_owned(),
					secret_nonces: secret_nonces.into_owned(),
					unlock_hash: unlock_hash,
				}
			},
			SerdeAttemptState::AwaitingFinishedRound { unsigned_round_tx, vtxos_spec, unlock_hash } => {
				AttemptState::AwaitingFinishedRound {
					unsigned_round_tx: unsigned_round_tx.into_owned(),
					vtxos_spec: vtxos_spec.into_owned(),
					unlock_hash: unlock_hash,
				}
			},
		}
	}
}

/// Model for [RoundFlowState]
#[derive(Debug, Serialize, Deserialize)]
enum SerdeRoundFlowState<'a> {
	/// We don't do flow and we just wait for the round to finish
	NonInteractivePending {
		unlock_hash: UnlockHash,
	},

	/// Waiting for round to happen
	InteractivePending,
	/// Interactive part ongoing
	InteractiveOngoing {
		round_seq: RoundSeq,
		attempt_seq: usize,
		state: SerdeAttemptState<'a>,
	},

	/// Interactive part finished, waiting for confirmation
	Finished {
		funding_tx: Cow<'a, Transaction>,
		unlock_hash: UnlockHash,
	},

	/// Failed during round
	Failed {
		error: Cow<'a, str>,
	},

	/// User canceled round
	Canceled,
}

impl<'a> From<&'a RoundFlowState> for SerdeRoundFlowState<'a> {
	fn from(state: &'a RoundFlowState) -> Self {
		match state {
			RoundFlowState::NonInteractivePending { unlock_hash } => {
				SerdeRoundFlowState::NonInteractivePending {
					unlock_hash: *unlock_hash,
				}
			},
			RoundFlowState::InteractivePending => SerdeRoundFlowState::InteractivePending,
			RoundFlowState::InteractiveOngoing { round_seq, attempt_seq, state } => {
				SerdeRoundFlowState::InteractiveOngoing {
					round_seq: *round_seq,
					attempt_seq: *attempt_seq,
					state: state.into(),
				}
			},
			RoundFlowState::Finished { funding_tx, unlock_hash } => {
				SerdeRoundFlowState::Finished {
					funding_tx: Cow::Borrowed(funding_tx),
					unlock_hash: *unlock_hash,
				}
			},
			RoundFlowState::Failed { error } => {
				SerdeRoundFlowState::Failed {
					error: Cow::Borrowed(error),
				}
			},
			RoundFlowState::Canceled => SerdeRoundFlowState::Canceled,
		}
	}
}

impl<'a> From<SerdeRoundFlowState<'a>> for RoundFlowState {
	fn from(state: SerdeRoundFlowState<'a>) -> Self {
		match state {
			SerdeRoundFlowState::NonInteractivePending { unlock_hash } => {
				RoundFlowState::NonInteractivePending { unlock_hash }
			},
			SerdeRoundFlowState::InteractivePending => RoundFlowState::InteractivePending,
			SerdeRoundFlowState::InteractiveOngoing { round_seq, attempt_seq, state } => {
				RoundFlowState::InteractiveOngoing {
					round_seq: round_seq,
					attempt_seq: attempt_seq,
					state: state.into(),
				}
			},
			SerdeRoundFlowState::Finished { funding_tx, unlock_hash } => {
				RoundFlowState::Finished {
					funding_tx: funding_tx.into_owned(),
					unlock_hash,
				}
			},
			SerdeRoundFlowState::Failed { error } => {
				RoundFlowState::Failed {
					error: error.into_owned(),
				}
			},
			SerdeRoundFlowState::Canceled => RoundFlowState::Canceled,
		}
	}
}

/// Model for [RoundState]
#[derive(Debug, Serialize, Deserialize)]
pub struct SerdeRoundState<'a> {
	done: bool,
	participation: SerdeRoundParticipation<'a>,
	movement_id: Option<MovementId>,
	flow: SerdeRoundFlowState<'a>,
	#[serde(with = "ark::encode::serde::cow::vec")]
	new_vtxos: Cow<'a, [Vtxo<Full>]>,
	sent_forfeit_sigs: bool,
}

impl<'a> From<&'a RoundState> for SerdeRoundState<'a> {
	fn from(state: &'a RoundState) -> Self {
		Self {
			done: state.done,
			participation: (&state.participation).into(),
			movement_id: state.movement_id,
			flow: (&state.flow).into(),
			new_vtxos: Cow::Borrowed(&state.new_vtxos),
			sent_forfeit_sigs: state.sent_forfeit_sigs,
		}
	}
}

impl<'a> From<SerdeRoundState<'a>> for RoundState {
	fn from(state: SerdeRoundState<'a>) -> Self {
		Self {
			done: state.done,
			participation: state.participation.into(),
			movement_id: state.movement_id,
			flow: state.flow.into(),
			new_vtxos: state.new_vtxos.into_owned(),
			sent_forfeit_sigs: state.sent_forfeit_sigs,
		}
	}
}

#[cfg(test)]
mod test {
	use crate::exit::{ExitState, ExitTxOrigin};
	use crate::vtxo::VtxoState;

	#[test]
	/// Each struct stored as JSON in the database should have test to check for backwards compatibility
	/// Parsing can occur either in convert.rs or this file (query.rs)
	fn test_serialised_structs() {
		// Exit state
		let serialised = r#"{"type":"start","tip_height":119}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();
		let serialised = r#"{"type":"processing","tip_height":119,"transactions":[{"txid":"9fd34b8c556dd9954bda80ba2cf3474a372702ebc31a366639483e78417c6812","status":{"type":"awaiting-input-confirmation","txids":["ddfe11920358d1a1fae970dc80459c60675bf1392896f69b103fc638313751de"]}}]}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();
		let serialised = r#"{"type":"awaiting-delta","tip_height":122,"confirmed_block":"122:3cdd30fc942301a74666c481beb82050ccd182050aee3c92d2197e8cad427b8f","claimable_height":134}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();
		let serialised = r#"{"type":"claimable","tip_height":134,"claimable_since": "134:71fe28f4c803a4c46a3a93d0a9937507d7c20b4bd9586ba317d1109e1aebaac9","last_scanned_block":null}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();
		let serialised = r#"{"type":"claim-in-progress","tip_height":134, "claimable_since": "134:6585896bdda6f08d924bf45cc2b16418af56703b3c50930e4dccbc1728d3800a","claim_txid":"599347c35870bd36f7acb22b81f9ffa8b911d9b5e94834858aebd3ec09339f4c"}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();
		let serialised = r#"{"type":"claimed","tip_height":134,"txid":"599347c35870bd36f7acb22b81f9ffa8b911d9b5e94834858aebd3ec09339f4c","block": "122:3cdd30fc942301a74666c481beb82050ccd182050aee3c92d2197e8cad427b8f"}"#;
		serde_json::from_str::<ExitState>(serialised).unwrap();

		// Exit child tx origins
		let serialized = r#"{"type":"wallet","confirmed_in":null}"#;
		serde_json::from_str::<ExitTxOrigin>(serialized).unwrap();
		let serialized = r#"{"type":"wallet","confirmed_in": "134:71fe28f4c803a4c46a3a93d0a9937507d7c20b4bd9586ba317d1109e1aebaac9"}"#;
		serde_json::from_str::<ExitTxOrigin>(serialized).unwrap();
		let serialized = r#"{"type":"mempool","fee_rate_kwu":25000,"total_fee":27625}"#;
		serde_json::from_str::<ExitTxOrigin>(serialized).unwrap();
		let serialized = r#"{"type":"block","confirmed_in": "134:71fe28f4c803a4c46a3a93d0a9937507d7c20b4bd9586ba317d1109e1aebaac9"}"#;
		serde_json::from_str::<ExitTxOrigin>(serialized).unwrap();

		// Vtxo state
		let serialised = r#"{"type": "spendable"}"#;
		serde_json::from_str::<VtxoState>(serialised).unwrap();
		let serialised = r#"{"type": "spent"}"#;
		serde_json::from_str::<VtxoState>(serialised).unwrap();
		let serialised = r#"{"type": "locked", "movement_id": null}"#;
		serde_json::from_str::<VtxoState>(serialised).unwrap();
	}
}