aboutsummaryrefslogtreecommitdiff
path: root/src/auditor/taler-auditor.c
blob: 5db848982045126b558ec3ff2f17612eea382109 (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
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
/*
  This file is part of TALER
  Copyright (C) 2016, 2017 Inria

  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 auditor/taler-auditor.c
 * @brief audits an exchange database.
 * @author Christian Grothoff
 *
 * NOTE:
 * - This auditor does not verify that 'reserves_in' actually matches
 *   the wire transfers from the bank. This needs to be checked separately!
 * - Similarly, we do not check that the outgoing wire transfers match those
 *   given in the 'wire_out' table. This needs to be checked separately!
 *
 * KNOWN BUGS:
 * - calculate, store and report aggregation fee balance!
 * - error handling if denomination keys are used that are not known to the
 *   auditor is, eh, awful / non-existent. We just throw the DB's constraint
 *   violation back at the user. Great UX.
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include "taler_auditordb_plugin.h"
#include "taler_exchangedb_plugin.h"
#include "taler_json_lib.h"
#include "taler_wire_lib.h"
#include "taler_signatures.h"


/**
 * How many coin histories do we keep in RAM at any given point in
 * time? Used bound memory consumption of the auditor. Larger values
 * reduce database accesses.
 *
 * Set to a VERY low value here for testing. Practical values may be
 * in the millions.
 */
#define MAX_COIN_SUMMARIES 4

/**
 * Use a 1 day grace period to deal with clocks not being perfectly synchronized.
 */
#define DEPOSIT_GRACE_PERIOD GNUNET_TIME_UNIT_DAYS

/**
 * Use a 1 day grace period to deal with clocks not being perfectly synchronized.
 */
#define CLOSING_GRACE_PERIOD GNUNET_TIME_UNIT_DAYS

/**
 * Return value from main().
 */
static int global_ret;

/**
 * Command-line option "-r": restart audit from scratch
 */
static int restart;

/**
 * Handle to access the exchange's database.
 */
static struct TALER_EXCHANGEDB_Plugin *edb;

/**
 * Which currency are we doing the audit for?
 */
static char *currency;

/**
 * Our configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Our session with the #edb.
 */
static struct TALER_EXCHANGEDB_Session *esession;

/**
 * Handle to access the auditor's database.
 */
static struct TALER_AUDITORDB_Plugin *adb;

/**
 * Our session with the #adb.
 */
static struct TALER_AUDITORDB_Session *asession;

/**
 * Master public key of the exchange to audit.
 */
static struct TALER_MasterPublicKeyP master_pub;

/**
 * Last reserve_in serial ID seen.
 */
static struct TALER_AUDITORDB_ProgressPoint pp;


/* ***************************** Report logic **************************** */


/**
 * Called in case we detect an emergency situation where the exchange
 * is paying out a larger amount on a denomination than we issued in
 * that denomination.  This means that the exchange's private keys
 * might have gotten compromised, and that we need to trigger an
 * emergency request to all wallets to deposit pending coins for the
 * denomination (and as an exchange suffer a huge financial loss).
 *
 * @param dki denomination key where the loss was detected
 */
static void
report_emergency (const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki)
{
  char *dhks;

  dhks = GNUNET_STRINGS_data_to_string_alloc (&dki->properties.denom_hash,
                                              sizeof (struct GNUNET_HashCode));
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Emergency detected. Exchange must revoke key using `taler-auditor -r %s`\n",
              dhks);
  GNUNET_free (dhks);
}


/**
 * Report a (serious) inconsistency in the exchange's database.
 *
 * @param table affected table
 * @param rowid affected row, UINT64_MAX if row is missing
 * @param diagnostic message explaining the problem
 */
static void
report_row_inconsistency (const char *table,
                          uint64_t rowid,
                          const char *diagnostic)
{
  // TODO: implement proper reporting logic writing to file.
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Database inconsistency detected in table %s at row %llu: %s\n",
              table,
              (unsigned long long) rowid,
              diagnostic);
}


/**
 * Report a minor inconsistency in the exchange's database (i.e. something
 * relating to timestamps that should have no financial implications).
 *
 * @param table affected table
 * @param rowid affected row, UINT64_MAX if row is missing
 * @param diagnostic message explaining the problem
 */
static void
report_row_minor_inconsistency (const char *table,
                                uint64_t rowid,
                                const char *diagnostic)
{
  // TODO: implement proper reporting logic writing to file.
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Minor inconsistency detected in table %s at row %llu: %s\n",
              table,
              (unsigned long long) rowid,
              diagnostic);
}


/**
 * Report a global inconsistency with respect to a reserve.
 *
 * @param reserve_pub the affected reserve
 * @param expected expected amount
 * @param observed observed amount
 * @param diagnostic message explaining what @a expected and @a observed refer to
 */
static void
report_reserve_inconsistency (const struct TALER_ReservePublicKeyP *reserve_pub,
                              const struct TALER_Amount *expected,
                              const struct TALER_Amount *observed,
                              const char *diagnostic)
{
  // TODO: implement proper reporting logic writing to file, include amounts.
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Reserve inconsistency detected affecting reserve %s: %s\n",
              TALER_B2S (reserve_pub),
              diagnostic);
}


/**
 * Report a global inconsistency with respect to a wire transfer.
 *
 * @param destination wire transfer target account
 * @param rowid which row is the inconsitency in
 * @param expected expected amount
 * @param observed observed amount
 * @param diagnostic message explaining what @a expected and @a observed refer to
 */
static void
report_wire_out_inconsistency (const json_t *destination,
                               uint64_t rowid,
                               const struct TALER_Amount *expected,
                               const struct TALER_Amount *observed,
                               const char *diagnostic)
{
  // TODO: implement proper reporting logic writing to file, include amounts.
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Wire out inconsistency detected: %s\n",
              diagnostic);
}


/**
 * Report a global inconsistency with respect to a coin's history.
 *
 * @param coin_pub the affected coin
 * @param expected expected amount
 * @param observed observed amount
 * @param diagnostic message explaining what @a expected and @a observed refer to
 */
static void
report_coin_inconsistency (const struct TALER_CoinSpendPublicKeyP *coin_pub,
                           const struct TALER_Amount *expected,
                           const struct TALER_Amount *observed,
                           const char *diagnostic)
{
  // TODO: implement proper reporting logic writing to file, include amounts.
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Coin inconsistency detected: %s\n",
              diagnostic);
}


/**
 * Report the final result on the reserve balances of the exchange.
 * The reserve must have @a total_balance in its escrow account just
 * to cover outstanding reserve funds (outstanding coins are on top).
 * The reserve has made @a total_fee_balance in profit from withdrawal
 * operations alone.
 *
 * Note that this is for the "ongoing" reporting period.  Historic
 * revenue (as stored via the "insert_historic_reserve_revenue")
 * is not included in the @a total_fee_balance.
 *
 * @param total_balance how much money (in total) is left in all of the
 *        reserves (that has not been withdrawn)
 * @param total_fee_balance how much money (in total) did the reserve
 *        make from withdrawal fees
 */
static void
report_reserve_balance (const struct TALER_Amount *total_balance,
                        const struct TALER_Amount *total_fee_balance)
{
  // TODO: implement proper reporting logic writing to file.
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Escrow balance to be held for reserves is %s\n",
              TALER_amount2s (total_balance));
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Withdraw fees income is %s\n",
              TALER_amount2s (total_fee_balance));
}


/**
 * Report on the aggregation fees the exchange made.
 *
 * Note that this is for the "ongoing" reporting period.  Historic
 * revenue (as stored via the "insert_historic_reserve_revenue")
 * is not included in the @a total_fee_balance.
 *
 * @param total_fee_balance how much money (in total) did the reserve
 *        make from aggregation fees
 */
static void
report_aggregation_fee_balance (const struct TALER_Amount *total_fee_balance)
{
  // TODO: implement proper reporting logic writing to file.
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Aggregation fees income is %s\n",
              TALER_amount2s (total_fee_balance));
}


/**
 * Report state of denomination processing.
 *
 * @param total_balance total value of outstanding coins
 * @param total_risk total value of issued coins in active denominations
 * @param deposit_fees total deposit fees collected
 * @param melt_fees total melt fees collected
 * @param refund_fees total refund fees collected
 */
static void
report_denomination_balance (const struct TALER_Amount *total_balance,
                             const struct TALER_Amount *total_risk,
                             const struct TALER_Amount *deposit_fees,
                             const struct TALER_Amount *melt_fees,
                             const struct TALER_Amount *refund_fees)
{
  // TODO: implement proper reporting logic writing to file.
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Escrow balance for issued coins is %s\n",
              TALER_amount2s (total_balance));
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Risk from active operations is %s\n",
              TALER_amount2s (total_risk));
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Deposit fee income is %s\n",
              TALER_amount2s (deposit_fees));
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Melt fee income is %s\n",
              TALER_amount2s (melt_fees));
  GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
              "Refund fee income is %s\n",
              TALER_amount2s (refund_fees));
}


/* ************************* Transaction-global state ************************ */

/**
 * Results about denominations, cached per-transaction.
 */
static struct GNUNET_CONTAINER_MultiHashMap *denominations;


/**
 * Obtain information about a @a denom_pub.
 *
 * @param denom_pub key to look up
 * @param[out] dki set to detailed information about @a denom_pub, NULL if not found, must
 *                 NOT be freed by caller
 * @param[out] dh set to the hash of @a denom_pub, may be NULL
 * @return #GNUNET_OK on success, #GNUNET_NO for not found, #GNUNET_SYSERR for DB error
 */
static int
get_denomination_info (const struct TALER_DenominationPublicKey *denom_pub,
                       const struct TALER_EXCHANGEDB_DenominationKeyInformationP **dki,
                       struct GNUNET_HashCode *dh)
{
  struct GNUNET_HashCode hc;
  struct TALER_EXCHANGEDB_DenominationKeyInformationP *dkip;
  int ret;

  if (NULL == dh)
    dh = &hc;
  GNUNET_CRYPTO_rsa_public_key_hash (denom_pub->rsa_public_key,
                                     dh);
  if (NULL == denominations)
    denominations = GNUNET_CONTAINER_multihashmap_create (256,
                                                          GNUNET_NO);
  dkip = GNUNET_CONTAINER_multihashmap_get (denominations,
                                            dh);
  if (NULL != dkip)
  {
    /* cache hit */
    *dki = dkip;
    return GNUNET_OK;
  }
  dkip = GNUNET_new (struct TALER_EXCHANGEDB_DenominationKeyInformationP);
  ret = edb->get_denomination_info (edb->cls,
                                    esession,
                                    denom_pub,
                                    dkip);
  if (GNUNET_OK != ret)
  {
    GNUNET_free (dkip);
    GNUNET_break (GNUNET_NO == ret);
    *dki = NULL;
    return ret;
  }
  {
    struct TALER_Amount value;

    TALER_amount_ntoh (&value,
                       &dkip->properties.value);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Tracking denomination `%s' (%s)\n",
                GNUNET_h2s (dh),
                TALER_amount2s (&value));
  }
  *dki = dkip;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (denominations,
                                                    dh,
                                                    dkip,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  return GNUNET_OK;
}


/**
 * Free denomination key information.
 *
 * @param cls NULL
 * @param key unused
 * @param value the `struct TALER_EXCHANGEDB_DenominationKeyInformationP *` to free
 * @return #GNUNET_OK (continue to iterate)
 */
static int
free_dk_info (void *cls,
              const struct GNUNET_HashCode *key,
              void *value)
{
  struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki = value;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Done with denomination `%s'\n",
              GNUNET_h2s (key));
  GNUNET_free (dki);
  return GNUNET_OK;
}


/**
 * Purge transaction global state cache, the transaction is
 * done and we do not want to have the state cross over to
 * the next transaction.
 */
static void
clear_transaction_state_cache ()
{
  if (NULL == denominations)
    return;
  GNUNET_CONTAINER_multihashmap_iterate (denominations,
                                         &free_dk_info,
                                         NULL);
  GNUNET_CONTAINER_multihashmap_destroy (denominations);
  denominations = NULL;
}


/* ***************************** Analyze reserves ************************ */
/* This logic checks the reserves_in, reserves_out and reserves-tables */

/**
 * Summary data we keep per reserve.
 */
struct ReserveSummary
{
  /**
   * Public key of the reserve.
   * Always set when the struct is first initialized.
   */
  struct TALER_ReservePublicKeyP reserve_pub;

