cdk-cln 0.16.0

CDK ln backend for cln
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! CDK lightning backend for CLN

#![doc = include_str!("../README.md")]

use std::cmp::max;
use std::path::PathBuf;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use bitcoin::hashes::sha256::Hash;
use cdk_common::amount::Amount;
use cdk_common::common::FeeReserve;
use cdk_common::database::DynKVStore;
use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState};
use cdk_common::payment::{
    self, Bolt11IncomingPaymentOptions, Bolt12IncomingPaymentOptions,
    CreateIncomingPaymentResponse, Event, IncomingPaymentOptions, MakePaymentResponse, MintPayment,
    OutgoingPaymentOptions, PaymentIdentifier, PaymentQuoteResponse, SettingsResponse,
    WaitPaymentResponse,
};
use cdk_common::util::{hex, unix_time};
use cdk_common::Bolt11Invoice;
use cln_rpc::model::requests::{
    DecodeRequest, FetchinvoiceRequest, InvoiceRequest, ListinvoicesRequest, ListpaysRequest,
    OfferRequest, PayRequest, WaitanyinvoiceRequest,
};
use cln_rpc::model::responses::{
    DecodeResponse, InvoiceResponse, ListinvoicesInvoices, ListinvoicesInvoicesStatus,
    ListpaysPaysStatus, PayStatus, WaitanyinvoiceResponse, WaitanyinvoiceStatus,
};
use cln_rpc::primitives::{Amount as CLN_Amount, AmountOrAny, Sha256};
use cln_rpc::ClnRpc;
use error::Error;
use futures::{Stream, StreamExt};
use tokio_util::sync::CancellationToken;
use tracing::instrument;
use uuid::Uuid;

pub mod error;

// KV Store constants for CLN
const CLN_KV_PRIMARY_NAMESPACE: &str = "cdk_cln_lightning_backend";
const CLN_KV_SECONDARY_NAMESPACE: &str = "payment_indices";
const LAST_PAY_INDEX_KV_KEY: &str = "last_pay_index";

/// CLN mint backend
#[derive(Clone)]
pub struct Cln {
    rpc_socket: PathBuf,
    fee_reserve: FeeReserve,
    expose_private_channels: bool,
    wait_invoice_cancel_token: CancellationToken,
    wait_invoice_is_active: Arc<AtomicBool>,
    kv_store: DynKVStore,
}

impl std::fmt::Debug for Cln {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cln")
            .field("rpc_socket", &self.rpc_socket)
            .field("fee_reserve", &self.fee_reserve)
            .finish_non_exhaustive()
    }
}

impl Cln {
    /// Create new [`Cln`]
    pub async fn new(
        rpc_socket: PathBuf,
        fee_reserve: FeeReserve,
        expose_private_channels: bool,
        kv_store: DynKVStore,
    ) -> Result<Self, Error> {
        Ok(Self {
            rpc_socket,
            fee_reserve,
            expose_private_channels,
            wait_invoice_cancel_token: CancellationToken::new(),
            wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
            kv_store,
        })
    }
}

#[async_trait]
impl MintPayment for Cln {
    type Err = payment::Error;

    async fn get_settings(&self) -> Result<SettingsResponse, Self::Err> {
        use std::collections::HashMap;
        Ok(SettingsResponse {
            unit: CurrencyUnit::Msat.to_string(),
            bolt11: Some(payment::Bolt11Settings {
                mpp: true,
                amountless: true,
                invoice_description: true,
            }),
            bolt12: Some(payment::Bolt12Settings { amountless: true }),
            custom: HashMap::new(),
        })
    }

    /// Is wait invoice active
    fn is_wait_invoice_active(&self) -> bool {
        self.wait_invoice_is_active.load(Ordering::SeqCst)
    }

    /// Cancel wait invoice
    fn cancel_wait_invoice(&self) {
        self.wait_invoice_cancel_token.cancel()
    }

