aboutsummaryrefslogtreecommitdiff
path: root/src/bank-lib/fakebank.c
blob: b3639cae462458d2692aa221041afe0bef7f7446 (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
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
/*
  This file is part of TALER
  (C) 2016-2021 Taler Systems SA

  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.

  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 TALER; see the file COPYING.  If not,
  see <http://www.gnu.org/licenses/>
*/
/**
 * @file bank-lib/fakebank.c
 * @brief library that fakes being a Taler bank for testcases
 * @author Christian Grothoff <christian@grothoff.org>
 */
// TODO: support adding WAD transfers

#include "platform.h"
#include <pthread.h>
#include <poll.h>
#include <sys/eventfd.h>
#include "taler_fakebank_lib.h"
#include "taler_bank_service.h"
#include "taler_mhd_lib.h"
#include <gnunet/gnunet_mhd_compat.h>

/**
 * Maximum POST request size (for /admin/add-incoming)
 */
#define REQUEST_BUFFER_MAX (4 * 1024)

/**
 * How long are exchange base URLs allowed to be at most?
 * Set to a relatively low number as this does contribute
 * significantly to our RAM consumption.
 */
#define MAX_URL_LEN 64

/**
 * Per account information.
 */
struct Account;


/**
 * Types of long polling activities.
 */
enum LongPollType
{
  /**
   * Transfer TO the exchange.
   */
  LP_CREDIT,

  /**
   * Transfer FROM the exchange.
   */
  LP_DEBIT

};

/**
 * Client waiting for activity on this account.
 */
struct LongPoller
{

  /**
   * Kept in a DLL.
   */
  struct LongPoller *next;

  /**
   * Kept in a DLL.
   */
  struct LongPoller *prev;

  /**
   * Account this long poller is waiting on.
   */
  struct Account *account;

  /**
   * Entry in the heap for this long poller.
   */
  struct GNUNET_CONTAINER_HeapNode *hn;

  /**
   * Client that is waiting for transactions.
   */
  struct MHD_Connection *conn;

  /**
   * When will this long poller time out?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * What does the @e connection wait for?
   */
  enum LongPollType type;

};


/**
 * Details about a transcation we (as the simulated bank) received.
 */
struct Transaction;

/**
 * Per account information.
 */
struct Account
{

  /**
   * Inbound transactions for this account in a MDLL.
   */
  struct Transaction *in_head;

  /**
   * Inbound transactions for this account in a MDLL.
   */
  struct Transaction *in_tail;

  /**
   * Outbound transactions for this account in a MDLL.
   */
  struct Transaction *out_head;

  /**
   * Outbound transactions for this account in a MDLL.
   */
  struct Transaction *out_tail;

  /**
   * Kept in a DLL.
   */
  struct LongPoller *lp_head;

  /**
   * Kept in a DLL.
   */
  struct LongPoller *lp_tail;

  /**
   * Account name (string, not payto!)
   */
  char *account_name;

  /**
   * Current account balance.
   */
  struct TALER_Amount balance;

  /**
   * true if the balance is negative.
   */
  bool is_negative;

};


/**
 * Details about a transcation we (as the simulated bank) received.
 */
struct Transaction
{
  /**
   * We store inbound transactions in a MDLL.
   */
  struct Transaction *next_in;

  /**
   * We store inbound transactions in a MDLL.
   */
  struct Transaction *prev_in;

  /**
   * We store outbound transactions in a MDLL.
   */
  struct Transaction *next_out;

  /**
   * We store outbound transactions in a MDLL.
   */
  struct Transaction *prev_out;

  /**
   * Amount to be transferred.
   */
  struct TALER_Amount amount;

  /**
   * Account to debit.
   */
  struct Account *debit_account;

  /**
   * Account to credit.
   */
  struct Account *credit_account;

  /**
   * Random unique identifier for the request.
   * Used to detect idempotent requests.
   */
  struct GNUNET_HashCode request_uid;

  /**
   * When did the transaction happen?
   */
  struct GNUNET_TIME_Absolute date;

  /**
   * Number of this transaction.
   */
  uint64_t row_id;

  /**
   * What does the @e subject contain?
   */
  enum
  {
    /**
     * Transfer TO the exchange.
     */
    T_CREDIT,

    /**
     * Transfer FROM the exchange.
     */
    T_DEBIT,

    /**
     * Exchange-to-exchange WAD transfer.
     */
    T_WAD,
  } type;

  /**
   * Wire transfer subject.
   */
  union
  {

    /**
     * Used if @e type is T_DEBIT.
     */
    struct
    {

      /**
       * Subject of the transfer.
       */
      struct TALER_WireTransferIdentifierRawP wtid;

      /**
       * Base URL of the exchange.
       */
      char exchange_base_url[MAX_URL_LEN];

    } debit;

    /**
     * Used if @e type is T_CREDIT.
     */
    struct
    {

      /**
       * Reserve public key of the credit operation.
       */
      struct TALER_ReservePublicKeyP reserve_pub;

    } credit;

    /**
     * Used if @e type is T_WAD.
     */
    struct
    {

      /**
       * Subject of the transfer.
       */
      struct TALER_WadIdentifierP wad;

      /**
       * Base URL of the originating exchange.
       */
      char origin_base_url[MAX_URL_LEN];

    } wad;

  } subject;

  /**
   * Has this transaction not yet been subjected to
   * #TALER_FAKEBANK_check_credit() or #TALER_FAKEBANK_check_debit() and
   * should thus be counted in #TALER_FAKEBANK_check_empty()?
   */
  bool unchecked;
};


/**
 * Handle for the fake bank.
 */
struct TALER_FAKEBANK_Handle
{
  /**
   * We store transactions in a revolving array.
   */
  struct Transaction **transactions;

  /**
   * HTTP server we run to pretend to be the "test" bank.
   */
  struct MHD_Daemon *mhd_bank;

  /**
   * Task running HTTP server for the "test" bank,
   * unless we are using a thread pool (then NULL).
   */
  struct GNUNET_SCHEDULER_Task *mhd_task;

  /**
   * Task for expiring long-polling connections,
   * unless we are using a thread pool (then NULL).
   */
  struct GNUNET_SCHEDULER_Task *lp_task;

  /**
   * Task for expiring long-polling connections, unless we are using the
   * GNUnet scheduler (then NULL).
   */
  pthread_t lp_thread;

  /**
   * MIN-heap of long pollers, sorted by timeout.
   */
  struct GNUNET_CONTAINER_Heap *lp_heap;

  /**
   * Hashmap of reserve public keys to
   * `struct Transaction` with that reserve public
   * key. Used to prevent public-key re-use.
   */
  struct GNUNET_CONTAINER_MultiPeerMap *rpubs;

  /**
   * Lock for accessing @a rpubs map.
   */
  pthread_mutex_t rpubs_lock;

  /**
   * Hashmap of hashes of account names to `struct Account`.
   */
  struct GNUNET_CONTAINER_MultiHashMap *accounts;

  /**
   * Lock for accessing @a accounts hash map.
   */
  pthread_mutex_t accounts_lock;

  /**
   * Hashmap of hashes of transaction request_uids to `struct Transaction`.
   */
  struct GNUNET_CONTAINER_MultiHashMap *uuid_map;

  /**
   * Lock for accessing @a uuid_map.
   */
  pthread_mutex_t uuid_map_lock;

  /**
   * Lock for accessing the internals of
   * accounts and transaction array entries.
   */
  pthread_mutex_t big_lock;

  /**
   * Current transaction counter.
   */
  uint64_t serial_counter;

  /**
   * Number of transactions we keep in memory (at most).
   */
  uint64_t ram_limit;

  /**
   * Currency used by the fakebank.
   */
  char *currency;

  /**
   * BaseURL of the fakebank.
   */
  char *my_baseurl;

  /**
   * Our port number.
   */
  uint16_t port;

  /**
   * Event FD to signal @a lp_thread a change in
   * @a lp_heap.
   */
  int lp_event;

  /**
   * Set to true once we are shutting down.
   */
  bool in_shutdown;

  /**
   * Should we run MHD immediately again?
   */
  bool mhd_again;

#if EPOLL_SUPPORT
  /**
   * Boxed @e mhd_fd.
   */
  struct GNUNET_NETWORK_Handle *mhd_rfd;

  /**
   * File descriptor to use to wait for MHD.
   */
  int mhd_fd;
#endif
};


/**
 * Special address "con_cls" can point to to indicate that the handler has
 * been called more than once already (was previously suspended).
 */
static int special_ptr;


/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls the `struct TALER_FAKEBANK_Handle`
 */
static void
run_mhd (void *cls);


/**
 * Trigger the @a lp. Frees associated resources,
 * except the entry of @a lp in the timeout heap.
 * Must be called while the ``big lock`` is held.
 *
 * @param[in] lp long poller to trigger
 * @param[in,out] h fakebank handle
 */
static void
lp_trigger (struct LongPoller *lp,
            struct TALER_FAKEBANK_Handle *h)
{
  struct Account *acc = lp->account;

  GNUNET_CONTAINER_DLL_remove (acc->lp_head,
                               acc->lp_tail,
                               lp);
  MHD_resume_connection (lp->conn);
  GNUNET_free (lp);
  h->mhd_again = true;
  if (NULL != h->mhd_task)
    GNUNET_SCHEDULER_cancel (h->mhd_task);
  h->mhd_task =
    GNUNET_SCHEDULER_add_now (&run_mhd,
                              h);
}


/**
 * Thread that is run to wake up connections that have hit their timeout. Runs
 * until in_shutdown is set to true. Must be send signals via lp_event on
 * shutdown and/or whenever the heap changes to an earlier timeout.
 *
 * @param cls a `struct TALER_FAKEBANK_Handle *`
 * @return NULL
 */
static void *
lp_expiration_thread (void *cls)
{
  struct TALER_FAKEBANK_Handle *h = cls;

  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->big_lock));
  while (! h->in_shutdown)
  {
    struct LongPoller *lp;
    int timeout_ms;

    lp = GNUNET_CONTAINER_heap_peek (h->lp_heap);
    while ( (NULL != lp) &&
            GNUNET_TIME_absolute_is_past (lp->timeout))
    {
      GNUNET_assert (lp ==
                     GNUNET_CONTAINER_heap_remove_root (h->lp_heap));
      lp_trigger (lp,
                  h);
      lp = GNUNET_CONTAINER_heap_peek (h->lp_heap);
    }
    if (NULL != lp)
    {
      struct GNUNET_TIME_Relative rem;
      unsigned long long left_ms;

      rem = GNUNET_TIME_absolute_get_remaining (lp->timeout);
      left_ms = rem.rel_value_us / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us;
      if (left_ms > INT_MAX)
        timeout_ms = INT_MAX;
      else
        timeout_ms = (int) left_ms;
    }
    else
    {
      timeout_ms = -1; /* infinity */
    }
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->big_lock));
    {
      struct pollfd p = {
        .fd = h->lp_event,
        .events = POLLIN
      };
      int ret;

      ret = poll (&p,
                  1,
                  timeout_ms);
      if (-1 == ret)
      {
        GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                             "poll");
      }
      else if (1 == ret)
      {
        /* clear event */
        uint64_t ev;
        ssize_t iret;

        iret = read (h->lp_event,
                     &ev,
                     sizeof (ev));
        if (-1 == iret)
        {
          GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                               "read");
        }
        else
        {
          GNUNET_break (sizeof (uint64_t) == iret);
        }
      }
    }
    GNUNET_assert (0 ==
                   pthread_mutex_lock (&h->big_lock));
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->big_lock));
  return NULL;
}