  /**
   * Sum of all incoming transfers during this transaction.
   * Updated only in #handle_reserve_in().
   */
  struct TALER_Amount total_in;

  /**
   * Sum of all outgoing transfers during this transaction (includes fees).
   * Updated only in #handle_reserve_out().
   */
  struct TALER_Amount total_out;

  /**
   * Sum of withdraw fees encountered during this transaction.
   */
  struct TALER_Amount total_fee;

  /**
   * Previous balance of the reserve as remembered by the auditor.
   * (updated based on @e total_in and @e total_out at the end).
   */
  struct TALER_Amount a_balance;

  /**
   * Previous withdraw fee balance of the reserve, as remembered by the auditor.
   * (updated based on @e total_fee at the end).
   */
  struct TALER_Amount a_withdraw_fee_balance;

  /**
   * Previous reserve expiration data, as remembered by the auditor.
   * (updated on-the-fly in #handle_reserve_in()).
   */
  struct GNUNET_TIME_Absolute a_expiration_date;

  /**
   * Did we have a previous reserve info?  Used to decide between
   * UPDATE and INSERT later.  Initialized in
   * #load_auditor_reserve_summary() together with the a-* values
   * (if available).
   */
  int had_ri;

};


/**
 * Load the auditor's remembered state about the reserve into @a rs.
 * The "total_in" and "total_out" amounts of @a rs must already be
 * initialized (so we can determine the currency).
 *
 * @param[in,out] rs reserve summary to (fully) initialize
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on DB errors
 */
static int
load_auditor_reserve_summary (struct ReserveSummary *rs)
{
  int ret;
  uint64_t rowid;

  ret = adb->get_reserve_info (adb->cls,
                               asession,
                               &rs->reserve_pub,
                               &master_pub,
                               &rowid,
                               &rs->a_balance,
                               &rs->a_withdraw_fee_balance,
                               &rs->a_expiration_date);
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == ret)
  {
    rs->had_ri = GNUNET_NO;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (rs->total_in.currency,
                                          &rs->a_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (rs->total_in.currency,
                                          &rs->a_withdraw_fee_balance));
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Creating fresh reserve `%s' with starting balance %s\n",
                TALER_B2S (&rs->reserve_pub),
                TALER_amount2s (&rs->a_balance));
    return GNUNET_OK;
  }
  rs->had_ri = GNUNET_YES;
  if ( (GNUNET_YES !=
        TALER_amount_cmp_currency (&rs->a_balance,
                                   &rs->a_withdraw_fee_balance)) ||
       (GNUNET_YES !=
        TALER_amount_cmp_currency (&rs->total_in,
                                   &rs->a_balance)) )
  {
    report_row_inconsistency ("auditor-reserve-info",
                              rowid,
                              "currencies for reserve differ");
    /* TODO: find a sane way to continue... */
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Auditor remembers reserve `%s' has balance %s\n",
              TALER_B2S (&rs->reserve_pub),
              TALER_amount2s (&rs->a_balance));
  return GNUNET_OK;
}


/**
 * Closure to the various callbacks we make while checking a reserve.
 */
struct ReserveContext
{
  /**
   * Map from hash of reserve's public key to a `struct ReserveSummary`.
   */
  struct GNUNET_CONTAINER_MultiHashMap *reserves;

  /**
   * Map from hash of denomination's public key to a
   * static string "revoked" for keys that have been revoked,
   * or "master signature invalid" in case the revocation is
   * there but bogus.
   */
  struct GNUNET_CONTAINER_MultiHashMap *revoked;

  /**
   * Total balance in all reserves (updated).
   */
  struct TALER_Amount total_balance;

  /**
   * Total withdraw fees gotten in all reserves (updated).
   */
  struct TALER_Amount total_fee_balance;

};


