summaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/wallet.ts
blob: 733c239f99fe7752603bfd9c6bd75b0476d6e116 (plain)
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
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
/*
 This file is part of GNU Taler
 (C) 2015-2019 GNUnet e.V.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * High-level wallet operations that should be indepentent from the underlying
 * browser extension interface.
 */

/**
 * Imports.
 */
import {
  AbsoluteTime,
  Amounts,
  CoinDumpJson,
  CoinRefreshRequest,
  CoinStatus,
  CoreApiResponse,
  DenomOperationMap,
  DenominationInfo,
  Duration,
  ExchangeDetailedResponse,
  ExchangeListItem,
  ExchangeTosStatusDetails,
  ExchangesListResponse,
  FeeDescription,
  GetExchangeTosResult,
  InitResponse,
  KnownBankAccounts,
  KnownBankAccountsInfo,
  Logger,
  ManualWithdrawalDetails,
  MerchantUsingTemplateDetails,
  NotificationType,
  RefreshReason,
  TalerError,
  TalerErrorCode,
  URL,
  ValidateIbanResponse,
  WalletCoreVersion,
  WalletNotification,
  codecForAbortTransaction,
  codecForAcceptBankIntegratedWithdrawalRequest,
  codecForAcceptExchangeTosRequest,
  codecForAcceptManualWithdrawalRequet,
  codecForAcceptPeerPullPaymentRequest,
  codecForAcceptTipRequest,
  codecForAddExchangeRequest,
  codecForAddKnownBankAccounts,
  codecForAny,
  codecForApplyDevExperiment,
  codecForApplyRefundFromPurchaseIdRequest,
  codecForApplyRefundRequest,
  codecForCheckPeerPullPaymentRequest,
  codecForCheckPeerPushDebitRequest,
  codecForConfirmPayRequest,
  codecForConfirmPeerPushPaymentRequest,
  codecForCreateDepositGroupRequest,
  codecForDeleteTransactionRequest,
  codecForForceRefreshRequest,
  codecForForgetKnownBankAccounts,
  codecForGetBalanceDetailRequest,
  codecForGetContractTermsDetails,
  codecForGetExchangeTosRequest,
  codecForGetWithdrawalDetailsForAmountRequest,
  codecForGetWithdrawalDetailsForUri,
  codecForImportDbRequest,
  codecForInitiatePeerPullPaymentRequest,
  codecForInitiatePeerPushPaymentRequest,
  codecForIntegrationTestArgs,
  codecForIntegrationTestV2Args,
  codecForListKnownBankAccounts,
  codecForMerchantPostOrderResponse,
  codecForPrepareDepositRequest,
  codecForPreparePayRequest,
  codecForPreparePayTemplateRequest,
  codecForPreparePeerPullPaymentRequest,
  codecForPreparePeerPushCreditRequest,
  codecForPrepareRefundRequest,
  codecForPrepareTipRequest,
  codecForResumeTransaction,
  codecForRetryTransactionRequest,
  codecForSetCoinSuspendedRequest,
  codecForSetWalletDeviceIdRequest,
  codecForSuspendTransaction,
  codecForTestPayArgs,
  codecForTransactionByIdRequest,
  codecForTransactionsRequest,
  codecForUserAttentionByIdRequest,
  codecForUserAttentionsRequest,
  codecForValidateIbanRequest,
  codecForWithdrawFakebankRequest,
  codecForWithdrawTestBalance,
  constructPayUri,
  durationFromSpec,
  durationMin,
  getErrorDetailFromException,
  j2s,
  parsePayTemplateUri,
  parsePaytoUri,
  validateIban,
} from "@gnu-taler/taler-util";
import {
  HttpRequestLibrary,
  readSuccessResponseJsonOrThrow,
} from "@gnu-taler/taler-util/http";
import { TalerCryptoInterface } from "./crypto/cryptoImplementation.js";
import {
  CryptoDispatcher,
  CryptoWorkerFactory,
} from "./crypto/workers/crypto-dispatcher.js";
import {
  CoinSourceType,
  ConfigRecordKey,
  DenominationRecord,
  ExchangeDetailsRecord,
  WalletStoresV1,
  clearDatabase,
  exportDb,
  importDb,
} from "./db.js";
import { DevExperimentHttpLib, applyDevExperiment } from "./dev-experiments.js";
import {
  ActiveLongpollInfo,
  ExchangeOperations,
  InternalWalletState,
  MerchantInfo,
  MerchantOperations,
  NotificationListener,
  RecoupOperations,
  RefreshOperations,
} from "./internal-wallet-state.js";
import {
  getUserAttentions,
  getUserAttentionsUnreadCount,
  markAttentionRequestAsRead,
} from "./operations/attention.js";
import { exportBackup } from "./operations/backup/export.js";
import {
  addBackupProvider,
  codecForAddBackupProviderRequest,
  codecForRemoveBackupProvider,
  codecForRunBackupCycle,
  getBackupInfo,
  getBackupRecovery,
  importBackupPlain,
  loadBackupRecovery,
  processBackupForProvider,
  removeBackupProvider,
  runBackupCycle,
} from "./operations/backup/index.js";
import { setWalletDeviceId } from "./operations/backup/state.js";
import { getBalanceDetail, getBalances } from "./operations/balance.js";
import {
  getExchangeTosStatus,
  makeExchangeListItem,
  runOperationWithErrorReporting,
} from "./operations/common.js";
import {
  createDepositGroup,
  generateDepositGroupTxId,
  prepareDepositGroup,
  processDepositGroup,
} from "./operations/deposits.js";
import {
  acceptExchangeTermsOfService,
  downloadTosFromAcceptedFormat,
  getExchangeDetails,
  getExchangeRequestTimeout,
  getExchangeTrust,
  provideExchangeRecordInTx,
  updateExchangeFromUrl,
  updateExchangeFromUrlHandler,
  updateExchangeTermsOfService,
} from "./operations/exchanges.js";
import { getMerchantInfo } from "./operations/merchants.js";
import {
  applyRefund,
  applyRefundFromPurchaseId,
  confirmPay,
  getContractTermsDetails,
  preparePayForUri,
  prepareRefund,
  processPurchase,
} from "./operations/pay-merchant.js";
import {
  checkPeerPullPaymentInitiation,
  checkPeerPushDebit,
  confirmPeerPullDebit,
  confirmPeerPushCredit,
  initiatePeerPullPayment,
  initiatePeerPushPayment,
  preparePeerPullDebit,
  preparePeerPushCredit,
  processPeerPullCredit,
  processPeerPullDebit,
  processPeerPushCredit,
  processPeerPushInitiation,
} from "./operations/pay-peer.js";
import { getPendingOperations } from "./operations/pending.js";
import {
  createRecoupGroup,
  processRecoupGroup,
  processRecoupGroupHandler,
} from "./operations/recoup.js";
import {
  autoRefresh,
  createRefreshGroup,
  processRefreshGroup,
} from "./operations/refresh.js";
import {
  runIntegrationTest,
  runIntegrationTest2,
  testPay,
  withdrawTestBalance,
} from "./operations/testing.js";
import { acceptTip, prepareTip, processTip } from "./operations/tip.js";
import {
  abortTransaction,
  deleteTransaction,
  getTransactionById,
  getTransactions,
  resumeTransaction,
  retryTransaction,
  suspendTransaction,
} from "./operations/transactions.js";
import {
  acceptWithdrawalFromUri,
  createManualWithdrawal,
  getExchangeWithdrawalInfo,
  getWithdrawalDetailsForUri,
  processWithdrawalGroup,
} from "./operations/withdraw.js";
import { PendingTaskInfo, PendingTaskType } from "./pending-types.js";
import { assertUnreachable } from "./util/assertUnreachable.js";
import {
  createTimeline,
  selectBestForOverlappingDenominations,
  selectMinimumFee,
} from "./util/denominations.js";
import { checkDbInvariant } from "./util/invariants.js";
import {
  AsyncCondition,
  OpenedPromise,
  openPromise,
} from "./util/promiseUtils.js";
import {
  DbAccess,
  GetReadOnlyAccess,
  GetReadWriteAccess,
} from "./util/query.js";
import { OperationAttemptResult, TaskIdentifiers } from "./util/retries.js";
import { TimerAPI, TimerGroup } from "./util/timer.js";
import {
  WALLET_BANK_INTEGRATION_PROTOCOL_VERSION,
  WALLET_EXCHANGE_PROTOCOL_VERSION,
  WALLET_MERCHANT_PROTOCOL_VERSION,
} from "./versions.js";
import {
  WalletApiOperation,
  WalletConfig,
  WalletConfigParameter,
  WalletCoreApiClient,
  WalletCoreResponseType,
} from "./wallet-api-types.js";

