aboutsummaryrefslogtreecommitdiff
path: root/src/lib/merchant_api_post_order_pay.c
blob: d10fc6d721599f72353ff2baf9cd41692639be9a (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
/*
  This file is part of TALER
  Copyright (C) 2014-2023 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1,
  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 Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with TALER; see the file COPYING.LGPL.
  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file merchant_api_post_order_pay.c
 * @brief Implementation of the POST /order/$ID/pay request
 *        of the merchant's HTTP API
 * @author Christian Grothoff
 * @author Marcello Stanisci
 */
#include "platform.h"
#include <curl/curl.h>
#include <gnunet/gnunet_common.h>
#include <gnunet/gnunet_json_lib.h>
#include <jansson.h>
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include "taler_merchant_service.h"
#include "merchant_api_common.h"
#include "merchant_api_curl_defaults.h"
#include <stdio.h>
#include <taler/taler_json_lib.h>
#include <taler/taler_signatures.h>
#include <taler/taler_exchange_service.h>
#include <taler/taler_curl_lib.h>


/**
 * @brief A Pay Handle
 */
struct TALER_MERCHANT_OrderPayHandle
{

  /**
   * The url for this request.
   */
  char *url;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result in "pay" @e mode.
   */
  TALER_MERCHANT_OrderPayCallback pay_cb;

  /**
   * Closure for @a pay_cb.
   */
  void *pay_cb_cls;

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Minor context that holds body and headers.
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * The coins we are paying with.
   */
  struct TALER_MERCHANT_PaidCoin *coins;

  /**
   * Hash of the contract we are paying, set
   * if @e am_wallet is true.
   */
  struct TALER_PrivateContractHashP h_contract_terms;

  /**
   * Public key of the merchant (instance) being paid, set
   * if @e am_wallet is true.
   */
  struct TALER_MerchantPublicKeyP merchant_pub;

  /**
   * JSON with the full reply, used during async
   * processing.
   */
  json_t *full_reply;

  /**
   * Pointer into @e coins array for the coin that
   * created a conflict (that we are checking).
   */
  const struct TALER_MERCHANT_PaidCoin *error_pc;

  /**
   * Coin history that proves a conflict.
   */
  json_t *error_history;

  /**
   * Number of @e coins we are paying with.
   */
  unsigned int num_coins;

  /**
   * Set to true if this is the wallet API and we have
   * initialized @e h_contract_terms and @e merchant_pub.
   */
  bool am_wallet;

};


/**
 * Parse blindly signed output tokens from response.
 *
 * @param token_sigs the JSON array with the token signatures. Can be NULL.
 * @param tokens where to store the parsed tokens.
 * @param num_tokens where to store the length of the @a tokens array.
 */
static enum GNUNET_GenericReturnValue
parse_tokens (const json_t *token_sigs,
              struct TALER_MERCHANT_OutputToken **tokens,
              unsigned int *num_tokens)
{
  GNUNET_array_grow (*tokens,
                     *num_tokens,
                     json_array_size (token_sigs));

  for (unsigned int i = 0; i<(*num_tokens); i++)
  {
    struct TALER_MERCHANT_OutputToken *token = &(*tokens)[i];
    struct GNUNET_JSON_Specification spec[] = {
      TALER_JSON_spec_blinded_token_issue_sig ("blind_sig",
                                               &token->blinded_sig),
      GNUNET_JSON_spec_end ()
    };
    const json_t *jtoken
      = json_array_get (token_sigs,
                        i);

    if (NULL == jtoken)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
    if (GNUNET_OK !=
        GNUNET_JSON_parse (jtoken,
                           spec,
                           NULL, NULL))
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
  }

  return GNUNET_YES;
}


/**
 * Function called when we're done processing the
 * HTTP /pay request.
 *
 * @param cls the `struct TALER_MERCHANT_Pay`
 * @param response_code HTTP response code, 0 on error
 * @param response response body, NULL if not in JSON
 */
static void
handle_pay_finished (void *cls,
                     long response_code,
                     const void *response)
{
  struct TALER_MERCHANT_OrderPayHandle *oph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_PayResponse pr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received /pay response with status code %u\n",
              (unsigned int) response_code);

  json_dumpf (json,
              stderr,
              JSON_INDENT (2));

  oph->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "/pay completed with response code %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case 0:
    pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (oph->am_wallet)
    {
      const json_t *token_sigs = NULL;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_fixed_auto ("sig",
                                     &pr.details.ok.merchant_sig),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_string ("pos_confirmation",
                                   &pr.details.ok.pos_confirmation),
          NULL),
        GNUNET_JSON_spec_mark_optional (
          GNUNET_JSON_spec_array_const ("token_sigs",
                                        &token_sigs),
          NULL),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        pr.hr.http_status = 0;
        pr.hr.hint = "sig field missing in response";
        break;
      }

      if (GNUNET_OK !=
          parse_tokens (token_sigs,
                        &pr.details.ok.tokens,
                        &pr.details.ok.num_tokens))
      {
        GNUNET_break_op (0);
        pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        pr.hr.http_status = 0;
        pr.hr.hint = "failed to parse token_sigs field in response";
        break;
      }

      if (GNUNET_OK !=
          TALER_merchant_pay_verify (&oph->h_contract_terms,
                                     &oph->merchant_pub,
                                     &pr.details.ok.merchant_sig))
      {
        GNUNET_break_op (0);
        pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        pr.hr.http_status = 0;
        pr.hr.hint = "signature invalid";
      }
    }
    break;
  /* Tolerating Not Acceptable because sometimes
   * - especially in tests - we might want to POST
   * coins one at a time.  */
  case MHD_HTTP_NOT_ACCEPTABLE:
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_BAD_REQUEST:
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    /* This should never happen, either us
     * or the merchant is buggy (or API version conflict);
     * just pass JSON reply to the application */
    break;
  case MHD_HTTP_PAYMENT_REQUIRED:
    /* was originally paid, but then refunded */
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_FORBIDDEN:
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case MHD_HTTP_NOT_FOUND:
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the
       application */
    break;
  case MHD_HTTP_REQUEST_TIMEOUT:
    pr.hr.ec = TALER_JSON_get_error_code (json);
    pr.hr.hint = TALER_JSON_get_error_hint (json);
    /* The merchant couldn't generate a timely response, likely because
       it itself waited too long on the exchange.
       Pass on to application. */
    break;
  case MHD_HTTP_CONFLICT:
    TALER_MERCHANT_parse_error_details_ (json,
                                         MHD_HTTP_CONFLICT,
                                         &pr.hr);
    break;
  case MHD_HTTP_GONE:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* The merchant says we are too late, the offer has expired or some
       denomination key of a coin involved has expired.
       Might be a disagreement in timestamps? Still, pass on to application. */
    break;
  case MHD_HTTP_PRECONDITION_FAILED:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* Nothing really to verify, the merchant is blaming us for failing to
       satisfy some constraint (likely it does not like our exchange because
       of some disagreement on the PKI).  We should pass the JSON reply to the
       application */
    break;
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
    {
      json_t *ebus = json_object_get (json,
                                      "exchange_base_urls");
      if (NULL == ebus)
      {
        GNUNET_break_op (0);
        pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
        pr.hr.http_status = 0;
        pr.hr.hint = "failed to parse exchange_base_urls field in response";
        break;
      }
      {
        size_t alen = json_array_size (ebus);
        const char *ebua[GNUNET_NZL (alen)];
        size_t idx;
        json_t *jebu;
        bool ok = true;

        GNUNET_assert (alen <= UINT_MAX);
        json_array_foreach (ebus, idx, jebu)
        {
          ebua[idx] = json_string_value (jebu);
          if (NULL == ebua[idx])
          {
            GNUNET_break_op (0);
            pr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
            pr.hr.http_status = 0;
            pr.hr.hint = "non-string value in exchange_base_urls in response";
            ok = false;
            break;
          }
        }
        if (! ok)
          break;
        pr.details.unavailable_for_legal_reasons.num_exchanges
          = (unsigned int) alen;
        pr.details.unavailable_for_legal_reasons.exchanges
          = ebua;
        oph->pay_cb (oph->pay_cb_cls,
                     &pr);
        TALER_MERCHANT_order_pay_cancel (oph);
        return;
      }
    }
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* Server had an internal issue; we should retry,
       but this API leaves this to the application */
    break;
  case MHD_HTTP_BAD_GATEWAY:
    /* Nothing really to verify, the merchant is blaming the exchange.
       We should pass the JSON reply to the application */
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    break;
  case MHD_HTTP_SERVICE_UNAVAILABLE:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* Exchange couldn't respond properly; the retry is
       left to the application */
    break;
  case MHD_HTTP_GATEWAY_TIMEOUT:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* Exchange couldn't respond in a timely fashion;
       the retry is left to the application */
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &pr.hr);
    /* unexpected response code */
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d\n",
                (unsigned int) response_code,
                (int) pr.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  oph->pay_cb (oph->pay_cb_cls,
               &pr);
  TALER_MERCHANT_order_pay_cancel (oph);
}