/**
 * Function called with details about incoming wire transfers.
 *
 * @param cls our `struct ReserveContext`
 * @param rowid unique serial ID for the refresh session in our DB
 * @param reserve_pub public key of the reserve (also the WTID)
 * @param credit amount that was received
 * @param sender_account_details information about the sender's bank account
 * @param transfer_details information that uniquely identifies the wire transfer
 * @param execution_date when did we receive the funds
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
handle_reserve_in (void *cls,
                   uint64_t rowid,
                   const struct TALER_ReservePublicKeyP *reserve_pub,
                   const struct TALER_Amount *credit,
                   const json_t *sender_account_details,
                   const json_t *transfer_details,
                   struct GNUNET_TIME_Absolute execution_date)
{
  struct ReserveContext *rc = cls;
  struct GNUNET_HashCode key;
  struct ReserveSummary *rs;
  struct GNUNET_TIME_Absolute expiry;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= pp.last_reserve_in_serial_id); 
  pp.last_reserve_in_serial_id = rowid + 1;

  GNUNET_CRYPTO_hash (reserve_pub,
                      sizeof (*reserve_pub),
                      &key);
  rs = GNUNET_CONTAINER_multihashmap_get (rc->reserves,
                                          &key);
  if (NULL == rs)
  {
    rs = GNUNET_new (struct ReserveSummary);
    rs->reserve_pub = *reserve_pub;
    rs->total_in = *credit;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (credit->currency,
                                          &rs->total_out));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (credit->currency,
                                          &rs->total_fee));
    if (GNUNET_OK !=
        load_auditor_reserve_summary (rs))
    {
      GNUNET_break (0);
      GNUNET_free (rs);
      return GNUNET_SYSERR;
    }
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (rc->reserves,
                                                      &key,
                                                      rs,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  else
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_add (&rs->total_in,
                                     &rs->total_in,
                                     credit));
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional incoming wire transfer for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (credit));
  expiry = GNUNET_TIME_absolute_add (execution_date,
                                     TALER_IDLE_RESERVE_EXPIRATION_TIME);
  rs->a_expiration_date = GNUNET_TIME_absolute_max (rs->a_expiration_date,
                                                    expiry);
  return GNUNET_OK;
}


/**
 * Function called with details about withdraw operations.  Verifies
 * the signature and updates the reserve's balance.
 *
 * @param cls our `struct ReserveContext`
 * @param rowid unique serial ID for the refresh session in our DB
 * @param h_blind_ev blinded hash of the coin's public key
 * @param denom_pub public denomination key of the deposited coin
 * @param denom_sig signature over the deposited coin
 * @param reserve_pub public key of the reserve
 * @param reserve_sig signature over the withdraw operation
 * @param execution_date when did the wallet withdraw the coin
 * @param amount_with_fee amount that was withdrawn
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
handle_reserve_out (void *cls,
                    uint64_t rowid,
                    const struct GNUNET_HashCode *h_blind_ev,
                    const struct TALER_DenominationPublicKey *denom_pub,
                    const struct TALER_DenominationSignature *denom_sig,
                    const struct TALER_ReservePublicKeyP *reserve_pub,
                    const struct TALER_ReserveSignatureP *reserve_sig,
                    struct GNUNET_TIME_Absolute execution_date,
                    const struct TALER_Amount *amount_with_fee)
{
  struct ReserveContext *rc = cls;
  struct TALER_WithdrawRequestPS wsrd;
  struct GNUNET_HashCode key;
  struct ReserveSummary *rs;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct TALER_Amount withdraw_fee;
  struct GNUNET_TIME_Absolute valid_start;
  struct GNUNET_TIME_Absolute expire_withdraw;
  int ret;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= pp.last_reserve_out_serial_id);
  pp.last_reserve_out_serial_id = rowid + 1;

  /* lookup denomination pub data (make sure denom_pub is valid, establish fees) */
  ret = get_denomination_info (denom_pub,
                               &dki,
                               &wsrd.h_denomination_pub);
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == ret)
  {
    report_row_inconsistency ("withdraw",
                              rowid,
                              "denomination key not found (foreign key constraint violated)");
    return GNUNET_OK;
  }

  /* check that execution date is within withdraw range for denom_pub  */
  valid_start = GNUNET_TIME_absolute_ntoh (dki->properties.start);
  expire_withdraw = GNUNET_TIME_absolute_ntoh (dki->properties.expire_withdraw);
  if ( (valid_start.abs_value_us > execution_date.abs_value_us) ||
       (expire_withdraw.abs_value_us < execution_date.abs_value_us) )
  {
    report_row_minor_inconsistency ("withdraw",
                                    rowid,
                                    "denomination key not valid at time of withdrawal");
  }

  /* check reserve_sig */
  wsrd.purpose.purpose = htonl (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW);
  wsrd.purpose.size = htonl (sizeof (wsrd));
  wsrd.reserve_pub = *reserve_pub;
  TALER_amount_hton (&wsrd.amount_with_fee,
                     amount_with_fee);
  wsrd.withdraw_fee = dki->properties.fee_withdraw;
  wsrd.h_coin_envelope = *h_blind_ev;
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_RESERVE_WITHDRAW,
                                  &wsrd.purpose,
                                  &reserve_sig->eddsa_signature,
                                  &reserve_pub->eddsa_pub))
  {
    report_row_inconsistency ("withdraw",
                              rowid,
                              "invalid signature for withdrawal");
    return GNUNET_OK;
  }

  GNUNET_CRYPTO_hash (reserve_pub,
                      sizeof (*reserve_pub),
                      &key);
  rs = GNUNET_CONTAINER_multihashmap_get (rc->reserves,
                                          &key);
  if (NULL == rs)
  {
    rs = GNUNET_new (struct ReserveSummary);
    rs->reserve_pub = *reserve_pub;
    rs->total_out = *amount_with_fee;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount_with_fee->currency,
                                          &rs->total_in));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount_with_fee->currency,
                                          &rs->total_fee));
    if (GNUNET_OK !=
        load_auditor_reserve_summary (rs))
    {
      GNUNET_break (0);
      GNUNET_free (rs);
      return GNUNET_SYSERR;
    }
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (rc->reserves,
                                                      &key,
                                                      rs,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  else
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_add (&rs->total_out,
                                     &rs->total_out,
                                     amount_with_fee));
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Reserve `%s' reduced by %s from withdraw\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (amount_with_fee));
  TALER_amount_ntoh (&withdraw_fee,
                     &dki->properties.fee_withdraw);
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_add (&rs->total_fee,
                                   &rs->total_fee,
                                   &withdraw_fee));

  return GNUNET_OK;
}


/**
 * Function called with details about withdraw operations.  Verifies
 * the signature and updates the reserve's balance.
 *
 * @param cls our `struct ReserveContext`
 * @param rowid unique serial ID for the refresh session in our DB
 * @param timestamp when did we receive the payback request
 * @param amount how much should be added back to the reserve
 * @param reserve_pub public key of the reserve
 * @param coin public information about the coin
 * @param coin_sig signature with @e coin_pub of type #TALER_SIGNATURE_WALLET_COIN_PAYBACK
 * @param coin_blind blinding factor used to blind the coin
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
handle_payback_by_reserve (void *cls,
                           uint64_t rowid,
                           struct GNUNET_TIME_Absolute timestamp,
                           const struct TALER_Amount *amount,
                           const struct TALER_ReservePublicKeyP *reserve_pub,
                           const struct TALER_CoinPublicInfo *coin,
                           const struct TALER_CoinSpendSignatureP *coin_sig,
                           const struct TALER_DenominationBlindingKeyP *coin_blind)
{
  struct ReserveContext *rc = cls;
  struct GNUNET_HashCode key;
  struct ReserveSummary *rs;
  struct GNUNET_TIME_Absolute expiry;
  struct TALER_PaybackRequestPS pr;
  struct TALER_MasterSignatureP msig;
  uint64_t rev_rowid;
  int ret;
  const char *rev;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= pp.last_reserve_payback_serial_id);
  pp.last_reserve_payback_serial_id = rowid + 1;

  if (GNUNET_OK !=
      TALER_test_coin_valid (coin))
  {
    report_row_inconsistency ("payback",
                              rowid,
                              "coin denomination signature invalid");
  }
  pr.purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_PAYBACK);
  pr.purpose.size = htonl (sizeof (pr));
  pr.coin_pub = coin->coin_pub;
  GNUNET_CRYPTO_rsa_public_key_hash (coin->denom_pub.rsa_public_key,
                                     &pr.h_denom_pub);
  pr.coin_blind = *coin_blind;
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_COIN_PAYBACK,
                                  &pr.purpose,
                                  &coin_sig->eddsa_signature,
                                  &coin->coin_pub.eddsa_pub))
  {
    report_row_inconsistency ("payback",
                              rowid,
                              "coin payback signature invalid");
  }

  /* check that the coin was eligible for payback!*/
  rev = GNUNET_CONTAINER_multihashmap_get (rc->revoked,
					   &pr.h_denom_pub);
  if (NULL == rev)
  {
    ret = edb->get_denomination_revocation (edb->cls,
					    esession,
					    &pr.h_denom_pub,
					    &msig,
					    &rev_rowid);
    if (GNUNET_SYSERR == ret)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
    if (GNUNET_NO == ret)
    {
      report_row_inconsistency ("payback",
				rowid,
				"denomination key not in revocation set");      
    }
    else
    {
      /* verify msig */
      struct TALER_MasterDenominationKeyRevocation kr;
      
      kr.purpose.purpose = htonl (TALER_SIGNATURE_MASTER_DENOMINATION_KEY_REVOKED);
      kr.purpose.size = htonl (sizeof (kr));
      kr.h_denom_pub = pr.h_denom_pub;
      if (GNUNET_OK !=
	  GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_MASTER_DENOMINATION_KEY_REVOKED,
				      &kr.purpose,
				      &msig.eddsa_signature,
				      &master_pub.eddsa_pub))
      {
	report_row_inconsistency ("denomination_revocations",
				  rev_rowid,
				  "master signature invalid");
	rev = "master signature invalid";
      }
      else
      {
	rev = "revoked";
      }
      GNUNET_assert (GNUNET_OK ==
		     GNUNET_CONTAINER_multihashmap_put (rc->revoked,
							&pr.h_denom_pub,
							(void *) rev,
							GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
    }
  }

  GNUNET_CRYPTO_hash (reserve_pub,
                      sizeof (*reserve_pub),
                      &key);
  rs = GNUNET_CONTAINER_multihashmap_get (rc->reserves,
                                          &key);
  if (NULL == rs)
  {
    rs = GNUNET_new (struct ReserveSummary);
    rs->reserve_pub = *reserve_pub;
    rs->total_in = *amount;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount->currency,
                                          &rs->total_out));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount->currency,
                                          &rs->total_fee));
    if (GNUNET_OK !=
        load_auditor_reserve_summary (rs))
    {
      GNUNET_break (0);
      GNUNET_free (rs);
      return GNUNET_SYSERR;
    }
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (rc->reserves,
                                                      &key,
                                                      rs,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  else
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_add (&rs->total_in,
                                     &rs->total_in,
                                     amount));
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional /payback value to for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (amount));
  expiry = GNUNET_TIME_absolute_add (timestamp,
                                     TALER_IDLE_RESERVE_EXPIRATION_TIME);
  rs->a_expiration_date = GNUNET_TIME_absolute_max (rs->a_expiration_date,
                                                    expiry);
  return GNUNET_OK;
}


/**
 * Function called about reserve closing operations
 * the aggregator triggered.
 *
 * @param cls closure
 * @param rowid row identifier used to uniquely identify the reserve closing operation
 * @param execution_date when did we execute the close operation
 * @param amount_with_fee how much did we debit the reserve
 * @param closing_fee how much did we charge for closing the reserve
 * @param reserve_pub public key of the reserve
 * @param receiver_account where did we send the funds
 * @param transfer_details details about the wire transfer
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
handle_reserve_closed (void *cls,
		       uint64_t rowid,
		       struct GNUNET_TIME_Absolute execution_date,
		       const struct TALER_Amount *amount_with_fee,
		       const struct TALER_Amount *closing_fee,
		       const struct TALER_ReservePublicKeyP *reserve_pub,
		       const json_t *receiver_account,
		       const json_t *transfer_details)
{
  struct ReserveContext *rc = cls;
  struct GNUNET_HashCode key;
  struct ReserveSummary *rs;
  
  /* should be monotonically increasing */
  GNUNET_assert (rowid >= pp.last_reserve_close_serial_id);
  pp.last_reserve_close_serial_id = rowid + 1;

  GNUNET_CRYPTO_hash (reserve_pub,
                      sizeof (*reserve_pub),
                      &key);
  rs = GNUNET_CONTAINER_multihashmap_get (rc->reserves,
                                          &key);
  if (NULL == rs)
  {
    rs = GNUNET_new (struct ReserveSummary);
    rs->reserve_pub = *reserve_pub;
    rs->total_out = *amount_with_fee;
    rs->total_fee = *closing_fee;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount_with_fee->currency,
                                          &rs->total_in));
    if (GNUNET_OK !=
        load_auditor_reserve_summary (rs))
    {
      GNUNET_break (0);
      GNUNET_free (rs);
      return GNUNET_SYSERR;
    }
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (rc->reserves,
                                                      &key,
                                                      rs,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  else
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_add (&rs->total_out,
                                     &rs->total_out,
                                     amount_with_fee));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_add (&rs->total_fee,
                                     &rs->total_fee,
                                     closing_fee));
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional closing operation for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (amount_with_fee));
  return GNUNET_OK;
}


/**
 * Check that the reserve summary matches what the exchange database
 * thinks about the reserve, and update our own state of the reserve.
 *
 * Remove all reserves that we are happy with from the DB.
 *
 * @param cls our `struct ReserveContext`
 * @param key hash of the reserve public key
 * @param value a `struct ReserveSummary`
 * @return #GNUNET_OK to process more entries
 */
static int
verify_reserve_balance (void *cls,
                        const struct GNUNET_HashCode *key,
                        void *value)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs = value;
  struct TALER_EXCHANGEDB_Reserve reserve;
  struct TALER_Amount balance;
  int ret;

  ret = GNUNET_OK;
  reserve.pub = rs->reserve_pub;
  if (GNUNET_OK !=
      edb->reserve_get (edb->cls,
                        esession,
                        &reserve))
  {
    char *diag;

    GNUNET_asprintf (&diag,
                     "Failed to find summary for reserve `%s'\n",
                     TALER_B2S (&rs->reserve_pub));
    report_row_inconsistency ("reserve-summary",
                              UINT64_MAX,
                              diag);
    GNUNET_free (diag);
    return GNUNET_OK;
  }

  if (GNUNET_OK !=
      TALER_amount_add (&balance,
                        &rs->total_in,
                        &rs->a_balance))
  {
    report_reserve_inconsistency (&rs->reserve_pub,
                                  &rs->total_in,
                                  &rs->a_balance,
                                  "could not add old balance to new balance");
    goto cleanup;
  }

  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&balance,
                             &balance,
                             &rs->total_out))
  {
    report_reserve_inconsistency (&rs->reserve_pub,
                                  &rs->total_in,
                                  &rs->total_out,
                                  "available balance insufficient to cover transfers");
    goto cleanup;
  }
  if (0 != TALER_amount_cmp (&balance,
                             &reserve.balance))
  {
    report_reserve_inconsistency (&rs->reserve_pub,
                                  &balance,
                                  &reserve.balance,
                                  "computed balance does not match stored balance");
    goto cleanup;
  }

  /* Check that reserve is being closed if it is past its expiration date */
  if ( (CLOSING_GRACE_PERIOD.rel_value_us >
	GNUNET_TIME_absolute_get_duration (rs->a_expiration_date).rel_value_us) &&
       ( (0 != balance.value) ||
	 (0 != balance.fraction) ) )
  {
    struct TALER_Amount zero;

    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (balance.currency,
                                          &zero));

    report_reserve_inconsistency (&rs->reserve_pub,
                                  &balance,
                                  &zero,
                                  "expired reserve needs to be closed");
  }

  /* Add withdraw fees we encountered to totals */
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Reserve reserve `%s' made %s in withdraw fees\n",
              TALER_B2S (&rs->reserve_pub),
              TALER_amount2s (&rs->total_fee));
  if (GNUNET_YES !=
      TALER_amount_add (&rs->a_withdraw_fee_balance,
                        &rs->a_withdraw_fee_balance,
                        &rs->total_fee))
  {
    GNUNET_break (0);
    ret = GNUNET_SYSERR;
    goto cleanup;
  }
  if ( (GNUNET_YES !=
        TALER_amount_add (&rc->total_balance,
                          &rc->total_balance,
                          &rs->total_in)) ||
       (GNUNET_SYSERR ==
        TALER_amount_subtract (&rc->total_balance,
                               &rc->total_balance,
                               &rs->total_out)) ||
       (GNUNET_YES !=
        TALER_amount_add (&rc->total_fee_balance,
                          &rc->total_fee_balance,
                          &rs->total_fee)) )
  {
    GNUNET_break (0);
    ret = GNUNET_SYSERR;
    goto cleanup;
  }

  if ( (0ULL == balance.value) &&
       (0U == balance.fraction) )
  {
    /* TODO: balance is zero, drop reserve details (and then do not update/insert) */
    if (rs->had_ri)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Final balance of reserve `%s' is %s, dropping it\n",
                  TALER_B2S (&rs->reserve_pub),
                  TALER_amount2s (&balance));
      ret = adb->del_reserve_info (adb->cls,
                                   asession,
                                   &rs->reserve_pub,
                                   &master_pub);
      if (GNUNET_SYSERR == ret)
      {
        GNUNET_break (0);
        goto cleanup;
      }
      if (GNUNET_NO == ret)
      {
        GNUNET_break (0);
        ret = GNUNET_SYSERR;
        goto cleanup;
      }
    }
    else
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Final balance of reserve `%s' is %s, no need to remember it\n",
                  TALER_B2S (&rs->reserve_pub),
                  TALER_amount2s (&balance));
    }
    ret = GNUNET_OK;
    goto cleanup;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Remembering final balance of reserve `%s' as %s\n",
              TALER_B2S (&rs->reserve_pub),
              TALER_amount2s (&balance));

  if (rs->had_ri)
    ret = adb->update_reserve_info (adb->cls,
                                    asession,
                                    &rs->reserve_pub,
                                    &master_pub,
                                    &balance,
                                    &rs->a_withdraw_fee_balance,
                                    rs->a_expiration_date);
  else
    ret = adb->insert_reserve_info (adb->cls,
                                    asession,
                                    &rs->reserve_pub,
                                    &master_pub,
                                    &balance,
                                    &rs->a_withdraw_fee_balance,
                                    rs->a_expiration_date);

 cleanup:
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (rc->reserves,
                                                       key,
                                                       rs));
  GNUNET_free (rs);
  return ret;
}


/**
 * Analyze reserves for being well-formed.
 *
 * @param cls NULL
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on invariant violation
 */
