summaryrefslogtreecommitdiff
path: root/src/auditor/taler-helper-auditor-reserves.c
blob: aa35c6a75a4f905e87b860848893a2e000e052a7 (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
/*
  This file is part of TALER
  Copyright (C) 2016-2022 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero 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 Affero Public License for more details.

  You should have received a copy of the GNU Affero Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file auditor/taler-helper-auditor-reserves.c
 * @brief audits the reserves of an exchange database
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include "taler_auditordb_plugin.h"
#include "taler_exchangedb_lib.h"
#include "taler_json_lib.h"
#include "taler_bank_service.h"
#include "taler_signatures.h"
#include "report-lib.h"


/**
 * 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;

/**
 * Run in test mode. Exit when idle instead of
 * going to sleep and waiting for more work.
 *
 * FIXME: not yet implemented!
 */
static int test_mode;

/**
 * After how long should idle reserves be closed?
 */
static struct GNUNET_TIME_Relative idle_reserve_expiration_time;

/**
 * Checkpointing our progress for reserves.
 */
static TALER_ARL_DEF_PP (reserves_reserve_in_serial_id);
static TALER_ARL_DEF_PP (reserves_reserve_out_serial_id);
static TALER_ARL_DEF_PP (reserves_reserve_recoup_serial_id);
static TALER_ARL_DEF_PP (reserves_reserve_open_serial_id);
static TALER_ARL_DEF_PP (reserves_reserve_close_serial_id);
static TALER_ARL_DEF_PP (reserves_purse_decisions_serial_id);
static TALER_ARL_DEF_PP (reserves_account_merges_serial_id);
static TALER_ARL_DEF_PP (reserves_history_requests_serial_id);

/**
 * Tracked global reserve balances.
 */
static TALER_ARL_DEF_AB (reserves_reserve_total_balance);
static TALER_ARL_DEF_AB (reserves_reserve_loss);
static TALER_ARL_DEF_AB (reserves_withdraw_fee_revenue);
static TALER_ARL_DEF_AB (reserves_close_fee_revenue);
static TALER_ARL_DEF_AB (reserves_purse_fee_revenue);
static TALER_ARL_DEF_AB (reserves_open_fee_revenue);
static TALER_ARL_DEF_AB (reserves_history_fee_revenue);


/**
 * Array of reports about row inconsistencies.
 */
static json_t *report_row_inconsistencies;

/**
 * Array of reports about the denomination key not being
 * valid at the time of withdrawal.
 */
static json_t *denomination_key_validity_withdraw_inconsistencies;

/**
 * Array of reports about reserve balance insufficient inconsistencies.
 */
static json_t *report_reserve_balance_insufficient_inconsistencies;

/**
 * Array of reports about purse balance insufficient inconsistencies.
 */
static json_t *report_purse_balance_insufficient_inconsistencies;

/**
 * Array of reports about reserve balance summary wrong in database.
 */
static json_t *report_reserve_balance_summary_wrong_inconsistencies;

/**
 * Total delta between expected and stored reserve balance summaries,
 * for positive deltas.  Used only when internal checks are
 * enabled.
 */
static struct TALER_Amount total_balance_summary_delta_plus;

/**
 * Total delta between expected and stored reserve balance summaries,
 * for negative deltas.  Used only when internal checks are
 * enabled.
 */
static struct TALER_Amount total_balance_summary_delta_minus;

/**
 * Array of reports about reserve's not being closed inconsistencies.
 */
static json_t *report_reserve_not_closed_inconsistencies;

/**
 * Total amount affected by reserves not having been closed on time.
 */
static struct TALER_Amount total_balance_reserve_not_closed;

/**
 * Report about amount calculation differences (causing profit
 * or loss at the exchange).
 */
static json_t *report_amount_arithmetic_inconsistencies;

/**
 * Profits the exchange made by bad amount calculations.
 */
static struct TALER_Amount total_arithmetic_delta_plus;

/**
 * Losses the exchange made by bad amount calculations.
 */
static struct TALER_Amount total_arithmetic_delta_minus;

/**
 * Array of reports about coin operations with bad signatures.
 */
static json_t *report_bad_sig_losses;

/**
 * Total amount lost by operations for which signatures were invalid.
 */
static struct TALER_Amount total_bad_sig_loss;

/**
 * Should we run checks that only work for exchange-internal audits?
 */
static int internal_checks;

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


/**
 * Report a (serious) inconsistency in the exchange's database with
 * respect to calculations involving amounts.
 *
 * @param operation what operation had the inconsistency
 * @param rowid affected row, 0 if row is missing
 * @param exchange amount calculated by exchange
 * @param auditor amount calculated by auditor
 * @param profitable 1 if @a exchange being larger than @a auditor is
 *           profitable for the exchange for this operation,
 *           -1 if @a exchange being smaller than @a auditor is
 *           profitable for the exchange, and 0 if it is unclear
 */
static void
report_amount_arithmetic_inconsistency (
  const char *operation,
  uint64_t rowid,
  const struct TALER_Amount *exchange,
  const struct TALER_Amount *auditor,
  int profitable)
{
  struct TALER_Amount delta;
  struct TALER_Amount *target;

  if (0 < TALER_amount_cmp (exchange,
                            auditor))
  {
    /* exchange > auditor */
    TALER_ARL_amount_subtract (&delta,
                               exchange,
                               auditor);
  }
  else
  {
    /* auditor < exchange */
    profitable = -profitable;
    TALER_ARL_amount_subtract (&delta,
                               auditor,
                               exchange);
  }
  TALER_ARL_report (report_amount_arithmetic_inconsistencies,
                    GNUNET_JSON_PACK (
                      GNUNET_JSON_pack_string ("operation",
                                               operation),
                      GNUNET_JSON_pack_uint64 ("rowid",
                                               rowid),
                      TALER_JSON_pack_amount ("exchange",
                                              exchange),
                      TALER_JSON_pack_amount ("auditor",
                                              auditor),
                      GNUNET_JSON_pack_int64 ("profitable",
                                              profitable)));
  if (0 != profitable)
  {
    target = (1 == profitable)
        ? &total_arithmetic_delta_plus
        : &total_arithmetic_delta_minus;
    TALER_ARL_amount_add (target,
                          target,
                          &delta);
  }
}


/**
 * Report a (serious) inconsistency in the exchange's database.
 *
 * @param table affected table
 * @param rowid affected row, 0 if row is missing
 * @param diagnostic message explaining the problem
 */
static void
report_row_inconsistency (const char *table,
                          uint64_t rowid,
                          const char *diagnostic)
{
  TALER_ARL_report (report_row_inconsistencies,
                    GNUNET_JSON_PACK (
                      GNUNET_JSON_pack_string ("table",
                                               table),
                      GNUNET_JSON_pack_uint64 ("row",
                                               rowid),
                      GNUNET_JSON_pack_string ("diagnostic",
                                               diagnostic)));
}


/* ***************************** 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 balance and fees encountered during this transaction.
   */
  struct TALER_AUDITORDB_ReserveFeeBalance curr_balance;

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

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

  /**
   * Which account did originally put money into the reserve?
   */
  char *sender_account;

  /**
   * 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).
   */
  bool 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 transaction status code
 */
static enum GNUNET_DB_QueryStatus
load_auditor_reserve_summary (struct ReserveSummary *rs)
{
  enum GNUNET_DB_QueryStatus qs;
  uint64_t rowid;

  qs = TALER_ARL_adb->get_reserve_info (TALER_ARL_adb->cls,
                                        &rs->reserve_pub,
                                        &rowid,
                                        &rs->prev_balance,
                                        &rs->a_expiration_date,
                                        &rs->sender_account);
  if (0 > qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
  {
    rs->had_ri = false;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.reserve_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.reserve_loss));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.withdraw_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.close_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.purse_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.open_fee_balance));
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (rs->total_in.currency,
                                          &rs->prev_balance.history_fee_balance));
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Creating fresh reserve `%s'\n",
                TALER_B2S (&rs->reserve_pub));
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  }
  rs->had_ri = true;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Auditor remembers reserve `%s' has balance %s\n",
              TALER_B2S (&rs->reserve_pub),
              TALER_amount2s (&rs->prev_balance.reserve_balance));
  return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
}


