aboutsummaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_private-post-orders.c
blob: 370050d468f6c6e1edb2fe72fd25a33752fbed80 (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
/*
  This file is part of TALER
  (C) 2014-2023 Taler Systems SA

  TALER 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.

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

  You should have received a copy of the GNU General Public
  License along with TALER; see the file COPYING.  If not,
  see <http://www.gnu.org/licenses/>
*/

/**
 * @file taler-merchant-httpd_private-post-orders.c
 * @brief the POST /orders handler
 * @author Christian Grothoff
 * @author Marcello Stanisci
 */
#include "platform.h"
#include <jansson.h>
#include <taler/taler_signatures.h>
#include <taler/taler_json_lib.h>
#include "taler-merchant-httpd_private-post-orders.h"
#include "taler-merchant-httpd_exchanges.h"
#include "taler-merchant-httpd_helper.h"
#include "taler-merchant-httpd_private-get-orders.h"


/**
 * How often do we retry the simple INSERT database transaction?
 */
#define MAX_RETRIES 3

/**
 * What is the label under which we find/place the merchant's
 * jurisdiction in the locations list by default?
 */
#define STANDARD_LABEL_MERCHANT_JURISDICTION "_mj"

/**
 * What is the label under which we find/place the merchant's
 * address in the locations list by default?
 */
#define STANDARD_LABEL_MERCHANT_ADDRESS "_ma"


/**
 * Generate the base URL for the given merchant instance.
 *
 * @param connection the MHD connection
 * @param instance_id the merchant instance ID
 * @returns the merchant instance's base URL
 */
static char *
make_merchant_base_url (struct MHD_Connection *connection,
                        const char *instance_id)
{
  struct GNUNET_Buffer buf;

  if (GNUNET_OK !=
      TMH_base_url_by_connection (connection,
                                  instance_id,
                                  &buf))
    return NULL;
  GNUNET_buffer_write_path (&buf,
                            "");
  return GNUNET_buffer_reap_str (&buf);
}


/**
 * Information about a product we are supposed to add to the order
 * based on what we know it from our inventory.
 */
struct InventoryProduct
{
  /**
   * Identifier of the product in the inventory.
   */
  const char *product_id;

  /**
   * Number of units of the product to add to the order.
   */
  uint32_t quantity;
};


/**
 * Handle for a rekey operation where we (re)request
 * the /keys from the exchange.
 */
struct RekeyExchange
{
  /**
   * Kept in a DLL.
   */
  struct RekeyExchange *prev;

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

  /**
   * order this is for.
   */
  struct OrderContext *oc;

  /**
   * Base URL of the exchange.
   */
  char *url;

  /**
   * Request for keys.
   */
  struct TMH_EXCHANGES_KeysOperation *fo;

};


/**
 * Information we keep per order we are processing.
 */
struct OrderContext
{

  /**
   * Connection of the request.
   */
  struct MHD_Connection *connection;

  /**
   * Kept in a DLL while suspended.
   */
  struct OrderContext *next;

  /**
   * Kept in a DLL while suspended.
   */
  struct OrderContext *prev;

  /**
   * Handler context for the request.
   */
  struct TMH_HandlerContext *hc;

  /**
   * Hash of the POST request data, used to detect
   * idempotent requests.
   */
  struct TALER_MerchantPostDataHashP h_post_data;

  /**
   * Payment deadline.
   */
  struct GNUNET_TIME_Timestamp pay_deadline;

  /**
   * Set to how long refunds will be allowed.
   */
  struct GNUNET_TIME_Relative refund_delay;

  /**
   * Order we are building (modified as we process
   * the request).
   */
  json_t *order;

  /**
   * Array of exchanges we find acceptable for this
   * order.
   */
  json_t *exchanges;

  /**
   * RFC8905 payment target type to find a matching merchant account
   */
  const char *payment_target;

  /**
   * Wire method (and our bank account) we have selected
   * to be included for this order.
   */
  const struct TMH_WireMethod *wm;

  /**
   * Forced requests to /keys to update our exchange
   * information.
   */
  struct RekeyExchange *pending_reload_head;

  /**
   * Forced requests to /keys to update our exchange
   * information.
   */
  struct RekeyExchange *pending_reload_tail;

  /**
   * Claim token for the request.
   */
  struct TALER_ClaimTokenP claim_token;

  /**
   * Length of the @e inventory_products array.
   */
  unsigned int inventory_products_length;

  /**
   * Array of inventory products in the @e order.
   */
  struct InventoryProduct *inventory_products;

  /**
   * array of UUIDs used to reserve products from @a inventory_products.
   */
  struct GNUNET_Uuid *uuids;

  /**
   * Shared key to use with @e pos_algorithm.
   */
  const char *pos_key;

  /**
   * Our order ID. Pointer into @e order.
   */
  const char *order_id;

  /**
   * which product (by offset) is out of stock, UINT_MAX if all were in-stock
   */
  unsigned int out_of_stock_index;

  /**
   * Length of the @e uuids array.
   */
  unsigned int uuids_length;

  /**
   * #GNUNET_YES if suspended.
   */
  enum GNUNET_GenericReturnValue suspended;

  /**
   * Selected algorithm (by template) when we are to
   * generate an OTP code for payment confirmation.
   */
  enum TALER_MerchantConfirmationAlgorithm pos_algorithm;

  /**
   * Current phase of setting up the order.
   */
  enum
  {
    ORDER_PHASE_INIT,
    ORDER_PHASE_MERGE_INVENTORY,
    ORDER_PHASE_ADD_PAYMENT_DETAILS,
    ORDER_PHASE_PATCH_ORDER,
    ORDER_PHASE_SET_EXCHANGES,
    ORDER_PHASE_CHECK_CONTRACT,
    ORDER_PHASE_EXECUTE_ORDER,

    /**
     * Processing is done, we should return #MHD_YES.
     */
    ORDER_PHASE_FINISHED_MHD_YES,

    /**
     * Processing is done, we should return #MHD_NO.
     */
    ORDER_PHASE_FINISHED_MHD_NO
  } phase;

  /**
   * Set to true once we are sure that we have at
   * least one good exchange.
   */
  bool exchange_good;

  /**
   * Did we previously force reloading of /keys from
   * all exchanges? Set to 'true' to prevent us from
   * doing it again (and again...).
   */
  bool forced_reload;

};


/**
 * Kept in a DLL while suspended.
 */
static struct OrderContext *oc_head;

/**
 * Kept in a DLL while suspended.
 */
static struct OrderContext *oc_tail;


void
TMH_force_orders_resume ()
{
  struct OrderContext *oc;

  while (NULL != (oc = oc_head))
  {
    GNUNET_CONTAINER_DLL_remove (oc_head,
                                 oc_tail,
                                 oc);
    oc->suspended = GNUNET_SYSERR;
    MHD_resume_connection (oc->connection);
  }
}


/**
 * Update the phase of @a oc based on @a mret.
 *
 * @param[in,out] oc order to update phase for
 * @param mret #MHD_NO to close with #MHD_NO
 *             #MHD_YES to close with #MHD_YES
 */
static void
finalize_order (struct OrderContext *oc,
                MHD_RESULT mret)
{
  oc->phase = (MHD_YES == mret)
    ? ORDER_PHASE_FINISHED_MHD_YES
    : ORDER_PHASE_FINISHED_MHD_NO;
}


/**
 * Update the phase of @a oc based on @a ret.
 *
 * @param[in,out] oc order to update phase for
 * @param ret #GNUNET_SYSERR to close with #MHD_NO
 *            #GNUNET_NO to close with #MHD_YES
 *            #GNUNET_OK is not allowed!
 */
static void
finalize_order2 (struct OrderContext *oc,
                 enum GNUNET_GenericReturnValue ret)
{
  GNUNET_assert (GNUNET_OK != ret);
  oc->phase = (GNUNET_NO == ret)
    ? ORDER_PHASE_FINISHED_MHD_YES
    : ORDER_PHASE_FINISHED_MHD_NO;
}


/**
 * Generate an error response for @a oc.
 *
 * @param[in,out] oc order context to respond to
 * @param http_status HTTP status code to set
 * @param ec error code to set
 * @param detail error message detail to set
 */
static void
reply_with_error (struct OrderContext *oc,
                  unsigned int http_status,
                  enum TALER_ErrorCode ec,
                  const char *detail)
{
  MHD_RESULT mret;

  mret = TALER_MHD_reply_with_error (oc->connection,
                                     http_status,
                                     ec,
                                     detail);
  finalize_order (oc,
                  mret);
}


/**
 * Clean up memory used by @a cls.
 *
 * @param[in] cls the `struct OrderContext` to clean up
 */
static void
clean_order (void *cls)
{
  struct OrderContext *oc = cls;
  struct RekeyExchange *rx;

  while (NULL != (rx = oc->pending_reload_head))
  {
    GNUNET_CONTAINER_DLL_remove (oc->pending_reload_head,
                                 oc->pending_reload_tail,
                                 rx);
    TMH_EXCHANGES_keys4exchange_cancel (rx->fo);
    GNUNET_free (rx->url);
    GNUNET_free (rx);
  }
  if (NULL != oc->exchanges)
  {
    json_decref (oc->exchanges);
    oc->exchanges = NULL;
  }
  GNUNET_array_grow (oc->inventory_products,
                     oc->inventory_products_length,
                     0);
  GNUNET_array_grow (oc->uuids,
                     oc->uuids_length,
                     0);
  json_decref (oc->order);
  GNUNET_free (oc);
}


/**
 * Execute the database transaction to setup the order.
 *
 * @param[in,out] oc order context
 * @return transaction status, #GNUNET_DB_STATUS_SUCCESS_NO_RESULTS if @a uuids were insufficient to reserve required inventory
 */
static enum GNUNET_DB_QueryStatus
execute_transaction (struct OrderContext *oc)
{
  enum GNUNET_DB_QueryStatus qs;
  struct GNUNET_TIME_Timestamp timestamp;
  uint64_t order_serial;

  if (GNUNET_OK !=
      TMH_db->start (TMH_db->cls,
                     "insert_order"))
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  /* Setup order */
  qs = TMH_db->insert_order (TMH_db->cls,
                             oc->hc->instance->settings.id,
                             oc->order_id,
                             &oc->h_post_data,
                             oc->pay_deadline,
                             &oc->claim_token,
                             oc->order,  /* called 'contract terms' at database. */
                             oc->pos_key,
                             oc->pos_algorithm);
  if (qs <= 0)
  {
    /* qs == 0: probably instance does not exist (anymore) */
    TMH_db->rollback (TMH_db->cls);
    return qs;
  }
  /* Migrate locks from UUIDs to new order: first release old locks */
  for (unsigned int i = 0; i<oc->uuids_length; i++)
  {
    qs = TMH_db->unlock_inventory (TMH_db->cls,
                                   &oc->uuids[i]);
    if (qs < 0)
    {
      TMH_db->rollback (TMH_db->cls);
      return qs;
    }
    /* qs == 0 is OK here, that just means we did not HAVE any lock under this
       UUID */
  }
  /* Migrate locks from UUIDs to new order: acquire new locks
     (note: this can basically ONLY fail on serializability OR
     because the UUID locks were insufficient for the desired
     quantities). */
  for (unsigned int i = 0; i<oc->inventory_products_length; i++)
  {
    qs = TMH_db->insert_order_lock (
      TMH_db->cls,
      oc->hc->instance->settings.id,
      oc->order_id,
      oc->inventory_products[i].product_id,
      oc->inventory_products[i].quantity);
    if (qs < 0)
    {
      TMH_db->rollback (TMH_db->cls);
      return qs;
    }
    if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    {
      /* qs == 0: lock acquisition failed due to insufficient stocks */
      TMH_db->rollback (TMH_db->cls);
      oc->out_of_stock_index = i; /* indicate which product is causing the issue */
      return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
    }
  }
  oc->out_of_stock_index = UINT_MAX;

  /* Get the order serial and timestamp for the order we just created to
     update long-poll clients. */
  qs = TMH_db->lookup_order_summary (TMH_db->cls,
                                     oc->hc->instance->settings.id,
                                     oc->order_id,
                                     &timestamp,
                                     &order_serial);
  if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != qs)
  {
    TMH_db->rollback (TMH_db->cls);
    return qs;
  }
  TMH_notify_order_change (oc->hc->instance,
                           TMH_OSF_NONE,
                           timestamp,
                           order_serial);
  /* finally, commit transaction (note: if it fails, we ALSO re-acquire
     the UUID locks, which is exactly what we want) */
  qs = TMH_db->commit (TMH_db->cls);
  if (0 > qs)
    return qs;
  return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;   /* 1 == success! */
}