/**
 * Lookup account with @a name, and if it does not exist, create it.
 *
 * @param[in,out] h bank to lookup account at
 * @param name account name to resolve
 * @return account handle (never NULL)
 */
static struct Account *
lookup_account (struct TALER_FAKEBANK_Handle *h,
                const char *name)
{
  struct GNUNET_HashCode hc;
  size_t slen;
  struct Account *account;

  memset (&hc,
          0,
          sizeof (hc));
  slen = strlen (name);
  GNUNET_CRYPTO_hash (name,
                      slen,
                      &hc);
  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->accounts_lock));
  account = GNUNET_CONTAINER_multihashmap_get (h->accounts,
                                               &hc);
  if (NULL == account)
  {
    account = GNUNET_new (struct Account);
    account->account_name = GNUNET_strdup (name);
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (h->currency,
                                          &account->balance));
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (h->accounts,
                                                      &hc,
                                                      account,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->accounts_lock));
  return account;
}


/**
 * Generate log messages for failed check operation.
 *
 * @param h handle to output transaction log for
 */
static void
check_log (struct TALER_FAKEBANK_Handle *h)
{
  for (uint64_t i = 0; i<h->ram_limit; i++)
  {
    struct Transaction *t = h->transactions[i];

    if (NULL == t)
      continue;
    if (! t->unchecked)
      continue;
    switch (t->type)
    {
    case T_DEBIT:
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "%s -> %s (%s) %s (%s)\n",
                  t->debit_account->account_name,
                  t->credit_account->account_name,
                  TALER_amount2s (&t->amount),
                  t->subject.debit.exchange_base_url,
                  "DEBIT");
      break;
    case T_CREDIT:
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "%s -> %s (%s) %s (%s)\n",
                  t->debit_account->account_name,
                  t->credit_account->account_name,
                  TALER_amount2s (&t->amount),
                  TALER_B2S (&t->subject.credit.reserve_pub),
                  "CREDIT");
      break;
    case T_WAD:
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "%s -> %s (%s) %s[%s] (%s)\n",
                  t->debit_account->account_name,
                  t->credit_account->account_name,
                  TALER_amount2s (&t->amount),
                  t->subject.wad.origin_base_url,
                  TALER_B2S (&t->subject.wad),
                  "WAD");
      break;
    }
  }
}


enum GNUNET_GenericReturnValue
TALER_FAKEBANK_check_debit (struct TALER_FAKEBANK_Handle *h,
                            const struct TALER_Amount *want_amount,
                            const char *want_debit,
                            const char *want_credit,
                            const char *exchange_base_url,
                            struct TALER_WireTransferIdentifierRawP *wtid)
{
  struct Account *debit_account;
  struct Account *credit_account;

  GNUNET_assert (0 ==
                 strcasecmp (want_amount->currency,
                             h->currency));
  debit_account = lookup_account (h,
                                  want_debit);
  credit_account = lookup_account (h,
                                   want_credit);
  for (struct Transaction *t = debit_account->out_tail;
       NULL != t;
       t = t->prev_out)
  {
    if ( (t->unchecked) &&
         (credit_account == t->credit_account) &&
         (T_DEBIT == t->type) &&
         (0 == TALER_amount_cmp (want_amount,
                                 &t->amount)) &&
         (0 == strcasecmp (exchange_base_url,
                           t->subject.debit.exchange_base_url)) )
    {
      *wtid = t->subject.debit.wtid;
      t->unchecked = false;
      return GNUNET_OK;
    }
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Did not find matching transaction! I have:\n");
  check_log (h);
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "I wanted: %s->%s (%s) from exchange %s (DEBIT)\n",
              want_debit,
              want_credit,
              TALER_amount2s (want_amount),
              exchange_base_url);
  return GNUNET_SYSERR;
}


enum GNUNET_GenericReturnValue
TALER_FAKEBANK_check_credit (struct TALER_FAKEBANK_Handle *h,
                             const struct TALER_Amount *want_amount,
                             const char *want_debit,
                             const char *want_credit,
                             const struct TALER_ReservePublicKeyP *reserve_pub)
{
  struct Account *debit_account;
  struct Account *credit_account;

  GNUNET_assert (0 == strcasecmp (want_amount->currency,
                                  h->currency));
  debit_account = lookup_account (h,
                                  want_debit);
  credit_account = lookup_account (h,
                                   want_credit);
  for (struct Transaction *t = credit_account->in_tail;
       NULL != t;
       t = t->prev_in)
  {
    if ( (t->unchecked) &&
         (debit_account == t->debit_account) &&
         (T_CREDIT == t->type) &&
         (0 == TALER_amount_cmp (want_amount,
                                 &t->amount)) &&
         (0 == GNUNET_memcmp (reserve_pub,
                              &t->subject.credit.reserve_pub)) )
    {
      t->unchecked = false;
      return GNUNET_OK;
    }
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Did not find matching transaction!\nI have:\n");
  check_log (h);
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "I wanted:\n%s -> %s (%s) with subject %s (CREDIT)\n",
              want_debit,
              want_credit,
              TALER_amount2s (want_amount),
              TALER_B2S (reserve_pub));
  return GNUNET_SYSERR;
}


/**
 * Update @a account balance by @a amount.
 *
 * The @a big_lock must already be locked when calling
 * this function.
 *
 * @param[in,out] account account to update
 * @param amount balance change
 * @param debit true to subtract, false to add @a amount
 */
static void
update_balance (struct Account *account,
                const struct TALER_Amount *amount,
                bool debit)
{
  if (debit == account->is_negative)
  {
    GNUNET_assert (0 <=
                   TALER_amount_add (&account->balance,
                                     &account->balance,
                                     amount));
    return;
  }
  if (0 <= TALER_amount_cmp (&account->balance,
                             amount))
  {
    GNUNET_assert (0 <=
                   TALER_amount_subtract (&account->balance,
                                          &account->balance,
                                          amount));
  }
  else
  {
    GNUNET_assert (0 <=
                   TALER_amount_subtract (&account->balance,
                                          amount,
                                          &account->balance));
    account->is_negative = ! account->is_negative;
  }
}


/**
 * Add transaction to the debit and credit accounts,
 * updating the balances as needed.
 *
 * The transaction @a t must already be locked
 * when calling this function!
 *
 * @param[in,out] h bank handle
 * @param[in,out] t transaction to add to account lists
 */
