cdk-redb 0.16.0-rc.2

Redb storage backend for CDK
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
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
//! Redb Wallet

use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

use async_trait::async_trait;
use cdk_common::bitcoin::bip32::DerivationPath;
use cdk_common::database::{validate_kvstore_params, WalletDatabase};
use cdk_common::mint_url::MintUrl;
use cdk_common::nut00::KnownMethod;
use cdk_common::util::unix_time;
use cdk_common::wallet::{
    self, MintQuote, ProofInfo, Transaction, TransactionDirection, TransactionId,
};
use cdk_common::{
    database, Amount, CurrencyUnit, Id, KeySet, KeySetInfo, Keys, MintInfo, PaymentMethod,
    PublicKey, SpendingConditions, State,
};
use redb::{Database, MultimapTableDefinition, ReadableDatabase, ReadableTable, TableDefinition};
use tracing::instrument;

use crate::error::Error;
use crate::migrations::migrate_00_to_01;
use crate::wallet::migrations::{
    migrate_01_to_02, migrate_02_to_03, migrate_03_to_04, migrate_04_to_05,
};

mod migrations;

// <Mint_url, Info>
const MINTS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mints_table");
// <Mint_Url, Keyset_id>
const MINT_KEYSETS_TABLE: MultimapTableDefinition<&str, &[u8]> =
    MultimapTableDefinition::new("mint_keysets");
// <Keyset_id, KeysetInfo>
const KEYSETS_TABLE: TableDefinition<&[u8], &str> = TableDefinition::new("keysets");
// <Quote_id, quote>
const MINT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_quotes");
// <Quote_id, quote>
const MELT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("melt_quotes");
const MINT_KEYS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_keys");
// <Y, Proof Info>
const PROOFS_TABLE: TableDefinition<&[u8], &str> = TableDefinition::new("proofs");
const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config");
const KEYSET_COUNTER: TableDefinition<&str, u32> = TableDefinition::new("keyset_counter");
// <Transaction_id, Transaction>
const TRANSACTIONS_TABLE: TableDefinition<&[u8], &str> = TableDefinition::new("transactions");
// <Saga_id, WalletSaga>
const SAGAS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("wallet_sagas");

// <Pubkey, P2PKSigningKey>
const P2PK_SIGNING_KEYS_TABLE: TableDefinition<&[u8], &str> =
    TableDefinition::new("p2pk_signing_keys");

const KEYSET_U32_MAPPING: TableDefinition<u32, &str> = TableDefinition::new("keyset_u32_mapping");
// <(primary_namespace, secondary_namespace, key), value>
const KV_STORE_TABLE: TableDefinition<(&str, &str, &str), &[u8]> = TableDefinition::new("kv_store");

const DATABASE_VERSION: u32 = 5;

/// Wallet Redb Database
#[derive(Debug, Clone)]
pub struct WalletRedbDatabase {
    db: Arc<Database>,
}