const logger = new Logger("wallet.ts");

/**
 * Call the right handler for a pending operation without doing
 * any special error handling.
 */
async function callOperationHandler(
  ws: InternalWalletState,
  pending: PendingTaskInfo,
  forceNow = false,
): Promise<OperationAttemptResult> {
  switch (pending.type) {
    case PendingTaskType.ExchangeUpdate:
      return await updateExchangeFromUrlHandler(ws, pending.exchangeBaseUrl, {
        forceNow,
      });
    case PendingTaskType.Refresh:
      return await processRefreshGroup(ws, pending.refreshGroupId);
    case PendingTaskType.Withdraw:
      return await processWithdrawalGroup(ws, pending.withdrawalGroupId, {
        forceNow,
      });
    case PendingTaskType.TipPickup:
      return await processTip(ws, pending.tipId);
    case PendingTaskType.Purchase:
      return await processPurchase(ws, pending.proposalId);
    case PendingTaskType.Recoup:
      return await processRecoupGroupHandler(ws, pending.recoupGroupId, {
        forceNow,
      });
    case PendingTaskType.ExchangeCheckRefresh:
      return await autoRefresh(ws, pending.exchangeBaseUrl);
    case PendingTaskType.Deposit: {
      return await processDepositGroup(ws, pending.depositGroupId);
    }
    case PendingTaskType.Backup:
      return await processBackupForProvider(ws, pending.backupProviderBaseUrl);
    case PendingTaskType.PeerPushInitiation:
      return await processPeerPushInitiation(ws, pending.pursePub);
    case PendingTaskType.PeerPullInitiation:
      return await processPeerPullCredit(ws, pending.pursePub);
    case PendingTaskType.PeerPullDebit:
      return await processPeerPullDebit(ws, pending.peerPullPaymentIncomingId);
    case PendingTaskType.PeerPushCredit:
      return await processPeerPushCredit(ws, pending.peerPushPaymentIncomingId);
    default:
      return assertUnreachable(pending);
  }
  throw Error(`not reached ${pending.type}`);
}

/**
 * Process pending operations.
 */
export async function runPending(
  ws: InternalWalletState,
  forceNow = false,
): Promise<void> {
  const pendingOpsResponse = await getPendingOperations(ws);
  for (const p of pendingOpsResponse.pendingOperations) {
    if (!forceNow && !AbsoluteTime.isExpired(p.timestampDue)) {
      continue;
    }
    await runOperationWithErrorReporting(ws, p.id, async () => {
      logger.trace(`running pending ${JSON.stringify(p, undefined, 2)}`);
      return await callOperationHandler(ws, p, forceNow);
    });
  }
}

export interface RetryLoopOpts {
  /**
   * Stop when the number of retries is exceeded for any pending
   * operation.
   */
  maxRetries?: number;

  /**
   * Stop the retry loop when all lifeness-giving pending operations
   * are done.
   *
   * Defaults to false.
   */
  stopWhenDone?: boolean;
}

export interface TaskLoopResult {
  /**
   * Was the maximum number of retries exceeded in a task?
   */
  retriesExceeded: boolean;
}

/**
 * Main retry loop of the wallet.
 *
 * Looks up pending operations from the wallet, runs them, repeat.
 */
async function runTaskLoop(
  ws: InternalWalletState,
  opts: RetryLoopOpts = {},
): Promise<TaskLoopResult> {
  logger.info(`running task loop opts=${j2s(opts)}`);
  let retriesExceeded = false;
  for (let iteration = 0; !ws.stopped; iteration++) {
    const pending = await getPendingOperations(ws);
    logger.trace(`pending operations: ${j2s(pending)}`);
    let numGivingLiveness = 0;
    let numDue = 0;
    let minDue: AbsoluteTime = AbsoluteTime.never();

    for (const p of pending.pendingOperations) {
      const maxRetries = opts.maxRetries;

      if (maxRetries && p.retryInfo && p.retryInfo.retryCounter > maxRetries) {
        retriesExceeded = true;
        logger.warn(
          `skipping, as ${maxRetries} retries are exceeded in an operation of type ${p.type}`,
        );
        continue;
      }
      if (p.givesLifeness) {
        numGivingLiveness++;
      }
      if (!p.isDue) {
        continue;
      }
      minDue = AbsoluteTime.min(minDue, p.timestampDue);
      numDue++;
    }

    if (opts.stopWhenDone && numGivingLiveness === 0 && iteration !== 0) {
      logger.warn(`stopping, as no pending operations have lifeness`);
      return {
        retriesExceeded,
      };
    }

    // Make sure that we run tasks that don't give lifeness at least
    // one time.
    if (iteration !== 0 && numDue === 0) {
      // We've executed pending, due operations at least one.
      // Now we don't have any more operations available,
      // and need to wait.

      // Wait for at most 5 seconds to the next check.
      const dt = durationMin(
        durationFromSpec({
          seconds: 5,
        }),
        Duration.getRemaining(minDue),
      );
      logger.trace(`waiting for at most ${dt.d_ms} ms`);
      const timeout = ws.timerGroup.resolveAfter(dt);
      ws.notify({
        type: NotificationType.WaitingForRetry,
        numGivingLiveness,
        numDue,
        numPending: pending.pendingOperations.length,
      });
      // Wait until either the timeout, or we are notified (via the latch)
      // that more work might be available.
      await Promise.race([timeout, ws.latch.wait()]);
    } else {
      logger.trace(
        `running ${pending.pendingOperations.length} pending operations`,
      );
      for (const p of pending.pendingOperations) {
        if (!AbsoluteTime.isExpired(p.timestampDue)) {
          continue;
        }
        await runOperationWithErrorReporting(ws, p.id, async () => {
          logger.trace(`running pending ${JSON.stringify(p, undefined, 2)}`);
          return await callOperationHandler(ws, p);
        });
        ws.notify({
          type: NotificationType.PendingOperationProcessed,
          id: p.id,
        });
      }
    }
  }
  logger.trace("exiting wallet retry loop");
  return {
    retriesExceeded,
  };
}

