summaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/operations/pay-peer.ts
blob: f464948f844f034413f0b3a405fc847d532b0518 (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
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
/*
 This file is part of GNU Taler
 (C) 2022 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/>
 */

/**
 * Imports.
 */
import {
  AbsoluteTime,
  ConfirmPeerPullDebitRequest,
  AcceptPeerPullPaymentResponse,
  ConfirmPeerPushCreditRequest,
  AcceptPeerPushPaymentResponse,
  AgeCommitmentProof,
  AmountJson,
  Amounts,
  AmountString,
  buildCodecForObject,
  PreparePeerPullDebitRequest,
  PreparePeerPullDebitResponse,
  PreparePeerPushCredit,
  PreparePeerPushCreditResponse,
  Codec,
  codecForAmountString,
  codecForAny,
  codecForExchangeGetContractResponse,
  codecForPeerContractTerms,
  CoinStatus,
  constructPayPullUri,
  constructPayPushUri,
  ContractTermsUtil,
  decodeCrock,
  eddsaGetPublic,
  encodeCrock,
  ExchangePurseDeposits,
  ExchangePurseMergeRequest,
  ExchangeReservePurseRequest,
  getRandomBytes,
  InitiatePeerPullCreditRequest,
  InitiatePeerPullCreditResponse,
  InitiatePeerPushDebitRequest,
  InitiatePeerPushDebitResponse,
  j2s,
  Logger,
  parsePayPullUri,
  parsePayPushUri,
  PayPeerInsufficientBalanceDetails,
  PeerContractTerms,
  CheckPeerPullCreditRequest,
  CheckPeerPullCreditResponse,
  CheckPeerPushDebitRequest,
  CheckPeerPushDebitResponse,
  RefreshReason,
  strcmp,
  TalerErrorCode,
  TalerProtocolTimestamp,
  TransactionType,
  UnblindedSignature,
  WalletAccountMergeFlags,
  codecOptional,
  codecForTimestamp,
  CancellationToken,
  NotificationType,
  HttpStatusCode,
  codecForWalletKycUuid,
  TransactionState,
  TransactionMajorState,
  TransactionMinorState,
  TalerPreciseTimestamp,
} from "@gnu-taler/taler-util";
import { SpendCoinDetails } from "../crypto/cryptoImplementation.js";
import {
  DenominationRecord,
  PeerPullPaymentIncomingRecord,
  PeerPullPaymentIncomingStatus,
  PeerPullPaymentInitiationRecord,
  PeerPullPaymentInitiationStatus,
  PeerPushPaymentCoinSelection,
  PeerPushPaymentIncomingRecord,
  PeerPushPaymentIncomingStatus,
  PeerPushPaymentInitiationRecord,
  PeerPushPaymentInitiationStatus,
  ReserveRecord,
  WithdrawalGroupStatus,
  WithdrawalRecordType,
} from "../db.js";
import { TalerError } from "@gnu-taler/taler-util";
import { InternalWalletState } from "../internal-wallet-state.js";
import {
  LongpollResult,
  resetOperationTimeout,
  runLongpollAsync,
  runOperationWithErrorReporting,
  spendCoins,
} from "../operations/common.js";
import {
  readSuccessResponseJsonOrErrorCode,
  readSuccessResponseJsonOrThrow,
  throwUnexpectedRequestError,
} from "@gnu-taler/taler-util/http";
import { checkDbInvariant } from "../util/invariants.js";
import {
  constructTaskIdentifier,
  OperationAttemptResult,
  OperationAttemptResultType,
  TaskIdentifiers,
} from "../util/retries.js";
import { getPeerPaymentBalanceDetailsInTx } from "./balance.js";
import { updateExchangeFromUrl } from "./exchanges.js";
import { getTotalRefreshCost } from "./refresh.js";
import {
  checkWithdrawalKycStatus,
  getExchangeWithdrawalInfo,
  internalCreateWithdrawalGroup,
  processWithdrawalGroup,
} from "./withdraw.js";
import { PendingTaskType } from "../pending-types.js";
import {
  constructTransactionIdentifier,
  notifyTransition,
  stopLongpolling,
} from "./transactions.js";
import { assertUnreachable } from "../util/assertUnreachable.js";

const logger = new Logger("operations/peer-to-peer.ts");

interface SelectedPeerCoin {
  coinPub: string;
  coinPriv: string;
  contribution: AmountString;
  denomPubHash: string;
  denomSig: UnblindedSignature;
  ageCommitmentProof: AgeCommitmentProof | undefined;
}

interface PeerCoinSelectionDetails {
  exchangeBaseUrl: string;

  /**
   * Info of Coins that were selected.
   */
  coins: SelectedPeerCoin[];

  /**
   * How much of the deposit fees is the customer paying?
   */
  depositFees: AmountJson;
}

/**
 * Information about a selected coin for peer to peer payments.
 */
interface CoinInfo {
  /**
   * Public key of the coin.
   */
  coinPub: string;

  coinPriv: string;

  /**
   * Deposit fee for the coin.
   */
  feeDeposit: AmountJson;

  value: AmountJson;

  denomPubHash: string;

  denomSig: UnblindedSignature;

  maxAge: number;

  ageCommitmentProof?: AgeCommitmentProof;
}

export type SelectPeerCoinsResult =
  | { type: "success"; result: PeerCoinSelectionDetails }
  | {
      type: "failure";
      insufficientBalanceDetails: PayPeerInsufficientBalanceDetails;
    };

export async function queryCoinInfosForSelection(
  ws: InternalWalletState,
  csel: PeerPushPaymentCoinSelection,
): Promise<SpendCoinDetails[]> {
  let infos: SpendCoinDetails[] = [];
  await ws.db
    .mktx((x) => [x.coins, x.denominations])
    .runReadOnly(async (tx) => {
      for (let i = 0; i < csel.coinPubs.length; i++) {
        const coin = await tx.coins.get(csel.coinPubs[i]);
        if (!coin) {
          throw Error("coin not found anymore");
        }
        const denom = await ws.getDenomInfo(
          ws,
          tx,
          coin.exchangeBaseUrl,
          coin.denomPubHash,
        );
        if (!denom) {
          throw Error("denom for coin not found anymore");
        }
        infos.push({
          coinPriv: coin.coinPriv,
          coinPub: coin.coinPub,
          denomPubHash: coin.denomPubHash,
          denomSig: coin.denomSig,
          ageCommitmentProof: coin.ageCommitmentProof,
          contribution: csel.contributions[i],
        });
      }
    });
  return infos;
}

export async function selectPeerCoins(
  ws: InternalWalletState,
  instructedAmount: AmountJson,
): Promise<SelectPeerCoinsResult> {
  if (Amounts.isZero(instructedAmount)) {
    // Other parts of the code assume that we have at least
    // one coin to spend.
    throw new Error("amount of zero not allowed");
  }
  return await ws.db
    .mktx((x) => [
      x.exchanges,
      x.contractTerms,
      x.coins,
      x.coinAvailability,
      x.denominations,
      x.refreshGroups,
      x.peerPushPaymentInitiations,
    ])
    .runReadWrite(async (tx) => {
      const exchanges = await tx.exchanges.iter().toArray();
      const exchangeFeeGap: { [url: string]: AmountJson } = {};
      const currency = Amounts.currencyOf(instructedAmount);
      for (const exch of exchanges) {
        if (exch.detailsPointer?.currency !== currency) {
          continue;
        }
        const coins = (
          await tx.coins.indexes.byBaseUrl.getAll(exch.baseUrl)
        ).filter((x) => x.status === CoinStatus.Fresh);
        const coinInfos: CoinInfo[] = [];
        for (const coin of coins) {
          const denom = await ws.getDenomInfo(
            ws,
            tx,
            coin.exchangeBaseUrl,
            coin.denomPubHash,
          );
          if (!denom) {
            throw Error("denom not found");
          }
          coinInfos.push({
            coinPub: coin.coinPub,
            feeDeposit: Amounts.parseOrThrow(denom.feeDeposit),
            value: Amounts.parseOrThrow(denom.value),
            denomPubHash: denom.denomPubHash,
            coinPriv: coin.coinPriv,
            denomSig: coin.denomSig,
            maxAge: coin.maxAge,
            ageCommitmentProof: coin.ageCommitmentProof,
          });
        }
        if (coinInfos.length === 0) {
          continue;
        }
        coinInfos.sort(
          (o1, o2) =>
            -Amounts.cmp(o1.value, o2.value) ||
            strcmp(o1.denomPubHash, o2.denomPubHash),
        );
        let amountAcc = Amounts.zeroOfCurrency(currency);
        let depositFeesAcc = Amounts.zeroOfCurrency(currency);
        const resCoins: {
          coinPub: string;
          coinPriv: string;
          contribution: AmountString;
          denomPubHash: string;
          denomSig: UnblindedSignature;
          ageCommitmentProof: AgeCommitmentProof | undefined;
        }[] = [];
        let lastDepositFee = Amounts.zeroOfCurrency(currency);
        for (const coin of coinInfos) {
          if (Amounts.cmp(amountAcc, instructedAmount) >= 0) {
            break;
          }
          const gap = Amounts.add(
            coin.feeDeposit,
            Amounts.sub(instructedAmount, amountAcc).amount,
          ).amount;
          const contrib = Amounts.min(gap, coin.value);
          amountAcc = Amounts.add(
            amountAcc,
            Amounts.sub(contrib, coin.feeDeposit).amount,
          ).amount;
          depositFeesAcc = Amounts.add(depositFeesAcc, coin.feeDeposit).amount;
          resCoins.push({
            coinPriv: coin.coinPriv,
            coinPub: coin.coinPub,
            contribution: Amounts.stringify(contrib),
            denomPubHash: coin.denomPubHash,
            denomSig: coin.denomSig,
            ageCommitmentProof: coin.ageCommitmentProof,
          });
          lastDepositFee = coin.feeDeposit;
        }
        if (Amounts.cmp(amountAcc, instructedAmount) >= 0) {
          const res: PeerCoinSelectionDetails = {
            exchangeBaseUrl: exch.baseUrl,
            coins: resCoins,
            depositFees: depositFeesAcc,
          };
          return { type: "success", result: res };
        }
        const diff = Amounts.sub(instructedAmount, amountAcc).amount;
        exchangeFeeGap[exch.baseUrl] = Amounts.add(lastDepositFee, diff).amount;

        continue;
      }
      // We were unable to select coins.
      // Now we need to produce error details.

      const infoGeneral = await getPeerPaymentBalanceDetailsInTx(ws, tx, {
        currency,
      });

      const perExchange: PayPeerInsufficientBalanceDetails["perExchange"] = {};

      let maxFeeGapEstimate = Amounts.zeroOfCurrency(currency);

      for (const exch of exchanges) {
        if (exch.detailsPointer?.currency !== currency) {
          continue;
        }
        const infoExchange = await getPeerPaymentBalanceDetailsInTx(ws, tx, {
          currency,
          restrictExchangeTo: exch.baseUrl,
        });
        let gap =
          exchangeFeeGap[exch.baseUrl] ?? Amounts.zeroOfCurrency(currency);
        if (Amounts.cmp(infoExchange.balanceMaterial, instructedAmount) < 0) {
          // Show fee gap only if we should've been able to pay with the material amount
          gap = Amounts.zeroOfCurrency(currency);
        }
        perExchange[exch.baseUrl] = {
          balanceAvailable: Amounts.stringify(infoExchange.balanceAvailable),
          balanceMaterial: Amounts.stringify(infoExchange.balanceMaterial),
          feeGapEstimate: Amounts.stringify(gap),
        };

        maxFeeGapEstimate = Amounts.max(maxFeeGapEstimate, gap);
      }

      const errDetails: PayPeerInsufficientBalanceDetails = {
        amountRequested: Amounts.stringify(instructedAmount),
        balanceAvailable: Amounts.stringify(infoGeneral.balanceAvailable),
        balanceMaterial: Amounts.stringify(infoGeneral.balanceMaterial),
        feeGapEstimate: Amounts.stringify(maxFeeGapEstimate),
        perExchange,
      };

      return { type: "failure", insufficientBalanceDetails: errDetails };
    });
}

export async function getTotalPeerPaymentCost(
  ws: InternalWalletState,
  pcs: SelectedPeerCoin[],
): Promise<AmountJson> {
  return ws.db
    .mktx((x) => [x.coins, x.denominations])
    .runReadOnly(async (tx) => {
      const costs: AmountJson[] = [];
      for (let i = 0; i < pcs.length; i++) {
        const coin = await tx.coins.get(pcs[i].coinPub);
        if (!coin) {
          throw Error("can't calculate payment cost, coin not found");
        }
        const denom = await tx.denominations.get([
          coin.exchangeBaseUrl,
          coin.denomPubHash,
        ]);
        if (!denom) {
          throw Error(
            "can't calculate payment cost, denomination for coin not found",
          );
        }
        const allDenoms = await tx.denominations.indexes.byExchangeBaseUrl
          .iter(coin.exchangeBaseUrl)
          .filter((x) =>
            Amounts.isSameCurrency(
              DenominationRecord.getValue(x),
              pcs[i].contribution,
            ),
          );
        const amountLeft = Amounts.sub(
          DenominationRecord.getValue(denom),
          pcs[i].contribution,
        ).amount;
        const refreshCost = getTotalRefreshCost(
          allDenoms,
          DenominationRecord.toDenomInfo(denom),
          amountLeft,
          ws.config.testing.denomselAllowLate,
        );
        costs.push(Amounts.parseOrThrow(pcs[i].contribution));
        costs.push(refreshCost);
      }
      const zero = Amounts.zeroOfAmount(pcs[0].contribution);
      return Amounts.sum([zero, ...costs]).amount;
    });
}

export async function checkPeerPushDebit(
  ws: InternalWalletState,
  req: CheckPeerPushDebitRequest,
): Promise<CheckPeerPushDebitResponse> {
  const instructedAmount = Amounts.parseOrThrow(req.amount);
  const coinSelRes = await selectPeerCoins(ws, instructedAmount);
  if (coinSelRes.type === "failure") {
    throw TalerError.fromDetail(
      TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
      {
        insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails,
      },
    );
  }
  const totalAmount = await getTotalPeerPaymentCost(
    ws,
    coinSelRes.result.coins,
  );
  return {
    amountEffective: Amounts.stringify(totalAmount),
    amountRaw: req.amount,
  };
}

async function processPeerPushDebitCreateReserve(
  ws: InternalWalletState,
  peerPushInitiation: PeerPushPaymentInitiationRecord,
): Promise<OperationAttemptResult> {
  const pursePub = peerPushInitiation.pursePub;
  const purseExpiration = peerPushInitiation.purseExpiration;
  const hContractTerms = peerPushInitiation.contractTermsHash;

  const purseSigResp = await ws.cryptoApi.signPurseCreation({
    hContractTerms,
    mergePub: peerPushInitiation.mergePub,
    minAge: 0,
    purseAmount: peerPushInitiation.amount,
    purseExpiration,
    pursePriv: peerPushInitiation.pursePriv,
  });

  const coins = await queryCoinInfosForSelection(
    ws,
    peerPushInitiation.coinSel,
  );

  const depositSigsResp = await ws.cryptoApi.signPurseDeposits({
    exchangeBaseUrl: peerPushInitiation.exchangeBaseUrl,
    pursePub: peerPushInitiation.pursePub,
    coins,
  });

  const econtractResp = await ws.cryptoApi.encryptContractForMerge({
    contractTerms: peerPushInitiation.contractTerms,
    mergePriv: peerPushInitiation.mergePriv,
    pursePriv: peerPushInitiation.pursePriv,
    pursePub: peerPushInitiation.pursePub,
    contractPriv: peerPushInitiation.contractPriv,
    contractPub: peerPushInitiation.contractPub,
  });

  const createPurseUrl = new URL(
    `purses/${peerPushInitiation.pursePub}/create`,
    peerPushInitiation.exchangeBaseUrl,
  );

  const httpResp = await ws.http.fetch(createPurseUrl.href, {
    method: "POST",
    body: {
      amount: peerPushInitiation.amount,
      merge_pub: peerPushInitiation.mergePub,
      purse_sig: purseSigResp.sig,
      h_contract_terms: hContractTerms,
      purse_expiration: purseExpiration,
      deposits: depositSigsResp.deposits,
      min_age: 0,
      econtract: econtractResp.econtract,
    },
  });

  const resp = await httpResp.json();

  logger.info(`resp: ${j2s(resp)}`);

  if (httpResp.status !== HttpStatusCode.Ok) {
    throw Error("got error response from exchange");
  }

  await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const ppi = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!ppi) {
        return;
      }
      ppi.status = PeerPushPaymentInitiationStatus.Done;
      await tx.peerPushPaymentInitiations.put(ppi);
    });

  return {
    type: OperationAttemptResultType.Finished,
    result: undefined,
  };
}

