aboutsummaryrefslogtreecommitdiff
path: root/src/auditor/taler-helper-auditor-wire-debit.c
blob: e9e31fdc766e13bd157e47aaaa1325cb0d54b9d6 (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
/*
  This file is part of TALER
  Copyright (C) 2017-2024 Taler Systems SA

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

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

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file auditor/taler-helper-auditor-wire-debit.c
 * @brief audits that wire outgoing transfers match those from an exchange
 * database.
 * @author Christian Grothoff
 * @author Özgür Kesim
 *
 * - We check that the outgoing wire transfers match those
 *   given in the 'wire_out' and 'reserve_closures' tables;
 *   any outgoing transfer MUST have a prior justification,
 *   so if one is missing we flag it (and never remove it).
 * - We check that all wire transfers that should
 *   have been made, were actually made. If any were not made,
 *   we flag those, but may remove those flags if we later
 *   find that the wire transfers were made (wire transfers
 *   could be delayed due to AML/KYC or core-banking issues).
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_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"
#include "taler_dbevents.h"


/**
 * Maximum number of wire transfers we process per
 * (database) transaction.
 */
#define MAX_PER_TRANSACTION 1024

/**
 * How much do we allow the bank and the exchange to disagree about
 * timestamps? Should be sufficiently large to avoid bogus reports from deltas
 * created by imperfect clock synchronization and network delay.
 */
#define TIME_TOLERANCE GNUNET_TIME_relative_multiply ( \
          GNUNET_TIME_UNIT_MINUTES, \
          15)


/**
 * How long do we try to long-poll for bank wire transfers?
 */
#define MAX_LONGPOLL_DELAY GNUNET_TIME_relative_multiply ( \
          GNUNET_TIME_UNIT_HOURS, \
          1)


/**
 * How long do we wait between polling for bank wire transfers at the minimum?
 */
#define MIN_LONGPOLL_DELAY GNUNET_TIME_relative_multiply ( \
          GNUNET_TIME_UNIT_MINUTES, \
          5)


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


/**
 * Information we keep for each supported account.
 */
struct WireAccount
{
  /**
   * Accounts are kept in a DLL.
   */
  struct WireAccount *next;

  /**
   * Plugins are kept in a DLL.
   */
  struct WireAccount *prev;

  /**
   * Account details.
   */
  const struct TALER_EXCHANGEDB_AccountInfo *ai;

  /**
   * Active wire request for the transaction history.
   */
  struct TALER_BANK_DebitHistoryHandle *dhh;

  /**
   * Task to trigger @e dhh long-polling.
   */
  struct GNUNET_SCHEDULER_Task *dhh_task;

  /**
   * Time when we expect the current @e dhh long-poll
   * to finish and we thus could begin another one.
   */
  struct GNUNET_TIME_Absolute dhh_next;

  /**
   * Progress point for this account.
   */
  uint64_t last_wire_out_serial_id;

  /**
   * Initial progress point for this account.
   */
  uint64_t start_wire_out_serial_id;

  /**
   * Where we are in the outbound transaction history.
   */
  uint64_t wire_off_out;

  /**
   * Label under which we store our pp's reserve_in_serial_id.
   */
  char *label_wire_out_serial_id;

  /**
   * Label under which we store our wire_off_out.
   */
  char *label_wire_off_out;
};


/**
 * Information we track for a reserve being closed.
 */
struct ReserveClosure
{
  /**
   * Row in the reserves_closed table for this action.
   */
  uint64_t rowid;

  /**
   * When was the reserve closed?
   */
  struct GNUNET_TIME_Timestamp execution_date;

  /**
   * Amount transferred (amount remaining minus fee).
   */
  struct TALER_Amount amount;

  /**
   * Target account where the money was sent.
   */
  char *receiver_account;

  /**
   * Wire transfer subject used.
   */
  struct TALER_WireTransferIdentifierRawP wtid;
};


/**
 * Map from H(wtid,receiver_account) to `struct ReserveClosure` entries.
 */
static struct GNUNET_CONTAINER_MultiHashMap *reserve_closures;

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

/**
 * State of the current database transaction with
 * the auditor DB.
 */
static enum GNUNET_DB_QueryStatus global_qs;

/**
 * Map with information about outgoing wire transfers.
 * Maps hashes of the wire subjects (in binary encoding)
 * to `struct ReserveOutInfo`s.
 */
static struct GNUNET_CONTAINER_MultiHashMap *out_map;

/**
 * Head of list of wire accounts we still need to look at.
 */
static struct WireAccount *wa_head;

/**
 * Tail of list of wire accounts we still need to look at.
 */
static struct WireAccount *wa_tail;

/**
 * Last reserve_out / wire_out serial IDs seen.
 */
static TALER_ARL_DEF_PP (wire_reserve_close_id);

/**
 * Amount that is considered "tiny"
 */
static struct TALER_Amount tiny_amount;

/**
 * Total amount that was transferred too much from the exchange.
 */
static TALER_ARL_DEF_AB (total_bad_amount_out_plus);

/**
 * Total amount that was transferred too little from the exchange.
 */
static TALER_ARL_DEF_AB (total_bad_amount_out_minus);

/**
 * Total amount which the exchange did not transfer in time.
 */
static TALER_ARL_DEF_AB (total_amount_lag);

/**
 * Total amount of reserve closures which the exchange did not transfer in time.
 */
static TALER_ARL_DEF_AB (total_closure_amount_lag);

/**
 * Total amount affected by duplicate wire transfer
 * subjects.
 */
static TALER_ARL_DEF_AB (wire_debit_duplicate_transfer_subject_total);

/**
 * Total amount debited to exchange accounts.
 */
static TALER_ARL_DEF_AB (total_wire_out);

/**
 * Total amount of profits drained.
 */
static TALER_ARL_DEF_AB (total_drained);

/**
 * Amount of zero in our currency.
 */
static struct TALER_Amount zero;