/**
 * Insert the hard-coded defaults for exchanges, coins and
 * auditors into the database, unless these defaults have
 * already been applied.
 */
async function fillDefaults(ws: InternalWalletState): Promise<void> {
  await ws.db
    .mktx((x) => [x.config, x.auditorTrust, x.exchanges, x.exchangeDetails])
    .runReadWrite(async (tx) => {
      const appliedRec = await tx.config.get("currencyDefaultsApplied");
      let alreadyApplied = appliedRec ? !!appliedRec.value : false;
      if (alreadyApplied) {
        logger.trace("defaults already applied");
        return;
      }
      logger.info("importing default exchanges and auditors");
      for (const c of ws.config.builtin.auditors) {
        await tx.auditorTrust.put(c);
      }
      for (const baseUrl of ws.config.builtin.exchanges) {
        const now = AbsoluteTime.now();
        provideExchangeRecordInTx(ws, tx, baseUrl, now);
      }
      await tx.config.put({
        key: ConfigRecordKey.CurrencyDefaultsApplied,
        value: true,
      });
    });
}

/**
 * Get the exchange ToS in the requested format.
 * Try to download in the accepted format not cached.
 */
async function getExchangeTos(
  ws: InternalWalletState,
  exchangeBaseUrl: string,
  acceptedFormat?: string[],
): Promise<GetExchangeTosResult> {
  // FIXME: download ToS in acceptable format if passed!
  const { exchangeDetails } = await updateExchangeFromUrl(ws, exchangeBaseUrl);
  const tosDetails = await ws.db
    .mktx((x) => [x.exchangeTos])
    .runReadOnly(async (tx) => {
      return await getExchangeTosStatusDetails(tx, exchangeDetails);
    });
  const content = tosDetails.content;
  const currentEtag = tosDetails.currentVersion;
  const contentType = tosDetails.contentType;
  if (
    content === undefined ||
    currentEtag === undefined ||
    contentType === undefined
  ) {
    throw Error("exchange is in invalid state");
  }
  if (
    acceptedFormat &&
    acceptedFormat.findIndex((f) => f === contentType) !== -1
  ) {
    return {
      acceptedEtag: exchangeDetails.tosAccepted?.etag,
      currentEtag,
      content,
      contentType,
      tosStatus: getExchangeTosStatus(exchangeDetails),
    };
  }

  const tosDownload = await downloadTosFromAcceptedFormat(
    ws,
    exchangeBaseUrl,
    getExchangeRequestTimeout(),
    acceptedFormat,
  );

  if (tosDownload.tosContentType === contentType) {
    return {
      acceptedEtag: exchangeDetails.tosAccepted?.etag,
      currentEtag,
      content,
      contentType,
      tosStatus: getExchangeTosStatus(exchangeDetails),
    };
  }

  await updateExchangeTermsOfService(ws, exchangeBaseUrl, tosDownload);

  return {
    acceptedEtag: exchangeDetails.tosAccepted?.etag,
    currentEtag: tosDownload.tosEtag,
    content: tosDownload.tosText,
    contentType: tosDownload.tosContentType,
    tosStatus: getExchangeTosStatus(exchangeDetails),
  };
}

/**
 * List bank accounts known to the wallet from
 * previous withdrawals.
 */
async function listKnownBankAccounts(
  ws: InternalWalletState,
  currency?: string,
): Promise<KnownBankAccounts> {
  const accounts: KnownBankAccountsInfo[] = [];
  await ws.db
    .mktx((x) => [x.bankAccounts])
    .runReadOnly(async (tx) => {
      const knownAccounts = await tx.bankAccounts.iter().toArray();
      for (const r of knownAccounts) {
        if (currency && currency !== r.currency) {
          continue;
        }
        const payto = parsePaytoUri(r.uri);
        if (payto) {
          accounts.push({
            uri: payto,
            alias: r.alias,
            kyc_completed: r.kycCompleted,
            currency: r.currency,
          });
        }
      }
    });
  return { accounts };
}

/**
 */
async function addKnownBankAccounts(
  ws: InternalWalletState,
  payto: string,
  alias: string,
  currency: string,
): Promise<void> {
  await ws.db
    .mktx((x) => [x.bankAccounts])
    .runReadWrite(async (tx) => {
      tx.bankAccounts.put({
        uri: payto,
        alias: alias,
        currency: currency,
        kycCompleted: false,
      });
    });
  return;
}

/**
 */
async function forgetKnownBankAccounts(
  ws: InternalWalletState,
  payto: string,
): Promise<void> {
  await ws.db
    .mktx((x) => [x.bankAccounts])
    .runReadWrite(async (tx) => {
      const account = await tx.bankAccounts.get(payto);
      if (!account) {
        throw Error(`account not found: ${payto}`);
      }
      tx.bankAccounts.delete(account.uri);
    });
  return;
}

async function getExchangeTosStatusDetails(
  tx: GetReadOnlyAccess<{ exchangeTos: typeof WalletStoresV1.exchangeTos }>,
  exchangeDetails: ExchangeDetailsRecord,
): Promise<ExchangeTosStatusDetails> {
  let exchangeTos = await tx.exchangeTos.get([
    exchangeDetails.exchangeBaseUrl,
    exchangeDetails.tosCurrentEtag,
  ]);

  if (!exchangeTos) {
    exchangeTos = {
      etag: "not-available",
      termsOfServiceContentType: "text/plain",
      termsOfServiceText: "terms of service unavailable",
      exchangeBaseUrl: exchangeDetails.exchangeBaseUrl,
    };
  }

  return {
    acceptedVersion: exchangeDetails.tosAccepted?.etag,
    content: exchangeTos.termsOfServiceText,
    contentType: exchangeTos.termsOfServiceContentType,
    currentVersion: exchangeTos.etag,
  };
}

async function getExchanges(
  ws: InternalWalletState,
): Promise<ExchangesListResponse> {
  const exchanges: ExchangeListItem[] = [];
  await ws.db
    .mktx((x) => [
      x.exchanges,
      x.exchangeDetails,
      x.exchangeTos,
      x.denominations,
      x.operationRetries,
    ])
    .runReadOnly(async (tx) => {
      const exchangeRecords = await tx.exchanges.iter().toArray();
      for (const r of exchangeRecords) {
        const exchangeDetails = await getExchangeDetails(tx, r.baseUrl);
        const opRetryRecord = await tx.operationRetries.get(
          TaskIdentifiers.forExchangeUpdate(r),
        );
        exchanges.push(
          makeExchangeListItem(r, exchangeDetails, opRetryRecord?.lastError),
        );
      }
    });
  return { exchanges };
}