static void
post_transaction (struct TALER_FAKEBANK_Handle *h,
                  struct Transaction *t)
{
  struct Account *debit_acc = t->debit_account;
  struct Account *credit_acc = t->credit_account;
  uint64_t row_id;
  struct Transaction *old;

  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->big_lock));
  row_id = ++h->serial_counter;
  old = h->transactions[row_id % h->ram_limit];
  h->transactions[row_id % h->ram_limit] = t;
  t->row_id = row_id;
  GNUNET_CONTAINER_MDLL_insert_tail (out,
                                     debit_acc->out_head,
                                     debit_acc->out_tail,
                                     t);
  update_balance (debit_acc,
                  &t->amount,
                  true);
  GNUNET_CONTAINER_MDLL_insert_tail (in,
                                     credit_acc->in_head,
                                     credit_acc->in_tail,
                                     t);
  update_balance (credit_acc,
                  &t->amount,
                  false);
  if (NULL != old)
  {
    struct Account *da;
    struct Account *ca;

    da = old->debit_account;
    ca = old->credit_account;
    /* slot was already in use, must clean out old
       entry first! */
    GNUNET_CONTAINER_MDLL_remove (out,
                                  da->out_head,
                                  da->out_tail,
                                  old);
    GNUNET_CONTAINER_MDLL_remove (in,
                                  ca->in_head,
                                  ca->in_tail,
                                  old);
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->big_lock));
  if ( (NULL != old) &&
       (T_DEBIT == old->type) )
  {
    GNUNET_assert (0 ==
                   pthread_mutex_lock (&h->uuid_map_lock));
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_remove (h->uuid_map,
                                                         &old->request_uid,
                                                         old));
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->uuid_map_lock));
  }
  GNUNET_free (old);
}


/**
 * Trigger long pollers that might have been waiting
 * for @a t.
 *
 * @param h fakebank handle
 * @param t transaction to notify on
 */
static void
notify_transaction (struct TALER_FAKEBANK_Handle *h,
                    struct Transaction *t)
{
  struct Account *debit_acc = t->debit_account;
  struct Account *credit_acc = t->credit_account;
  struct LongPoller *nxt;

  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->big_lock));
  for (struct LongPoller *lp = debit_acc->lp_head;
       NULL != lp;
       lp = nxt)
  {
    nxt = lp->next;
    if (LP_DEBIT == lp->type)
    {
      GNUNET_assert (lp ==
                     GNUNET_CONTAINER_heap_remove_node (lp->hn));
      lp_trigger (lp,
                  h);
    }
  }
  for (struct LongPoller *lp = credit_acc->lp_head;
       NULL != lp;
       lp = nxt)
  {
    nxt = lp->next;
    if (LP_CREDIT == lp->type)
    {
      GNUNET_assert (lp ==
                     GNUNET_CONTAINER_heap_remove_node (lp->hn));
      lp_trigger (lp,
                  h);
    }
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->big_lock));
}


/**
 * Tell the fakebank to create another wire transfer *from* an exchange.
 *
 * @param h fake bank handle
 * @param debit_account account to debit
 * @param credit_account account to credit
 * @param amount amount to transfer
 * @param subject wire transfer subject to use
 * @param exchange_base_url exchange URL
 * @param request_uid unique number to make the request unique, or NULL to create one
 * @param[out] ret_row_id pointer to store the row ID of this transaction
 * @param[out] timestamp set to the time of the transfer
 * @return #GNUNET_YES if the transfer was successful,
 *         #GNUNET_SYSERR if the request_uid was reused for a different transfer
 */
static enum GNUNET_GenericReturnValue
make_transfer (
  struct TALER_FAKEBANK_Handle *h,
  const char *debit_account,
  const char *credit_account,
  const struct TALER_Amount *amount,
  const struct TALER_WireTransferIdentifierRawP *subject,
  const char *exchange_base_url,
  const struct GNUNET_HashCode *request_uid,
  uint64_t *ret_row_id,
  struct GNUNET_TIME_Absolute *timestamp)
{
  struct Transaction *t;
  struct Account *debit_acc;
  struct Account *credit_acc;
  size_t url_len;

  GNUNET_assert (0 == strcasecmp (amount->currency,
                                  h->currency));
  GNUNET_assert (NULL != debit_account);
  GNUNET_assert (NULL != credit_account);
  GNUNET_break (0 != strncasecmp ("payto://",
                                  debit_account,
                                  strlen ("payto://")));
  GNUNET_break (0 != strncasecmp ("payto://",
                                  credit_account,
                                  strlen ("payto://")));
  url_len = strlen (exchange_base_url);
  GNUNET_assert (url_len < MAX_URL_LEN);
  debit_acc = lookup_account (h,
                              debit_account);
  credit_acc = lookup_account (h,
                               credit_account);
  if (NULL != request_uid)
  {
    GNUNET_assert (0 ==
                   pthread_mutex_lock (&h->uuid_map_lock));
    t = GNUNET_CONTAINER_multihashmap_get (h->uuid_map,
                                           request_uid);
    if (NULL != t)
    {
      if ( (debit_acc != t->debit_account) ||
           (credit_acc != t->credit_account) ||
           (0 != TALER_amount_cmp (amount,
                                   &t->amount)) ||
           (T_DEBIT != t->type) ||
           (0 != GNUNET_memcmp (subject,
                                &t->subject.debit.wtid)) )
      {
        /* Transaction exists, but with different details. */
        GNUNET_break (0);
        GNUNET_assert (0 ==
                       pthread_mutex_unlock (&h->uuid_map_lock));
        return GNUNET_SYSERR;
      }
      *ret_row_id = t->row_id;
      *timestamp = t->date;
      GNUNET_assert (0 ==
                     pthread_mutex_unlock (&h->uuid_map_lock));
      return GNUNET_OK;
    }
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->uuid_map_lock));
  }
  t = GNUNET_new (struct Transaction);
  t->unchecked = true;
  t->debit_account = debit_acc;
  t->credit_account = credit_acc;
  t->amount = *amount;
  t->date = GNUNET_TIME_absolute_get ();
  (void) GNUNET_TIME_round_abs (&t->date);
  *timestamp = t->date;
  t->type = T_DEBIT;
  memcpy (t->subject.debit.exchange_base_url,
          exchange_base_url,
          url_len);
  t->subject.debit.wtid = *subject;
  if (NULL == request_uid)
    GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE,
                                      &t->request_uid);
  else
    t->request_uid = *request_uid;
  post_transaction (h,
                    t);
  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->uuid_map_lock));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (
                   h->uuid_map,
                   &t->request_uid,
                   t,
                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->uuid_map_lock));
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Making transfer %llu from %s to %s over %s and subject %s; for exchange: %s\n",
              (unsigned long long) t->row_id,
              debit_account,
              credit_account,
              TALER_amount2s (amount),
              TALER_B2S (subject),
              exchange_base_url);
  *ret_row_id = t->row_id;
  notify_transaction (h,
                      t);
  return GNUNET_OK;
}


/**
 * Tell the fakebank to create another wire transfer *to* an exchange.
 *
 * @param h fake bank handle
 * @param debit_account account to debit
 * @param credit_account account to credit
 * @param amount amount to transfer
 * @param reserve_pub reserve public key to use in subject
 * @param[out] row_id serial_id of the transfer
 * @param[out] timestamp when was the transfer made
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
make_admin_transfer (
  struct TALER_FAKEBANK_Handle *h,
  const char *debit_account,
  const char *credit_account,
  const struct TALER_Amount *amount,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  uint64_t *row_id,
  struct GNUNET_TIME_Absolute *timestamp)
{
  struct Transaction *t;
  const struct GNUNET_PeerIdentity *pid;
  struct Account *debit_acc;
  struct Account *credit_acc;

  GNUNET_static_assert (sizeof (*pid) ==
                        sizeof (*reserve_pub));
  pid = (const struct GNUNET_PeerIdentity *) reserve_pub;
  GNUNET_assert (NULL != debit_account);
  GNUNET_assert (NULL != credit_account);
  GNUNET_assert (0 == strcasecmp (amount->currency,
                                  h->currency));
  GNUNET_break (0 != strncasecmp ("payto://",
                                  debit_account,
                                  strlen ("payto://")));
  GNUNET_break (0 != strncasecmp ("payto://",
                                  credit_account,
                                  strlen ("payto://")));
  debit_acc = lookup_account (h,
                              debit_account);
  credit_acc = lookup_account (h,
                               credit_account);

  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->rpubs_lock));
  t = GNUNET_CONTAINER_multipeermap_get (h->rpubs,
                                         pid);
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->rpubs_lock));
  if (NULL != t)
  {
    /* duplicate reserve public key not allowed */
    GNUNET_break_op (0);
    return GNUNET_NO;
  }

  t = GNUNET_new (struct Transaction);
  t->unchecked = true;
  t->debit_account = debit_acc;
  t->credit_account = credit_acc;
  t->amount = *amount;
  t->date = GNUNET_TIME_absolute_get ();
  (void) GNUNET_TIME_round_abs (&t->date);
  if (NULL != timestamp)
    *timestamp = t->date;
  t->type = T_CREDIT;
  t->subject.credit.reserve_pub = *reserve_pub;
  post_transaction (h,
                    t);
  if (NULL != row_id)
    *row_id = t->row_id;
  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->rpubs_lock));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multipeermap_put (
                   h->rpubs,
                   pid,
                   t,
                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->rpubs_lock));
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Making transfer from %s to %s over %s and subject %s at row %llu\n",
              debit_account,
              credit_account,
              TALER_amount2s (amount),
              TALER_B2S (reserve_pub),
              (unsigned long long) t->row_id);
  notify_transaction (h,
                      t);
  return GNUNET_OK;
}


