summaryrefslogtreecommitdiff
path: root/src/stasis/plugin_anastasis_postgres.c
blob: 801552d2543b0e411d769618ce57c867b8d8df80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
/*
  This file is part of Anastasis
  Copyright (C) 2020, 2021, 2022 Anastasis SARL

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

  Anastasis 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 General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file stasis/plugin_anastasis_postgres.c
 * @brief database helper functions for postgres used by GNU Anastasis
 * @author Christian Grothoff
 * @author Marcello Stanisci
 */
#include "platform.h"
#include "anastasis_database_plugin.h"
#include "anastasis_database_lib.h"
#include <taler/taler_pq_lib.h>

/**
 * How long do we keep transient accounts open (those that have
 * not been paid at all, but are awaiting payment). This puts
 * a cap on how long users have to make a payment after a payment
 * request was generated.
 */
#define TRANSIENT_LIFETIME GNUNET_TIME_UNIT_WEEKS

/**
 * How often do we re-try if we run into a DB serialization error?
 */
#define MAX_RETRIES 3


/**
 * Type of the "cls" argument given to each of the functions in
 * our API.
 */
struct PostgresClosure
{

  /**
   * Postgres connection handle.
   */
  struct GNUNET_PQ_Context *conn;

  /**
   * Underlying configuration.
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * Name of the currently active transaction, NULL if none is active.
   */
  const char *transaction_name;

  /**
   * Currency we accept payments in.
   */
  char *currency;

  /**
   * Prepared statements have been initialized.
   */
  bool init;
};


/**
 * Drop anastasis tables
 *
 * @param cls closure our `struct Plugin`
 * @return #GNUNET_OK upon success; #GNUNET_SYSERR upon failure
 */
static enum GNUNET_GenericReturnValue
postgres_drop_tables (void *cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_Context *conn;

  conn = GNUNET_PQ_connect_with_cfg (pg->cfg,
                                     "stasis-postgres",
                                     "drop",
                                     NULL,
                                     NULL);
  if (NULL == conn)
    return GNUNET_SYSERR;
  GNUNET_PQ_disconnect (conn);
  return GNUNET_OK;
}


/**
 * Initialize tables.
 *
 * @param cls the `struct PostgresClosure` with the plugin-specific state
 * @return #GNUNET_OK upon success; #GNUNET_SYSERR upon failure
 */
static enum GNUNET_GenericReturnValue
postgres_create_tables (void *cls)
{
  struct PostgresClosure *pc = cls;
  struct GNUNET_PQ_Context *conn;

  conn = GNUNET_PQ_connect_with_cfg (pc->cfg,
                                     "stasis-postgres",
                                     "stasis-",
                                     NULL,
                                     NULL);
  if (NULL == conn)
    return GNUNET_SYSERR;
  GNUNET_PQ_disconnect (conn);
  return GNUNET_OK;
}


/**
 * Establish connection to the database.
 *
 * @param cls plugin context
 * @return #GNUNET_OK upon success; #GNUNET_SYSERR upon failure
 */