async function getExchangeDetailedInfo(
  ws: InternalWalletState,
  exchangeBaseurl: string,
): Promise<ExchangeDetailedResponse> {
  //TODO: should we use the forceUpdate parameter?
  const exchange = await ws.db
    .mktx((x) => [
      x.exchanges,
      x.exchangeTos,
      x.exchangeDetails,
      x.denominations,
    ])
    .runReadOnly(async (tx) => {
      const ex = await tx.exchanges.get(exchangeBaseurl);
      const dp = ex?.detailsPointer;
      if (!dp) {
        return;
      }
      const { currency } = dp;
      const exchangeDetails = await getExchangeDetails(tx, ex.baseUrl);
      if (!exchangeDetails) {
        return;
      }

      const denominationRecords =
        await tx.denominations.indexes.byExchangeBaseUrl
          .iter(ex.baseUrl)
          .toArray();

      if (!denominationRecords) {
        return;
      }

      const tos = await getExchangeTosStatusDetails(tx, exchangeDetails);

      const denominations: DenominationInfo[] = denominationRecords.map((x) =>
        DenominationRecord.toDenomInfo(x),
      );

      return {
        info: {
          exchangeBaseUrl: ex.baseUrl,
          currency,
          tos,
          paytoUris: exchangeDetails.wireInfo.accounts.map((x) => x.payto_uri),
          auditors: exchangeDetails.auditors,
          wireInfo: exchangeDetails.wireInfo,
          globalFees: exchangeDetails.globalFees,
        },
        denominations,
      };
    });

  if (!exchange) {
    throw Error(`exchange with base url "${exchangeBaseurl}" not found`);
  }

  const denoms = exchange.denominations.map((d) => ({
    ...d,
    group: Amounts.stringifyValue(d.value),
  }));
  const denomFees: DenomOperationMap<FeeDescription[]> = {
    deposit: createTimeline(
      denoms,
      "denomPubHash",
      "stampStart",
      "stampExpireDeposit",
      "feeDeposit",
      "group",
      selectBestForOverlappingDenominations,
    ),
    refresh: createTimeline(
      denoms,
      "denomPubHash",
      "stampStart",
      "stampExpireWithdraw",
      "feeRefresh",
      "group",
      selectBestForOverlappingDenominations,
    ),
    refund: createTimeline(
      denoms,
      "denomPubHash",
      "stampStart",
      "stampExpireWithdraw",
      "feeRefund",
      "group",
      selectBestForOverlappingDenominations,
    ),
    withdraw: createTimeline(
      denoms,
      "denomPubHash",
      "stampStart",
      "stampExpireWithdraw",
      "feeWithdraw",
      "group",
      selectBestForOverlappingDenominations,
    ),
  };

  const transferFees = Object.entries(
    exchange.info.wireInfo.feesForType,
  ).reduce((prev, [wireType, infoForType]) => {
    const feesByGroup = [
      ...infoForType.map((w) => ({
        ...w,
        fee: Amounts.stringify(w.closingFee),
        group: "closing",
      })),
      ...infoForType.map((w) => ({ ...w, fee: w.wireFee, group: "wire" })),
    ];
    prev[wireType] = createTimeline(
      feesByGroup,
      "sig",
      "startStamp",
      "endStamp",
      "fee",
      "group",
      selectMinimumFee,
    );
    return prev;
  }, {} as Record<string, FeeDescription[]>);

  const globalFeesByGroup = [
    ...exchange.info.globalFees.map((w) => ({
      ...w,
      fee: w.accountFee,
      group: "account",
    })),
    ...exchange.info.globalFees.map((w) => ({
      ...w,
      fee: w.historyFee,
      group: "history",
    })),
    ...exchange.info.globalFees.map((w) => ({
      ...w,
      fee: w.purseFee,
      group: "purse",
    })),
  ];

  const globalFees = createTimeline(
    globalFeesByGroup,
    "signature",
    "startDate",
    "endDate",
    "fee",
    "group",
    selectMinimumFee,
  );

  return {
    exchange: {
      ...exchange.info,
      denomFees,
      transferFees,
      globalFees,
    },
  };
}

async function setCoinSuspended(
  ws: InternalWalletState,
  coinPub: string,
  suspended: boolean,
): Promise<void> {
  await ws.db
    .mktx((x) => [x.coins, x.coinAvailability])
    .runReadWrite(async (tx) => {
      const c = await tx.coins.get(coinPub);
      if (!c) {
        logger.warn(`coin ${coinPub} not found, won't suspend`);
        return;
      }
      const coinAvailability = await tx.coinAvailability.get([
        c.exchangeBaseUrl,
        c.denomPubHash,
        c.maxAge,
      ]);
      checkDbInvariant(!!coinAvailability);
      if (suspended) {
        if (c.status !== CoinStatus.Fresh) {
          return;
        }
        if (coinAvailability.freshCoinCount === 0) {
          throw Error(
            `invalid coin count ${coinAvailability.freshCoinCount} in DB`,
          );
        }
        coinAvailability.freshCoinCount--;
        c.status = CoinStatus.FreshSuspended;
      } else {
        if (c.status == CoinStatus.Dormant) {
          return;
        }
        coinAvailability.freshCoinCount++;
        c.status = CoinStatus.Fresh;
      }
      await tx.coins.put(c);
      await tx.coinAvailability.put(coinAvailability);
    });
}

/**
 * Dump the public information of coins we have in an easy-to-process format.
 */
async function dumpCoins(ws: InternalWalletState): Promise<CoinDumpJson> {
  const coinsJson: CoinDumpJson = { coins: [] };
  logger.info("dumping coins");
  await ws.db
    .mktx((x) => [x.coins, x.denominations, x.withdrawalGroups])
    .runReadOnly(async (tx) => {
      const coins = await tx.coins.iter().toArray();
      for (const c of coins) {
        const denom = await tx.denominations.get([
          c.exchangeBaseUrl,
          c.denomPubHash,
        ]);
        if (!denom) {
          logger.warn("no denom found for coin");
          continue;
        }
        const cs = c.coinSource;
        let refreshParentCoinPub: string | undefined;
        if (cs.type == CoinSourceType.Refresh) {
          refreshParentCoinPub = cs.oldCoinPub;
        }
        let withdrawalReservePub: string | undefined;
        if (cs.type == CoinSourceType.Withdraw) {
          withdrawalReservePub = cs.reservePub;
        }
        const denomInfo = await ws.getDenomInfo(
          ws,
          tx,
          c.exchangeBaseUrl,
          c.denomPubHash,
        );
        if (!denomInfo) {
          logger.warn("no denomination found for coin");
          continue;
        }
        coinsJson.coins.push({
          coin_pub: c.coinPub,
          denom_pub: denomInfo.denomPub,
          denom_pub_hash: c.denomPubHash,
          denom_value: Amounts.stringify({
            value: denom.amountVal,
            currency: denom.currency,
            fraction: denom.amountFrac,
          }),
          exchange_base_url: c.exchangeBaseUrl,
          refresh_parent_coin_pub: refreshParentCoinPub,
          withdrawal_reserve_pub: withdrawalReservePub,
          coin_status: c.status,
          ageCommitmentProof: c.ageCommitmentProof,
          spend_allocation: c.spendAllocation
            ? {
                amount: c.spendAllocation.amount,
                id: c.spendAllocation.id,
              }
            : undefined,
        });
      }
    });
  return coinsJson;
}

/**
 * Get an API client from an internal wallet state object.
 */
export async function getClientFromWalletState(
  ws: InternalWalletState,
): Promise<WalletCoreApiClient> {
  let id = 0;
  const client: WalletCoreApiClient = {
    async call(op, payload): Promise<any> {
      const res = await handleCoreApiRequest(ws, op, `${id++}`, payload);
      switch (res.type) {
        case "error":
          throw TalerError.fromUncheckedDetail(res.error);
        case "response":
          return res.result;
      }
    },
  };
  return client;
}

declare const __VERSION__: string;
declare const __GIT_HASH__: string;

const VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "dev";
const GIT_HASH = typeof __GIT_HASH__ !== "undefined" ? __GIT_HASH__ : undefined;

/**
 * Implementation of the "wallet-core" API.
 */
async function dispatchRequestInternal<Op extends WalletApiOperation>(
  ws: InternalWalletState,
  operation: WalletApiOperation,
  payload: unknown,
): Promise<WalletCoreResponseType<typeof operation>> {
  if (!ws.initCalled && operation !== WalletApiOperation.InitWallet) {
    throw Error(
      `wallet must be initialized before running operation ${operation}`,
    );
  }
  // FIXME: Can we make this more type-safe by using the request/response type
  // definitions we already have?
  switch (operation) {
    case WalletApiOperation.InitWallet: {
      logger.trace("initializing wallet");
      ws.initCalled = true;
      if (typeof payload === "object" && (payload as any).skipDefaults) {
        logger.trace("skipping defaults");
      } else {
        logger.trace("filling defaults");
        await fillDefaults(ws);
      }
      const resp: InitResponse = {
        versionInfo: getVersion(ws),
      };
      return resp;
    }
    case WalletApiOperation.WithdrawTestkudos: {
      await withdrawTestBalance(ws, {
        amount: "TESTKUDOS:10",
        bankAccessApiBaseUrl:
          "https://bank.test.taler.net/demobanks/default/access-api/",
        exchangeBaseUrl: "https://exchange.test.taler.net/",
      });
      return {
        versionInfo: getVersion(ws),
      };
    }
    case WalletApiOperation.WithdrawTestBalance: {
      const req = codecForWithdrawTestBalance().decode(payload);
      await withdrawTestBalance(ws, req);
      return {};
    }
    case WalletApiOperation.RunIntegrationTest: {
      const req = codecForIntegrationTestArgs().decode(payload);
      await runIntegrationTest(ws, req);
      return {};
    }
    case WalletApiOperation.RunIntegrationTestV2: {
      const req = codecForIntegrationTestV2Args().decode(payload);
      await runIntegrationTest2(ws, req);
      return {};
    }
    case WalletApiOperation.ValidateIban: {
      const req = codecForValidateIbanRequest().decode(payload);
      const valRes = validateIban(req.iban);
      const resp: ValidateIbanResponse = {
        valid: valRes.type === "valid",
      };
      return resp;
    }
    case WalletApiOperation.TestPay: {
      const req = codecForTestPayArgs().decode(payload);
      return await testPay(ws, req);
    }
    case WalletApiOperation.GetTransactions: {
      const req = codecForTransactionsRequest().decode(payload);
      return await getTransactions(ws, req);
    }
    case WalletApiOperation.GetTransactionById: {
      const req = codecForTransactionByIdRequest().decode(payload);
      return await getTransactionById(ws, req);
    }
    case WalletApiOperation.AddExchange: {
      const req = codecForAddExchangeRequest().decode(payload);
      await updateExchangeFromUrl(ws, req.exchangeBaseUrl, {
        forceNow: req.forceUpdate,
      });
      return {};
    }
    case WalletApiOperation.ListExchanges: {
      return await getExchanges(ws);
    }
    case WalletApiOperation.GetExchangeDetailedInfo: {
      const req = codecForAddExchangeRequest().decode(payload);
      return await getExchangeDetailedInfo(ws, req.exchangeBaseUrl);
    }
    case WalletApiOperation.ListKnownBankAccounts: {
      const req = codecForListKnownBankAccounts().decode(payload);
      return await listKnownBankAccounts(ws, req.currency);
    }
    case WalletApiOperation.AddKnownBankAccounts: {
      const req = codecForAddKnownBankAccounts().decode(payload);
      await addKnownBankAccounts(ws, req.payto, req.alias, req.currency);
      return {};
    }
    case WalletApiOperation.ForgetKnownBankAccounts: {
      const req = codecForForgetKnownBankAccounts().decode(payload);
      await forgetKnownBankAccounts(ws, req.payto);
      return {};
    }
    case WalletApiOperation.GetWithdrawalDetailsForUri: {
      const req = codecForGetWithdrawalDetailsForUri().decode(payload);
      return await getWithdrawalDetailsForUri(ws, req.talerWithdrawUri);
    }
    case WalletApiOperation.AcceptManualWithdrawal: {
      const req = codecForAcceptManualWithdrawalRequet().decode(payload);
      const res = await createManualWithdrawal(ws, {
        amount: Amounts.parseOrThrow(req.amount),
        exchangeBaseUrl: req.exchangeBaseUrl,
        restrictAge: req.restrictAge,
      });
      return res;
    }
    case WalletApiOperation.GetWithdrawalDetailsForAmount: {
      const req =
        codecForGetWithdrawalDetailsForAmountRequest().decode(payload);
      const wi = await getExchangeWithdrawalInfo(
        ws,
        req.exchangeBaseUrl,
        Amounts.parseOrThrow(req.amount),
        req.restrictAge,
      );
      const resp: ManualWithdrawalDetails = {
        amountRaw: req.amount,
        amountEffective: Amounts.stringify(wi.selectedDenoms.totalCoinValue),
        paytoUris: wi.exchangePaytoUris,
        tosAccepted: wi.termsOfServiceAccepted,
        ageRestrictionOptions: wi.ageRestrictionOptions,
      };
      return resp;
    }
    case WalletApiOperation.GetBalances: {
      return await getBalances(ws);
    }
    case WalletApiOperation.GetBalanceDetail: {
      const req = codecForGetBalanceDetailRequest().decode(payload);
      return await getBalanceDetail(ws, req);
    }
    case WalletApiOperation.GetUserAttentionRequests: {
      const req = codecForUserAttentionsRequest().decode(payload);
      return await getUserAttentions(ws, req);
    }
    case WalletApiOperation.MarkAttentionRequestAsRead: {
      const req = codecForUserAttentionByIdRequest().decode(payload);
      return await markAttentionRequestAsRead(ws, req);
    }
    case WalletApiOperation.GetUserAttentionUnreadCount: {
      const req = codecForUserAttentionsRequest().decode(payload);
      return await getUserAttentionsUnreadCount(ws, req);
    }
    case WalletApiOperation.GetPendingOperations: {
      return await getPendingOperations(ws);
    }
    case WalletApiOperation.SetExchangeTosAccepted: {
      const req = codecForAcceptExchangeTosRequest().decode(payload);
      await acceptExchangeTermsOfService(ws, req.exchangeBaseUrl, req.etag);
      return {};
    }
    case WalletApiOperation.ApplyRefund: {
      const req = codecForApplyRefundRequest().decode(payload);
      return await applyRefund(ws, req.talerRefundUri);
    }
    case WalletApiOperation.ApplyRefundFromPurchaseId: {
      const req = codecForApplyRefundFromPurchaseIdRequest().decode(payload);
      return await applyRefundFromPurchaseId(ws, req.purchaseId);
    }
    case WalletApiOperation.AcceptBankIntegratedWithdrawal: {
      const req =
        codecForAcceptBankIntegratedWithdrawalRequest().decode(payload);
      return await acceptWithdrawalFromUri(ws, {
        selectedExchange: req.exchangeBaseUrl,
        talerWithdrawUri: req.talerWithdrawUri,
        forcedDenomSel: req.forcedDenomSel,
        restrictAge: req.restrictAge,
      });
    }
    case WalletApiOperation.GetExchangeTos: {
      const req = codecForGetExchangeTosRequest().decode(payload);
      return getExchangeTos(ws, req.exchangeBaseUrl, req.acceptedFormat);
    }
    case WalletApiOperation.GetContractTermsDetails: {
      const req = codecForGetContractTermsDetails().decode(payload);
      return getContractTermsDetails(ws, req.proposalId);
    }
    case WalletApiOperation.RetryPendingNow: {
      await runPending(ws, true);
      return {};
    }
    case WalletApiOperation.PreparePayForUri: {
      const req = codecForPreparePayRequest().decode(payload);
      return await preparePayForUri(ws, req.talerPayUri);
    }
    case WalletApiOperation.PreparePayForTemplate: {
      const req = codecForPreparePayTemplateRequest().decode(payload);
      const url = parsePayTemplateUri(req.talerPayTemplateUri);
      const templateDetails: MerchantUsingTemplateDetails = {};
      if (!url) {
        throw Error("invalid taler-template URI");
      }
      if (
        url.templateParams.amount !== undefined &&
        typeof url.templateParams.amount === "string"
      ) {
        templateDetails.amount =
          req.templateParams.amount ?? url.templateParams.amount;
      }
      if (
        url.templateParams.summary !== undefined &&
        typeof url.templateParams.summary === "string"
      ) {
        templateDetails.summary =
          req.templateParams.summary ?? url.templateParams.summary;
      }
      const reqUrl = new URL(
        `templates/${url.templateId}`,
        url.merchantBaseUrl,
      );
      const httpReq = await ws.http.postJson(reqUrl.href, templateDetails);
      const resp = await readSuccessResponseJsonOrThrow(
        httpReq,
        codecForMerchantPostOrderResponse(),
      );

      const payUri = constructPayUri(
        url.merchantBaseUrl,
        resp.order_id,
        "",
        resp.token,
      );

      return await preparePayForUri(ws, payUri);
    }
    case WalletApiOperation.ConfirmPay: {
      const req = codecForConfirmPayRequest().decode(payload);
      return await confirmPay(ws, req.proposalId, req.sessionId);
    }
    case WalletApiOperation.AbortTransaction: {
      const req = codecForAbortTransaction().decode(payload);
      await abortTransaction(ws, req.transactionId);
      return {};
    }
    case WalletApiOperation.SuspendTransaction: {
      const req = codecForSuspendTransaction().decode(payload);
      await suspendTransaction(ws, req.transactionId);
      return {};
    }
    case WalletApiOperation.ResumeTransaction: {
      const req = codecForResumeTransaction().decode(payload);
      await resumeTransaction(ws, req.transactionId);
      return {};
    }
    case WalletApiOperation.DumpCoins: {
      return await dumpCoins(ws);
    }
    case WalletApiOperation.SetCoinSuspended: {
      const req = codecForSetCoinSuspendedRequest().decode(payload);
      await setCoinSuspended(ws, req.coinPub, req.suspended);
      return {};
    }
    case WalletApiOperation.ForceRefresh: {
      const req = codecForForceRefreshRequest().decode(payload);
      if (req.coinPubList.length == 0) {
        throw Error("refusing to create empty refresh group");
      }
      const refreshGroupId = await ws.db
        .mktx((x) => [
          x.refreshGroups,
          x.coinAvailability,
          x.denominations,
          x.coins,
        ])
        .runReadWrite(async (tx) => {
          let coinPubs: CoinRefreshRequest[] = [];
          for (const c of req.coinPubList) {
            const coin = await tx.coins.get(c);
            if (!coin) {
              throw Error(`coin (pubkey ${c}) not found`);
            }
            const denom = await ws.getDenomInfo(
              ws,
              tx,
              coin.exchangeBaseUrl,
              coin.denomPubHash,
            );
            checkDbInvariant(!!denom);
            coinPubs.push({
              coinPub: c,
              amount: denom?.value,
            });
          }
          return await createRefreshGroup(
            ws,
            tx,
            Amounts.currencyOf(coinPubs[0].amount),
            coinPubs,
            RefreshReason.Manual,
          );
        });
      processRefreshGroup(ws, refreshGroupId.refreshGroupId).catch((x) => {
        logger.error(x);
      });
      return {
        refreshGroupId,
      };
    }
    case WalletApiOperation.PrepareTip: {
      const req = codecForPrepareTipRequest().decode(payload);
      return await prepareTip(ws, req.talerTipUri);
    }
    case WalletApiOperation.PrepareRefund: {
      const req = codecForPrepareRefundRequest().decode(payload);
      return await prepareRefund(ws, req.talerRefundUri);
    }
    case WalletApiOperation.AcceptTip: {
      const req = codecForAcceptTipRequest().decode(payload);
      return await acceptTip(ws, req.walletTipId);
    }
    case WalletApiOperation.ExportBackupPlain: {
      return exportBackup(ws);
    }
    case WalletApiOperation.AddBackupProvider: {
      const req = codecForAddBackupProviderRequest().decode(payload);
      return await addBackupProvider(ws, req);
    }
    case WalletApiOperation.RunBackupCycle: {
      const req = codecForRunBackupCycle().decode(payload);
      await runBackupCycle(ws, req);
      return {};
    }
    case WalletApiOperation.RemoveBackupProvider: {
      const req = codecForRemoveBackupProvider().decode(payload);
      await removeBackupProvider(ws, req);
      return {};
    }
    case WalletApiOperation.ExportBackupRecovery: {
      const resp = await getBackupRecovery(ws);
      return resp;
    }
    case WalletApiOperation.ImportBackupRecovery: {
      const req = codecForAny().decode(payload);
      await loadBackupRecovery(ws, req);
      return {};
    }
    case WalletApiOperation.GetBackupInfo: {
      const resp = await getBackupInfo(ws);
      return resp;
    }
    case WalletApiOperation.PrepareDeposit: {
      const req = codecForPrepareDepositRequest().decode(payload);
      return await prepareDepositGroup(ws, req);
    }
    case WalletApiOperation.GenerateDepositGroupTxId:
      return {
        transactionId: generateDepositGroupTxId(),
      };
    case WalletApiOperation.CreateDepositGroup: {
      const req = codecForCreateDepositGroupRequest().decode(payload);
      return await createDepositGroup(ws, req);
    }
    case WalletApiOperation.DeleteTransaction: {
      const req = codecForDeleteTransactionRequest().decode(payload);
      await deleteTransaction(ws, req.transactionId);
      return {};
    }
    case WalletApiOperation.RetryTransaction: {
      const req = codecForRetryTransactionRequest().decode(payload);
      await retryTransaction(ws, req.transactionId);
      return {};
    }
    case WalletApiOperation.SetWalletDeviceId: {
      const req = codecForSetWalletDeviceIdRequest().decode(payload);
      await setWalletDeviceId(ws, req.walletDeviceId);
      return {};
    }
    case WalletApiOperation.ListCurrencies: {
      return await ws.db
        .mktx((x) => [x.auditorTrust, x.exchangeTrust])
        .runReadOnly(async (tx) => {
          const trustedAuditors = await tx.auditorTrust.iter().toArray();
          const trustedExchanges = await tx.exchangeTrust.iter().toArray();
          return {
            trustedAuditors: trustedAuditors.map((x) => ({
              currency: x.currency,
              auditorBaseUrl: x.auditorBaseUrl,
              auditorPub: x.auditorPub,
            })),
            trustedExchanges: trustedExchanges.map((x) => ({
              currency: x.currency,
              exchangeBaseUrl: x.exchangeBaseUrl,
              exchangeMasterPub: x.exchangeMasterPub,
            })),
          };
        });
    }
    case WalletApiOperation.WithdrawFakebank: {
      const req = codecForWithdrawFakebankRequest().decode(payload);
      const amount = Amounts.parseOrThrow(req.amount);
      const details = await getExchangeWithdrawalInfo(
        ws,
        req.exchange,
        amount,
        undefined,
      );
      const wres = await createManualWithdrawal(ws, {
        amount: amount,
        exchangeBaseUrl: req.exchange,
      });
      const paytoUri = details.exchangePaytoUris[0];
      const pt = parsePaytoUri(paytoUri);
      if (!pt) {
        throw Error("failed to parse payto URI");
      }
      const components = pt.targetPath.split("/");
      const creditorAcct = components[components.length - 1];
      logger.info(`making testbank transfer to '${creditorAcct}'`);
      const fbReq = await ws.http.postJson(
        new URL(`${creditorAcct}/admin/add-incoming`, req.bank).href,
        {
          amount: Amounts.stringify(amount),
          reserve_pub: wres.reservePub,
          debit_account:
            "payto://x-taler-bank/localhost/testdebtor?receiver-name=Foo",
        },
      );
      const fbResp = await readSuccessResponseJsonOrThrow(fbReq, codecForAny());
      logger.info(`started fakebank withdrawal: ${j2s(fbResp)}`);
      return {};
    }
    case WalletApiOperation.TestCrypto: {
      return await ws.cryptoApi.hashString({ str: "hello world" });
    }
    case WalletApiOperation.ClearDb:
      await clearDatabase(ws.db.idbHandle());
      return {};
    case WalletApiOperation.Recycle: {
      const backup = await exportBackup(ws);
      await clearDatabase(ws.db.idbHandle());
      await importBackupPlain(ws, backup);
      return {};
    }
    case WalletApiOperation.ExportDb: {
      const dbDump = await exportDb(ws.db.idbHandle());
      return dbDump;
    }
    case WalletApiOperation.ImportDb: {
      const req = codecForImportDbRequest().decode(payload);
      await importDb(ws.db.idbHandle(), req.dump);
      return [];
    }
    case WalletApiOperation.CheckPeerPushDebit: {
      const req = codecForCheckPeerPushDebitRequest().decode(payload);
      return await checkPeerPushDebit(ws, req);
    }
    case WalletApiOperation.InitiatePeerPushDebit: {
      const req = codecForInitiatePeerPushPaymentRequest().decode(payload);
      return await initiatePeerPushPayment(ws, req);
    }
    case WalletApiOperation.PreparePeerPushCredit: {
      const req = codecForPreparePeerPushCreditRequest().decode(payload);
      return await preparePeerPushCredit(ws, req);
    }
    case WalletApiOperation.ConfirmPeerPushCredit: {
      const req = codecForConfirmPeerPushPaymentRequest().decode(payload);
      return await confirmPeerPushCredit(ws, req);
    }
    case WalletApiOperation.CheckPeerPullCredit: {
      const req = codecForPreparePeerPullPaymentRequest().decode(payload);
      return await checkPeerPullPaymentInitiation(ws, req);
    }
    case WalletApiOperation.InitiatePeerPullCredit: {
      const req = codecForInitiatePeerPullPaymentRequest().decode(payload);
      return await initiatePeerPullPayment(ws, req);
    }
    case WalletApiOperation.PreparePeerPullDebit: {
      const req = codecForCheckPeerPullPaymentRequest().decode(payload);
      return await preparePeerPullDebit(ws, req);
    }
    case WalletApiOperation.ConfirmPeerPullDebit: {
      const req = codecForAcceptPeerPullPaymentRequest().decode(payload);
      return await confirmPeerPullDebit(ws, req);
    }
    case WalletApiOperation.ApplyDevExperiment: {
      const req = codecForApplyDevExperiment().decode(payload);
      await applyDevExperiment(ws, req.devExperimentUri);
      return {};
    }
    case WalletApiOperation.GetVersion: {
      return getVersion(ws);
    }
    // default:
    //  assertUnreachable(operation);
  }
  throw TalerError.fromDetail(
    TalerErrorCode.WALLET_CORE_API_OPERATION_UNKNOWN,
    {
      operation,
    },
    "unknown operation",
  );
}

