cdk-cln 0.17.1

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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
//! 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;
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 cdk_common::QuoteId;
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 CLN_KV_BOLT12_OUTGOING_SECONDARY_NAMESPACE: &str = "bolt12_outgoing_payments";
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 }),
            onchain: None,
            custom: HashMap::new(),
        })
    }

    /// Is payment event stream active
    fn is_payment_event_stream_active(&self) -> bool {
        self.wait_invoice_is_active.load(Ordering::SeqCst)
    }

    /// Cancel payment event stream
    fn cancel_payment_event_stream(&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 =
                                sha256::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,
                    extra_json: None,
                    estimated_blocks: None,
                    fee_options: None,
                })
            }
            OutgoingPaymentOptions::Bolt12(bolt12_options) => {
                let quote_id = bolt12_options.quote_id.clone();
                Self::bolt12_quote_payment_hash_key(&quote_id)?;
                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: Some(PaymentIdentifier::QuoteId(quote_id)),
                    amount,
                    fee: Amount::new(fee, unit.clone()),
                    state: MeltQuoteState::Unpaid,
                    extra_json: None,
                    estimated_blocks: None,
                    fee_options: None,
                })
            }
            OutgoingPaymentOptions::Onchain(_) => Err(payment::Error::UnsupportedPaymentOption),
        }
    }

    #[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 payment_lookup_id: PaymentIdentifier;

        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?;
                payment_lookup_id = payment_identifier;

                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 quote_id = bolt12_options.quote_id.clone();
                let quote_payment_identifier = PaymentIdentifier::QuoteId(quote_id.clone());

                self.check_outgoing_unpaided(&quote_payment_identifier)
                    .await?;

                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_hash = Self::parse_payment_hash(
                    decode_response
                        .invoice_payment_hash
                        .ok_or(Error::UnknownInvoice)?,
                )?;

                let payment_identifier = PaymentIdentifier::Bolt12PaymentHash(payment_hash);

                self.check_outgoing_unpaided(&payment_identifier).await?;
                self.write_bolt12_quote_payment_hash(&quote_id, &payment_hash)
                    .await?;
                payment_lookup_id = quote_payment_identifier;

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

                cln_response.invoice
            }
            _ => {
                return Err(payment::Error::UnsupportedPaymentOption);
            }
        };
        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,
                };

                MakePaymentResponse {
                    payment_lookup_id,
                    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 expiry = unix_expiry
                    .map(|t| t.checked_sub(time_now).ok_or(payment::Error::InvalidExpiry))
                    .transpose()?;

                let request = InvoiceRequest {
                    amount_msat,
                    description: description.unwrap_or_default(),
                    label: label.clone(),
                    expiry,
                    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,
                })
            }
            IncomingPaymentOptions::Onchain(_) => Err(payment::Error::UnsupportedPaymentOption),
        }
    }

    #[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 (payment_hash, missing_payment_state) = match payment_identifier {
            PaymentIdentifier::PaymentHash(hash) | PaymentIdentifier::Bolt12PaymentHash(hash) => {
                (*hash, MeltQuoteState::Unknown)
            }
            PaymentIdentifier::QuoteId(quote_id) => match self
                .read_bolt12_quote_payment_hash(quote_id)
                .await
                .map_err(payment::Error::from)?
            {
                Bolt12QuotePaymentHashLookup::Found(payment_hash) => {
                    (payment_hash, MeltQuoteState::Unpaid)
                }
                Bolt12QuotePaymentHashLookup::Missing => {
                    return Ok(outgoing_payment_response_with_status(
                        payment_identifier,
                        MeltQuoteState::Unpaid,
                    ));
                }
                Bolt12QuotePaymentHashLookup::Malformed => {
                    return Ok(outgoing_payment_response_with_status(
                        payment_identifier,
                        MeltQuoteState::Unknown,
                    ));
                }
            },
            _ => {
                tracing::error!("Unsupported identifier to check outgoing payment for cln.");
                return Err(payment::Error::UnknownPaymentState);
            }
        };

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

        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: missing_payment_state,
                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?)
    }

    fn bolt12_quote_payment_hash_key(quote_id: &QuoteId) -> Result<String, Error> {
        match quote_id {
            QuoteId::UUID(uuid) => Ok(uuid.to_string()),
            QuoteId::BASE64(_) => Err(Error::InvalidQuoteId),
        }
    }

    fn parse_payment_hash(payment_hash: String) -> Result<[u8; 32], Error> {
        hex::decode(payment_hash)
            .map_err(|e| Error::Bolt12(e.to_string()))?
            .try_into()
            .map_err(|_| Error::InvalidHash)
    }

    async fn write_bolt12_quote_payment_hash(
        &self,
        quote_id: &QuoteId,
        payment_hash: &[u8; 32],
    ) -> Result<(), Error> {
        let key = Self::bolt12_quote_payment_hash_key(quote_id)?;
        let value = hex::encode(payment_hash);
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(|e| Error::Database(e.to_string()))?;

        tx.kv_write(
            CLN_KV_PRIMARY_NAMESPACE,
            CLN_KV_BOLT12_OUTGOING_SECONDARY_NAMESPACE,
            &key,
            value.as_bytes(),
        )
        .await
        .map_err(|e| Error::Database(e.to_string()))?;
        tx.commit()
            .await
            .map_err(|e| Error::Database(e.to_string()))?;

        Ok(())
    }

    async fn read_bolt12_quote_payment_hash(
        &self,
        quote_id: &QuoteId,
    ) -> Result<Bolt12QuotePaymentHashLookup, Error> {
        let key = Self::bolt12_quote_payment_hash_key(quote_id)?;
        let Some(stored_hash) = self
            .kv_store
            .kv_read(
                CLN_KV_PRIMARY_NAMESPACE,
                CLN_KV_BOLT12_OUTGOING_SECONDARY_NAMESPACE,
                &key,
            )
            .await
            .map_err(|e| Error::Database(e.to_string()))?
        else {
            return Ok(Bolt12QuotePaymentHashLookup::Missing);
        };

        let payment_hash = match String::from_utf8(stored_hash) {
            Ok(payment_hash) => payment_hash,
            Err(err) => {
                tracing::warn!(
                    "CLN: invalid UTF-8 in BOLT12 payment hash mapping for quote {quote_id}: {err}"
                );
                return Ok(Bolt12QuotePaymentHashLookup::Malformed);
            }
        };

        match Self::parse_payment_hash(payment_hash) {
            Ok(payment_hash) => Ok(Bolt12QuotePaymentHashLookup::Found(payment_hash)),
            Err(err) => {
                tracing::warn!(
                    "CLN: invalid BOLT12 payment hash mapping for quote {quote_id}: {err}"
                );
                Ok(Bolt12QuotePaymentHashLookup::Malformed)
            }
        }
    }

    #[cfg(test)]
    async fn outgoing_payment_hash(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<Option<[u8; 32]>, payment::Error> {
        match payment_identifier {
            PaymentIdentifier::PaymentHash(hash) | PaymentIdentifier::Bolt12PaymentHash(hash) => {
                Ok(Some(*hash))
            }
            PaymentIdentifier::QuoteId(quote_id) => {
                match self
                    .read_bolt12_quote_payment_hash(quote_id)
                    .await
                    .map_err(payment::Error::from)?
                {
                    Bolt12QuotePaymentHashLookup::Found(payment_hash) => Ok(Some(payment_hash)),
                    Bolt12QuotePaymentHashLookup::Missing
                    | Bolt12QuotePaymentHashLookup::Malformed => Ok(None),
                }
            }
            _ => {
                tracing::error!("Unsupported identifier to check outgoing payment for cln.");
                Err(payment::Error::UnknownPaymentState)
            }
        }
    }

    /// 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)
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Bolt12QuotePaymentHashLookup {
    Found([u8; 32]),
    Missing,
    Malformed,
}

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: &sha256::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))
        }
    }
}

