1use bitcoin::hashes::sha256;
2use fedimint_api_client::api::ServerError;
3use fedimint_client_module::DynGlobalClientContext;
4use fedimint_client_module::sm::{ClientSMDatabaseTransaction, State, StateTransition};
5use fedimint_client_module::transaction::{ClientInput, ClientInputBundle};
6use fedimint_core::config::FederationId;
7use fedimint_core::core::OperationId;
8use fedimint_core::encoding::{Decodable, Encodable};
9use fedimint_core::module::Amounts;
10use fedimint_core::util::SafeUrl;
11use fedimint_core::util::backoff_util::api_networking_backoff;
12use fedimint_core::{OutPoint, TransactionId, crit, secp256k1, util};
13use fedimint_lnv2_common::contracts::OutgoingContract;
14use fedimint_lnv2_common::{LightningInput, LightningInputV0, OutgoingWitness};
15use fedimint_logging::LOG_CLIENT_MODULE_LNV2;
16use futures::future::pending;
17use secp256k1::Keypair;
18use secp256k1::schnorr::Signature;
19use tracing::instrument;
20
21use crate::api::LightningFederationApi;
22use crate::events::{SendPaymentStatus, SendPaymentUpdateEvent};
23use crate::{LightningClientContext, LightningInvoice};
24
25#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
26pub struct SendStateMachine {
27 pub common: SendSMCommon,
28 pub state: SendSMState,
29}
30
31impl SendStateMachine {
32 pub fn update(&self, state: SendSMState) -> Self {
33 Self {
34 common: self.common.clone(),
35 state,
36 }
37 }
38}
39
40#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
41pub struct SendSMCommon {
42 pub operation_id: OperationId,
43 pub outpoint: OutPoint,
44 pub contract: OutgoingContract,
45 pub gateway_api: Option<SafeUrl>,
46 pub invoice: Option<LightningInvoice>,
47 pub refund_keypair: Keypair,
48}
49
50#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
51pub enum SendSMState {
52 Funding,
53 Funded,
54 Rejected(String),
55 Success([u8; 32]),
56 Refunding(Vec<OutPoint>),
57}
58
59async fn send_update_event(
60 context: LightningClientContext,
61 global_context: &DynGlobalClientContext,
62 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
63 operation_id: OperationId,
64 status: SendPaymentStatus,
65) {
66 let account = global_context.account(dbtx).await;
67
68 context
69 .client_ctx
70 .log_event(
71 &mut dbtx.module_tx(),
72 SendPaymentUpdateEvent {
73 operation_id,
74 status,
75 account,
76 },
77 )
78 .await;
79}
80
81impl State for SendStateMachine {
96 type ModuleContext = LightningClientContext;
97
98 fn transitions(
99 &self,
100 context: &Self::ModuleContext,
101 global_context: &DynGlobalClientContext,
102 ) -> Vec<StateTransition<Self>> {
103 let c_pay = context.clone();
104 let gc_pay = global_context.clone();
105 let c_preimage = context.clone();
106 let gc_preimage = global_context.clone();
107
108 match &self.state {
109 SendSMState::Funding => {
110 vec![StateTransition::new(
111 Self::await_funding(global_context.clone(), self.common.outpoint.txid),
112 move |_, error, old_state| {
113 Box::pin(async move { Self::transition_funding(error, &old_state) })
114 },
115 )]
116 }
117 SendSMState::Funded => {
118 vec![
119 StateTransition::new(
120 Self::gateway_send_payment(
121 self.common.gateway_api.clone().unwrap(),
122 context.federation_id,
123 self.common.outpoint,
124 self.common.contract.clone(),
125 self.common.invoice.clone().unwrap(),
126 self.common.refund_keypair,
127 context.clone(),
128 ),
129 move |dbtx, response, old_state| {
130 Box::pin(Self::transition_gateway_send_payment(
131 c_pay.clone(),
132 gc_pay.clone(),
133 dbtx,
134 response,
135 old_state,
136 ))
137 },
138 ),
139 StateTransition::new(
140 Self::await_preimage(
141 self.common.outpoint,
142 self.common.contract.clone(),
143 gc_preimage.clone(),
144 ),
145 move |dbtx, preimage, old_state| {
146 Box::pin(Self::transition_preimage(
147 c_preimage.clone(),
148 dbtx,
149 gc_preimage.clone(),
150 old_state,
151 preimage,
152 ))
153 },
154 ),
155 ]
156 }
157 SendSMState::Refunding(..) | SendSMState::Success(..) | SendSMState::Rejected(..) => {
158 vec![]
159 }
160 }
161 }
162
163 fn operation_id(&self) -> OperationId {
164 self.common.operation_id
165 }
166}
167
168impl SendStateMachine {
169 async fn await_funding(
170 global_context: DynGlobalClientContext,
171 txid: TransactionId,
172 ) -> Result<(), String> {
173 global_context.await_tx_accepted(txid).await
174 }
175
176 fn transition_funding(
177 result: Result<(), String>,
178 old_state: &SendStateMachine,
179 ) -> SendStateMachine {
180 match result {
181 Ok(()) => old_state.update(SendSMState::Funded),
182 Err(error) => old_state.update(SendSMState::Rejected(error)),
183 }
184 }
185
186 #[instrument(target = LOG_CLIENT_MODULE_LNV2, skip(refund_keypair, context))]
187 async fn gateway_send_payment(
188 gateway_api: SafeUrl,
189 federation_id: FederationId,
190 outpoint: OutPoint,
191 contract: OutgoingContract,
192 invoice: LightningInvoice,
193 refund_keypair: Keypair,
194 context: LightningClientContext,
195 ) -> Result<[u8; 32], Signature> {
196 util::retry("gateway-send-payment", api_networking_backoff(), || async {
197 let payment_result = context
198 .gateway_conn
199 .send_payment(
200 gateway_api.clone(),
201 federation_id,
202 outpoint,
203 contract.clone(),
204 invoice.clone(),
205 refund_keypair.sign_schnorr(secp256k1::Message::from_digest(
206 *invoice.consensus_hash::<sha256::Hash>().as_ref(),
207 )),
208 )
209 .await?;
210
211 if !contract.verify_gateway_response(&payment_result) {
212 return Err(SendPaymentAttemptError::InvalidResponse(payment_result));
213 }
214
215 Ok(payment_result)
216 })
217 .await
218 .expect("Number of retries has no limit")
219 }
220
221 async fn transition_gateway_send_payment(
222 context: LightningClientContext,
223 global_context: DynGlobalClientContext,
224 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
225 gateway_response: Result<[u8; 32], Signature>,
226 old_state: SendStateMachine,
227 ) -> SendStateMachine {
228 match gateway_response {
229 Ok(preimage) => {
230 send_update_event(
231 context,
232 &global_context,
233 dbtx,
234 old_state.common.operation_id,
235 SendPaymentStatus::Success(preimage),
236 )
237 .await;
238
239 old_state.update(SendSMState::Success(preimage))
240 }
241 Err(signature) => {
242 let client_input = ClientInput::<LightningInput> {
243 input: LightningInput::V0(LightningInputV0::Outgoing(
244 old_state.common.outpoint,
245 OutgoingWitness::Cancel(signature),
246 )),
247 amounts: Amounts::new_bitcoin(old_state.common.contract.amount),
248 keys: vec![old_state.common.refund_keypair],
249 };
250
251 let change_range = global_context
252 .claim_inputs(
253 dbtx,
254 ClientInputBundle::new_no_sm(vec![client_input]),
256 )
257 .await
258 .expect("Cannot claim input, additional funding needed");
259
260 send_update_event(
261 context,
262 &global_context,
263 dbtx,
264 old_state.common.operation_id,
265 SendPaymentStatus::Refunded,
266 )
267 .await;
268
269 old_state.update(SendSMState::Refunding(change_range.into_iter().collect()))
270 }
271 }
272 }
273
274 #[instrument(target = LOG_CLIENT_MODULE_LNV2, skip(global_context))]
275 async fn await_preimage(
276 outpoint: OutPoint,
277 contract: OutgoingContract,
278 global_context: DynGlobalClientContext,
279 ) -> Option<[u8; 32]> {
280 let preimage = global_context
281 .module_api()
282 .await_preimage(outpoint, contract.expiration)
283 .await?;
284
285 if contract.verify_preimage(&preimage) {
286 return Some(preimage);
287 }
288
289 crit!(target: LOG_CLIENT_MODULE_LNV2, "Federation returned invalid preimage {:?}", preimage);
290
291 pending().await
292 }
293
294 async fn transition_preimage(
295 context: LightningClientContext,
296 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
297 global_context: DynGlobalClientContext,
298 old_state: SendStateMachine,
299 preimage: Option<[u8; 32]>,
300 ) -> SendStateMachine {
301 if let Some(preimage) = preimage {
302 send_update_event(
303 context,
304 &global_context,
305 dbtx,
306 old_state.common.operation_id,
307 SendPaymentStatus::Success(preimage),
308 )
309 .await;
310
311 return old_state.update(SendSMState::Success(preimage));
312 }
313
314 let client_input = ClientInput::<LightningInput> {
315 input: LightningInput::V0(LightningInputV0::Outgoing(
316 old_state.common.outpoint,
317 OutgoingWitness::Refund,
318 )),
319 amounts: Amounts::new_bitcoin(old_state.common.contract.amount),
320 keys: vec![old_state.common.refund_keypair],
321 };
322
323 let change_range = global_context
324 .claim_inputs(dbtx, ClientInputBundle::new_no_sm(vec![client_input]))
325 .await
326 .expect("Cannot claim input, additional funding needed");
327
328 send_update_event(
329 context,
330 &global_context,
331 dbtx,
332 old_state.common.operation_id,
333 SendPaymentStatus::Refunded,
334 )
335 .await;
336
337 old_state.update(SendSMState::Refunding(change_range.into_iter().collect()))
338 }
339}
340
341#[derive(Debug, thiserror::Error)]
344enum SendPaymentAttemptError {
345 #[error(transparent)]
347 Gateway(#[from] ServerError),
348
349 #[error("Invalid gateway response: {0:?}")]
352 InvalidResponse(Result<[u8; 32], Signature>),
353}