/**
 * Transform an order into a proposal and store it in the
 * database. Write the resulting proposal or an error message
 * of a MHD connection.
 *
 * @param[in,out] oc order context
 */
static void
execute_order (struct OrderContext *oc)
{
  const struct TALER_MERCHANTDB_InstanceSettings *settings =
    &oc->hc->instance->settings;
  struct TALER_Amount total;
  const char *summary;
  const char *fulfillment_msg = NULL;
  const json_t *products;
  const json_t *merchant;
  struct GNUNET_TIME_Timestamp timestamp;
  struct GNUNET_TIME_Timestamp refund_deadline = { 0 };
  struct GNUNET_TIME_Timestamp wire_transfer_deadline;
  struct GNUNET_JSON_Specification spec[] = {
    TALER_JSON_spec_amount ("amount",
                            TMH_currency,
                            &total),
    GNUNET_JSON_spec_string ("order_id",
                             &oc->order_id),
    TALER_JSON_spec_i18n_str ("summary",
                              &summary),
    /**
     * The following entries we don't actually need,
     * except to check that the order is well-formed */
    GNUNET_JSON_spec_array_const ("products",
                                  &products),
    GNUNET_JSON_spec_object_const ("merchant",
                                   &merchant),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_i18n_str ("fulfillment_message",
                                &fulfillment_msg),
      NULL),
    GNUNET_JSON_spec_timestamp ("timestamp",
                                &timestamp),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("refund_deadline",
                                  &refund_deadline),
      NULL),
    GNUNET_JSON_spec_timestamp ("pay_deadline",
                                &oc->pay_deadline),
    GNUNET_JSON_spec_timestamp ("wire_transfer_deadline",
                                &wire_transfer_deadline),
    GNUNET_JSON_spec_end ()
  };
  enum GNUNET_DB_QueryStatus qs;

  /* extract fields we need to sign separately */
  {
    enum GNUNET_GenericReturnValue res;

    res = TALER_MHD_parse_json_data (oc->connection,
                                     oc->order,
                                     spec);
    if (GNUNET_OK != res)
    {
      GNUNET_break_op (0);
      finalize_order2 (oc,
                       res);
      return;
    }
  }

  /* check product list in contract is well-formed */
  if (! TMH_products_array_valid (products))
  {
    GNUNET_JSON_parse_free (spec);
    GNUNET_break_op (0);
    reply_with_error (oc,
                      MHD_HTTP_BAD_REQUEST,
                      TALER_EC_GENERIC_PARAMETER_MALFORMED,
                      "order:products");
    return;
  }

  /* Test if we already have an order with this id */
  {
    struct TALER_ClaimTokenP token;
    json_t *contract_terms;
    struct TALER_MerchantPostDataHashP orig_post;

    TMH_db->preflight (TMH_db->cls);
    qs = TMH_db->lookup_order (TMH_db->cls,
                               oc->hc->instance->settings.id,
                               oc->order_id,
                               &token,
                               &orig_post,
                               &contract_terms);
    /* If yes, check for idempotency */
    if (0 > qs)
    {
      GNUNET_break (0);
      TMH_db->rollback (TMH_db->cls);
      GNUNET_JSON_parse_free (spec);
      reply_with_error (oc,
                        MHD_HTTP_INTERNAL_SERVER_ERROR,
                        TALER_EC_GENERIC_DB_FETCH_FAILED,
                        "lookup_order");
      return;
    }
    if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
    {
      MHD_RESULT ret;

      json_decref (contract_terms);
      /* Comparing the contract terms is sufficient because all the other
         params get added to it at some point. */
      if (0 == GNUNET_memcmp (&orig_post,
                              &oc->h_post_data))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Order creation idempotent\n");
        ret = TALER_MHD_REPLY_JSON_PACK (
          oc->connection,
          MHD_HTTP_OK,
          GNUNET_JSON_pack_string ("order_id",
                                   oc->order_id),
          GNUNET_JSON_pack_allow_null (
            GNUNET_JSON_pack_data_varsize (
              "token",
              GNUNET_is_zero (&token)
              ? NULL
              : &token,
              sizeof (token))));
        GNUNET_JSON_parse_free (spec);
        finalize_order (oc,
                        ret);
        return;
      }
      /* This request is not idempotent */
      GNUNET_break_op (0);
      reply_with_error (
        oc,
        MHD_HTTP_CONFLICT,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_ALREADY_EXISTS,
        oc->order_id);
      GNUNET_JSON_parse_free (spec);
      return;
    }
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Executing database transaction to create order '%s' for instance '%s'\n",
              oc->order_id,
              settings->id);
  for (unsigned int i = 0; i<MAX_RETRIES; i++)
  {
    TMH_db->preflight (TMH_db->cls);
    qs = execute_transaction (oc);
    if (GNUNET_DB_STATUS_SOFT_ERROR != qs)
      break;
  }
  if (0 >= qs)
  {
    GNUNET_JSON_parse_free (spec);
    /* Special report if retries insufficient */
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
    {
      GNUNET_break (0);
      reply_with_error (oc,
                        MHD_HTTP_INTERNAL_SERVER_ERROR,
                        TALER_EC_GENERIC_DB_SOFT_FAILURE,
                        NULL);
      return;
    }
    if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    {
      /* should be: contract (!) with same order ID
         already exists */
      reply_with_error (
        oc,
        MHD_HTTP_CONFLICT,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_ALREADY_EXISTS,
        oc->order_id);
      return;
    }
    /* Other hard transaction error (disk full, etc.) */
    GNUNET_break (0);
    reply_with_error (
      oc,
      MHD_HTTP_INTERNAL_SERVER_ERROR,
      TALER_EC_GENERIC_DB_COMMIT_FAILED,
      NULL);
    return;
  }

  /* DB transaction succeeded, check for out-of-stock */
  if (oc->out_of_stock_index < UINT_MAX)
  {
    /* We had a product that has insufficient quantities,
       generate the details for the response. */
    struct TALER_MERCHANTDB_ProductDetails pd;
    MHD_RESULT ret;

    memset (&pd,
            0,
            sizeof (pd));
    qs = TMH_db->lookup_product (
      TMH_db->cls,
      oc->hc->instance->settings.id,
      oc->inventory_products[oc->out_of_stock_index].product_id,
      &pd);
    GNUNET_JSON_parse_free (spec);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Order creation failed: product out of stock\n");
      ret = TALER_MHD_REPLY_JSON_PACK (
        oc->connection,
        MHD_HTTP_GONE,
        GNUNET_JSON_pack_string (
          "product_id",
          oc->inventory_products[oc->out_of_stock_index].product_id),
        GNUNET_JSON_pack_uint64 (
          "requested_quantity",
          oc->inventory_products[oc->out_of_stock_index].quantity),
        GNUNET_JSON_pack_uint64 (
          "available_quantity",
          pd.total_stock - pd.total_sold - pd.total_lost),
        GNUNET_JSON_pack_allow_null (
          GNUNET_JSON_pack_timestamp (
            "restock_expected",
            pd.next_restock)));
      TALER_MERCHANTDB_product_details_free (&pd);
      finalize_order (oc,
                      ret);
      return;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Order creation failed: unknown product out of stock\n");
      finalize_order (oc,
                      TALER_MHD_REPLY_JSON_PACK (
                        oc->connection,
                        MHD_HTTP_GONE,
                        GNUNET_JSON_pack_string (
                          "product_id",
                          oc->inventory_products[oc->out_of_stock_index].
                          product_id),
                        GNUNET_JSON_pack_uint64 (
                          "requested_quantity",
                          oc->inventory_products[oc->out_of_stock_index].
                          quantity),
                        GNUNET_JSON_pack_uint64 (
                          "available_quantity",
                          0)));
      return;
    case GNUNET_DB_STATUS_SOFT_ERROR:
      GNUNET_break (0);
      reply_with_error (
        oc,
        MHD_HTTP_INTERNAL_SERVER_ERROR,
        TALER_EC_GENERIC_DB_SOFT_FAILURE,
        NULL);
      return;
    case GNUNET_DB_STATUS_HARD_ERROR:
      GNUNET_break (0);
      reply_with_error (
        oc,
        MHD_HTTP_INTERNAL_SERVER_ERROR,
        TALER_EC_GENERIC_DB_FETCH_FAILED,
        NULL);
      return;
    }
    GNUNET_break (0);
    oc->phase = ORDER_PHASE_FINISHED_MHD_NO;
    return;
  } /* end 'out of stock' case */

  /* Everything in-stock, generate positive response */
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Order creation succeeded\n");
  {
    MHD_RESULT ret;

    ret = TALER_MHD_REPLY_JSON_PACK (
      oc->connection,
      MHD_HTTP_OK,
      GNUNET_JSON_pack_string ("order_id",
                               oc->order_id),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_data_varsize (
          "token",
          GNUNET_is_zero (&oc->claim_token)
          ? NULL
          : &oc->claim_token,
          sizeof (oc->claim_token))));
    GNUNET_JSON_parse_free (spec);
    finalize_order (oc,
                    ret);
  }
}