enum GNUNET_GenericReturnValue
TALER_FAKEBANK_check_empty (struct TALER_FAKEBANK_Handle *h)
{
  for (uint64_t i = 0; i<h->ram_limit; i++)
  {
    struct Transaction *t = h->transactions[i];

    if ( (NULL != t) &&
         (t->unchecked) )
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Expected empty transaction set, but I have:\n");
      check_log (h);
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


static int
free_account (void *cls,
              const struct GNUNET_HashCode *key,
              void *val)
{
  struct Account *account = val;

  (void) cls;
  (void) key;
  GNUNET_assert (NULL == account->lp_head);
  GNUNET_free (account->account_name);
  GNUNET_free (account);
  return GNUNET_OK;
}


void
TALER_FAKEBANK_stop (struct TALER_FAKEBANK_Handle *h)
{
  if (NULL != h->lp_task)
  {
    GNUNET_SCHEDULER_cancel (h->lp_task);
    h->lp_task = NULL;
  }
#if EPOLL_SUPPORT
  if (NULL != h->mhd_rfd)
  {
    GNUNET_NETWORK_socket_free_memory_only_ (h->mhd_rfd);
    h->mhd_rfd = NULL;
  }
#endif
  if (-1 != h->lp_event)
  {
    uint64_t val = 1;
    void *ret;
    struct LongPoller *lp;

    GNUNET_assert (0 ==
                   pthread_mutex_lock (&h->big_lock));
    h->in_shutdown = true;
    while (NULL != (lp = GNUNET_CONTAINER_heap_remove_root (h->lp_heap)))
      lp_trigger (lp,
                  h);
    GNUNET_break (sizeof (val) ==
                  write (h->lp_event,
                         &val,
                         sizeof (val)));
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->big_lock));
    GNUNET_break (0 ==
                  pthread_join (h->lp_thread,
                                &ret));
    GNUNET_break (NULL == ret);
    GNUNET_break (0 == close (h->lp_event));
    h->lp_event = -1;
  }
  else
  {
    struct LongPoller *lp;

    while (NULL != (lp = GNUNET_CONTAINER_heap_remove_root (h->lp_heap)))
      lp_trigger (lp,
                  h);
  }
  if (NULL != h->mhd_bank)
  {
    MHD_stop_daemon (h->mhd_bank);
    h->mhd_bank = NULL;
  }
  if (NULL != h->mhd_task)
  {
    GNUNET_SCHEDULER_cancel (h->mhd_task);
    h->mhd_task = NULL;
  }
  if (NULL != h->accounts)
  {
    GNUNET_CONTAINER_multihashmap_iterate (h->accounts,
                                           &free_account,
                                           NULL);
    GNUNET_CONTAINER_multihashmap_destroy (h->accounts);
  }
  GNUNET_CONTAINER_multihashmap_destroy (h->uuid_map);
  GNUNET_CONTAINER_multipeermap_destroy (h->rpubs);
  GNUNET_CONTAINER_heap_destroy (h->lp_heap);
  GNUNET_assert (0 ==
                 pthread_mutex_destroy (&h->big_lock));
  GNUNET_assert (0 ==
                 pthread_mutex_destroy (&h->uuid_map_lock));
  GNUNET_assert (0 ==
                 pthread_mutex_destroy (&h->accounts_lock));
  GNUNET_assert (0 ==
                 pthread_mutex_destroy (&h->rpubs_lock));
  for (uint64_t i = 0; i<h->ram_limit; i++)
    GNUNET_free (h->transactions[i]);
  GNUNET_free (h->transactions);
  GNUNET_free (h->my_baseurl);
  GNUNET_free (h->currency);
  GNUNET_free (h);
}


/**
 * Function called whenever MHD is done with a request.  If the
 * request was a POST, we may have stored a `struct Buffer *` in the
 * @a con_cls that might still need to be cleaned up.  Call the
 * respective function to free the memory.
 *
 * @param cls client-defined closure
 * @param connection connection handle
 * @param con_cls value as set by the last call to
 *        the #MHD_AccessHandlerCallback
 * @param toe reason for request termination
 * @see #MHD_OPTION_NOTIFY_COMPLETED
 * @ingroup request
 */
static void
handle_mhd_completion_callback (void *cls,
                                struct MHD_Connection *connection,
                                void **con_cls,
                                enum MHD_RequestTerminationCode toe)
{
  /*  struct TALER_FAKEBANK_Handle *h = cls; */
  (void) cls;
  (void) connection;
  (void) toe;
  if (NULL == *con_cls)
    return;
  if (&special_ptr == *con_cls)
    return;
  GNUNET_JSON_post_parser_cleanup (*con_cls);
  *con_cls = NULL;
}


/**
 * Handle incoming HTTP request for /admin/add/incoming.
 *
 * @param h the fakebank handle
 * @param connection the connection
 * @param account account into which to deposit the funds (credit)
 * @param upload_data request data
 * @param upload_data_size size of @a upload_data in bytes
 * @param con_cls closure for request (a `struct Buffer *`)
 * @return MHD result code
 */