async function transitionPeerPushDebitFromReadyToDone(
  ws: InternalWalletState,
  pursePub: string,
): Promise<void> {
  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushDebit,
    pursePub,
  });
  const transitionInfo = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const ppiRec = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!ppiRec) {
        return undefined;
      }
      if (ppiRec.status !== PeerPushPaymentInitiationStatus.PendingReady) {
        return undefined;
      }
      const oldTxState = computePeerPushDebitTransactionState(ppiRec);
      ppiRec.status = PeerPushPaymentInitiationStatus.Done;
      const newTxState = computePeerPushDebitTransactionState(ppiRec);
      return {
        oldTxState,
        newTxState,
      };
    });
  notifyTransition(ws, transactionId, transitionInfo);
}

/**
 * Process the "pending(ready)" state of a peer-push-debit transaction.
 */
async function processPeerPushDebitReady(
  ws: InternalWalletState,
  peerPushInitiation: PeerPushPaymentInitiationRecord,
): Promise<OperationAttemptResult> {
  const pursePub = peerPushInitiation.pursePub;
  const retryTag = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });
  runLongpollAsync(ws, retryTag, async (ct) => {
    const mergeUrl = new URL(`purses/${pursePub}/merge`);
    mergeUrl.searchParams.set("timeout_ms", "30000");
    const resp = await ws.http.fetch(mergeUrl.href, {
      // timeout: getReserveRequestTimeout(withdrawalGroup),
      cancellationToken: ct,
    });
    if (resp.status === HttpStatusCode.Ok) {
      const purseStatus = await readSuccessResponseJsonOrThrow(
        resp,
        codecForExchangePurseStatus(),
      );
      if (purseStatus.deposit_timestamp) {
        await transitionPeerPushDebitFromReadyToDone(
          ws,
          peerPushInitiation.pursePub,
        );
        return {
          ready: true,
        };
      }
    } else if (resp.status === HttpStatusCode.Gone) {
      // FIXME: transition the reserve into the expired state
    }
    return {
      ready: false,
    };
  });
  logger.trace(
    "returning early from withdrawal for long-polling in background",
  );
  return {
    type: OperationAttemptResultType.Longpoll,
  };
}