/**
 * Check that the contract is now well-formed.
 *
 * @param[in,out] oc order context
 */
static void
check_contract (struct OrderContext *oc)
{
  struct TALER_PrivateContractHashP h_control;

  switch (TALER_JSON_contract_hash (oc->order,
                                    &h_control))
  {
  case GNUNET_SYSERR:
    GNUNET_break (0);
    reply_with_error (
      oc,
      MHD_HTTP_INTERNAL_SERVER_ERROR,
      TALER_EC_GENERIC_FAILED_COMPUTE_JSON_HASH,
      "could not compute hash of patched order");
    return;
  case GNUNET_NO:
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_GENERIC_FAILED_COMPUTE_JSON_HASH,
      "order contained unallowed values");
    return;
  case GNUNET_OK:
    oc->phase++;
    return;
  }
  GNUNET_assert (0);
}


/**
 * Compute the set of exchanges that would be acceptable
 * for this order.
 *
 * @param cls our `struct OrderContext`
 * @param url base URL of an exchange (not used)
 * @param exchange internal handle for the exchange
 */
static void
get_acceptable (void *cls,
                const char *url,
                const struct TMH_Exchange *exchange)
{
  struct OrderContext *oc = cls;
  unsigned int priority;
  json_t *j_exchange;
  enum GNUNET_GenericReturnValue res;

  res = TMH_exchange_check_debit (exchange,
                                  oc->wm);
  switch (res)
  {
  case GNUNET_OK:
    priority = 1024;   /* high */
    oc->exchange_good = true;
    break;
  case GNUNET_NO:
    if (oc->forced_reload)
      priority = 0;   /* fresh negative response */
    else
      priority = 512; /* stale negative response */
    break;
  case GNUNET_SYSERR:
    if (oc->forced_reload)
      priority = 256;   /* fresh, no accounts yet */
    else
      priority = 768;  /* stale, no accounts yet */
    break;
  }
  j_exchange = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("url",
                             url),
    GNUNET_JSON_pack_uint64 ("priority",
                             priority),
    GNUNET_JSON_pack_data_auto ("master_pub",
                                TMH_EXCHANGES_get_master_pub (exchange)));
  GNUNET_assert (NULL != j_exchange);
  GNUNET_assert (0 ==
                 json_array_append_new (oc->exchanges,
                                        j_exchange));
}