struct TALER_MERCHANT_OrderPayHandle *
TALER_MERCHANT_order_pay_frontend (
  struct GNUNET_CURL_Context *ctx,
  const char *merchant_url,
  const char *order_id,
  const char *session_id,
  const json_t *wallet_data,
  unsigned int num_coins,
  const struct TALER_MERCHANT_PaidCoin coins[static num_coins],
  unsigned int num_tokens,
  const struct TALER_MERCHANT_UsedToken tokens[static num_tokens],
  json_t *j_output_tokens,
  TALER_MERCHANT_OrderPayCallback pay_cb,
  void *pay_cb_cls)
{
  struct TALER_MERCHANT_OrderPayHandle *oph;
  json_t *pay_obj;
  json_t *j_coins;
  json_t *j_tokens = NULL;
  CURL *eh;
  struct TALER_Amount total_fee;
  struct TALER_Amount total_amount;

  j_coins = json_array ();
  GNUNET_assert (NULL != j_coins);
  for (unsigned int i = 0; i<num_coins; i++)
  {
    json_t *j_coin;
    const struct TALER_MERCHANT_PaidCoin *pc = &coins[i];
    struct TALER_Amount fee;
    struct TALER_DenominationHashP denom_hash;

    if (0 >
        TALER_amount_subtract (&fee,
                               &pc->amount_with_fee,
                               &pc->amount_without_fee))
    {
      /* Integer underflow, fee larger than total amount?
         This should not happen (client violated API!) */
      GNUNET_break (0);
      json_decref (j_coins);
      return NULL;
    }
    if (0 == i)
    {
      total_fee = fee;
      total_amount = pc->amount_with_fee;
    }
    else
    {
      if ( (0 >
            TALER_amount_add (&total_fee,
                              &total_fee,
                              &fee)) ||
           (0 >
            TALER_amount_add (&total_amount,
                              &total_amount,
                              &pc->amount_with_fee)) )
      {
        /* integer overflow */
        GNUNET_break (0);
        json_decref (j_coins);
        return NULL;
      }
    }

    TALER_denom_pub_hash (&pc->denom_pub,
                          &denom_hash);
    /* create JSON for this coin */
    j_coin = GNUNET_JSON_PACK (
      TALER_JSON_pack_amount ("contribution",
                              &pc->amount_with_fee),
      GNUNET_JSON_pack_data_auto ("coin_pub",
                                  &pc->coin_pub),
      GNUNET_JSON_pack_string ("exchange_url",
                               pc->exchange_url),
      GNUNET_JSON_pack_data_auto ("h_denom",
                                  &denom_hash),
      TALER_JSON_pack_denom_sig ("ub_sig",
                                 &pc->denom_sig),
      GNUNET_JSON_pack_data_auto ("coin_sig",
                                  &pc->coin_sig));
    if (0 !=
        json_array_append_new (j_coins,
                               j_coin))
    {
      GNUNET_break (0);
      json_decref (j_coins);
      return NULL;
    }
  }

  if (0 < num_tokens)
  {
    j_tokens = json_array ();
    GNUNET_assert (NULL != j_tokens);
    for (unsigned int i = 0; i<num_tokens; i++)
    {
      json_t *j_token;
      const struct TALER_MERCHANT_UsedToken *ut = &tokens[i];

      j_token = GNUNET_JSON_PACK (
        GNUNET_JSON_pack_data_auto ("token_sig",
                                    &ut->token_sig),
        GNUNET_JSON_pack_data_auto ("token_pub",
                                    &ut->token_pub),
        TALER_JSON_pack_token_issue_sig ("ub_sig",
                                         &ut->ub_sig));
      if (0 !=
          json_array_append_new (j_tokens,
                                 j_token))
      {
        GNUNET_break (0);
        json_decref (j_tokens);
        return NULL;
      }
    }
  }

  pay_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_array_steal ("coins",
                                  j_coins),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_array_steal ("tokens",
                                    j_tokens)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("wallet_data",
                                      (json_t *) wallet_data)),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("session_id",
                               session_id)));

  json_dumpf (pay_obj,
              stderr,
              JSON_INDENT (2));

  oph = GNUNET_new (struct TALER_MERCHANT_OrderPayHandle);
  oph->ctx = ctx;
  oph->pay_cb = pay_cb;
  oph->pay_cb_cls = pay_cb_cls;
  {
    char *path;

    GNUNET_asprintf (&path,
                     "orders/%s/pay",
                     order_id);
    oph->url = TALER_url_join (merchant_url,
                               path,
                               NULL);
    GNUNET_free (path);
  }
  if (NULL == oph->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    json_decref (pay_obj);
    GNUNET_free (oph);
    return NULL;
  }
  oph->num_coins = num_coins;
  oph->coins = GNUNET_new_array (num_coins,
                                 struct TALER_MERCHANT_PaidCoin);
  GNUNET_memcpy (oph->coins,
                 coins,
                 num_coins * sizeof (struct TALER_MERCHANT_PaidCoin));

  eh = TALER_MERCHANT_curl_easy_get_ (oph->url);
  if (GNUNET_OK !=
      TALER_curl_easy_post (&oph->post_ctx,
                            eh,
                            pay_obj))
  {
    GNUNET_break (0);
    curl_easy_cleanup (eh);
    json_decref (pay_obj);
    GNUNET_free (oph->url);
    GNUNET_free (oph);
    return NULL;
  }
  json_decref (pay_obj);
  oph->job = GNUNET_CURL_job_add2 (ctx,
                                   eh,
                                   oph->post_ctx.headers,
                                   &handle_pay_finished,
                                   oph);
  return oph;
}