/**
 * 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;

  /**
   * Transaction status code, set to error codes if applicable.
   */
  enum GNUNET_DB_QueryStatus qs;

};


/**
 * Create a new reserve for @a reserve_pub in @a rc.
 *
 * @param[in,out] rc context to update
 * @param reserve_pub key for which to create a reserve
 * @return NULL on error
 */
static struct ReserveSummary *
setup_reserve (struct ReserveContext *rc,
               const struct TALER_ReservePublicKeyP *reserve_pub)
{
  struct ReserveSummary *rs;
  struct GNUNET_HashCode key;
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_CRYPTO_hash (reserve_pub,
                      sizeof (*reserve_pub),
                      &key);
  rs = GNUNET_CONTAINER_multihashmap_get (rc->reserves,
                                          &key);
  if (NULL != rs)
    return rs;
  rs = GNUNET_new (struct ReserveSummary);
  rs->reserve_pub = *reserve_pub;
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->total_in));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->total_out));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.reserve_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.reserve_loss));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.withdraw_fee_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.close_fee_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.purse_fee_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.open_fee_balance));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &rs->curr_balance.history_fee_balance));
  if (0 > (qs = load_auditor_reserve_summary (rs)))
  {
    GNUNET_free (rs);
    rc->qs = qs;
    return NULL;
  }
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap_put (rc->reserves,
                                                    &key,
                                                    rs,
                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  return rs;
}