/**
 * Function called with the result of a #TMH_EXCHANGES_keys4exchange()
 * operation.
 *
 * @param cls closure with our `struct RekeyExchange *`
 * @param keys the keys of the exchange
 * @param exchange representation of the exchange
 */
static void
keys_forced (
  void *cls,
  struct TALER_EXCHANGE_Keys *keys,
  struct TMH_Exchange *exchange)
{
  struct RekeyExchange *rx = cls;
  struct OrderContext *oc = rx->oc;

  rx->fo = NULL;
  GNUNET_CONTAINER_DLL_remove (oc->pending_reload_head,
                               oc->pending_reload_tail,
                               rx);
  if (NULL == keys)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Failed to download %s/keys\n",
                rx->url);
  }
  get_acceptable (oc,
                  rx->url,
                  exchange);
  GNUNET_free (rx->url);
  GNUNET_free (rx);
  if (NULL != oc->pending_reload_head)
    return;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Resuming order processing after /keys downloads (now have %u accounts)\n",
              (unsigned int) json_array_size (oc->exchanges));
  GNUNET_assert (GNUNET_YES == oc->suspended);
  GNUNET_CONTAINER_DLL_remove (oc_head,
                               oc_tail,
                               oc);
  oc->suspended = GNUNET_NO;
  MHD_resume_connection (oc->connection);
  TALER_MHD_daemon_trigger (); /* we resumed, kick MHD */
}


/**
 * Force re-downloading of /keys from @a exchange,
 * we currently have no acceptable exchange, so we
 * should try to get one.
 *
 * @param cls closure with our `struct OrderContext`
 * @param url base URL of the exchange
 * @param exchange internal handle for the exchange
 */
