1use std::fmt;
2
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::secp256k1::Keypair;
11use fedimint_core::time::duration_since_epoch;
12use fedimint_core::util::FmtCompact as _;
13use fedimint_core::{Amount, OutPoint};
14use fedimint_lnv2_common::contracts::OutgoingContract;
15use fedimint_lnv2_common::{LightningInput, LightningInputV0, LightningInvoice, OutgoingWitness};
16use serde::{Deserialize, Serialize};
17
18use super::FinalReceiveState;
19use super::events::{OutgoingPaymentFailed, OutgoingPaymentSucceeded};
20use crate::{GatewayClientContextV2, GatewayClientModuleV2};
21
22#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
23pub struct SendStateMachine {
24 pub common: SendSMCommon,
25 pub state: SendSMState,
26}
27
28impl SendStateMachine {
29 pub fn update(&self, state: SendSMState) -> Self {
30 Self {
31 common: self.common.clone(),
32 state,
33 }
34 }
35}
36
37impl fmt::Display for SendStateMachine {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 write!(
40 f,
41 "Send State Machine Operation ID: {:?} State: {}",
42 self.common.operation_id, self.state
43 )
44 }
45}
46
47#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
48pub struct SendSMCommon {
49 pub operation_id: OperationId,
50 pub outpoint: OutPoint,
51 pub contract: OutgoingContract,
52 pub max_delay: u64,
53 pub min_contract_amount: Amount,
54 pub invoice: LightningInvoice,
55 pub claim_keypair: Keypair,
56}
57
58#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
59pub enum SendSMState {
60 Sending,
61 Claiming(Claiming),
62 Cancelled(Cancelled),
63}
64
65#[derive(Debug, Serialize, Deserialize)]
66pub struct PaymentResponse {
67 preimage: [u8; 32],
68 target_federation: Option<FederationId>,
69}
70
71impl fmt::Display for SendSMState {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 match self {
74 SendSMState::Sending => write!(f, "Sending"),
75 SendSMState::Claiming(_) => write!(f, "Claiming"),
76 SendSMState::Cancelled(_) => write!(f, "Cancelled"),
77 }
78 }
79}
80
81#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
82pub struct Claiming {
83 pub preimage: [u8; 32],
84 pub outpoints: Vec<OutPoint>,
85}
86
87#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable, Serialize, Deserialize)]
88pub enum Cancelled {
89 InvoiceExpired,
90 TimeoutTooClose,
91 Underfunded,
92 RegistrationError(String),
93 FinalizationError(String),
94 Rejected,
95 Refunded,
96 Failure,
97 LightningRpcError(String),
98 DuplicatePayment,
99}
100
101impl State for SendStateMachine {
111 type ModuleContext = GatewayClientContextV2;
112
113 fn transitions(
114 &self,
115 context: &Self::ModuleContext,
116 global_context: &DynGlobalClientContext,
117 ) -> Vec<StateTransition<Self>> {
118 let gc = global_context.clone();
119 let gateway_context = context.clone();
120
121 match &self.state {
122 SendSMState::Sending => {
123 vec![StateTransition::new(
124 Self::send_payment(context.clone(), self.common.clone()),
125 move |dbtx, result, old_state| {
126 Box::pin(Self::transition_send_payment(
127 dbtx,
128 old_state,
129 gc.clone(),
130 result,
131 gateway_context.clone(),
132 ))
133 },
134 )]
135 }
136 SendSMState::Claiming(..) | SendSMState::Cancelled(..) => {
137 vec![]
138 }
139 }
140 }
141
142 fn operation_id(&self) -> OperationId {
143 self.common.operation_id
144 }
145}
146
147impl SendStateMachine {
148 async fn send_payment(
149 context: GatewayClientContextV2,
150 common: SendSMCommon,
151 ) -> Result<PaymentResponse, Cancelled> {
152 let SendSMCommon {
153 operation_id: _,
154 outpoint,
155 contract,
156 max_delay,
157 min_contract_amount,
158 invoice,
159 claim_keypair: _,
160 } = common;
161 let LightningInvoice::Bolt11(invoice) = invoice;
162
163 if max_delay == 0 {
169 return Err(Cancelled::TimeoutTooClose);
170 }
171
172 let Some(max_fee) = contract.amount.checked_sub(min_contract_amount) else {
173 return Err(Cancelled::Underfunded);
174 };
175
176 context.gateway.await_lightning_connected().await;
186 let fresh_max_delay = context
187 .module
188 .await_outgoing_contract_max_delay(outpoint)
189 .await;
190
191 let fresh_dispatch_refusal = fresh_dispatch_refusal(
200 invoice.would_expire(duration_since_epoch()),
201 fresh_max_delay,
202 );
203
204 if let Some(client) = context.gateway.is_lnv1_invoice(&invoice).await {
209 let final_state = context
210 .gateway
211 .relay_lnv1_swap(client.value(), &invoice, fresh_dispatch_refusal.is_none())
212 .await;
213 return match final_state {
214 Ok(Some(final_receive_state)) => match final_receive_state {
215 FinalReceiveState::Rejected => Err(Cancelled::Rejected),
216 FinalReceiveState::Success(preimage) => Ok(PaymentResponse {
217 preimage,
218 target_federation: Some(client.value().federation_id()),
219 }),
220 FinalReceiveState::Refunded => Err(Cancelled::Refunded),
221 FinalReceiveState::Failure => Err(Cancelled::Failure),
222 },
223 Ok(None) => Err(fresh_dispatch_refusal
224 .expect("the relay only refuses a fresh dispatch when one was denied")),
225 Err(e) => Err(Cancelled::FinalizationError(e.fmt_compact().to_string())),
226 };
227 }
228
229 match context
230 .gateway
231 .is_direct_swap(&invoice)
232 .await
233 .map_err(|e| Cancelled::RegistrationError(e.fmt_compact().to_string()))?
234 {
235 Some((contract, client)) => {
236 match client
237 .get_first_module::<GatewayClientModuleV2>()
238 .expect("Must have client module")
239 .relay_direct_swap(
240 contract,
241 invoice
242 .amount_milli_satoshis()
243 .expect("amountless invoices are not supported"),
244 fresh_dispatch_refusal.is_none(),
245 )
246 .await
247 {
248 Ok(Some(final_receive_state)) => match final_receive_state {
249 FinalReceiveState::Rejected => Err(Cancelled::Rejected),
250 FinalReceiveState::Success(preimage) => Ok(PaymentResponse {
251 preimage,
252 target_federation: Some(client.federation_id()),
253 }),
254 FinalReceiveState::Refunded => Err(Cancelled::Refunded),
255 FinalReceiveState::Failure => Err(Cancelled::Failure),
256 },
257 Ok(None) => Err(fresh_dispatch_refusal
258 .expect("the relay only refuses a fresh dispatch when one was denied")),
259 Err(e) => Err(Cancelled::FinalizationError(e.fmt_compact().to_string())),
260 }
261 }
262 None => {
263 if let Some(refusal) = fresh_dispatch_refusal
267 && !context
268 .gateway
269 .outbound_payment_exists(*invoice.payment_hash())
270 .await
271 {
272 return Err(refusal);
273 }
274
275 let preimage = context
276 .gateway
277 .pay(invoice, fresh_max_delay, max_fee)
278 .await
279 .map_err(|e| Cancelled::LightningRpcError(e.to_string()))?;
280 Ok(PaymentResponse {
281 preimage,
282 target_federation: None,
283 })
284 }
285 }
286 }
287
288 async fn transition_send_payment(
289 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
290 old_state: SendStateMachine,
291 global_context: DynGlobalClientContext,
292 result: Result<PaymentResponse, Cancelled>,
293 client_ctx: GatewayClientContextV2,
294 ) -> SendStateMachine {
295 match result {
296 Ok(payment_response) => {
297 client_ctx
298 .module
299 .client_ctx
300 .log_event(
301 &mut dbtx.module_tx(),
302 OutgoingPaymentSucceeded {
303 payment_image: old_state.common.contract.payment_image.clone(),
304 target_federation: payment_response.target_federation,
305 },
306 )
307 .await;
308 let client_input = ClientInput::<LightningInput> {
309 input: LightningInput::V0(LightningInputV0::Outgoing(
310 old_state.common.outpoint,
311 OutgoingWitness::Claim(payment_response.preimage),
312 )),
313 amounts: Amounts::new_bitcoin(old_state.common.contract.amount),
314 keys: vec![old_state.common.claim_keypair],
315 };
316
317 let outpoints = global_context
318 .claim_inputs(dbtx, ClientInputBundle::new_no_sm(vec![client_input]))
319 .await
320 .expect("Cannot claim input, additional funding needed")
321 .into_iter()
322 .collect();
323
324 old_state.update(SendSMState::Claiming(Claiming {
325 preimage: payment_response.preimage,
326 outpoints,
327 }))
328 }
329 Err(e) => {
330 client_ctx
331 .module
332 .client_ctx
333 .log_event(
334 &mut dbtx.module_tx(),
335 OutgoingPaymentFailed {
336 payment_image: old_state.common.contract.payment_image.clone(),
337 error: e.clone(),
338 },
339 )
340 .await;
341 old_state.update(SendSMState::Cancelled(e))
342 }
343 }
344 }
345}
346
347pub(crate) fn fresh_dispatch_refusal(
351 invoice_expired: bool,
352 fresh_max_delay: u64,
353) -> Option<Cancelled> {
354 if invoice_expired {
355 Some(Cancelled::InvoiceExpired)
356 } else if fresh_max_delay == 0 {
357 Some(Cancelled::TimeoutTooClose)
358 } else {
359 None
360 }
361}