static enum GNUNET_GenericReturnValue
prepare_statements (void *cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_PreparedStatement ps[] = {
    GNUNET_PQ_make_prepare ("user_insert",
                            "INSERT INTO anastasis_user "
                            "(user_id"
                            ",expiration_date"
                            ") VALUES "
                            "($1, $2);",
                            2),
    GNUNET_PQ_make_prepare ("do_commit",
                            "COMMIT",
                            0),
    GNUNET_PQ_make_prepare ("user_select",
                            "SELECT"
                            " expiration_date "
                            "FROM anastasis_user"
                            " WHERE user_id=$1"
                            " FOR UPDATE;",
                            1),
    GNUNET_PQ_make_prepare ("user_update",
                            "UPDATE anastasis_user"
                            " SET "
                            " expiration_date=$1"
                            " WHERE user_id=$2;",
                            2),
    GNUNET_PQ_make_prepare ("recdoc_payment_insert",
                            "INSERT INTO anastasis_recdoc_payment "
                            "(user_id"
                            ",post_counter"
                            ",amount_val"
                            ",amount_frac"
                            ",payment_identifier"
                            ",creation_date"
                            ") VALUES "
                            "($1, $2, $3, $4, $5, $6);",
                            6),
    GNUNET_PQ_make_prepare ("challenge_payment_insert",
                            "INSERT INTO anastasis_challenge_payment "
                            "(truth_uuid"
                            ",amount_val"
                            ",amount_frac"
                            ",payment_identifier"
                            ",creation_date"
                            ") VALUES "
                            "($1, $2, $3, $4, $5);",
                            5),
    GNUNET_PQ_make_prepare ("truth_payment_insert",
                            "INSERT INTO anastasis_truth_payment "
                            "(truth_uuid"
                            ",amount_val"
                            ",amount_frac"
                            ",expiration"
                            ") VALUES "
                            "($1, $2, $3, $4);",
                            4),
    GNUNET_PQ_make_prepare ("recdoc_payment_done",
                            "UPDATE anastasis_recdoc_payment "
                            "SET"
                            " paid=TRUE "
                            "WHERE"
                            "  payment_identifier=$1"
                            " AND"
                            "  user_id=$2"
                            " AND"
                            "  paid=FALSE;",
                            2),
    GNUNET_PQ_make_prepare ("challenge_refund_update",
                            "UPDATE anastasis_challenge_payment "
                            "SET"
                            " refunded=TRUE "
                            "WHERE"
                            "  payment_identifier=$1"
                            " AND"
                            "  paid=TRUE"
                            " AND"
                            "  truth_uuid=$2;",
                            2),
    GNUNET_PQ_make_prepare ("challenge_payment_done",
                            "UPDATE anastasis_challenge_payment "
                            "SET"
                            " paid=TRUE "
                            "WHERE"
                            "  payment_identifier=$1"
                            " AND"
                            "  refunded=FALSE"
                            " AND"
                            "  truth_uuid=$2"
                            " AND"
                            "  paid=FALSE;",
                            2),
    GNUNET_PQ_make_prepare ("recdoc_payment_select",
                            "SELECT"
                            " creation_date"
                            ",post_counter"
                            ",amount_val"
                            ",amount_frac"
                            ",paid"
                            " FROM anastasis_recdoc_payment"
                            " WHERE payment_identifier=$1;",
                            1),
    GNUNET_PQ_make_prepare ("truth_payment_select",
                            "SELECT"
                            " expiration"
                            " FROM anastasis_truth_payment"
                            " WHERE truth_uuid=$1"
                            "   AND expiration>$2;",
                            2),
    GNUNET_PQ_make_prepare ("challenge_payment_select",
                            "SELECT"
                            " creation_date"
                            ",amount_val"
                            ",amount_frac"
                            ",paid"
                            " FROM anastasis_challenge_payment"
                            " WHERE payment_identifier=$1"
                            "   AND truth_uuid=$2"
                            "   AND refunded=FALSE"
                            "   AND counter>0;",
                            1),
    GNUNET_PQ_make_prepare ("challenge_pending_payment_select",
                            "SELECT"
                            " creation_date"
                            ",payment_identifier"
                            ",amount_val"
                            ",amount_frac"
                            " FROM anastasis_challenge_payment"
                            " WHERE"
                            "  paid=FALSE"
                            " AND"
                            "  refunded=FALSE"
                            " AND"
                            "  truth_uuid=$1"
                            " AND"
                            "  creation_date > $2;",
                            1),
    GNUNET_PQ_make_prepare ("recdoc_payments_select",
                            "SELECT"
                            " user_id"
                            ",payment_identifier"
                            ",amount_val"
                            ",amount_frac"
                            " FROM anastasis_recdoc_payment"
                            " WHERE paid=FALSE;",
                            0),
    GNUNET_PQ_make_prepare ("gc_accounts",
                            "DELETE FROM anastasis_user "
                            "WHERE"
                            " expiration_date < $1;",
                            1),
    GNUNET_PQ_make_prepare ("gc_recdoc_pending_payments",
                            "DELETE FROM anastasis_recdoc_payment "
                            "WHERE"
                            "  paid=FALSE"
                            " AND"
                            "  creation_date < $1;",
                            1),
    GNUNET_PQ_make_prepare ("gc_challenge_pending_payments",
                            "DELETE FROM anastasis_challenge_payment "
                            "WHERE"
                            "  (paid=FALSE"
                            "   OR"
                            "   refunded=TRUE)"
                            " AND"
                            "  creation_date < $1;",
                            1),
    GNUNET_PQ_make_prepare ("truth_insert",
                            "INSERT INTO anastasis_truth "
                            "(truth_uuid"
                            ",key_share_data"
                            ",method_name"
                            ",encrypted_truth"
                            ",truth_mime"
                            ",expiration"
                            ") VALUES "
                            "($1, $2, $3, $4, $5, $6);",
                            6),
    GNUNET_PQ_make_prepare ("test_auth_iban_payment",
                            "SELECT"
                            " credit_val"
                            ",credit_frac"
                            ",wire_subject"
                            " FROM anastasis_auth_iban_in"
                            " WHERE debit_account_details=$1"
                            "  AND execution_date>=$2;",
                            2),
    GNUNET_PQ_make_prepare ("store_auth_iban_payment_details",
                            "INSERT INTO anastasis_auth_iban_in "
                            "(wire_reference"
                            ",wire_subject"
                            ",credit_val"
                            ",credit_frac"
                            ",debit_account_details"
                            ",credit_account_details"
                            ",execution_date"
                            ") VALUES "
                            "($1, $2, $3, $4, $5, $6, $7);",
                            7),
    GNUNET_PQ_make_prepare ("recovery_document_insert",
                            "INSERT INTO anastasis_recoverydocument "
                            "(user_id"
                            ",version"
                            ",account_sig"
                            ",recovery_data_hash"
                            ",recovery_data"
                            ",recovery_meta_data"
                            ") VALUES "
                            "($1, $2, $3, $4, $5, $6);",
                            6),
    GNUNET_PQ_make_prepare ("truth_select",
                            "SELECT "
                            " method_name"
                            ",encrypted_truth"
                            ",truth_mime"
                            " FROM anastasis_truth"
                            " WHERE truth_uuid =$1;",
                            1),
    GNUNET_PQ_make_prepare ("latest_recoverydocument_select",
                            "SELECT "
                            " version"
                            ",account_sig"
                            ",recovery_data_hash"
                            ",recovery_data"
                            " FROM anastasis_recoverydocument"
                            " WHERE user_id =$1 "
                            " ORDER BY version DESC"
                            " LIMIT 1;",
                            1),
    GNUNET_PQ_make_prepare ("latest_recovery_version_select",
                            "SELECT"
                            " version"
                            ",recovery_data_hash"
                            ",expiration_date"
                            " FROM anastasis_recoverydocument"
                            " JOIN anastasis_user USING (user_id)"
                            " WHERE user_id=$1"
                            " ORDER BY version DESC"
                            " LIMIT 1;",
                            1),
    GNUNET_PQ_make_prepare ("recoverydocument_select",
                            "SELECT "
                            " account_sig"
                            ",recovery_data_hash"
                            ",recovery_data"
                            " FROM anastasis_recoverydocument"
                            " WHERE user_id=$1"
                            " AND version=$2;",
                            2),
    GNUNET_PQ_make_prepare ("postcounter_select",
                            "SELECT"
                            " post_counter"
                            " FROM anastasis_recdoc_payment"
                            " WHERE user_id=$1"
                            "  AND payment_identifier=$2;",
                            2),
    GNUNET_PQ_make_prepare ("postcounter_update",
                            "UPDATE "
                            "anastasis_recdoc_payment "
                            "SET "
                            "post_counter=$1 "
                            "WHERE user_id =$2 "
                            "AND payment_identifier=$3;",
                            3),
    GNUNET_PQ_make_prepare ("key_share_select",
                            "SELECT "
                            "key_share_data "
                            "FROM "
                            "anastasis_truth "
                            "WHERE truth_uuid =$1;",
                            1),
    GNUNET_PQ_make_prepare ("challengecode_insert",
                            "INSERT INTO anastasis_challengecode "
                            "(truth_uuid"
                            ",code"
                            ",creation_date"
                            ",expiration_date"
                            ",retry_counter"
                            ") VALUES "
                            "($1, $2, $3, $4, $5);",
                            5),
    GNUNET_PQ_make_prepare ("challengecode_select",
                            "SELECT "
                            " code"
                            ",satisfied"
                            " FROM anastasis_challengecode"
                            " WHERE truth_uuid=$1"
                            "   AND expiration_date > $2"
                            "   AND retry_counter != 0;",
                            2),
    GNUNET_PQ_make_prepare ("challengecode_set_satisfied",
                            "UPDATE anastasis_challengecode"
                            " SET satisfied=TRUE"
                            " WHERE truth_uuid=$1"
                            "   AND code=$2"
                            "   AND creation_date IN"
                            " (SELECT creation_date"
                            "    FROM anastasis_challengecode"
                            "   WHERE truth_uuid=$1"
                            "     AND code=$2"
                            "    ORDER BY creation_date DESC"
                            "     LIMIT 1);",
                            2),
    GNUNET_PQ_make_prepare ("challengecode_test_satisfied",
                            "SELECT 1 FROM anastasis_challengecode"
                            " WHERE truth_uuid=$1"
                            "   AND satisfied=TRUE"
                            "   AND code=$2"
                            "   AND creation_date >= $3"
                            " LIMIT 1;",
                            3),
    GNUNET_PQ_make_prepare ("challengecode_select_meta",
                            "SELECT "
                            " code"
                            ",retry_counter"
                            ",retransmission_date"
                            " FROM anastasis_challengecode"
                            " WHERE truth_uuid=$1"
                            "   AND expiration_date > $2"
                            "   AND creation_date > $3"
                            " ORDER BY creation_date DESC"
                            " LIMIT 1;",
                            2),
    GNUNET_PQ_make_prepare ("challengecode_update_retry",
                            "UPDATE anastasis_challengecode"
                            " SET retry_counter=retry_counter - 1"
                            " WHERE truth_uuid=$1"
                            "   AND code=$2"
                            "   AND retry_counter != 0;",
                            1),
    GNUNET_PQ_make_prepare ("challengepayment_dec_counter",
                            "UPDATE anastasis_challenge_payment"
                            " SET counter=counter - 1"
                            " WHERE truth_uuid=$1"
                            "   AND payment_identifier=$2"
                            "   AND counter > 0;",
                            2),
    GNUNET_PQ_make_prepare ("challengecode_mark_sent",
                            "UPDATE anastasis_challengecode"
                            " SET retransmission_date=$3"
                            " WHERE truth_uuid=$1"
                            "   AND code=$2"
                            "   AND creation_date IN"
                            " (SELECT creation_date"
                            "    FROM anastasis_challengecode"
                            "   WHERE truth_uuid=$1"
                            "     AND code=$2"
                            "    ORDER BY creation_date DESC"
                            "     LIMIT 1);",
                            3),
    GNUNET_PQ_make_prepare ("get_last_auth_iban_payment",
                            "SELECT "
                            " wire_reference"
                            " FROM anastasis_auth_iban_in"
                            " WHERE credit_account_details=$1"
                            " ORDER BY wire_reference DESC"
                            " LIMIT 1;",
                            1),
    GNUNET_PQ_make_prepare ("gc_challengecodes",
                            "DELETE FROM anastasis_challengecode "
                            "WHERE "
                            "expiration_date < $1;",
                            1),
    GNUNET_PQ_PREPARED_STATEMENT_END
  };

  {
    enum GNUNET_GenericReturnValue ret;

    ret = GNUNET_PQ_prepare_statements (pg->conn,
                                        ps);
    if (GNUNET_OK != ret)
      return ret;
    pg->init = true;
    return GNUNET_OK;
  }
}


/**
 * Check that the database connection is still up.
 *
 * @param cls a `struct PostgresClosure` with connection to check
 */
static void
check_connection (void *cls)
{
  struct PostgresClosure *pg = cls;

  GNUNET_PQ_reconnect_if_down (pg->conn);
}


/**
 * Connect to the database if the connection does not exist yet.
 *
 * @param pg the plugin-specific state
 * @param skip_prepare true if we should skip prepared statement setup
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
internal_setup (struct PostgresClosure *pg,
                bool skip_prepare)
{
  if (NULL == pg->conn)
  {
#if AUTO_EXPLAIN
    /* Enable verbose logging to see where queries do not
       properly use indices */
    struct GNUNET_PQ_ExecuteStatement es[] = {
      GNUNET_PQ_make_try_execute ("LOAD 'auto_explain';"),
      GNUNET_PQ_make_try_execute ("SET auto_explain.log_min_duration=50;"),
      GNUNET_PQ_make_try_execute ("SET auto_explain.log_timing=TRUE;"),
      GNUNET_PQ_make_try_execute ("SET auto_explain.log_analyze=TRUE;"),
      /* https://wiki.postgresql.org/wiki/Serializable suggests to really
         force the default to 'serializable' if SSI is to be used. */
      GNUNET_PQ_make_try_execute (
        "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;"),
      GNUNET_PQ_make_try_execute ("SET enable_sort=OFF;"),
      GNUNET_PQ_make_try_execute ("SET enable_seqscan=OFF;"),
      GNUNET_PQ_EXECUTE_STATEMENT_END
    };