struct TALER_MERCHANT_OrderPayHandle *
TALER_MERCHANT_order_pay (
  struct GNUNET_CURL_Context *ctx,
  const char *merchant_url,
  const char *session_id,
  const struct TALER_PrivateContractHashP *h_contract_terms,
  int choice_index,
  const struct TALER_Amount *amount,
  const struct TALER_Amount *max_fee,
  const struct TALER_MerchantPublicKeyP *merchant_pub,
  const struct TALER_MerchantSignatureP *merchant_sig,
  struct GNUNET_TIME_Timestamp timestamp,
  struct GNUNET_TIME_Timestamp refund_deadline,
  struct GNUNET_TIME_Timestamp pay_deadline,
  const struct TALER_MerchantWireHashP *h_wire,
  const char *order_id,
  unsigned int num_coins,
  const struct TALER_MERCHANT_PayCoin coins[static num_coins],
  unsigned int num_tokens,
  const struct TALER_MERCHANT_UseToken tokens[static num_tokens],
  unsigned int num_output_tokens,
  const struct TALER_MERCHANT_OutputToken output_tokens[static num_output_tokens
  ],
  TALER_MERCHANT_OrderPayCallback pay_cb,
  void *pay_cb_cls)
{
  json_t *j_output_tokens = NULL;
  const json_t *wallet_data = NULL;
  struct GNUNET_HashCode wallet_data_hash;

  if (GNUNET_YES !=
      TALER_amount_cmp_currency (amount,
                                 max_fee))
  {
    GNUNET_break (0);
    return NULL;
  }
  if ((0 < num_tokens || 0 < num_output_tokens) && 0 > choice_index)
  {
    /* Tokens (input or output) require a valid choice_index to be set.
       Only contracts with coices can use or issue tokens. */
    GNUNET_break (0);
    return NULL;
  }
  if (0 < num_output_tokens)
  {
    /* Build token envelopes json array. */
    j_output_tokens = json_array ();
    GNUNET_assert (NULL != j_output_tokens);
    for (unsigned int i = 0; i<num_output_tokens; i++)
    {
      json_t *j_token_ev;
      const struct TALER_MERCHANT_OutputToken *ev = &output_tokens[i];

      j_token_ev = GNUNET_JSON_PACK (
        TALER_JSON_pack_token_envelope ("token_ev",
                                        &ev->envelope));

      if (0 !=
          json_array_append_new (j_output_tokens,
                                 j_token_ev))
      {
        GNUNET_break (0);
        json_decref (j_output_tokens);
        return NULL;
      }
    }
  }
  if (0 <= choice_index)
  {
    wallet_data = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_int64 ("choice_index",
                              choice_index),
      GNUNET_JSON_pack_allow_null (
        GNUNET_JSON_pack_array_incref ("tokens_evs",
                                       j_output_tokens)));
    TALER_json_hash (wallet_data,
                     &wallet_data_hash);
  }
  {
    struct TALER_MERCHANT_PaidCoin pc[num_coins];
    struct TALER_MERCHANT_UsedToken ut[num_tokens];

    for (unsigned int i = 0; i<num_coins; i++)
    {
      const struct TALER_MERCHANT_PayCoin *coin = &coins[i]; // coin priv.
      struct TALER_MERCHANT_PaidCoin *p = &pc[i]; // coin pub.
      struct TALER_Amount fee;
      struct TALER_DenominationHashP h_denom_pub;

      if (0 >
          TALER_amount_subtract (&fee,
                                 &coin->amount_with_fee,
                                 &coin->amount_without_fee))
      {
        /* Integer underflow, fee larger than total amount?
           This should not happen (client violated API!) */
        GNUNET_break (0);
        return NULL;
      }
      TALER_denom_pub_hash (&coin->denom_pub,
                            &h_denom_pub);
      TALER_wallet_deposit_sign (&coin->amount_with_fee,
                                 &fee,
                                 h_wire,
                                 h_contract_terms,
                                 (NULL != wallet_data)
                                 ? &wallet_data_hash
                                 : NULL,
                                 coin->h_age_commitment,
                                 NULL /* h_extensions! */,
                                 &h_denom_pub,
                                 timestamp,
                                 merchant_pub,
                                 refund_deadline,
                                 &coin->coin_priv,
                                 &p->coin_sig);
      p->denom_pub = coin->denom_pub;
      p->denom_sig = coin->denom_sig;
      p->denom_value = coin->denom_value;
      GNUNET_CRYPTO_eddsa_key_get_public (&coin->coin_priv.eddsa_priv,
                                          &p->coin_pub.eddsa_pub);
      p->amount_with_fee = coin->amount_with_fee;
      p->amount_without_fee = coin->amount_without_fee;
      p->exchange_url = coin->exchange_url;
    }
    for (unsigned int i = 0; i<num_tokens; i++)
    {
      const struct TALER_MERCHANT_UseToken *token = &tokens[i];
      struct TALER_MERCHANT_UsedToken *t = &ut[i];

      TALER_wallet_token_use_sign (h_contract_terms,
                                   &wallet_data_hash, // checked for != NULL above
                                   &token->token_priv,
                                   &t->token_sig);
      t->ub_sig = token->ub_sig;
      t->issue_pub = token->issue_pub;
      GNUNET_CRYPTO_eddsa_key_get_public (&token->token_priv.private_key,
                                          &t->token_pub.public_key);
    }
    {
      struct TALER_MERCHANT_OrderPayHandle *oph;

      oph = TALER_MERCHANT_order_pay_frontend (ctx,
                                               merchant_url,
                                               order_id,
                                               session_id,
                                               wallet_data,
                                               num_coins,
                                               pc,
                                               num_tokens,
                                               ut,
                                               j_output_tokens,
                                               pay_cb,
                                               pay_cb_cls);
      if (NULL == oph)
        return NULL;
      oph->h_contract_terms = *h_contract_terms;
      oph->merchant_pub = *merchant_pub;
      oph->am_wallet = true;
      return oph;
    }
  }
}


void
TALER_MERCHANT_order_pay_cancel (struct TALER_MERCHANT_OrderPayHandle *oph)
{
  if (NULL != oph->job)
  {
    GNUNET_CURL_job_cancel (oph->job);
    oph->job = NULL;
  }
  TALER_curl_easy_post_finished (&oph->post_ctx);
  json_decref (oph->error_history);
  json_decref (oph->full_reply);
  GNUNET_free (oph->coins);
  GNUNET_free (oph->url);
  GNUNET_free (oph);
}


/* end of merchant_api_post_order_pay.c */