fn outgoing_payment_response_with_status(
    payment_identifier: &PaymentIdentifier,
    status: MeltQuoteState,
) -> MakePaymentResponse {
    MakePaymentResponse {
        payment_lookup_id: payment_identifier.clone(),
        payment_proof: None,
        status,
        total_spent: Amount::new(0, CurrencyUnit::Msat),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeSet, HashMap};
    use std::str::FromStr;
    use std::sync::{Arc, Mutex};

    use cdk_common::database::{
        DbTransactionFinalizer, Error as DatabaseError, KVStore, KVStoreDatabase,
        KVStoreTransaction,
    };
    use cdk_common::payment::Bolt11OutgoingPaymentOptions;

    use super::*;

    type MemoryKvKey = (String, String, String);

    #[derive(Debug, Default)]
    struct MemoryKvStore {
        entries: Arc<Mutex<HashMap<MemoryKvKey, Vec<u8>>>>,
    }

    #[derive(Debug)]
    struct MemoryKvTransaction {
        entries: Arc<Mutex<HashMap<MemoryKvKey, Vec<u8>>>>,
        writes: HashMap<MemoryKvKey, Option<Vec<u8>>>,
    }

    fn memory_kv_lock_error() -> DatabaseError {
        DatabaseError::Database(Box::new(std::io::Error::other(
            "memory kv store lock poisoned",
        )))
    }

    fn memory_kv_key(primary_namespace: &str, secondary_namespace: &str, key: &str) -> MemoryKvKey {
        (
            primary_namespace.to_string(),
            secondary_namespace.to_string(),
            key.to_string(),
        )
    }

    #[async_trait::async_trait]
    impl KVStoreDatabase for MemoryKvStore {
        type Err = DatabaseError;

        async fn kv_read(
            &self,
            primary_namespace: &str,
            secondary_namespace: &str,
            key: &str,
        ) -> Result<Option<Vec<u8>>, Self::Err> {
            let entries = self.entries.lock().map_err(|_| memory_kv_lock_error())?;

            Ok(entries
                .get(&memory_kv_key(primary_namespace, secondary_namespace, key))
                .cloned())
        }

        async fn kv_list(
            &self,
            primary_namespace: &str,
            secondary_namespace: &str,
        ) -> Result<Vec<String>, Self::Err> {
            let entries = self.entries.lock().map_err(|_| memory_kv_lock_error())?;

            Ok(entries
                .keys()
                .filter(|(primary, secondary, _)| {
                    primary == primary_namespace && secondary == secondary_namespace
                })
                .map(|(_, _, key)| key.clone())
                .collect())
        }
    }

    #[async_trait::async_trait]
    impl KVStore for MemoryKvStore {
        async fn begin_transaction(
            &self,
        ) -> Result<Box<dyn KVStoreTransaction<Self::Err> + Send + Sync>, DatabaseError> {
            Ok(Box::new(MemoryKvTransaction {
                entries: Arc::clone(&self.entries),
                writes: HashMap::new(),
            }))
        }
    }

    #[async_trait::async_trait]
    impl KVStoreTransaction<DatabaseError> for MemoryKvTransaction {
        async fn kv_read(
            &mut self,
            primary_namespace: &str,
            secondary_namespace: &str,
            key: &str,
        ) -> Result<Option<Vec<u8>>, DatabaseError> {
            let key = memory_kv_key(primary_namespace, secondary_namespace, key);

            if let Some(value) = self.writes.get(&key) {
                return Ok(value.clone());
            }

            let entries = self.entries.lock().map_err(|_| memory_kv_lock_error())?;

            Ok(entries.get(&key).cloned())
        }

        async fn kv_write(
            &mut self,
            primary_namespace: &str,
            secondary_namespace: &str,
            key: &str,
            value: &[u8],
        ) -> Result<(), DatabaseError> {
            self.writes.insert(
                memory_kv_key(primary_namespace, secondary_namespace, key),
                Some(value.to_vec()),
            );

            Ok(())
        }

        async fn kv_remove(
            &mut self,
            primary_namespace: &str,
            secondary_namespace: &str,
            key: &str,
        ) -> Result<(), DatabaseError> {
            self.writes.insert(
                memory_kv_key(primary_namespace, secondary_namespace, key),
                None,
            );

            Ok(())
        }

        async fn kv_list(
            &mut self,
            primary_namespace: &str,
            secondary_namespace: &str,
        ) -> Result<Vec<String>, DatabaseError> {
            let entries = self.entries.lock().map_err(|_| memory_kv_lock_error())?;
            let mut keys = entries
                .keys()
                .filter(|(primary, secondary, _)| {
                    primary == primary_namespace && secondary == secondary_namespace
                })
                .map(|(_, _, key)| key.clone())
                .collect::<BTreeSet<_>>();

            for ((primary, secondary, key), value) in &self.writes {
                if primary == primary_namespace && secondary == secondary_namespace {
                    match value {
                        Some(_) => {
                            keys.insert(key.clone());
                        }
                        None => {
                            keys.remove(key);
                        }
                    }
                }
            }

            Ok(keys.into_iter().collect())
        }
    }

    #[async_trait::async_trait]
    impl DbTransactionFinalizer for MemoryKvTransaction {
        type Err = DatabaseError;

        async fn commit(self: Box<Self>) -> Result<(), Self::Err> {
            let this = *self;
            let mut entries = this.entries.lock().map_err(|_| memory_kv_lock_error())?;

            for (key, value) in this.writes {
                match value {
                    Some(value) => {
                        entries.insert(key, value);
                    }
                    None => {
                        entries.remove(&key);
                    }
                }
            }

            Ok(())
        }

        async fn rollback(self: Box<Self>) -> Result<(), Self::Err> {
            Ok(())
        }
    }

    #[derive(Debug)]
    struct UnusedKvStore;

    #[async_trait::async_trait]
    impl KVStoreDatabase for UnusedKvStore {
        type Err = DatabaseError;

        async fn kv_read(
            &self,
            _primary_namespace: &str,
            _secondary_namespace: &str,
            _key: &str,
        ) -> Result<Option<Vec<u8>>, Self::Err> {
            Ok(None)
        }

        async fn kv_list(
            &self,
            _primary_namespace: &str,
            _secondary_namespace: &str,
        ) -> Result<Vec<String>, Self::Err> {
            Ok(Vec::new())
        }
    }

    #[async_trait::async_trait]
    impl KVStore for UnusedKvStore {
        async fn begin_transaction(
            &self,
        ) -> Result<Box<dyn KVStoreTransaction<Self::Err> + Send + Sync>, DatabaseError> {
            Err(DatabaseError::Database(Box::new(std::io::Error::other(
                "unused kv store transaction",
            ))))
        }
    }

    fn test_cln_with_kv(kv_store: DynKVStore) -> Cln {
        Cln {
            rpc_socket: PathBuf::new(),
            fee_reserve: FeeReserve {
                min_fee_reserve: Amount::ZERO,
                percent_fee_reserve: 0.0,
            },
            expose_private_channels: false,
            wait_invoice_cancel_token: CancellationToken::new(),
            wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
            kv_store,
        }
    }

    fn test_cln() -> Cln {
        test_cln_with_kv(Arc::new(UnusedKvStore))
    }

    fn test_cln_with_memory_kv() -> Cln {
        test_cln_with_kv(Arc::new(MemoryKvStore::default()))
    }

    fn test_invoice() -> Bolt11Invoice {
        Bolt11Invoice::from_str("lnbc100n1pnvpufspp5djn8hrq49r8cghwye9kqw752qjncwyfnrprhprpqk43mwcy4yfsqdq5g9kxy7fqd9h8vmmfvdjscqzzsxqyz5vqsp5uhpjt36rj75pl7jq2sshaukzfkt7uulj456s4mh7uy7l6vx7lvxs9qxpqysgqedwz08acmqwtk8g4vkwm2w78suwt2qyzz6jkkwcgrjm3r3hs6fskyhvud4fan3keru7emjm8ygqpcrwtlmhfjfmer3afs5hhwamgr4cqtactdq")
            .expect("test invoice must parse")
    }

    #[tokio::test]
    async fn get_payment_quote_rejects_amountless_mismatch() {
        let invoice = test_invoice();
        let invoice_amount = invoice
            .amount_milli_satoshis()
            .expect("test invoice must include amount");
        let options = Bolt11OutgoingPaymentOptions {
            bolt11: invoice,
            max_fee_amount: None,
            timeout_secs: None,
            melt_options: Some(MeltOptions::new_amountless(invoice_amount + 1)),
            quote_id: cdk_common::QuoteId::new(),
        };

        let err = test_cln()
            .get_payment_quote(
                &CurrencyUnit::Msat,
                OutgoingPaymentOptions::Bolt11(Box::new(options)),
            )
            .await
            .expect_err("amountless override must match invoice amount");

        assert!(matches!(err, payment::Error::AmountMismatch));
    }

    #[tokio::test]
    async fn get_payment_quote_accepts_matching_amountless_amount() {
        let invoice = test_invoice();
        let invoice_amount = invoice
            .amount_milli_satoshis()
            .expect("test invoice must include amount");
        let options = Bolt11OutgoingPaymentOptions {
            bolt11: invoice,
            max_fee_amount: None,
            timeout_secs: None,
            melt_options: Some(MeltOptions::new_amountless(invoice_amount)),
            quote_id: cdk_common::QuoteId::new(),
        };

        let quote = test_cln()
            .get_payment_quote(
                &CurrencyUnit::Msat,
                OutgoingPaymentOptions::Bolt11(Box::new(options)),
            )
            .await
            .expect("matching amountless override must be accepted");

        assert_eq!(
            quote.amount,
            Amount::new(invoice_amount, CurrencyUnit::Msat)
        );
    }

    #[tokio::test]
    async fn bolt12_quote_payment_hash_round_trips_through_kv() {
        let cln = test_cln_with_memory_kv();
        let quote_id = QuoteId::new();
        let payment_hash = [42; 32];

        cln.write_bolt12_quote_payment_hash(&quote_id, &payment_hash)
            .await
            .expect("payment hash should be written");

        let stored_payment_hash = cln
            .read_bolt12_quote_payment_hash(&quote_id)
            .await
            .expect("payment hash should be read");

        assert_eq!(
            stored_payment_hash,
            Bolt12QuotePaymentHashLookup::Found(payment_hash)
        );
        assert_eq!(
            Cln::bolt12_quote_payment_hash_key(&quote_id).expect("uuid quote id should be valid"),
            quote_id.to_string()
        );
    }

    #[tokio::test]
    async fn bolt12_quote_payment_hash_write_overwrites_existing_mapping() {
        let cln = test_cln_with_memory_kv();
        let quote_id = QuoteId::new();
        let first_payment_hash = [1; 32];
        let second_payment_hash = [2; 32];

        cln.write_bolt12_quote_payment_hash(&quote_id, &first_payment_hash)
            .await
            .expect("first payment hash should be written");
        cln.write_bolt12_quote_payment_hash(&quote_id, &second_payment_hash)
            .await
            .expect("second payment hash should be written");

        let stored_payment_hash = cln
            .read_bolt12_quote_payment_hash(&quote_id)
            .await
            .expect("payment hash should be read");

        assert_eq!(
            stored_payment_hash,
            Bolt12QuotePaymentHashLookup::Found(second_payment_hash)
        );
    }

    #[tokio::test]
    async fn quote_id_outgoing_lookup_without_mapping_returns_unpaid() {
        let cln = test_cln_with_memory_kv();
        let payment_identifier = PaymentIdentifier::QuoteId(QuoteId::new());

        let response = cln
            .check_outgoing_payment(&payment_identifier)
            .await
            .expect("missing quote mapping should not require CLN lookup");

        assert_eq!(response.payment_lookup_id, payment_identifier);
        assert_eq!(response.status, MeltQuoteState::Unpaid);
        assert_eq!(response.payment_proof, None);
        assert_eq!(response.total_spent, Amount::new(0, CurrencyUnit::Msat));
    }

    #[tokio::test]
    async fn malformed_quote_id_mapping_returns_unknown() {
        let kv_store = Arc::new(MemoryKvStore::default());
        let cln = test_cln_with_kv(kv_store.clone());
        let quote_id = QuoteId::new();
        let key =
            Cln::bolt12_quote_payment_hash_key(&quote_id).expect("uuid quote id should be valid");

        let mut tx = kv_store
            .begin_transaction()
            .await
            .expect("transaction should begin");
        tx.kv_write(
            CLN_KV_PRIMARY_NAMESPACE,
            CLN_KV_BOLT12_OUTGOING_SECONDARY_NAMESPACE,
            &key,
            b"not-a-payment-hash",
        )
        .await
        .expect("malformed payment hash should be written");
        tx.commit().await.expect("transaction should commit");

        let payment_identifier = PaymentIdentifier::QuoteId(quote_id);
        let response = cln
            .check_outgoing_payment(&payment_identifier)
            .await
            .expect("malformed quote mapping should not require CLN lookup");

        assert_eq!(response.payment_lookup_id, payment_identifier);
        assert_eq!(response.status, MeltQuoteState::Unknown);
    }

    #[tokio::test]
    async fn base64_quote_id_mapping_is_rejected() {
        let cln = test_cln_with_memory_kv();
        let quote_id = QuoteId::BASE64("SGVsbG8gV29ybGQh".to_string());
        let payment_hash = [9; 32];

        let err = cln
            .write_bolt12_quote_payment_hash(&quote_id, &payment_hash)
            .await
            .expect_err("base64 quote ids should not be stored in CLN bolt12 mapping");

        assert!(matches!(err, Error::InvalidQuoteId));
    }

    #[tokio::test]
    async fn direct_hash_outgoing_lookup_bypasses_quote_mapping() {
        let cln = test_cln();
        let payment_hash = [7; 32];

        assert_eq!(
            cln.outgoing_payment_hash(&PaymentIdentifier::PaymentHash(payment_hash))
                .await
                .expect("payment hash should resolve"),
            Some(payment_hash)
        );
        assert_eq!(
            cln.outgoing_payment_hash(&PaymentIdentifier::Bolt12PaymentHash(payment_hash))
                .await
                .expect("bolt12 payment hash should resolve"),
            Some(payment_hash)
        );
    }
}