#else
    struct GNUNET_PQ_ExecuteStatement *es = NULL;
#endif
    struct GNUNET_PQ_Context *db_conn;

    db_conn = GNUNET_PQ_connect_with_cfg (pg->cfg,
                                          "stasis-postgres",
                                          NULL,
                                          es,
                                          NULL);
    if (NULL == db_conn)
      return GNUNET_SYSERR;
    pg->conn = db_conn;
  }
  if (NULL == pg->transaction_name)
    GNUNET_PQ_reconnect_if_down (pg->conn);
  if (pg->init)
    return GNUNET_OK;
  if (skip_prepare)
    return GNUNET_OK;
  return prepare_statements (pg);
}


/**
 * Do a pre-flight check that we are not in an uncommitted transaction.
 * If we are, try to commit the previous transaction and output a warning.
 * Does not return anything, as we will continue regardless of the outcome.
 *
 * @param cls the `struct PostgresClosure` with the plugin-specific state
 * @return #GNUNET_OK if everything is fine
 *         #GNUNET_NO if a transaction was rolled back
 *         #GNUNET_SYSERR on hard errors
 */
static enum GNUNET_GenericReturnValue
postgres_preflight (void *cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("ROLLBACK"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  if (! pg->init)
  {
    if (GNUNET_OK !=
        internal_setup (pg,
                        false))
      return GNUNET_SYSERR;
  }
  if (NULL == pg->transaction_name)
    return GNUNET_OK;  /* all good */
  if (GNUNET_OK ==
      GNUNET_PQ_exec_statements (pg->conn,
                                 es))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "BUG: Preflight check rolled back transaction `%s'!\n",
                pg->transaction_name);
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "BUG: Preflight check failed to rollback transaction `%s'!\n",
                pg->transaction_name);
  }
  pg->transaction_name = NULL;
  return GNUNET_NO;
}


/**
 * Start a transaction.
 *
 * @param cls the `struct PostgresClosure` with the plugin-specific state
 * @param name unique name identifying the transaction (for debugging),
 *             must point to a constant
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
begin_transaction (void *cls,
                   const char *name)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("START TRANSACTION ISOLATION LEVEL SERIALIZABLE"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  pg->transaction_name = name;
  if (GNUNET_OK !=
      GNUNET_PQ_exec_statements (pg->conn,
                                 es))
  {
    TALER_LOG_ERROR ("Failed to start transaction\n");
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
* Roll back the current transaction of a database connection.
*
* @param cls the `struct PostgresClosure` with the plugin-specific state
* @return #GNUNET_OK on success
*/
static void
rollback (void *cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("ROLLBACK"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  if (GNUNET_OK !=
      GNUNET_PQ_exec_statements (pg->conn,
                                 es))
  {
    TALER_LOG_ERROR ("Failed to rollback transaction\n");
    GNUNET_break (0);
  }
  pg->transaction_name = NULL;
}


/**
 * Commit the current transaction of a database connection.
 *
 * @param cls the `struct PostgresClosure` with the plugin-specific state
 * @return transaction status code
 */
static enum GNUNET_DB_QueryStatus
commit_transaction (void *cls)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;
  struct GNUNET_PQ_QueryParam no_params[] = {
    GNUNET_PQ_query_param_end
  };

  qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                           "do_commit",
                                           no_params);
  pg->transaction_name = NULL;
  return qs;
}


/**
 * Register callback to be invoked on events of type @a es.
 *
 * @param cls database context to use
 * @param es specification of the event to listen for
 * @param timeout how long to wait for the event
 * @param cb function to call when the event happens, possibly
 *         multiple times (until cancel is invoked)
 * @param cb_cls closure for @a cb
 * @return handle useful to cancel the listener
 */
static struct GNUNET_DB_EventHandler *
postgres_event_listen (void *cls,
                       const struct GNUNET_DB_EventHeaderP *es,
                       struct GNUNET_TIME_Relative timeout,
                       GNUNET_DB_EventCallback cb,
                       void *cb_cls)
{
  struct PostgresClosure *pg = cls;

  return GNUNET_PQ_event_listen (pg->conn,
                                 es,
                                 timeout,
                                 cb,
                                 cb_cls);
}


/**
 * Stop notifications.
 *
 * @param eh handle to unregister.
 */
static void
postgres_event_listen_cancel (struct GNUNET_DB_EventHandler *eh)
{
  GNUNET_PQ_event_listen_cancel (eh);
}


/**
 * Notify all that listen on @a es of an event.
 *
 * @param cls database context to use
 * @param es specification of the event to generate
 * @param extra additional event data provided
 * @param extra_size number of bytes in @a extra
 */
static void
postgres_event_notify (void *cls,
                       const struct GNUNET_DB_EventHeaderP *es,
                       const void *extra,
                       size_t extra_size)
{
  struct PostgresClosure *pg = cls;

  return GNUNET_PQ_event_notify (pg->conn,
                                 es,
                                 extra,
                                 extra_size);
}


/**
 * Function called to perform "garbage collection" on the
 * database, expiring records we no longer require.  Deletes
 * all user records that are not paid up (and by cascade deletes
 * the associated recovery documents). Also deletes expired
 * truth and financial records older than @a fin_expire.
 *
 * @param cls closure
 * @param expire_backups backups older than the given time stamp should be garbage collected
 * @param expire_pending_payments payments still pending from since before
 *            this value should be garbage collected
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_gc (void *cls,
             struct GNUNET_TIME_Absolute expire_backups,
             struct GNUNET_TIME_Absolute expire_pending_payments)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_absolute_time (&expire_backups),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_QueryParam params2[] = {
    GNUNET_PQ_query_param_absolute_time (&expire_pending_payments),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                           "gc_accounts",
                                           params);
  if (qs < 0)
    return qs;
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "gc_recdoc_pending_payments",
                                             params2);
}


/**
 * Store encrypted recovery document.
 *
 * @param cls closure
 * @param account_pub public key of the user's account
 * @param account_sig signature affirming storage request
 * @param recovery_data_hash hash of @a data
 * @param recovery_data contains encrypted_recovery_document
 * @param recovery_data_size size of data blob
 * @param payment_secret identifier for the payment, used to later charge on uploads
 * @param[out] version set to the version assigned to the document by the database
 * @return transaction status, 0 if upload could not be finished because @a payment_secret
 *         did not have enough upload left; HARD error if @a payment_secret is unknown, ...
 */
static enum ANASTASIS_DB_StoreStatus
postgres_store_recovery_document (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  const struct ANASTASIS_AccountSignatureP *account_sig,
  const struct GNUNET_HashCode *recovery_data_hash,
  const void *recovery_data,
  size_t recovery_data_size,
  const void *recovery_meta_data,
  size_t recovery_meta_data_size,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  uint32_t *version)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  for (unsigned int retry = 0; retry<MAX_RETRIES; retry++)
  {
    if (GNUNET_OK !=
        begin_transaction (pg,
                           "store_recovery_document"))
    {
      GNUNET_break (0);
      return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
    }
    /* get the current version and hash of the latest recovery document
       for this account */
    {
      struct GNUNET_HashCode dh;
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_uint32 ("version",
                                      version),
        GNUNET_PQ_result_spec_auto_from_type ("recovery_data_hash",
                                              &dh),
        GNUNET_PQ_result_spec_end
      };

      qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                     "latest_recovery_version_select",
                                                     params,
                                                     rs);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        GNUNET_break (0);
        rollback (pg);
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        *version = 1;
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        /* had an existing recovery_data, is it identical? */
        if (0 == GNUNET_memcmp (&dh,
                                recovery_data_hash))
        {
          /* Yes. Previous identical recovery data exists */
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_NO_RESULTS;
        }
        (*version)++;
        break;
      default:
        GNUNET_break (0);
        rollback (pg);
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      }
    }

    /* First, check if account exists */
    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_end
      };

      qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                     "user_select",
                                                     params,
                                                     rs);
    }
    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
      rollback (pg);
      return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
    case GNUNET_DB_STATUS_SOFT_ERROR:
      goto retry;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      rollback (pg);
      return ANASTASIS_DB_STORE_STATUS_PAYMENT_REQUIRED;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      /* handle interesting case below */
      break;
    }

    {
      uint32_t postcounter;

      /* lookup if the user has enough uploads left and decrement */
      {
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_auto_from_type (account_pub),
          GNUNET_PQ_query_param_auto_from_type (payment_secret),
          GNUNET_PQ_query_param_end
        };
        struct GNUNET_PQ_ResultSpec rs[] = {
          GNUNET_PQ_result_spec_uint32 ("post_counter",
                                        &postcounter),
          GNUNET_PQ_result_spec_end
        };

        qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                       "postcounter_select",
                                                       params,
                                                       rs);
        switch (qs)
        {
        case GNUNET_DB_STATUS_HARD_ERROR:
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SOFT_ERROR:
          goto retry;
        case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
          break;
        }
      }

      if (0 == postcounter)
      {
        rollback (pg);
        return ANASTASIS_DB_STORE_STATUS_STORE_LIMIT_EXCEEDED;
      }
      /* Decrement the postcounter by one */
      postcounter--;

      /* Update the postcounter in the Database */
      {
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_uint32 (&postcounter),
          GNUNET_PQ_query_param_auto_from_type (account_pub),
          GNUNET_PQ_query_param_auto_from_type (payment_secret),
          GNUNET_PQ_query_param_end
        };

        qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                 "postcounter_update",
                                                 params);
        switch (qs)
        {
        case GNUNET_DB_STATUS_HARD_ERROR:
          GNUNET_break (0);
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SOFT_ERROR:
          goto retry;
        case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
          GNUNET_break (0);
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
          break;
        default:
          GNUNET_break (0);
          rollback (pg);
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        }
      }
    }

    /* finally, actually insert the recovery document */
    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_uint32 (version),
        GNUNET_PQ_query_param_auto_from_type (account_sig),
        GNUNET_PQ_query_param_auto_from_type (recovery_data_hash),
        GNUNET_PQ_query_param_fixed_size (recovery_data,
                                          recovery_data_size),
        (NULL == recovery_meta_data)
        ? GNUNET_PQ_query_param_null ()
        : GNUNET_PQ_query_param_fixed_size (recovery_meta_data,
                                            recovery_meta_data_size),
        GNUNET_PQ_query_param_end
      };

      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "recovery_document_insert",
                                               params);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        rollback (pg);
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        GNUNET_break (0);
        rollback (pg);
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        qs = commit_transaction (pg);
        if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
          goto retry;
        if (qs < 0)
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        return ANASTASIS_DB_STORE_STATUS_SUCCESS;
      }
    }