export async function processPeerPushDebit(
  ws: InternalWalletState,
  pursePub: string,
): Promise<OperationAttemptResult> {
  const peerPushInitiation = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadOnly(async (tx) => {
      return tx.peerPushPaymentInitiations.get(pursePub);
    });
  if (!peerPushInitiation) {
    throw Error("peer push payment not found");
  }

  const retryTag = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });

  // We're already running!
  if (ws.activeLongpoll[retryTag]) {
    logger.info("peer-push-debit task already in long-polling, returning!");
    return {
      type: OperationAttemptResultType.Longpoll,
    };
  }

  switch (peerPushInitiation.status) {
    case PeerPushPaymentInitiationStatus.PendingCreatePurse:
      return processPeerPushDebitCreateReserve(ws, peerPushInitiation);
    case PeerPushPaymentInitiationStatus.PendingReady:
      return processPeerPushDebitReady(ws, peerPushInitiation);
  }

  return {
    type: OperationAttemptResultType.Finished,
    result: undefined,
  };
}

/**
 * Initiate sending a peer-to-peer push payment.
 */
export async function initiatePeerPushDebit(
  ws: InternalWalletState,
  req: InitiatePeerPushDebitRequest,
): Promise<InitiatePeerPushDebitResponse> {
  const instructedAmount = Amounts.parseOrThrow(
    req.partialContractTerms.amount,
  );
  const purseExpiration = req.partialContractTerms.purse_expiration;
  const contractTerms = req.partialContractTerms;

  const pursePair = await ws.cryptoApi.createEddsaKeypair({});
  const mergePair = await ws.cryptoApi.createEddsaKeypair({});

  const hContractTerms = ContractTermsUtil.hashContractTerms(contractTerms);

  const contractKeyPair = await ws.cryptoApi.createEddsaKeypair({});

  const coinSelRes = await selectPeerCoins(ws, instructedAmount);

  if (coinSelRes.type !== "success") {
    throw TalerError.fromDetail(
      TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
      {
        insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails,
      },
    );
  }

  const sel = coinSelRes.result;

  logger.info(`selected p2p coins (push): ${j2s(coinSelRes)}`);

  const totalAmount = await getTotalPeerPaymentCost(
    ws,
    coinSelRes.result.coins,
  );

  await ws.db
    .mktx((x) => [
      x.exchanges,
      x.contractTerms,
      x.coins,
      x.coinAvailability,
      x.denominations,
      x.refreshGroups,
      x.peerPushPaymentInitiations,
    ])
    .runReadWrite(async (tx) => {
      // FIXME: Instead of directly doing a spendCoin here,
      // we might want to mark the coins as used and spend them
      // after we've been able to create the purse.
      await spendCoins(ws, tx, {
        // allocationId: `txn:peer-push-debit:${pursePair.pub}`,
        allocationId: constructTransactionIdentifier({
          tag: TransactionType.PeerPushDebit,
          pursePub: pursePair.pub,
        }),
        coinPubs: sel.coins.map((x) => x.coinPub),
        contributions: sel.coins.map((x) =>
          Amounts.parseOrThrow(x.contribution),
        ),
        refreshReason: RefreshReason.PayPeerPush,
      });

      await tx.peerPushPaymentInitiations.add({
        amount: Amounts.stringify(instructedAmount),
        contractPriv: contractKeyPair.priv,
        contractPub: contractKeyPair.pub,
        contractTermsHash: hContractTerms,
        exchangeBaseUrl: sel.exchangeBaseUrl,
        mergePriv: mergePair.priv,
        mergePub: mergePair.pub,
        purseExpiration: purseExpiration,
        pursePriv: pursePair.priv,
        pursePub: pursePair.pub,
        timestampCreated: TalerPreciseTimestamp.now(),
        status: PeerPushPaymentInitiationStatus.PendingCreatePurse,
        contractTerms: contractTerms,
        coinSel: {
          coinPubs: sel.coins.map((x) => x.coinPub),
          contributions: sel.coins.map((x) => x.contribution),
        },
        totalCost: Amounts.stringify(totalAmount),
      });

      await tx.contractTerms.put({
        h: hContractTerms,
        contractTermsRaw: contractTerms,
      });
    });

  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub: pursePair.pub,
  });

  await runOperationWithErrorReporting(ws, taskId, async () => {
    return await processPeerPushDebit(ws, pursePair.pub);
  });

  return {
    contractPriv: contractKeyPair.priv,
    mergePriv: mergePair.priv,
    pursePub: pursePair.pub,
    exchangeBaseUrl: coinSelRes.result.exchangeBaseUrl,
    talerUri: constructPayPushUri({
      exchangeBaseUrl: coinSelRes.result.exchangeBaseUrl,
      contractPriv: contractKeyPair.priv,
    }),
    transactionId: constructTransactionIdentifier({
      tag: TransactionType.PeerPushDebit,
      pursePub: pursePair.pub,
    }),
  };
}

interface ExchangePurseStatus {
  balance: AmountString;
  deposit_timestamp?: TalerProtocolTimestamp;
  merge_timestamp?: TalerProtocolTimestamp;
}

export const codecForExchangePurseStatus = (): Codec<ExchangePurseStatus> =>
  buildCodecForObject<ExchangePurseStatus>()
    .property("balance", codecForAmountString())
    .property("deposit_timestamp", codecOptional(codecForTimestamp))
    .property("merge_timestamp", codecOptional(codecForTimestamp))
    .build("ExchangePurseStatus");

export async function preparePeerPushCredit(
  ws: InternalWalletState,
  req: PreparePeerPushCredit,
): Promise<PreparePeerPushCreditResponse> {
  const uri = parsePayPushUri(req.talerUri);

  if (!uri) {
    throw Error("got invalid taler://pay-push URI");
  }

  const existing = await ws.db
    .mktx((x) => [x.contractTerms, x.peerPushPaymentIncoming])
    .runReadOnly(async (tx) => {
      const existingPushInc =
        await tx.peerPushPaymentIncoming.indexes.byExchangeAndContractPriv.get([
          uri.exchangeBaseUrl,
          uri.contractPriv,
        ]);
      if (!existingPushInc) {
        return;
      }
      const existingContractTermsRec = await tx.contractTerms.get(
        existingPushInc.contractTermsHash,
      );
      if (!existingContractTermsRec) {
        throw Error(
          "contract terms for peer push payment credit not found in database",
        );
      }
      const existingContractTerms = codecForPeerContractTerms().decode(
        existingContractTermsRec.contractTermsRaw,
      );
      return { existingPushInc, existingContractTerms };
    });

  if (existing) {
    return {
      amount: existing.existingContractTerms.amount,
      amountEffective: existing.existingPushInc.estimatedAmountEffective,
      amountRaw: existing.existingContractTerms.amount,
      contractTerms: existing.existingContractTerms,
      peerPushPaymentIncomingId:
        existing.existingPushInc.peerPushPaymentIncomingId,
      transactionId: constructTransactionIdentifier({
        tag: TransactionType.PeerPushCredit,
        peerPushPaymentIncomingId: existing.existingPushInc.peerPushPaymentIncomingId,
      }),
    };
  }

  const exchangeBaseUrl = uri.exchangeBaseUrl;

  await updateExchangeFromUrl(ws, exchangeBaseUrl);

  const contractPriv = uri.contractPriv;
  const contractPub = encodeCrock(eddsaGetPublic(decodeCrock(contractPriv)));

  const getContractUrl = new URL(`contracts/${contractPub}`, exchangeBaseUrl);

  const contractHttpResp = await ws.http.get(getContractUrl.href);

  const contractResp = await readSuccessResponseJsonOrThrow(
    contractHttpResp,
    codecForExchangeGetContractResponse(),
  );

  const pursePub = contractResp.purse_pub;

  const dec = await ws.cryptoApi.decryptContractForMerge({
    ciphertext: contractResp.econtract,
    contractPriv: contractPriv,
    pursePub: pursePub,
  });

  const getPurseUrl = new URL(`purses/${pursePub}/deposit`, exchangeBaseUrl);

  const purseHttpResp = await ws.http.get(getPurseUrl.href);

  const purseStatus = await readSuccessResponseJsonOrThrow(
    purseHttpResp,
    codecForExchangePurseStatus(),
  );

  const peerPushPaymentIncomingId = encodeCrock(getRandomBytes(32));

  const contractTermsHash = ContractTermsUtil.hashContractTerms(
    dec.contractTerms,
  );

  const withdrawalGroupId = encodeCrock(getRandomBytes(32));

  const wi = await getExchangeWithdrawalInfo(
    ws,
    exchangeBaseUrl,
    Amounts.parseOrThrow(purseStatus.balance),
    undefined,
  );

  await ws.db
    .mktx((x) => [x.contractTerms, x.peerPushPaymentIncoming])
    .runReadWrite(async (tx) => {
      await tx.peerPushPaymentIncoming.add({
        peerPushPaymentIncomingId,
        contractPriv: contractPriv,
        exchangeBaseUrl: exchangeBaseUrl,
        mergePriv: dec.mergePriv,
        pursePub: pursePub,
        timestamp: TalerPreciseTimestamp.now(),
        contractTermsHash,
        status: PeerPushPaymentIncomingStatus.Proposed,
        withdrawalGroupId,
        currency: Amounts.currencyOf(purseStatus.balance),
        estimatedAmountEffective: Amounts.stringify(
          wi.withdrawalAmountEffective,
        ),
      });

      await tx.contractTerms.put({
        h: contractTermsHash,
        contractTermsRaw: dec.contractTerms,
      });
    });

  return {
    amount: purseStatus.balance,
    amountEffective: wi.withdrawalAmountEffective,
    amountRaw: purseStatus.balance,
    contractTerms: dec.contractTerms,
    peerPushPaymentIncomingId,
    transactionId: constructTransactionIdentifier({
      tag: TransactionType.PeerPushCredit,
      peerPushPaymentIncomingId,
    }),
  };
}