static MHD_RESULT
handle_admin_add_incoming (struct TALER_FAKEBANK_Handle *h,
                           struct MHD_Connection *connection,
                           const char *account,
                           const char *upload_data,
                           size_t *upload_data_size,
                           void **con_cls)
{
  enum GNUNET_JSON_PostResult pr;
  json_t *json;
  uint64_t row_id;
  struct GNUNET_TIME_Absolute timestamp;

  pr = GNUNET_JSON_post_parser (REQUEST_BUFFER_MAX,
                                connection,
                                con_cls,
                                upload_data,
                                upload_data_size,
                                &json);
  switch (pr)
  {
  case GNUNET_JSON_PR_OUT_OF_MEMORY:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_CONTINUE:
    return MHD_YES;
  case GNUNET_JSON_PR_REQUEST_TOO_LARGE:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_JSON_INVALID:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_SUCCESS:
    break;
  }
  {
    const char *debit_account;
    struct TALER_Amount amount;
    struct TALER_ReservePublicKeyP reserve_pub;
    char *debit;
    enum GNUNET_GenericReturnValue ret;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_fixed_auto ("reserve_pub",
                                   &reserve_pub),
      GNUNET_JSON_spec_string ("debit_account",
                               &debit_account),
      TALER_JSON_spec_amount ("amount",
                              h->currency,
                              &amount),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        (ret = TALER_MHD_parse_json_data (connection,
                                          json,
                                          spec)))
    {
      GNUNET_break_op (0);
      json_decref (json);
      return (GNUNET_NO == ret) ? MHD_YES : MHD_NO;
    }
    if (0 != strcasecmp (amount.currency,
                         h->currency))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Currency `%s' does not match our configuration\n",
                  amount.currency);
      json_decref (json);
      return TALER_MHD_reply_with_error (
        connection,
        MHD_HTTP_CONFLICT,
        TALER_EC_GENERIC_CURRENCY_MISMATCH,
        NULL);
    }
    debit = TALER_xtalerbank_account_from_payto (debit_account);
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Receiving incoming wire transfer: %s->%s, subject: %s, amount: %s\n",
                debit,
                account,
                TALER_B2S (&reserve_pub),
                TALER_amount2s (&amount));
    ret = make_admin_transfer (h,
                               debit,
                               account,
                               &amount,
                               &reserve_pub,
                               &row_id,
                               &timestamp);
    GNUNET_free (debit);
    if (GNUNET_OK != ret)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Reserve public key not unique\n");
      json_decref (json);
      return TALER_MHD_reply_with_error (
        connection,
        MHD_HTTP_CONFLICT,
        TALER_EC_BANK_DUPLICATE_RESERVE_PUB_SUBJECT,
        NULL);
    }
  }
  json_decref (json);

  /* Finally build response object */
  return TALER_MHD_REPLY_JSON_PACK (connection,
                                    MHD_HTTP_OK,
                                    GNUNET_JSON_pack_uint64 ("row_id",
                                                             row_id),
                                    GNUNET_JSON_pack_time_abs ("timestamp",
                                                               timestamp));
}


/**
 * Handle incoming HTTP request for /transfer.
 *
 * @param h the fakebank handle
 * @param connection the connection
 * @param account account making the transfer
 * @param upload_data request data
 * @param upload_data_size size of @a upload_data in bytes
 * @param con_cls closure for request (a `struct Buffer *`)
 * @return MHD result code
 */
static MHD_RESULT
handle_transfer (struct TALER_FAKEBANK_Handle *h,
                 struct MHD_Connection *connection,
                 const char *account,
                 const char *upload_data,
                 size_t *upload_data_size,
                 void **con_cls)
{
  enum GNUNET_JSON_PostResult pr;
  json_t *json;
  uint64_t row_id;
  struct GNUNET_TIME_Absolute ts;

  pr = GNUNET_JSON_post_parser (REQUEST_BUFFER_MAX,
                                connection,
                                con_cls,
                                upload_data,
                                upload_data_size,
                                &json);
  switch (pr)
  {
  case GNUNET_JSON_PR_OUT_OF_MEMORY:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_CONTINUE:
    return MHD_YES;
  case GNUNET_JSON_PR_REQUEST_TOO_LARGE:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_JSON_INVALID:
    GNUNET_break (0);
    return MHD_NO;
  case GNUNET_JSON_PR_SUCCESS:
    break;
  }
  {
    struct GNUNET_HashCode uuid;
    struct TALER_WireTransferIdentifierRawP wtid;
    const char *credit_account;
    char *credit;
    const char *base_url;
    struct TALER_Amount amount;
    enum GNUNET_GenericReturnValue ret;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_fixed_auto ("request_uid",
                                   &uuid),
      TALER_JSON_spec_amount ("amount",
                              h->currency,
                              &amount),
      GNUNET_JSON_spec_string ("exchange_base_url",
                               &base_url),
      GNUNET_JSON_spec_fixed_auto ("wtid",
                                   &wtid),
      GNUNET_JSON_spec_string ("credit_account",
                               &credit_account),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        (ret = TALER_MHD_parse_json_data (connection,
                                          json,
                                          spec)))
    {
      GNUNET_break_op (0);
      json_decref (json);
      return (GNUNET_NO == ret) ? MHD_YES : MHD_NO;
    }
    {
      int ret;

      credit = TALER_xtalerbank_account_from_payto (credit_account);
      ret = make_transfer (h,
                           account,
                           credit,
                           &amount,
                           &wtid,
                           base_url,
                           &uuid,
                           &row_id,
                           &ts);
      if (GNUNET_OK != ret)
      {
        MHD_RESULT res;
        char *uids;

        GNUNET_break (0);
        uids = GNUNET_STRINGS_data_to_string_alloc (&uuid,
                                                    sizeof (uuid));
        json_decref (json);
        res = TALER_MHD_reply_with_error (connection,
                                          MHD_HTTP_CONFLICT,
                                          TALER_EC_BANK_TRANSFER_REQUEST_UID_REUSED,
                                          uids);
        GNUNET_free (uids);
        return res;
      }
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Receiving incoming wire transfer: %s->%s, subject: %s, amount: %s, from %s\n",
                  account,
                  credit,
                  TALER_B2S (&wtid),
                  TALER_amount2s (&amount),
                  base_url);
      GNUNET_free (credit);
    }
  }
  json_decref (json);

  /* Finally build response object */
  return TALER_MHD_REPLY_JSON_PACK (
    connection,
    MHD_HTTP_OK,
    GNUNET_JSON_pack_uint64 ("row_id",
                             row_id),
    GNUNET_JSON_pack_time_abs ("timestamp",
                               ts));
}


/**
 * Handle incoming HTTP request for / (home page).
 *
 * @param h the fakebank handle
 * @param connection the connection
 * @return MHD result code
 */
static MHD_RESULT
handle_home_page (struct TALER_FAKEBANK_Handle *h,
                  struct MHD_Connection *connection)
{
  MHD_RESULT ret;
  struct MHD_Response *resp;
#define HELLOMSG "Hello, Fakebank!"

  (void) h;
  resp = MHD_create_response_from_buffer (
    strlen (HELLOMSG),
    HELLOMSG,
    MHD_RESPMEM_MUST_COPY);
  ret = MHD_queue_response (connection,
                            MHD_HTTP_OK,
                            resp);
  MHD_destroy_response (resp);
  return ret;
}


/**
 * This is the "base" structure for both the /history and the
 * /history-range API calls.
 */
struct HistoryArgs
{

  /**
   * Bank account number of the requesting client.
   */
  uint64_t account_number;

  /**
   * Index of the starting transaction.
   */
  uint64_t start_idx;

  /**
   * Requested number of results and order
   * (positive: ascending, negative: descending)
   */
  int64_t delta;

  /**
   * Timeout for long polling.
   */
  struct GNUNET_TIME_Relative lp_timeout;

  /**
   * true if starting point was given.
   */
  bool have_start;

};


/**
 * Parse URL history arguments, of _both_ APIs:
 * /history/incoming and /history/outgoing.
 *
 * @param h bank handle to work on
 * @param connection MHD connection.
 * @param[out] ha will contain the parsed values.
 * @return #GNUNET_OK only if the parsing succeeds,
 *         #GNUNET_SYSERR if it failed,
 *         #GNUNET_NO if it failed and an error was returned
 */
static enum GNUNET_GenericReturnValue
parse_history_common_args (const struct TALER_FAKEBANK_Handle *h,
                           struct MHD_Connection *connection,
                           struct HistoryArgs *ha)
{
  const char *start;
  const char *delta;
  const char *long_poll_ms;
  unsigned long long lp_timeout;
  unsigned long long sval;
  long long d;
  char dummy;

  start = MHD_lookup_connection_value (connection,
                                       MHD_GET_ARGUMENT_KIND,
                                       "start");
  ha->have_start = (NULL != start);
  delta = MHD_lookup_connection_value (connection,
                                       MHD_GET_ARGUMENT_KIND,
                                       "delta");
  long_poll_ms = MHD_lookup_connection_value (connection,
                                              MHD_GET_ARGUMENT_KIND,
                                              "long_poll_ms");
  lp_timeout = 0;
  if ( (NULL == delta) ||
       (1 != sscanf (delta,
                     "%lld%c",
                     &d,
                     &dummy)) )
  {
    /* Fail if one of the above failed.  */
    /* Invalid request, given that this is fakebank we impolitely
     * just kill the connection instead of returning a nice error.
     */
    GNUNET_break_op (0);
    return (MHD_YES ==
            TALER_MHD_reply_with_error (connection,
                                        MHD_HTTP_BAD_REQUEST,
                                        TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                        "delta"))
      ? GNUNET_NO
      : GNUNET_SYSERR;
  }
  if ( (NULL != long_poll_ms) &&
       (1 != sscanf (long_poll_ms,
                     "%llu%c",
                     &lp_timeout,
                     &dummy)) )
  {
    /* Fail if one of the above failed.  */
    /* Invalid request, given that this is fakebank we impolitely
     * just kill the connection instead of returning a nice error.
     */
    GNUNET_break_op (0);
    return (MHD_YES ==
            TALER_MHD_reply_with_error (connection,
                                        MHD_HTTP_BAD_REQUEST,
                                        TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                        "long_poll_ms"))
      ? GNUNET_NO
      : GNUNET_SYSERR;
  }
  if ( (NULL != start) &&
       (1 != sscanf (start,
                     "%llu%c",
                     &sval,
                     &dummy)) )
  {
    /* Fail if one of the above failed.  */
    /* Invalid request, given that this is fakebank we impolitely
     * just kill the connection instead of returning a nice error.
     */
    GNUNET_break_op (0);
    return (MHD_YES ==
            TALER_MHD_reply_with_error (connection,
                                        MHD_HTTP_BAD_REQUEST,
                                        TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                        "start"))
      ? GNUNET_NO
      : GNUNET_SYSERR;
  }
  if (NULL == start)
    ha->start_idx = (d > 0) ? 0 : h->serial_counter;
  else
    ha->start_idx = (uint64_t) sval;
  ha->delta = (int64_t) d;
  if (0 == ha->delta)
  {
    GNUNET_break_op (0);
    return (MHD_YES ==
            TALER_MHD_reply_with_error (connection,
                                        MHD_HTTP_BAD_REQUEST,
                                        TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                        "delta"))
      ? GNUNET_NO
      : GNUNET_SYSERR;
  }
  ha->lp_timeout
    = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
                                     lp_timeout);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Request for %lld records from %llu\n",
              (long long) ha->delta,
              (unsigned long long) ha->start_idx);
  return GNUNET_OK;
}


/**
 * Task run when a long poller is about to time out.
 * Only used in single-threaded mode.
 *
 * @param cls a `struct TALER_FAKEBANK_Handle *`
 */
static void
lp_timeout (void *cls)
{
  struct TALER_FAKEBANK_Handle *h = cls;
  struct LongPoller *lp;

  h->lp_task = NULL;
  while (NULL != (lp = GNUNET_CONTAINER_heap_peek (h->lp_heap)))
  {
    if (GNUNET_TIME_absolute_is_future (lp->timeout))
      break;
    GNUNET_assert (lp ==
                   GNUNET_CONTAINER_heap_remove_root (h->lp_heap));
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Timeout reached for long poller %p\n",
                lp->conn);
    lp_trigger (lp,
                h);
  }
  if (NULL == lp)
    return;
  h->lp_task = GNUNET_SCHEDULER_add_at (lp->timeout,
                                        &lp_timeout,
                                        h);
}


/**
 * Reschedule the timeout task of @a h for time @a t.
 *
 * @param h fakebank handle
 * @param t when will the next connection timeout expire
 */
static void
reschedule_lp_timeout (struct TALER_FAKEBANK_Handle *h,
                       struct GNUNET_TIME_Absolute t)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Scheduling timeout task for %s\n",
              GNUNET_STRINGS_absolute_time_to_string (t));
  if (-1 != h->lp_event)
  {
    uint64_t num = 1;

    GNUNET_break (sizeof (num) ==
                  write (h->lp_event,
                         &num,
                         sizeof (num)));
  }
  else
  {
    if (NULL != h->lp_task)
      GNUNET_SCHEDULER_cancel (h->lp_task);
    h->lp_task = GNUNET_SCHEDULER_add_at (t,
                                          &lp_timeout,
                                          h);
  }
}


/**
 * Start long-polling for @a connection and @a acc
 * for transfers in @a dir. Must be called with the
 * "big lock" held.
 *
 * @param[in,out] h fakebank handle
 * @param[in,out] connection to suspend
 * @param[in,out] acc account affected
 * @param lp_timeout how long to suspend
 * @param dir direction of transfers to watch for
 */
static void
start_lp (struct TALER_FAKEBANK_Handle *h,
          struct MHD_Connection *connection,
          struct Account *acc,
          struct GNUNET_TIME_Relative lp_timeout,
          enum LongPollType dir)
{
  struct LongPoller *lp;
  bool toc;

  lp = GNUNET_new (struct LongPoller);
  lp->account = acc;
  lp->conn = connection;
  lp->timeout = GNUNET_TIME_relative_to_absolute (lp_timeout);
  lp->type = dir;
  lp->hn = GNUNET_CONTAINER_heap_insert (h->lp_heap,
                                         lp,
                                         lp->timeout.abs_value_us);
  toc = (lp ==
         GNUNET_CONTAINER_heap_peek (h->lp_heap));
  GNUNET_CONTAINER_DLL_insert (acc->lp_head,
                               acc->lp_tail,
                               lp);
  MHD_suspend_connection (connection);
  if (toc)
    reschedule_lp_timeout (h,
                           lp->timeout);

}


/**
 * Handle incoming HTTP request for /history/outgoing
 *
 * @param h the fakebank handle
 * @param connection the connection
 * @param account which account the request is about
 * @param con_cls closure for request (NULL or &special_ptr)
 */
static MHD_RESULT
handle_debit_history (struct TALER_FAKEBANK_Handle *h,
                      struct MHD_Connection *connection,
                      const char *account,
                      void **con_cls)
{
  struct HistoryArgs ha;
  struct Account *acc;
  struct Transaction *pos;
  json_t *history;
  char *debit_payto;
  enum GNUNET_GenericReturnValue ret;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Handling /history/outgoing connection %p\n",
              connection);
  if (GNUNET_OK !=
      (ret = parse_history_common_args (h,
                                        connection,
                                        &ha)))
  {
    GNUNET_break_op (0);
    return (GNUNET_SYSERR == ret) ? MHD_NO : MHD_YES;
  }
  if (&special_ptr == *con_cls)
    ha.lp_timeout = GNUNET_TIME_UNIT_ZERO;
  acc = lookup_account (h,
                        account);
  GNUNET_asprintf (&debit_payto,
                   "payto://x-taler-bank/localhost/%s",
                   account);
  history = json_array ();
  if (NULL == history)
  {
    GNUNET_break (0);
    GNUNET_free (debit_payto);
    return MHD_NO;
  }
  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->big_lock));
  if (! ha.have_start)
  {
    pos = (0 > ha.delta)
          ? acc->out_tail
          : acc->out_head;
  }
  else
  {
    struct Transaction *t = h->transactions[ha.start_idx % h->ram_limit];
    bool overflow;
    uint64_t dir;
    bool skip = true;

    dir = (0 > ha.delta) ? (h->ram_limit - 1) : 1;
    overflow = (t->row_id != ha.start_idx);
    /* If account does not match, linear scan for
       first matching account. */
    while ( (! overflow) &&
            (NULL != t) &&
            (t->debit_account != acc) )
    {
      skip = false;
      t = h->transactions[(t->row_id + dir) % h->ram_limit];
      if ( (NULL != t) &&
           (t->row_id == ha.start_idx) )
        overflow = true; /* full circle, give up! */
    }
    if ( (NULL == t) ||
         overflow)
    {
      GNUNET_free (debit_payto);
      if (GNUNET_TIME_relative_is_zero (ha.lp_timeout) &&
          (0 < ha.delta))
      {
        GNUNET_assert (0 ==
                       pthread_mutex_unlock (&h->big_lock));
        return TALER_MHD_REPLY_JSON_PACK (
          connection,
          MHD_HTTP_OK,
          GNUNET_JSON_pack_array_steal (
            "outgoing_transactions",
            history));
      }
      *con_cls = &special_ptr;
      start_lp (h,
                connection,
                acc,
                ha.lp_timeout,
                LP_DEBIT);
      GNUNET_assert (0 ==
                     pthread_mutex_unlock (&h->big_lock));
      json_decref (history);
      return MHD_YES;
    }
    if (t->debit_account != acc)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Invalid start specified, transaction %llu not with account %s!\n",
                  (unsigned long long) ha.start_idx,
                  account);
      GNUNET_assert (0 ==
                     pthread_mutex_unlock (&h->big_lock));
      GNUNET_free (debit_payto);
      json_decref (history);
      return MHD_NO;
    }
    if (skip)
    {
      /* range is exclusive, skip the matching entry */
      if (0 > ha.delta)
        pos = t->prev_out;
      else
        pos = t->next_out;
    }
    else
    {
      pos = t;
    }
  }
  if (NULL != pos)
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Returning %lld debit transactions starting (inclusive) from %llu\n",
                (long long) ha.delta,
                (unsigned long long) pos->row_id);
  else
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "No debit transactions exist after given starting point\n");
  while ( (0 != ha.delta) &&
          (NULL != pos) )
  {
    json_t *trans;
    char *credit_payto;

    if (T_DEBIT != pos->type)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Unexpected CREDIT transaction #%llu for account `%s'\n",
                  (unsigned long long) pos->row_id,
                  account);
      if (0 > ha.delta)
        pos = pos->prev_in;
      if (0 < ha.delta)
        pos = pos->next_in;
      continue;
    }
    GNUNET_asprintf (&credit_payto,
                     "payto://x-taler-bank/localhost/%s",
                     pos->credit_account->account_name);
    trans = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_uint64 ("row_id",
                               pos->row_id),
      GNUNET_JSON_pack_time_abs ("date",
                                 pos->date),
      TALER_JSON_pack_amount ("amount",
                              &pos->amount),
      GNUNET_JSON_pack_string ("credit_account",
                               credit_payto),
      GNUNET_JSON_pack_string ("debit_account",
                               debit_payto),          // FIXME: inefficient to return this here always!
      GNUNET_JSON_pack_string ("exchange_base_url",
                               pos->subject.debit.exchange_base_url),
      GNUNET_JSON_pack_data_auto ("wtid",
                                  &pos->subject.debit.wtid));
    GNUNET_assert (NULL != trans);
    GNUNET_free (credit_payto);
    GNUNET_assert (0 ==
                   json_array_append_new (history,
                                          trans));
    if (ha.delta > 0)
      ha.delta--;
    else
      ha.delta++;
    if (0 > ha.delta)
      pos = pos->prev_out;
    if (0 < ha.delta)
      pos = pos->next_out;
  }
  if ( (0 == json_array_size (history)) &&
       (! GNUNET_TIME_relative_is_zero (ha.lp_timeout)) &&
       (0 < ha.delta))
  {
    *con_cls = &special_ptr;
    start_lp (h,
              connection,
              acc,
              ha.lp_timeout,
              LP_DEBIT);
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->big_lock));
    json_decref (history);
    return MHD_YES;
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->big_lock));
  GNUNET_free (debit_payto);
  return TALER_MHD_REPLY_JSON_PACK (connection,
                                    MHD_HTTP_OK,
                                    GNUNET_JSON_pack_array_steal (
                                      "outgoing_transactions",
                                      history));
}