static int
analyze_reserves (void *cls)
{
  struct ReserveContext rc;
  int ret;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Analyzing reserves\n");
  ret = adb->get_reserve_summary (adb->cls,
                                  asession,
                                  &master_pub,
                                  &rc.total_balance,
                                  &rc.total_fee_balance);
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == ret)
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &rc.total_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &rc.total_fee_balance));
  }

  rc.reserves = GNUNET_CONTAINER_multihashmap_create (512,
                                                      GNUNET_NO);
  rc.revoked = GNUNET_CONTAINER_multihashmap_create (4,
						     GNUNET_NO);

  if (GNUNET_SYSERR ==
      edb->select_reserves_in_above_serial_id (edb->cls,
                                               esession,
                                               pp.last_reserve_in_serial_id,
                                               &handle_reserve_in,
                                               &rc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_SYSERR ==
      edb->select_reserves_out_above_serial_id (edb->cls,
                                                esession,
                                                pp.last_reserve_out_serial_id,
                                                &handle_reserve_out,
                                                &rc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_SYSERR ==
      edb->select_payback_above_serial_id (edb->cls,
                                           esession,
                                           pp.last_reserve_payback_serial_id,
                                           &handle_payback_by_reserve,
                                           &rc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_SYSERR ==
      edb->select_reserve_closed_above_serial_id (edb->cls,
						  esession,
						  pp.last_reserve_close_serial_id,
						  &handle_reserve_closed,
						  &rc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  GNUNET_CONTAINER_multihashmap_iterate (rc.reserves,
                                         &verify_reserve_balance,
                                         &rc);
  GNUNET_break (0 ==
                GNUNET_CONTAINER_multihashmap_size (rc.reserves));
  GNUNET_CONTAINER_multihashmap_destroy (rc.reserves);
  GNUNET_CONTAINER_multihashmap_destroy (rc.revoked);


  if (GNUNET_NO == ret)
  {
    ret = adb->insert_reserve_summary (adb->cls,
                                       asession,
                                       &master_pub,
                                       &rc.total_balance,
                                       &rc.total_fee_balance);
  }
  else
  {
    ret = adb->update_reserve_summary (adb->cls,
                                       asession,
                                       &master_pub,
                                       &rc.total_balance,
                                       &rc.total_fee_balance);
  }
  if (GNUNET_OK != ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  report_reserve_balance (&rc.total_balance,
                          &rc.total_fee_balance);
  return GNUNET_OK;
}


/* *********************** Analyze aggregations ******************** */
/* This logic checks that the aggregator did the right thing
   paying each merchant what they were due (and on time). */


/**
 * Information we keep per loaded wire plugin.
 */
struct WirePlugin
{

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

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

  /**
   * Name of the wire method.
   */
  char *type;

  /**
   * Handle to the wire plugin.
   */
  struct TALER_WIRE_Plugin *plugin;

};


/**
 * Information about wire fees charged by the exchange.
 */
struct WireFeeInfo
{

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

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

  /**
   * When does the fee go into effect (inclusive).
   */
  struct GNUNET_TIME_Absolute start_date;

  /**
   * When does the fee stop being in effect (exclusive).
   */
  struct GNUNET_TIME_Absolute end_date;

  /**
   * How high is the fee.
   */
  struct TALER_Amount wire_fee;

};


/**
 * Closure for callbacks during #analyze_merchants().
 */
struct AggregationContext
{

  /**
   * DLL of wire plugins encountered.
   */
  struct WirePlugin *wire_head;

  /**
   * DLL of wire plugins encountered.
   */
  struct WirePlugin *wire_tail;

  /**
   * DLL of wire fees charged by the exchange.
   */
  struct WireFeeInfo *fee_head;

  /**
   * DLL of wire fees charged by the exchange.
   */
  struct WireFeeInfo *fee_tail;

  /**
   * How much did we make in aggregation fees.
   */
  struct TALER_Amount total_aggregation_fees;

  /**
   * Final result status.
   */
  int ret;
};


/**
 * Find the relevant wire plugin.
 *
 * @param ac context to search
 * @param type type of the wire plugin to load
 * @return NULL on error
 */
static struct TALER_WIRE_Plugin *
get_wire_plugin (struct AggregationContext *ac,
                 const char *type)
{
  struct WirePlugin *wp;
  struct TALER_WIRE_Plugin *plugin;

  for (wp = ac->wire_head; NULL != wp; wp = wp->next)
    if (0 == strcmp (type,
                     wp->type))
      return wp->plugin;
  plugin = TALER_WIRE_plugin_load (cfg,
                                   type);
  if (NULL == plugin)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to locate wire plugin for `%s'\n",
                type);
    return NULL;
  }
  wp = GNUNET_new (struct WirePlugin);
  wp->type = GNUNET_strdup (type);
  wp->plugin = plugin;
  GNUNET_CONTAINER_DLL_insert (ac->wire_head,
                               ac->wire_tail,
                               wp);
  return plugin;
}


/**
 * Closure for #wire_transfer_information_cb.
 */
struct WireCheckContext
{

  /**
   * Corresponding merchant context.
   */
  struct AggregationContext *ac;

  /**
   * Total deposits claimed by all transactions that were aggregated
   * under the given @e wtid.
   */
  struct TALER_Amount total_deposits;

  /**
   * Hash of the wire transfer details of the receiver.
   */
  struct GNUNET_HashCode h_wire;

  /**
   * Execution time of the wire transfer.
   */
  struct GNUNET_TIME_Absolute date;

  /**
   * Wire method used for the transfer.
   */
  const char *method;

  /**
   * Set to #GNUNET_SYSERR if there are inconsistencies.
   */
  int ok;

};


/**
 * Check coin's transaction history for plausibility.  Does NOT check
 * the signatures (those are checked independently), but does calculate
 * the amounts for the aggregation table and checks that the total
 * claimed coin value is within the value of the coin's denomination.
 *
 * @param coin_pub public key of the coin (for reporting)
 * @param h_proposal_data hash of the proposal for which we calculate the amount
 * @param merchant_pub public key of the merchant (who is allowed to issue refunds)
 * @param dki denomination information about the coin
 * @param tl_head head of transaction history to verify
 * @param[out] merchant_gain amount the coin contributes to the wire transfer to the merchant
 * @param[out] merchant_fees fees the exchange charged the merchant for the transaction(s)
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static int
check_transaction_history (const struct TALER_CoinSpendPublicKeyP *coin_pub,
                           const struct GNUNET_HashCode *h_proposal_data,
                           const struct TALER_MerchantPublicKeyP *merchant_pub,
                           const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki,
                           const struct TALER_EXCHANGEDB_TransactionList *tl_head,
                           struct TALER_Amount *merchant_gain,
                           struct TALER_Amount *merchant_fees)
{
  struct TALER_Amount expenditures;
  struct TALER_Amount refunds;
  struct TALER_Amount spent;
  struct TALER_Amount value;
  struct TALER_Amount merchant_loss;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Checking transaction history of coin %s\n",
              TALER_B2S (coin_pub));

  GNUNET_assert (NULL != tl_head);
  TALER_amount_get_zero (currency,
                         &expenditures);
  TALER_amount_get_zero (currency,
                         &refunds);
  TALER_amount_get_zero (currency,
                         merchant_gain);
  TALER_amount_get_zero (currency,
                         merchant_fees);
  TALER_amount_get_zero (currency,
                         &merchant_loss);
  /* Go over transaction history to compute totals; note that we do not
     know the order, so instead of subtracting we compute positive
     (deposit, melt) and negative (refund) values separately here,
     and then subtract the negative from the positive after the loop. */
  for (const struct TALER_EXCHANGEDB_TransactionList *tl = tl_head;NULL != tl;tl = tl->next)
  {
    const struct TALER_Amount *amount_with_fee;
    const struct TALER_Amount *fee;
    const struct TALER_AmountNBO *fee_dki;
    struct TALER_Amount tmp;

    switch (tl->type) {
    case TALER_EXCHANGEDB_TT_DEPOSIT:
      amount_with_fee = &tl->details.deposit->amount_with_fee;
      fee = &tl->details.deposit->deposit_fee;
      fee_dki = &dki->properties.fee_deposit;
      if (GNUNET_OK !=
          TALER_amount_add (&expenditures,
                            &expenditures,
                            amount_with_fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      /* Check if this deposit is within the remit of the aggregation
         we are investigating, if so, include it in the totals. */
      if ( (0 == memcmp (merchant_pub,
                         &tl->details.deposit->merchant_pub,
                         sizeof (struct TALER_MerchantPublicKeyP))) &&
           (0 == memcmp (h_proposal_data,
                         &tl->details.deposit->h_proposal_data,
                         sizeof (struct GNUNET_HashCode))) )
      {
        struct TALER_Amount amount_without_fee;

        if (GNUNET_OK !=
            TALER_amount_subtract (&amount_without_fee,
                                   amount_with_fee,
                                   fee))
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
        if (GNUNET_OK !=
            TALER_amount_add (merchant_gain,
                              merchant_gain,
                              &amount_without_fee))
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                    "Detected applicable deposit of %s\n",
                    TALER_amount2s (&amount_without_fee));
        if (GNUNET_OK !=
            TALER_amount_add (merchant_fees,
                              merchant_fees,
                              fee))
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
      }
      /* Check that the fees given in the transaction list and in dki match */
      TALER_amount_ntoh (&tmp,
			 fee_dki);
      if (0 !=
	  TALER_amount_cmp (&tmp,
			    fee))
      {
	/* Disagreement in fee structure within DB, should be impossible! */
	GNUNET_break (0);
	return GNUNET_SYSERR;
      }
      break;
    case TALER_EXCHANGEDB_TT_REFRESH_MELT:
      amount_with_fee = &tl->details.melt->amount_with_fee;
      fee = &tl->details.melt->melt_fee;
      fee_dki = &dki->properties.fee_refresh;
      if (GNUNET_OK !=
          TALER_amount_add (&expenditures,
                            &expenditures,
                            amount_with_fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      /* Check that the fees given in the transaction list and in dki match */
      TALER_amount_ntoh (&tmp,
			 fee_dki);
      if (0 !=
	  TALER_amount_cmp (&tmp,
			    fee))
      {
	/* Disagreement in fee structure within DB, should be impossible! */
	GNUNET_break (0);
	return GNUNET_SYSERR;
      }
      break;
    case TALER_EXCHANGEDB_TT_REFUND:
      amount_with_fee = &tl->details.refund->refund_amount;
      fee = &tl->details.refund->refund_fee;
      fee_dki = &dki->properties.fee_refund;
      if (GNUNET_OK !=
          TALER_amount_add (&refunds,
                            &refunds,
                            amount_with_fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      if (GNUNET_OK !=
          TALER_amount_add (&expenditures,
                            &expenditures,
                            fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      /* Check if this refund is within the remit of the aggregation
         we are investigating, if so, include it in the totals. */
      if ( (0 == memcmp (merchant_pub,
                         &tl->details.refund->merchant_pub,
                         sizeof (struct TALER_MerchantPublicKeyP))) &&
           (0 == memcmp (h_proposal_data,
                         &tl->details.refund->h_proposal_data,
                         sizeof (struct GNUNET_HashCode))) )
      {
        if (GNUNET_OK !=
            TALER_amount_add (&merchant_loss,
                              &merchant_loss,
                              amount_with_fee))
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                    "Detected applicable refund of %s\n",
                    TALER_amount2s (amount_with_fee));
        if (GNUNET_OK !=
            TALER_amount_add (merchant_fees,
                              merchant_fees,
                              fee))
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
      }
      /* Check that the fees given in the transaction list and in dki match */
      TALER_amount_ntoh (&tmp,
			 fee_dki);
      if (0 !=
	  TALER_amount_cmp (&tmp,
			    fee))
      {
	/* Disagreement in fee structure within DB, should be impossible! */
	GNUNET_break (0);
	return GNUNET_SYSERR;
      }
      break;
    case TALER_EXCHANGEDB_TT_PAYBACK:
      amount_with_fee = &tl->details.payback->value;
      if (GNUNET_OK !=
          TALER_amount_add (&expenditures,
                            &expenditures,
                            amount_with_fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      break;
    }

  } /* for 'tl' */

  /* Calculate total balance change, i.e. expenditures minus refunds */
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&spent,
                             &expenditures,
                             &refunds))
  {
    /* refunds above expenditures? Bad! */
    report_coin_inconsistency (coin_pub,
                               &expenditures,
                               &refunds,
                               "could not subtract refunded amount from expenditures");
    return GNUNET_SYSERR;
  }

  /* Now check that 'spent' is less or equal than total coin value */
  TALER_amount_ntoh (&value,
                     &dki->properties.value);
  if (1 == TALER_amount_cmp (&spent,
                             &value))
  {
    /* spent > value */
    report_coin_inconsistency (coin_pub,
                               &spent,
                               &value,
                               "accepted deposits (minus refunds) exceeds denomination value");
    return GNUNET_SYSERR;
  }

  /* Finally, update @a merchant_gain by subtracting what he "lost" from refunds */
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (merchant_gain,
                             merchant_gain,
                             &merchant_loss))
  {
    /* refunds above deposits? Bad! */
    report_coin_inconsistency (coin_pub,
                               merchant_gain,
                               &merchant_loss,
                               "merchant was granted more refunds than he deposited");
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Coin %s contributes %s to contract %s\n",
              TALER_B2S (coin_pub),
              TALER_amount2s (merchant_gain),
              GNUNET_h2s (h_proposal_data));
  return GNUNET_OK;
}


/**
 * Function called with the results of the lookup of the
 * transaction data associated with a wire transfer identifier.
 *
 * @param cls a `struct WireCheckContext`
 * @param rowid which row in the table is the information from (for diagnostics)
 * @param merchant_pub public key of the merchant (should be same for all callbacks with the same @e cls)
 * @param wire_method which wire plugin was used for the transfer?
 * @param h_wire hash of wire transfer details of the merchant (should be same for all callbacks with the same @e cls)
 * @param exec_time execution time of the wire transfer (should be same for all callbacks with the same @e cls)
 * @param h_proposal_data which proposal was this payment about
 * @param coin_pub which public key was this payment about
 * @param coin_value amount contributed by this coin in total (with fee)
 * @param coin_fee applicable fee for this coin
 */
static void
wire_transfer_information_cb (void *cls,
                              uint64_t rowid,
                              const struct TALER_MerchantPublicKeyP *merchant_pub,
                              const char *wire_method,
                              const struct GNUNET_HashCode *h_wire,
                              struct GNUNET_TIME_Absolute exec_time,
                              const struct GNUNET_HashCode *h_proposal_data,
                              const struct TALER_CoinSpendPublicKeyP *coin_pub,
                              const struct TALER_Amount *coin_value,
                              const struct TALER_Amount *coin_fee)
{
  struct WireCheckContext *wcc = cls;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct TALER_Amount contribution;
  struct TALER_Amount computed_value;
  struct TALER_Amount computed_fees;
  struct TALER_Amount coin_value_without_fee;
  struct TALER_EXCHANGEDB_TransactionList *tl;
  const struct TALER_CoinPublicInfo *coin;

  /* Obtain coin's transaction history */
  tl = edb->get_coin_transactions (edb->cls,
                                   esession,
                                   coin_pub);
  if (NULL == tl)
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "no transaction history for coin claimed in aggregation");
    return;
  }

  /* Obtain general denomination information about the coin */
  coin = NULL;
  switch (tl->type)
  {
  case TALER_EXCHANGEDB_TT_DEPOSIT:
    coin = &tl->details.deposit->coin;
    break;
  case TALER_EXCHANGEDB_TT_REFRESH_MELT:
    coin = &tl->details.melt->coin;
    break;
  case TALER_EXCHANGEDB_TT_REFUND:
    coin = &tl->details.refund->coin;
    break;
  case TALER_EXCHANGEDB_TT_PAYBACK:
    coin = &tl->details.payback->coin;
    break;
  }
  GNUNET_assert (NULL != coin); /* hard check that switch worked */
  if (GNUNET_OK !=
      get_denomination_info (&coin->denom_pub,
                             &dki,
                             NULL))
  {
    /* This should be impossible from database constraints */
    GNUNET_break (0);
    edb->free_coin_transaction_list (edb->cls,
                                     tl);
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "could not find denomination key for coin claimed in aggregation");
    return;
  }

  /* Check transaction history to see if it supports aggregate valuation */
  check_transaction_history (coin_pub,
                             h_proposal_data,
                             merchant_pub,
                             dki,
                             tl,
                             &computed_value,
                             &computed_fees);
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&coin_value_without_fee,
                             coin_value,
                             coin_fee))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "inconsistent coin value and fee claimed in aggregation");
    return;
  }
  if (0 !=
      TALER_amount_cmp (&computed_value,
                        &coin_value_without_fee))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "coin transaction history and aggregation disagree about coin's contribution");
  }
  if (0 !=
      TALER_amount_cmp (&computed_fees,
                        coin_fee))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "coin transaction history and aggregation disagree about applicable fees");
  }
  edb->free_coin_transaction_list (edb->cls,
                                   tl);

  /* Check other details of wire transfer match */
  if (0 != strcmp (wire_method,
                   wcc->method))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "wire method of aggregate do not match wire transfer");
  }
  if (0 != memcmp (h_wire,
                   &wcc->h_wire,
                   sizeof (struct GNUNET_HashCode)))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "account details of aggregate do not match account details of wire transfer");
    return;
  }
  if (exec_time.abs_value_us != wcc->date.abs_value_us)
  {
    /* This should be impossible from database constraints */
    GNUNET_break (0);
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "date given in aggregate does not match wire transfer date");
    return;
  }
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&contribution,
                             coin_value,
                             coin_fee))
  {
    wcc->ok = GNUNET_SYSERR;
    report_row_inconsistency ("aggregation",
                              rowid,
                              "could not calculate contribution of coin");
    return;
  }

  /* Add coin's contribution to total aggregate value */
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_add (&wcc->total_deposits,
                                   &wcc->total_deposits,
                                   &contribution));
}


/**
 * Lookup the wire fee that the exchange charges at @a timestamp.
 *
 * @param ac context for caching the result
 * @param type type of the wire plugin
 * @param timestamp time for which we need the fee
 * @return NULL on error (fee unknown)
 */
static const struct TALER_Amount *
get_wire_fee (struct AggregationContext *ac,
              const char *type,
              struct GNUNET_TIME_Absolute timestamp)
{
  struct WireFeeInfo *wfi;
  struct WireFeeInfo *pos;
  struct TALER_MasterSignatureP master_sig;

  /* Check if fee is already loaded in cache */
  for (pos = ac->fee_head; NULL != pos; pos = pos->next)
  {
    if ( (pos->start_date.abs_value_us <= timestamp.abs_value_us) &&
         (pos->end_date.abs_value_us > timestamp.abs_value_us) )
      return &pos->wire_fee;
    if (pos->start_date.abs_value_us > timestamp.abs_value_us)
      break;
  }

  /* Lookup fee in exchange database */
  wfi = GNUNET_new (struct WireFeeInfo);
  if (GNUNET_OK !=
      edb->get_wire_fee (edb->cls,
                         esession,
                         type,
                         timestamp,
                         &wfi->start_date,
                         &wfi->end_date,
                         &wfi->wire_fee,
                         &master_sig))
  {
    GNUNET_break (0);
    GNUNET_free (wfi);
    return NULL;
  }

  /* Check signature (not terribly meaningful as the exchange can
     easily make this one up, but it means that we have proof that
     the master key was used for inconsistent wire fees if a
     merchant complains. */
  {
    struct TALER_MasterWireFeePS wp;

    wp.purpose.purpose = htonl (TALER_SIGNATURE_MASTER_WIRE_FEES);
    wp.purpose.size = htonl (sizeof (wp));
    GNUNET_CRYPTO_hash (type,
                        strlen (type) + 1,
                        &wp.h_wire_method);
    wp.start_date = GNUNET_TIME_absolute_hton (wfi->start_date);
    wp.end_date = GNUNET_TIME_absolute_hton (wfi->end_date);
    TALER_amount_hton (&wp.wire_fee,
                       &wfi->wire_fee);
    if (GNUNET_OK !=
        GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_MASTER_WIRE_FEES,
                                    &wp.purpose,
                                    &master_sig.eddsa_signature,
                                    &master_pub.eddsa_pub))
    {
      GNUNET_break (0);
      GNUNET_free (wfi);
      return NULL;
    }
  }

  /* Established fee, keep in sorted list */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Wire fee is %s starting at %s\n",
              TALER_amount2s (&wfi->wire_fee),
              GNUNET_STRINGS_absolute_time_to_string (wfi->start_date));
  if ( (NULL == pos) ||
       (NULL == pos->prev) )
    GNUNET_CONTAINER_DLL_insert (ac->fee_head,
                                 ac->fee_tail,
                                 wfi);
  else
    GNUNET_CONTAINER_DLL_insert_after (ac->fee_head,
                                       ac->fee_tail,
                                       pos->prev,
                                       wfi);
  /* Check non-overlaping fee invariant */
  /* TODO: maybe report problems more nicely? */
  if (NULL != wfi->prev)
    GNUNET_break (wfi->prev->end_date.abs_value_us <= wfi->start_date.abs_value_us);
  if (NULL != wfi->next)
    GNUNET_break (wfi->next->start_date.abs_value_us >= wfi->end_date.abs_value_us);
  return &wfi->wire_fee;
}


/**
 * Check that a wire transfer made by the exchange is valid
 * (has matching deposits).
 *
 * @param cls a `struct AggregationContext`
 * @param rowid identifier of the respective row in the database
 * @param date timestamp of the wire transfer (roughly)
 * @param wtid wire transfer subject
 * @param wire wire transfer details of the receiver
 * @param amount amount that was wired
 * @return #GNUNET_OK to continue, #GNUNET_SYSERR to stop iteration
 */
static int
check_wire_out_cb (void *cls,
                   uint64_t rowid,
                   struct GNUNET_TIME_Absolute date,
                   const struct TALER_WireTransferIdentifierRawP *wtid,
                   const json_t *wire,
                   const struct TALER_Amount *amount)
{
  struct AggregationContext *ac = cls;
  struct WireCheckContext wcc;
  json_t *method;
  struct TALER_WIRE_Plugin *plugin;
  const struct TALER_Amount *wire_fee;
  struct TALER_Amount final_amount;
  struct TALER_Amount exchange_gain;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= pp.last_wire_out_serial_id);
  pp.last_wire_out_serial_id = rowid + 1;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Checking wire transfer %s over %s performed on %s\n",
              TALER_B2S (wtid),
              TALER_amount2s (amount),
              GNUNET_STRINGS_absolute_time_to_string (date));
  wcc.ac = ac;
  method = json_object_get (wire,
                            "type");
  if ( (NULL == method) ||
       (! json_is_string (method)) )
  {
    report_row_inconsistency ("wire_out",
                              rowid,
                              "specified wire address lacks type");
    return GNUNET_OK;
  }
  wcc.method = json_string_value (method);
  wcc.ok = GNUNET_OK;
  wcc.date = date;
  TALER_amount_get_zero (amount->currency,
                         &wcc.total_deposits);
  TALER_JSON_hash (wire,
                   &wcc.h_wire);
  edb->lookup_wire_transfer (edb->cls,
                             esession,
                             wtid,
                             &wire_transfer_information_cb,
                             &wcc);
  if (GNUNET_OK != wcc.ok)
  {
    report_row_inconsistency ("wire_out",
                              rowid,
                              "audit of associated transactions failed");
    return GNUNET_OK;
  }

  /* Subtract aggregation fee from total */
  wire_fee = get_wire_fee (ac,
                           wcc.method,
                           date);
  if (NULL == wire_fee)
  {
    GNUNET_break (0);
    ac->ret = GNUNET_SYSERR;
    return GNUNET_SYSERR;
  }
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&final_amount,
                             &wcc.total_deposits,
                             wire_fee))
  {
    report_row_inconsistency ("wire_out",
                              rowid,
                              "could not subtract wire fee from total amount");
    return GNUNET_OK;
  }

  /* Round down to amount supported by wire method */
  plugin = get_wire_plugin (ac,
                            wcc.method);
  if (NULL == plugin)
  {
    report_row_inconsistency ("wire_out",
                              rowid,
                              "could not load required wire plugin to validate");
    return GNUNET_OK;
  }

  if (GNUNET_SYSERR ==
      plugin->amount_round (plugin->cls,
                            &final_amount))
  {
    report_row_minor_inconsistency ("wire_out",
                                    rowid,
                                    "wire plugin failed to round given amount");
  }

  /* Calculate the exchange's gain as the fees plus rounding differences! */
  if (GNUNET_OK !=
      TALER_amount_subtract (&exchange_gain,
                             &wcc.total_deposits,
                             &final_amount))
  {
    GNUNET_break (0);
    ac->ret = GNUNET_SYSERR;
    return GNUNET_SYSERR;
  }

  /* Sum up aggregation fees (we simply include the rounding gains) */
  if (GNUNET_OK !=
      TALER_amount_add (&ac->total_aggregation_fees,
                        &ac->total_aggregation_fees,
                        &exchange_gain))
  {
    GNUNET_break (0);
    ac->ret = GNUNET_SYSERR;
    return GNUNET_SYSERR;
  }

  /* Check that calculated amount matches actual amount */
  if (0 != TALER_amount_cmp (amount,
                             &final_amount))
  {
    report_wire_out_inconsistency (wire,
                                   rowid,
                                   &final_amount,
                                   amount,
                                   "computed amount inconsistent with wire amount");
    return GNUNET_OK;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Wire transfer %s is OK\n",
              TALER_B2S (wtid));
  return GNUNET_OK;
}


/**
 * Analyze the exchange aggregator's payment processing.
 *
 * @param cls closure
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on hard errors
 */
static int
analyze_aggregations (void *cls)
{
  struct AggregationContext ac;
  struct WirePlugin *wc;
  struct WireFeeInfo *wfi;
  int have_balance;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Analyzing aggregations\n");
  ac.ret = GNUNET_OK;
  ac.wire_head = NULL;
  ac.wire_tail = NULL;
  ac.fee_head = NULL;
  ac.fee_tail = NULL;
  have_balance = adb->get_wire_fee_summary (adb->cls,
                                            asession,
                                            &master_pub,
                                            &ac.total_aggregation_fees);
  if (GNUNET_SYSERR == have_balance)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == have_balance)
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &ac.total_aggregation_fees));
  if (GNUNET_SYSERR ==
      edb->select_wire_out_above_serial_id (edb->cls,
                                            esession,
                                            pp.last_wire_out_serial_id,
                                            &check_wire_out_cb,
                                            &ac))
  {
    GNUNET_break (0);
    ac.ret = GNUNET_SYSERR;
  }
  while (NULL != (wc = ac.wire_head))
  {
    GNUNET_CONTAINER_DLL_remove (ac.wire_head,
                                 ac.wire_tail,
                                 wc);
    TALER_WIRE_plugin_unload (wc->plugin);
    GNUNET_free (wc->type);
    GNUNET_free (wc);
  }
  while (NULL != (wfi = ac.fee_head))
  {
    GNUNET_CONTAINER_DLL_remove (ac.fee_head,
                                 ac.fee_tail,
                                 wfi);
    GNUNET_free (wfi);
  }
  if (GNUNET_OK != ac.ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == have_balance)
    ac.ret = adb->insert_wire_fee_summary (adb->cls,
                                           asession,
                                           &master_pub,
                                           &ac.total_aggregation_fees);
  else
    ac.ret = adb->update_wire_fee_summary (adb->cls,
                                           asession,
                                           &master_pub,
                                           &ac.total_aggregation_fees);
  if (GNUNET_OK != ac.ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  report_aggregation_fee_balance (&ac.total_aggregation_fees);
  return GNUNET_OK;
}


/* ************************* Analyze coins ******************** */
/* This logic checks that the exchange did the right thing for each
   coin, checking deposits, refunds, refresh* and known_coins
   tables */


/**
 * Summary data we keep per denomination.
 */
struct DenominationSummary
{
  /**
   * Total value of outstanding (not deposited) coins issued with this
   * denomination key.
   */
  struct TALER_Amount denom_balance;

  /**
   * Total value of coins issued with this denomination key.
   */
  struct TALER_Amount denom_risk;

  /**
   * Denomination key information for this denomination.
   */
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;

  /**
   * #GNUNET_YES if this record already existed in the DB.
   * Used to decide between insert/update in
   * #sync_denomination().
   */
  int in_db;
};


/**
 * Closure for callbacks during #analyze_coins().
 */
struct CoinContext
{

  /**
   * Map for tracking information about denominations.
   */
  struct GNUNET_CONTAINER_MultiHashMap *denom_summaries;

  /**
   * Total outstanding balances across all denomination keys.
   */
  struct TALER_Amount total_denom_balance;

  /**
   * Total deposit fees earned so far.
   */
  struct TALER_Amount deposit_fee_balance;

  /**
   * Total melt fees earned so far.
   */
  struct TALER_Amount melt_fee_balance;

  /**
   * Total refund fees earned so far.
   */
  struct TALER_Amount refund_fee_balance;

  /**
   * Current financial risk of the exchange operator with respect
   * to key compromise.
   *
   * TODO: not yet properly used!
   */
  struct TALER_Amount risk;

  /**
   * Current write/replace offset in the circular @e summaries buffer.
   */
  unsigned int summaries_off;

  /**
   * #GNUNET_OK as long as we are fine to commit the result to the #adb.
   */
  int ret;

};


/**
 * Initialize information about denomination from the database.
 *
 * @param denom_hash hash of the public key of the denomination
 * @param[out] ds summary to initialize
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static int
init_denomination (const struct GNUNET_HashCode *denom_hash,
                   struct DenominationSummary *ds)
{
  int ret;

  ret = adb->get_denomination_balance (adb->cls,
                                       asession,
                                       denom_hash,
                                       &ds->denom_balance,
                                       &ds->denom_risk);
  if (GNUNET_OK == ret)
  {
    ds->in_db = GNUNET_YES;
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Starting balance for denomination `%s' is %s\n",
                GNUNET_h2s (denom_hash),
                TALER_amount2s (&ds->denom_balance));
    return GNUNET_OK;
  }
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_get_zero (currency,
                                        &ds->denom_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_get_zero (currency,
                                        &ds->denom_risk));
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting balance for denomination `%s' is %s\n",
              GNUNET_h2s (denom_hash),
              TALER_amount2s (&ds->denom_balance));
  return GNUNET_OK;
}


/**
 * Obtain the denomination summary for the given @a dh
 *
 * @param cc our execution context
 * @param dki denomination key information for @a dh
 * @param dh the denomination hash to use for the lookup
 * @return NULL on error
 */
static struct DenominationSummary *
get_denomination_summary (struct CoinContext *cc,
                          const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki,
                          const struct GNUNET_HashCode *dh)
{
  struct DenominationSummary *ds;

  ds = GNUNET_CONTAINER_multihashmap_get (cc->denom_summaries,
                                          dh);
  if (NULL != ds)
    return ds;
  ds = GNUNET_new (struct DenominationSummary);
  ds->dki = dki;
  if (GNUNET_OK !=
      init_denomination (dh,
                         ds))
  {
    GNUNET_break (0);
    GNUNET_free (ds);
    return NULL;
  }
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (cc->denom_summaries,
                                                    dh,
                                                    ds,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  return ds;
}


/**
 * Write information about the current knowledge about a denomination key
 * back to the database and update our global reporting data about the
 * denomination.  Also remove and free the memory of @a value.
 *
 * @param cls the `struct CoinContext`
 * @param denom_hash the hash of the denomination key
 * @param value a `struct DenominationSummary`
 * @return #GNUNET_OK (continue to iterate)
 */
static int
sync_denomination (void *cls,
                   const struct GNUNET_HashCode *denom_hash,
                   void *value)
{
  struct CoinContext *cc = cls;
  struct DenominationSummary *ds = value;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki = ds->dki;
  struct GNUNET_TIME_Absolute now;
  struct GNUNET_TIME_Absolute expire_deposit;
  struct GNUNET_TIME_Absolute expire_deposit_grace;
  int ret;

  now = GNUNET_TIME_absolute_get ();
  expire_deposit = GNUNET_TIME_absolute_ntoh (dki->properties.expire_deposit);
  /* add day grace period to deal with clocks not being perfectly synchronized */
  expire_deposit_grace = GNUNET_TIME_absolute_add (expire_deposit,
                                                   DEPOSIT_GRACE_PERIOD);
  if (now.abs_value_us > expire_deposit_grace.abs_value_us)
  {
    /* Denominationkey has expired, book remaining balance of
       outstanding coins as revenue; and reduce cc->risk exposure. */
    if (ds->in_db)
      ret = adb->del_denomination_balance (adb->cls,
                                           asession,
                                           denom_hash);
    else
      ret = GNUNET_OK;
    if ( (GNUNET_OK == ret) &&
         ( (0 != ds->denom_risk.value) ||
           (0 != ds->denom_risk.fraction) ) )
    {
      /* The denomination expired and carried a balance; we can now
         book the remaining balance as profit, and reduce our risk
         exposure by the accumulated risk of the denomination. */
      if (GNUNET_SYSERR ==
          TALER_amount_subtract (&cc->risk,
                                 &cc->risk,
                                 &ds->denom_risk))
      {
        /* Holy smokes, our risk assessment was inconsistent!
           This is really, really bad. */
        GNUNET_break (0);
        cc->ret = GNUNET_SYSERR;
      }
    }
    if ( (GNUNET_OK == ret) &&
         ( (0 != ds->denom_balance.value) ||
           (0 != ds->denom_balance.fraction) ) )
    {
      /* book denom_balance coin expiration profits! */
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Denomination `%s' expired, booking %s in expiration profits\n",
                  GNUNET_h2s (denom_hash),
                  TALER_amount2s (&ds->denom_balance));
      if (GNUNET_OK !=
          adb->insert_historic_denom_revenue (adb->cls,
                                              asession,
                                              &master_pub,
                                              denom_hash,
                                              expire_deposit,
                                              &ds->denom_balance))
      {
        /* Failed to store profits? Bad database */
        GNUNET_break (0);
        cc->ret = GNUNET_SYSERR;
      }
    }
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Final balance for denomination `%s' is %s\n",
                GNUNET_h2s (denom_hash),
                TALER_amount2s (&ds->denom_balance));
    if (ds->in_db)
      ret = adb->update_denomination_balance (adb->cls,
                                              asession,
                                              denom_hash,
                                              &ds->denom_balance,
                                              &ds->denom_risk);
    else
      ret = adb->insert_denomination_balance (adb->cls,
                                              asession,
                                              denom_hash,
                                              &ds->denom_balance,
                                              &ds->denom_risk);
  }
  if (GNUNET_OK != ret)
  {
    GNUNET_break (0);
    cc->ret = GNUNET_SYSERR;
  }
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (cc->denom_summaries,
                                                       denom_hash,
                                                       ds));
  GNUNET_free (ds);
  return cc->ret;
}


/**
 * Function called with details about all withdraw operations.
 * Updates the denomination balance and the overall balance as
 * we now have additional coins that have been issued.
 *
 * Note that the signature was already checked in
 * #handle_reserve_out(), so we do not check it again here.
 *
 * @param cls our `struct CoinContext`
 * @param rowid unique serial ID for the refresh session in our DB
 * @param h_blind_ev blinded hash of the coin's public key
 * @param denom_pub public denomination key of the deposited coin
 * @param denom_sig signature over the deposited coin
 * @param reserve_pub public key of the reserve
 * @param reserve_sig signature over the withdraw operation (verified elsewhere)
 * @param execution_date when did the wallet withdraw the coin
 * @param amount_with_fee amount that was withdrawn
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
withdraw_cb (void *cls,
             uint64_t rowid,
             const struct GNUNET_HashCode *h_blind_ev,
             const struct TALER_DenominationPublicKey *denom_pub,
             const struct TALER_DenominationSignature *denom_sig,
             const struct TALER_ReservePublicKeyP *reserve_pub,
             const struct TALER_ReserveSignatureP *reserve_sig,
             struct GNUNET_TIME_Absolute execution_date,
             const struct TALER_Amount *amount_with_fee)
{
  struct CoinContext *cc = cls;
  struct DenominationSummary *ds;
  struct GNUNET_HashCode dh;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct TALER_Amount value;

  GNUNET_assert (rowid >= pp.last_withdraw_serial_id); /* should be monotonically increasing */
  pp.last_withdraw_serial_id = rowid + 1;

  if (GNUNET_OK !=
      get_denomination_info (denom_pub,
                             &dki,
                             &dh))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  ds = get_denomination_summary (cc,
                                 dki,
                                 &dh);
  TALER_amount_ntoh (&value,
                     &dki->properties.value);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Issued coin in denomination `%s' of total value %s\n",
              GNUNET_h2s (&dh),
              TALER_amount2s (&value));
  if (GNUNET_OK !=
      TALER_amount_add (&ds->denom_balance,
                        &ds->denom_balance,
                        &value))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New balance of denomination `%s' is %s\n",
              GNUNET_h2s (&dh),
              TALER_amount2s (&ds->denom_balance));
  if (GNUNET_OK !=
      TALER_amount_add (&cc->total_denom_balance,
                        &cc->total_denom_balance,
                        &value))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&cc->risk,
                        &cc->risk,
                        &value))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&ds->denom_risk,
                        &ds->denom_risk,
                        &value))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Function called with details about coins that were melted, with the
 * goal of auditing the refresh's execution.  Verifies the signature
 * and updates our information about coins outstanding (the old coin's
 * denomination has less, the fresh coins increased outstanding
 * balances).
 *
 * @param cls closure
 * @param rowid unique serial ID for the refresh session in our DB
 * @param denom_pub denomination public key of @a coin_pub
 * @param coin_pub public key of the coin
 * @param coin_sig signature from the coin
 * @param amount_with_fee amount that was deposited including fee
 * @param num_newcoins how many coins were issued
 * @param noreveal_index which index was picked by the exchange in cut-and-choose
 * @param session_hash what is the session hash
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
refresh_session_cb (void *cls,
                    uint64_t rowid,
                    const struct TALER_DenominationPublicKey *denom_pub,
                    const struct TALER_CoinSpendPublicKeyP *coin_pub,
                    const struct TALER_CoinSpendSignatureP *coin_sig,
                    const struct TALER_Amount *amount_with_fee,
                    uint16_t num_newcoins,
                    uint16_t noreveal_index,
                    const struct GNUNET_HashCode *session_hash)
{
  struct CoinContext *cc = cls;
  struct TALER_RefreshMeltCoinAffirmationPS rmc;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct DenominationSummary *dso;
  struct TALER_Amount amount_without_fee;
  struct TALER_Amount tmp;

  GNUNET_assert (rowid >= pp.last_melt_serial_id); /* should be monotonically increasing */
  pp.last_melt_serial_id = rowid + 1;

  if (GNUNET_OK !=
      get_denomination_info (denom_pub,
                             &dki,
                             NULL))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* verify melt signature */
  rmc.purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_MELT);
  rmc.purpose.size = htonl (sizeof (rmc));
  rmc.session_hash = *session_hash;
  TALER_amount_hton (&rmc.amount_with_fee,
                     amount_with_fee);
  rmc.melt_fee = dki->properties.fee_refresh;
  rmc.coin_pub = *coin_pub;
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_COIN_MELT,
                                  &rmc.purpose,
                                  &coin_sig->eddsa_signature,
                                  &coin_pub->eddsa_pub))
  {
    report_row_inconsistency ("melt",
                              rowid,
                              "invalid signature for coin melt");
    return GNUNET_OK;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Melting coin %s in denomination `%s' of value %s\n",
              TALER_B2S (coin_pub),
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (amount_with_fee));

  {
    struct TALER_DenominationPublicKey new_dp[num_newcoins];
    const struct TALER_EXCHANGEDB_DenominationKeyInformationP *new_dki[num_newcoins];
    struct TALER_Amount refresh_cost;
    int err;

    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (amount_with_fee->currency,
                                          &refresh_cost));

    if (GNUNET_OK !=
        edb->get_refresh_order (edb->cls,
                                esession,
                                session_hash,
                                num_newcoins,
                                new_dp))
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
    /* Update outstanding amounts for all new coin's denominations, and check
       that the resulting amounts are consistent with the value being refreshed. */
    err = GNUNET_NO;
    for (unsigned int i=0;i<num_newcoins;i++)
    {
      /* lookup new coin denomination key */
      if (GNUNET_OK !=
          get_denomination_info (&new_dp[i],
                                 &new_dki[i],
                                 NULL))
      {
        GNUNET_break (0);
        err = GNUNET_YES;
      }
      GNUNET_CRYPTO_rsa_public_key_free (new_dp[i].rsa_public_key);
      new_dp[i].rsa_public_key = NULL;
    }
    if (err)
      return GNUNET_SYSERR;

    /* calculate total refresh cost */
    for (unsigned int i=0;i<num_newcoins;i++)
    {
      /* update cost of refresh */
      struct TALER_Amount fee;
      struct TALER_Amount value;

      TALER_amount_ntoh (&fee,
                         &new_dki[i]->properties.fee_withdraw);
      TALER_amount_ntoh (&value,
                         &new_dki[i]->properties.value);
      if ( (GNUNET_OK !=
            TALER_amount_add (&refresh_cost,
                              &refresh_cost,
                              &fee)) ||
           (GNUNET_OK !=
            TALER_amount_add (&refresh_cost,
                              &refresh_cost,
                              &value)) )
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
    }

    /* compute contribution of old coin */
    {
      struct TALER_Amount melt_fee;

      TALER_amount_ntoh (&melt_fee,
                         &dki->properties.fee_refresh);
      if (GNUNET_OK !=
          TALER_amount_subtract (&amount_without_fee,
                                 amount_with_fee,
                                 &melt_fee))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
    }

    /* check old coin covers complete expenses */
    if (1 == TALER_amount_cmp (&refresh_cost,
                               &amount_without_fee))
    {
      /* refresh_cost > amount_without_fee */
      report_row_inconsistency ("melt",
                                rowid,
                                "refresh costs exceed value of melt");
      return GNUNET_OK;
    }

    /* update outstanding denomination amounts */
    for (unsigned int i=0;i<num_newcoins;i++)
    {
      struct DenominationSummary *dsi;
      struct TALER_Amount value;

      dsi = get_denomination_summary (cc,
                                      new_dki[i],
                                      &new_dki[i]->properties.denom_hash);
      TALER_amount_ntoh (&value,
                         &new_dki[i]->properties.value);
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Created fresh coin in denomination `%s' of value %s\n",
                  GNUNET_h2s (&new_dki[i]->properties.denom_hash),
                  TALER_amount2s (&value));
      if (GNUNET_OK !=
          TALER_amount_add (&dsi->denom_balance,
                            &dsi->denom_balance,
                            &value))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      if (GNUNET_OK !=
          TALER_amount_add (&dsi->denom_risk,
                            &dsi->denom_risk,
                            &value))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "New balance of denomination `%s' is %s\n",
                  GNUNET_h2s (&new_dki[i]->properties.denom_hash),
                  TALER_amount2s (&dsi->denom_balance));
      if (GNUNET_OK !=
          TALER_amount_add (&cc->total_denom_balance,
                            &cc->total_denom_balance,
                            &value))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
      if (GNUNET_OK !=
          TALER_amount_add (&cc->risk,
                            &cc->risk,
                            &value))
      {
        GNUNET_break (0);
        return GNUNET_SYSERR;
      }
    }
  }

  /* update old coin's denomination balance */
  dso = get_denomination_summary (cc,
                                  dki,
                                  &dki->properties.denom_hash);
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&tmp,
                             &dso->denom_balance,
                             amount_with_fee))
  {
    report_emergency (dki);
    return GNUNET_SYSERR;
  }
  dso->denom_balance = tmp;
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&cc->total_denom_balance,
                             &cc->total_denom_balance,
                             amount_with_fee))
  {
    /* This should not be possible, unless the AUDITOR
       has a bug in tracking total balance. */
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New balance of denomination `%s' after melt is %s\n",
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (&dso->denom_balance));

  /* update global up melt fees */
  {
    struct TALER_Amount rfee;

    TALER_amount_ntoh (&rfee,
                       &dki->properties.fee_refresh);
    if (GNUNET_OK !=
        TALER_amount_add (&cc->melt_fee_balance,
                          &cc->melt_fee_balance,
                          &rfee))
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }

  /* We're good! */
  return GNUNET_OK;
}


/**
 * Function called with details about deposits that have been made,
 * with the goal of auditing the deposit's execution.
 *
 * @param cls closure
 * @param rowid unique serial ID for the deposit in our DB
 * @param timestamp when did the deposit happen
 * @param merchant_pub public key of the merchant
 * @param denom_pub denomination public key of @a coin_pub
 * @param coin_pub public key of the coin
 * @param coin_sig signature from the coin
 * @param amount_with_fee amount that was deposited including fee
 * @param h_proposal_data hash of the proposal data known to merchant and customer
 * @param refund_deadline by which the merchant adviced that he might want
 *        to get a refund
 * @param wire_deadline by which the merchant adviced that he would like the
 *        wire transfer to be executed
 * @param receiver_wire_account wire details for the merchant, NULL from iterate_matching_deposits()
 * @param done flag set if the deposit was already executed (or not)
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
deposit_cb (void *cls,
            uint64_t rowid,
            struct GNUNET_TIME_Absolute timestamp,
            const struct TALER_MerchantPublicKeyP *merchant_pub,
            const struct TALER_DenominationPublicKey *denom_pub,
            const struct TALER_CoinSpendPublicKeyP *coin_pub,
            const struct TALER_CoinSpendSignatureP *coin_sig,
            const struct TALER_Amount *amount_with_fee,
            const struct GNUNET_HashCode *h_proposal_data,
            struct GNUNET_TIME_Absolute refund_deadline,
            struct GNUNET_TIME_Absolute wire_deadline,
            const json_t *receiver_wire_account,
            int done)
{
  struct CoinContext *cc = cls;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct DenominationSummary *ds;
  struct TALER_DepositRequestPS dr;
  struct TALER_Amount tmp;

  GNUNET_assert (rowid >= pp.last_deposit_serial_id); /* should be monotonically increasing */
  pp.last_deposit_serial_id = rowid + 1;

  if (GNUNET_OK !=
      get_denomination_info (denom_pub,
                             &dki,
                             NULL))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* Verify deposit signature */
  dr.purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_DEPOSIT);
  dr.purpose.size = htonl (sizeof (dr));
  dr.h_proposal_data = *h_proposal_data;
  if (GNUNET_OK !=
      TALER_JSON_hash (receiver_wire_account,
                       &dr.h_wire))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  dr.timestamp = GNUNET_TIME_absolute_hton (timestamp);
  dr.refund_deadline = GNUNET_TIME_absolute_hton (refund_deadline);
  TALER_amount_hton (&dr.amount_with_fee,
                     amount_with_fee);
  dr.deposit_fee = dki->properties.fee_deposit;
  dr.merchant = *merchant_pub;
  dr.coin_pub = *coin_pub;
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_WALLET_COIN_DEPOSIT,
                                  &dr.purpose,
                                  &coin_sig->eddsa_signature,
                                  &coin_pub->eddsa_pub))
  {
    report_row_inconsistency ("deposit",
                              rowid,
                              "invalid signature for coin deposit");
    return GNUNET_OK;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Deposited coin %s in denomination `%s' of value %s\n",
              TALER_B2S (coin_pub),
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (amount_with_fee));

  /* update old coin's denomination balance */
  ds = get_denomination_summary (cc,
                                 dki,
                                 &dki->properties.denom_hash);
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&tmp,
                             &ds->denom_balance,
                             amount_with_fee))
  {
    report_emergency (dki);
    return GNUNET_SYSERR;
  }
  ds->denom_balance = tmp;
  if (GNUNET_SYSERR ==
      TALER_amount_subtract (&cc->total_denom_balance,
                             &cc->total_denom_balance,
                             amount_with_fee))
  {
    /* This should not be possible, unless the AUDITOR
       has a bug in tracking total balance. */
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New balance of denomination `%s' after deposit is %s\n",
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (&ds->denom_balance));

  /* update global up melt fees */
  {
    struct TALER_Amount dfee;

    TALER_amount_ntoh (&dfee,
                       &dki->properties.fee_deposit);
    if (GNUNET_OK !=
        TALER_amount_add (&cc->deposit_fee_balance,
                          &cc->deposit_fee_balance,
                          &dfee))
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }

  return GNUNET_OK;
}


/**
 * Function called with details about coins that were refunding,
 * with the goal of auditing the refund's execution.  Adds the
 * refunded amount back to the outstanding balance of the respective
 * denomination.
 *
 * @param cls closure
 * @param rowid unique serial ID for the refund in our DB
 * @param denom_pub denomination public key of @a coin_pub
 * @param coin_pub public key of the coin
 * @param merchant_pub public key of the merchant
 * @param merchant_sig signature of the merchant
 * @param h_proposal_data hash of the proposal data known to merchant and customer
 * @param rtransaction_id refund transaction ID chosen by the merchant
 * @param amount_with_fee amount that was deposited including fee
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static int
refund_cb (void *cls,
           uint64_t rowid,
           const struct TALER_DenominationPublicKey *denom_pub,
           const struct TALER_CoinSpendPublicKeyP *coin_pub,
           const struct TALER_MerchantPublicKeyP *merchant_pub,
           const struct TALER_MerchantSignatureP *merchant_sig,
           const struct GNUNET_HashCode *h_proposal_data,
           uint64_t rtransaction_id,
           const struct TALER_Amount *amount_with_fee)
{
  struct CoinContext *cc = cls;
  const struct TALER_EXCHANGEDB_DenominationKeyInformationP *dki;
  struct DenominationSummary *ds;
  struct TALER_RefundRequestPS rr;
  struct TALER_Amount amount_without_fee;
  struct TALER_Amount refund_fee;

  GNUNET_assert (rowid >= pp.last_refund_serial_id); /* should be monotonically increasing */
  pp.last_refund_serial_id = rowid + 1;

  if (GNUNET_OK !=
      get_denomination_info (denom_pub,
                             &dki,
                             NULL))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* verify refund signature */
  rr.purpose.purpose = htonl (TALER_SIGNATURE_MERCHANT_REFUND);
  rr.purpose.size = htonl (sizeof (rr));
  rr.h_proposal_data = *h_proposal_data;
  rr.coin_pub = *coin_pub;
  rr.merchant = *merchant_pub;
  rr.rtransaction_id = GNUNET_htonll (rtransaction_id);
  TALER_amount_hton (&rr.refund_amount,
                     amount_with_fee);
  rr.refund_fee = dki->properties.fee_refund;
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_MERCHANT_REFUND,
                                  &rr.purpose,
                                  &merchant_sig->eddsa_sig,
                                  &merchant_pub->eddsa_pub))
  {
    report_row_inconsistency ("refund",
                              rowid,
                              "invalid signature for refund");
    return GNUNET_OK;
  }

  TALER_amount_ntoh (&refund_fee,
                     &dki->properties.fee_refund);
  if (GNUNET_OK !=
      TALER_amount_subtract (&amount_without_fee,
                             amount_with_fee,
                             &refund_fee))
  {
    report_row_inconsistency ("refund",
                              rowid,
                              "refunded amount smaller than refund fee");
    return GNUNET_OK;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Refunding coin %s in denomination `%s' value %s\n",
              TALER_B2S (coin_pub),
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (amount_with_fee));

  /* update coin's denomination balance */
  ds = get_denomination_summary (cc,
                                 dki,
                                 &dki->properties.denom_hash);
  if (GNUNET_OK !=
      TALER_amount_add (&ds->denom_balance,
                        &ds->denom_balance,
                        &amount_without_fee))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&ds->denom_risk,
                        &ds->denom_risk,
                        &amount_without_fee))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&cc->total_denom_balance,
                        &cc->total_denom_balance,
                        &amount_without_fee))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&cc->risk,
                        &cc->risk,
                        &amount_without_fee))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New balance of denomination `%s' after refund is %s\n",
              GNUNET_h2s (&dki->properties.denom_hash),
              TALER_amount2s (&ds->denom_balance));

  /* update total refund fee balance */
  if (GNUNET_OK !=
      TALER_amount_add (&cc->refund_fee_balance,
                        &cc->refund_fee_balance,
                        &refund_fee))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  return GNUNET_OK;
}


/**
 * Analyze the exchange's processing of coins.
 *
 * @param cls closure
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on hard errors
 */
static int
analyze_coins (void *cls)
{
  struct CoinContext cc;
  int dret;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Analyzing coins\n");
  /* setup 'cc' */
  cc.ret = GNUNET_OK;
  cc.denom_summaries = GNUNET_CONTAINER_multihashmap_create (256,
                                                           GNUNET_NO);
  dret = adb->get_balance_summary (adb->cls,
                                   asession,
                                   &master_pub,
                                   &cc.total_denom_balance,
                                   &cc.deposit_fee_balance,
                                   &cc.melt_fee_balance,
                                   &cc.refund_fee_balance,
                                   &cc.risk);
  if (GNUNET_SYSERR == dret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == dret)
  {
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &cc.total_denom_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &cc.deposit_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &cc.melt_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &cc.refund_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_get_zero (currency,
                                          &cc.risk));
  }

  /* process withdrawals */
  if (GNUNET_SYSERR ==
      edb->select_reserves_out_above_serial_id (edb->cls,
                                                esession,
                                                pp.last_withdraw_serial_id,
                                                &withdraw_cb,
                                                &cc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* process refunds */
  if (GNUNET_SYSERR ==
      edb->select_refunds_above_serial_id (edb->cls,
                                           esession,
                                           pp.last_refund_serial_id,
                                           &refund_cb,
                                           &cc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* process refreshs */
  if (GNUNET_SYSERR ==
      edb->select_refreshs_above_serial_id (edb->cls,
                                            esession,
                                            pp.last_melt_serial_id,
                                            &refresh_session_cb,
                                            &cc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* process deposits */
  if (GNUNET_SYSERR ==
      edb->select_deposits_above_serial_id (edb->cls,
                                            esession,
                                            pp.last_deposit_serial_id,
                                            &deposit_cb,
                                            &cc))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  /* sync 'cc' back to disk */
  GNUNET_CONTAINER_multihashmap_iterate (cc.denom_summaries,
                                         &sync_denomination,
                                         &cc);
  GNUNET_CONTAINER_multihashmap_destroy (cc.denom_summaries);
  if (GNUNET_OK != cc.ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_YES == dret)
      dret = adb->update_balance_summary (adb->cls,
                                          asession,
                                          &master_pub,
                                          &cc.total_denom_balance,
                                          &cc.deposit_fee_balance,
                                          &cc.melt_fee_balance,
                                          &cc.refund_fee_balance,
                                          &cc.risk);
  else
    dret = adb->insert_balance_summary (adb->cls,
                                        asession,
                                        &master_pub,
                                        &cc.total_denom_balance,
                                        &cc.deposit_fee_balance,
                                        &cc.melt_fee_balance,
                                        &cc.refund_fee_balance,
                                        &cc.risk);
  if (GNUNET_OK != dret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  report_denomination_balance (&cc.total_denom_balance,
                               &cc.risk,
                               &cc.deposit_fee_balance,
                               &cc.melt_fee_balance,
                               &cc.refund_fee_balance);
  return GNUNET_OK;
}


/* *************************** General transaction logic ****************** */

/**
 * Type of an analysis function.  Each analysis function runs in
 * its own transaction scope and must thus be internally consistent.
 *
 * @param cls closure
 * @param int #GNUNET_OK on success, #GNUNET_SYSERR on hard errors
 */
typedef int
(*Analysis)(void *cls);


/**
 * Perform the given @a analysis incrementally, checkpointing our
 * progress in the auditor DB.
 *
 * @param analysis analysis to run
 * @param analysis_cls closure for @a analysis
 * @return #GNUNET_OK if @a analysis succeessfully committed,
 *         #GNUNET_SYSERR on hard errors
 */
static int
incremental_processing (Analysis analysis,
                        void *analysis_cls)
{
  int ret;
  int have_pp;

  have_pp = adb->get_auditor_progress (adb->cls,
                                       asession,
                                       &master_pub,
                                       &pp);
  if (GNUNET_SYSERR == have_pp)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_NO == have_pp)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
                _("First analysis using this auditor, starting audit from scratch\n"));
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                _("Resuming audit at %llu/%llu/%llu/%llu/%llu/%llu/%llu\n"),
                (unsigned long long) pp.last_reserve_in_serial_id,
                (unsigned long long) pp.last_reserve_out_serial_id,
                (unsigned long long) pp.last_withdraw_serial_id,
                (unsigned long long) pp.last_deposit_serial_id,
                (unsigned long long) pp.last_melt_serial_id,
                (unsigned long long) pp.last_refund_serial_id,
                (unsigned long long) pp.last_wire_out_serial_id);
  }
  ret = analysis (analysis_cls);
  if (GNUNET_OK != ret)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Analysis phase failed, not recording progress\n");
    return GNUNET_SYSERR;
  }
  if (GNUNET_YES == have_pp)
    ret = adb->update_auditor_progress (adb->cls,
                                        asession,
                                        &master_pub,
                                        &pp);
  else
    ret = adb->insert_auditor_progress (adb->cls,
                                        asession,
                                        &master_pub,
                                        &pp);
  if (GNUNET_OK != ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              _("Concluded audit step at %llu/%llu/%llu/%llu/%llu/%llu/%llu\n\n"),
              (unsigned long long) pp.last_reserve_in_serial_id,
              (unsigned long long) pp.last_reserve_out_serial_id,
              (unsigned long long) pp.last_withdraw_serial_id,
              (unsigned long long) pp.last_deposit_serial_id,
              (unsigned long long) pp.last_melt_serial_id,
              (unsigned long long) pp.last_refund_serial_id,
              (unsigned long long) pp.last_wire_out_serial_id);
  return GNUNET_OK;
}


/**
 * Perform the given @a analysis within a transaction scope.
 * Commit on success.
 *
 * @param analysis analysis to run
 * @param analysis_cls closure for @a analysis
 * @return #GNUNET_OK if @a analysis succeessfully committed,
 *         #GNUNET_NO if we had an error on commit (retry may help)
 *         #GNUNET_SYSERR on hard errors
 */
static int
transact (Analysis analysis,
          void *analysis_cls)
{
  int ret;

  ret = adb->start (adb->cls,
                    asession);
  if (GNUNET_OK != ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  ret = edb->start (edb->cls,
                    esession);
  if (GNUNET_OK != ret)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  ret = incremental_processing (analysis,
                                analysis_cls);
  if (GNUNET_OK == ret)
  {
    ret = edb->commit (edb->cls,
                       esession);
    if (GNUNET_OK != ret)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Exchange DB commit failed, rolling back transaction\n");
      adb->rollback (adb->cls,
                     asession);
    }
    else
    {
      ret = adb->commit (adb->cls,
                         asession);
      if (GNUNET_OK != ret)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                    "Auditor DB commit failed!\n");
      }
    }
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Processing failed, rolling back transaction\n");
    adb->rollback (adb->cls,
                   asession);
    edb->rollback (edb->cls,
                   esession);
  }
  clear_transaction_state_cache ();
  return ret;
}


/**
 * Initialize DB sessions and run the analysis.
 */
static void
setup_sessions_and_run ()
{
  esession = edb->get_session (edb->cls);
  if (NULL == esession)
  {
    fprintf (stderr,
             "Failed to initialize exchange session.\n");
    global_ret = 1;
    return;
  }
  asession = adb->get_session (adb->cls);
  if (NULL == asession)
  {
    fprintf (stderr,
             "Failed to initialize auditor session.\n");
    global_ret = 1;
    return;
  }

  transact (&analyze_reserves,
            NULL);
  transact (&analyze_aggregations,
            NULL);
  transact (&analyze_coins,
            NULL);
}


/**
 * Main function that will be run.
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param c configuration
 */
static void
run (void *cls,
     char *const *args,
     const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Launching auditor\n");
  cfg = c;
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_string (cfg,
                                             "taler",
                                             "CURRENCY",
                                             &currency))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               "taler",
                               "CURRENCY");
    global_ret = 1;
    return;
  }
  if (NULL ==
      (edb = TALER_EXCHANGEDB_plugin_load (cfg)))
  {
    fprintf (stderr,
             "Failed to initialize exchange database plugin.\n");
    global_ret = 1;
    return;
  }
  if (NULL ==
      (adb = TALER_AUDITORDB_plugin_load (cfg)))
  {
    fprintf (stderr,
             "Failed to initialize auditor database plugin.\n");
    global_ret = 1;
    TALER_EXCHANGEDB_plugin_unload (edb);
    return;
  }
  if (restart)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Full audit restart requested, dropping old audit data.\n");
    GNUNET_break (GNUNET_OK ==
                  adb->drop_tables (adb->cls));
    TALER_AUDITORDB_plugin_unload (adb);
    if (NULL ==
        (adb = TALER_AUDITORDB_plugin_load (cfg)))
    {
      fprintf (stderr,
               "Failed to initialize auditor database plugin after drop.\n");
      global_ret = 1;
      TALER_EXCHANGEDB_plugin_unload (edb);
      return;
    }
    GNUNET_break (GNUNET_OK ==
                  adb->create_tables (adb->cls));
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting audit\n");
  setup_sessions_and_run ();
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Audit complete\n");
  TALER_AUDITORDB_plugin_unload (adb);
  TALER_EXCHANGEDB_plugin_unload (edb);
}


/**
 * The main function of the database initialization tool.
 * Used to initialize the Taler Exchange's database.
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc,
      char *const *argv)
{
  const struct GNUNET_GETOPT_CommandLineOption options[] = {
    GNUNET_GETOPT_option_mandatory
    (GNUNET_GETOPT_option_base32_auto ('m',
                                           "exchange-key",
                                           "KEY",
                                           "public key of the exchange (Crockford base32 encoded)",
                                           &master_pub)),
    GNUNET_GETOPT_option_flag ('r',
                                  "restart",
                                  "restart audit from the beginning (required on first run)",
                                  &restart),
    GNUNET_GETOPT_OPTION_END
  };

  /* force linker to link against libtalerutil; if we do
     not do this, the linker may "optimize" libtalerutil
     away and skip #TALER_OS_init(), which we do need */
  (void) TALER_project_data_default ();
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_log_setup ("taler-auditor",
                                   "MESSAGE",
                                   NULL));
  if (GNUNET_OK !=
      GNUNET_PROGRAM_run (argc,
			  argv,
                          "taler-auditor",
			  "Audit Taler exchange database",
			  options,
			  &run,
			  NULL))
    return 1;
  return global_ret;
}


/* end of taler-auditor.c */