    #[instrument(skip_all)]
    async fn wait_payment_event(
        &self,
    ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
        tracing::info!(
            "CLN: Starting wait_any_incoming_payment with socket: {:?}",
            self.rpc_socket
        );

        let last_pay_index = self.get_last_pay_index().await?.inspect(|&idx| {
            tracing::info!("CLN: Found last payment index: {}", idx);
        });

        tracing::debug!("CLN: Connecting to CLN node...");
        let cln_client = match cln_rpc::ClnRpc::new(&self.rpc_socket).await {
            Ok(client) => {
                tracing::debug!("CLN: Successfully connected to CLN node");
                client
            }
            Err(err) => {
                tracing::error!("CLN: Failed to connect to CLN node: {}", err);
                return Err(Error::from(err).into());
            }
        };

        tracing::debug!("CLN: Creating stream processing pipeline");
        let kv_store = self.kv_store.clone();
        let stream = futures::stream::unfold(
            (
                cln_client,
                last_pay_index,
                self.wait_invoice_cancel_token.clone(),
                Arc::clone(&self.wait_invoice_is_active),
                kv_store,
            ),
            |(mut cln_client, mut last_pay_idx, cancel_token, is_active, kv_store)| async move {
                // Set the stream as active
                is_active.store(true, Ordering::SeqCst);
                tracing::debug!("CLN: Stream is now active, waiting for invoice events with lastpay_index: {:?}", last_pay_idx);

                loop {
                    tokio::select! {
                        _ = cancel_token.cancelled() => {
                            // Set the stream as inactive
                            is_active.store(false, Ordering::SeqCst);
                            tracing::info!("CLN: Invoice stream cancelled");
                            // End the stream
                            return None;
                        }
                        result = cln_client.call(cln_rpc::Request::WaitAnyInvoice(WaitanyinvoiceRequest {
                            timeout: None,
                            lastpay_index: last_pay_idx,
                        })) => {
                            tracing::debug!("CLN: Received response from WaitAnyInvoice call");
                            match result {
                                Ok(invoice) => {
                                    tracing::debug!("CLN: Successfully received invoice data");
                                        // Try to convert the invoice to WaitanyinvoiceResponse
                            let wait_any_response_result: Result<WaitanyinvoiceResponse, _> =
                                invoice.try_into();

                            let wait_any_response = match wait_any_response_result {
                                Ok(response) => {
                                    tracing::debug!("CLN: Parsed WaitAnyInvoice response successfully");
                                    response
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        "CLN: Failed to parse WaitAnyInvoice response: {:?}",
                                        e
                                    );
                                    // Continue to the next iteration without panicking
                                    continue;
                                }
                            };

                            // Check the status of the invoice
                            // We only want to yield invoices that have been paid
                            match wait_any_response.status {
                                WaitanyinvoiceStatus::PAID => {
                                    tracing::info!("CLN: Invoice with payment index {} is PAID",
                                                 wait_any_response.pay_index.unwrap_or_default());
                                }
                                WaitanyinvoiceStatus::EXPIRED => {
                                    tracing::debug!("CLN: Invoice with payment index {} is EXPIRED, skipping",
                                                  wait_any_response.pay_index.unwrap_or_default());
                                    continue;
                                }
                            }

                            last_pay_idx = wait_any_response.pay_index;
                            tracing::debug!("CLN: Updated last_pay_idx to {:?}", last_pay_idx);


                            // Store the updated pay index in KV store for persistence
                            if let Some(pay_index) = last_pay_idx {
                                let index_str = pay_index.to_string();
                                if let Ok(mut tx) = kv_store.begin_transaction().await {
                                    if let Err(e) = tx.kv_write(CLN_KV_PRIMARY_NAMESPACE, CLN_KV_SECONDARY_NAMESPACE, LAST_PAY_INDEX_KV_KEY, index_str.as_bytes()).await {
                                        tracing::warn!("CLN: Failed to write last pay index {} to KV store: {}", pay_index, e);
                                    } else if let Err(e) = tx.commit().await {
                                        tracing::warn!("CLN: Failed to commit last pay index {} to KV store: {}", pay_index, e);
                                    } else {
                                        tracing::debug!("CLN: Stored last pay index {} in KV store", pay_index);
                                    }
                                } else {
                                    tracing::warn!("CLN: Failed to begin KV transaction for storing pay index {}", pay_index);
                                }
                            }

                            let payment_hash = wait_any_response.payment_hash;
                            tracing::debug!("CLN: Payment hash: {}", payment_hash);

                            let amount_msats = match wait_any_response.amount_received_msat {
                                Some(amt) => {
                                    tracing::info!("CLN: Received payment of {} msats for {}",
                                                 amt.msat(), payment_hash);
                                    amt
                                }
                                None => {
                                    tracing::error!("CLN: No amount in paid invoice, this should not happen");
                                    continue;
                                }
                            };

                            let payment_hash = Hash::from_bytes_ref(payment_hash.as_ref());

                            let request_lookup_id = match wait_any_response.bolt12 {
                                // If it is a bolt12 payment we need to get the offer_id as this is what we use as the request look up.
                                // Since this is not returned in the wait any response,
                                // we need to do a second query for it.
                                Some(bolt12) => {
                                    tracing::info!("CLN: Processing BOLT12 payment, bolt12 value: {}", bolt12);
                                    match fetch_invoice_by_payment_hash(
                                        &mut cln_client,
                                        payment_hash,
                                    )
                                    .await
                                    {
                                        Ok(Some(invoice)) => {
                                            if let Some(local_offer_id) = invoice.local_offer_id {
                                                tracing::info!("CLN: Received bolt12 payment of {} msats for offer {}",
                                                             amount_msats.msat(), local_offer_id);
                                                PaymentIdentifier::OfferId(local_offer_id.to_string())
                                            } else {
                                                tracing::warn!("CLN: BOLT12 invoice has no local_offer_id, skipping");
                                                continue;
                                            }
                                        }
                                        Ok(None) => {
                                            tracing::warn!("CLN: Failed to find invoice by payment hash, skipping");
                                            continue;
                                        }
                                        Err(e) => {
                                            tracing::warn!(
                                                "CLN: Error fetching invoice by payment hash: {e}"
                                            );
                                            continue;
                                        }
                                    }
                                }
                                None => {
                                 tracing::info!("CLN: Processing BOLT11 payment with hash {}", payment_hash);
                                 PaymentIdentifier::PaymentHash(*payment_hash.as_ref())
                                },
                            };

                            let response = WaitPaymentResponse {
                                payment_identifier: request_lookup_id,
                                payment_amount: Amount::new(amount_msats.msat(), CurrencyUnit::Msat),
                                payment_id: payment_hash.to_string(),
                            };
                            tracing::info!("CLN: Created WaitPaymentResponse with amount {} msats", amount_msats.msat());
                            let event = Event::PaymentReceived(response);

                            break Some((event, (cln_client, last_pay_idx, cancel_token, is_active, kv_store)));
                                }
                                Err(e) => {
                                    tracing::warn!("CLN: Error fetching invoice: {e}");
                                    tokio::time::sleep(Duration::from_secs(1)).await;
                                    continue;
                                }
                            }
                        }
                    }
                }
            },
        )
        .boxed();