export function talerPaytoFromExchangeReserve(
  exchangeBaseUrl: string,
  reservePub: string,
): string {
  const url = new URL(exchangeBaseUrl);
  let proto: string;
  if (url.protocol === "http:") {
    proto = "taler-reserve-http";
  } else if (url.protocol === "https:") {
    proto = "taler-reserve";
  } else {
    throw Error(`unsupported exchange base URL protocol (${url.protocol})`);
  }

  let path = url.pathname;
  if (!path.endsWith("/")) {
    path = path + "/";
  }

  return `payto://${proto}/${url.host}${url.pathname}${reservePub}`;
}

async function getMergeReserveInfo(
  ws: InternalWalletState,
  req: {
    exchangeBaseUrl: string;
  },
): Promise<ReserveRecord> {
  // We have to eagerly create the key pair outside of the transaction,
  // due to the async crypto API.
  const newReservePair = await ws.cryptoApi.createEddsaKeypair({});

  const mergeReserveRecord: ReserveRecord = await ws.db
    .mktx((x) => [x.exchanges, x.reserves, x.withdrawalGroups])
    .runReadWrite(async (tx) => {
      const ex = await tx.exchanges.get(req.exchangeBaseUrl);
      checkDbInvariant(!!ex);
      if (ex.currentMergeReserveRowId != null) {
        const reserve = await tx.reserves.get(ex.currentMergeReserveRowId);
        checkDbInvariant(!!reserve);
        return reserve;
      }
      const reserve: ReserveRecord = {
        reservePriv: newReservePair.priv,
        reservePub: newReservePair.pub,
      };
      const insertResp = await tx.reserves.put(reserve);
      checkDbInvariant(typeof insertResp.key === "number");
      reserve.rowId = insertResp.key;
      ex.currentMergeReserveRowId = reserve.rowId;
      await tx.exchanges.put(ex);
      return reserve;
    });

  return mergeReserveRecord;
}

export async function processPeerPushCredit(
  ws: InternalWalletState,
  peerPushPaymentIncomingId: string,
): Promise<OperationAttemptResult> {
  let peerInc: PeerPushPaymentIncomingRecord | undefined;
  let contractTerms: PeerContractTerms | undefined;
  await ws.db
    .mktx((x) => [x.contractTerms, x.peerPushPaymentIncoming])
    .runReadWrite(async (tx) => {
      peerInc = await tx.peerPushPaymentIncoming.get(peerPushPaymentIncomingId);
      if (!peerInc) {
        return;
      }
      const ctRec = await tx.contractTerms.get(peerInc.contractTermsHash);
      if (ctRec) {
        contractTerms = ctRec.contractTermsRaw;
      }
      await tx.peerPushPaymentIncoming.put(peerInc);
    });

  if (!peerInc) {
    throw Error(
      `can't accept unknown incoming p2p push payment (${peerPushPaymentIncomingId})`,
    );
  }

  checkDbInvariant(!!contractTerms);

  const amount = Amounts.parseOrThrow(contractTerms.amount);

  if (
    peerInc.status === PeerPushPaymentIncomingStatus.MergeKycRequired &&
    peerInc.kycInfo
  ) {
    const txId = constructTransactionIdentifier({
      tag: TransactionType.PeerPushCredit,
      peerPushPaymentIncomingId: peerInc.peerPushPaymentIncomingId,
    });
    await checkWithdrawalKycStatus(
      ws,
      peerInc.exchangeBaseUrl,
      txId,
      peerInc.kycInfo,
      "individual",
    );
  }

  const mergeReserveInfo = await getMergeReserveInfo(ws, {
    exchangeBaseUrl: peerInc.exchangeBaseUrl,
  });

  const mergeTimestamp = TalerProtocolTimestamp.now();

  const reservePayto = talerPaytoFromExchangeReserve(
    peerInc.exchangeBaseUrl,
    mergeReserveInfo.reservePub,
  );

  const sigRes = await ws.cryptoApi.signPurseMerge({
    contractTermsHash: ContractTermsUtil.hashContractTerms(contractTerms),
    flags: WalletAccountMergeFlags.MergeFullyPaidPurse,
    mergePriv: peerInc.mergePriv,
    mergeTimestamp: mergeTimestamp,
    purseAmount: Amounts.stringify(amount),
    purseExpiration: contractTerms.purse_expiration,
    purseFee: Amounts.stringify(Amounts.zeroOfCurrency(amount.currency)),
    pursePub: peerInc.pursePub,
    reservePayto,
    reservePriv: mergeReserveInfo.reservePriv,
  });

  const mergePurseUrl = new URL(
    `purses/${peerInc.pursePub}/merge`,
    peerInc.exchangeBaseUrl,
  );

  const mergeReq: ExchangePurseMergeRequest = {
    payto_uri: reservePayto,
    merge_timestamp: mergeTimestamp,
    merge_sig: sigRes.mergeSig,
    reserve_sig: sigRes.accountSig,
  };

  const mergeHttpResp = await ws.http.postJson(mergePurseUrl.href, mergeReq);

  if (mergeHttpResp.status === HttpStatusCode.UnavailableForLegalReasons) {
    const respJson = await mergeHttpResp.json();
    const kycPending = codecForWalletKycUuid().decode(respJson);
    logger.info(`kyc uuid response: ${j2s(kycPending)}`);

    await ws.db
      .mktx((x) => [x.peerPushPaymentIncoming])
      .runReadWrite(async (tx) => {
        const peerInc = await tx.peerPushPaymentIncoming.get(
          peerPushPaymentIncomingId,
        );
        if (!peerInc) {
          return;
        }
        peerInc.kycInfo = {
          paytoHash: kycPending.h_payto,
          requirementRow: kycPending.requirement_row,
        };
        peerInc.status = PeerPushPaymentIncomingStatus.MergeKycRequired;
        await tx.peerPushPaymentIncoming.put(peerInc);
      });
    return {
      type: OperationAttemptResultType.Pending,
      result: undefined,
    };
  }

  logger.trace(`merge request: ${j2s(mergeReq)}`);
  const res = await readSuccessResponseJsonOrThrow(
    mergeHttpResp,
    codecForAny(),
  );
  logger.trace(`merge response: ${j2s(res)}`);

  await internalCreateWithdrawalGroup(ws, {
    amount,
    wgInfo: {
      withdrawalType: WithdrawalRecordType.PeerPushCredit,
      contractTerms,
    },
    forcedWithdrawalGroupId: peerInc.withdrawalGroupId,
    exchangeBaseUrl: peerInc.exchangeBaseUrl,
    reserveStatus: WithdrawalGroupStatus.PendingQueryingStatus,
    reserveKeyPair: {
      priv: mergeReserveInfo.reservePriv,
      pub: mergeReserveInfo.reservePub,
    },
  });

  await ws.db
    .mktx((x) => [x.contractTerms, x.peerPushPaymentIncoming])
    .runReadWrite(async (tx) => {
      const peerInc = await tx.peerPushPaymentIncoming.get(
        peerPushPaymentIncomingId,
      );
      if (!peerInc) {
        return;
      }
      if (
        peerInc.status === PeerPushPaymentIncomingStatus.Accepted ||
        peerInc.status === PeerPushPaymentIncomingStatus.MergeKycRequired
      ) {
        peerInc.status = PeerPushPaymentIncomingStatus.Done;
      }
      await tx.peerPushPaymentIncoming.put(peerInc);
    });

  return {
    type: OperationAttemptResultType.Finished,
    result: undefined,
  };
}

export async function confirmPeerPushCredit(
  ws: InternalWalletState,
  req: ConfirmPeerPushCreditRequest,
): Promise<AcceptPeerPushPaymentResponse> {
  let peerInc: PeerPushPaymentIncomingRecord | undefined;

  await ws.db
    .mktx((x) => [x.contractTerms, x.peerPushPaymentIncoming])
    .runReadWrite(async (tx) => {
      peerInc = await tx.peerPushPaymentIncoming.get(
        req.peerPushPaymentIncomingId,
      );
      if (!peerInc) {
        return;
      }
      if (peerInc.status === PeerPushPaymentIncomingStatus.Proposed) {
        peerInc.status = PeerPushPaymentIncomingStatus.Accepted;
      }
      await tx.peerPushPaymentIncoming.put(peerInc);
    });

  if (!peerInc) {
    throw Error(
      `can't accept unknown incoming p2p push payment (${req.peerPushPaymentIncomingId})`,
    );
  }

  ws.workAvailable.trigger();

  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushCredit,
    peerPushPaymentIncomingId: req.peerPushPaymentIncomingId,
  });

  return {
    transactionId,
  };
}