export function getVersion(ws: InternalWalletState): WalletCoreVersion {
  const version: WalletCoreVersion = {
    hash: GIT_HASH,
    version: VERSION,
    exchange: WALLET_EXCHANGE_PROTOCOL_VERSION,
    merchant: WALLET_MERCHANT_PROTOCOL_VERSION,
    bank: WALLET_BANK_INTEGRATION_PROTOCOL_VERSION,
    devMode: false,
  };
  return version;
}

function translateLegacyOperationNames(operation: string): string {
  switch (operation) {
    case "initiatePeerPullPayment":
      return WalletApiOperation.InitiatePeerPullCredit.toString();
    case "initiatePeerPushPayment":
      return WalletApiOperation.InitiatePeerPushDebit.toString();
    case "checkPeerPullPayment":
      return WalletApiOperation.PreparePeerPullDebit.toString();
    case "acceptPeerPullPayment":
      return WalletApiOperation.ConfirmPeerPullDebit.toString();
    case "checkPeerPushPayment":
      return WalletApiOperation.PreparePeerPushCredit.toString();
    case "acceptPeerPushPayment":
      return WalletApiOperation.ConfirmPeerPushCredit.toString();
  }
  return operation;
}

/**
 * Handle a request to the wallet-core API.
 */
export async function handleCoreApiRequest(
  ws: InternalWalletState,
  operation: string,
  id: string,
  payload: unknown,
): Promise<CoreApiResponse> {
  operation = translateLegacyOperationNames(operation);

  try {
    const result = await dispatchRequestInternal(ws, operation as any, payload);
    return {
      type: "response",
      operation,
      id,
      result,
    };
  } catch (e: any) {
    const err = getErrorDetailFromException(e);
    logger.info(`finished wallet core request with error: ${j2s(err)}`);
    return {
      type: "error",
      operation,
      id,
      error: err,
    };
  }
}