impl WalletRedbDatabase {
    /// Create new [`WalletRedbDatabase`]
    pub fn new(path: &Path) -> Result<Self, Error> {
        {
            // Check if parent directory exists before attempting to create database
            if let Some(parent) = path.parent() {
                if !parent.exists() {
                    return Err(Error::Io(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        format!("Parent directory does not exist: {parent:?}"),
                    )));
                }
            }

            let db = Arc::new(Database::create(path)?);

            let db_version: Option<String>;
            {
                // Check database version
                let read_txn = db.begin_read()?;
                let table = read_txn.open_table(CONFIG_TABLE);

                db_version = match table {
                    Ok(table) => table.get("db_version")?.map(|v| v.value().to_string()),
                    Err(_) => None,
                };
            }

            match db_version {
                Some(db_version) => {
                    let mut current_file_version = u32::from_str(&db_version)?;
                    tracing::info!("Current file version {}", current_file_version);

                    match current_file_version.cmp(&DATABASE_VERSION) {
                        Ordering::Less => {
                            tracing::info!(
                                "Database needs to be upgraded at {} current is {}",
                                current_file_version,
                                DATABASE_VERSION
                            );
                            if current_file_version == 0 {
                                current_file_version = migrate_00_to_01(Arc::clone(&db))?;
                            }

                            if current_file_version == 1 {
                                current_file_version = migrate_01_to_02(Arc::clone(&db))?;
                            }

                            if current_file_version == 2 {
                                current_file_version = migrate_02_to_03(Arc::clone(&db))?;
                            }

                            if current_file_version == 3 {
                                current_file_version = migrate_03_to_04(Arc::clone(&db))?;
                            }

                            if current_file_version == 4 {
                                current_file_version = migrate_04_to_05(Arc::clone(&db))?;
                            }

                            if current_file_version != DATABASE_VERSION {
                                tracing::warn!(
                                    "Database upgrade did not complete at {} current is {}",
                                    current_file_version,
                                    DATABASE_VERSION
                                );
                                return Err(Error::UnknownDatabaseVersion);
                            }

                            let write_txn = db.begin_write()?;
                            {
                                let mut table = write_txn.open_table(CONFIG_TABLE)?;

                                table
                                    .insert("db_version", DATABASE_VERSION.to_string().as_str())?;
                            }

                            write_txn.commit()?;
                        }
                        Ordering::Equal => {
                            tracing::info!("Database is at current version {}", DATABASE_VERSION);
                        }
                        Ordering::Greater => {
                            tracing::warn!(
                                "Database upgrade did not complete at {} current is {}",
                                current_file_version,
                                DATABASE_VERSION
                            );
                            return Err(Error::UnknownDatabaseVersion);
                        }
                    }
                }
                None => {
                    let write_txn = db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(CONFIG_TABLE)?;
                        // Open all tables to init a new db
                        let _ = write_txn.open_table(MINTS_TABLE)?;
                        let _ = write_txn.open_multimap_table(MINT_KEYSETS_TABLE)?;
                        let _ = write_txn.open_table(KEYSETS_TABLE)?;
                        let _ = write_txn.open_table(MINT_QUOTES_TABLE)?;
                        let _ = write_txn.open_table(MELT_QUOTES_TABLE)?;
                        let _ = write_txn.open_table(MINT_KEYS_TABLE)?;
                        let _ = write_txn.open_table(PROOFS_TABLE)?;
                        let _ = write_txn.open_table(KEYSET_COUNTER)?;
                        let _ = write_txn.open_table(TRANSACTIONS_TABLE)?;
                        let _ = write_txn.open_table(KEYSET_U32_MAPPING)?;
                        let _ = write_txn.open_table(KV_STORE_TABLE)?;
                        let _ = write_txn.open_table(P2PK_SIGNING_KEYS_TABLE)?;
                        table.insert("db_version", DATABASE_VERSION.to_string().as_str())?;
                    }

                    write_txn.commit()?;
                }
            }
            drop(db);
        }

        // Check parent directory again for final database creation
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                return Err(Error::Io(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!("Parent directory does not exist: {parent:?}"),
                )));
            }
        }

        let db = Database::create(path)?;

        Ok(Self { db: Arc::new(db) })
    }
}

#[async_trait]
impl WalletDatabase<database::Error> for WalletRedbDatabase {
    #[instrument(skip(self))]
    async fn get_mint(&self, mint_url: MintUrl) -> Result<Option<MintInfo>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn.open_table(MINTS_TABLE).map_err(Error::from)?;

        if let Some(mint_info) = table
            .get(mint_url.to_string().as_str())
            .map_err(Error::from)?
        {
            return Ok(serde_json::from_str(mint_info.value()).map_err(Error::from)?);
        }