export async function processPeerPullDebit(
  ws: InternalWalletState,
  peerPullPaymentIncomingId: string,
): Promise<OperationAttemptResult> {
  const peerPullInc = await ws.db
    .mktx((x) => [x.peerPullPaymentIncoming])
    .runReadOnly(async (tx) => {
      return tx.peerPullPaymentIncoming.get(peerPullPaymentIncomingId);
    });
  if (!peerPullInc) {
    throw Error("peer pull debit not found");
  }
  if (peerPullInc.status === PeerPullPaymentIncomingStatus.Accepted) {
    const pursePub = peerPullInc.pursePub;

    const coinSel = peerPullInc.coinSel;
    if (!coinSel) {
      throw Error("invalid state, no coins selected");
    }

    const coins = await queryCoinInfosForSelection(ws, coinSel);

    const depositSigsResp = await ws.cryptoApi.signPurseDeposits({
      exchangeBaseUrl: peerPullInc.exchangeBaseUrl,
      pursePub: peerPullInc.pursePub,
      coins,
    });

    const purseDepositUrl = new URL(
      `purses/${pursePub}/deposit`,
      peerPullInc.exchangeBaseUrl,
    );

    const depositPayload: ExchangePurseDeposits = {
      deposits: depositSigsResp.deposits,
    };

    if (logger.shouldLogTrace()) {
      logger.trace(`purse deposit payload: ${j2s(depositPayload)}`);
    }

    const httpResp = await ws.http.postJson(
      purseDepositUrl.href,
      depositPayload,
    );
    const resp = await readSuccessResponseJsonOrThrow(httpResp, codecForAny());
    logger.trace(`purse deposit response: ${j2s(resp)}`);
  }

  await ws.db
    .mktx((x) => [x.peerPullPaymentIncoming])
    .runReadWrite(async (tx) => {
      const pi = await tx.peerPullPaymentIncoming.get(
        peerPullPaymentIncomingId,
      );
      if (!pi) {
        throw Error("peer pull payment not found anymore");
      }
      if (pi.status === PeerPullPaymentIncomingStatus.Accepted) {
        pi.status = PeerPullPaymentIncomingStatus.Paid;
      }
      await tx.peerPullPaymentIncoming.put(pi);
    });

  return {
    type: OperationAttemptResultType.Finished,
    result: undefined,
  };
}

export async function confirmPeerPullDebit(
  ws: InternalWalletState,
  req: ConfirmPeerPullDebitRequest,
): Promise<AcceptPeerPullPaymentResponse> {
  const peerPullInc = await ws.db
    .mktx((x) => [x.peerPullPaymentIncoming])
    .runReadOnly(async (tx) => {
      return tx.peerPullPaymentIncoming.get(req.peerPullPaymentIncomingId);
    });

  if (!peerPullInc) {
    throw Error(
      `can't accept unknown incoming p2p pull payment (${req.peerPullPaymentIncomingId})`,
    );
  }

  const instructedAmount = Amounts.parseOrThrow(
    peerPullInc.contractTerms.amount,
  );

  const coinSelRes = await selectPeerCoins(ws, instructedAmount);
  logger.info(`selected p2p coins (pull): ${j2s(coinSelRes)}`);

  if (coinSelRes.type !== "success") {
    throw TalerError.fromDetail(
      TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
      {
        insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails,
      },
    );
  }

  const sel = coinSelRes.result;

  const totalAmount = await getTotalPeerPaymentCost(
    ws,
    coinSelRes.result.coins,
  );

  const ppi = await ws.db
    .mktx((x) => [
      x.exchanges,
      x.coins,
      x.denominations,
      x.refreshGroups,
      x.peerPullPaymentIncoming,
      x.coinAvailability,
    ])
    .runReadWrite(async (tx) => {
      await spendCoins(ws, tx, {
        // allocationId: `txn:peer-pull-debit:${req.peerPullPaymentIncomingId}`,
        allocationId: constructTransactionIdentifier({
          tag: TransactionType.PeerPullDebit,
          peerPullPaymentIncomingId: req.peerPullPaymentIncomingId,
        }),
        coinPubs: sel.coins.map((x) => x.coinPub),
        contributions: sel.coins.map((x) =>
          Amounts.parseOrThrow(x.contribution),
        ),
        refreshReason: RefreshReason.PayPeerPull,
      });

      const pi = await tx.peerPullPaymentIncoming.get(
        req.peerPullPaymentIncomingId,
      );
      if (!pi) {
        throw Error();
      }
      if (pi.status === PeerPullPaymentIncomingStatus.Proposed) {
        pi.status = PeerPullPaymentIncomingStatus.Accepted;
        pi.coinSel = {
          coinPubs: sel.coins.map((x) => x.coinPub),
          contributions: sel.coins.map((x) => x.contribution),
          totalCost: Amounts.stringify(totalAmount),
        };
      }
      await tx.peerPullPaymentIncoming.put(pi);
      return pi;
    });

  await runOperationWithErrorReporting(
    ws,
    TaskIdentifiers.forPeerPullPaymentDebit(ppi),
    async () => {
      return processPeerPullDebit(ws, ppi.peerPullPaymentIncomingId);
    },
  );

  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPullDebit,
    peerPullPaymentIncomingId: req.peerPullPaymentIncomingId,
  });

  return {
    transactionId,
  };
}

/**
 * Look up information about an incoming peer pull payment.
 * Store the results in the wallet DB.
 */
export async function preparePeerPullDebit(
  ws: InternalWalletState,
  req: PreparePeerPullDebitRequest,
): Promise<PreparePeerPullDebitResponse> {
  const uri = parsePayPullUri(req.talerUri);

  if (!uri) {
    throw Error("got invalid taler://pay-pull URI");
  }

  const existingPullIncomingRecord = await ws.db
    .mktx((x) => [x.peerPullPaymentIncoming])
    .runReadOnly(async (tx) => {
      return tx.peerPullPaymentIncoming.indexes.byExchangeAndContractPriv.get([
        uri.exchangeBaseUrl,
        uri.contractPriv,
      ]);
    });

  if (existingPullIncomingRecord) {
    return {
      amount: existingPullIncomingRecord.contractTerms.amount,
      amountRaw: existingPullIncomingRecord.contractTerms.amount,
      amountEffective: existingPullIncomingRecord.totalCostEstimated,
      contractTerms: existingPullIncomingRecord.contractTerms,
      peerPullPaymentIncomingId:
        existingPullIncomingRecord.peerPullPaymentIncomingId,
      transactionId: constructTransactionIdentifier({
        tag: TransactionType.PeerPullDebit,
        peerPullPaymentIncomingId: existingPullIncomingRecord.peerPullPaymentIncomingId,
      }),
    };
  }

  const exchangeBaseUrl = uri.exchangeBaseUrl;
  const contractPriv = uri.contractPriv;
  const contractPub = encodeCrock(eddsaGetPublic(decodeCrock(contractPriv)));

  const getContractUrl = new URL(`contracts/${contractPub}`, exchangeBaseUrl);

  const contractHttpResp = await ws.http.get(getContractUrl.href);

  const contractResp = await readSuccessResponseJsonOrThrow(
    contractHttpResp,
    codecForExchangeGetContractResponse(),
  );

  const pursePub = contractResp.purse_pub;

  const dec = await ws.cryptoApi.decryptContractForDeposit({
    ciphertext: contractResp.econtract,
    contractPriv: contractPriv,
    pursePub: pursePub,
  });

  const getPurseUrl = new URL(`purses/${pursePub}/merge`, exchangeBaseUrl);

  const purseHttpResp = await ws.http.get(getPurseUrl.href);

  const purseStatus = await readSuccessResponseJsonOrThrow(
    purseHttpResp,
    codecForExchangePurseStatus(),
  );

  const peerPullPaymentIncomingId = encodeCrock(getRandomBytes(32));

  let contractTerms: PeerContractTerms;

  if (dec.contractTerms) {
    contractTerms = codecForPeerContractTerms().decode(dec.contractTerms);
    // FIXME: Check that the purseStatus balance matches contract terms amount
  } else {
    // FIXME: In this case, where do we get the purse expiration from?!
    // https://bugs.gnunet.org/view.php?id=7706
    throw Error("pull payments without contract terms not supported yet");
  }

  // FIXME: Why don't we compute the totalCost here?!

  const instructedAmount = Amounts.parseOrThrow(contractTerms.amount);

  const coinSelRes = await selectPeerCoins(ws, instructedAmount);
  logger.info(`selected p2p coins (pull): ${j2s(coinSelRes)}`);

  if (coinSelRes.type !== "success") {
    throw TalerError.fromDetail(
      TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE,
      {
        insufficientBalanceDetails: coinSelRes.insufficientBalanceDetails,
      },
    );
  }

  const totalAmount = await getTotalPeerPaymentCost(
    ws,
    coinSelRes.result.coins,
  );

  await ws.db
    .mktx((x) => [x.peerPullPaymentIncoming])
    .runReadWrite(async (tx) => {
      await tx.peerPullPaymentIncoming.add({
        peerPullPaymentIncomingId,
        contractPriv: contractPriv,
        exchangeBaseUrl: exchangeBaseUrl,
        pursePub: pursePub,
        timestampCreated: TalerPreciseTimestamp.now(),
        contractTerms,
        status: PeerPullPaymentIncomingStatus.Proposed,
        totalCostEstimated: Amounts.stringify(totalAmount),
      });
    });

  return {
    amount: contractTerms.amount,
    amountEffective: Amounts.stringify(totalAmount),
    amountRaw: contractTerms.amount,
    contractTerms: contractTerms,
    peerPullPaymentIncomingId,
    transactionId: constructTransactionIdentifier({
      tag: TransactionType.PeerPullDebit,
      peerPullPaymentIncomingId: peerPullPaymentIncomingId,
    }),
  };
}