/**
 * Public handle to a running wallet.
 */
export class Wallet {
  private ws: InternalWalletState;
  private _client: WalletCoreApiClient | undefined;

  private constructor(
    db: DbAccess<typeof WalletStoresV1>,
    http: HttpRequestLibrary,
    timer: TimerAPI,
    cryptoWorkerFactory: CryptoWorkerFactory,
    config?: WalletConfigParameter,
  ) {
    this.ws = new InternalWalletStateImpl(
      db,
      http,
      timer,
      cryptoWorkerFactory,
      Wallet.getEffectiveConfig(config),
    );
  }

  get client(): WalletCoreApiClient {
    if (!this._client) {
      throw Error();
    }
    return this._client;
  }

  static async create(
    db: DbAccess<typeof WalletStoresV1>,
    http: HttpRequestLibrary,
    timer: TimerAPI,
    cryptoWorkerFactory: CryptoWorkerFactory,
    config?: WalletConfigParameter,
  ): Promise<Wallet> {
    const w = new Wallet(db, http, timer, cryptoWorkerFactory, config);
    w._client = await getClientFromWalletState(w.ws);
    return w;
  }

  public static defaultConfig: Readonly<WalletConfig> = {
    builtin: {
      exchanges: ["https://exchange.demo.taler.net/"],
      auditors: [
        {
          currency: "KUDOS",
          auditorPub: "BW9DC48PHQY4NH011SHHX36DZZ3Q22Y6X7FZ1VD1CMZ2PTFZ6PN0",
          auditorBaseUrl: "https://auditor.demo.taler.net/",
          uids: ["5P25XF8TVQP9AW6VYGY2KV47WT5Y3ZXFSJAA570GJPX5SVJXKBVG"],
        },
      ],
    },
    features: {
      batchWithdrawal: false,
      allowHttp: false,
    },
    testing: {
      preventThrottling: false,
      devModeActive: false,
      insecureTrustExchange: false,
      denomselAllowLate: false,
    },
  };