static void
rekey_exchanges (void *cls,
                 const char *url,
                 const struct TMH_Exchange *exchange)
{
  struct OrderContext *oc = cls;
  struct RekeyExchange *rx;

  rx = GNUNET_new (struct RekeyExchange);
  rx->oc = oc;
  rx->url = GNUNET_strdup (url);
  GNUNET_CONTAINER_DLL_insert (oc->pending_reload_head,
                               oc->pending_reload_tail,
                               rx);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Forcing download of %s/keys\n",
              url);
  rx->fo = TMH_EXCHANGES_keys4exchange (url,
                                        true,
                                        &keys_forced,
                                        rx);
}


/**
 * Set list of acceptable exchanges in @a oc.
 *
 * @param[in,out] oc order context
 * @return true to suspend execution
 */
static bool
set_exchanges (struct OrderContext *oc)
{
  /* Note: re-building 'oc->exchanges' every time here might be a tad
     expensive; could likely consider caching the result if it starts to
     matter. */
  if (NULL == oc->exchanges)
    oc->exchanges = json_array ();
  TMH_exchange_get_trusted (&get_acceptable,
                            oc);
  if (! oc->exchange_good)
  {
    if (! oc->forced_reload)
    {
      oc->forced_reload = true;
      GNUNET_assert (0 ==
                     json_array_clear (oc->exchanges));
      TMH_exchange_get_trusted (&rekey_exchanges,
                                oc);
    }
    if (NULL != oc->pending_reload_head)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Still trying to re-load /keys\n");
      MHD_suspend_connection (oc->connection);
      oc->suspended = GNUNET_YES;
      GNUNET_CONTAINER_DLL_insert (oc_head,
                                   oc_tail,
                                   oc);
      return true; /* reloads pending */
    }
    if (0 == json_array_size (oc->exchanges))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Cannot create order: lacking trusted exchanges\n");
      reply_with_error (
        oc,
        MHD_HTTP_CONFLICT,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_NO_EXCHANGES_FOR_WIRE_METHOD,
        oc->wm->wire_method);
      return false;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Creating order, but possibly without usable trusted exchanges\n");
  }
  /* 'set' is correct here: reference in oc->exchanges released in cleanup_order() */
  GNUNET_assert (0 ==
                 json_object_set (oc->order,
                                  "exchanges",
                                  oc->exchanges));
  oc->phase++;
  return false;
}


/**
 * Add missing fields to the order.  Upon success, continue
 * processing with execute_order().
 *
 * @param[in,out] oc order context
 */