retry:
    rollback (pg);
  }
  return ANASTASIS_DB_STORE_STATUS_SOFT_ERROR;
}


/**
 * Increment account lifetime based on payment having been received.
 * Does nothing if the payment is not new.
 *
 * @param cls closure
 * @param account_pub which account received a payment
 * @param payment_identifier proof of payment, must be unique and match pending payment
 * @param lifetime for how long is the account now paid (increment)
 * @param[out] paid_until set to the end of the lifetime after the operation
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_increment_lifetime (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  const struct ANASTASIS_PaymentSecretP *payment_identifier,
  struct GNUNET_TIME_Relative lifetime,
  struct GNUNET_TIME_Timestamp *paid_until)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Incrementing lifetime of account %s based on payment by %s\n",
              TALER_B2S (account_pub),
              GNUNET_TIME_relative2s (lifetime,
                                      true));
  check_connection (pg);
  for (unsigned int retries = 0; retries<MAX_RETRIES; retries++)
  {
    if (GNUNET_OK !=
        begin_transaction (pg,
                           "increment lifetime"))
    {
      GNUNET_break (0);
      return GNUNET_DB_STATUS_HARD_ERROR;
    }

    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (payment_identifier),
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "recdoc_payment_done",
                                               params);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        rollback (pg);
        *paid_until = GNUNET_TIME_UNIT_ZERO_TS;
        return qs;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        /* Payment not new or payment request unknown. */
        /* continued below */
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        /* Payment just now marked as 'paid' */
        /* continued below */
        break;
      }
    }

    {
      enum GNUNET_DB_QueryStatus qs2;
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_TIME_Timestamp expiration;
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_timestamp ("expiration_date",
                                         &expiration),
        GNUNET_PQ_result_spec_end
      };

      qs2 = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                      "user_select",
                                                      params,
                                                      rs);
      switch (qs2)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        rollback (pg);
        return qs2;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
        {
          /* inconsistent, cannot have recdoc payment but no user!? */
          GNUNET_break (0);
          rollback (pg);
          return GNUNET_DB_STATUS_HARD_ERROR;
        }
        else
        {
          /* user does not exist, create new one */
          struct GNUNET_PQ_QueryParam params[] = {
            GNUNET_PQ_query_param_auto_from_type (account_pub),
            GNUNET_PQ_query_param_timestamp (&expiration),
            GNUNET_PQ_query_param_end
          };

          expiration = GNUNET_TIME_relative_to_timestamp (lifetime);
          GNUNET_break (! GNUNET_TIME_absolute_is_never (expiration.abs_time));
          *paid_until = expiration;
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Creating new account %s with initial lifetime of %s\n",
                      TALER_B2S (account_pub),
                      GNUNET_TIME_relative2s (lifetime,
                                              true));
          qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                   "user_insert",
                                                   params);
        }
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
        {
          /* existing rec doc payment (payment replay), return
             existing expiration */
          *paid_until = expiration;
          rollback (pg);
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Payment existed, lifetime of account %s unchanged at %s\n",
                      TALER_B2S (account_pub),
                      GNUNET_TIME_timestamp2s (*paid_until));
          return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
        }
        else
        {
          /* user exists, payment is new, update expiration_date */
          struct GNUNET_PQ_QueryParam params[] = {
            GNUNET_PQ_query_param_timestamp (&expiration),
            GNUNET_PQ_query_param_auto_from_type (account_pub),
            GNUNET_PQ_query_param_end
          };

          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Incrementing lifetime of account %s by %s\n",
                      TALER_B2S (account_pub),
                      GNUNET_TIME_relative2s (lifetime,
                                              true));
          expiration
            = GNUNET_TIME_absolute_to_timestamp (
                GNUNET_TIME_absolute_add (expiration.abs_time,
                                          lifetime));
          GNUNET_break (! GNUNET_TIME_absolute_is_never (
                          expiration.abs_time));
          *paid_until = expiration;
          qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                   "user_update",
                                                   params);
        }
        break;
      }
    }

    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
      rollback (pg);
      return qs;
    case GNUNET_DB_STATUS_SOFT_ERROR:
      goto retry;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_break (0);
      rollback (pg);
      return GNUNET_DB_STATUS_HARD_ERROR;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      break;
    }
    qs = commit_transaction (pg);
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
      goto retry;
    if (qs < 0)
      return GNUNET_DB_STATUS_HARD_ERROR;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Incremented lifetime of account %s to %s\n",
                TALER_B2S (account_pub),
                GNUNET_TIME_timestamp2s (*paid_until));
    return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
retry:
    rollback (pg);
  }
  return GNUNET_DB_STATUS_SOFT_ERROR;
}


/**
 * Update account lifetime to the maximum of the current
 * value and @a eol.
 *
 * @param cls closure
 * @param account_pub which account received a payment
 * @param payment_identifier proof of payment, must be unique and match pending payment
 * @param eol for how long is the account now paid (absolute)
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_update_lifetime (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  const struct ANASTASIS_PaymentSecretP *payment_identifier,
  struct GNUNET_TIME_Timestamp eol)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  for (unsigned int retries = 0; retries<MAX_RETRIES; retries++)
  {
    if (GNUNET_OK !=
        begin_transaction (pg,
                           "update lifetime"))
    {
      GNUNET_break (0);
      return GNUNET_DB_STATUS_HARD_ERROR;
    }

    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (payment_identifier),
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "recdoc_payment_done",
                                               params);
      if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
        goto retry;
      if (0 >= qs)
      {
        /* same payment made before, or unknown, or error
           => no further action! */
        rollback (pg);
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Payment existed, lifetime of account %s unchanged\n",
                    TALER_B2S (account_pub));
        return qs;
      }
    }

    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_TIME_Timestamp expiration;
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_timestamp ("expiration_date",
                                         &expiration),
        GNUNET_PQ_result_spec_end
      };

      qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                     "user_select",
                                                     params,
                                                     rs);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        rollback (pg);
        return qs;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        {
          /* user does not exist, create new one */
          struct GNUNET_PQ_QueryParam params[] = {
            GNUNET_PQ_query_param_auto_from_type (account_pub),
            GNUNET_PQ_query_param_timestamp (&eol),
            GNUNET_PQ_query_param_end
          };

          GNUNET_break (! GNUNET_TIME_absolute_is_never (eol.abs_time));
          qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                   "user_insert",
                                                   params);
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Created new account %s with expiration %s\n",
                      TALER_B2S (account_pub),
                      GNUNET_TIME_timestamp2s (eol));
        }
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        {
          /* user exists, update expiration_date */
          struct GNUNET_PQ_QueryParam params[] = {
            GNUNET_PQ_query_param_timestamp (&expiration),
            GNUNET_PQ_query_param_auto_from_type (account_pub),
            GNUNET_PQ_query_param_end
          };

          expiration = GNUNET_TIME_timestamp_max (expiration,
                                                  eol);
          GNUNET_break (! GNUNET_TIME_absolute_is_never (expiration.abs_time));
          qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                   "user_update",
                                                   params);
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Updated account %s to new expiration %s\n",
                      TALER_B2S (account_pub),
                      GNUNET_TIME_timestamp2s (expiration));
        }
        break;
      }
    }

    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
      rollback (pg);
      return qs;
    case GNUNET_DB_STATUS_SOFT_ERROR:
      goto retry;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_break (0);
      rollback (pg);
      return GNUNET_DB_STATUS_HARD_ERROR;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      break;
    }
    qs = commit_transaction (pg);
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
      goto retry;
    if (qs < 0)
      return GNUNET_DB_STATUS_HARD_ERROR;
    return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