/**
 * Handle incoming HTTP request for /history/incoming
 *
 * @param h the fakebank handle
 * @param connection the connection
 * @param account which account the request is about
 * @param con_cls closure for request (NULL or &special_ptr)
 * @return MHD result code
 */
static MHD_RESULT
handle_credit_history (struct TALER_FAKEBANK_Handle *h,
                       struct MHD_Connection *connection,
                       const char *account,
                       void **con_cls)
{
  struct HistoryArgs ha;
  struct Account *acc;
  const struct Transaction *pos;
  json_t *history;
  char *credit_payto;
  enum GNUNET_GenericReturnValue ret;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Handling /history/incoming connection %p (%d)\n",
              connection,
              (*con_cls == &special_ptr));
  if (GNUNET_OK !=
      (ret = parse_history_common_args (h,
                                        connection,
                                        &ha)))
  {
    GNUNET_break_op (0);
    return (GNUNET_SYSERR == ret) ? MHD_NO : MHD_YES;
  }
  if (&special_ptr == *con_cls)
    ha.lp_timeout = GNUNET_TIME_UNIT_ZERO;
  *con_cls = &special_ptr;
  acc = lookup_account (h,
                        account);
  history = json_array ();
  GNUNET_assert (NULL != history);
  GNUNET_asprintf (&credit_payto,
                   "payto://x-taler-bank/localhost/%s",
                   account);
  GNUNET_assert (0 ==
                 pthread_mutex_lock (&h->big_lock));
  if (! ha.have_start)
  {
    pos = (0 > ha.delta)
          ? acc->in_tail
          : acc->in_head;
  }
  else
  {
    struct Transaction *t = h->transactions[ha.start_idx % h->ram_limit];
    bool overflow;
    uint64_t dir;
    bool skip = true;

    overflow = ( (NULL != t) && (t->row_id != ha.start_idx) );
    dir = (0 > ha.delta) ? (h->ram_limit - 1) : 1;
    /* If account does not match, linear scan for
       first matching account. */
    while ( (! overflow) &&
            (NULL != t) &&
            (t->credit_account != acc) )
    {
      skip = false;
      t = h->transactions[(t->row_id + dir) % h->ram_limit];
      if ( (NULL != t) &&
           (t->row_id == ha.start_idx) )
        overflow = true; /* full circle, give up! */
    }
    if ( (NULL == t) ||
         overflow)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "No transactions available, suspending request\n");
      GNUNET_free (credit_payto);
      if (GNUNET_TIME_relative_is_zero (ha.lp_timeout) &&
          (0 < ha.delta))
      {
        GNUNET_assert (0 ==
                       pthread_mutex_unlock (&h->big_lock));
        return TALER_MHD_REPLY_JSON_PACK (connection,
                                          MHD_HTTP_OK,
                                          GNUNET_JSON_pack_array_steal (
                                            "incoming_transactions",
                                            history));
      }
      *con_cls = &special_ptr;
      start_lp (h,
                connection,
                acc,
                ha.lp_timeout,
                LP_CREDIT);
      GNUNET_assert (0 ==
                     pthread_mutex_unlock (&h->big_lock));
      json_decref (history);
      return MHD_YES;
    }
    if (skip)
    {
      /* range from application is exclusive, skip the
  matching entry */
      if (0 > ha.delta)
        pos = t->prev_in;
      else
        pos = t->next_in;
    }
    else
    {
      pos = t;
    }
  }
  if (NULL != pos)
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Returning %lld credit transactions starting (inclusive) from %llu\n",
                (long long) ha.delta,
                (unsigned long long) pos->row_id);
  else
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "No credit transactions exist after given starting point\n");
  while ( (0 != ha.delta) &&
          (NULL != pos) )
  {
    json_t *trans;
    char *debit_payto;

    if (T_CREDIT != pos->type)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Unexpected DEBIT transaction #%llu for account `%s'\n",
                  (unsigned long long) pos->row_id,
                  account);
      if (0 > ha.delta)
        pos = pos->prev_in;
      if (0 < ha.delta)
        pos = pos->next_in;
      continue;
    }
    GNUNET_asprintf (&debit_payto,
                     "payto://x-taler-bank/localhost/%s",
                     pos->debit_account->account_name);
    trans = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_uint64 ("row_id",
                               pos->row_id),
      GNUNET_JSON_pack_time_abs ("date",
                                 pos->date),
      TALER_JSON_pack_amount ("amount",
                              &pos->amount),
      GNUNET_JSON_pack_string ("credit_account",
                               credit_payto),   // FIXME: inefficient to repeat this always here!
      GNUNET_JSON_pack_string ("debit_account",
                               debit_payto),
      GNUNET_JSON_pack_data_auto ("reserve_pub",
                                  &pos->subject.credit.reserve_pub));
    GNUNET_assert (NULL != trans);
    GNUNET_free (debit_payto);
    GNUNET_assert (0 ==
                   json_array_append_new (history,
                                          trans));
    if (ha.delta > 0)
      ha.delta--;
    else
      ha.delta++;
    if (0 > ha.delta)
      pos = pos->prev_in;
    if (0 < ha.delta)
      pos = pos->next_in;
  }
  if ( (0 == json_array_size (history)) &&
       (! GNUNET_TIME_relative_is_zero (ha.lp_timeout)) &&
       (0 < ha.delta))
  {
    *con_cls = &special_ptr;
    start_lp (h,
              connection,
              acc,
              ha.lp_timeout,
              LP_CREDIT);
    GNUNET_assert (0 ==
                   pthread_mutex_unlock (&h->big_lock));
    json_decref (history);
    return MHD_YES;
  }
  GNUNET_assert (0 ==
                 pthread_mutex_unlock (&h->big_lock));
  GNUNET_free (credit_payto);
  return TALER_MHD_REPLY_JSON_PACK (connection,
                                    MHD_HTTP_OK,
                                    GNUNET_JSON_pack_array_steal (
                                      "incoming_transactions",
                                      history));
}


