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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use std::fmt;

use anyhow::Context;
use bitcoin::{Amount, SignedAmount};
use bitcoin::hex::DisplayHex;
use lightning::util::ser::Writeable;
use lnurllib::lightning_address::LightningAddress;
use log::{debug, error, info, trace, warn};
use server_rpc::protos::{self, lightning_payment_status::PaymentStatus};

use ark::{musig, VtxoPolicy};
use ark::arkoor::ArkoorDestination;
use ark::arkoor::package::{ArkoorPackageBuilder, ArkoorPackageCosignResponse};
use ark::lightning::{Bolt12Invoice, Bolt12InvoiceExt, Invoice, Offer, PaymentHash, Preimage};
use ark::util::IteratorExt;
use bitcoin_ext::BlockHeight;

use crate::{Wallet, WalletVtxo};
use crate::lightning::lnaddr_invoice;
use crate::movement::{MovementDestination, MovementStatus, PaymentMethod};
use crate::movement::update::MovementUpdate;
use crate::persist::models::LightningSend;
use crate::subsystem::{LightningMovement, LightningSendMovement, Subsystem};


impl Wallet {
	/// Returns each pending lightning payment.
	pub async fn pending_lightning_sends(&self) -> anyhow::Result<Vec<LightningSend>> {
		Ok(self.db.get_all_pending_lightning_send().await?)
	}

	/// Queries the database for any VTXO that is a pending lightning send.
	pub async fn pending_lightning_send_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
		let vtxos = self.db.get_all_pending_lightning_send().await?.into_iter()
			.flat_map(|pending_lightning_send| pending_lightning_send.htlc_vtxos)
			.collect::<Vec<_>>();

