Skip to main content

bark/lightning/
pay.rs

1use std::fmt;
2
3use anyhow::Context;
4use bitcoin::Amount;
5use lightning::util::ser::Writeable;
6use lnurllib::lightning_address::LightningAddress;
7use log::{info, warn};
8use server_rpc::protos;
9
10use ark::lightning::{Bolt12Invoice, Bolt12InvoiceExt, Invoice, Offer, PaymentHash, Preimage};
11
12use crate::Wallet;
13use crate::WalletVtxo;
14use crate::actions::DriveMode;
15use crate::actions::lightning::pay::ln_pay_action_id;
16use crate::actions::lightning::pay::{
17	Htlcs, LightningSend, LightningSendState, Progress, settle_lightning_send_payment,
18	start_lightning_send,
19};
20use crate::lightning::lnaddr_invoice;
21use crate::movement::PaymentMethod;
22
23impl Wallet {
24	/// Returns every in-progress lightning send checkpoint.
25	pub async fn pending_lightning_sends(&self) -> anyhow::Result<Vec<LightningSend>> {
26		let mut result = Vec::new();
27		for cp in self.inner.db.get_all_wallet_action_checkpoints().await? {
28			if let Some(ls) = cp.into_lightning_send() {
29				result.push(ls);
30			}
31		}
32		Ok(result)
33	}
34
35	/// Returns the VTXOs currently held by any in-progress lightning send.
36	pub async fn pending_lightning_send_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
37		let mut vtxos = Vec::new();
38		for send in self.pending_lightning_sends().await? {
39			let ids: Vec<_> = match &send.progress {
40				Progress::Start => send.input_vtxo_ids.clone(),
41				Progress::HtlcReceived(h) => h.vtxo_ids.clone(),
42				Progress::PaymentInitiated(h) => h.vtxo_ids.clone(),
43				Progress::RevocableHtlcs { htlcs, .. } => htlcs.vtxo_ids.clone(),
44			};
45			for id in ids {
46				vtxos.push(self.get_vtxo_by_id(id).await?);
47			}
48		}
49		Ok(vtxos)
50	}
51
52	/// Drives every pending lightning send forward by one step (or to
53	/// completion if it's ready). Each action runs to its next park
54	/// independently; errors on one don't stop the others.
55	pub async fn sync_pending_lightning_send_vtxos(&self) -> anyhow::Result<()> {
56		let pending = self.pending_lightning_sends().await?;
57		if pending.is_empty() {
58			return Ok(());
59		}
60		info!("Syncing {} pending lightning sends", pending.len());
61		for send in pending {
62			let id = send.id();
63			if let Err(e) = self.drive_action(send, DriveMode::UntilParkOrDone).await {
64				warn!("Failed to sync lightning send {}: {:#}", id, e);
65			}
66		}
67		Ok(())
68	}
69
70	/// Fetches the current checkpoint for the given payment hash, if any.
71	pub async fn lightning_send_checkpoint(&self, hash: PaymentHash)
72		-> anyhow::Result<Option<LightningSend>>
73	{
74		Ok(self.inner.db.get_wallet_action_checkpoint(&ln_pay_action_id(hash)).await?
75			.and_then(|cp| cp.into_lightning_send()))
76	}
77
78	/// Triage a payment hash: paid, in-progress, or unknown.
79	pub async fn lightning_send_state(&self, hash: PaymentHash)
80		-> anyhow::Result<LightningSendState>
81	{
82		if let Some(paid) = self.inner.db.get_paid_invoice(hash).await? {
83			return Ok(LightningSendState::Paid(paid));
84		}
85		if let Some(cp) = self.lightning_send_checkpoint(hash).await? {
86			return Ok(LightningSendState::InProgress(cp));
87		}
88		Ok(LightningSendState::Unknown)
89	}
90
91	/// Cheap "has this invoice ever been paid?" check.
92	pub async fn is_invoice_paid(&self, hash: PaymentHash) -> anyhow::Result<bool> {
93		Ok(self.inner.db.get_paid_invoice(hash).await?.is_some())
94	}
95
96	/// Drive a lightning send forward (e.g., to settle a pending one
97	/// or revoke a failed one). `wait=true` keeps driving past parks
98	/// until the action terminates. Returns the current state.
99	pub async fn check_lightning_payment(&self, hash: PaymentHash, wait: bool)
100		-> anyhow::Result<LightningSendState>
101	{
102		let send = match self.lightning_send_state(hash).await? {
103			LightningSendState::InProgress(s) => s,
104			s => return Ok(s),
105		};
106
107		let mode = if wait { DriveMode::UntilDone } else { DriveMode::UntilParkOrDone };
108		self.drive_action(send, mode).await?;
109		self.lightning_send_state(hash).await
110	}
111
112	/// Settle a payment using a preimage we already have (e.g. from a
113	/// mailbox notification), skipping the server poll.
114	pub(crate) async fn settle_lightning_send_with_preimage(
115		&self,
116		send: LightningSend,
117		htlcs: Htlcs,
118		preimage: Preimage,
119	) -> anyhow::Result<()> {
120		let payment_hash = send.invoice.payment_hash();
121		if preimage.compute_payment_hash() != payment_hash {
122			bail!("preimage mismatch for payment hash {}", payment_hash);
123		}
124		settle_lightning_send_payment(self, &send, &htlcs, preimage).await?;
125		// Remove the in-progress row now that the paid_invoice record
126		// is the source of truth.
127		self.inner.db.remove_wallet_action_checkpoint(&ln_pay_action_id(payment_hash)).await?;
128		Ok(())
129	}
130
131	/// Pays a Lightning [Invoice] using Ark VTXOs.
132	///
133	/// `wait=true` keeps the call open until the payment settles or
134	/// fails; `wait=false` returns once the payment has been kicked off
135	/// and lets the background sync drive it to completion. Returns the
136	/// parsed [`Invoice`] in either case; callers wanting the preimage
137	/// can look up the settled record via [`Self::lightning_send_state`].
138	pub async fn pay_lightning_invoice<T>(
139		&self,
140		invoice: T,
141		user_amount: Option<Amount>,
142		wait: bool,
143	) -> anyhow::Result<Invoice>
144	where
145		T: TryInto<Invoice>,
146		T::Error: std::error::Error + fmt::Display + Send + Sync + 'static,
147	{
148		let invoice = invoice.try_into().context("failed to parse invoice")?;
149		let amount = invoice.get_payment_amount(user_amount)?;
150		info!("Sending bolt11 payment of {} to invoice {}", amount, invoice);
151		self.make_lightning_payment(&invoice, invoice.clone().into(), user_amount, wait).await?;
152		Ok(invoice)
153	}
154
155	/// Same as [`Self::pay_lightning_invoice`] but resolves the invoice
156	/// from a [`LightningAddress`] first.
157	pub async fn pay_lightning_address(
158		&self,
159		addr: &LightningAddress,
160		amount: Amount,
161		comment: Option<impl AsRef<str>>,
162		wait: bool,
163	) -> anyhow::Result<Invoice> {
164		let comment = comment.as_ref();
165		let invoice: Invoice = lnaddr_invoice(addr, amount, comment).await
166			.context("lightning address error")?.into();
167		info!("Sending {} to lightning address {}", amount, addr);
168		self.make_lightning_payment(&invoice, addr.clone().into(), None, wait).await?;
169		info!("Paid invoice {}", invoice);
170		Ok(invoice)
171	}
172
173	/// Attempts to pay the given BOLT12 [`Offer`] using offchain funds.
174	pub async fn pay_lightning_offer(
175		&self,
176		offer: Offer,
177		user_amount: Option<Amount>,
178		wait: bool,
179	) -> anyhow::Result<Invoice> {
180		let (mut srv, _) = self.require_server().await?;
181
182		let offer_bytes = {
183			let mut bytes = Vec::new();
184			offer.write(&mut bytes).context("failed to serialize BOLT12 offer")?;
185			bytes
186		};
187
188		let req = protos::FetchBolt12InvoiceRequest {
189			offer: offer_bytes,
190			amount_sat: user_amount.map(|a| a.to_sat()),
191		};
192
193		if let Some(amt) = user_amount {
194			info!("Sending bolt12 payment of {} (user amount) to offer {}", amt, offer);
195		} else if let Some(amt) = offer.amount() {
196			info!("Sending bolt12 payment of {:?} (invoice amount) to offer {}", amt, offer);
197		} else {
198			warn!("Paying offer without amount nor user amount provided: {}", offer);
199		}
200
201		let resp = srv.client.fetch_bolt12_invoice(req).await?.into_inner();
202		let invoice = Bolt12Invoice::try_from(resp.invoice)
203			.map_err(|e| anyhow!("invalid invoice: {:?}", e))?;
204
205		invoice.validate_issuance(&offer)
206			.context("invalid BOLT12 invoice received from offer")?;
207
208		let invoice: Invoice = invoice.into();
209		self.make_lightning_payment(&invoice, offer.into(), None, wait).await?;
210		info!("Paid invoice: {}", invoice);
211		Ok(invoice)
212	}
213
214	/// Low-level lightning payment primitive. Exposed for
215	/// [`PaymentMethod::Custom`] use cases (e.g. LNURL-pay).
216	pub async fn make_lightning_payment(
217		&self,
218		invoice: &Invoice,
219		original_payment_method: PaymentMethod,
220		user_amount: Option<Amount>,
221		wait: bool,
222	) -> anyhow::Result<()> {
223		if !original_payment_method.is_lightning() && !original_payment_method.is_custom() {
224			bail!("Invalid original payment method for lightning payment");
225		}
226
227		let payment_hash = invoice.payment_hash();
228		let mode = if wait { DriveMode::UntilDone } else { DriveMode::UntilParkOrDone };
229
230		if self.is_invoice_paid(payment_hash).await? {
231			bail!("Invoice has already been paid");
232		}
233
234		let key = ln_pay_action_id(payment_hash);
235		let guard = self.inner.lock_manager.try_lock(&key).await
236			.context("Payment operation already in progress for this invoice")?;
237
238		// Resume an existing checkpoint, or build a fresh send.
239		let action = match self.lightning_send_checkpoint(payment_hash).await? {
240			Some(existing) => existing,
241			None => {
242				let start = start_lightning_send(
243					self, invoice.clone(), user_amount, original_payment_method,
244				).await?;
245
246				self.inner.db.upsert_wallet_action_checkpoint(
247					&start.id(), &start.clone().into()
248				).await?;
249
250				start
251			},
252		};
253
254		self.drive_action_with_guard(action, mode, guard).await
255	}
256}