/**
 * 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 wire_reference unique reference identifying the wire transfer
 * @param execution_date when did we receive the funds
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
handle_reserve_in (void *cls,
                   uint64_t rowid,
                   const struct TALER_ReservePublicKeyP *reserve_pub,
                   const struct TALER_Amount *credit,
                   const char *sender_account_details,
                   uint64_t wire_reference,
                   struct GNUNET_TIME_Timestamp execution_date)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;
  struct GNUNET_TIME_Timestamp expiry;

  (void) wire_reference;
  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_reserve_in_serial_id));
  TALER_ARL_USE_PP (reserves_reserve_in_serial_id) = rowid + 1;
  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (NULL == rs->sender_account)
    rs->sender_account = GNUNET_strdup (sender_account_details);
  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_to_timestamp (
    GNUNET_TIME_absolute_add (execution_date.abs_time,
                              idle_reserve_expiration_time));
  rs->a_expiration_date = GNUNET_TIME_timestamp_max (rs->a_expiration_date,
                                                     expiry);
  TALER_ARL_amount_add (&rs->total_in,
                        &rs->total_in,
                        credit);
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  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 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 enum GNUNET_GenericReturnValue
handle_reserve_out (void *cls,
                    uint64_t rowid,
                    const struct TALER_BlindedCoinHashP *h_blind_ev,
                    const struct TALER_DenominationPublicKey *denom_pub,
                    const struct TALER_ReservePublicKeyP *reserve_pub,
                    const struct TALER_ReserveSignatureP *reserve_sig,
                    struct GNUNET_TIME_Timestamp execution_date,
                    const struct TALER_Amount *amount_with_fee)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;
  const struct TALER_EXCHANGEDB_DenominationKeyInformation *issue;
  struct TALER_Amount auditor_amount_with_fee;
  enum GNUNET_DB_QueryStatus qs;
  struct TALER_DenominationHashP h_denom_pub;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_reserve_out_serial_id));
  TALER_ARL_USE_PP (reserves_reserve_out_serial_id) = rowid + 1;

  /* lookup denomination pub data (make sure denom_pub is valid, establish fees);
     initializes wsrd.h_denomination_pub! */
  qs = TALER_ARL_get_denomination_info (denom_pub,
                                        &issue,
                                        &h_denom_pub);
  if (0 > qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    if (GNUNET_DB_STATUS_HARD_ERROR == qs)
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Hard database error trying to get denomination %s (%s) from database!\n",
                  TALER_B2S (denom_pub),
                  TALER_amount2s (amount_with_fee));
    rc->qs = qs;
    return GNUNET_SYSERR;
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
  {
    report_row_inconsistency ("withdraw",
                              rowid,
                              "denomination key not found");
    if (TALER_ARL_do_abort ())
      return GNUNET_SYSERR;
    return GNUNET_OK;
  }

  /* check that execution date is within withdraw range for denom_pub  */
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Checking withdraw timing: %llu, expire: %llu, timing: %llu\n",
              (unsigned long long) issue->start.abs_time.abs_value_us,
              (unsigned long long) issue->expire_withdraw.abs_time.abs_value_us,
              (unsigned long long) execution_date.abs_time.abs_value_us);
  if (GNUNET_TIME_timestamp_cmp (issue->start,
                                 >,
                                 execution_date) ||
      GNUNET_TIME_timestamp_cmp (issue->expire_withdraw,
                                 <,
                                 execution_date))
  {
    TALER_ARL_report (denomination_key_validity_withdraw_inconsistencies,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rowid),
                        TALER_JSON_pack_time_abs_human ("execution_date",
                                                        execution_date.abs_time),
                        GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                    reserve_pub),
                        GNUNET_JSON_pack_data_auto ("denompub_h",
                                                    &h_denom_pub)));
  }

  /* check reserve_sig (first: setup remaining members of wsrd) */
  if (GNUNET_OK !=
      TALER_wallet_withdraw_verify (&h_denom_pub,
                                    amount_with_fee,
                                    h_blind_ev,
                                    reserve_pub,
                                    reserve_sig))
  {
    TALER_ARL_report (report_bad_sig_losses,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_string ("operation",
                                                 "withdraw"),
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rowid),
                        TALER_JSON_pack_amount ("loss",
                                                amount_with_fee),
                        GNUNET_JSON_pack_data_auto ("key_pub",
                                                    reserve_pub)));
    TALER_ARL_amount_add (&total_bad_sig_loss,
                          &total_bad_sig_loss,
                          amount_with_fee);
    if (TALER_ARL_do_abort ())
      return GNUNET_SYSERR;
    return GNUNET_OK;     /* exit function here, we cannot add this to the legitimate withdrawals */
  }

  TALER_ARL_amount_add (&auditor_amount_with_fee,
                        &issue->value,
                        &issue->fees.withdraw);
  if (0 !=
      TALER_amount_cmp (&auditor_amount_with_fee,
                        amount_with_fee))
  {
    report_row_inconsistency ("withdraw",
                              rowid,
                              "amount with fee from exchange does not match denomination value plus fee");
  }
  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Reserve `%s' reduced by %s from withdraw\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (&auditor_amount_with_fee));
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Increasing withdraw profits by fee %s\n",
              TALER_amount2s (&issue->fees.withdraw));
  TALER_ARL_amount_add (&rs->curr_balance.withdraw_fee_balance,
                        &rs->curr_balance.withdraw_fee_balance,
                        &issue->fees.withdraw);
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_withdraw_fee_revenue),
                        &TALER_ARL_USE_AB (reserves_withdraw_fee_revenue),
                        &issue->fees.withdraw);
  TALER_ARL_amount_add (&rs->total_out,
                        &rs->total_out,
                        &auditor_amount_with_fee);
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  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 recoup 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, denomination signature is
 *        already verified in #check_recoup()
 * @param denom_pub public key of the denomionation of @a coin
 * @param coin_sig signature with @e coin_pub of type #TALER_SIGNATURE_WALLET_COIN_RECOUP
 * @param coin_blind blinding factor used to blind the coin
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
handle_recoup_by_reserve (
  void *cls,
  uint64_t rowid,
  struct GNUNET_TIME_Timestamp timestamp,
  const struct TALER_Amount *amount,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  const struct TALER_CoinPublicInfo *coin,
  const struct TALER_DenominationPublicKey *denom_pub,
  const struct TALER_CoinSpendSignatureP *coin_sig,
  const union GNUNET_CRYPTO_BlindingSecretP *coin_blind)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;
  struct GNUNET_TIME_Timestamp expiry;
  struct TALER_MasterSignatureP msig;
  uint64_t rev_rowid;
  enum GNUNET_DB_QueryStatus qs;
  const char *rev;

  (void) denom_pub;
  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_reserve_recoup_serial_id));
  TALER_ARL_USE_PP (reserves_reserve_recoup_serial_id) = rowid + 1;
  /* We know that denom_pub matches denom_pub_hash because this
     is how the SQL statement joined the tables. */
  if (GNUNET_OK !=
      TALER_wallet_recoup_verify (&coin->denom_pub_hash,
                                  coin_blind,
                                  &coin->coin_pub,
                                  coin_sig))
  {
    TALER_ARL_report (report_bad_sig_losses,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_string ("operation",
                                                 "recoup"),
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rowid),
                        TALER_JSON_pack_amount ("loss",
                                                amount),
                        GNUNET_JSON_pack_data_auto ("key_pub",
                                                    &coin->coin_pub)));
    TALER_ARL_amount_add (&total_bad_sig_loss,
                          &total_bad_sig_loss,
                          amount);
  }

  /* check that the coin was eligible for recoup!*/
  rev = GNUNET_CONTAINER_multihashmap_get (rc->revoked,
                                           &coin->denom_pub_hash.hash);
  if (NULL == rev)
  {
    qs = TALER_ARL_edb->get_denomination_revocation (TALER_ARL_edb->cls,
                                                     &coin->denom_pub_hash,
                                                     &msig,
                                                     &rev_rowid);
    if (0 > qs)
    {
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      rc->qs = qs;
      return GNUNET_SYSERR;
    }
    if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    {
      report_row_inconsistency ("recoup",
                                rowid,
                                "denomination key not in revocation set");
      TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_reserve_loss),
                            &TALER_ARL_USE_AB (reserves_reserve_loss),
                            amount);
    }
    else
    {
      if (GNUNET_OK !=
          TALER_exchange_offline_denomination_revoke_verify (
            &coin->denom_pub_hash,
            &TALER_ARL_master_pub,
            &msig))
      {
        rev = "master signature invalid";
      }
      else
      {
        rev = "revoked";
      }
      GNUNET_assert (
        GNUNET_OK ==
        GNUNET_CONTAINER_multihashmap_put (
          rc->revoked,
          &coin->denom_pub_hash.hash,
          (void *) rev,
          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
    }
  }
  else
  {
    rev_rowid = 0;   /* reported elsewhere */
  }
  if ( (NULL != rev) &&
       (0 == strcmp (rev,
                     "master signature invalid")) )
  {
    TALER_ARL_report (report_bad_sig_losses,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_string ("operation",
                                                 "recoup-master"),
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rev_rowid),
                        TALER_JSON_pack_amount ("loss",
                                                amount),
                        GNUNET_JSON_pack_data_auto ("key_pub",
                                                    &TALER_ARL_master_pub)));
    TALER_ARL_amount_add (&total_bad_sig_loss,
                          &total_bad_sig_loss,
                          amount);
  }

  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  TALER_ARL_amount_add (&rs->total_in,
                        &rs->total_in,
                        amount);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional /recoup value to for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (amount));
  expiry = GNUNET_TIME_absolute_to_timestamp (
    GNUNET_TIME_absolute_add (timestamp.abs_time,
                              idle_reserve_expiration_time));
  rs->a_expiration_date = GNUNET_TIME_timestamp_max (rs->a_expiration_date,
                                                     expiry);
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  return GNUNET_OK;
}


/**
 * Obtain the closing fee for a transfer at @a time for target
 * @a receiver_account.
 *
 * @param receiver_account payto:// URI of the target account
 * @param atime when was the transfer made
 * @param[out] fee set to the closing fee
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
get_closing_fee (const char *receiver_account,
                 struct GNUNET_TIME_Timestamp atime,
                 struct TALER_Amount *fee)
{
  struct TALER_MasterSignatureP master_sig;
  struct GNUNET_TIME_Timestamp start_date;
  struct GNUNET_TIME_Timestamp end_date;
  struct TALER_WireFeeSet fees;
  char *method;

  method = TALER_payto_get_method (receiver_account);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Method is `%s'\n",
              method);
  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT !=
      TALER_ARL_edb->get_wire_fee (TALER_ARL_edb->cls,
                                   method,
                                   atime,
                                   &start_date,
                                   &end_date,
                                   &fees,
                                   &master_sig))
  {
    char *diag;

    GNUNET_asprintf (&diag,
                     "closing fee for `%s' unavailable at %s\n",
                     method,
                     GNUNET_TIME_timestamp2s (atime));
    report_row_inconsistency ("closing-fee",
                              atime.abs_time.abs_value_us,
                              diag);
    GNUNET_free (diag);
    GNUNET_free (method);
    return GNUNET_SYSERR;
  }
  *fee = fees.closing;
  GNUNET_free (method);
  return GNUNET_OK;
}