/**
 * Handle to the context for interacting with the bank.
 */
static struct GNUNET_CURL_Context *ctx;

/**
 * Scheduler context for running the @e ctx.
 */
static struct GNUNET_CURL_RescheduleContext *rc;

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

/**
 * Should we ignore if the bank does not know our bank
 * account?
 */
static int ignore_account_404;

/**
 * Database event handler to wake us up again.
 */
static struct GNUNET_DB_EventHandler *eh;

/**
 * The auditors's configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;


/**
 * Entry in map with wire information we expect to obtain from the
 * #TALER_ARL_edb later.
 */
struct ReserveOutInfo
{

  /**
   * Hash of the wire transfer subject.
   */
  struct GNUNET_HashCode subject_hash;

  /**
   * Expected details about the wire transfer.
   */
  struct TALER_BANK_DebitDetails details;

};


/**
 * Free entry in #out_map.
 *
 * @param cls NULL
 * @param key unused key
 * @param value the `struct ReserveOutInfo` to free
 * @return #GNUNET_OK
 */
static enum GNUNET_GenericReturnValue
free_roi (void *cls,
          const struct GNUNET_HashCode *key,
          void *value)
{
  struct ReserveOutInfo *roi = value;

  (void) cls;
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (out_map,
                                                       key,
                                                       roi));
  GNUNET_free (roi);
  return GNUNET_OK;
}


/**
 * Free entry in #reserve_closures.
 *
 * @param cls NULL
 * @param key unused key
 * @param value the `struct ReserveClosure` to free
 * @return #GNUNET_OK
 */
static enum GNUNET_GenericReturnValue
free_rc (void *cls,
         const struct GNUNET_HashCode *key,
         void *value)
{
  struct ReserveClosure *rc = value;

  (void) cls;
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (reserve_closures,
                                                       key,
                                                       rc));
  GNUNET_free (rc->receiver_account);
  GNUNET_free (rc);
  return GNUNET_OK;
}


/**
 * Task run on shutdown.
 *
 * @param cls NULL
 */
static void
do_shutdown (void *cls)
{
  struct WireAccount *wa;

  (void) cls;
  if (NULL != eh)
  {
    TALER_ARL_adb->event_listen_cancel (eh);
    eh = NULL;
  }
  TALER_ARL_done ();
  if (NULL != reserve_closures)
  {
    GNUNET_CONTAINER_multihashmap_iterate (reserve_closures,
                                           &free_rc,
                                           NULL);
    GNUNET_CONTAINER_multihashmap_destroy (reserve_closures);
    reserve_closures = NULL;
  }
  if (NULL != out_map)
  {
    GNUNET_CONTAINER_multihashmap_iterate (out_map,
                                           &free_roi,
                                           NULL);
    GNUNET_CONTAINER_multihashmap_destroy (out_map);
    out_map = NULL;
  }
  while (NULL != (wa = wa_head))
  {
    if (NULL != wa->dhh_task)
    {
      GNUNET_SCHEDULER_cancel (wa->dhh_task);
      wa->dhh_task = NULL;
    }
    if (NULL != wa->dhh)
    {
      TALER_BANK_debit_history_cancel (wa->dhh);
      wa->dhh = NULL;
    }
    GNUNET_CONTAINER_DLL_remove (wa_head,
                                 wa_tail,
                                 wa);
    GNUNET_free (wa->label_wire_out_serial_id);
    GNUNET_free (wa->label_wire_off_out);
    GNUNET_free (wa);
  }
  if (NULL != ctx)
  {
    GNUNET_CURL_fini (ctx);
    ctx = NULL;
  }
  if (NULL != rc)
  {
    GNUNET_CURL_gnunet_rc_destroy (rc);
    rc = NULL;
  }
  TALER_EXCHANGEDB_unload_accounts ();
  TALER_ARL_cfg = NULL;
}


/**
 * Detect any entries in #reserve_closures that were not yet
 * observed on the wire transfer side and update the progress
 * point accordingly.
 *
 * @param cls NULL
 * @param key unused key
 * @param value the `struct ReserveClosure` to free
 * @return #GNUNET_OK
 */
static enum GNUNET_GenericReturnValue
check_pending_rc (void *cls,
                  const struct GNUNET_HashCode *key,
                  void *value)
{
  struct ReserveClosure *rc = value;

  (void) cls;
  (void) key;
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_closure_amount_lag),
                        &TALER_ARL_USE_AB (total_closure_amount_lag),
                        &rc->amount);
  if (! TALER_amount_is_zero (&rc->amount))
  {
    struct TALER_AUDITORDB_ClosureLags cl = {
      .account = rc->receiver_account,
      .amount = rc->amount,
      .deadline = rc->execution_date.abs_time,
      .wtid = rc->wtid
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_auditor_closure_lags (
      TALER_ARL_adb->cls,
      &cl);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
  }
  TALER_ARL_USE_PP (wire_reserve_close_id)
    = GNUNET_MIN (TALER_ARL_USE_PP (wire_reserve_close_id),
                  rc->rowid);
  return GNUNET_OK;
}


/**
 * Compute the key under which a reserve closure for a given
 * @a receiver_account and @a wtid would be stored.
 *
 * @param receiver_account payto://-URI of the account
 * @param wtid wire transfer identifier used
 * @param[out] key set to the key
 */
static void
hash_rc (const char *receiver_account,
         const struct TALER_WireTransferIdentifierRawP *wtid,
         struct GNUNET_HashCode *key)
{
  size_t slen = strlen (receiver_account);
  char buf[sizeof (struct TALER_WireTransferIdentifierRawP) + slen];

  GNUNET_memcpy (buf,
                 wtid,
                 sizeof (*wtid));
  GNUNET_memcpy (&buf[sizeof (*wtid)],
                 receiver_account,
                 slen);
  GNUNET_CRYPTO_hash (buf,
                      sizeof (buf),
                      key);
}


/**
 * Start the database transactions and begin the audit.
 *
 * @return transaction status code
 */