        Ok(None)
    }

    #[instrument(skip(self))]
    async fn get_mints(&self) -> Result<HashMap<MintUrl, Option<MintInfo>>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(MINTS_TABLE).map_err(Error::from)?;
        let mints = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(mint, mint_info)| {
                MintUrl::from_str(mint.value())
                    .ok()
                    .map(|url| (url, serde_json::from_str(mint_info.value()).ok()))
            })
            .collect();

        Ok(mints)
    }

    #[instrument(skip(self))]
    async fn get_mint_keysets(
        &self,
        mint_url: MintUrl,
    ) -> Result<Option<Vec<KeySetInfo>>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn
            .open_multimap_table(MINT_KEYSETS_TABLE)
            .map_err(Error::from)?;

        let keyset_ids = table
            .get(mint_url.to_string().as_str())
            .map_err(Error::from)?
            .flatten()
            .map(|k| Id::from_bytes(k.value()))
            .collect::<Result<Vec<_>, _>>()?;

        let mut keysets = vec![];

        let keysets_t = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;

        for keyset_id in keyset_ids {
            if let Some(keyset) = keysets_t
                .get(keyset_id.to_bytes().as_slice())
                .map_err(Error::from)?
            {
                let keyset = serde_json::from_str(keyset.value()).map_err(Error::from)?;

                keysets.push(keyset);
            }
        }

        match keysets.is_empty() {
            true => Ok(None),
            false => Ok(Some(keysets)),
        }
    }

    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
    async fn get_keyset_by_id(
        &self,
        keyset_id: &Id,
    ) -> Result<Option<KeySetInfo>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;

        match table
            .get(keyset_id.to_bytes().as_slice())
            .map_err(Error::from)?
        {
            Some(keyset) => {
                let keyset: KeySetInfo =
                    serde_json::from_str(keyset.value()).map_err(Error::from)?;

                Ok(Some(keyset))
            }
            None => Ok(None),
        }
    }

    #[instrument(skip_all)]
    async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn
            .open_table(MINT_QUOTES_TABLE)
            .map_err(Error::from)?;

        if let Some(mint_info) = table.get(quote_id).map_err(Error::from)? {
            return Ok(serde_json::from_str(mint_info.value()).map_err(Error::from)?);
        }

        Ok(None)
    }

    #[instrument(skip_all)]
    async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn
            .open_table(MINT_QUOTES_TABLE)
            .map_err(Error::from)?;

        Ok(table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .flat_map(|(_id, quote)| serde_json::from_str(quote.value()))
            .collect())
    }

    async fn get_unissued_mint_quotes(&self) -> Result<Vec<MintQuote>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Into::<Error>::into)?;
        let table = read_txn
            .open_table(MINT_QUOTES_TABLE)
            .map_err(Error::from)?;

        Ok(table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .flat_map(|(_id, quote)| serde_json::from_str::<MintQuote>(quote.value()).ok())
            .filter(|quote| {
                quote.amount_issued == Amount::ZERO
                    || quote.payment_method == PaymentMethod::Known(KnownMethod::Bolt12)
            })
            .collect())
    }

    #[instrument(skip_all)]
    async fn get_melt_quote(
        &self,
        quote_id: &str,
    ) -> Result<Option<wallet::MeltQuote>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(MELT_QUOTES_TABLE)
            .map_err(Error::from)?;

        if let Some(mint_info) = table.get(quote_id).map_err(Error::from)? {
            return Ok(serde_json::from_str(mint_info.value()).map_err(Error::from)?);
        }

        Ok(None)
    }

    #[instrument(skip_all)]
    async fn get_melt_quotes(&self) -> Result<Vec<wallet::MeltQuote>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(MELT_QUOTES_TABLE)
            .map_err(Error::from)?;

        Ok(table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .flat_map(|(_id, quote)| serde_json::from_str(quote.value()))
            .collect())
    }

    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
    async fn get_keys(&self, keyset_id: &Id) -> Result<Option<Keys>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(MINT_KEYS_TABLE).map_err(Error::from)?;

        if let Some(mint_info) = table
            .get(keyset_id.to_string().as_str())
            .map_err(Error::from)?
        {
            return Ok(serde_json::from_str(mint_info.value()).map_err(Error::from)?);
        }

        Ok(None)
    }

    #[instrument(skip_all)]
    async fn get_proofs(
        &self,
        mint_url: Option<MintUrl>,
        unit: Option<CurrencyUnit>,
        state: Option<Vec<State>>,
        spending_conditions: Option<Vec<SpendingConditions>>,
    ) -> Result<Vec<ProofInfo>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;

        let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

        let proofs: Vec<ProofInfo> = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_k, v)| {
                let mut proof = None;

                if let Ok(proof_info) = serde_json::from_str::<ProofInfo>(v.value()) {
                    if proof_info.matches_conditions(&mint_url, &unit, &state, &spending_conditions)
                    {
                        proof = Some(proof_info)
                    }
                }

                proof
            })
            .collect();

        Ok(proofs)
    }

    #[instrument(skip(self, ys))]
    async fn get_proofs_by_ys(
        &self,
        ys: Vec<PublicKey>,
    ) -> Result<Vec<ProofInfo>, database::Error> {
        if ys.is_empty() {
            return Ok(Vec::new());
        }

        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

        let mut proofs = Vec::new();

        for y in ys {
            if let Some(proof) = table.get(y.to_bytes().as_slice()).map_err(Error::from)? {
                let proof_info =
                    serde_json::from_str::<ProofInfo>(proof.value()).map_err(Error::from)?;
                proofs.push(proof_info);
            }
        }

        Ok(proofs)
    }

    async fn get_balance(
        &self,
        mint_url: Option<MintUrl>,
        unit: Option<CurrencyUnit>,
        state: Option<Vec<State>>,
    ) -> Result<u64, database::Error> {
        // For redb, we still need to fetch all proofs and sum them
        // since redb doesn't have SQL aggregation
        let proofs = self.get_proofs(mint_url, unit, state, None).await?;
        Ok(proofs.iter().map(|p| u64::from(p.proof.amount)).sum())
    }

    #[instrument(skip(self))]
    async fn get_transaction(
        &self,
        transaction_id: TransactionId,
    ) -> Result<Option<Transaction>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(TRANSACTIONS_TABLE)
            .map_err(Error::from)?;

        if let Some(transaction) = table.get(transaction_id.as_slice()).map_err(Error::from)? {
            return Ok(serde_json::from_str(transaction.value()).map_err(Error::from)?);
        }

        Ok(None)
    }

    #[instrument(skip(self))]
    async fn list_transactions(
        &self,
        mint_url: Option<MintUrl>,
        direction: Option<TransactionDirection>,
        unit: Option<CurrencyUnit>,
    ) -> Result<Vec<Transaction>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;

        let table = read_txn
            .open_table(TRANSACTIONS_TABLE)
            .map_err(Error::from)?;

        let transactions: Vec<Transaction> = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_k, v)| {
                let mut transaction = None;

                if let Ok(tx) = serde_json::from_str::<Transaction>(v.value()) {
                    if tx.matches_conditions(&mint_url, &direction, &unit) {
                        transaction = Some(tx)
                    }
                }

                transaction
            })
            .collect();

        Ok(transactions)
    }

    #[instrument(skip(self, added, removed_ys))]
    async fn update_proofs(
        &self,
        added: Vec<ProofInfo>,
        removed_ys: Vec<PublicKey>,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

            for proof_info in added.iter() {
                table
                    .insert(
                        proof_info.y.to_bytes().as_slice(),
                        serde_json::to_string(&proof_info)
                            .map_err(Error::from)?
                            .as_str(),
                    )
                    .map_err(Error::from)?;
            }

            for y in removed_ys.iter() {
                table.remove(y.to_bytes().as_slice()).map_err(Error::from)?;
            }
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    async fn update_proofs_state(
        &self,
        ys: Vec<PublicKey>,
        state: State,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

            for y in ys {
                let y_slice = y.to_bytes();
                let proof = table
                    .get(y_slice.as_slice())
                    .map_err(Error::from)?
                    .ok_or(Error::UnknownY)?;

                let mut proof_info =
                    serde_json::from_str::<ProofInfo>(proof.value()).map_err(Error::from)?;
                drop(proof);

                proof_info.state = state;

                table
                    .insert(
                        y_slice.as_slice(),
                        serde_json::to_string(&proof_info)
                            .map_err(Error::from)?
                            .as_str(),
                    )
                    .map_err(Error::from)?;
            }
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn add_transaction(&self, transaction: Transaction) -> Result<(), database::Error> {
        let id = transaction.id();
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(TRANSACTIONS_TABLE)
                .map_err(Error::from)?;
            table
                .insert(
                    id.as_slice(),
                    serde_json::to_string(&transaction)
                        .map_err(Error::from)?
                        .as_str(),
                )
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn update_mint_url(
        &self,
        old_mint_url: MintUrl,
        new_mint_url: MintUrl,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;

        // Update proofs table
        {
            let read_table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
            let proofs: Vec<ProofInfo> = read_table
                .iter()
                .map_err(Error::from)?
                .flatten()
                .filter_map(|(_k, v)| {
                    let proof_info = serde_json::from_str::<ProofInfo>(v.value()).ok()?;
                    if proof_info.mint_url == old_mint_url {
                        Some(proof_info)
                    } else {
                        None
                    }
                })
                .collect();
            drop(read_table);

            if !proofs.is_empty() {
                let mut write_table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
                for mut proof_info in proofs {
                    proof_info.mint_url = new_mint_url.clone();
                    write_table
                        .insert(
                            proof_info.y.to_bytes().as_slice(),
                            serde_json::to_string(&proof_info)
                                .map_err(Error::from)?
                                .as_str(),
                        )
                        .map_err(Error::from)?;
                }
            }
        }

        // Update mint quotes
        {
            let mut table = write_txn
                .open_table(MINT_QUOTES_TABLE)
                .map_err(Error::from)?;

            let unix_time = unix_time();

            let quotes: Vec<MintQuote> = table
                .iter()
                .map_err(Error::from)?
                .flatten()
                .filter_map(|(_, quote)| {
                    let mut q: MintQuote = serde_json::from_str(quote.value()).ok()?;
                    if q.mint_url == old_mint_url && q.expiry >= unix_time {
                        q.mint_url = new_mint_url.clone();
                        Some(q)
                    } else {
                        None
                    }
                })
                .collect();

            for quote in quotes {
                table
                    .insert(
                        quote.id.as_str(),
                        serde_json::to_string(&quote).map_err(Error::from)?.as_str(),
                    )
                    .map_err(Error::from)?;
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
    async fn increment_keyset_counter(
        &self,
        keyset_id: &Id,
        count: u32,
    ) -> Result<u32, database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let new_counter = {
            let mut table = write_txn.open_table(KEYSET_COUNTER).map_err(Error::from)?;
            let current_counter = table
                .get(keyset_id.to_string().as_str())
                .map_err(Error::from)?
                .map(|x| x.value())
                .unwrap_or_default();

            let new_counter = current_counter + count;

            table
                .insert(keyset_id.to_string().as_str(), new_counter)
                .map_err(Error::from)?;

            new_counter
        };
        write_txn.commit().map_err(Error::from)?;
        Ok(new_counter)
    }

    #[instrument(skip(self))]
    async fn add_mint(
        &self,
        mint_url: MintUrl,
        mint_info: Option<MintInfo>,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(MINTS_TABLE).map_err(Error::from)?;
            table
                .insert(
                    mint_url.to_string().as_str(),
                    serde_json::to_string(&mint_info)
                        .map_err(Error::from)?
                        .as_str(),
                )
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn remove_mint(&self, mint_url: MintUrl) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(MINTS_TABLE).map_err(Error::from)?;
            table
                .remove(mint_url.to_string().as_str())
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn add_mint_keysets(
        &self,
        mint_url: MintUrl,
        keysets: Vec<KeySetInfo>,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_multimap_table(MINT_KEYSETS_TABLE)
                .map_err(Error::from)?;
            let mut keysets_table = write_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
            let mut u32_table = write_txn
                .open_table(KEYSET_U32_MAPPING)
                .map_err(Error::from)?;

            let mut existing_u32 = false;

            for keyset in keysets {
                // Check if keyset already exists
                let existing_keyset = {
                    let existing_keyset = keysets_table
                        .get(keyset.id.to_bytes().as_slice())
                        .map_err(Error::from)?;

                    existing_keyset.map(|r| r.value().to_string())
                };

                let existing = u32_table
                    .insert(u32::from(keyset.id), keyset.id.to_string().as_str())
                    .map_err(Error::from)?;

                match existing {
                    None => existing_u32 = false,
                    Some(id) => {
                        let id = Id::from_str(id.value())?;

                        if id == keyset.id {
                            existing_u32 = false;
                        } else {
                            existing_u32 = true;
                            break;
                        }
                    }
                }

                let keyset = if let Some(existing_keyset) = existing_keyset {
                    let mut existing_keyset: KeySetInfo = serde_json::from_str(&existing_keyset)?;

                    existing_keyset.active = keyset.active;
                    existing_keyset.input_fee_ppk = keyset.input_fee_ppk;

                    existing_keyset
                } else {
                    table
                        .insert(
                            mint_url.to_string().as_str(),
                            keyset.id.to_bytes().as_slice(),
                        )
                        .map_err(Error::from)?;

                    keyset
                };

                keysets_table
                    .insert(
                        keyset.id.to_bytes().as_slice(),
                        serde_json::to_string(&keyset)
                            .map_err(Error::from)?
                            .as_str(),
                    )
                    .map_err(Error::from)?;
            }

            if existing_u32 {
                tracing::warn!("Keyset already exists for keyset id");
                return Err(database::Error::Duplicate);
            }
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(MINT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Check for existing quote and version match
            let existing_quote_json = table
                .get(quote.id.as_str())
                .map_err(Error::from)?
                .map(|v| v.value().to_string());

            let mut quote_to_save = quote.clone();

            if let Some(json) = existing_quote_json {
                let existing_quote: MintQuote = serde_json::from_str(&json).map_err(Error::from)?;

                if existing_quote.version != quote.version {
                    return Err(database::Error::ConcurrentUpdate);
                }

                // Increment version for update
                quote_to_save.version = quote.version.wrapping_add(1);
            }

            table
                .insert(
                    quote_to_save.id.as_str(),
                    serde_json::to_string(&quote_to_save)
                        .map_err(Error::from)?
                        .as_str(),
                )
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(MINT_QUOTES_TABLE)
                .map_err(Error::from)?;
            table.remove(quote_id).map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn add_melt_quote(&self, quote: wallet::MeltQuote) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(MELT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Check for existing quote and version match
            let existing_quote_json = table
                .get(quote.id.as_str())
                .map_err(Error::from)?
                .map(|v| v.value().to_string());

            let mut quote_to_save = quote.clone();

            if let Some(json) = existing_quote_json {
                let existing_quote: wallet::MeltQuote =
                    serde_json::from_str(&json).map_err(Error::from)?;

                if existing_quote.version != quote.version {
                    return Err(database::Error::ConcurrentUpdate);
                }

                // Increment version for update
                quote_to_save.version = quote.version.wrapping_add(1);
            }

            table
                .insert(
                    quote_to_save.id.as_str(),
                    serde_json::to_string(&quote_to_save)
                        .map_err(Error::from)?
                        .as_str(),
                )
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(MELT_QUOTES_TABLE)
                .map_err(Error::from)?;
            table.remove(quote_id).map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn add_keys(&self, keyset: KeySet) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;

        keyset.verify_id()?;

        {
            let mut table = write_txn.open_table(MINT_KEYS_TABLE).map_err(Error::from)?;

            let existing_keys = table
                .insert(
                    keyset.id.to_string().as_str(),
                    serde_json::to_string(&keyset.keys)
                        .map_err(Error::from)?
                        .as_str(),
                )
                .map_err(Error::from)?
                .is_some();

            let mut table = write_txn
                .open_table(KEYSET_U32_MAPPING)
                .map_err(Error::from)?;

            let existing = table
                .insert(u32::from(keyset.id), keyset.id.to_string().as_str())
                .map_err(Error::from)?;

            let existing_u32 = match existing {
                None => false,
                Some(id) => {
                    let id = Id::from_str(id.value())?;
                    id != keyset.id
                }
            };

            if existing_keys || existing_u32 {
                tracing::warn!("Keys already exist for keyset id");
                return Err(database::Error::Duplicate);
            }
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
    async fn remove_keys(&self, keyset_id: &Id) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(MINT_KEYS_TABLE).map_err(Error::from)?;

            table
                .remove(keyset_id.to_string().as_str())
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn remove_transaction(
        &self,
        transaction_id: TransactionId,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(TRANSACTIONS_TABLE)
                .map_err(Error::from)?;
            table
                .remove(transaction_id.as_slice())
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn add_saga(&self, saga: wallet::WalletSaga) -> Result<(), database::Error> {
        let saga_json = serde_json::to_string(&saga).map_err(Error::from)?;
        let id_str = saga.id.to_string();

        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(SAGAS_TABLE).map_err(Error::from)?;
            table
                .insert(id_str.as_str(), saga_json.as_str())
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn get_saga(
        &self,
        id: &uuid::Uuid,
    ) -> Result<Option<wallet::WalletSaga>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(SAGAS_TABLE).map_err(Error::from)?;
        let id_str = id.to_string();

        let result = table
            .get(id_str.as_str())
            .map_err(Error::from)?
            .map(|saga| serde_json::from_str(saga.value()).map_err(Error::from))
            .transpose()?;

        Ok(result)
    }

    #[instrument(skip(self))]
    async fn update_saga(&self, saga: wallet::WalletSaga) -> Result<bool, database::Error> {
        let id_str = saga.id.to_string();

        // The saga.version has already been incremented by the caller, so we check
        // for (saga.version - 1) as the expected version in the database.
        let expected_version = saga.version.saturating_sub(1);

        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let updated = {
            let mut table = write_txn.open_table(SAGAS_TABLE).map_err(Error::from)?;

            // Read existing saga to check version (optimistic locking)
            let existing_saga_json = table
                .get(id_str.as_str())
                .map_err(Error::from)?
                .map(|v| v.value().to_string());

            match existing_saga_json {
                Some(json) => {
                    let existing_saga: wallet::WalletSaga =
                        serde_json::from_str(&json).map_err(Error::from)?;

                    // Check if version matches expected version
                    if existing_saga.version != expected_version {
                        // Version mismatch - another instance modified it
                        false
                    } else {
                        // Version matches - safe to update
                        let saga_json = serde_json::to_string(&saga).map_err(Error::from)?;
                        table
                            .insert(id_str.as_str(), saga_json.as_str())
                            .map_err(Error::from)?;
                        true
                    }
                }
                None => {
                    // Saga doesn't exist - can't update
                    false
                }
            }
        };
        write_txn.commit().map_err(Error::from)?;
        Ok(updated)
    }

    #[instrument(skip(self))]
    async fn delete_saga(&self, id: &uuid::Uuid) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let id_str = id.to_string();
        {
            let mut table = write_txn.open_table(SAGAS_TABLE).map_err(Error::from)?;
            table.remove(id_str.as_str()).map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn get_incomplete_sagas(&self) -> Result<Vec<wallet::WalletSaga>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(SAGAS_TABLE).map_err(Error::from)?;

        let mut sagas: Vec<wallet::WalletSaga> = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_, saga_json)| {
                serde_json::from_str::<wallet::WalletSaga>(saga_json.value()).ok()
            })
            .collect();

        // Sort by created_at ascending (oldest first)
        sagas.sort_by_key(|saga| saga.created_at);

        Ok(sagas)
    }

    #[instrument(skip(self))]
    async fn reserve_proofs(
        &self,
        ys: Vec<PublicKey>,
        operation_id: &uuid::Uuid,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;

        {
            let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

            for y in ys {
                let y_bytes = y.to_bytes();

                // Read the proof and convert to string immediately
                let proof_json_str = {
                    let proof_json_opt = table.get(y_bytes.as_slice()).map_err(Error::from)?;
                    proof_json_opt.map(|proof_json| proof_json.value().to_string())
                };

                let Some(proof_json_str) = proof_json_str else {
                    return Err(database::Error::ProofNotUnspent);
                };

                let mut proof: ProofInfo =
                    serde_json::from_str(&proof_json_str).map_err(Error::from)?;

                if proof.state != State::Unspent {
                    return Err(database::Error::ProofNotUnspent);
                }

                proof.state = State::Reserved;
                proof.used_by_operation = Some(*operation_id);

                let updated_json = serde_json::to_string(&proof).map_err(Error::from)?;
                table
                    .insert(y_bytes.as_slice(), updated_json.as_str())
                    .map_err(Error::from)?;
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn release_proofs(&self, operation_id: &uuid::Uuid) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;

        {
            let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

            // Collect all proofs first to avoid borrowing issues
            let all_proofs: Vec<(Vec<u8>, ProofInfo)> = table
                .iter()
                .map_err(Error::from)?
                .flatten()
                .filter_map(|(y, proof_json)| {
                    let proof: ProofInfo = serde_json::from_str(proof_json.value()).ok()?;
                    Some((y.value().to_vec(), proof))
                })
                .collect();

            // Now update proofs that match the operation_id
            for (y_bytes, mut proof) in all_proofs {
                if proof.used_by_operation == Some(*operation_id) {
                    proof.state = State::Unspent;
                    proof.used_by_operation = None;

                    let updated_json = serde_json::to_string(&proof).map_err(Error::from)?;
                    table
                        .insert(y_bytes.as_slice(), updated_json.as_str())
                        .map_err(Error::from)?;
                }
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn get_reserved_proofs(
        &self,
        operation_id: &uuid::Uuid,
    ) -> Result<Vec<ProofInfo>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;

        let proofs: Vec<ProofInfo> = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_, proof_json)| {
                serde_json::from_str::<ProofInfo>(proof_json.value()).ok()
            })
            .filter(|proof| proof.used_by_operation == Some(*operation_id))
            .collect();

        Ok(proofs)
    }

    #[instrument(skip(self))]
    async fn reserve_melt_quote(
        &self,
        quote_id: &str,
        operation_id: &uuid::Uuid,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let operation_id_str = operation_id.to_string();

        {
            let mut table = write_txn
                .open_table(MELT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Read existing quote
            let quote_json = table
                .get(quote_id)
                .map_err(Error::from)?
                .map(|v| v.value().to_string());

            match quote_json {
                Some(json) => {
                    let mut quote: wallet::MeltQuote =
                        serde_json::from_str(&json).map_err(Error::from)?;

                    // Check if already reserved by another operation
                    if quote.used_by_operation.is_some() {
                        return Err(database::Error::QuoteAlreadyInUse);
                    }

                    // Reserve the quote
                    quote.used_by_operation = Some(operation_id_str);
                    let updated_json = serde_json::to_string(&quote).map_err(Error::from)?;
                    table
                        .insert(quote_id, updated_json.as_str())
                        .map_err(Error::from)?;
                }
                None => {
                    return Err(database::Error::UnknownQuote);
                }
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn release_melt_quote(&self, operation_id: &uuid::Uuid) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let operation_id_str = operation_id.to_string();

        {
            let mut table = write_txn
                .open_table(MELT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Collect all quotes first to avoid borrowing issues
            let all_quotes: Vec<(String, wallet::MeltQuote)> = table
                .iter()
                .map_err(Error::from)?
                .flatten()
                .filter_map(|(id, quote_json)| {
                    let quote: wallet::MeltQuote = serde_json::from_str(quote_json.value()).ok()?;
                    Some((id.value().to_string(), quote))
                })
                .collect();

            // Update quotes that match the operation_id
            for (quote_id, mut quote) in all_quotes {
                if quote.used_by_operation.as_deref() == Some(&operation_id_str) {
                    quote.used_by_operation = None;
                    let updated_json = serde_json::to_string(&quote).map_err(Error::from)?;
                    table
                        .insert(quote_id.as_str(), updated_json.as_str())
                        .map_err(Error::from)?;
                }
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn reserve_mint_quote(
        &self,
        quote_id: &str,
        operation_id: &uuid::Uuid,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let operation_id_str = operation_id.to_string();

        {
            let mut table = write_txn
                .open_table(MINT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Read existing quote
            let quote_json = table
                .get(quote_id)
                .map_err(Error::from)?
                .map(|v| v.value().to_string());

            match quote_json {
                Some(json) => {
                    let mut quote: MintQuote = serde_json::from_str(&json).map_err(Error::from)?;

                    // Check if already reserved by another operation
                    if quote.used_by_operation.is_some() {
                        return Err(database::Error::QuoteAlreadyInUse);
                    }

                    // Reserve the quote
                    quote.used_by_operation = Some(operation_id_str);
                    let updated_json = serde_json::to_string(&quote).map_err(Error::from)?;
                    table
                        .insert(quote_id, updated_json.as_str())
                        .map_err(Error::from)?;
                }
                None => {
                    return Err(database::Error::UnknownQuote);
                }
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn release_mint_quote(&self, operation_id: &uuid::Uuid) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        let operation_id_str = operation_id.to_string();

        {
            let mut table = write_txn
                .open_table(MINT_QUOTES_TABLE)
                .map_err(Error::from)?;

            // Collect all quotes first to avoid borrowing issues
            let all_quotes: Vec<(String, MintQuote)> = table
                .iter()
                .map_err(Error::from)?
                .flatten()
                .filter_map(|(id, quote_json)| {
                    let quote: MintQuote = serde_json::from_str(quote_json.value()).ok()?;
                    Some((id.value().to_string(), quote))
                })
                .collect();

            // Update quotes that match the operation_id
            for (quote_id, mut quote) in all_quotes {
                if quote.used_by_operation.as_deref() == Some(&operation_id_str) {
                    quote.used_by_operation = None;
                    let updated_json = serde_json::to_string(&quote).map_err(Error::from)?;
                    table
                        .insert(quote_id.as_str(), updated_json.as_str())
                        .map_err(Error::from)?;
                }
            }
        }

        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self, value))]
    async fn kv_write(
        &self,
        primary_namespace: &str,
        secondary_namespace: &str,
        key: &str,
        value: &[u8],
    ) -> Result<(), database::Error> {
        // Validate parameters according to KV store requirements
        validate_kvstore_params(primary_namespace, secondary_namespace, Some(key))?;

        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(KV_STORE_TABLE).map_err(Error::from)?;
            table
                .insert((primary_namespace, secondary_namespace, key), value)
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;

        Ok(())
    }

    #[instrument(skip(self))]
    async fn kv_read(
        &self,
        primary_namespace: &str,
        secondary_namespace: &str,
        key: &str,
    ) -> Result<Option<Vec<u8>>, database::Error> {
        // Validate parameters according to KV store requirements
        validate_kvstore_params(primary_namespace, secondary_namespace, Some(key))?;

        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(KV_STORE_TABLE).map_err(Error::from)?;

        let result = table
            .get((primary_namespace, secondary_namespace, key))
            .map_err(Error::from)?
            .map(|v| v.value().to_vec());

        Ok(result)
    }

    #[instrument(skip(self))]
    async fn kv_list(
        &self,
        primary_namespace: &str,
        secondary_namespace: &str,
    ) -> Result<Vec<String>, database::Error> {
        // Validate parameters according to KV store requirements
        validate_kvstore_params(primary_namespace, secondary_namespace, None)?;

        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn.open_table(KV_STORE_TABLE).map_err(Error::from)?;

        let start = (primary_namespace, secondary_namespace, "");
        let iter = table.range(start..).map_err(Error::from)?;

        let mut keys = Vec::new();

        for item in iter {
            let (key, _) = item.map_err(Error::from)?;
            let (p, s, k) = key.value();
            if p == primary_namespace && s == secondary_namespace {
                keys.push(k.to_string());
            } else {
                break;
            }
        }

        Ok(keys)
    }

    #[instrument(skip(self))]
    async fn kv_remove(
        &self,
        primary_namespace: &str,
        secondary_namespace: &str,
        key: &str,
    ) -> Result<(), database::Error> {
        // Validate parameters according to KV store requirements
        validate_kvstore_params(primary_namespace, secondary_namespace, Some(key))?;

        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn.open_table(KV_STORE_TABLE).map_err(Error::from)?;
            table
                .remove((primary_namespace, secondary_namespace, key))
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;

        Ok(())
    }

    #[instrument(skip(self))]
    async fn add_p2pk_key(
        &self,
        pubkey: &PublicKey,
        derivation_path: DerivationPath,
        derivation_index: u32,
    ) -> Result<(), database::Error> {
        let write_txn = self.db.begin_write().map_err(Error::from)?;
        {
            let mut table = write_txn
                .open_table(P2PK_SIGNING_KEYS_TABLE)
                .map_err(Error::from)?;
            table
                .insert(
                    pubkey.to_bytes().as_slice(),
                    serde_json::to_string(&wallet::P2PKSigningKey {
                        pubkey: *pubkey,
                        derivation_path,
                        derivation_index,
                        created_time: unix_time(),
                    })
                    .map_err(Error::from)?
                    .as_str(),
                )
                .map_err(Error::from)?;
        }
        write_txn.commit().map_err(Error::from)?;
        Ok(())
    }

    #[instrument(skip(self))]
    async fn get_p2pk_key(
        &self,
        pubkey: &PublicKey,
    ) -> Result<Option<wallet::P2PKSigningKey>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(P2PK_SIGNING_KEYS_TABLE)
            .map_err(Error::from)?;

        if let Some(key) = table
            .get(pubkey.to_bytes().as_slice())
            .map_err(Error::from)?
        {
            return Ok(Some(
                serde_json::from_str(key.value()).map_err(Error::from)?,
            ));
        }

        Ok(None)
    }

    #[instrument(skip(self))]
    async fn list_p2pk_keys(&self) -> Result<Vec<wallet::P2PKSigningKey>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(P2PK_SIGNING_KEYS_TABLE)
            .map_err(Error::from)?;

        let keys: Vec<wallet::P2PKSigningKey> = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_k, v)| {
                if let Ok(key) = serde_json::from_str::<wallet::P2PKSigningKey>(v.value()) {
                    return Some(key);
                }

                None
            })
            .collect();

        Ok(keys)
    }

    #[instrument(skip(self))]
    async fn latest_p2pk(&self) -> Result<Option<wallet::P2PKSigningKey>, database::Error> {
        let read_txn = self.db.begin_read().map_err(Error::from)?;
        let table = read_txn
            .open_table(P2PK_SIGNING_KEYS_TABLE)
            .map_err(Error::from)?;

        let latest_key = table
            .iter()
            .map_err(Error::from)?
            .flatten()
            .filter_map(|(_k, v)| serde_json::from_str::<wallet::P2PKSigningKey>(v.value()).ok())
            .max_by_key(|key| key.derivation_index);

        Ok(latest_key)
    }
}

#[cfg(test)]
mod test {
    use std::path::PathBuf;

    use cdk_common::wallet_db_test;

    use super::WalletRedbDatabase;

    async fn provide_db(test_id: String) -> WalletRedbDatabase {
        let path = PathBuf::from(format!("/tmp/cdk-test-{}.redb", test_id));
        WalletRedbDatabase::new(&path).expect("database")
    }

    wallet_db_test!(provide_db);
}