export async function queryPurseForPeerPullCredit(
  ws: InternalWalletState,
  pullIni: PeerPullPaymentInitiationRecord,
  cancellationToken: CancellationToken,
): Promise<LongpollResult> {
  const purseDepositUrl = new URL(
    `purses/${pullIni.pursePub}/deposit`,
    pullIni.exchangeBaseUrl,
  );
  purseDepositUrl.searchParams.set("timeout_ms", "30000");
  logger.info(`querying purse status via ${purseDepositUrl.href}`);
  const resp = await ws.http.get(purseDepositUrl.href, {
    timeout: { d_ms: 60000 },
    cancellationToken,
  });

  logger.info(`purse status code: HTTP ${resp.status}`);

  const result = await readSuccessResponseJsonOrErrorCode(
    resp,
    codecForExchangePurseStatus(),
  );

  if (result.isError) {
    logger.info(`got purse status error, EC=${result.talerErrorResponse.code}`);
    if (resp.status === 404) {
      return { ready: false };
    } else {
      throwUnexpectedRequestError(resp, result.talerErrorResponse);
    }
  }

  if (!result.response.deposit_timestamp) {
    logger.info("purse not ready yet (no deposit)");
    return { ready: false };
  }

  const reserve = await ws.db
    .mktx((x) => [x.reserves])
    .runReadOnly(async (tx) => {
      return await tx.reserves.get(pullIni.mergeReserveRowId);
    });

  if (!reserve) {
    throw Error("reserve for peer pull credit not found in wallet DB");
  }

  await internalCreateWithdrawalGroup(ws, {
    amount: Amounts.parseOrThrow(pullIni.amount),
    wgInfo: {
      withdrawalType: WithdrawalRecordType.PeerPullCredit,
      contractTerms: pullIni.contractTerms,
      contractPriv: pullIni.contractPriv,
    },
    forcedWithdrawalGroupId: pullIni.withdrawalGroupId,
    exchangeBaseUrl: pullIni.exchangeBaseUrl,
    reserveStatus: WithdrawalGroupStatus.PendingQueryingStatus,
    reserveKeyPair: {
      priv: reserve.reservePriv,
      pub: reserve.reservePub,
    },
  });

  await ws.db
    .mktx((x) => [x.peerPullPaymentInitiations])
    .runReadWrite(async (tx) => {
      const finPi = await tx.peerPullPaymentInitiations.get(pullIni.pursePub);
      if (!finPi) {
        logger.warn("peerPullPaymentInitiation not found anymore");
        return;
      }
      if (finPi.status === PeerPullPaymentInitiationStatus.PendingReady) {
        finPi.status = PeerPullPaymentInitiationStatus.DonePurseDeposited;
      }
      await tx.peerPullPaymentInitiations.put(finPi);
    });
  return {
    ready: true,
  };
}

export async function processPeerPullCredit(
  ws: InternalWalletState,
  pursePub: string,
): Promise<OperationAttemptResult> {
  const pullIni = await ws.db
    .mktx((x) => [x.peerPullPaymentInitiations])
    .runReadOnly(async (tx) => {
      return tx.peerPullPaymentInitiations.get(pursePub);
    });
  if (!pullIni) {
    throw Error("peer pull payment initiation not found in database");
  }

  const retryTag = constructTaskIdentifier({
    tag: PendingTaskType.PeerPullCredit,
    pursePub,
  });

  // We're already running!
  if (ws.activeLongpoll[retryTag]) {
    logger.info("peer-pull-credit already in long-polling, returning!");
    return {
      type: OperationAttemptResultType.Longpoll,
    };
  }

  logger.trace(`processing ${retryTag}, status=${pullIni.status}`);

  switch (pullIni.status) {
    case PeerPullPaymentInitiationStatus.DonePurseDeposited: {
      // We implement this case so that the "retry" action on a peer-pull-credit transaction
      // also retries the withdrawal task.

      logger.warn(
        "peer pull payment initiation is already finished, retrying withdrawal",
      );

      const withdrawalGroupId = pullIni.withdrawalGroupId;

      if (withdrawalGroupId) {
        const taskId = constructTaskIdentifier({
          tag: PendingTaskType.Withdraw,
          withdrawalGroupId,
        });
        stopLongpolling(ws, taskId);
        await resetOperationTimeout(ws, taskId);
        await runOperationWithErrorReporting(ws, taskId, () =>
          processWithdrawalGroup(ws, withdrawalGroupId),
        );
      }
      return {
        type: OperationAttemptResultType.Finished,
        result: undefined,
      };
    }
    case PeerPullPaymentInitiationStatus.PendingReady:
      runLongpollAsync(ws, retryTag, async (cancellationToken) =>
        queryPurseForPeerPullCredit(ws, pullIni, cancellationToken),
      );
      logger.trace(
        "returning early from processPeerPullCredit for long-polling in background",
      );
      return {
        type: OperationAttemptResultType.Longpoll,
      };
    case PeerPullPaymentInitiationStatus.PendingMergeKycRequired: {
      const transactionId = constructTransactionIdentifier({
        tag: TransactionType.PeerPullCredit,
        pursePub: pullIni.pursePub,
      });
      if (pullIni.kycInfo) {
        await checkWithdrawalKycStatus(
          ws,
          pullIni.exchangeBaseUrl,
          transactionId,
          pullIni.kycInfo,
          "individual",
        );
      }
      break;
    }
    case PeerPullPaymentInitiationStatus.PendingCreatePurse:
      break;
    default:
      throw Error(`unknown PeerPullPaymentInitiationStatus ${pullIni.status}`);
  }

  const mergeReserve = await ws.db
    .mktx((x) => [x.reserves])
    .runReadOnly(async (tx) => {
      return tx.reserves.get(pullIni.mergeReserveRowId);
    });

  if (!mergeReserve) {
    throw Error("merge reserve for peer pull payment not found in database");
  }

  const purseFee = Amounts.stringify(Amounts.zeroOfAmount(pullIni.amount));

  const reservePayto = talerPaytoFromExchangeReserve(
    pullIni.exchangeBaseUrl,
    mergeReserve.reservePub,
  );

  const econtractResp = await ws.cryptoApi.encryptContractForDeposit({
    contractPriv: pullIni.contractPriv,
    contractPub: pullIni.contractPub,
    contractTerms: pullIni.contractTerms,
    pursePriv: pullIni.pursePriv,
    pursePub: pullIni.pursePub,
  });

  const purseExpiration = pullIni.contractTerms.purse_expiration;
  const sigRes = await ws.cryptoApi.signReservePurseCreate({
    contractTermsHash: pullIni.contractTermsHash,
    flags: WalletAccountMergeFlags.CreateWithPurseFee,
    mergePriv: pullIni.mergePriv,
    mergeTimestamp: TalerPreciseTimestamp.round(pullIni.mergeTimestamp),
    purseAmount: pullIni.contractTerms.amount,
    purseExpiration: purseExpiration,
    purseFee: purseFee,
    pursePriv: pullIni.pursePriv,
    pursePub: pullIni.pursePub,
    reservePayto,
    reservePriv: mergeReserve.reservePriv,
  });

  const reservePurseReqBody: ExchangeReservePurseRequest = {
    merge_sig: sigRes.mergeSig,
    merge_timestamp: TalerPreciseTimestamp.round(pullIni.mergeTimestamp),
    h_contract_terms: pullIni.contractTermsHash,
    merge_pub: pullIni.mergePub,
    min_age: 0,
    purse_expiration: purseExpiration,
    purse_fee: purseFee,
    purse_pub: pullIni.pursePub,
    purse_sig: sigRes.purseSig,
    purse_value: pullIni.contractTerms.amount,
    reserve_sig: sigRes.accountSig,
    econtract: econtractResp.econtract,
  };

  logger.info(`reserve purse request: ${j2s(reservePurseReqBody)}`);

  const reservePurseMergeUrl = new URL(
    `reserves/${mergeReserve.reservePub}/purse`,
    pullIni.exchangeBaseUrl,
  );

  const httpResp = await ws.http.postJson(
    reservePurseMergeUrl.href,
    reservePurseReqBody,
  );

  if (httpResp.status === HttpStatusCode.UnavailableForLegalReasons) {
    const respJson = await httpResp.json();
    const kycPending = codecForWalletKycUuid().decode(respJson);
    logger.info(`kyc uuid response: ${j2s(kycPending)}`);

    await ws.db
      .mktx((x) => [x.peerPullPaymentInitiations])
      .runReadWrite(async (tx) => {
        const peerIni = await tx.peerPullPaymentInitiations.get(pursePub);
        if (!peerIni) {
          return;
        }
        peerIni.kycInfo = {
          paytoHash: kycPending.h_payto,
          requirementRow: kycPending.requirement_row,
        };
        peerIni.status =
          PeerPullPaymentInitiationStatus.PendingMergeKycRequired;
        await tx.peerPullPaymentInitiations.put(peerIni);
      });
    return {
      type: OperationAttemptResultType.Pending,
      result: undefined,
    };
  }

  const resp = await readSuccessResponseJsonOrThrow(httpResp, codecForAny());

  logger.info(`reserve merge response: ${j2s(resp)}`);

  await ws.db
    .mktx((x) => [x.peerPullPaymentInitiations])
    .runReadWrite(async (tx) => {
      const pi2 = await tx.peerPullPaymentInitiations.get(pursePub);
      if (!pi2) {
        return;
      }
      pi2.status = PeerPullPaymentInitiationStatus.PendingReady;
      await tx.peerPullPaymentInitiations.put(pi2);
    });

  ws.notify({
    type: NotificationType.PeerPullCreditReady,
    transactionId: constructTransactionIdentifier({
      tag: TransactionType.PeerPullCredit,
      pursePub: pullIni.pursePub,
    }),
  });

  return {
    type: OperationAttemptResultType.Finished,
    result: undefined,
  };
}