        tracing::info!("CLN: Successfully initialized invoice stream");
        Ok(stream)
    }

    #[instrument(skip_all)]
    async fn get_payment_quote(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<PaymentQuoteResponse, Self::Err> {
        match options {
            cdk_common::payment::OutgoingPaymentOptions::Custom(_) => {
                Err(cdk_common::payment::Error::UnsupportedPaymentOption)
            }
            OutgoingPaymentOptions::Bolt11(bolt11_options) => {
                // If we have specific amount options, use those
                let amount_msat: Amount = if let Some(melt_options) = bolt11_options.melt_options {
                    match melt_options {
                        MeltOptions::Amountless { amountless } => {
                            let amount_msat = amountless.amount_msat;

                            if let Some(invoice_amount) =
                                bolt11_options.bolt11.amount_milli_satoshis()
                            {
                                if !invoice_amount == u64::from(amount_msat) {
                                    return Err(payment::Error::AmountMismatch);
                                }
                            }
                            amount_msat
                        }
                        MeltOptions::Mpp { mpp } => mpp.amount,
                    }
                } else {
                    // Fall back to invoice amount
                    bolt11_options
                        .bolt11
                        .amount_milli_satoshis()
                        .ok_or(Error::UnknownInvoiceAmount)?
                        .into()
                };
                // Convert to target unit
                let amount =
                    Amount::new(amount_msat.into(), CurrencyUnit::Msat).convert_to(unit)?;

                // Calculate fee
                let relative_fee_reserve =
                    (self.fee_reserve.percent_fee_reserve * amount.value() as f32) as u64;
                let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
                let fee = max(relative_fee_reserve, absolute_fee_reserve);

                Ok(PaymentQuoteResponse {
                    request_lookup_id: Some(PaymentIdentifier::PaymentHash(
                        *bolt11_options.bolt11.payment_hash().as_ref(),
                    )),
                    amount,
                    fee: Amount::new(fee, unit.clone()),
                    state: MeltQuoteState::Unpaid,
                })
            }
            OutgoingPaymentOptions::Bolt12(bolt12_options) => {
                let offer = bolt12_options.offer;

                let amount_msat: u64 = if let Some(amount) = bolt12_options.melt_options {
                    amount.amount_msat().into()
                } else {
                    // Fall back to offer amount
                    let decode_response = self.decode_string(offer.to_string()).await?;

                    decode_response
                        .offer_amount_msat
                        .ok_or(Error::UnknownInvoiceAmount)?
                        .msat()
                };

                // Convert to target unit
                let amount = Amount::new(amount_msat, CurrencyUnit::Msat).convert_to(unit)?;

                // Calculate fee
                let relative_fee_reserve =
                    (self.fee_reserve.percent_fee_reserve * amount.value() as f32) as u64;
                let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
                let fee = max(relative_fee_reserve, absolute_fee_reserve);

                Ok(PaymentQuoteResponse {
                    request_lookup_id: None,
                    amount,
                    fee: Amount::new(fee, unit.clone()),
                    state: MeltQuoteState::Unpaid,
                })
            }
        }
    }

    #[instrument(skip_all)]
    async fn make_payment(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<MakePaymentResponse, Self::Err> {
        let max_fee_msat: Option<u64>;
        let mut partial_amount: Option<u64> = None;
        let mut amount_msat: Option<u64> = None;

        let mut cln_client = self.cln_client().await?;

        let invoice = match &options {
            OutgoingPaymentOptions::Bolt11(bolt11_options) => {
                let payment_identifier =
                    PaymentIdentifier::PaymentHash(*bolt11_options.bolt11.payment_hash().as_ref());

                self.check_outgoing_unpaided(&payment_identifier).await?;

                if let Some(melt_options) = bolt11_options.melt_options {
                    match melt_options {
                        MeltOptions::Mpp { mpp } => partial_amount = Some(mpp.amount.into()),
                        MeltOptions::Amountless { amountless } => {
                            amount_msat = Some(amountless.amount_msat.into());
                        }
                    }
                }

                max_fee_msat = bolt11_options
                    .max_fee_amount
                    .as_ref()
                    .map(|a| a.to_msat())
                    .transpose()?;

                bolt11_options.bolt11.to_string()
            }
            OutgoingPaymentOptions::Bolt12(bolt12_options) => {
                let offer = &bolt12_options.offer;

                let amount_msat: u64 = if let Some(amount) = bolt12_options.melt_options {
                    amount.amount_msat().into()
                } else {
                    // Fall back to offer amount
                    let decode_response = self.decode_string(offer.to_string()).await?;

                    decode_response
                        .offer_amount_msat
                        .ok_or(Error::UnknownInvoiceAmount)?
                        .msat()
                };

                // Fetch invoice from offer

                let cln_response = cln_client
                    .call_typed(&FetchinvoiceRequest {
                        amount_msat: Some(CLN_Amount::from_msat(amount_msat)),
                        payer_metadata: None,
                        payer_note: None,
                        quantity: None,
                        recurrence_counter: None,
                        recurrence_label: None,
                        recurrence_start: None,
                        timeout: None,
                        offer: offer.to_string(),
                        bip353: None,
                    })
                    .await
                    .map_err(|err| {
                        tracing::error!("Could not fetch invoice for offer: {:?}", err);
                        Error::ClnRpc(err)
                    })?;

                let decode_response = self.decode_string(cln_response.invoice.clone()).await?;

                let payment_identifier = PaymentIdentifier::Bolt12PaymentHash(
                    hex::decode(
                        decode_response
                            .invoice_payment_hash
                            .ok_or(Error::UnknownInvoice)?,
                    )
                    .map_err(|e| Error::Bolt12(e.to_string()))?
                    .try_into()
                    .map_err(|_| Error::InvalidHash)?,
                );

                self.check_outgoing_unpaided(&payment_identifier).await?;

                max_fee_msat = bolt12_options
                    .max_fee_amount
                    .clone()
                    .map(|a| a.to_msat())
                    .transpose()?;

                cln_response.invoice
            }
            _ => {
                max_fee_msat = None;
                "".to_string()
            }
        };
        if invoice.is_empty() {
            return Err(Error::UnknownInvoice.into());
        }

        tracing::debug!("Attempting payment with max fee: {:?}", max_fee_msat);

        let cln_response = cln_client
            .call_typed(&PayRequest {
                bolt11: invoice,
                amount_msat: amount_msat.map(CLN_Amount::from_msat),
                label: None,
                riskfactor: None,
                maxfeepercent: None,
                retry_for: None,
                maxdelay: None,
                exemptfee: None,
                localinvreqid: None,
                exclude: None,
                maxfee: max_fee_msat.map(CLN_Amount::from_msat),
                description: None,
                partial_msat: partial_amount.map(CLN_Amount::from_msat),
            })
            .await;

        let response = match cln_response {
            Ok(pay_response) => {
                let status = match pay_response.status {
                    PayStatus::COMPLETE => MeltQuoteState::Paid,
                    PayStatus::PENDING => MeltQuoteState::Pending,
                    PayStatus::FAILED => MeltQuoteState::Failed,
                };

                let payment_identifier = match options {
                    cdk_common::payment::OutgoingPaymentOptions::Custom(_) => {
                        PaymentIdentifier::PaymentHash(*pay_response.payment_hash.as_ref())
                    }
                    OutgoingPaymentOptions::Bolt11(_) => {
                        PaymentIdentifier::PaymentHash(*pay_response.payment_hash.as_ref())
                    }
                    OutgoingPaymentOptions::Bolt12(_) => {
                        PaymentIdentifier::Bolt12PaymentHash(*pay_response.payment_hash.as_ref())
                    }
                };

                MakePaymentResponse {
                    payment_lookup_id: payment_identifier,
                    payment_proof: Some(hex::encode(pay_response.payment_preimage.to_vec())),
                    status,
                    total_spent: Amount::new(
                        pay_response.amount_sent_msat.msat(),
                        CurrencyUnit::Msat,
                    )
                    .convert_to(unit)?,
                }
            }
            Err(err) => {
                tracing::error!("Could not pay invoice: {}", err);
                return Err(Error::ClnRpc(err).into());
            }
        };

        Ok(response)
    }

    #[instrument(skip_all)]
    async fn create_incoming_payment_request(
        &self,
        options: IncomingPaymentOptions,
    ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
        match options {
            cdk_common::payment::IncomingPaymentOptions::Custom(_) => {
                Err(cdk_common::payment::Error::UnsupportedPaymentOption)
            }
            IncomingPaymentOptions::Bolt11(Bolt11IncomingPaymentOptions {
                description,
                amount,
                unix_expiry,
            }) => {
                let time_now = unix_time();

                let mut cln_client = self.cln_client().await?;

                let label = Uuid::new_v4().to_string();

                let amount_converted = amount.convert_to(&CurrencyUnit::Msat)?;
                let amount_msat =
                    AmountOrAny::Amount(CLN_Amount::from_msat(amount_converted.value()));

                let request = InvoiceRequest {
                    amount_msat,
                    description: description.unwrap_or_default(),
                    label: label.clone(),
                    expiry: unix_expiry.map(|t| t - time_now),
                    fallbacks: None,
                    preimage: None,
                    cltv: None,
                    deschashonly: None,
                    exposeprivatechannels: None,
                };

                // cln-rpc types exposeprivatechannels as Option<Vec<ShortChannelId>>
                // which cannot represent boolean true. Use call_raw to bypass this
                // limitation when expose_private_channels is enabled.
                let invoice_response: InvoiceResponse = if self.expose_private_channels {
                    let mut params = serde_json::to_value(&request).map_err(Error::from)?;
                    params["exposeprivatechannels"] = serde_json::Value::Bool(true);
                    cln_client
                        .call_raw("invoice", &params)
                        .await
                        .map_err(Error::from)?
                } else {
                    cln_client.call_typed(&request).await.map_err(Error::from)?
                };

                let request = Bolt11Invoice::from_str(&invoice_response.bolt11)?;
                let expiry = request.expires_at().map(|t| t.as_secs());
                let payment_hash = request.payment_hash();

                Ok(CreateIncomingPaymentResponse {
                    request_lookup_id: PaymentIdentifier::PaymentHash(*payment_hash.as_ref()),
                    request: request.to_string(),
                    expiry,
                    extra_json: None,
                })
            }
            IncomingPaymentOptions::Bolt12(bolt12_options) => {
                let Bolt12IncomingPaymentOptions {
                    description,
                    amount,
                    unix_expiry,
                } = *bolt12_options;
                let mut cln_client = self.cln_client().await?;

                let label = Uuid::new_v4().to_string();

                // Match like this until we change to option
                let amount = match amount {
                    Some(amount) => {
                        let amount = amount.convert_to(&CurrencyUnit::Msat)?;

                        amount.value().to_string()
                    }
                    None => "any".to_string(),
                };

                // It seems that the only way to force cln to create a unique offer
                // is to encode some random data in the offer
                let issuer = Uuid::new_v4().to_string();

                let offer_response = cln_client
                    .call_typed(&OfferRequest {
                        amount,
                        absolute_expiry: unix_expiry,
                        description: Some(description.unwrap_or_default()),
                        issuer: Some(issuer.to_string()),
                        label: Some(label.to_string()),
                        single_use: None,
                        quantity_max: None,
                        recurrence: None,
                        recurrence_base: None,
                        recurrence_limit: None,
                        recurrence_paywindow: None,
                        recurrence_start_any_period: None,
                    })
                    .await
                    .map_err(Error::from)?;

                Ok(CreateIncomingPaymentResponse {
                    request_lookup_id: PaymentIdentifier::OfferId(
                        offer_response.offer_id.to_string(),
                    ),
                    request: offer_response.bolt12,
                    expiry: unix_expiry,
                    extra_json: None,
                })
            }
        }
    }

    #[instrument(skip(self))]
    async fn check_incoming_payment_status(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
        let mut cln_client = self.cln_client().await?;

        let listinvoices_response = match payment_identifier {
            PaymentIdentifier::Label(label) => {
                // Query by label
                cln_client
                    .call_typed(&ListinvoicesRequest {
                        payment_hash: None,
                        label: Some(label.to_string()),
                        invstring: None,
                        offer_id: None,
                        index: None,
                        limit: None,
                        start: None,
                    })
                    .await
                    .map_err(Error::from)?
            }
            PaymentIdentifier::OfferId(offer_id) => {
                // Query by offer_id
                cln_client
                    .call_typed(&ListinvoicesRequest {
                        payment_hash: None,
                        label: None,
                        invstring: None,
                        offer_id: Some(offer_id.to_string()),
                        index: None,
                        limit: None,
                        start: None,
                    })
                    .await
                    .map_err(Error::from)?
            }
            PaymentIdentifier::PaymentHash(payment_hash) => {
                // Query by payment_hash
                cln_client
                    .call_typed(&ListinvoicesRequest {
                        payment_hash: Some(hex::encode(payment_hash)),
                        label: None,
                        invstring: None,
                        offer_id: None,
                        index: None,
                        limit: None,
                        start: None,
                    })
                    .await
                    .map_err(Error::from)?
            }
            _ => {
                tracing::error!("Unsupported payment id for CLN");
                return Err(payment::Error::UnknownPaymentState);
            }
        };

        Ok(listinvoices_response
            .invoices
            .iter()
            .filter(|p| p.status == ListinvoicesInvoicesStatus::PAID)
            .filter(|p| p.amount_msat.is_some()) // Filter out invoices without an amount
            .map(|p| WaitPaymentResponse {
                payment_identifier: payment_identifier.clone(),
                payment_amount: Amount::new(
                    p.amount_msat
                        // Safe to expect since we filtered for Some
                        .expect("We have filter out those without amounts")
                        .msat(),
                    CurrencyUnit::Msat,
                ),
                payment_id: p.payment_hash.to_string(),
            })
            .collect())
    }

    #[instrument(skip(self))]
    async fn check_outgoing_payment(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<MakePaymentResponse, Self::Err> {
        let mut cln_client = self.cln_client().await?;

        let payment_hash = match payment_identifier {
            PaymentIdentifier::PaymentHash(hash) => hash,
            PaymentIdentifier::Bolt12PaymentHash(hash) => hash,
            _ => {
                tracing::error!("Unsupported identifier to check outgoing payment for cln.");
                return Err(payment::Error::UnknownPaymentState);
            }
        };

        let listpays_response = cln_client
            .call_typed(&ListpaysRequest {
                payment_hash: Some(*Sha256::from_bytes_ref(payment_hash)),
                bolt11: None,
                status: None,
                start: None,
                index: None,
                limit: None,
            })
            .await
            .map_err(Error::from)?;

        match listpays_response.pays.first() {
            Some(pays_response) => {
                let status = cln_pays_status_to_mint_state(pays_response.status);

                Ok(MakePaymentResponse {
                    payment_lookup_id: payment_identifier.clone(),
                    payment_proof: pays_response.preimage.map(|p| hex::encode(p.to_vec())),
                    status,
                    total_spent: pays_response
                        .amount_sent_msat
                        .map_or(Amount::new(0, CurrencyUnit::Msat), |a| {
                            Amount::new(a.msat(), CurrencyUnit::Msat)
                        }),
                })
            }
            None => Ok(MakePaymentResponse {
                payment_lookup_id: payment_identifier.clone(),
                payment_proof: None,
                status: MeltQuoteState::Unknown,
                total_spent: Amount::new(0, CurrencyUnit::Msat),
            }),
        }
    }
}

impl Cln {
    async fn cln_client(&self) -> Result<ClnRpc, Error> {
        Ok(cln_rpc::ClnRpc::new(&self.rpc_socket).await?)
    }

    /// Get last pay index for cln
    async fn get_last_pay_index(&self) -> Result<Option<u64>, Error> {
        // First try to read from KV store
        if let Some(stored_index) = self
            .kv_store
            .kv_read(
                CLN_KV_PRIMARY_NAMESPACE,
                CLN_KV_SECONDARY_NAMESPACE,
                LAST_PAY_INDEX_KV_KEY,
            )
            .await
            .map_err(|e| Error::Database(e.to_string()))?
        {
            if let Ok(index_str) = std::str::from_utf8(&stored_index) {
                if let Ok(index) = index_str.parse::<u64>() {
                    tracing::debug!("CLN: Retrieved last pay index {} from KV store", index);
                    return Ok(Some(index));
                }
            }
        }

        // Fall back to querying CLN directly
        tracing::debug!("CLN: No stored last pay index found in KV store, querying CLN directly");
        let mut cln_client = self.cln_client().await?;
        let listinvoices_response = cln_client
            .call_typed(&ListinvoicesRequest {
                index: None,
                invstring: None,
                label: None,
                limit: None,
                offer_id: None,
                payment_hash: None,
                start: None,
            })
            .await
            .map_err(Error::from)?;

        match listinvoices_response.invoices.last() {
            Some(last_invoice) => Ok(last_invoice.pay_index),
            None => Ok(None),
        }
    }

    /// Decode string
    #[instrument(skip(self))]
    async fn decode_string(&self, string: String) -> Result<DecodeResponse, Error> {
        let mut cln_client = self.cln_client().await?;

        cln_client
            .call_typed(&DecodeRequest { string })
            .await
            .map_err(|err| {
                tracing::error!("Could not fetch invoice for offer: {:?}", err);
                Error::ClnRpc(err)
            })
    }

    /// Checks that outgoing payment is not already paid
    #[instrument(skip(self))]
    async fn check_outgoing_unpaided(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<(), payment::Error> {
        let pay_state = self.check_outgoing_payment(payment_identifier).await?;

        match pay_state.status {
            MeltQuoteState::Unpaid | MeltQuoteState::Unknown | MeltQuoteState::Failed => Ok(()),
            MeltQuoteState::Paid => {
                tracing::debug!("Melt attempted on invoice already paid");
                Err(payment::Error::InvoiceAlreadyPaid)
            }
            MeltQuoteState::Pending => {
                tracing::debug!("Melt attempted on invoice already pending");
                Err(payment::Error::InvoicePaymentPending)
            }
        }
    }
}

fn cln_pays_status_to_mint_state(status: ListpaysPaysStatus) -> MeltQuoteState {
    match status {
        ListpaysPaysStatus::PENDING => MeltQuoteState::Pending,
        ListpaysPaysStatus::COMPLETE => MeltQuoteState::Paid,
        ListpaysPaysStatus::FAILED => MeltQuoteState::Failed,
    }
}

async fn fetch_invoice_by_payment_hash(
    cln_client: &mut cln_rpc::ClnRpc,
    payment_hash: &Hash,
) -> Result<Option<ListinvoicesInvoices>, Error> {
    tracing::debug!("Fetching invoice by payment hash: {}", payment_hash);

    let payment_hash_str = payment_hash.to_string();
    tracing::debug!("Payment hash string: {}", payment_hash_str);

    let request = ListinvoicesRequest {
        payment_hash: Some(payment_hash_str),
        index: None,
        invstring: None,
        label: None,
        limit: None,
        offer_id: None,
        start: None,
    };
    tracing::debug!("Created ListinvoicesRequest");

    match cln_client.call_typed(&request).await {
        Ok(invoice_response) => {
            let invoice_count = invoice_response.invoices.len();
            tracing::debug!(
                "Received {} invoices for payment hash {}",
                invoice_count,
                payment_hash
            );

            if invoice_count > 0 {
                let first_invoice = invoice_response.invoices.first().cloned();
                if let Some(invoice) = &first_invoice {
                    tracing::debug!("Found invoice with payment hash {}", payment_hash);
                    tracing::debug!(
                        "Invoice details - local_offer_id: {:?}, status: {:?}",
                        invoice.local_offer_id,
                        invoice.status
                    );
                } else {
                    tracing::warn!("No invoice found with payment hash {}", payment_hash);
                }
                Ok(first_invoice)
            } else {
                tracing::warn!("No invoices returned for payment hash {}", payment_hash);
                Ok(None)
            }
        }
        Err(e) => {
            tracing::error!(
                "Error fetching invoice by payment hash {}: {}",
                payment_hash,
                e
            );
            Err(Error::from(e))
        }
    }
}