static enum GNUNET_DB_QueryStatus
begin_transaction (void);


/**
 * Commit the transaction, checkpointing our progress in the auditor DB.
 *
 * @param qs transaction status so far
 */
static void
commit (enum GNUNET_DB_QueryStatus qs)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Transaction logic ended with status %d\n",
              qs);
  if (qs < 0)
    goto handle_db_error;
  qs = TALER_ARL_adb->update_balance (
    TALER_ARL_adb->cls,
    TALER_ARL_SET_AB (total_drained),
    TALER_ARL_SET_AB (total_wire_out),
    TALER_ARL_SET_AB (total_bad_amount_out_plus),
    TALER_ARL_SET_AB (total_bad_amount_out_minus),
    TALER_ARL_SET_AB (total_amount_lag),
    TALER_ARL_SET_AB (total_closure_amount_lag),
    TALER_ARL_SET_AB (wire_debit_duplicate_transfer_subject_total),
    TALER_ARL_SET_AB (total_wire_out),
    NULL);
  if (0 > qs)
    goto handle_db_error;
  qs = TALER_ARL_adb->insert_balance (
    TALER_ARL_adb->cls,
    TALER_ARL_SET_AB (total_drained),
    TALER_ARL_SET_AB (total_wire_out),
    TALER_ARL_SET_AB (total_bad_amount_out_plus),
    TALER_ARL_SET_AB (total_bad_amount_out_minus),
    TALER_ARL_SET_AB (total_amount_lag),
    TALER_ARL_SET_AB (total_closure_amount_lag),
    TALER_ARL_SET_AB (wire_debit_duplicate_transfer_subject_total),
    TALER_ARL_SET_AB (total_wire_out),
    NULL);
  if (0 > qs)
    goto handle_db_error;
  for (struct WireAccount *wa = wa_head;
       NULL != wa;
       wa = wa->next)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Transaction of account %s ends at %llu/%llu\n",
                wa->ai->section_name,
                (unsigned long long) wa->last_wire_out_serial_id,
                (unsigned long long) wa->wire_off_out);
    qs = TALER_ARL_adb->update_auditor_progress (
      TALER_ARL_adb->cls,
      wa->label_wire_out_serial_id,
      wa->last_wire_out_serial_id,
      wa->label_wire_off_out,
      wa->wire_off_out,
      NULL);
    if (0 > qs)
      goto handle_db_error;
    qs = TALER_ARL_adb->insert_auditor_progress (
      TALER_ARL_adb->cls,
      wa->label_wire_out_serial_id,
      wa->last_wire_out_serial_id,
      wa->label_wire_off_out,
      wa->wire_off_out,
      NULL);
    if (0 > qs)
      goto handle_db_error;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Transaction ends at %s=%llu for account `%s'\n",
                wa->label_wire_out_serial_id,
                (unsigned long long) wa->last_wire_out_serial_id,
                wa->ai->section_name);
  }
  GNUNET_CONTAINER_multihashmap_iterate (reserve_closures,
                                         &check_pending_rc,
                                         NULL);
  qs = TALER_ARL_adb->update_auditor_progress (
    TALER_ARL_adb->cls,
    TALER_ARL_SET_PP (wire_reserve_close_id),
    NULL);
  if (0 > qs)
    goto handle_db_error;
  qs = TALER_ARL_adb->insert_auditor_progress (
    TALER_ARL_adb->cls,
    TALER_ARL_SET_PP (wire_reserve_close_id),
    NULL);
  if (0 > qs)
    goto handle_db_error;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Concluded audit step at %llu\n",
              (unsigned long long) TALER_ARL_USE_PP (wire_reserve_close_id));
  qs = TALER_ARL_edb->commit (TALER_ARL_edb->cls);
  if (0 > qs)
    goto handle_db_error;
  qs = TALER_ARL_adb->commit (TALER_ARL_adb->cls);
  if (0 > qs)
    goto handle_db_error;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Transaction concluded!\n");
  if (1 == test_mode)
    GNUNET_SCHEDULER_shutdown ();
  return;
handle_db_error:
  TALER_ARL_adb->rollback (TALER_ARL_adb->cls);
  TALER_ARL_edb->rollback (TALER_ARL_edb->cls);
  for (unsigned int max_retries = 3; max_retries>0; max_retries--)
  {
    if (GNUNET_DB_STATUS_HARD_ERROR == qs)
      break;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Serialization issue, trying again\n");
    qs = begin_transaction ();
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Hard database error, terminating\n");
  GNUNET_SCHEDULER_shutdown ();
}


/**
 * Check that @a want is within #TIME_TOLERANCE of @a have.
 * Otherwise report an inconsistency in row @a rowid of @a table.
 *
 * @param table where is the inconsistency (if any)
 * @param rowid what is the row
 * @param want what is the expected time
 * @param have what is the time we got
 * @return true on success, false to abort
 */
static bool
check_time_difference (const char *table,
                       uint64_t rowid,
                       struct GNUNET_TIME_Timestamp want,
                       struct GNUNET_TIME_Timestamp have)
{
  struct GNUNET_TIME_Relative delta;
  char *details;

  if (GNUNET_TIME_timestamp_cmp (have, >, want))
    delta = GNUNET_TIME_absolute_get_difference (want.abs_time,
                                                 have.abs_time);
  else
    delta = GNUNET_TIME_absolute_get_difference (have.abs_time,
                                                 want.abs_time);
  if (GNUNET_TIME_relative_cmp (delta,
                                <=,
                                TIME_TOLERANCE))
    return true;

  GNUNET_asprintf (&details,
                   "execution date mismatch (%s)",
                   GNUNET_TIME_relative2s (delta,
                                           true));
  {
    struct TALER_AUDITORDB_RowMinorInconsistencies rmi = {
      .row_id = rowid,
      .diagnostic = details,
      .row_table = (char *) table
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_row_minor_inconsistencies (
      TALER_ARL_adb->cls,
      &rmi);

    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      GNUNET_free (details);
      return false;
    }
  }
  GNUNET_free (details);
  return true;
}


/**
 * Closure for #check_rc_matches
 */
struct CheckMatchContext
{

  /**
   * Reserve operation looking for a match
   */
  const struct ReserveOutInfo *roi;

  /**
   * Set to true if we found a match.
   */
  bool found;
};


/**
 * Check if any of the reserve closures match the given wire transfer.
 *
 * @param[in,out] cls a `struct CheckMatchContext`
 * @param key key of @a value in #reserve_closures
 * @param value a `struct ReserveClosure`
 */
static enum GNUNET_GenericReturnValue
check_rc_matches (void *cls,
                  const struct GNUNET_HashCode *key,
                  void *value)
{
  struct CheckMatchContext *ctx = cls;
  struct ReserveClosure *rc = value;

  if ((0 == GNUNET_memcmp (&ctx->roi->details.wtid,
                           &rc->wtid)) &&
      (0 == strcasecmp (rc->receiver_account,
                        ctx->roi->details.credit_account_uri)) &&
      (0 == TALER_amount_cmp (&rc->amount,
                              &ctx->roi->details.amount)))
  {
    if (! check_time_difference ("reserves_closures",
                                 rc->rowid,
                                 rc->execution_date,
                                 ctx->roi->details.execution_date))
    {
      free_rc (NULL,
               key,
               rc);
      return GNUNET_SYSERR;
    }
    ctx->found = true;
    free_rc (NULL,
             key,
             rc);
    return GNUNET_NO;
  }
  return GNUNET_OK;
}


/**
 * Maximum required length for make_missing_diag().
 */
#define MAX_DIAG_LEN 128

/**
 * Make diagnostic string for missing wire transfer.
 *
 * @param[out] diag where to write the diagnostic string
 * @param wtid wire transfer ID to include
 */
static void
make_missing_diag (char diag[MAX_DIAG_LEN],
                   const struct TALER_WireTransferIdentifierRawP *wtid)
{
  char *wtid_s;

  wtid_s = GNUNET_STRINGS_data_to_string_alloc (wtid,
                                                sizeof (*wtid));
  GNUNET_snprintf (diag,
                   MAX_DIAG_LEN,
                   "expected outgoing wire transfer %s missing",
                   wtid_s);
  GNUNET_free (wtid_s);
}


/**
 * Check if an existing report on a missing wire
 * out operation justified the @a roi. If so,
 * clear the existing report.
 *
 * @param roi reserve out operation to check
 * @return #GNUNET_YES if @a roi was justified by a previous report,
 *         #GNUNET_NO of @a roi was not justified by a previous missing report
 *         #GNUNET_SYSERR on database trouble
 */
static enum GNUNET_GenericReturnValue
check_reported_inconsistency (struct ReserveOutInfo *roi)
{
  char diag[MAX_DIAG_LEN];
  struct TALER_AUDITORDB_WireOutInconsistency woi = {
    .wire_out_row_id = roi->details.serial_id,
    .destination_account = (char *) roi->details.credit_account_uri,
    .diagnostic = diag,
    .expected = roi->details.amount,
    .claimed = zero,
  };
  enum GNUNET_DB_QueryStatus qs;

  make_missing_diag (diag,
                     &roi->details.wtid);
  qs = TALER_ARL_adb->delete_wire_out_inconsistency_if_matching (
    TALER_ARL_adb->cls,
    &woi);
  if (qs < 0)
  {
    global_qs = qs;
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return GNUNET_SYSERR;
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    return GNUNET_NO;
  TALER_ARL_amount_subtract (&TALER_ARL_USE_AB (total_bad_amount_out_minus),
                             &TALER_ARL_USE_AB (total_bad_amount_out_minus),
                             &roi->details.amount);
  return GNUNET_YES;
}


/**
 * Check if a profit drain operation justified the @a roi
 *
 * @param roi reserve out operation to check
 * @return #GNUNET_YES if @a roi was justified by a profit drain,
 *         #GNUNET_NO of @a roi was not justified by a proft drain
 *         #GNUNET_SYSERR on database trouble
 */
static enum GNUNET_GenericReturnValue
check_profit_drain (struct ReserveOutInfo *roi)
{
  enum GNUNET_DB_QueryStatus qs;
  uint64_t serial;
  char *account_section;
  char *payto_uri;
  struct GNUNET_TIME_Timestamp request_timestamp;
  struct TALER_Amount amount;
  struct TALER_MasterSignatureP master_sig;

  qs = TALER_ARL_edb->get_drain_profit (
    TALER_ARL_edb->cls,
    &roi->details.wtid,
    &serial,
    &account_section,
    &payto_uri,
    &request_timestamp,
    &amount,
    &master_sig);
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    GNUNET_break (0);
    global_ret = EXIT_FAILURE;
    GNUNET_SCHEDULER_shutdown ();
    return GNUNET_SYSERR;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    /* should fail on commit later ... */
    GNUNET_break (0);
    return GNUNET_SYSERR;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    /* not a profit drain */
    return GNUNET_NO;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    break;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Profit drain of %s to %s found!\n",
              TALER_amount2s (&amount),
              payto_uri);
  if (GNUNET_OK !=
      TALER_exchange_offline_profit_drain_verify (
        &roi->details.wtid,
        request_timestamp,
        &amount,
        account_section,
        payto_uri,
        &TALER_ARL_master_pub,
        &master_sig))
  {
    struct TALER_AUDITORDB_RowInconsistency ri = {
      .row_id = roi->details.serial_id,
      .row_table = "profit_drains",
      .diagnostic = "invalid signature"
    };

    GNUNET_break (0);
    qs = TALER_ARL_adb->insert_row_inconsistency (
      TALER_ARL_adb->cls,
      &ri);
    GNUNET_free (payto_uri);
    GNUNET_free (account_section);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
    return GNUNET_NO;
  }
  GNUNET_free (account_section);
  if (0 !=
      strcasecmp (payto_uri,
                  roi->details.credit_account_uri))
  {
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .row_id = serial,
      .destination_account = (char *) roi->details.credit_account_uri,
      .diagnostic = "profit drain wired to invalid account",
      .expected = roi->details.amount,
      .claimed = zero,
    };

    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      GNUNET_free (payto_uri);
      return GNUNET_SYSERR;
    }
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &amount);
    GNUNET_free (payto_uri);
    return GNUNET_YES; /* justified, kind-of */
  }
  GNUNET_free (payto_uri);
  if (0 !=
      TALER_amount_cmp (&amount,
                        &roi->details.amount))
  {
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .row_id = roi->details.serial_id,
      .destination_account = (char *) roi->details.credit_account_uri,
      .diagnostic = "incorrect amount drained to correct account",
      .expected = roi->details.amount,
      .claimed = amount,
    };

    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          &roi->details.amount);
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &amount);
    return GNUNET_YES; /* justified, kind-of */
  }
  /* profit drain was correct */
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_drained),
                        &TALER_ARL_USE_AB (total_drained),
                        &amount);
  return GNUNET_YES;
}


/**
 * Check whether the given transfer was justified by a reserve closure or
 * profit drain. If not, complain that we failed to match an entry from
 * #out_map.  This means a wire transfer was made without proper
 * justification.
 *
 * @param cls a `struct WireAccount`
 * @param key unused key
 * @param value the `struct ReserveOutInfo` to report
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
complain_out_not_found (void *cls,
                        const struct GNUNET_HashCode *key,
                        void *value)
{
  // struct WireAccount *wa = cls;
  struct ReserveOutInfo *roi = value;
  struct GNUNET_HashCode rkey;
  struct CheckMatchContext ctx = {
    .roi = roi,
    .found = false
  };
  enum GNUNET_GenericReturnValue ret;

  (void) cls;
  (void) key;
  hash_rc (roi->details.credit_account_uri,
           &roi->details.wtid,
           &rkey);
  GNUNET_CONTAINER_multihashmap_get_multiple (reserve_closures,
                                              &rkey,
                                              &check_rc_matches,
                                              &ctx);
  if (ctx.found)
    return GNUNET_OK;
  ret = check_reported_inconsistency (roi);
  if (GNUNET_NO != ret)
    return ret;
  ret = check_profit_drain (roi);
  if (GNUNET_NO != ret)
    return ret;


  {
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .row_id = roi->details.serial_id,
      .destination_account = (char *) roi->details.credit_account_uri,
      .diagnostic = "missing justification for outgoing wire transfer",
      .expected = zero,
      .claimed = roi->details.amount
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
  }
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_plus),
                        &TALER_ARL_USE_AB (total_bad_amount_out_plus),
                        &roi->details.amount);
  return GNUNET_OK;
}


/**
 * Function called with details about outgoing wire transfers
 * as claimed by the exchange DB.
 *
 * @param cls a `struct WireAccount`
 * @param rowid unique serial ID in wire_out table
 * @param date timestamp of the transfer (roughly)
 * @param wtid wire transfer subject
 * @param payto_uri wire transfer details of the receiver
 * @param amount amount that was wired
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
wire_out_cb (
  void *cls,
  uint64_t rowid,
  struct GNUNET_TIME_Timestamp date,
  const struct TALER_WireTransferIdentifierRawP *wtid,
  const char *payto_uri,
  const struct TALER_Amount *amount)
{
  struct WireAccount *wa = cls;
  struct GNUNET_HashCode key;
  struct ReserveOutInfo *roi;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Exchange wire OUT #%llu at %s of %s with WTID %s\n",
              (unsigned long long) rowid,
              GNUNET_TIME_timestamp2s (date),
              TALER_amount2s (amount),
              TALER_B2S (wtid));
  wa->last_wire_out_serial_id = rowid + 1;
  TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_wire_out),
                        &TALER_ARL_USE_AB (total_wire_out),
                        amount);
  GNUNET_CRYPTO_hash (wtid,
                      sizeof (*wtid),
                      &key);
  roi = GNUNET_CONTAINER_multihashmap_get (out_map,
                                           &key);
  if (NULL == roi)
  {
    /* Wire transfer was not made (yet) at all (but would have been
       justified), so the entire amount is missing / still to be done.  This
       is moderately harmless, it might just be that the
       taler-exchange-transfer tool or bank has not yet fully caught up with
       the transfers it should do.
       May be cleared later by check_reported_inconsistency() */
    char diag[MAX_DIAG_LEN];
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .destination_account = (char *) payto_uri,
      .diagnostic = diag,
      .wire_out_row_id = rowid,
      .expected = *amount,
      .claimed = zero,
    };
    enum GNUNET_DB_QueryStatus qs;

    make_missing_diag (diag,
                       wtid);
    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          amount);
    return GNUNET_OK;
  }
  if (0 != strcasecmp (payto_uri,
                       roi->details.credit_account_uri))
  {
    /* Destination bank account is wrong in actual wire transfer, so
       we should count the wire transfer as entirely spurious, and
       additionally consider the justified wire transfer as missing. */
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .row_id = rowid,
      .destination_account = (char *) payto_uri,
      .diagnostic = "receiver account mismatch",
      .expected = *amount,
      .claimed = zero,
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_plus),
                          &roi->details.amount);
    TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          &TALER_ARL_USE_AB (total_bad_amount_out_minus),
                          amount);
    return GNUNET_OK;
  }
  if (0 != TALER_amount_cmp (&roi->details.amount,
                             amount))
  {
    struct TALER_AUDITORDB_WireOutInconsistency woi = {
      .destination_account = (char *) payto_uri,
      .diagnostic = "wire amount does not match",
      .wire_out_row_id = rowid,
      .expected = *amount,
      .claimed = zero,
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_wire_out_inconsistency (
      TALER_ARL_adb->cls,
      &woi);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_SYSERR;
    }
    if (0 < TALER_amount_cmp (amount,
                              &roi->details.amount))
    {
      /* amount > roi->details.amount: wire transfer was smaller than it should have been */
      struct TALER_Amount delta;

      TALER_ARL_amount_subtract (&delta,
                                 amount,
                                 &roi->details.amount);
      TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_minus),
                            &TALER_ARL_USE_AB (total_bad_amount_out_minus),
                            &delta);
    }
    else
    {
      /* roi->details.amount < amount: wire transfer was larger than it should have been */
      struct TALER_Amount delta;

      TALER_ARL_amount_subtract (&delta,
                                 &roi->details.amount,
                                 amount);
      TALER_ARL_amount_add (&TALER_ARL_USE_AB (total_bad_amount_out_plus),
                            &TALER_ARL_USE_AB (total_bad_amount_out_plus),
                            &delta);
    }
    return GNUNET_OK;
  }

  {
    enum GNUNET_GenericReturnValue ret;

    if (! check_time_difference ("wire_out",
                                 rowid,
                                 date,
                                 roi->details.execution_date))
    {
      /* We had a database error, fail */
      ret = GNUNET_SYSERR;
    }
    else
    {
      ret = GNUNET_OK;
    }
    GNUNET_assert (GNUNET_OK ==
                   free_roi (NULL,
                             &key,
                             roi));
    return ret;
  }
}


/**
 * Main function for processing 'reserves_out' data.  We start by going over
 * the DEBIT transactions this time, and then verify that all of them are
 * justified by 'reserves_out'.
 *
 * @param[in,out] wa wire account list to process
 */
static void
process_debits (struct WireAccount *wa);


/**
 * Go over the "wire_out" table of the exchange and
 * verify that all wire outs are in that table.
 *
 * @param[in,out] wa wire account we are processing
 */
static void
check_exchange_wire_out (struct WireAccount *wa)
{
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL == wa->dhh);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Analyzing exchange's wire OUT table for account `%s'\n",
              wa->ai->section_name);
  qs = TALER_ARL_edb->select_wire_out_above_serial_id_by_account (
    TALER_ARL_edb->cls,
    wa->ai->section_name,
    wa->last_wire_out_serial_id,
    &wire_out_cb,
    wa);
  if (0 > qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    global_ret = EXIT_FAILURE;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_CONTAINER_multihashmap_iterate (out_map,
                                         &complain_out_not_found,
                                         wa);
  /* clean up */
  GNUNET_CONTAINER_multihashmap_iterate (out_map,
                                         &free_roi,
                                         NULL);
  process_debits (wa->next);
}