  static getEffectiveConfig(
    param?: WalletConfigParameter,
  ): Readonly<WalletConfig> {
    return deepMerge(Wallet.defaultConfig, param ?? {});
  }

  addNotificationListener(f: (n: WalletNotification) => void): void {
    return this.ws.addNotificationListener(f);
  }

  stop(): void {
    this.ws.stop();
  }

  runPending(forceNow = false): Promise<void> {
    return runPending(this.ws, forceNow);
  }

  runTaskLoop(opts?: RetryLoopOpts): Promise<TaskLoopResult> {
    return runTaskLoop(this.ws, opts);
  }

  handleCoreApiRequest(
    operation: string,
    id: string,
    payload: unknown,
  ): Promise<CoreApiResponse> {
    return handleCoreApiRequest(this.ws, operation, id, payload);
  }
}

/**
 * Internal state of the wallet.
 *
 * This ties together all the operation implementations.
 */
class InternalWalletStateImpl implements InternalWalletState {
  /**
   * @see {@link InternalWalletState.activeLongpoll}
   */
  activeLongpoll: ActiveLongpollInfo = {};

  cryptoApi: TalerCryptoInterface;
  cryptoDispatcher: CryptoDispatcher;

  merchantInfoCache: Record<string, MerchantInfo> = {};

  readonly timerGroup: TimerGroup;
  latch = new AsyncCondition();
  stopped = false;

  listeners: NotificationListener[] = [];

  initCalled = false;

  exchangeOps: ExchangeOperations = {
    getExchangeDetails,
    getExchangeTrust,
    updateExchangeFromUrl,
  };

  recoupOps: RecoupOperations = {
    createRecoupGroup,
    processRecoupGroup,
  };

  merchantOps: MerchantOperations = {
    getMerchantInfo,
  };

  refreshOps: RefreshOperations = {
    createRefreshGroup,
  };

  // FIXME: Use an LRU cache here.
  private denomCache: Record<string, DenominationInfo> = {};

  /**
   * Promises that are waiting for a particular resource.
   */
  private resourceWaiters: Record<string, OpenedPromise<void>[]> = {};

  /**
   * Resources that are currently locked.
   */
  private resourceLocks: Set<string> = new Set();

  config: Readonly<WalletConfig>;

  constructor(
    // FIXME: Make this a getter and make
    // the actual value nullable.
    // Check if we are in a DB migration / garbage collection
    // and throw an error in that case.
    public db: DbAccess<typeof WalletStoresV1>,
    public http: HttpRequestLibrary,
    public timer: TimerAPI,
    cryptoWorkerFactory: CryptoWorkerFactory,
    configParam: WalletConfig,
  ) {
    this.cryptoDispatcher = new CryptoDispatcher(cryptoWorkerFactory);
    this.cryptoApi = this.cryptoDispatcher.cryptoApi;
    this.timerGroup = new TimerGroup(timer);
    this.config = configParam;
    if (this.config.testing.devModeActive) {
      this.http = new DevExperimentHttpLib(this.http);
    }
  }

  async getDenomInfo(
    ws: InternalWalletState,
    tx: GetReadWriteAccess<{
      denominations: typeof WalletStoresV1.denominations;
    }>,
    exchangeBaseUrl: string,
    denomPubHash: string,
  ): Promise<DenominationInfo | undefined> {
    const key = `${exchangeBaseUrl}:${denomPubHash}`;
    const cached = this.denomCache[key];
    if (cached) {
      return cached;
    }
    const d = await tx.denominations.get([exchangeBaseUrl, denomPubHash]);
    if (d) {
      return DenominationRecord.toDenomInfo(d);
    }
    return undefined;
  }

  notify(n: WalletNotification): void {
    logger.trace("Notification", j2s(n));
    for (const l of this.listeners) {
      const nc = JSON.parse(JSON.stringify(n));
      setTimeout(() => {
        l(nc);
      }, 0);
    }
  }

  addNotificationListener(f: (n: WalletNotification) => void): void {
    this.listeners.push(f);
  }

  /**
   * Stop ongoing processing.
   */
  stop(): void {
    logger.trace("stopping (at internal wallet state)");
    this.stopped = true;
    this.timerGroup.stopCurrentAndFutureTimers();
    this.cryptoDispatcher.stop();
    for (const key of Object.keys(this.activeLongpoll)) {
      logger.trace(`cancelling active longpoll ${key}`);
      this.activeLongpoll[key].cancel();
      delete this.activeLongpoll[key];
    }
  }

  async runUntilDone(
    req: {
      maxRetries?: number;
    } = {},
  ): Promise<void> {
    await runTaskLoop(this, { ...req, stopWhenDone: true });
  }

  /**
   * Run an async function after acquiring a list of locks, identified
   * by string tokens.
   */
  async runSequentialized<T>(
    tokens: string[],
    f: () => Promise<T>,
  ): Promise<T> {
    // Make sure locks are always acquired in the same order
    tokens = [...tokens].sort();

    for (const token of tokens) {
      if (this.resourceLocks.has(token)) {
        const p = openPromise<void>();
        let waitList = this.resourceWaiters[token];
        if (!waitList) {
          waitList = this.resourceWaiters[token] = [];
        }
        waitList.push(p);
        await p.promise;
      }
      this.resourceLocks.add(token);
    }

    try {
      logger.trace(`begin exclusive execution on ${JSON.stringify(tokens)}`);
      const result = await f();
      logger.trace(`end exclusive execution on ${JSON.stringify(tokens)}`);
      return result;
    } finally {
      for (const token of tokens) {
        this.resourceLocks.delete(token);
        let waiter = (this.resourceWaiters[token] ?? []).shift();
        if (waiter) {
          waiter.resolve();
        }
      }
    }
  }
}

/**
 * Take the full object as template, create a new result with all the values.
 * Use the override object to change the values in the result
 * return result
 * @param full
 * @param override
 * @returns
 */
function deepMerge<T extends object>(full: T, override: object): T {
  const keys = Object.keys(full);
  const result = { ...full };
  for (const k of keys) {
    // @ts-ignore
    const newVal = override[k];
    if (newVal === undefined) continue;
    // @ts-ignore
    result[k] =
      // @ts-ignore
      typeof newVal === "object" ? deepMerge(full[k], newVal) : newVal;
  }
  return result;
}