/**
 * Handle incoming HTTP request.
 *
 * @param h our handle
 * @param connection the connection
 * @param url the requested url
 * @param method the method (POST, GET, ...)
 * @param account which account should process the request
 * @param upload_data request data
 * @param upload_data_size size of @a upload_data in bytes
 * @param con_cls closure
 * @return MHD result code
 */
static MHD_RESULT
serve (struct TALER_FAKEBANK_Handle *h,
       struct MHD_Connection *connection,
       const char *account,
       const char *url,
       const char *method,
       const char *upload_data,
       size_t *upload_data_size,
       void **con_cls)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Fakebank, serving URL `%s' for account `%s'\n",
              url,
              account);
  if (0 == strcasecmp (method,
                       MHD_HTTP_METHOD_GET))
  {
    if ( (0 == strcmp (url,
                       "/history/incoming")) &&
         (NULL != account) )
      return handle_credit_history (h,
                                    connection,
                                    account,
                                    con_cls);
    if ( (0 == strcmp (url,
                       "/history/outgoing")) &&
         (NULL != account) )
      return handle_debit_history (h,
                                   connection,
                                   account,
                                   con_cls);
    if (0 == strcmp (url,
                     "/"))
      return handle_home_page (h,
                               connection);
  }
  else if (0 == strcasecmp (method,
                            MHD_HTTP_METHOD_POST))
  {
    if ( (0 == strcmp (url,
                       "/admin/add-incoming")) &&
         (NULL != account) )
      return handle_admin_add_incoming (h,
                                        connection,
                                        account,
                                        upload_data,
                                        upload_data_size,
                                        con_cls);
    if ( (0 == strcmp (url,
                       "/transfer")) &&
         (NULL != account) )
      return handle_transfer (h,
                              connection,
                              account,
                              upload_data,
                              upload_data_size,
                              con_cls);
  }
  /* Unexpected URL path, just close the connection. */
  TALER_LOG_ERROR ("Breaking URL: %s %s\n",
                   method,
                   url);
  GNUNET_break_op (0);
  return TALER_MHD_reply_with_error (
    connection,
    MHD_HTTP_NOT_FOUND,
    TALER_EC_GENERIC_ENDPOINT_UNKNOWN,
    url);
}


/**
 * Handle incoming HTTP request.
 *
 * @param cls a `struct TALER_FAKEBANK_Handle`
 * @param connection the connection
 * @param url the requested url
 * @param method the method (POST, GET, ...)
 * @param version HTTP version (ignored)
 * @param upload_data request data
 * @param upload_data_size size of @a upload_data in bytes
 * @param con_cls closure for request
 * @return MHD result code
 */