/**
 * Function called about reserve opening operations.
 *
 * @param cls closure
 * @param rowid row identifier used to uniquely identify the reserve closing operation
 * @param reserve_payment how much to pay from the
 *        reserve's own balance for opening the reserve
 * @param request_timestamp when was the request created
 * @param reserve_expiration desired expiration time for the reserve
 * @param purse_limit minimum number of purses the client
 *       wants to have concurrently open for this reserve
 * @param reserve_pub public key of the reserve
 * @param reserve_sig signature affirming the operation
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
handle_reserve_open (
  void *cls,
  uint64_t rowid,
  const struct TALER_Amount *reserve_payment,
  struct GNUNET_TIME_Timestamp request_timestamp,
  struct GNUNET_TIME_Timestamp reserve_expiration,
  uint32_t purse_limit,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  const struct TALER_ReserveSignatureP *reserve_sig)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_reserve_open_serial_id));
  TALER_ARL_USE_PP (reserves_reserve_open_serial_id) = rowid + 1;

  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_wallet_reserve_open_verify (reserve_payment,
                                        request_timestamp,
                                        reserve_expiration,
                                        purse_limit,
                                        reserve_pub,
                                        reserve_sig))
  {
    TALER_ARL_report (report_bad_sig_losses,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_string ("operation",
                                                 "reserve-open"),
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rowid),
                        TALER_JSON_pack_amount ("loss",
                                                reserve_payment),
                        GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                    reserve_pub)));
    TALER_ARL_amount_add (&total_bad_sig_loss,
                          &total_bad_sig_loss,
                          reserve_payment);
    return GNUNET_OK;
  }
  TALER_ARL_amount_add (&rs->curr_balance.open_fee_balance,
                        &rs->curr_balance.open_fee_balance,
                        reserve_payment);
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_open_fee_revenue),
                        &TALER_ARL_USE_AB (reserves_open_fee_revenue),
                        reserve_payment);
  TALER_ARL_amount_add (&rs->total_out,
                        &rs->total_out,
                        reserve_payment);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional open operation for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (reserve_payment));
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  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
 * @param close_request_row which close request triggered the operation?
 *         0 if it was a timeout
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
handle_reserve_closed (
  void *cls,
  uint64_t rowid,
  struct GNUNET_TIME_Timestamp execution_date,
  const struct TALER_Amount *amount_with_fee,
  const struct TALER_Amount *closing_fee,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  const char *receiver_account,
  const struct TALER_WireTransferIdentifierRawP *transfer_details,
  uint64_t close_request_row)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;

  (void) transfer_details;
  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_reserve_close_serial_id));
  TALER_ARL_USE_PP (reserves_reserve_close_serial_id) = rowid + 1;

  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  {
    struct TALER_Amount expected_fee;

    /* verify closing_fee is correct! */
    if (GNUNET_OK !=
        get_closing_fee (receiver_account,
                         execution_date,
                         &expected_fee))
    {
      GNUNET_break (0);
    }
    else if (0 != TALER_amount_cmp (&expected_fee,
                                    closing_fee))
    {
      report_amount_arithmetic_inconsistency (
        "closing aggregation fee",
        rowid,
        closing_fee,
        &expected_fee,
        1);
    }
  }

  TALER_ARL_amount_add (&rs->curr_balance.close_fee_balance,
                        &rs->curr_balance.close_fee_balance,
                        closing_fee);
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_close_fee_revenue),
                        &TALER_ARL_USE_AB (reserves_close_fee_revenue),
                        closing_fee);
  TALER_ARL_amount_add (&rs->total_out,
                        &rs->total_out,
                        amount_with_fee);
  if (0 != close_request_row)
  {
    struct TALER_ReserveSignatureP reserve_sig;
    struct GNUNET_TIME_Timestamp request_timestamp;
    struct TALER_Amount close_balance;
    struct TALER_Amount close_fee;
    char *payto_uri;
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_edb->select_reserve_close_request_info (
      TALER_ARL_edb->cls,
      reserve_pub,
      close_request_row,
      &reserve_sig,
      &request_timestamp,
      &close_balance,
      &close_fee,
      &payto_uri);
    if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != qs)
    {
      report_row_inconsistency ("reserves_close",
                                rowid,
                                "reserve close request unknown");
    }
    else
    {
      struct TALER_PaytoHashP h_payto;

      TALER_payto_hash (payto_uri,
                        &h_payto);
      if (GNUNET_OK !=
          TALER_wallet_reserve_close_verify (
            request_timestamp,
            &h_payto,
            reserve_pub,
            &reserve_sig))
      {
        TALER_ARL_report (report_bad_sig_losses,
                          GNUNET_JSON_PACK (
                            GNUNET_JSON_pack_string ("operation",
                                                     "close-request"),
                            GNUNET_JSON_pack_uint64 ("row",
                                                     close_request_row),
                            TALER_JSON_pack_amount ("loss",
                                                    amount_with_fee),
                            GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                        reserve_pub)));
        TALER_ARL_amount_add (&total_bad_sig_loss,
                              &total_bad_sig_loss,
                              amount_with_fee);
      }
    }
    if ( (NULL == payto_uri) &&
         (NULL == rs->sender_account) )
    {
      GNUNET_break (! rs->had_ri);
      report_row_inconsistency ("reserves_close",
                                rowid,
                                "target account not verified, auditor does not know reserve");
    }
    if (NULL == payto_uri)
    {
      if ( (NULL == rs->sender_account) ||
           (0 != strcmp (rs->sender_account,
                         receiver_account)) )
      {
        report_row_inconsistency ("reserves_close",
                                  rowid,
                                  "target account does not match origin account");
      }
    }
    else
    {
      if (0 != strcmp (payto_uri,
                       receiver_account))
      {
        report_row_inconsistency ("reserves_close",
                                  rowid,
                                  "target account does not match origin account");
      }
    }
    GNUNET_free (payto_uri);
  }
  else
  {
    if (NULL == rs->sender_account)
    {
      GNUNET_break (! rs->had_ri);
      report_row_inconsistency ("reserves_close",
                                rowid,
                                "target account not verified, auditor does not know reserve");
    }
    else if (0 != strcmp (rs->sender_account,
                          receiver_account))
    {
      report_row_inconsistency ("reserves_close",
                                rowid,
                                "target account does not match origin account");
    }
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Additional closing operation for reserve `%s' of %s\n",
              TALER_B2S (reserve_pub),
              TALER_amount2s (amount_with_fee));
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  return GNUNET_OK;
}


/**
 * Function called with details about account merge requests that have been
 * made, with the goal of accounting for the merge fee paid by the reserve (if
 * applicable).
 *
 * @param cls closure
 * @param rowid unique serial ID for the deposit in our DB
 * @param reserve_pub reserve affected by the merge
 * @param purse_pub purse being merged
 * @param h_contract_terms hash over contract of the purse
 * @param purse_expiration when would the purse expire
 * @param amount total amount in the purse
 * @param min_age minimum age of all coins deposited into the purse
 * @param flags how was the purse created
 * @param purse_fee if a purse fee was paid, how high is it
 * @param merge_timestamp when was the merge approved
 * @param reserve_sig signature by reserve approving the merge
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
handle_account_merged (
  void *cls,
  uint64_t rowid,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  const struct TALER_PurseContractPublicKeyP *purse_pub,
  const struct TALER_PrivateContractHashP *h_contract_terms,
  struct GNUNET_TIME_Timestamp purse_expiration,
  const struct TALER_Amount *amount,
  uint32_t min_age,
  enum TALER_WalletAccountMergeFlags flags,
  const struct TALER_Amount *purse_fee,
  struct GNUNET_TIME_Timestamp merge_timestamp,
  const struct TALER_ReserveSignatureP *reserve_sig)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;

  /* should be monotonically increasing */
  GNUNET_assert (rowid >= TALER_ARL_USE_PP (reserves_account_merges_serial_id));
  TALER_ARL_USE_PP (reserves_account_merges_serial_id) = rowid + 1;
  if (GNUNET_OK !=
      TALER_wallet_account_merge_verify (merge_timestamp,
                                         purse_pub,
                                         purse_expiration,
                                         h_contract_terms,
                                         amount,
                                         purse_fee,
                                         min_age,
                                         flags,
                                         reserve_pub,
                                         reserve_sig))
  {
    TALER_ARL_report (report_bad_sig_losses,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_string ("operation",
                                                 "account-merge"),
                        GNUNET_JSON_pack_uint64 ("row",
                                                 rowid),
                        TALER_JSON_pack_amount ("loss",
                                                purse_fee),
                        GNUNET_JSON_pack_data_auto ("key_pub",
                                                    reserve_pub)));
    TALER_ARL_amount_add (&total_bad_sig_loss,
                          &total_bad_sig_loss,
                          purse_fee);
    return GNUNET_OK;
  }
  if ( (flags & TALER_WAMF_MERGE_MODE_MASK) !=
       TALER_WAMF_MODE_CREATE_WITH_PURSE_FEE)
    return GNUNET_OK; /* no impact on reserve balance */
  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_purse_fee_revenue),
                        &TALER_ARL_USE_AB (reserves_purse_fee_revenue),
                        purse_fee);
  TALER_ARL_amount_add (&rs->curr_balance.purse_fee_balance,
                        &rs->curr_balance.purse_fee_balance,
                        purse_fee);
  TALER_ARL_amount_add (&rs->total_out,
                        &rs->total_out,
                        purse_fee);
  return GNUNET_OK;
}


/**
 * Function called with details about a purse that was merged into an account.
 * Only updates the reserve balance, the actual verifications are done in the
 * purse helper.
 *
 * @param cls closure
 * @param rowid unique serial ID for the refund in our DB
 * @param purse_pub public key of the purse
 * @param reserve_pub which reserve is the purse credited to
 * @param purse_value what is the target value of the purse
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
purse_decision_cb (void *cls,
                   uint64_t rowid,
                   const struct TALER_PurseContractPublicKeyP *purse_pub,
                   const struct TALER_ReservePublicKeyP *reserve_pub,
                   const struct TALER_Amount *purse_value)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs;

  GNUNET_assert (rowid >= TALER_ARL_USE_PP (
                   reserves_purse_decisions_serial_id));                         /* should be monotonically increasing */
  TALER_ARL_USE_PP (reserves_purse_decisions_serial_id) = rowid + 1;
  rs = setup_reserve (rc,
                      reserve_pub);
  if (NULL == rs)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  TALER_ARL_amount_add (&rs->total_in,
                        &rs->total_in,
                        purse_value);
  if (TALER_ARL_do_abort ())
    return GNUNET_SYSERR;
  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 enum GNUNET_GenericReturnValue
verify_reserve_balance (void *cls,
                        const struct GNUNET_HashCode *key,
                        void *value)
{
  struct ReserveContext *rc = cls;
  struct ReserveSummary *rs = value;
  struct TALER_Amount mbalance;
  struct TALER_Amount nbalance;
  enum GNUNET_DB_QueryStatus qs;
  enum GNUNET_GenericReturnValue ret;

  ret = GNUNET_OK;
  /* Check our reserve summary balance calculation shows that
     the reserve balance is acceptable (i.e. non-negative) */
  TALER_ARL_amount_add (&mbalance,
                        &rs->total_in,
                        &rs->prev_balance.reserve_balance);
  if (TALER_ARL_SR_INVALID_NEGATIVE ==
      TALER_ARL_amount_subtract_neg (&nbalance,
                                     &mbalance,
                                     &rs->total_out))
  {
    struct TALER_Amount loss;

    TALER_ARL_amount_subtract (&loss,
                               &rs->total_out,
                               &mbalance);
    TALER_ARL_amount_add (&rs->curr_balance.reserve_loss,
                          &rs->prev_balance.reserve_loss,
                          &loss);
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_reserve_loss),
                          &TALER_ARL_USE_AB (reserves_reserve_loss),
                          &loss);
    TALER_ARL_report (report_reserve_balance_insufficient_inconsistencies,
                      GNUNET_JSON_PACK (
                        GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                    &rs->reserve_pub),
                        TALER_JSON_pack_amount ("loss",
                                                &loss)));
    /* Continue with a reserve balance of zero */
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (TALER_ARL_currency,
                                          &rs->curr_balance.reserve_balance));
  }
  else
  {
    /* Update remaining reserve balance! */
    rs->curr_balance.reserve_balance = nbalance;
  }

  if (internal_checks)
  {
    /* Now check OUR balance calculation vs. the one the exchange has
       in its database. This can only be done when we are doing an
       internal audit, as otherwise the balance of the 'reserves' table
       is not replicated at the auditor. */
    struct TALER_EXCHANGEDB_Reserve reserve;

    reserve.pub = rs->reserve_pub;
    qs = TALER_ARL_edb->reserves_get (TALER_ARL_edb->cls,
                                      &reserve);
    if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != qs)
    {
      /* If the exchange doesn't have this reserve in the summary, it
         is like the exchange 'lost' that amount from its records,
         making an illegitimate gain over the amount it dropped.
         We don't add the amount to some total simply because it is
         not an actualized gain and could be trivially corrected by
         restoring the summary. */
      TALER_ARL_report (report_reserve_balance_insufficient_inconsistencies,
                        GNUNET_JSON_PACK (
                          GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                      &rs->reserve_pub),
                          TALER_JSON_pack_amount ("gain",
                                                  &nbalance)));
      if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
      {
        GNUNET_break (0);
        qs = GNUNET_DB_STATUS_HARD_ERROR;
      }
      rc->qs = qs;
    }
    else
    {
      /* Check that exchange's balance matches our expected balance for the reserve */
      if (0 != TALER_amount_cmp (&rs->curr_balance.reserve_balance,
                                 &reserve.balance))
      {
        struct TALER_Amount delta;

        if (0 < TALER_amount_cmp (&rs->curr_balance.reserve_balance,
                                  &reserve.balance))
        {
          /* balance > reserve.balance */
          TALER_ARL_amount_subtract (&delta,
                                     &rs->curr_balance.reserve_balance,
                                     &reserve.balance);
          TALER_ARL_amount_add (&total_balance_summary_delta_plus,
                                &total_balance_summary_delta_plus,
                                &delta);
        }
        else
        {
          /* balance < reserve.balance */
          TALER_ARL_amount_subtract (&delta,
                                     &reserve.balance,
                                     &rs->curr_balance.reserve_balance);
          TALER_ARL_amount_add (&total_balance_summary_delta_minus,
                                &total_balance_summary_delta_minus,
                                &delta);
        }
        TALER_ARL_report (report_reserve_balance_summary_wrong_inconsistencies,
                          GNUNET_JSON_PACK (
                            GNUNET_JSON_pack_data_auto ("reserve_pub",
                                                        &rs->reserve_pub),
                            TALER_JSON_pack_amount ("exchange",
                                                    &reserve.balance),
                            TALER_JSON_pack_amount ("auditor",
                                                    &rs->curr_balance.
                                                    reserve_balance)));
      }
    }
  }   /* end of 'if (internal_checks)' */

  /* Check that reserve is being closed if it is past its expiration date
     (and the closing fee would not exceed the remaining balance) */
  if (GNUNET_TIME_relative_cmp (CLOSING_GRACE_PERIOD,
                                <,
                                GNUNET_TIME_absolute_get_duration (
                                  rs->a_expiration_date.abs_time)))
  {
    /* Reserve is expired */
    struct TALER_Amount cfee;

    if ( (NULL != rs->sender_account) &&
         (GNUNET_OK ==
          get_closing_fee (rs->sender_account,
                           rs->a_expiration_date,
                           &cfee)) )
    {
      /* We got the closing fee */
      if (1 == TALER_amount_cmp (&nbalance,
                                 &cfee))
      {
        /* remaining balance (according to us) exceeds closing fee */
        TALER_ARL_amount_add (&total_balance_reserve_not_closed,
                              &total_balance_reserve_not_closed,
                              &nbalance);
        TALER_ARL_report (
          report_reserve_not_closed_inconsistencies,
          GNUNET_JSON_PACK (
            GNUNET_JSON_pack_data_auto ("reserve_pub",
                                        &rs->reserve_pub),
            TALER_JSON_pack_amount ("balance",
                                    &nbalance),
            TALER_JSON_pack_time_abs_human ("expiration_time",
                                            rs->a_expiration_date.abs_time)));
      }
    }
    else
    {
      /* We failed to determine the closing fee, complain! */
      TALER_ARL_amount_add (&total_balance_reserve_not_closed,
                            &total_balance_reserve_not_closed,
                            &nbalance);
      TALER_ARL_report (
        report_reserve_not_closed_inconsistencies,
        GNUNET_JSON_PACK (
          GNUNET_JSON_pack_data_auto ("reserve_pub",
                                      &rs->reserve_pub),
          TALER_JSON_pack_amount ("balance",
                                  &nbalance),
          TALER_JSON_pack_time_abs_human ("expiration_time",
                                          rs->a_expiration_date.abs_time),
          GNUNET_JSON_pack_string ("diagnostic",
                                   "could not determine closing fee")));
    }
  }

  /* We already computed the 'new' balance in 'curr_balance'
     to include the previous balance, so this one is just
     an assignment, not adding up! */
  rs->prev_balance.reserve_balance = rs->curr_balance.reserve_balance;

  /* Add up new totals to previous totals  */
  TALER_ARL_amount_add (&rs->prev_balance.reserve_loss,
                        &rs->prev_balance.reserve_loss,
                        &rs->curr_balance.reserve_loss);
  TALER_ARL_amount_add (&rs->prev_balance.withdraw_fee_balance,
                        &rs->prev_balance.withdraw_fee_balance,
                        &rs->curr_balance.withdraw_fee_balance);
  TALER_ARL_amount_add (&rs->prev_balance.close_fee_balance,
                        &rs->prev_balance.close_fee_balance,
                        &rs->curr_balance.close_fee_balance);
  TALER_ARL_amount_add (&rs->prev_balance.purse_fee_balance,
                        &rs->prev_balance.purse_fee_balance,
                        &rs->curr_balance.purse_fee_balance);
  TALER_ARL_amount_add (&rs->prev_balance.open_fee_balance,
                        &rs->prev_balance.open_fee_balance,
                        &rs->curr_balance.open_fee_balance);
  TALER_ARL_amount_add (&rs->prev_balance.history_fee_balance,
                        &rs->prev_balance.history_fee_balance,
                        &rs->curr_balance.history_fee_balance);

  /* Update global balance: add incoming first, then try
     to subtract outgoing... */
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (reserves_reserve_total_balance),
                        &TALER_ARL_USE_AB (reserves_reserve_total_balance),
                        &rs->total_in);
  {
    struct TALER_Amount r;

    if (TALER_ARL_SR_INVALID_NEGATIVE ==
        TALER_ARL_amount_subtract_neg (&r,
                                       &TALER_ARL_USE_AB (
                                         reserves_reserve_total_balance),
                                       &rs->total_out))
    {
      /* We could not reduce our total balance, i.e. exchange allowed IN TOTAL (!)
         to be withdrawn more than it was IN TOTAL ever given (exchange balance
         went negative!).  Woopsie. Calculate how badly it went and log. */
      report_amount_arithmetic_inconsistency ("global escrow balance",
                                              0,
                                              &TALER_ARL_USE_AB (
                                                reserves_reserve_total_balance),                   /* what we had */
                                              &rs->total_out,   /* what we needed */
                                              0 /* specific profit/loss does not apply to the total summary */);
      /* We unexpectedly went negative, so a sane value to continue from
         would be zero. */
      GNUNET_assert (GNUNET_OK ==
                     TALER_amount_set_zero (TALER_ARL_currency,
                                            &TALER_ARL_USE_AB (
                                              reserves_reserve_total_balance)));
    }
    else
    {
      TALER_ARL_USE_AB (reserves_reserve_total_balance) = r;
    }
  }

  if (TALER_amount_is_zero (&rs->prev_balance.reserve_balance))
  {
    /* 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 zero, dropping it\n",
                  TALER_B2S (&rs->reserve_pub));
      qs = TALER_ARL_adb->del_reserve_info (TALER_ARL_adb->cls,
                                            &rs->reserve_pub);
      if (0 >= qs)
      {
        GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
        ret = GNUNET_SYSERR;
        rc->qs = qs;
      }
    }
    else
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Final balance of reserve `%s' is zero, no need to remember it\n",
                  TALER_B2S (&rs->reserve_pub));
    }
  }
  else
  {
    /* balance is non-zero, persist for future audits */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Remembering final balance of reserve `%s' as %s\n",
                TALER_B2S (&rs->reserve_pub),
                TALER_amount2s (&rs->prev_balance.reserve_balance));
    if (rs->had_ri)
      qs = TALER_ARL_adb->update_reserve_info (TALER_ARL_adb->cls,
                                               &rs->reserve_pub,
                                               &rs->prev_balance,
                                               rs->a_expiration_date);
    else
      qs = TALER_ARL_adb->insert_reserve_info (TALER_ARL_adb->cls,
                                               &rs->reserve_pub,
                                               &rs->prev_balance,
                                               rs->a_expiration_date,
                                               rs->sender_account);
    if (0 >= qs)
    {
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      ret = GNUNET_SYSERR;
      rc->qs = qs;
    }
  }
  /* now we can discard the cached entry */
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (rc->reserves,
                                                       key,
                                                       rs));
  GNUNET_free (rs->sender_account);
  GNUNET_free (rs);
  return ret;
}


/**
 * Analyze reserves for being well-formed.
 *
 * @param cls NULL
 * @return transaction status code
 */
static enum GNUNET_DB_QueryStatus
analyze_reserves (void *cls)
{
  struct ReserveContext rc;
  enum GNUNET_DB_QueryStatus qsx;
  enum GNUNET_DB_QueryStatus qs;
  enum GNUNET_DB_QueryStatus qsp;

  (void) cls;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Analyzing reserves\n");
  qsp = TALER_ARL_adb->get_auditor_progress (
    TALER_ARL_adb->cls,
    TALER_ARL_GET_PP (reserves_reserve_in_serial_id),
    TALER_ARL_GET_PP (reserves_reserve_out_serial_id),
    TALER_ARL_GET_PP (reserves_reserve_recoup_serial_id),
    TALER_ARL_GET_PP (reserves_reserve_open_serial_id),
    TALER_ARL_GET_PP (reserves_reserve_close_serial_id),
    TALER_ARL_GET_PP (reserves_purse_decisions_serial_id),
    TALER_ARL_GET_PP (reserves_account_merges_serial_id),
    TALER_ARL_GET_PP (reserves_history_requests_serial_id),
    NULL);
  if (0 > qsp)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qsp);
    return qsp;
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qsp)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
                "First analysis using this auditor, starting audit from scratch\n");
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Resuming reserve audit at %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu\n",
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_reserve_in_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_reserve_out_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_reserve_recoup_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_reserve_open_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_reserve_close_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_purse_decisions_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_account_merges_serial_id),
                (unsigned long long) TALER_ARL_USE_PP (
                  reserves_history_requests_serial_id));
  }
  rc.qs = GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
  qsx = TALER_ARL_adb->get_balance (
    TALER_ARL_adb->cls,
    TALER_ARL_GET_AB (reserves_reserve_total_balance),
    TALER_ARL_GET_AB (reserves_reserve_loss),
    TALER_ARL_GET_AB (reserves_withdraw_fee_revenue),
    TALER_ARL_GET_AB (reserves_close_fee_revenue),
    TALER_ARL_GET_AB (reserves_purse_fee_revenue),
    TALER_ARL_GET_AB (reserves_open_fee_revenue),
    TALER_ARL_GET_AB (reserves_history_fee_revenue),
    NULL);
  if (qsx < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qsx);
    return qsx;
  }
  rc.reserves = GNUNET_CONTAINER_multihashmap_create (512,
                                                      GNUNET_NO);
  rc.revoked = GNUNET_CONTAINER_multihashmap_create (4,
                                                     GNUNET_NO);
  qs = TALER_ARL_edb->select_reserves_in_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_reserve_in_serial_id),
    &handle_reserve_in,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  qs = TALER_ARL_edb->select_withdrawals_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_reserve_out_serial_id),
    &handle_reserve_out,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  qs = TALER_ARL_edb->select_recoup_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_reserve_recoup_serial_id),
    &handle_recoup_by_reserve,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  qs = TALER_ARL_edb->select_reserve_open_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_reserve_open_serial_id),
    &handle_reserve_open,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  qs = TALER_ARL_edb->select_reserve_closed_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_reserve_close_serial_id),
    &handle_reserve_closed,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  /* process purse_decisions (to credit reserve) */
  if (0 >
      (qs = TALER_ARL_edb->select_purse_decisions_above_serial_id (
         TALER_ARL_edb->cls,
         TALER_ARL_USE_PP (reserves_purse_decisions_serial_id),
         false, /* only go for merged purses! */
         &purse_decision_cb,
         &rc)))
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  if (0 > rc.qs)
    return rc.qs;
  /* Charge purse fee! */
  qs = TALER_ARL_edb->select_account_merges_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (reserves_account_merges_serial_id),
    &handle_account_merged,
    &rc);
  if (qs < 0)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  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_DB_STATUS_SUCCESS_ONE_RESULT != rc.qs)
    return qs;
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qsx)
  {
    qs = TALER_ARL_adb->insert_balance (
      TALER_ARL_adb->cls,
      TALER_ARL_SET_AB (reserves_reserve_total_balance),
      TALER_ARL_SET_AB (reserves_reserve_loss),
      TALER_ARL_SET_AB (reserves_withdraw_fee_revenue),
      TALER_ARL_SET_AB (reserves_close_fee_revenue),
      TALER_ARL_SET_AB (reserves_purse_fee_revenue),
      TALER_ARL_SET_AB (reserves_open_fee_revenue),
      TALER_ARL_SET_AB (reserves_history_fee_revenue),
      NULL);
  }
  else
  {
    qs = TALER_ARL_adb->update_balance (
      TALER_ARL_adb->cls,
      TALER_ARL_SET_AB (reserves_reserve_total_balance),
      TALER_ARL_SET_AB (reserves_reserve_loss),
      TALER_ARL_SET_AB (reserves_withdraw_fee_revenue),
      TALER_ARL_SET_AB (reserves_close_fee_revenue),
      TALER_ARL_SET_AB (reserves_purse_fee_revenue),
      TALER_ARL_SET_AB (reserves_open_fee_revenue),
      TALER_ARL_SET_AB (reserves_history_fee_revenue),
      NULL);
  }
  if (0 >= qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qsp)
    qs = TALER_ARL_adb->update_auditor_progress (
      TALER_ARL_adb->cls,
      TALER_ARL_SET_PP (reserves_reserve_in_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_out_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_recoup_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_open_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_close_serial_id),
      TALER_ARL_SET_PP (reserves_purse_decisions_serial_id),
      TALER_ARL_SET_PP (reserves_account_merges_serial_id),
      TALER_ARL_SET_PP (reserves_history_requests_serial_id),
      NULL);
  else
    qs = TALER_ARL_adb->insert_auditor_progress (
      TALER_ARL_adb->cls,
      TALER_ARL_SET_PP (reserves_reserve_in_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_out_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_recoup_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_open_serial_id),
      TALER_ARL_SET_PP (reserves_reserve_close_serial_id),
      TALER_ARL_SET_PP (reserves_purse_decisions_serial_id),
      TALER_ARL_SET_PP (reserves_account_merges_serial_id),
      TALER_ARL_SET_PP (reserves_history_requests_serial_id),
      NULL);
  if (0 >= qs)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Failed to update auditor DB, not recording progress\n");
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Concluded reserve audit step at %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu\n",
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_reserve_in_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_reserve_out_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_reserve_recoup_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_reserve_open_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_reserve_close_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_purse_decisions_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_account_merges_serial_id),
              (unsigned long long) TALER_ARL_USE_PP (
                reserves_history_requests_serial_id));
  return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
}


/**
 * 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)
{
  (void) cls;
  (void) args;
  (void) cfgfile;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Launching auditor\n");
  if (GNUNET_OK !=
      TALER_ARL_init (c))
  {
    global_ret = EXIT_FAILURE;
    return;
  }
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_time (TALER_ARL_cfg,
                                           "exchangedb",
                                           "IDLE_RESERVE_EXPIRATION_TIME",
                                           &idle_reserve_expiration_time))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               "exchangedb",
                               "IDLE_RESERVE_EXPIRATION_TIME");
    global_ret = EXIT_FAILURE;
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Starting audit\n");
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_reserve_total_balance)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_reserve_loss)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_withdraw_fee_revenue)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_close_fee_revenue)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_purse_fee_revenue)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_open_fee_revenue)));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &TALER_ARL_USE_AB (
                                          reserves_history_fee_revenue)));
  // REVIEW:
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_balance_summary_delta_plus));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_balance_summary_delta_minus));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_arithmetic_delta_plus));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_arithmetic_delta_minus));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_balance_reserve_not_closed));
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &total_bad_sig_loss));

  GNUNET_assert (NULL !=
                 (report_row_inconsistencies = json_array ()));
  GNUNET_assert (NULL !=
                 (denomination_key_validity_withdraw_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_reserve_balance_summary_wrong_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_reserve_balance_insufficient_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_purse_balance_insufficient_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_reserve_not_closed_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_amount_arithmetic_inconsistencies
                    = json_array ()));
  GNUNET_assert (NULL !=
                 (report_bad_sig_losses = json_array ()));
  if (GNUNET_OK !=
      TALER_ARL_setup_sessions_and_run (&analyze_reserves,
                                        NULL))
  {
    global_ret = EXIT_FAILURE;
    return;
  }
  TALER_ARL_done (
    GNUNET_JSON_PACK (
      /* Tested in test-auditor.sh #3 */
      GNUNET_JSON_pack_array_steal (
        "reserve_balance_summary_wrong_inconsistencies",
        report_reserve_balance_summary_wrong_inconsistencies),
      TALER_JSON_pack_amount ("total_balance_summary_delta_plus",
                              &total_balance_summary_delta_plus),
      TALER_JSON_pack_amount ("total_balance_summary_delta_minus",
                              &total_balance_summary_delta_minus),
      /* Tested in test-auditor.sh #21 */
      TALER_JSON_pack_amount ("total_balance_reserve_not_closed",
                              &total_balance_reserve_not_closed),
      /* Tested in test-auditor.sh #7 */
      TALER_JSON_pack_amount ("total_bad_sig_loss",
                              &total_bad_sig_loss),
      TALER_JSON_pack_amount ("total_arithmetic_delta_plus",
                              &total_arithmetic_delta_plus),
      TALER_JSON_pack_amount ("total_arithmetic_delta_minus",
                              &total_arithmetic_delta_minus),

      /* Global 'balances' */
      TALER_JSON_pack_amount ("total_escrow_balance",
                              &TALER_ARL_USE_AB (
                                reserves_reserve_total_balance)),
      /* Tested in test-auditor.sh #3 */
      TALER_JSON_pack_amount ("total_irregular_loss",
                              &TALER_ARL_USE_AB (reserves_reserve_loss)),
      TALER_JSON_pack_amount ("total_withdraw_fee_income",
                              &TALER_ARL_USE_AB (
                                reserves_withdraw_fee_revenue)),
      TALER_JSON_pack_amount ("total_close_fee_income",
                              &TALER_ARL_USE_AB (reserves_close_fee_revenue)),
      TALER_JSON_pack_amount ("total_purse_fee_income",
                              &TALER_ARL_USE_AB (reserves_purse_fee_revenue)),
      TALER_JSON_pack_amount ("total_open_fee_income",
                              &TALER_ARL_USE_AB (reserves_open_fee_revenue)),
      TALER_JSON_pack_amount ("total_history_fee_income",
                              &TALER_ARL_USE_AB (reserves_history_fee_revenue)),

      /* Detailed report tables */
      GNUNET_JSON_pack_array_steal (
        "reserve_balance_insufficient_inconsistencies",
        report_reserve_balance_insufficient_inconsistencies),
      GNUNET_JSON_pack_array_steal (
        "purse_balance_insufficient_inconsistencies",
        report_purse_balance_insufficient_inconsistencies),
      /* Tested in test-auditor.sh #21 */
      GNUNET_JSON_pack_array_steal ("reserve_not_closed_inconsistencies",
                                    report_reserve_not_closed_inconsistencies),
      /* Tested in test-auditor.sh #7 */
      GNUNET_JSON_pack_array_steal ("bad_sig_losses",
                                    report_bad_sig_losses),
      /* Tested in test-revocation.sh #4 */
      GNUNET_JSON_pack_array_steal ("row_inconsistencies",
                                    report_row_inconsistencies),
      /* Tested in test-auditor.sh #23 */
      GNUNET_JSON_pack_array_steal (
        "denomination_key_validity_withdraw_inconsistencies",
        denomination_key_validity_withdraw_inconsistencies),
      GNUNET_JSON_pack_array_steal ("amount_arithmetic_inconsistencies",
                                    report_amount_arithmetic_inconsistencies),

      /* Information about audited range ... */
      TALER_JSON_pack_time_abs_human ("auditor_start_time",
                                      start_time),
      TALER_JSON_pack_time_abs_human ("auditor_end_time",
                                      GNUNET_TIME_absolute_get ()),
      GNUNET_JSON_pack_uint64 ("start_ppr_reserve_in_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_reserve_out_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_reserve_recoup_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_reserve_open_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_reserve_close_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_purse_decisions_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_account_merges_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("start_ppr_history_requests_serial_id",
                               0 /* no longer supported */),
      GNUNET_JSON_pack_uint64 ("end_ppr_reserve_in_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_reserve_in_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_reserve_out_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_reserve_out_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_reserve_recoup_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_reserve_recoup_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_reserve_open_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_reserve_open_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_reserve_close_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_reserve_close_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_purse_decisions_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_purse_decisions_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_account_merges_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_account_merges_serial_id)),
      GNUNET_JSON_pack_uint64 ("end_ppr_history_requests_serial_id",
                               TALER_ARL_USE_PP (
                                 reserves_history_requests_serial_id))));
}


/**
 * The main function to check the database's handling of reserves.
 *
 * @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_flag ('i',
                               "internal",
                               "perform checks only applicable for exchange-internal audits",
                               &internal_checks),
    GNUNET_GETOPT_option_flag ('t',
                               "test",
                               "run in test mode and exit when idle",
                               &test_mode),
    GNUNET_GETOPT_option_timetravel ('T',
                                     "timetravel"),
    GNUNET_GETOPT_OPTION_END
  };
  enum GNUNET_GenericReturnValue ret;

  /* 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 ();
  if (GNUNET_OK !=
      GNUNET_STRINGS_get_utf8_args (argc, argv,
                                    &argc, &argv))
    return EXIT_INVALIDARGUMENT;
  ret = GNUNET_PROGRAM_run (
    argc,
    argv,
    "taler-helper-auditor-reserves",
    gettext_noop ("Audit Taler exchange reserve handling"),
    options,
    &run,
    NULL);
  GNUNET_free_nz ((void *) argv);
  if (GNUNET_SYSERR == ret)
    return EXIT_INVALIDARGUMENT;
  if (GNUNET_NO == ret)
    return EXIT_SUCCESS;
  return global_ret;
}


/* end of taler-helper-auditor-reserves.c */