/**
 * Find a preferred exchange based on when we withdrew last from this exchange.
 */
async function getPreferredExchangeForCurrency(
  ws: InternalWalletState,
  currency: string,
): Promise<string | undefined> {
  // Find an exchange with the matching currency.
  // Prefer exchanges with the most recent withdrawal.
  const url = await ws.db
    .mktx((x) => [x.exchanges])
    .runReadOnly(async (tx) => {
      const exchanges = await tx.exchanges.iter().toArray();
      let candidate = undefined;
      for (const e of exchanges) {
        if (e.detailsPointer?.currency !== currency) {
          continue;
        }
        if (!candidate) {
          candidate = e;
          continue;
        }
        if (candidate.lastWithdrawal && !e.lastWithdrawal) {
          continue;
        }
        if (candidate.lastWithdrawal && e.lastWithdrawal) {
          if (
            AbsoluteTime.cmp(
              AbsoluteTime.fromPreciseTimestamp(e.lastWithdrawal),
              AbsoluteTime.fromPreciseTimestamp(candidate.lastWithdrawal),
            ) > 0
          ) {
            candidate = e;
          }
        }
      }
      if (candidate) {
        return candidate.baseUrl;
      }
      return undefined;
    });
  return url;
}

/**
 * Check fees and available exchanges for a peer push payment initiation.
 */
export async function checkPeerPullPaymentInitiation(
  ws: InternalWalletState,
  req: CheckPeerPullCreditRequest,
): Promise<CheckPeerPullCreditResponse> {
  // FIXME: We don't support exchanges with purse fees yet.
  // Select an exchange where we have money in the specified currency
  // FIXME: How do we handle regional currency scopes here? Is it an additional input?

  logger.trace("checking peer-pull-credit fees");

  const currency = Amounts.currencyOf(req.amount);
  let exchangeUrl;
  if (req.exchangeBaseUrl) {
    exchangeUrl = req.exchangeBaseUrl;
  } else {
    exchangeUrl = await getPreferredExchangeForCurrency(ws, currency);
  }

  if (!exchangeUrl) {
    throw Error("no exchange found for initiating a peer pull payment");
  }

  logger.trace(`found ${exchangeUrl} as preferred exchange`);

  const wi = await getExchangeWithdrawalInfo(
    ws,
    exchangeUrl,
    Amounts.parseOrThrow(req.amount),
    undefined,
  );

  logger.trace(`got withdrawal info`);

  return {
    exchangeBaseUrl: exchangeUrl,
    amountEffective: wi.withdrawalAmountEffective,
    amountRaw: req.amount,
  };
}

/**
 * Initiate a peer pull payment.
 */
export async function initiatePeerPullPayment(
  ws: InternalWalletState,
  req: InitiatePeerPullCreditRequest,
): Promise<InitiatePeerPullCreditResponse> {
  const currency = Amounts.currencyOf(req.partialContractTerms.amount);
  let maybeExchangeBaseUrl: string | undefined;
  if (req.exchangeBaseUrl) {
    maybeExchangeBaseUrl = req.exchangeBaseUrl;
  } else {
    maybeExchangeBaseUrl = await getPreferredExchangeForCurrency(ws, currency);
  }

  if (!maybeExchangeBaseUrl) {
    throw Error("no exchange found for initiating a peer pull payment");
  }

  const exchangeBaseUrl = maybeExchangeBaseUrl;

  await updateExchangeFromUrl(ws, exchangeBaseUrl);

  const mergeReserveInfo = await getMergeReserveInfo(ws, {
    exchangeBaseUrl: exchangeBaseUrl,
  });

  const mergeTimestamp = TalerPreciseTimestamp.now();

  const pursePair = await ws.cryptoApi.createEddsaKeypair({});
  const mergePair = await ws.cryptoApi.createEddsaKeypair({});

  const contractTerms = req.partialContractTerms;

  const hContractTerms = ContractTermsUtil.hashContractTerms(contractTerms);

  const contractKeyPair = await ws.cryptoApi.createEddsaKeypair({});

  const withdrawalGroupId = encodeCrock(getRandomBytes(32));

  const mergeReserveRowId = mergeReserveInfo.rowId;
  checkDbInvariant(!!mergeReserveRowId);

  const wi = await getExchangeWithdrawalInfo(
    ws,
    exchangeBaseUrl,
    Amounts.parseOrThrow(req.partialContractTerms.amount),
    undefined,
  );

  await ws.db
    .mktx((x) => [x.peerPullPaymentInitiations, x.contractTerms])
    .runReadWrite(async (tx) => {
      await tx.peerPullPaymentInitiations.put({
        amount: req.partialContractTerms.amount,
        contractTermsHash: hContractTerms,
        exchangeBaseUrl: exchangeBaseUrl,
        pursePriv: pursePair.priv,
        pursePub: pursePair.pub,
        mergePriv: mergePair.priv,
        mergePub: mergePair.pub,
        status: PeerPullPaymentInitiationStatus.PendingCreatePurse,
        contractTerms: contractTerms,
        mergeTimestamp,
        mergeReserveRowId: mergeReserveRowId,
        contractPriv: contractKeyPair.priv,
        contractPub: contractKeyPair.pub,
        withdrawalGroupId,
        estimatedAmountEffective: wi.withdrawalAmountEffective,
      });
      await tx.contractTerms.put({
        contractTermsRaw: contractTerms,
        h: hContractTerms,
      });
    });

  // FIXME: Should we somehow signal to the client
  // whether purse creation has failed, or does the client/
  // check this asynchronously from the transaction status?

  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPullCredit,
    pursePub: pursePair.pub,
  });

  await runOperationWithErrorReporting(ws, taskId, async () => {
    return processPeerPullCredit(ws, pursePair.pub);
  });

  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPullCredit,
    pursePub: pursePair.pub,
  });

  return {
    talerUri: constructPayPullUri({
      exchangeBaseUrl: exchangeBaseUrl,
      contractPriv: contractKeyPair.priv,
    }),
    transactionId,
  };
}

export function computePeerPushDebitTransactionState(
  ppiRecord: PeerPushPaymentInitiationRecord,
): TransactionState {
  switch (ppiRecord.status) {
    case PeerPushPaymentInitiationStatus.PendingCreatePurse:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPushPaymentInitiationStatus.PendingReady:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Ready,
      };
    case PeerPushPaymentInitiationStatus.Aborted:
      return {
        major: TransactionMajorState.Aborted,
      };
    case PeerPushPaymentInitiationStatus.AbortingDeletePurse:
      return {
        major: TransactionMajorState.Aborting,
        minor: TransactionMinorState.DeletePurse,
      };
    case PeerPushPaymentInitiationStatus.AbortingRefresh:
      return {
        major: TransactionMajorState.Aborting,
        minor: TransactionMinorState.Refresh,
      };
    case PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse:
      return {
        major: TransactionMajorState.SuspendedAborting,
        minor: TransactionMinorState.DeletePurse,
      };
    case PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh:
      return {
        major: TransactionMajorState.SuspendedAborting,
        minor: TransactionMinorState.Refresh,
      };
    case PeerPushPaymentInitiationStatus.SuspendedCreatePurse:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPushPaymentInitiationStatus.SuspendedReady:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.Ready,
      };
    case PeerPushPaymentInitiationStatus.Done:
      return {
        major: TransactionMajorState.Done,
      };
  }
}

export async function abortPeerPushDebitTransaction(
  ws: InternalWalletState,
  pursePub: string,
) {
  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });
  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushDebit,
    pursePub,
  });
  stopLongpolling(ws, taskId);
  const transitionInfo = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const pushDebitRec = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!pushDebitRec) {
        logger.warn(`peer push debit ${pursePub} not found`);
        return;
      }
      let newStatus: PeerPushPaymentInitiationStatus | undefined = undefined;
      switch (pushDebitRec.status) {
        case PeerPushPaymentInitiationStatus.PendingReady:
        case PeerPushPaymentInitiationStatus.SuspendedReady:
          newStatus = PeerPushPaymentInitiationStatus.AbortingDeletePurse;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedCreatePurse:
        case PeerPushPaymentInitiationStatus.PendingCreatePurse:
          // Network request might already be in-flight!
          newStatus = PeerPushPaymentInitiationStatus.AbortingDeletePurse;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh:
        case PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse:
        case PeerPushPaymentInitiationStatus.AbortingRefresh:
        case PeerPushPaymentInitiationStatus.Done:
        case PeerPushPaymentInitiationStatus.AbortingDeletePurse:
        case PeerPushPaymentInitiationStatus.Aborted:
          // Do nothing
          break;
        default:
          assertUnreachable(pushDebitRec.status);
      }
      if (newStatus != null) {
        const oldTxState = computePeerPushDebitTransactionState(pushDebitRec);
        pushDebitRec.status = newStatus;
        const newTxState = computePeerPushDebitTransactionState(pushDebitRec);
        await tx.peerPushPaymentInitiations.put(pushDebitRec);
        return {
          oldTxState,
          newTxState,
        };
      }
      return undefined;
    });
  notifyTransition(ws, transactionId, transitionInfo);
}