static MHD_RESULT
handle_mhd_request (void *cls,
                    struct MHD_Connection *connection,
                    const char *url,
                    const char *method,
                    const char *version,
                    const char *upload_data,
                    size_t *upload_data_size,
                    void **con_cls)
{
  struct TALER_FAKEBANK_Handle *h = cls;
  char *account = NULL;
  char *end;
  MHD_RESULT ret;

  (void) version;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Handling request for `%s'\n",
              url);
  if ( (strlen (url) > 1) &&
       (NULL != (end = strchr (url + 1, '/'))) )
  {
    account = GNUNET_strndup (url + 1,
                              end - url - 1);
    url = end;
  }
  ret = serve (h,
               connection,
               account,
               url,
               method,
               upload_data,
               upload_data_size,
               con_cls);
  GNUNET_free (account);
  return ret;
}


#if EPOLL_SUPPORT
/**
 * Schedule MHD.  This function should be called initially when an
 * MHD is first getting its client socket, and will then automatically
 * always be called later whenever there is work to be done.
 *
 * @param h fakebank handle to schedule MHD for
 */
static void
schedule_httpd (struct TALER_FAKEBANK_Handle *h)
{
  int haveto;
  MHD_UNSIGNED_LONG_LONG timeout;
  struct GNUNET_TIME_Relative tv;

  haveto = MHD_get_timeout (h->mhd_bank,
                            &timeout);
  if (MHD_YES == haveto)
    tv.rel_value_us = (uint64_t) timeout * 1000LL;
  else
    tv = GNUNET_TIME_UNIT_FOREVER_REL;
  if (NULL != h->mhd_task)
    GNUNET_SCHEDULER_cancel (h->mhd_task);
  h->mhd_task =
    GNUNET_SCHEDULER_add_read_net (tv,
                                   h->mhd_rfd,
                                   &run_mhd,
                                   h);
}


#else
/**
 * Schedule MHD.  This function should be called initially when an
 * MHD is first getting its client socket, and will then automatically
 * always be called later whenever there is work to be done.
 *
 * @param h fakebank handle to schedule MHD for
 */
static void
schedule_httpd (struct TALER_FAKEBANK_Handle *h)
{
  fd_set rs;
  fd_set ws;
  fd_set es;
  struct GNUNET_NETWORK_FDSet *wrs;
  struct GNUNET_NETWORK_FDSet *wws;
  int max;
  int haveto;
  MHD_UNSIGNED_LONG_LONG timeout;
  struct GNUNET_TIME_Relative tv;

  FD_ZERO (&rs);
  FD_ZERO (&ws);
  FD_ZERO (&es);
  max = -1;
  if (MHD_YES != MHD_get_fdset (h->mhd_bank,
                                &rs,
                                &ws,
                                &es,
                                &max))
  {
    GNUNET_assert (0);
    return;
  }
  haveto = MHD_get_timeout (h->mhd_bank,
                            &timeout);
  if (MHD_YES == haveto)
    tv.rel_value_us = (uint64_t) timeout * 1000LL;
  else
    tv = GNUNET_TIME_UNIT_FOREVER_REL;
  if (-1 != max)
  {
    wrs = GNUNET_NETWORK_fdset_create ();
    wws = GNUNET_NETWORK_fdset_create ();
    GNUNET_NETWORK_fdset_copy_native (wrs,
                                      &rs,
                                      max + 1);
    GNUNET_NETWORK_fdset_copy_native (wws,
                                      &ws,
                                      max + 1);
  }
  else
  {
    wrs = NULL;
    wws = NULL;
  }
  if (NULL != h->mhd_task)
    GNUNET_SCHEDULER_cancel (h->mhd_task);
  h->mhd_task =
    GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                 tv,
                                 wrs,
                                 wws,
                                 &run_mhd,
                                 h);
  if (NULL != wrs)
    GNUNET_NETWORK_fdset_destroy (wrs);
  if (NULL != wws)
    GNUNET_NETWORK_fdset_destroy (wws);
}


#endif


/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls the `struct TALER_FAKEBANK_Handle`
 */
static void
run_mhd (void *cls)
{
  struct TALER_FAKEBANK_Handle *h = cls;

  h->mhd_task = NULL;
  h->mhd_again = true;
  while (h->mhd_again)
  {
    h->mhd_again = false;
    MHD_run (h->mhd_bank);
  }
  schedule_httpd (h);
}


struct TALER_FAKEBANK_Handle *
TALER_FAKEBANK_start (uint16_t port,
                      const char *currency)
{
  return TALER_FAKEBANK_start2 (port,
                                currency,
                                65536, /* RAM limit */
                                1);
}


struct TALER_FAKEBANK_Handle *
TALER_FAKEBANK_start2 (uint16_t port,
                       const char *currency,
                       uint64_t ram_limit,
                       unsigned int num_threads)
{
  struct TALER_FAKEBANK_Handle *h;

  if (SIZE_MAX / sizeof (struct Transaction *) < ram_limit)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "This CPU architecture does not support keeping %llu transactions in RAM\n",
                (unsigned long long) ram_limit);
    return NULL;
  }
  GNUNET_assert (strlen (currency) < TALER_CURRENCY_LEN);
  h = GNUNET_new (struct TALER_FAKEBANK_Handle);
  h->lp_event = -1;
  h->port = port;
  h->ram_limit = ram_limit;
  h->serial_counter = 0;
  GNUNET_assert (0 ==
                 pthread_mutex_init (&h->accounts_lock,
                                     NULL));
  GNUNET_assert (0 ==
                 pthread_mutex_init (&h->rpubs_lock,
                                     NULL));
  GNUNET_assert (0 ==
                 pthread_mutex_init (&h->uuid_map_lock,
                                     NULL));
  GNUNET_assert (0 ==
                 pthread_mutex_init (&h->big_lock,
                                     NULL));
  h->transactions
    = GNUNET_malloc_large (sizeof (struct Transaction *)
                           * ram_limit);
  if (NULL == h->transactions)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "malloc");
    TALER_FAKEBANK_stop (h);
    return NULL;
  }
  h->accounts = GNUNET_CONTAINER_multihashmap_create (128,
                                                      GNUNET_NO);
  h->uuid_map = GNUNET_CONTAINER_multihashmap_create (ram_limit * 4 / 3,
                                                      GNUNET_YES);
  if (NULL == h->uuid_map)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "malloc");
    TALER_FAKEBANK_stop (h);
    return NULL;
  }
  h->rpubs = GNUNET_CONTAINER_multipeermap_create (ram_limit * 4 / 3,
                                                   GNUNET_NO);
  if (NULL == h->rpubs)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "malloc");
    TALER_FAKEBANK_stop (h);
    return NULL;
  }
  h->lp_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
  h->currency = GNUNET_strdup (currency);
  GNUNET_asprintf (&h->my_baseurl,
                   "http://localhost:%u/",
                   (unsigned int) port);
  if (0 == num_threads)
  {
    h->mhd_bank = MHD_start_daemon (MHD_USE_DEBUG
#if EPOLL_SUPPORT
                                    | MHD_USE_EPOLL
#endif
                                    | MHD_USE_DUAL_STACK
                                    | MHD_ALLOW_SUSPEND_RESUME,
                                    port,
                                    NULL, NULL,
                                    &handle_mhd_request, h,
                                    MHD_OPTION_NOTIFY_COMPLETED,
                                    &handle_mhd_completion_callback, h,
                                    MHD_OPTION_LISTEN_BACKLOG_SIZE,
                                    (unsigned int) 1024,
                                    MHD_OPTION_CONNECTION_LIMIT,
                                    (unsigned int) 65536,
                                    MHD_OPTION_END);
    if (NULL == h->mhd_bank)
    {
      TALER_FAKEBANK_stop (h);
      return NULL;
    }
#if EPOLL_SUPPORT
    h->mhd_fd = MHD_get_daemon_info (h->mhd_bank,
                                     MHD_DAEMON_INFO_EPOLL_FD)->epoll_fd;
    h->mhd_rfd = GNUNET_NETWORK_socket_box_native (h->mhd_fd);
#endif
    schedule_httpd (h);
  }
  else
  {
    h->lp_event = eventfd (0,
                           EFD_CLOEXEC);
    if (-1 == h->lp_event)
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                           "eventfd");
      TALER_FAKEBANK_stop (h);
      return NULL;
    }
    if (0 !=
        pthread_create (&h->lp_thread,
                        NULL,
                        &lp_expiration_thread,
                        h))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                           "pthread_create");
      GNUNET_break (0 == close (h->lp_event));
      h->lp_event = -1;
      TALER_FAKEBANK_stop (h);
      return NULL;
    }
    h->mhd_bank = MHD_start_daemon (MHD_USE_DEBUG
                                    | MHD_USE_AUTO_INTERNAL_THREAD
                                    | MHD_ALLOW_SUSPEND_RESUME
                                    | MHD_USE_TURBO
                                    | MHD_USE_TCP_FASTOPEN
                                    | MHD_USE_DUAL_STACK,
                                    port,
                                    NULL, NULL,
                                    &handle_mhd_request, h,
                                    MHD_OPTION_NOTIFY_COMPLETED,
                                    &handle_mhd_completion_callback, h,
                                    MHD_OPTION_LISTEN_BACKLOG_SIZE,
                                    (unsigned int) 1024,
                                    MHD_OPTION_CONNECTION_LIMIT,
                                    (unsigned int) 65536,
                                    MHD_OPTION_THREAD_POOL_SIZE,
                                    num_threads,
                                    MHD_OPTION_END);
    if (NULL == h->mhd_bank)
    {
      GNUNET_break (0);
      TALER_FAKEBANK_stop (h);
      return NULL;
    }
  }
  return h;
}


/* end of fakebank.c */