/**
 * This function is called for all transactions that
 * are debited from the exchange's account (outgoing
 * transactions).
 *
 * @param cls `struct WireAccount` with current wire account to process
 * @param dhr HTTP response details
 */
static void
history_debit_cb (
  void *cls,
  const struct TALER_BANK_DebitHistoryResponse *dhr);


/**
 * Task scheduled to begin long-polling on the
 * bank transfer.
 *
 * @param cls a `struct WireAccount *`
 */
static void
dh_long_poll (void *cls)
{
  struct WireAccount *wa = cls;

  wa->dhh_task = NULL;
  wa->dhh_next
    = GNUNET_TIME_relative_to_absolute (MIN_LONGPOLL_DELAY);
  GNUNET_assert (NULL == wa->dhh);
  wa->dhh = TALER_BANK_debit_history (
    ctx,
    wa->ai->auth,
    wa->wire_off_out,
    MAX_PER_TRANSACTION,
    MAX_LONGPOLL_DELAY,
    &history_debit_cb,
    wa);
  if (NULL == wa->dhh)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to start long-polling for bank transaction history for `%s'\n",
                wa->ai->section_name);
    global_ret = EXIT_FAILURE;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


static void
history_debit_cb (
  void *cls,
  const struct TALER_BANK_DebitHistoryResponse *dhr)
{
  struct WireAccount *wa = cls;
  struct ReserveOutInfo *roi;
  size_t slen;

  wa->dhh = NULL;
  if ( (MHD_HTTP_OK == dhr->http_status) &&
       (0 != dhr->details.ok.details_length) )
  {
    /* As we got results, we go again *immediately* */
    wa->dhh_next = GNUNET_TIME_UNIT_ZERO_ABS;
  }
  GNUNET_assert (NULL == wa->dhh_task);
  wa->dhh_task
    = GNUNET_SCHEDULER_add_at (wa->dhh_next,
                               &dh_long_poll,
                               wa);
  switch (dhr->http_status)
  {
  case MHD_HTTP_OK:
    for (unsigned int i = 0; i < dhr->details.ok.details_length; i++)
    {
      const struct TALER_BANK_DebitDetails *dd
        = &dhr->details.ok.details[i];

      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Analyzing bank DEBIT #%llu at %s of %s with WTID %s\n",
                  (unsigned long long) dd->serial_id,
                  GNUNET_TIME_timestamp2s (dd->execution_date),
                  TALER_amount2s (&dd->amount),
                  TALER_B2S (&dd->wtid));
      wa->wire_off_out = dd->serial_id + 1;
      slen = strlen (dd->credit_account_uri) + 1;
      roi = GNUNET_malloc (sizeof (struct ReserveOutInfo)
                           + slen);
      GNUNET_CRYPTO_hash (&dd->wtid,
                          sizeof (dd->wtid),
                          &roi->subject_hash);
      roi->details = *dd;
      roi->details.credit_account_uri
        = (const char *) &roi[1];
      GNUNET_memcpy (&roi[1],
                     dd->credit_account_uri,
                     slen);
      if (GNUNET_OK !=
          GNUNET_CONTAINER_multihashmap_put (out_map,
                                             &roi->subject_hash,
                                             roi,
                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
      {
        struct TALER_AUDITORDB_WireFormatInconsistency wfi = {
          .amount = dd->amount,
          .wire_offset = dd->serial_id,
          .diagnostic = "duplicate outgoing wire transfer subject"
        };
        enum GNUNET_DB_QueryStatus qs;

        qs = TALER_ARL_adb->insert_wire_format_inconsistency (
          TALER_ARL_adb->cls,
          &wfi);
        if (qs < 0)
        {
          global_qs = qs;
          GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
          commit (qs);
          return;
        }
        TALER_ARL_amount_add (&TALER_ARL_USE_AB (
                                wire_debit_duplicate_transfer_subject_total),
                              &TALER_ARL_USE_AB (
                                wire_debit_duplicate_transfer_subject_total),
                              &dd->amount);
      }
    }
    check_exchange_wire_out (wa);
    return;
  case MHD_HTTP_NO_CONTENT:
    check_exchange_wire_out (wa);
    return;
  case MHD_HTTP_NOT_FOUND:
    if (ignore_account_404)
    {
      check_exchange_wire_out (wa);
      return;
    }
    break;
  default:
    break;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Error fetching debit history of account %s: %u/%u!\n",
              wa->ai->section_name,
              dhr->http_status,
              (unsigned int) dhr->ec);
  commit (GNUNET_DB_STATUS_HARD_ERROR);
  global_ret = EXIT_FAILURE;
  GNUNET_SCHEDULER_shutdown ();
  return;
}


static void
process_debits (struct WireAccount *wa)
{
  /* skip accounts where DEBIT is not enabled */
  while ( (NULL != wa) &&
          (! wa->ai->debit_enabled) )
    wa = wa->next;
  if (NULL == wa)
  {
    /* end of iteration */
    commit (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Checking bank DEBIT records of account `%s'\n",
              wa->ai->section_name);
  if ( (NULL == wa->dhh) &&
       (NULL == wa->dhh_task) )
  {
    wa->dhh = TALER_BANK_debit_history (
      ctx,
      wa->ai->auth,
      wa->wire_off_out,
      MAX_PER_TRANSACTION,
      GNUNET_TIME_UNIT_ZERO,
      &history_debit_cb,
      wa);
    if (NULL == wa->dhh)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to obtain bank transaction history for `%s'\n",
                  wa->ai->section_name);
      commit (GNUNET_DB_STATUS_HARD_ERROR);
      global_ret = EXIT_FAILURE;
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  }
}


/**
 * Function called about reserve closing operations the aggregator triggered.
 *
 * @param cls closure; NULL
 * @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, in payto://-format
 * @param wtid identifier used for the wire transfer
 * @param close_request_row which close request triggered the operation?
 *         0 if it was a timeout (not used)
 * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to stop
 */
static enum GNUNET_GenericReturnValue
reserve_closed_cb (
  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 *wtid,
  uint64_t close_request_row)
{
  struct ReserveClosure *rc;
  struct GNUNET_HashCode key;

  (void) cls;
  (void) close_request_row;
  rc = GNUNET_new (struct ReserveClosure);
  if (TALER_ARL_SR_INVALID_NEGATIVE ==
      TALER_ARL_amount_subtract_neg (&rc->amount,
                                     amount_with_fee,
                                     closing_fee))
  {
    struct TALER_AUDITORDB_RowInconsistency ri = {
      .row_id = rowid,
      .row_table = "reserves_closures",
      .diagnostic = "closing fee above reserve balance (and closed anyway)"
    };
    enum GNUNET_DB_QueryStatus qs;

    qs = TALER_ARL_adb->insert_row_inconsistency (
      TALER_ARL_adb->cls,
      &ri);
    if (qs < 0)
    {
      global_qs = qs;
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return GNUNET_OK;
    }
    GNUNET_free (rc);
    return GNUNET_OK;
  }
  TALER_ARL_USE_PP (wire_reserve_close_id)
    = GNUNET_MAX (TALER_ARL_USE_PP (wire_reserve_close_id),
                  rowid + 1);
  rc->receiver_account = GNUNET_strdup (receiver_account);
  rc->wtid = *wtid;
  rc->execution_date = execution_date;
  rc->rowid = rowid;
  hash_rc (receiver_account,
           wtid,
           &key);
  (void) GNUNET_CONTAINER_multihashmap_put (
    reserve_closures,
    &key,
    rc,
    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  return GNUNET_OK;
}


/**
 * Start the database transactions and begin the audit.
 *
 * @return transaction status code
 */
static enum GNUNET_DB_QueryStatus
begin_transaction (void)
{
  enum GNUNET_DB_QueryStatus qs;

  if (GNUNET_SYSERR ==
      TALER_ARL_edb->preflight (TALER_ARL_edb->cls))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to initialize exchange database connection.\n");
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  if (GNUNET_SYSERR ==
      TALER_ARL_adb->preflight (TALER_ARL_adb->cls))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to initialize auditor database session.\n");
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  global_qs = GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  if (GNUNET_OK !=
      TALER_ARL_adb->start (TALER_ARL_adb->cls))
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  TALER_ARL_edb->preflight (TALER_ARL_edb->cls);
  if (GNUNET_OK !=
      TALER_ARL_edb->start (TALER_ARL_edb->cls,
                            "wire auditor"))
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  qs = TALER_ARL_adb->get_balance (
    TALER_ARL_adb->cls,
    TALER_ARL_GET_AB (total_drained),
    TALER_ARL_GET_AB (total_wire_out),
    TALER_ARL_GET_AB (total_bad_amount_out_plus),
    TALER_ARL_GET_AB (total_bad_amount_out_minus),
    TALER_ARL_GET_AB (total_amount_lag),
    TALER_ARL_GET_AB (total_closure_amount_lag),
    TALER_ARL_GET_AB (wire_debit_duplicate_transfer_subject_total),
    TALER_ARL_GET_AB (total_wire_out),
    NULL);
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    GNUNET_break (0);
    return qs;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return qs;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    break;
  }
  for (struct WireAccount *wa = wa_head;
       NULL != wa;
       wa = wa->next)
  {
    GNUNET_asprintf (&wa->label_wire_out_serial_id,
                     "wire-%s-%s",
                     wa->ai->section_name,
                     "wire_out_serial_id");
    GNUNET_asprintf (&wa->label_wire_off_out,
                     "wire-%s-%s",
                     wa->ai->section_name,
                     "wire_off_out");
    qs = TALER_ARL_adb->get_auditor_progress (
      TALER_ARL_adb->cls,
      wa->label_wire_out_serial_id,
      &wa->last_wire_out_serial_id,
      wa->label_wire_off_out,
      &wa->wire_off_out,
      NULL);
    if (0 > qs)
    {
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
      return qs;
    }
    GNUNET_assert (2 == qs);
    wa->start_wire_out_serial_id = wa->last_wire_out_serial_id;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Resuming account %s debit audit at %llu/%llu\n",
                wa->ai->section_name,
                (unsigned long long) wa->last_wire_out_serial_id,
                (unsigned long long) wa->wire_off_out);
  }
  qs = TALER_ARL_adb->get_auditor_progress (
    TALER_ARL_adb->cls,
    TALER_ARL_GET_PP (wire_reserve_close_id),
    NULL);
  if (0 > qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    return qs;
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
                "First analysis of with wire auditor, starting audit from scratch\n");
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Resuming wire debit audit at %llu\n",
                (unsigned long long) TALER_ARL_USE_PP (wire_reserve_close_id));
  }

  qs = TALER_ARL_edb->select_reserve_closed_above_serial_id (
    TALER_ARL_edb->cls,
    TALER_ARL_USE_PP (wire_reserve_close_id),
    &reserve_closed_cb,
    NULL);
  if (0 > qs)
  {
    GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  process_debits (wa_head);
  return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
}


/**
 * Function called with information about a wire account.  Adds the
 * account to our list for processing (if it is enabled and we can
 * load the plugin).
 *
 * @param cls closure, NULL
 * @param ai account information
 */
static void
process_account_cb (void *cls,
                    const struct TALER_EXCHANGEDB_AccountInfo *ai)
{
  struct WireAccount *wa;

  (void) cls;
  if ( (! ai->debit_enabled) &&
       (! ai->credit_enabled) )
    return; /* not an active exchange account */
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Found exchange account `%s'\n",
              ai->section_name);
  wa = GNUNET_new (struct WireAccount);
  wa->ai = ai;
  GNUNET_CONTAINER_DLL_insert (wa_head,
                               wa_tail,
                               wa);
}