export async function cancelAbortingPeerPushDebitTransaction(
  ws: InternalWalletState,
  pursePub: string,
) {
  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });
  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushDebit,
    pursePub,
  });
  stopLongpolling(ws, taskId);
  const transitionInfo = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const pushDebitRec = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!pushDebitRec) {
        logger.warn(`peer push debit ${pursePub} not found`);
        return;
      }
      let newStatus: PeerPushPaymentInitiationStatus | undefined = undefined;
      switch (pushDebitRec.status) {
        case PeerPushPaymentInitiationStatus.AbortingRefresh:
        case PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh:
          // FIXME: We also need to abort the refresh group!
          newStatus = PeerPushPaymentInitiationStatus.Aborted;
          break;
        case PeerPushPaymentInitiationStatus.AbortingDeletePurse:
        case PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse:
          newStatus = PeerPushPaymentInitiationStatus.Aborted;
          break;
        case PeerPushPaymentInitiationStatus.PendingReady:
        case PeerPushPaymentInitiationStatus.SuspendedReady:
        case PeerPushPaymentInitiationStatus.SuspendedCreatePurse:
        case PeerPushPaymentInitiationStatus.PendingCreatePurse:
        case PeerPushPaymentInitiationStatus.Done:
        case PeerPushPaymentInitiationStatus.Aborted:
          // Do nothing
          break;
        default:
          assertUnreachable(pushDebitRec.status);
      }
      if (newStatus != null) {
        const oldTxState = computePeerPushDebitTransactionState(pushDebitRec);
        pushDebitRec.status = newStatus;
        const newTxState = computePeerPushDebitTransactionState(pushDebitRec);
        await tx.peerPushPaymentInitiations.put(pushDebitRec);
        return {
          oldTxState,
          newTxState,
        };
      }
      return undefined;
    });
  notifyTransition(ws, transactionId, transitionInfo);
}

export async function suspendPeerPushDebitTransaction(
  ws: InternalWalletState,
  pursePub: string,
) {
  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });
  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushDebit,
    pursePub,
  });
  stopLongpolling(ws, taskId);
  const transitionInfo = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const pushDebitRec = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!pushDebitRec) {
        logger.warn(`peer push debit ${pursePub} not found`);
        return;
      }
      let newStatus: PeerPushPaymentInitiationStatus | undefined = undefined;
      switch (pushDebitRec.status) {
        case PeerPushPaymentInitiationStatus.PendingCreatePurse:
          newStatus = PeerPushPaymentInitiationStatus.SuspendedCreatePurse;
          break;
        case PeerPushPaymentInitiationStatus.AbortingRefresh:
          newStatus = PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh;
          break;
        case PeerPushPaymentInitiationStatus.AbortingDeletePurse:
          newStatus =
            PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse;
          break;
        case PeerPushPaymentInitiationStatus.PendingReady:
          newStatus = PeerPushPaymentInitiationStatus.SuspendedReady;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse:
        case PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh:
        case PeerPushPaymentInitiationStatus.SuspendedReady:
        case PeerPushPaymentInitiationStatus.SuspendedCreatePurse:
        case PeerPushPaymentInitiationStatus.Done:
        case PeerPushPaymentInitiationStatus.Aborted:
          // Do nothing
          break;
        default:
          assertUnreachable(pushDebitRec.status);
      }
      if (newStatus != null) {
        const oldTxState = computePeerPushDebitTransactionState(pushDebitRec);
        pushDebitRec.status = newStatus;
        const newTxState = computePeerPushDebitTransactionState(pushDebitRec);
        await tx.peerPushPaymentInitiations.put(pushDebitRec);
        return {
          oldTxState,
          newTxState,
        };
      }
      return undefined;
    });
  notifyTransition(ws, transactionId, transitionInfo);
}

export async function resumePeerPushDebitTransaction(
  ws: InternalWalletState,
  pursePub: string,
) {
  const taskId = constructTaskIdentifier({
    tag: PendingTaskType.PeerPushDebit,
    pursePub,
  });
  const transactionId = constructTransactionIdentifier({
    tag: TransactionType.PeerPushDebit,
    pursePub,
  });
  stopLongpolling(ws, taskId);
  const transitionInfo = await ws.db
    .mktx((x) => [x.peerPushPaymentInitiations])
    .runReadWrite(async (tx) => {
      const pushDebitRec = await tx.peerPushPaymentInitiations.get(pursePub);
      if (!pushDebitRec) {
        logger.warn(`peer push debit ${pursePub} not found`);
        return;
      }
      let newStatus: PeerPushPaymentInitiationStatus | undefined = undefined;
      switch (pushDebitRec.status) {
        case PeerPushPaymentInitiationStatus.SuspendedAbortingDeletePurse:
          newStatus = PeerPushPaymentInitiationStatus.AbortingDeletePurse;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedAbortingRefresh:
          newStatus = PeerPushPaymentInitiationStatus.AbortingRefresh;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedReady:
          newStatus = PeerPushPaymentInitiationStatus.PendingReady;
          break;
        case PeerPushPaymentInitiationStatus.SuspendedCreatePurse:
          newStatus = PeerPushPaymentInitiationStatus.PendingCreatePurse;
          break;
        case PeerPushPaymentInitiationStatus.PendingCreatePurse:
        case PeerPushPaymentInitiationStatus.AbortingRefresh:
        case PeerPushPaymentInitiationStatus.AbortingDeletePurse:
        case PeerPushPaymentInitiationStatus.PendingReady:
        case PeerPushPaymentInitiationStatus.Done:
        case PeerPushPaymentInitiationStatus.Aborted:
          // Do nothing
          break;
        default:
          assertUnreachable(pushDebitRec.status);
      }
      if (newStatus != null) {
        const oldTxState = computePeerPushDebitTransactionState(pushDebitRec);
        pushDebitRec.status = newStatus;
        const newTxState = computePeerPushDebitTransactionState(pushDebitRec);
        await tx.peerPushPaymentInitiations.put(pushDebitRec);
        return {
          oldTxState,
          newTxState,
        };
      }
      return undefined;
    });
  notifyTransition(ws, transactionId, transitionInfo);
}

export function computePeerPushCreditTransactionState(
  pushCreditRecord: PeerPushPaymentIncomingRecord,
): TransactionState {
  switch (pushCreditRecord.status) {
    case PeerPushPaymentIncomingStatus.Proposed:
      return {
        major: TransactionMajorState.Dialog,
        minor: TransactionMinorState.Proposed,
      };
    case PeerPushPaymentIncomingStatus.Accepted:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Merge,
      };
    case PeerPushPaymentIncomingStatus.Done:
      return {
        major: TransactionMajorState.Done,
      };
    case PeerPushPaymentIncomingStatus.MergeKycRequired:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.KycRequired,
      };
    case PeerPushPaymentIncomingStatus.Withdrawing:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Withdraw,
      };
  }
}

export function computePeerPullCreditTransactionState(
  pullCreditRecord: PeerPullPaymentInitiationRecord,
): TransactionState {
  switch (pullCreditRecord.status) {
    case PeerPullPaymentInitiationStatus.PendingCreatePurse:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPullPaymentInitiationStatus.PendingMergeKycRequired:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.MergeKycRequired,
      };
    case PeerPullPaymentInitiationStatus.PendingReady:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Ready,
      };
    case PeerPullPaymentInitiationStatus.DonePurseDeposited:
      return {
        major: TransactionMajorState.Done,
      };
    case PeerPullPaymentInitiationStatus.PendingWithdrawing:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Withdraw,
      };
    case PeerPullPaymentInitiationStatus.SuspendedCreatePurse:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.CreatePurse,
      };
    case PeerPullPaymentInitiationStatus.SuspendedReady:
      return {
        major: TransactionMajorState.Suspended,
        minor: TransactionMinorState.Ready,
      };
    case PeerPullPaymentInitiationStatus.SuspendedWithdrawing:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Withdraw,
      };
  }
}

export function computePeerPullDebitTransactionState(
  pullDebitRecord: PeerPullPaymentIncomingRecord,
): TransactionState {
  switch (pullDebitRecord.status) {
    case PeerPullPaymentIncomingStatus.Proposed:
      return {
        major: TransactionMajorState.Dialog,
        minor: TransactionMinorState.Proposed,
      };
    case PeerPullPaymentIncomingStatus.Accepted:
      return {
        major: TransactionMajorState.Pending,
        minor: TransactionMinorState.Deposit,
      };
    case PeerPullPaymentIncomingStatus.Paid:
      return {
        major: TransactionMajorState.Done,
      };
  }
}