retry:
    rollback (pg);
  }
  return GNUNET_DB_STATUS_SOFT_ERROR;
}


/**
 * Store payment. Used to begin a payment, not indicative
 * that the payment actually was made. (That is done
 * when we increment the account's lifetime.)
 *
 * @param cls closure
 * @param account_pub anastasis's public key
 * @param post_counter how many uploads does @a amount pay for
 * @param payment_secret payment secret which the user must provide with every upload
 * @param amount how much we asked for
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_record_recdoc_payment (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  uint32_t post_counter,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  const struct TALER_Amount *amount)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_TIME_Timestamp expiration;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_uint32 (&post_counter),
    TALER_PQ_query_param_amount (amount),
    GNUNET_PQ_query_param_auto_from_type (payment_secret),
    GNUNET_PQ_query_param_timestamp (&now),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));

  /* because of constraint at user_id, first we have to verify
     if user exists, and if not, create one */
  {
    struct GNUNET_PQ_QueryParam params[] = {
      GNUNET_PQ_query_param_auto_from_type (account_pub),
      GNUNET_PQ_query_param_end
    };
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_timestamp ("expiration_date",
                                       &expiration),
      GNUNET_PQ_result_spec_end
    };

    qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "user_select",
                                                   params,
                                                   rs);
  }
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    return qs;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    {
      /* create new user with short lifetime */
      struct GNUNET_TIME_Timestamp exp
        = GNUNET_TIME_relative_to_timestamp (TRANSIENT_LIFETIME);
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_timestamp (&exp),
        GNUNET_PQ_query_param_end
      };

      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "user_insert",
                                               params);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        return GNUNET_DB_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        GNUNET_break (0);
        return GNUNET_DB_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        GNUNET_break (0);
        return GNUNET_DB_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        /* successful, continue below */
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Created new account %s with transient life until %s\n",
                    TALER_B2S (account_pub),
                    GNUNET_TIME_timestamp2s (exp));
        break;
      }
    }
    /* continue below */
    break;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    /* handle case below */
    break;
  }

  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "recdoc_payment_insert",
                                             params);
}


/**
 * Record truth upload payment was made.
 *
 * @param cls closure
 * @param uuid the truth's UUID
 * @param amount the amount that was paid
 * @param duration how long is the truth paid for
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_record_truth_upload_payment (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *uuid,
  const struct TALER_Amount *amount,
  struct GNUNET_TIME_Relative duration)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp exp = GNUNET_TIME_relative_to_timestamp (
    duration);
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (uuid),
    TALER_PQ_query_param_amount (amount),
    GNUNET_PQ_query_param_timestamp (&exp),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "truth_payment_insert",
                                             params);
}


/**
 * Inquire whether truth upload payment was made.
 *
 * @param cls closure
 * @param uuid the truth's UUID
 * @param[out] paid_until set for how long this truth is paid for
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_check_truth_upload_paid (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *uuid,
  struct GNUNET_TIME_Timestamp *paid_until)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (uuid),
    GNUNET_PQ_query_param_timestamp (&now),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_timestamp ("expiration",
                                     paid_until),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "truth_payment_select",
                                                   params,
                                                   rs);
}


/**
 * Store payment for challenge.
 *
 * @param cls closure
 * @param truth_uuid identifier of the challenge to pay
 * @param payment_secret payment secret which the user must provide with every upload
 * @param amount how much we asked for
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_record_challenge_payment (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  const struct TALER_Amount *amount)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    TALER_PQ_query_param_amount (amount),
    GNUNET_PQ_query_param_auto_from_type (payment_secret),
    GNUNET_PQ_query_param_timestamp (&now),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challenge_payment_insert",
                                             params);
}


/**
 * Store refund granted for challenge.
 *
 * @param cls closure
 * @param truth_uuid identifier of the challenge to refund
 * @param payment_secret payment secret which the user must provide with every upload
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_record_challenge_refund (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const struct ANASTASIS_PaymentSecretP *payment_secret)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (payment_secret),
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challenge_refund_update",
                                             params);
}


/**
 * Store inbound IBAN payment made for authentication.
 *
 * @param cls closure
 * @param wire_reference unique identifier inside LibEuFin/Nexus
 * @param wire_subject subject of the wire transfer
 * @param amount how much was transferred
 * @param debit_account account that was debited
 * @param credit_account Anastasis operator account credited
 * @param execution_date when was the transfer made
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_record_auth_iban_payment (
  void *cls,
  uint64_t wire_reference,
  const char *wire_subject,
  const struct TALER_Amount *amount,
  const char *debit_account,
  const char *credit_account,
  struct GNUNET_TIME_Timestamp execution_date)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&wire_reference),
    GNUNET_PQ_query_param_string (wire_subject),
    TALER_PQ_query_param_amount (amount),
    GNUNET_PQ_query_param_string (debit_account),
    GNUNET_PQ_query_param_string (credit_account),
    GNUNET_PQ_query_param_timestamp (&execution_date),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "store_auth_iban_payment_details",
                                             params);
}


/**
 * Closure for #test_auth_cb.
 */
struct TestIbanContext
{

  /**
   * Plugin context.
   */
  struct PostgresClosure *pg;

  /**
   * Function to call on each wire transfer found.
   */
  ANASTASIS_DB_AuthIbanTransfercheck cb;

  /**
   * Closure for @a cb.
   */
  void *cb_cls;

  /**
   * Value to return.
   */
  enum GNUNET_DB_QueryStatus qs;
};


/**
 * Helper function for #postgres_test_auth_iban_payment().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct TestIbanContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
test_auth_cb (void *cls,
              PGresult *result,
              unsigned int num_results)
{
  struct TestIbanContext *tic = cls;
  struct PostgresClosure *pg = tic->pg;

  for (unsigned int i = 0; i<num_results; i++)
  {
    struct TALER_Amount credit;
    char *wire_subject;
    struct GNUNET_PQ_ResultSpec rs[] = {
      TALER_PQ_result_spec_amount ("credit",
                                   pg->currency,
                                   &credit),
      GNUNET_PQ_result_spec_string ("wire_subject",
                                    &wire_subject),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      tic->qs = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    if (tic->cb (tic->cb_cls,
                 &credit,
                 wire_subject))
    {
      GNUNET_free (wire_subject);
      tic->qs = GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
      return;
    }
    GNUNET_free (wire_subject);
  }
}


/**
 * Function to check if we are aware of a wire transfer
 * that satisfies the IBAN plugin's authentication check.
 *
 * @param cls closure
 * @param debit_account which debit account to check
 * @param earliest_date earliest date to check
 * @param cb function to call on all entries found
 * @param cb_cls closure for @a cb
 * @return transaction status,
 *    #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT if @a cb
 *      returned 'true' once
 *    #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if no
 *      wire transfers existed for which @a cb returned true
 */
static enum GNUNET_DB_QueryStatus
postgres_test_auth_iban_payment (
  void *cls,
  const char *debit_account,
  struct GNUNET_TIME_Timestamp earliest_date,
  ANASTASIS_DB_AuthIbanTransfercheck cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct TestIbanContext tic = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (debit_account),
    GNUNET_PQ_query_param_timestamp (&earliest_date),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "test_auth_iban_payment",
                                             params,
                                             &test_auth_cb,
                                             &tic);
  if (qs < 0)
    return qs;
  return tic.qs;
}


/**
 * Function to check the last known IBAN payment.
 *
 * @param cls closure
 * @param credit_account which credit account to check
 * @param[out] last_row set to the last known row
 * @return transaction status,
 *    #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT if @a cb
 *      returned 'true' once
 *    #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if no
 *      wire transfers existed for which @a cb returned true
 */
static enum GNUNET_DB_QueryStatus
postgres_get_last_auth_iban_payment_row (
  void *cls,
  const char *credit_account,
  uint64_t *last_row)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (credit_account),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("wire_reference",
                                  last_row),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "get_last_auth_iban_payment",
                                                   params,
                                                   rs);
}