		Ok(vtxos)
	}

	/// Syncs pending lightning payments, verifying whether the payment status has changed and
	/// creating a revocation VTXO if necessary.
	pub async fn sync_pending_lightning_send_vtxos(&self) -> anyhow::Result<()> {
		let pending_payments = self.pending_lightning_sends().await?;

		if pending_payments.is_empty() {
			return Ok(());
		}

		info!("Syncing {} pending lightning sends", pending_payments.len());

		for payment in pending_payments {
			let payment_hash = payment.invoice.payment_hash();
			self.check_lightning_payment(payment_hash, false).await?;
		}

		Ok(())
	}

	/// Performs the revocation of HTLC VTXOs associated with a failed Lightning payment.
	///
	/// Builds a revocation package, requests server cosign,
	/// then constructs new spendable VTXOs from server response.
	///
	/// Updates wallet database and movement logs to reflect the failed
	/// payment and new produced VTXOs; removes the pending send record.
	///
	/// # Arguments
	///
	/// * `payment` - A reference to the [`LightningSend`] representing the failed payment whose
	///     associated HTLC VTXOs should be revoked.
	///
	/// # Errors
	///
	/// Returns an error if revocation fails at any step.
	///
	/// # Returns
	///
	/// Returns `Ok(())` if revocation succeeds and the wallet state is properly updated.
	async fn process_lightning_revocation(&self, payment: &LightningSend) -> anyhow::Result<()> {
		let (mut srv, _) = self.require_server().await?;
		let htlc_vtxos = payment.htlc_vtxos.clone().into_iter()
			.map(|v| v.vtxo).collect::<Vec<_>>();

		debug!("Processing {} HTLC VTXOs for revocation", htlc_vtxos.len());

		let mut secs = Vec::with_capacity(htlc_vtxos.len());
		let mut pubs = Vec::with_capacity(htlc_vtxos.len());
		let mut htlc_keypairs = Vec::with_capacity(htlc_vtxos.len());
		for input in htlc_vtxos.iter() {
			let keypair = self.get_vtxo_key(input).await?;
			let (s, p) = musig::nonce_pair(&keypair);
			secs.push(s);
			pubs.push(p);
			htlc_keypairs.push(keypair);
		}

		let (revocation_keypair, _) = self.derive_store_next_keypair().await?;

		let revocation_claim_policy = VtxoPolicy::new_pubkey(revocation_keypair.public_key());
		let builder = ArkoorPackageBuilder::new_claim_all_with_checkpoints(
			htlc_vtxos.iter().cloned(),
			revocation_claim_policy,
		)
			.context("Failed to construct arkoor package")?
			.generate_user_nonces(&htlc_keypairs)?;

		let cosign_request = protos::ArkoorPackageCosignRequest::from(
			builder.cosign_request(),
		);

		let response = srv.client
			.request_lightning_pay_htlc_revocation(cosign_request).await
			.context("server failed to cosign arkoor")?.into_inner();

		let cosign_resp = ArkoorPackageCosignResponse::try_from(response)
			.context("Failed to parse cosign response from server")?;

		let vtxos = builder
			.user_cosign(&htlc_keypairs, cosign_resp)
			.context("Failed to cosign vtxos")?
			.build_signed_vtxos();

		let mut revoked = Amount::ZERO;
		for vtxo in &vtxos {
			debug!("Got revocation VTXO: {}: {}", vtxo.id(), vtxo.amount());
			revoked += vtxo.amount();
		}

		let count = vtxos.len();
		let effective = -payment.amount.to_signed()? - payment.fee.to_signed()? + revoked.to_signed()?;
		if effective != SignedAmount::ZERO {
			warn!("Movement {} should have fee of zero, but got {}: amount = {}, fee = {}, revoked = {}",
				payment.movement_id, effective, payment.amount, payment.fee, revoked,
			);
		}
		self.movements.finish_movement_with_update(
			payment.movement_id,
			MovementStatus::Failed,
			MovementUpdate::new()
				.effective_balance(effective)
				.fee(effective.unsigned_abs())
				.produced_vtxos(&vtxos)
		).await?;
		self.store_spendable_vtxos(&vtxos).await?;
		self.mark_vtxos_as_spent(&htlc_vtxos).await?;

		self.db.remove_lightning_send(payment.invoice.payment_hash()).await?;

		debug!("Revoked {} HTLC VTXOs", count);

		Ok(())
	}

	/// Processes the result of a lightning payment by checking the preimage sent by the server and
	/// completing the payment if successful.
	///
	/// Note:
	/// - That function cannot return an Error if the server provides a valid preimage, meaning
	/// that if some occur, it is useless to ask for revocation as server wouldn't accept it.
	/// In that case, it is better to keep the payment pending and try again later
	///
	/// # Returns
	///
	/// Returns `Ok(Some(Preimage))` if the payment is successfully completed and a preimage is
	/// received.
	/// Returns `Ok(None)` if preimage is missing, invalid or does not match the payment hash.
	/// Returns an `Err` if an error occurs during the payment completion.
	async fn process_lightning_send_server_preimage(
		&self,
		preimage: Option<Vec<u8>>,
		payment: &LightningSend,
	) -> anyhow::Result<Option<Preimage>> {
		let payment_hash = payment.invoice.payment_hash();
		let preimage_res = preimage
			.context("preimage is missing")
			.map(|p| Ok(Preimage::try_from(p)?))
			.flatten();

		match preimage_res {
			Ok(preimage) if preimage.compute_payment_hash() == payment_hash => {
				info!("Lightning payment succeeded! Preimage: {}. Payment hash: {}",
					preimage.as_hex(), payment.invoice.payment_hash().as_hex());

				// Complete the payment
				self.db.finish_lightning_send(payment_hash, Some(preimage)).await?;
				self.mark_vtxos_as_spent(&payment.htlc_vtxos).await?;
				self.movements.finish_movement_with_update(
					payment.movement_id,
					MovementStatus::Successful,
					MovementUpdate::new().metadata([(
						"payment_preimage".into(),
						serde_json::to_value(preimage).expect("payment preimage can serde"),
					)])
				).await?;

				Ok(Some(preimage))
			},
			_ => {
				error!("Server failed to provide a valid preimage. \
					Payment hash: {}. Preimage result: {:#?}", payment_hash, preimage_res
				);
				Ok(None)
			}
		}
	}

	/// Checks the status of a lightning payment associated with a set of VTXOs, processes the
	/// payment result and optionally takes appropriate actions based on the payment outcome.
	///
	/// # Arguments
	///
	/// * `payment_hash` - The [PaymentHash] identifying the lightning payment.
	/// * `wait`         - If true, asks the server to wait for payment completion (may block longer).
	///
	/// # Returns
	///
	/// Returns `Ok(Some(LightningSend))` with the current payment status.
	/// Returns `Ok(None)` if no lightning send is found for the payment hash.
	/// Returns an `Err` if an error occurs during the process.
	///
	/// # Behavior
	///
	/// - Validates that all HTLC VTXOs share the same invoice, amount and policy.
	/// - Sends a request to the Ark server to check the payment status.
	/// - Depending on the payment status:
	///   - **Failed**: Revokes the associated VTXOs.
	///   - **Pending**: Checks if the HTLC has expired based on the tip height. If expired,
	///     revokes the VTXOs.
	///   - **Complete**: Extracts the payment preimage, logs the payment, registers movement
	///     in the database and returns the payment info.
	pub async fn check_lightning_payment(&self, payment_hash: PaymentHash, wait: bool)
		-> anyhow::Result<Option<LightningSend>>
	{
		trace!("Checking lightning payment status for payment hash: {}", payment_hash);

		// Try to mark this payment as in-flight to prevent concurrent status checks.
		// This prevents race conditions where multiple concurrent calls could both
		// attempt to process success/revocation, leading to duplicate operations.
		{
			let mut inflight = self.inflight_lightning_payments.lock().await;
			if !inflight.insert(payment_hash) {
				bail!("Payment operation already in progress for this invoice");
			}
		}

		let result = self.check_lightning_payment_inner(payment_hash, wait).await;

		// Always remove from inflight set when done
		{
			let mut inflight = self.inflight_lightning_payments.lock().await;
			inflight.remove(&payment_hash);
		}

		result
	}

	/// Internal implementation of lightning payment status check after concurrency check.
	async fn check_lightning_payment_inner(&self, payment_hash: PaymentHash, wait: bool)
		-> anyhow::Result<Option<LightningSend>>
	{
		let (mut srv, _) = self.require_server().await?;

		let payment = self.db.get_lightning_send(payment_hash).await?
			.context("no lightning send found for payment hash")?;

		// If the payment already has a preimage, it was already completed successfully
		if payment.preimage.is_some() {
			trace!("Payment already completed with preimage");
			return Ok(Some(payment));
		}

		if payment.htlc_vtxos.is_empty() {
			bail!("No HTLC VTXOs found for payment");
		}

		let policy = payment.htlc_vtxos.iter()
			.all_same(|v| v.vtxo.policy())
			.ok_or(anyhow::anyhow!("All lightning htlc should have the same policy"))?;

		let policy = policy.as_server_htlc_send().context("VTXO is not an HTLC send")?;
		if policy.payment_hash != payment_hash {
			bail!("Payment hash mismatch");
		}

		let req = protos::CheckLightningPaymentRequest {
			hash: payment_hash.to_vec(),
			wait,
		};
		// NB: we don't early return on server error or bad response because we
		// don't want it to prevent us from revoking or exiting HTLCs if necessary.
		let response = srv.client.check_lightning_payment(req).await
			.map(|r| r.into_inner().payment_status);

		let tip = self.chain.tip().await?;
		let min_vtxo_expiry = payment.htlc_vtxos.iter()
			.map(|v| v.vtxo.expiry_height())
			.min().context("no HTLC VTXOs for expiry check")?;
		let expired = tip > policy.htlc_expiry
			|| tip > min_vtxo_expiry.saturating_sub(self.config().vtxo_refresh_expiry_threshold);

		let should_revoke = match response {
			Ok(Some(PaymentStatus::Success(status))) => {
				let preimage_opt = self.process_lightning_send_server_preimage(
					Some(status.preimage), &payment,
				).await?;

				if preimage_opt.is_some() {
					// Re-fetch from DB to get the updated payment with preimage
					let updated_payment = self.db.get_lightning_send(payment_hash).await?
						.context("payment disappeared from database")?;
					return Ok(Some(updated_payment));
				} else {
					trace!("Server said payment is complete, but has no valid preimage: {:?}", preimage_opt);
					expired
				}
			},
			Ok(Some(PaymentStatus::Failed(_))) => {
				info!("Payment failed, revoking VTXO");
				true
			},
			Ok(Some(PaymentStatus::Pending(_))) => {
				trace!("Payment is still pending");
				expired
			},
			// bad server response or request error
			Ok(None) | Err(_) => expired,
		};

		if should_revoke {
			debug!("Revoking HTLC VTXOs for payment {} (tip: {}, expiry: {})",
				payment_hash, tip, policy.htlc_expiry);

			if let Err(e) = self.process_lightning_revocation(&payment).await {
				warn!("Failed to revoke VTXO: {}", e);

				// if one of the htlc is about to expire, we exit all of them.
				// Maybe we want a different behavior here, but we have to decide whether
				// htlc vtxos revocation is a all or nothing process.
				if tip > min_vtxo_expiry.saturating_sub(self.config().vtxo_refresh_expiry_threshold) {
					warn!("HTLC VTXOs for payment {} are near VTXO expiry, marking to exit", payment_hash);

					let vtxos = payment.htlc_vtxos
						.iter()
						.map(|v| v.vtxo.clone())
						.collect::<Vec<_>>();
					self.exit.write().await.start_exit_for_vtxos(&vtxos).await?;

					let exited = vtxos.iter().map(|v| v.amount()).sum::<Amount>();
					let effective = -payment.amount.to_signed()? - payment.fee.to_signed()? + exited.to_signed()?;
					if effective != SignedAmount::ZERO {
						warn!("Movement {} should have fee of zero, but got {}: amount = {}, fee = {}, exited = {}",
							payment.movement_id, effective, payment.amount, payment.fee, exited,
						);
					}
					self.movements.finish_movement_with_update(
						payment.movement_id,
						MovementStatus::Failed,
						MovementUpdate::new()
							.effective_balance(effective)
							.fee(effective.unsigned_abs())
							.exited_vtxos(&vtxos)
					).await?;
					self.db.finish_lightning_send(payment.invoice.payment_hash(), None).await?;
				}

				return Err(e)
			}
		}

		// Return current payment state from DB (may have been updated by revocation)
		Ok(self.db.get_lightning_send(payment_hash).await?)
	}

	/// Pays a Lightning [Invoice] using Ark VTXOs. This is also an out-of-round payment
	/// so the same [Wallet::send_arkoor_payment] rules apply.
	///
	/// # Returns
	///
	/// Returns the [Invoice] for which payment was initiated.
	pub async fn pay_lightning_invoice<T>(
		&self,
		invoice: T,
		user_amount: Option<Amount>,
	) -> anyhow::Result<LightningSend>
	where
		T: TryInto<Invoice>,
		T::Error: std::error::Error + fmt::Display + Send + Sync + 'static,
	{
		let invoice = invoice.try_into().context("failed to parse invoice")?;
		let amount = invoice.get_payment_amount(user_amount)?;
		info!("Sending bolt11 payment of {} to invoice {}", amount, invoice);
		self.make_lightning_payment(&invoice, invoice.clone().into(), user_amount).await
	}

	/// Same as [Wallet::pay_lightning_invoice] but instead it pays a [LightningAddress].
	pub async fn pay_lightning_address(
		&self,
		addr: &LightningAddress,
		amount: Amount,
		comment: Option<impl AsRef<str>>,
	) -> anyhow::Result<LightningSend> {
		let comment = comment.as_ref();
		let invoice = lnaddr_invoice(addr, amount, comment).await
			.context("lightning address error")?;
		info!("Sending {} to lightning address {}", amount, addr);
		let ret = self.make_lightning_payment(&invoice.into(), addr.clone().into(), None).await
			.context("bolt11 payment error")?;
		info!("Paid invoice {}", ret.invoice);
		Ok(ret)
	}

	/// Attempts to pay the given BOLT12 [Offer] using offchain funds.
	pub async fn pay_lightning_offer(
		&self,
		offer: Offer,
		user_amount: Option<Amount>,
	) -> anyhow::Result<LightningSend> {
		let (mut srv, _) = self.require_server().await?;

		let offer_bytes = {
			let mut bytes = Vec::new();
			offer.write(&mut bytes).context("failed to serialize BOLT12 offer")?;
			bytes
		};

		let req = protos::FetchBolt12InvoiceRequest {
			offer: offer_bytes,
			amount_sat: user_amount.map(|a| a.to_sat()),
		};

		if let Some(amt) = user_amount {
			info!("Sending bolt12 payment of {} (user amount) to offer {}", amt, offer);
		} else if let Some(amt) = offer.amount() {
			info!("Sending bolt12 payment of {:?} (invoice amount) to offer {}", amt, offer);
		} else {
			warn!("Paying offer without amount nor user amount provided: {}", offer);
		}

		let resp = srv.client.fetch_bolt12_invoice(req).await?.into_inner();
		let invoice = Bolt12Invoice::try_from(resp.invoice)
			.map_err(|e| anyhow!("invalid invoice: {:?}", e))?;

		invoice.validate_issuance(&offer)
			.context("invalid BOLT12 invoice received from offer")?;

		let ret = self.make_lightning_payment(&invoice.into(), offer.into(), None).await
			.context("bolt12 payment error")?;
		info!("Paid invoice: {}", ret.invoice.to_string());

		Ok(ret)
	}

	/// Makes a payment using the Lightning Network. This is a low-level primitive to allow for
	/// more fine-grained control over the payment process. The primary purpose of using this method
	/// is to support [PaymentMethod::Custom] for other payment use cases such as LNURL-Pay.
	///
	/// It's recommended to use the following higher-level functions where suitable:
	/// - BOLT11: [Wallet::pay_lightning_invoice]
	/// - BOLT12: [Wallet::pay_lightning_offer]
	/// - Lightning Address: [Wallet::pay_lightning_address]
	///
	/// # Parameters
	/// - `invoice`: A reference to the BOLT11/BOLT12 invoice to be paid.
	/// - `original_payment_method`: The payment method that the given invoice was originally
	///   derived from (e.g., BOLT11, an offer, lightning address). This will appear in the stored
	///   [Movement](crate::movement::Movement).
	/// - `user_amount`: An optional custom amount to override the amount specified in the invoice.
	///   If not provided, the invoice's amount is used.
	///
	/// # Returns
	/// Returns a `LightningSend` representing the successful payment.
	/// If an error occurs during the process, an `anyhow::Error` is returned.
	///
	/// # Errors
	/// This function can return an error for the following reasons:
	/// - If the given payment method is not either an officially supported lightning payment method
	///   or [PaymentMethod::Custom].
	/// - The `invoice` belongs to a different network than the one configured in the server's
	///   properties.
	/// - The `invoice` has already been paid (the payment hash exists in the database).
	/// - The `invoice` contains an invalid or tampered signature.
	/// - The wallet doesn't have enough funds to cover the payment.
	/// - Validation, signing, server or network issues occur.
	///
	/// # Notes
	/// - A movement won't be recorded until we receive an intermediary HTLC VTXO.
	/// - This is effectively an arkoor payment with an additional HTLC conversion step, so the
	///   same [Wallet::send_arkoor_payment] rules apply.
	pub async fn make_lightning_payment(
		&self,
		invoice: &Invoice,
		original_payment_method: PaymentMethod,
		user_amount: Option<Amount>,
	) -> anyhow::Result<LightningSend> {
		if !original_payment_method.is_lightning() && !original_payment_method.is_custom() {
			bail!("Invalid original payment method for lightning payment");
		}

		let payment_hash = invoice.payment_hash();

		// Try to mark this payment as in-flight to prevent concurrent attempts.
		// This prevents a race condition where multiple concurrent calls could all pass
		// the DB check below before any of them complete, leading to orphaned state.
		{
			let mut inflight = self.inflight_lightning_payments.lock().await;
			if !inflight.insert(payment_hash) {
				bail!("Payment already in progress for this invoice");
			}
		}

		// Execute the payment, ensuring we remove from inflight set on any exit path
		let result = self.make_lightning_payment_inner(
			invoice, original_payment_method, user_amount, payment_hash
		).await;

		// Always remove from inflight set when done
		{
			let mut inflight = self.inflight_lightning_payments.lock().await;
			inflight.remove(&payment_hash);
		}

		result
	}

	/// Internal implementation of lightning payment after concurrency check.
	async fn make_lightning_payment_inner(
		&self,
		invoice: &Invoice,
		original_payment_method: PaymentMethod,
		user_amount: Option<Amount>,
		payment_hash: PaymentHash,
	) -> anyhow::Result<LightningSend> {
		let (mut srv, ark_info) = self.require_server().await?;

		let tip = self.chain.tip().await?;

		let properties = self.db.read_properties().await?.context("Missing config")?;
		if invoice.network() != properties.network {
			bail!("Invoice is for wrong network: {}", invoice.network());
		}

		let lightning_send = self.db.get_lightning_send(payment_hash).await?;
		if lightning_send.is_some() {
			bail!("Invoice has already been paid");
		}

		invoice.check_signature()?;

		let payment_amount = invoice.get_payment_amount(user_amount)?;
		if payment_amount == Amount::ZERO {
			bail!("Cannot pay invoice for 0 sats (0 sat invoices are not any-amount invoices)");
		}

		let (change_keypair, _) = self.derive_store_next_keypair().await?;

		let (inputs, fee) = self.select_vtxos_to_cover_with_fee(
			payment_amount, |a, v| ark_info.fees.lightning_send.calculate(a, v).context("fee overflowed"),
		).await.context("Could not find enough suitable VTXOs to cover lightning payment")?;
		let total_amount = payment_amount + fee;

		let mut secs = Vec::with_capacity(inputs.len());
		let mut pubs = Vec::with_capacity(inputs.len());
		let mut input_keypairs = Vec::with_capacity(inputs.len());
		let mut input_ids = Vec::with_capacity(inputs.len());
		for input in inputs.iter() {
			let keypair = self.get_vtxo_key(input).await?;
			let (s, p) = musig::nonce_pair(&keypair);
			secs.push(s);
			pubs.push(p);
			input_keypairs.push(keypair);
			input_ids.push(input.id());
		}

		let expiry = tip + ark_info.htlc_send_expiry_delta as BlockHeight;
		let policy = VtxoPolicy::new_server_htlc_send(
			change_keypair.public_key(), invoice.payment_hash(), expiry,
		);

		let input_amount = inputs.iter().map(|v| v.amount()).sum::<Amount>();
		let pay_dest = ArkoorDestination { total_amount, policy };
		let outputs = if input_amount == total_amount {
			vec![pay_dest]
		} else {
			let change_dest = ArkoorDestination {
				total_amount: input_amount - total_amount,
				policy: VtxoPolicy::new_pubkey(change_keypair.public_key()),
			};
			vec![pay_dest, change_dest]
		};
		let builder = ArkoorPackageBuilder::new_with_checkpoints(
			inputs.iter().map(|v| &v.vtxo).cloned(),
			outputs,
		)
			.context("Failed to construct arkoor package")?
			.generate_user_nonces(&input_keypairs)
			.context("invalid nb of keypairs")?;

		let package_cosign_request = protos::ArkoorPackageCosignRequest::from(
			builder.cosign_request(),
		);
		let cosign_request = protos::LightningPayHtlcCosignRequest {
			parts: package_cosign_request.parts,
		};

		let response = srv.client.request_lightning_pay_htlc_cosign(cosign_request).await
			.context("htlc request failed")?.into_inner();

		let cosign_responses = ArkoorPackageCosignResponse::try_from(response)
			.context("Failed to parse cosign response from server")?;

		let vtxos = builder
			.user_cosign(&input_keypairs, cosign_responses)
			.context("Failed to cosign vtxos")?
			.build_signed_vtxos();

		let (htlc_vtxos, change_vtxos) = vtxos.into_iter()
			.partition::<Vec<_>, _>(|v| matches!(v.policy(), VtxoPolicy::ServerHtlcSend(_)));

		// Validate the new vtxos. They have the same chain anchor.
		let mut effective_balance = Amount::ZERO;
		for vtxo in &htlc_vtxos {
			self.validate_vtxo(vtxo).await?;
			effective_balance += vtxo.amount();
		}

		let movement_id = self.movements.new_movement_with_update(
			Subsystem::LIGHTNING_SEND,
			LightningSendMovement::Send.to_string(),
			MovementUpdate::new()
				.intended_balance(-payment_amount.to_signed()?)
				.effective_balance(-effective_balance.to_signed()?)
				.fee(fee)
				.consumed_vtxos(&inputs)
				.sent_to([MovementDestination::new(original_payment_method, payment_amount)])
				.metadata(LightningMovement::metadata(invoice.payment_hash(), &htlc_vtxos, None))
		).await?;
		self.store_locked_vtxos(&htlc_vtxos, Some(movement_id)).await?;
		self.mark_vtxos_as_spent(&input_ids).await?;

		// Validate the change vtxo. It has the same chain anchor as the last input.
		for change in &change_vtxos {
			let last_input = inputs.last().context("no inputs provided")?;
			let tx = self.chain.get_tx(&last_input.chain_anchor().txid).await?;
			let tx = tx.with_context(|| {
				format!("input vtxo chain anchor not found for lightning change vtxo: {}", last_input.chain_anchor().txid)
			})?;
			change.validate(&tx).context("invalid lightning change vtxo")?;
			self.store_spendable_vtxos([change]).await?;
		}

		self.movements.update_movement(
			movement_id,
			MovementUpdate::new()
				.produced_vtxos(change_vtxos)
				.metadata(LightningMovement::metadata(invoice.payment_hash(), &htlc_vtxos, None))
		).await?;

		let lightning_send = self.db.store_new_pending_lightning_send(
			&invoice,
			payment_amount,
			fee,
			&htlc_vtxos.iter().map(|v| v.id()).collect::<Vec<_>>(),
			movement_id,
		).await?;

		// Register HTLC VTXOs with server before initiating payment
		self.register_vtxos_with_server(&htlc_vtxos).await?;

		let req = protos::InitiateLightningPaymentRequest {
			invoice: invoice.to_string(),
			htlc_vtxo_ids: htlc_vtxos.iter().map(|v| v.id().to_bytes().to_vec()).collect(),
			payment_amount_sat: payment_amount.to_sat(),
		};

		srv.client.initiate_lightning_payment(req).await?;

		Ok(lightning_send)
	}
}