/**
 * Function called on events received from Postgres.
 *
 * @param cls closure, NULL
 * @param extra additional event data provided
 * @param extra_size number of bytes in @a extra
 */
static void
db_notify (void *cls,
           const void *extra,
           size_t extra_size)
{
  (void) cls;
  (void) extra;
  (void) extra_size;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Received notification to wake wire helper\n");
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS !=
      begin_transaction ())
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Audit failed\n");
    GNUNET_break (0);
    global_ret = EXIT_FAILURE;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * 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;
  cfg = c;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Launching wire auditor\n");
  if (GNUNET_OK !=
      TALER_ARL_init (c))
  {
    global_ret = EXIT_FAILURE;
    return;
  }

  reserve_closures
    = GNUNET_CONTAINER_multihashmap_create (1024,
                                            GNUNET_NO);
  if (GNUNET_OK !=
      TALER_config_get_amount (TALER_ARL_cfg,
                               "auditor",
                               "TINY_AMOUNT",
                               &tiny_amount))
  {
    global_ret = EXIT_NOTCONFIGURED;
    return;
  }
  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (TALER_ARL_currency,
                                        &zero));
  GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
                                 NULL);
  ctx = GNUNET_CURL_init (&GNUNET_CURL_gnunet_scheduler_reschedule,
                          &rc);
  rc = GNUNET_CURL_gnunet_rc_create (ctx);
  if (NULL == ctx)
  {
    GNUNET_break (0);
    global_ret = EXIT_FAILURE;
    return;
  }
  reserve_closures = GNUNET_CONTAINER_multihashmap_create (1024,
                                                           GNUNET_NO);
  out_map = GNUNET_CONTAINER_multihashmap_create (1024,
                                                  true);
  if (GNUNET_OK !=
      TALER_EXCHANGEDB_load_accounts (TALER_ARL_cfg,
                                      TALER_EXCHANGEDB_ALO_DEBIT
                                      | TALER_EXCHANGEDB_ALO_CREDIT
                                      | TALER_EXCHANGEDB_ALO_AUTHDATA))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "No bank accounts configured\n");
    global_ret = EXIT_NOTCONFIGURED;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  TALER_EXCHANGEDB_find_accounts (&process_account_cb,
                                  NULL);

  if (0 == test_mode)
  {
    struct GNUNET_DB_EventHeaderP es = {
      .size = htons (sizeof (es)),
      .type = htons (TALER_DBEVENT_EXCHANGE_AUDITOR_WAKE_HELPER_WIRE)
    };

    eh = TALER_ARL_adb->event_listen (TALER_ARL_adb->cls,
                                      &es,
                                      GNUNET_TIME_UNIT_FOREVER_REL,
                                      &db_notify,
                                      NULL);
    GNUNET_assert (NULL != eh);
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS !=
      begin_transaction ())
  {
    GNUNET_break (0);
    global_ret = EXIT_FAILURE;
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * The main function of the wire auditing tool. Checks that
 * the exchange's records of wire transfers match that of
 * the wire gateway.
 *
 * @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 ('I',
                               "ignore-not-found",
                               "continue, even if the bank account of the exchange was not found",
                               &ignore_account_404),
    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-wire-debit",
    gettext_noop (
      "Audit exchange database for consistency with the bank's outgoing wire transfers"),
    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-wire-debit.c */