/**
 * Check payment identifier. Used to check if a payment identifier given by
 * the user is valid (existing and paid).
 *
 * @param cls closure
 * @param payment_secret payment secret which the user must provide with every upload
 * @param truth_uuid which truth should we check the payment status of
 * @param[out] paid bool value to show if payment is paid
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_check_challenge_payment (
  void *cls,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  bool *paid)
{
  struct PostgresClosure *pg = cls;
  uint8_t paid8;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (payment_secret),
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_auto_from_type ("paid",
                                          &paid8),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "challenge_payment_select",
                                                 params,
                                                 rs);
  *paid = (0 != paid8);
  return qs;
}


/**
 * Check payment identifier. Used to check if a payment identifier given by
 * the user is valid (existing and paid).
 *
 * @param cls closure
 * @param payment_secret payment secret which the user must provide with every upload
 * @param[out] paid bool value to show if payment is paid
 * @param[out] valid_counter bool value to show if post_counter is > 0
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_check_payment_identifier (
  void *cls,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  bool *paid,
  bool *valid_counter)
{
  struct PostgresClosure *pg = cls;
  uint32_t counter;
  uint8_t paid8;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (payment_secret),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_auto_from_type ("paid",
                                          &paid8),
    GNUNET_PQ_result_spec_uint32 ("post_counter",
                                  &counter),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "recdoc_payment_select",
                                                 params,
                                                 rs);

  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
  {
    if (counter > 0)
      *valid_counter = true;
    else
      *valid_counter = false;
    *paid = (0 != paid8);
  }
  return qs;
}


/**
 * Upload Truth, which contains the Truth and the KeyShare.
 *
 * @param cls closure
 * @param truth_uuid the identifier for the Truth
 * @param key_share_data contains information of an EncryptedKeyShare
 * @param mime_type presumed mime type of data in @a encrypted_truth
 * @param encrypted_truth contains the encrypted Truth which includes the ground truth i.e. H(challenge answer), phonenumber, SMS
 * @param encrypted_truth_size the size of the Truth
 * @param method name of method
 * @param truth_expiration time till the according data will be stored
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_store_truth (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const struct ANASTASIS_CRYPTO_EncryptedKeyShareP *key_share_data,
  const char *mime_type,
  const void *encrypted_truth,
  size_t encrypted_truth_size,
  const char *method,
  struct GNUNET_TIME_Relative truth_expiration)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp expiration;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_auto_from_type (key_share_data),
    GNUNET_PQ_query_param_string (method),
    GNUNET_PQ_query_param_fixed_size (encrypted_truth,
                                      encrypted_truth_size),
    GNUNET_PQ_query_param_string (mime_type),
    GNUNET_PQ_query_param_timestamp (&expiration),
    GNUNET_PQ_query_param_end
  };


  expiration = GNUNET_TIME_relative_to_timestamp (truth_expiration);
  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "truth_insert",
                                             params);
}


/**
 * Get the encrypted truth to validate the challenge response
 *
 * @param cls closure
 * @param truth_uuid the identifier for the Truth
 * @param[out] truth contains the encrypted truth
 * @param[out] truth_size size of the encrypted truth
 * @param[out] truth_mime mime type of truth
 * @param[out] method type of the challenge
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_get_escrow_challenge (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  void **truth,
  size_t *truth_size,
  char **truth_mime,
  char **method)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_variable_size ("encrypted_truth",
                                         truth,
                                         truth_size),
    GNUNET_PQ_result_spec_string ("truth_mime",
                                  truth_mime),
    GNUNET_PQ_result_spec_string ("method_name",
                                  method),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "truth_select",
                                                   params,
                                                   rs);
}


/**
 * Lookup (encrypted) key share by @a truth_uuid.
 *
 * @param cls closure
 * @param truth_uuid the identifier for the Truth
 * @param[out] key_share contains the encrypted Keyshare
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_get_key_share (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  struct ANASTASIS_CRYPTO_EncryptedKeyShareP *key_share)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_auto_from_type ("key_share_data",
                                          key_share),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "key_share_select",
                                                   params,
                                                   rs);
}


/**
 * Check if an account exists, and if so, return the
 * current @a recovery_document_hash.
 *
 * @param cls closure
 * @param account_pub account identifier
 * @param[out] paid_until until when is the account paid up?
 * @param[out] recovery_data_hash set to hash of @a recovery document
 * @param[out] version set to the recovery policy version
 * @return transaction status
 */
enum ANASTASIS_DB_AccountStatus
postgres_lookup_account (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  struct GNUNET_TIME_Timestamp *paid_until,
  struct GNUNET_HashCode *recovery_data_hash,
  uint32_t *version)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  {
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_timestamp ("expiration_date",
                                       paid_until),
      GNUNET_PQ_result_spec_auto_from_type ("recovery_data_hash",
                                            recovery_data_hash),
      GNUNET_PQ_result_spec_uint32 ("version",
                                    version),
      GNUNET_PQ_result_spec_end
    };

    qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "latest_recovery_version_select",
                                                   params,
                                                   rs);
  }
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    return ANASTASIS_DB_ACCOUNT_STATUS_HARD_ERROR;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return ANASTASIS_DB_ACCOUNT_STATUS_HARD_ERROR;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    break; /* handle interesting case below */
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    return ANASTASIS_DB_ACCOUNT_STATUS_VALID_HASH_RETURNED;
  }

  /* check if account exists */
  {
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_timestamp ("expiration_date",
                                       paid_until),
      GNUNET_PQ_result_spec_end
    };

    qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "user_select",
                                                   params,
                                                   rs);
  }
  switch (qs)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
    return ANASTASIS_DB_ACCOUNT_STATUS_HARD_ERROR;
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return ANASTASIS_DB_ACCOUNT_STATUS_HARD_ERROR;
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    /* indicates: no account */
    return ANASTASIS_DB_ACCOUNT_STATUS_PAYMENT_REQUIRED;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    /* indicates: no backup */
    *version = UINT32_MAX;
    memset (recovery_data_hash,
            0,
            sizeof (*recovery_data_hash));
    return ANASTASIS_DB_ACCOUNT_STATUS_NO_RESULTS;
  default:
    GNUNET_break (0);
    return ANASTASIS_DB_ACCOUNT_STATUS_HARD_ERROR;
  }
}


/**
 * Fetch latest recovery document for user.
 *
 * @param cls closure
 * @param account_pub public key of the user's account
 * @param account_sig signature
 * @param recovery_data_hash hash of the current recovery data
 * @param data_size size of data blob
 * @param data blob which contains the recovery document
 * @param[out] version set to the version number of the policy being returned
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_get_latest_recovery_document (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  struct ANASTASIS_AccountSignatureP *account_sig,
  struct GNUNET_HashCode *recovery_data_hash,
  size_t *data_size,
  void **data,
  uint32_t *version)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint32 ("version",
                                  version),
    GNUNET_PQ_result_spec_auto_from_type ("account_sig",
                                          account_sig),
    GNUNET_PQ_result_spec_auto_from_type ("recovery_data_hash",
                                          recovery_data_hash),
    GNUNET_PQ_result_spec_variable_size ("recovery_data",
                                         data,
                                         data_size),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "latest_recoverydocument_select",
                                                   params,
                                                   rs);
}


/**
 * Closure for meta_iterator().
 */
struct MetaIteratorContext
{
  /**
   * Function to call on each result.
   */
  ANASTASIS_DB_RecoveryMetaCallback cb;

  /**
   * Closure for @e cb.
   */
  void *cb_cls;

  /**
   * Set to true on database failure.
   */
  bool db_failure;
};