static void
patch_order (struct OrderContext *oc)
{
  const struct TALER_MERCHANTDB_InstanceSettings *settings =
    &oc->hc->instance->settings;
  const char *order_id = NULL;
  const char *fulfillment_url = NULL;
  const char *merchant_base_url = NULL;
  const json_t *jmerchant = NULL;
  const json_t *delivery_location = NULL;
  struct TALER_Amount max_fee = { 0 };
  struct GNUNET_TIME_Timestamp timestamp
    = GNUNET_TIME_UNIT_ZERO_TS;
  struct GNUNET_TIME_Timestamp delivery_date
    = GNUNET_TIME_UNIT_ZERO_TS;
  struct GNUNET_TIME_Timestamp refund_deadline
    = GNUNET_TIME_UNIT_FOREVER_TS;
  struct GNUNET_TIME_Timestamp wire_deadline
    = GNUNET_TIME_UNIT_FOREVER_TS;
  /* auto_refund only needs to be type-checked,
   * mostly because in GNUnet relative times can't
   * be negative.  */
  struct GNUNET_TIME_Relative auto_refund;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("merchant_base_url",
                               &merchant_base_url),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("merchant",
                                     &jmerchant),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("order_id",
                               &order_id),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("fulfillment_url",
                               &fulfillment_url),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("timestamp",
                                  &timestamp),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("refund_deadline",
                                  &refund_deadline),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("pay_deadline",
                                  &oc->pay_deadline),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("wire_transfer_deadline",
                                  &wire_deadline),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount ("max_fee",
                              TMH_currency,
                              &max_fee),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_timestamp ("delivery_date",
                                  &delivery_date),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_relative_time ("auto_refund",
                                      &auto_refund),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_object_const ("delivery_location",
                                     &delivery_location),
      NULL),
    GNUNET_JSON_spec_end ()
  };
  enum GNUNET_GenericReturnValue ret;

  ret = TALER_MHD_parse_json_data (oc->connection,
                                   oc->order,
                                   spec);
  if (GNUNET_OK != ret)
  {
    GNUNET_break_op (0);
    finalize_order2 (oc,
                     ret);
    return;
  }

  /* Add order_id if it doesn't exist. */
  if (NULL == order_id)
  {
    char buf[256];
    time_t timer;
    struct tm *tm_info;
    size_t off;
    uint64_t rand;
    char *last;
    json_t *jbuf;

    time (&timer);
    tm_info = localtime (&timer);
    if (NULL == tm_info)
    {
      GNUNET_JSON_parse_free (spec);
      reply_with_error (
        oc,
        MHD_HTTP_INTERNAL_SERVER_ERROR,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_NO_LOCALTIME,
        NULL);
    }
    off = strftime (buf,
                    sizeof (buf) - 1,
                    "%Y.%j",
                    tm_info);
    /* Check for error state of strftime */
    GNUNET_assert (0 != off);
    buf[off++] = '-';
    rand = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
                                     UINT64_MAX);
    last = GNUNET_STRINGS_data_to_string (&rand,
                                          sizeof (uint64_t),
                                          &buf[off],
                                          sizeof (buf) - off);
    GNUNET_assert (NULL != last);
    *last = '\0';
    jbuf = json_string (buf);
    GNUNET_assert (NULL != jbuf);
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Assigning order ID `%s' server-side\n",
                buf);
    GNUNET_break (0 ==
                  json_object_set_new (oc->order,
                                       "order_id",
                                       jbuf));
    order_id = json_string_value (jbuf);
    GNUNET_assert (NULL != order_id);
  }

  /* Patch fulfillment URL with order_id (implements #6467). */
  if (NULL != fulfillment_url)
  {
    const char *pos;

    pos = strstr (fulfillment_url,
                  "${ORDER_ID}");
    if (NULL != pos)
    {
      /* replace ${ORDER_ID} with the real order_id */
      char *nurl;

      /* We only allow one placeholder */
      if (strstr (pos + strlen ("${ORDER_ID}"),
                  "${ORDER_ID}"))
      {
        GNUNET_break_op (0);
        reply_with_error (oc,
                          MHD_HTTP_BAD_REQUEST,
                          TALER_EC_GENERIC_PARAMETER_MALFORMED,
                          "fulfillment_url");
        return;
      }

      GNUNET_asprintf (&nurl,
                       "%.*s%s%s",
                       /* first output URL until ${ORDER_ID} */
                       (int) (pos - fulfillment_url),
                       fulfillment_url,
                       /* replace ${ORDER_ID} with the right order_id */
                       order_id,
                       /* append rest of original URL */
                       pos + strlen ("${ORDER_ID}"));
      /* replace in JSON of the order */
      GNUNET_break (0 ==
                    json_object_set_new (oc->order,
                                         "fulfillment_url",
                                         json_string (nurl)));
      GNUNET_free (nurl);
    }
  }

  /* Check soundness of refund deadline, and that a timestamp
   * is actually present.  */
  {
    struct GNUNET_TIME_Timestamp now = GNUNET_TIME_timestamp_get ();

    /* Add timestamp if it doesn't exist (or is zero) */
    if (GNUNET_TIME_absolute_is_zero (timestamp.abs_time))
    {
      GNUNET_assert (0 ==
                     json_object_set_new (oc->order,
                                          "timestamp",
                                          GNUNET_JSON_from_timestamp (now)));
    }

    /* If no refund_deadline given, set one based on refund_delay.  */
    if (GNUNET_TIME_absolute_is_never (refund_deadline.abs_time))
    {
      if (GNUNET_TIME_relative_is_zero (oc->refund_delay))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Refund delay is zero, no refunds are possible for this order\n");
        refund_deadline = GNUNET_TIME_UNIT_ZERO_TS;
      }
      else
      {
        refund_deadline = GNUNET_TIME_relative_to_timestamp (oc->refund_delay);
      }
      GNUNET_assert (0 ==
                     json_object_set_new (oc->order,
                                          "refund_deadline",
                                          GNUNET_JSON_from_timestamp (
                                            refund_deadline)));
    }
    if ( (! GNUNET_TIME_absolute_is_zero (delivery_date.abs_time)) &&
         (GNUNET_TIME_absolute_is_past (delivery_date.abs_time)) )
    {
      GNUNET_break_op (0);
      reply_with_error (
        oc,
        MHD_HTTP_BAD_REQUEST,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_DELIVERY_DATE_IN_PAST,
        NULL);
      return;
    }
  }

  if (GNUNET_TIME_absolute_is_zero (oc->pay_deadline.abs_time))
  {
    oc->pay_deadline = GNUNET_TIME_relative_to_timestamp (
      settings->default_pay_delay);
    GNUNET_assert (0 ==
                   json_object_set_new (oc->order,
                                        "pay_deadline",
                                        GNUNET_JSON_from_timestamp (
                                          oc->pay_deadline)));
  }
  else if (GNUNET_TIME_absolute_is_past (oc->pay_deadline.abs_time))
  {
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_PAY_DEADLINE_IN_PAST,
      NULL);
    return;
  }
  if ( (! GNUNET_TIME_absolute_is_zero (refund_deadline.abs_time)) &&
       (GNUNET_TIME_absolute_is_past (refund_deadline.abs_time)) )
  {
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_REFUND_DEADLINE_IN_PAST,
      NULL);
    return;
  }

  if (GNUNET_TIME_absolute_is_never (wire_deadline.abs_time))
  {
    struct GNUNET_TIME_Timestamp t;

    t = GNUNET_TIME_relative_to_timestamp (
      GNUNET_TIME_relative_max (settings->default_wire_transfer_delay,
                                oc->refund_delay));
    wire_deadline = GNUNET_TIME_timestamp_max (refund_deadline,
                                               t);
    if (GNUNET_TIME_absolute_is_never (wire_deadline.abs_time))
    {
      GNUNET_break_op (0);
      reply_with_error (
        oc,
        MHD_HTTP_BAD_REQUEST,
        TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_WIRE_DEADLINE_IS_NEVER,
        "order:wire_transfer_deadline");
      return;
    }
    GNUNET_assert (0 ==
                   json_object_set_new (oc->order,
                                        "wire_transfer_deadline",
                                        GNUNET_JSON_from_timestamp (
                                          wire_deadline)));
  }
  if (GNUNET_TIME_timestamp_cmp (wire_deadline,
                                 <,
                                 refund_deadline))
  {
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_REFUND_AFTER_WIRE_DEADLINE,
      "order:wire_transfer_deadline;order:refund_deadline");
    return;
  }

  /* Note: total amount currency match checked
     later in execute_order() */
  if (GNUNET_OK !=
      TALER_amount_is_valid (&max_fee))
  {
    struct TALER_Amount stefan;

    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (TMH_currency,
                                          &stefan));
    if (settings->use_stefan)
    {
      /* FIXME: update amount from stefan curve! */
      stefan.value = 5; // FIXME!
    }

    GNUNET_assert (0 ==
                   json_object_set_new (
                     oc->order,
                     "max_fee",
                     TALER_JSON_from_amount (&stefan)));
  }

  if (NULL == merchant_base_url)
  {
    char *url;

    url = make_merchant_base_url (oc->connection,
                                  settings->id);
    if (NULL == url)
    {
      GNUNET_break_op (0);
      reply_with_error (
        oc,
        MHD_HTTP_BAD_REQUEST,
        TALER_EC_GENERIC_PARAMETER_MISSING,
        "order:merchant_base_url");
      return;
    }
    GNUNET_assert (0 ==
                   json_object_set_new (oc->order,
                                        "merchant_base_url",
                                        json_string (url)));
    GNUNET_free (url);
  }
  else if (('\0' == *merchant_base_url) ||
           ('/' != merchant_base_url[strlen (merchant_base_url) - 1]))
  {
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_PROPOSAL_PARSE_ERROR,
      "merchant_base_url is not valid");
    return;
  }

  /* Merchant information must not already be present */
  if (NULL != jmerchant)
  {
    GNUNET_break_op (0);
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_PROPOSAL_PARSE_ERROR,
      "'merchant' field already set, but must be provided by backend");
    return;
  }

  {
    json_t *jm;

    jm = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_string ("name",
                               settings->name),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_string ("website",
                                 settings->website)),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_string ("email",
                                 settings->email)),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_string ("logo",
                                 settings->logo)));
    GNUNET_assert (NULL != jm);
    {
      json_t *loca;

      /* Handle merchant address */
      loca = settings->address;
      if (NULL != loca)
      {
        loca = json_deep_copy (loca);
        GNUNET_assert (0 ==
                       json_object_set_new (jm,
                                            "address",
                                            loca));
      }
    }
    {
      json_t *locj;

      /* Handle merchant jurisdiction */
      locj = settings->jurisdiction;
      if (NULL != locj)
      {
        locj = json_deep_copy (locj);
        GNUNET_assert (0 ==
                       json_object_set_new (jm,
                                            "jurisdiction",
                                            locj));
      }
    }
    GNUNET_assert (0 ==
                   json_object_set_new (oc->order,
                                        "merchant",
                                        jm));
  }

  GNUNET_assert (0 ==
                 json_object_set_new (oc->order,
                                      "merchant_pub",
                                      GNUNET_JSON_from_data_auto (
                                        &oc->hc->instance->merchant_pub)));

  if (GNUNET_OK !=
      TALER_JSON_contract_seed_forgettable (oc->order))
  {
    reply_with_error (
      oc,
      MHD_HTTP_BAD_REQUEST,
      TALER_EC_GENERIC_JSON_INVALID,
      "could not compute hash of order due to bogus forgettable fields");
    return;
  }

  if ( (NULL != delivery_location) &&
       (! TMH_location_object_valid (delivery_location)) )
  {
    GNUNET_break_op (0);
    reply_with_error (oc,
                      MHD_HTTP_BAD_REQUEST,
                      TALER_EC_GENERIC_PARAMETER_MALFORMED,
                      "delivery_location");
    return;
  }
  oc->phase++;
}


/**
 * Process the @a payment_target and add the details of how the
 * order could be paid to @a order. On success, continue
 * processing with patch_order().
 *
 * @param[in,out] oc order context
 */
static void
add_payment_details (struct OrderContext *oc)
{
  struct TMH_WireMethod *wm;

  wm = oc->hc->instance->wm_head;
  /* Locate wire method that has a matching payment target */
  while ( (NULL != wm) &&
          ( (! wm->active) ||
            ( (NULL != oc->payment_target) &&
              (0 != strcasecmp (oc->payment_target,
                                wm->wire_method) ) ) ) )
    wm = wm->next;
  if (NULL == wm)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "No wire method available for instance '%s'\n",
                oc->hc->instance->settings.id);
    reply_with_error (oc,
                      MHD_HTTP_NOT_FOUND,
                      TALER_EC_MERCHANT_PRIVATE_POST_ORDERS_INSTANCE_CONFIGURATION_LACKS_WIRE,
                      oc->payment_target);
    return;
  }
  oc->wm = wm;
  GNUNET_assert (0 ==
                 json_object_set_new (oc->order,
                                      "h_wire",
                                      GNUNET_JSON_from_data_auto (
                                        &wm->h_wire)));
  GNUNET_assert (0 ==
                 json_object_set_new (oc->order,
                                      "wire_method",
                                      json_string (wm->wire_method)));
  oc->phase++;
}


/**
 * Merge the inventory products into @a order, querying the
 * database about the details of those products. Upon success,
 * continue processing by calling add_payment_details().
 *
 * @param[in,out] oc order context to process
 */
static void
merge_inventory (struct OrderContext *oc)
{
  /**
   * inventory_products => instructions to add products to contract terms
   * order.products => contains products that are not from the backend-managed inventory.
   */
  {
    json_t *jprod = json_object_get (oc->order,
                                     "products");
    if (NULL == jprod)
    {
      GNUNET_assert (0 ==
                     json_object_set_new (oc->order,
                                          "products",
                                          json_array ()));
    }
    else if (! TMH_products_array_valid (jprod))
    {
      reply_with_error (oc,
                        MHD_HTTP_BAD_REQUEST,
                        TALER_EC_GENERIC_PARAMETER_MALFORMED,
                        "order.products");
      return;
    }
  }

  /* Populate products from inventory product array and database */
  {
    json_t *np = json_array ();

    GNUNET_assert (NULL != np);
    for (unsigned int i = 0; i<oc->inventory_products_length; i++)
    {
      struct TALER_MERCHANTDB_ProductDetails pd;
      enum GNUNET_DB_QueryStatus qs;

      qs = TMH_db->lookup_product (TMH_db->cls,
                                   oc->hc->instance->settings.id,
                                   oc->inventory_products[i].product_id,
                                   &pd);
      if (qs <= 0)
      {
        enum TALER_ErrorCode ec = TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
        unsigned int http_status = 0;

        switch (qs)
        {
        case GNUNET_DB_STATUS_HARD_ERROR:
          GNUNET_break (0);
          http_status = MHD_HTTP_INTERNAL_SERVER_ERROR;
          ec = TALER_EC_GENERIC_DB_FETCH_FAILED;
          break;
        case GNUNET_DB_STATUS_SOFT_ERROR:
          GNUNET_break (0);
          http_status = MHD_HTTP_INTERNAL_SERVER_ERROR;
          ec = TALER_EC_GENERIC_DB_SOFT_FAILURE;
          break;
        case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      "Product %s from order unknown\n",
                      oc->inventory_products[i].product_id);
          http_status = MHD_HTTP_NOT_FOUND;
          ec = TALER_EC_MERCHANT_GENERIC_PRODUCT_UNKNOWN;
          break;
        case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
          /* case listed to make compilers happy */
          GNUNET_assert (0);
        }
        json_decref (np);
        reply_with_error (oc,
                          http_status,
                          ec,
                          oc->inventory_products[i].product_id);
        return;
      }
      {
        json_t *p;

        p = GNUNET_JSON_PACK (
          GNUNET_JSON_pack_string ("description",
                                   pd.description),
          GNUNET_JSON_pack_object_steal ("description_i18n",
                                         pd.description_i18n),
          GNUNET_JSON_pack_string ("unit",
                                   pd.unit),
          TALER_JSON_pack_amount ("price",
                                  &pd.price),
          GNUNET_JSON_pack_array_steal ("taxes",
                                        pd.taxes),
          GNUNET_JSON_pack_string ("image",
                                   pd.image),
          GNUNET_JSON_pack_uint64 (
            "quantity",
            oc->inventory_products[i].quantity));
        GNUNET_assert (NULL != p);
        GNUNET_assert (0 ==
                       json_array_append_new (np,
                                              p));
      }
      GNUNET_free (pd.description);
      GNUNET_free (pd.unit);
      GNUNET_free (pd.image);
      json_decref (pd.address);
    }
    /* merge into existing products list */
    {
      json_t *xp;

      xp = json_object_get (oc->order,
                            "products");
      GNUNET_assert (NULL != xp);
      json_array_extend (xp, np);
      json_decref (np);
    }
  }
  oc->phase++;
}


static void
parse_order_request (struct OrderContext *oc)
{
  const json_t *ip = NULL;
  const json_t *uuid = NULL;
  bool create_token = true; /* default */
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_json ("order",
                           &oc->order),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_relative_time ("refund_delay",
                                      &oc->refund_delay),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("payment_target",
                               &oc->payment_target),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_array_const ("inventory_products",
                                    &ip),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_array_const ("lock_uuids",
                                    &uuid),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_bool ("create_token",
                             &create_token),
      NULL),
    GNUNET_JSON_spec_end ()
  };
  enum GNUNET_GenericReturnValue ret;

  ret = TALER_MHD_parse_json_data (oc->connection,
                                   oc->hc->request_body,
                                   spec);
  if (GNUNET_OK != ret)
  {
    GNUNET_break_op (0);
    finalize_order2 (oc,
                     ret);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Refund delay is %s\n",
              GNUNET_TIME_relative2s (oc->refund_delay,
                                      false));
  TMH_db->expire_locks (TMH_db->cls);
  if (create_token)
  {
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
                                &oc->claim_token,
                                sizeof (oc->claim_token));
  }
  /* Compute h_post_data (for idempotency check) */
  {
    char *req_body_enc;

    /* Dump normalized JSON to string. */
    if (NULL == (req_body_enc
                   = json_dumps (oc->hc->request_body,
                                 JSON_ENCODE_ANY
                                 | JSON_COMPACT
                                 | JSON_SORT_KEYS)))
    {
      GNUNET_break (0);
      GNUNET_JSON_parse_free (spec);
      reply_with_error (oc,
                        MHD_HTTP_INTERNAL_SERVER_ERROR,
                        TALER_EC_GENERIC_ALLOCATION_FAILURE,
                        "request body normalization for hashing");
      return;
    }
    GNUNET_CRYPTO_hash (req_body_enc,
                        strlen (req_body_enc),
                        &oc->h_post_data.hash);
    GNUNET_free (req_body_enc);
  }

  /* parse the inventory_products (optionally given) */
  if (NULL != ip)
  {
    GNUNET_array_grow (oc->inventory_products,
                       oc->inventory_products_length,
                       json_array_size (ip));
    for (unsigned int i = 0; i<oc->inventory_products_length; i++)
    {
      struct InventoryProduct *ipr = &oc->inventory_products[i];
      const char *error_name;
      unsigned int error_line;
      struct GNUNET_JSON_Specification ispec[] = {
        GNUNET_JSON_spec_string ("product_id",
                                 &ipr->product_id),
        GNUNET_JSON_spec_uint32 ("quantity",
                                 &ipr->quantity),
        GNUNET_JSON_spec_end ()
      };

      ret = GNUNET_JSON_parse (json_array_get (ip,
                                               i),
                               ispec,
                               &error_name,
                               &error_line);
      if (GNUNET_OK != ret)
      {
        GNUNET_break_op (0);
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Product parsing failed at #%u: %s:%u\n",
                    i,
                    error_name,
                    error_line);
        reply_with_error (oc,
                          MHD_HTTP_BAD_REQUEST,
                          TALER_EC_GENERIC_PARAMETER_MALFORMED,
                          "inventory_products");
        return;
      }
    }
  }

  /* parse the lock_uuids (optionally given) */
  if (NULL != uuid)
  {
    GNUNET_array_grow (oc->uuids,
                       oc->uuids_length,
                       json_array_size (uuid));
    for (unsigned int i = 0; i<oc->uuids_length; i++)
    {
      json_t *ui = json_array_get (uuid,
                                   i);

      if (! json_is_string (ui))
      {
        GNUNET_break_op (0);
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "UUID parsing failed at #%u\n",
                    i);
        reply_with_error (oc,
                          MHD_HTTP_BAD_REQUEST,
                          TALER_EC_GENERIC_PARAMETER_MALFORMED,
                          "lock_uuids");
        return;
      }
      TMH_uuid_from_string (json_string_value (ui),
                            &oc->uuids[i]);
    }
  }
  oc->phase++;
}


MHD_RESULT
TMH_private_post_orders_with_pos_secrets (
  const struct TMH_RequestHandler *rh,
  struct MHD_Connection *connection,
  struct TMH_HandlerContext *hc,
  const char *pos_key,
  enum TALER_MerchantConfirmationAlgorithm pos_algorithm)
{
  struct OrderContext *oc = hc->ctx;

  if (NULL == oc)
  {
    oc = GNUNET_new (struct OrderContext);
    hc->ctx = oc;
    hc->cc = &clean_order;
    oc->connection = connection;
    oc->hc = hc;
    oc->pos_key = pos_key;
    oc->pos_algorithm = pos_algorithm;
  }
  while (1)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Processing order in phase %d\n",
                oc->phase);
    switch (oc->phase)
    {
    case ORDER_PHASE_INIT:
      parse_order_request (oc);
      break;
    case ORDER_PHASE_MERGE_INVENTORY:
      merge_inventory (oc);
      break;
    case ORDER_PHASE_ADD_PAYMENT_DETAILS:
      add_payment_details (oc);
      break;
    case ORDER_PHASE_PATCH_ORDER:
      patch_order (oc);
      break;
    case ORDER_PHASE_SET_EXCHANGES:
      if (set_exchanges (oc))
        return MHD_YES;
      break;
    case ORDER_PHASE_CHECK_CONTRACT:
      check_contract (oc);
      break;
    case ORDER_PHASE_EXECUTE_ORDER:
      execute_order (oc);
      break;
    case ORDER_PHASE_FINISHED_MHD_YES:
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Finished processing order (1)\n");
      return MHD_YES;
    case ORDER_PHASE_FINISHED_MHD_NO:
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Finished processing order (0)\n");
      return MHD_NO;
    }
  }
}


MHD_RESULT
TMH_private_post_orders (
  const struct TMH_RequestHandler *rh,
  struct MHD_Connection *connection,
  struct TMH_HandlerContext *hc)
{
  return TMH_private_post_orders_with_pos_secrets (rh,
                                                   connection,
                                                   hc,
                                                   NULL,
                                                   TALER_MCA_NONE);
}


/* end of taler-merchant-httpd_private-post-orders.c */