/**
 * Helper function for #postgres_get_recovery_meta_data().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct MetaIteratorContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
meta_iterator (void *cls,
               PGresult *result,
               unsigned int num_results)
{
  struct MetaIteratorContext *ctx = cls;

  for (unsigned int i = 0; i<num_results; i++)
  {
    uint32_t version;
    void *meta_data = NULL;
    size_t meta_data_size = 0;
    bool unused = false;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint32 ("version",
                                    &version),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_variable_size ("recovery_meta_data",
                                             &meta_data,
                                             &meta_data_size),
        &unused),
      GNUNET_PQ_result_spec_end
    };
    enum GNUNET_GenericReturnValue ret;

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      ctx->db_failure = true;
      return;
    }
    ret = ctx->cb (ctx->cb_cls,
                   version,
                   meta_data,
                   meta_data_size);
    GNUNET_PQ_cleanup_result (rs);
    if (GNUNET_OK != ret)
      break;
  }
}


/**
 * Fetch recovery document meta data for user. Returns
 * meta data in descending order from @a max_version.
 * The size of the result set may be limited.
 *
 * @param cls closure
 * @param account_pub public key of the user's account
 * @param max_version the maximum version number the user requests
 * @param cb function to call on each result
 * @param cb_cls closure for @a cb
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_get_recovery_meta_data (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  uint32_t max_version,
  ANASTASIS_DB_RecoveryMetaCallback cb,
  void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct MetaIteratorContext ctx = {
    .cb = cb,
    .cb_cls = cb_cls
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_uint32 (&max_version),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "recoverydocument_select_meta",
                                             params,
                                             &meta_iterator,
                                             &ctx);
  if (qs < 0)
    return qs;
  if (ctx.db_failure)
    return GNUNET_DB_STATUS_HARD_ERROR;
  return qs;
}


/**
 * Fetch recovery document for user according given version.
 *
 * @param cls closure
 * @param account_pub public key of the user's account
 * @param version the version number of the policy the user requests
 * @param[out] account_sig signature
 * @param[out] recovery_data_hash hash of the current recovery data
 * @param[out] data_size size of data blob
 * @param[out] data blob which contains the recovery document
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_get_recovery_document (
  void *cls,
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  uint32_t version,
  struct ANASTASIS_AccountSignatureP *account_sig,
  struct GNUNET_HashCode *recovery_data_hash,
  size_t *data_size,
  void **data)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (account_pub),
    GNUNET_PQ_query_param_uint32 (&version),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_auto_from_type ("account_sig",
                                          account_sig),
    GNUNET_PQ_result_spec_auto_from_type ("recovery_data_hash",
                                          recovery_data_hash),
    GNUNET_PQ_result_spec_variable_size ("recovery_data",
                                         data,
                                         data_size),
    GNUNET_PQ_result_spec_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "recoverydocument_select",
                                                   params,
                                                   rs);
}


/**
 * Closure for check_valid_code().
 */
struct CheckValidityContext
{
  /**
   * Code to check for.
   */
  const struct GNUNET_HashCode *hashed_code;

  /**
   * Truth we are processing.
   */
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid;

  /**
   * Database context.
   */
  struct PostgresClosure *pg;

  /**
   * Set to the matching challenge code (if @e valid).
   */
  uint64_t code;

  /**
   * Set to true if a code matching @e hashed_code was found.
   */
  bool valid;

  /**
   * Set to true if a code matching @e hashed_code was set to 'satisfied' by the plugin.
   */
  bool satisfied;

  /**
   * Set to true if we had a database failure.
   */
  bool db_failure;

};


/**
 * Helper function for #postgres_verify_challenge_code().
 * To be called with the results of a SELECT statement
 * that has returned @a num_results results.
 *
 * @param cls closure of type `struct CheckValidityContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
check_valid_code (void *cls,
                  PGresult *result,
                  unsigned int num_results)
{
  struct CheckValidityContext *cvc = cls;
  struct PostgresClosure *pg = cvc->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    uint64_t server_code;
    uint8_t sat;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_uint64 ("code",
                                    &server_code),
      GNUNET_PQ_result_spec_auto_from_type ("satisfied",
                                            &sat),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      cvc->db_failure = true;
      return;
    }
    {
      struct GNUNET_HashCode shashed_code;

      ANASTASIS_hash_answer (server_code,
                             &shashed_code);
      if (0 ==
          GNUNET_memcmp (&shashed_code,
                         cvc->hashed_code))
      {
        cvc->valid = true;
        cvc->code = server_code;
        cvc->satisfied = (0 != sat);
      }
      else
      {
        /* count failures to prevent brute-force attacks */
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_auto_from_type (cvc->truth_uuid),
          GNUNET_PQ_query_param_uint64 (&server_code),
          GNUNET_PQ_query_param_end
        };
        enum GNUNET_DB_QueryStatus qs;

        qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                 "challengecode_update_retry",
                                                 params);
        if (qs <= 0)
        {
          GNUNET_break (0);
          cvc->db_failure = true;
        }
      }
    }
  }
}


/**
 * Verify the provided code with the code on the server.
 * If the code matches the function will return with success, if the code
 * does not match, the retry counter will be decreased by one.
 *
 * @param cls closure
 * @param truth_uuid identification of the challenge which the code corresponds to
 * @param hashed_code code which the user provided and wants to verify
 * @param[out] code set to the original numeric code
 * @param[out] satisfied set to true if the challenge is set to satisfied
 * @return code validity status
 */
enum ANASTASIS_DB_CodeStatus
postgres_verify_challenge_code (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const struct GNUNET_HashCode *hashed_code,
  uint64_t *code,
  bool *satisfied)
{
  struct PostgresClosure *pg = cls;
  struct CheckValidityContext cvc = {
    .truth_uuid = truth_uuid,
    .hashed_code = hashed_code,
    .pg = pg
  };
  struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_timestamp (&now),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  *satisfied = false;
  check_connection (pg);
  qs = GNUNET_PQ_eval_prepared_multi_select (pg->conn,
                                             "challengecode_select",
                                             params,
                                             &check_valid_code,
                                             &cvc);
  if ( (qs < 0) ||
       (cvc.db_failure) )
    return ANASTASIS_DB_CODE_STATUS_HARD_ERROR;
  *code = cvc.code;
  if (cvc.valid)
  {
    *satisfied = cvc.satisfied;
    return ANASTASIS_DB_CODE_STATUS_VALID_CODE_STORED;
  }
  if (0 == qs)
    return ANASTASIS_DB_CODE_STATUS_NO_RESULTS;
  return ANASTASIS_DB_CODE_STATUS_CHALLENGE_CODE_MISMATCH;
}


/**
 * Set the 'satisfied' bit for the given challenge and code to
 * 'true'.
 *
 * @param cls closure
 * @param truth_uuid identification of the challenge which the code corresponds to
 * @param code code which is now satisfied
 * @return transaction status
 */
static enum GNUNET_DB_QueryStatus
postgres_mark_challenge_code_satisfied (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const uint64_t code)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_uint64 (&code),
    GNUNET_PQ_query_param_end
  };

  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challengecode_set_satisfied",
                                             params);
}


/**
 * Check if the 'satisfied' bit for the given challenge and code is
 * 'true' and the challenge code is not yet expired.
 *
 * @param cls closure
 * @param truth_uuid identification of the challenge which the code corresponds to
 * @param code code which is now satisfied
 * @return transaction status,
 *        #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if the challenge code is not satisfied or expired
 *        #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT if the challenge code has been marked as satisfied
 */
static enum GNUNET_DB_QueryStatus
postgres_test_challenge_code_satisfied (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const uint64_t code,
  struct GNUNET_TIME_Timestamp after)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_uint64 (&code),
    GNUNET_PQ_query_param_timestamp (&after),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_end
  };

  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "challengecode_test_satisfied",
                                                   params,
                                                   rs);
}


/**
 * Lookup pending payment for a certain challenge.
 *
 * @param cls closure
 * @param truth_uuid identification of the challenge
 * @param[out] payment_secret set to the challenge payment secret
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_lookup_challenge_payment (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  struct ANASTASIS_PaymentSecretP *payment_secret)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
  struct GNUNET_TIME_Timestamp recent
    = GNUNET_TIME_absolute_to_timestamp (
        GNUNET_TIME_absolute_subtract (now,
                                       ANASTASIS_CHALLENGE_OFFER_LIFETIME));
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_timestamp (&recent),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_auto_from_type ("payment_identifier",
                                          payment_secret),
    GNUNET_PQ_result_spec_end
  };

  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "challenge_pending_payment_select",
                                                   params,
                                                   rs);
}


/**
 * Update payment status of challenge
 *
 * @param cls closure
 * @param truth_uuid which challenge received a payment
 * @param payment_identifier proof of payment, must be unique and match pending payment
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_update_challenge_payment (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  const struct ANASTASIS_PaymentSecretP *payment_identifier)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (payment_identifier),
    GNUNET_PQ_query_param_auto_from_type (truth_uuid),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challenge_payment_done",
                                             params);
}


/**
 * Create a new challenge code for a given challenge identified by the challenge
 * public key. The function will first check if there is already a valid code
 * for this challenge present and won't insert a new one in this case.
 *
 * @param cls closure
 * @param truth_uuid the identifier for the challenge
 * @param rotation_period for how long is the code available
 * @param validity_period for how long is the code available
 * @param retry_counter amount of retries allowed
 * @param[out] retransmission_date when to next retransmit
 * @param[out] code set to the code which will be checked for later
 * @return transaction status,
 *        #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if we are out of valid tries,
 *        #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT if @a code is now in the DB
 */
enum GNUNET_DB_QueryStatus
postgres_create_challenge_code (
  void *cls,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  struct GNUNET_TIME_Relative rotation_period,
  struct GNUNET_TIME_Relative validity_period,
  uint32_t retry_counter,
  struct GNUNET_TIME_Timestamp *retransmission_date,
  uint64_t *code)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;
  struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_TIME_Timestamp expiration_date;
  struct GNUNET_TIME_Absolute ex_rot;

  check_connection (pg);
  expiration_date = GNUNET_TIME_relative_to_timestamp (validity_period);
  ex_rot = GNUNET_TIME_absolute_subtract (now.abs_time,
                                          rotation_period);
  for (unsigned int retries = 0; retries<MAX_RETRIES; retries++)
  {
    if (GNUNET_OK !=
        begin_transaction (pg,
                           "create_challenge_code"))
    {
      GNUNET_break (0);
      return GNUNET_DB_STATUS_HARD_ERROR;
    }

    {
      uint32_t old_retry_counter;
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (truth_uuid),
        GNUNET_PQ_query_param_timestamp (&now),
        GNUNET_PQ_query_param_absolute_time (&ex_rot),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_uint64 ("code",
                                      code),
        GNUNET_PQ_result_spec_uint32 ("retry_counter",
                                      &old_retry_counter),
        GNUNET_PQ_result_spec_timestamp ("retransmission_date",
                                         retransmission_date),
        GNUNET_PQ_result_spec_end
      };
      enum GNUNET_DB_QueryStatus qs;

      qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                     "challengecode_select_meta",
                                                     params,
                                                     rs);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        GNUNET_break (0);
        rollback (pg);
        return qs;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "No active challenge found, creating a fresh one\n");
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        if (0 == old_retry_counter)
        {
          rollback (pg);
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Active challenge %llu has zero tries left, refusing to create another one\n",
                      (unsigned long long) code);
          return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
        }
        rollback (pg);
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Active challenge has %u tries left, returning old challenge\n",
                    (unsigned int) old_retry_counter);
        return qs;
      }
    }

    *code = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE,
                                      ANASTASIS_PIN_MAX_VALUE);
    *retransmission_date = GNUNET_TIME_UNIT_ZERO_TS;
    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (truth_uuid),
        GNUNET_PQ_query_param_uint64 (code),
        GNUNET_PQ_query_param_timestamp (&now),
        GNUNET_PQ_query_param_timestamp (&expiration_date),
        GNUNET_PQ_query_param_uint32 (&retry_counter),
        GNUNET_PQ_query_param_end
      };

      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "challengecode_insert",
                                               params);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        rollback (pg);
        return GNUNET_DB_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        GNUNET_break (0);
        rollback (pg);
        return GNUNET_DB_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Created fresh challenge with %u tries left\n",
                    (unsigned int) retry_counter);
        break;
      }
    }
    qs = commit_transaction (pg);
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
      goto retry;
    if (qs < 0)
      return qs;
    return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
retry:
    rollback (pg);
  }
  return GNUNET_DB_STATUS_SOFT_ERROR;
}


/**
 * Remember in the database that we successfully sent a challenge.
 *
 * @param cls closure
 * @param payment_secret payment secret which the user must provide with every upload
 * @param truth_uuid the identifier for the challenge
 * @param code the challenge that was sent
 */
static enum GNUNET_DB_QueryStatus
postgres_mark_challenge_sent (
  void *cls,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  const struct ANASTASIS_CRYPTO_TruthUUIDP *truth_uuid,
  uint64_t code)
{
  struct PostgresClosure *pg = cls;
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  {
    struct GNUNET_TIME_Timestamp now;
    struct GNUNET_PQ_QueryParam params[] = {
      GNUNET_PQ_query_param_auto_from_type (truth_uuid),
      GNUNET_PQ_query_param_uint64 (&code),
      GNUNET_PQ_query_param_timestamp (&now),
      GNUNET_PQ_query_param_end
    };

    now = GNUNET_TIME_timestamp_get ();
    qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challengecode_mark_sent",
                                             params);
    if (qs <= 0)
      return qs;
  }
  {
    struct GNUNET_PQ_QueryParam params[] = {
      GNUNET_PQ_query_param_auto_from_type (truth_uuid),
      GNUNET_PQ_query_param_auto_from_type (payment_secret),
      GNUNET_PQ_query_param_end
    };

    qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "challengepayment_dec_counter",
                                             params);
    if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
      return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT; /* probably was free */
    return qs;
  }
}


/**
 * Function called to remove all expired codes from the database.
 *
 * @return transaction status
 */
enum GNUNET_DB_QueryStatus
postgres_challenge_gc (void *cls)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_TIME_Timestamp time_now = GNUNET_TIME_timestamp_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_timestamp (&time_now),
    GNUNET_PQ_query_param_end
  };

  check_connection (pg);
  GNUNET_break (GNUNET_OK ==
                postgres_preflight (pg));
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "gc_challengecodes",
                                             params);
}


/**
 * Initialize Postgres database subsystem.
 *
 * @param cls a configuration instance
 * @return NULL on error, otherwise a `struct TALER_ANASTASISDB_Plugin`
 */
void *
libanastasis_plugin_db_postgres_init (void *cls)
{
  struct GNUNET_CONFIGURATION_Handle *cfg = cls;
  struct PostgresClosure *pg;
  struct ANASTASIS_DatabasePlugin *plugin;

  pg = GNUNET_new (struct PostgresClosure);
  pg->cfg = cfg;
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_string (cfg,
                                             "taler",
                                             "CURRENCY",
                                             &pg->currency))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               "taler",
                               "CURRENCY");
    GNUNET_PQ_disconnect (pg->conn);
    GNUNET_free (pg);
    return NULL;
  }
  plugin = GNUNET_new (struct ANASTASIS_DatabasePlugin);
  plugin->cls = pg;
  /* FIXME: Should this be the same? */
  plugin->connect = &postgres_preflight;
  plugin->create_tables = &postgres_create_tables;
  plugin->drop_tables = &postgres_drop_tables;
  plugin->gc = &postgres_gc;
  plugin->preflight = &postgres_preflight;
  plugin->rollback = &rollback;
  plugin->commit = &commit_transaction;
  plugin->event_listen = &postgres_event_listen;
  plugin->event_listen_cancel = &postgres_event_listen_cancel;
  plugin->event_notify = &postgres_event_notify;
  plugin->store_recovery_document = &postgres_store_recovery_document;
  plugin->record_recdoc_payment = &postgres_record_recdoc_payment;
  plugin->store_truth = &postgres_store_truth;
  plugin->get_escrow_challenge = &postgres_get_escrow_challenge;
  plugin->get_key_share = &postgres_get_key_share;
  plugin->get_latest_recovery_document = &postgres_get_latest_recovery_document;
  plugin->get_recovery_meta_data = &postgres_get_recovery_meta_data;
  plugin->get_recovery_document = &postgres_get_recovery_document;
  plugin->lookup_account = &postgres_lookup_account;
  plugin->check_payment_identifier = &postgres_check_payment_identifier;
  plugin->increment_lifetime = &postgres_increment_lifetime;
  plugin->update_lifetime = &postgres_update_lifetime;
  plugin->start = &begin_transaction;
  plugin->check_connection = &check_connection;
  plugin->verify_challenge_code = &postgres_verify_challenge_code;
  plugin->mark_challenge_code_satisfied =
    &postgres_mark_challenge_code_satisfied;
  plugin->test_challenge_code_satisfied =
    &postgres_test_challenge_code_satisfied;
  plugin->create_challenge_code = &postgres_create_challenge_code;
  plugin->mark_challenge_sent = &postgres_mark_challenge_sent;
  plugin->challenge_gc = &postgres_challenge_gc;
  plugin->record_truth_upload_payment = &postgres_record_truth_upload_payment;
  plugin->check_truth_upload_paid = &postgres_check_truth_upload_paid;
  plugin->record_challenge_payment = &postgres_record_challenge_payment;
  plugin->record_challenge_refund = &postgres_record_challenge_refund;
  plugin->check_challenge_payment = &postgres_check_challenge_payment;
  plugin->lookup_challenge_payment = &postgres_lookup_challenge_payment;
  plugin->update_challenge_payment = &postgres_update_challenge_payment;
  plugin->record_auth_iban_payment = &postgres_record_auth_iban_payment;
  plugin->test_auth_iban_payment = &postgres_test_auth_iban_payment;
  plugin->get_last_auth_iban_payment_row
    = &postgres_get_last_auth_iban_payment_row;
  return plugin;
}


/**
 * Shutdown Postgres database subsystem.
 *
 * @param cls a `struct ANASTASIS_DB_STATUS_Plugin`
 * @return NULL (always)
 */
void *
libanastasis_plugin_db_postgres_done (void *cls)
{
  struct ANASTASIS_DatabasePlugin *plugin = cls;
  struct PostgresClosure *pg = plugin->cls;

  GNUNET_PQ_disconnect (pg->conn);
  GNUNET_free (pg->currency);
  GNUNET_free (pg);
  GNUNET_free (plugin);
  return NULL;
}


/* end of plugin_anastasisdb_postgres.c */