summaryrefslogtreecommitdiff
path: root/src/lib/merchant_api_pay.c
blob: 0db4631ecb1ca884b3dd3db91497001b841410ae (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
/*
  This file is part of TALER
  Copyright (C) 2014, 2015, 2016, 2017, 2020 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 lib/merchant_api_pay.c
 * @brief Implementation of the /pay request
 *        of the merchant's HTTP API
 * @author Christian Grothoff
 * @author Marcello Stanisci
 */
#include "platform.h"
#include <curl/curl.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 <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_Pay
{

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

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

  /**
   * Function to call with the result in "abort-refund" @e mode.
   */
  TALER_MERCHANT_PayRefundCallback abort_cb;

  /**
   * Closure for @a abort_cb.
   */
  void *abort_cb_cls;

  /**
   * Operational mode, either "pay" or "abort-refund".
   */
  const char *mode;

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

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

  /**
   * Hash of the contract, only available in "abort-refund" mode.
   */
  struct GNUNET_HashCode h_contract_terms;

};


/**
 * Check that the response for a /pay refund is well-formed,
 * and call the application callback with the result if it is
 * OK. Otherwise returns #GNUNET_SYSERR.
 *
 * @param ph handle to operation that created the reply
 * @param json the reply to parse
 * @return #GNUNET_OK on success
 */
static int
check_abort_refund (struct TALER_MERCHANT_Pay *ph,
                    const json_t *json)
{
  json_t *refunds;
  unsigned int num_refunds;
  struct TALER_MerchantPublicKeyP merchant_pub;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_json ("refund_permissions", &refunds),
    GNUNET_JSON_spec_fixed_auto ("merchant_pub", &merchant_pub),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  num_refunds = json_array_size (refunds);
  {
    struct TALER_MERCHANT_RefundEntry res[GNUNET_NZL (num_refunds)];

    for (unsigned int i = 0; i<num_refunds; i++)
    {
      struct TALER_MerchantSignatureP *sig = &res[i].merchant_sig;
      json_t *refund = json_array_get (refunds, i);
      struct GNUNET_JSON_Specification spec_detail[] = {
        GNUNET_JSON_spec_fixed_auto ("merchant_sig",
                                     sig),
        GNUNET_JSON_spec_fixed_auto ("coin_pub",
                                     &res[i].coin_pub),
        GNUNET_JSON_spec_uint64 ("rtransaction_id",
                                 &res[i].rtransaction_id),
        GNUNET_JSON_spec_end ()
      };
      int found;

      if (GNUNET_OK !=
          GNUNET_JSON_parse (refund,
                             spec_detail,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        GNUNET_JSON_parse_free (spec);
        return GNUNET_SYSERR;
      }

      found = -1;
      for (unsigned int j = 0; j<ph->num_coins; j++)
      {
        if (0 == memcmp (&ph->coins[j].coin_pub,
                         &res[i].coin_pub,
                         sizeof
                         (struct TALER_CoinSpendPublicKeyP)))
        {
          found = j;
          break;
        }
      }
      if (-1 == found)
      {
        GNUNET_break_op (0);
        GNUNET_JSON_parse_free (spec);
        return GNUNET_SYSERR;
      }

      {
        struct TALER_RefundRequestPS rr = {
          .purpose.purpose = htonl (TALER_SIGNATURE_MERCHANT_REFUND),
          .purpose.size = htonl (sizeof (struct TALER_RefundRequestPS)),
          .h_contract_terms = ph->h_contract_terms,
          .coin_pub = res[i].coin_pub,
          .merchant = merchant_pub,
          .rtransaction_id = GNUNET_htonll (res[i].rtransaction_id)
        };

        TALER_amount_hton (&rr.refund_amount,
                           &ph->coins[found].amount_with_fee);
        TALER_amount_hton (&rr.refund_fee,
                           &ph->coins[found].refund_fee);
        if (GNUNET_OK !=
            GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_MERCHANT_REFUND,
                                        &rr.purpose,
                                        &sig->eddsa_sig,
                                        &merchant_pub.eddsa_pub))
        {
          GNUNET_break_op (0);
          GNUNET_JSON_parse_free (spec);
          return GNUNET_SYSERR;
        }
      }
    }
    {
      struct TALER_MERCHANT_HttpResponse hr = {
        .reply = json,
        .http_status = MHD_HTTP_OK
      };

      ph->abort_cb (ph->abort_cb_cls,
                    &hr,
                    &merchant_pub,
                    &ph->h_contract_terms,
                    num_refunds,
                    res);
    }
    ph->abort_cb = NULL;
  }
  GNUNET_JSON_parse_free (spec);
  return GNUNET_OK;
}


/**
 * We got a 403 response back from the exchange (or the merchant).
 * Now we need to check the provided cryptographic proof that the
 * coin was actually already spent!
 *
 * @param pc handle of the original coin we paid with
 * @param json cryptographic proof of coin's transaction
 *        history as was returned by the exchange/merchant
 * @return #GNUNET_OK if proof checks out
 */
static int
check_coin_history (const struct TALER_MERCHANT_PaidCoin *pc,
                    json_t *json)
{
  struct TALER_Amount spent;
  struct TALER_Amount spent_plus_contrib;

  if (GNUNET_OK !=
      TALER_EXCHANGE_verify_coin_history (NULL, /* do not verify fees */
                                          pc->amount_with_fee.currency,
                                          &pc->coin_pub,
                                          json,
                                          &spent))
  {
    /* Exchange's history fails to verify */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_amount_add (&spent_plus_contrib,
                        &spent,
                        &pc->amount_with_fee))
  {
    /* We got an integer overflow? Bad application! */
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (-1 != TALER_amount_cmp (&pc->denom_value,
                              &spent_plus_contrib))
  {
    /* according to our calculations, the transaction should
       have still worked, exchange error! */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Accepting proof of double-spending\n");
  return GNUNET_OK;
}


/**
 * We got a 409 response back from the exchange (or the merchant).
 * Now we need to check the provided cryptographic proof that the
 * coin was actually already spent!
 *
 * @param ph handle of the original pay operation
 * @param json cryptographic proof returned by the
 *        exchange/merchant
 * @return #GNUNET_OK if proof checks out
 */
static int
check_conflict (struct TALER_MERCHANT_Pay *ph,
                const json_t *json)
{
  json_t *history;
  json_t *ereply;
  struct TALER_CoinSpendPublicKeyP coin_pub;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_json ("exchange-reply", &ereply),
    GNUNET_JSON_spec_fixed_auto ("coin_pub", &coin_pub),
    GNUNET_JSON_spec_end ()
  };
  struct GNUNET_JSON_Specification hspec[] = {
    GNUNET_JSON_spec_json ("history", &history),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      GNUNET_JSON_parse (ereply,
                         hspec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    GNUNET_JSON_parse_free (spec);
    return GNUNET_SYSERR;
  }
  GNUNET_JSON_parse_free (spec);

  for (unsigned int i = 0; i<ph->num_coins; i++)
  {
    if (0 == memcmp (&ph->coins[i].coin_pub,
                     &coin_pub,
                     sizeof (struct TALER_CoinSpendPublicKeyP)))
    {
      int ret;

      ret = check_coin_history (&ph->coins[i],
                                history);
      GNUNET_JSON_parse_free (hspec);
      return ret;
    }
  }
  GNUNET_break_op (0); /* complaint is not about any of the coins
                          that we actually paid with... */
  GNUNET_JSON_parse_free (hspec);
  return GNUNET_SYSERR;
}


/**
 * 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 json response body, NULL if not in JSON
 */
static void
handle_pay_finished (void *cls,
                     long response_code,
                     const void *response)
{
  struct TALER_MERCHANT_Pay *ph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_HttpResponse hr = {
    .http_status = (unsigned int) response_code,
    .reply = json
  };

  ph->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "/pay completed with response code %u\n",
              (unsigned int) response_code);
  if (0 == strcasecmp (ph->mode,
                       "pay"))
  {
    switch (response_code)
    {
    case 0:
      hr.ec = TALER_EC_INVALID_RESPONSE;
      break;
    case MHD_HTTP_OK:
      break;
    /* Tolerating Not Acceptable because sometimes
     * - especially in tests - we might want to POST
     * coins one at a time.  */
    case MHD_HTTP_NOT_ACCEPTABLE:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      break;
    case MHD_HTTP_BAD_REQUEST:
      hr.ec = TALER_JSON_get_error_code (json);
      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_FORBIDDEN:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      /* Nothing really to verify, merchant says we tried to abort the payment
       * after it was successful. We should pass the JSON reply to the
       * application */
      break;
    case MHD_HTTP_NOT_FOUND:
      hr.ec = TALER_JSON_get_error_code (json);
      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_PRECONDITION_FAILED:
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &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_REQUEST_TIMEOUT:
      hr.ec = TALER_JSON_get_error_code (json);
      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:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      if (GNUNET_OK != check_conflict (ph,
                                       json))
      {
        GNUNET_break_op (0);
        response_code = 0;
      }
      break;
    case MHD_HTTP_GONE:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      /* 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_FAILED_DEPENDENCY:
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &hr);
      /* Nothing really to verify, the merchant is blaming the exchange.
         We should pass the JSON reply to the application */
      break;
    case MHD_HTTP_INTERNAL_SERVER_ERROR:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      /* Server had an internal issue; we should retry,
         but this API leaves this to the application */
      break;
    case MHD_HTTP_SERVICE_UNAVAILABLE:
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &hr);
      /* Exchange couldn't respond properly; the retry is
         left to the application */
      break;
    default:
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &hr);
      /* unexpected response code */
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Unexpected response code %u/%d\n",
                  (unsigned int) response_code,
                  (int) hr.ec);
      GNUNET_break_op (0);
      break;
    }
    ph->pay_cb (ph->pay_cb_cls,
                &hr);
  }
  else
  {
    GNUNET_assert (0 == strcasecmp (ph->mode,
                                    "abort-refund"));

    switch (response_code)
    {
    case 0:
      hr.ec = TALER_EC_INVALID_RESPONSE;
      break;
    case MHD_HTTP_OK:
      if (GNUNET_OK ==
          check_abort_refund (ph,
                              json))
      {
        TALER_MERCHANT_pay_cancel (ph);
        return;
      }
      hr.http_status = 0;
      hr.ec = TALER_EC_PAY_MERCHANT_INVALID_RESPONSE;
      break;
    case MHD_HTTP_BAD_REQUEST:
      hr.ec = TALER_JSON_get_error_code (json);
      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_CONFLICT:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      break;
    case MHD_HTTP_FORBIDDEN:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      /* Nothing really to verify, merchant says one of
         the signatures is invalid; as we checked them,
         this should never happen, we should pass the JSON
         reply to the application */
      break;
    case MHD_HTTP_NOT_FOUND:
      hr.ec = TALER_JSON_get_error_code (json);
      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_FAILED_DEPENDENCY:
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &hr);
      /* Nothing really to verify, the merchant is blaming the exchange.
         We should pass the JSON reply to the application */
      break;
    case MHD_HTTP_INTERNAL_SERVER_ERROR:
      hr.ec = TALER_JSON_get_error_code (json);
      hr.hint = TALER_JSON_get_error_hint (json);
      /* Server had an internal issue; we should retry,
         but this API leaves this to the application */
      break;
    default:
      /* unexpected response code */
      TALER_MERCHANT_parse_error_details_ (json,
                                           response_code,
                                           &hr);
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Unexpected response code %u/%d\n",
                  (unsigned int) response_code,
                  (int) hr.ec);
      GNUNET_break_op (0);
      break;
    }
    ph->abort_cb (ph->abort_cb_cls,
                  &hr,
                  NULL,
                  NULL,
                  0,
                  NULL);
  }
  TALER_MERCHANT_pay_cancel (ph);
}


/**
 * Issue /pay request. Generic version for the various
 * variants of the API.
 *
 * @param ctx the execution loop context
 * @param merchant_url base URL of the merchant's backend
 * @param merchant_pub public key of the merchant
 * @param num_coins number of coins used to pay
 * @param coins array of coins we use to pay
 * @param mode mode string to use ("pay" or "abort-refund").
 * @param pay_cb the callback to call when a reply for this
 *        request is available
 * @param pay_cb_cls closure for @a pay_cb
 * @param abort_cb callback to call for the abort-refund variant
 * @param abort_cb_cls closure for @a abort_cb
 * @return a handle for this request
 */
static struct TALER_MERCHANT_Pay *
request_pay_generic (
  struct GNUNET_CURL_Context *ctx,
  const char *merchant_url,
  const struct TALER_MerchantPublicKeyP *merchant_pub,
  const char *order_id,
  unsigned int num_coins,
  const struct TALER_MERCHANT_PaidCoin *coins,
  const char *mode,
  TALER_MERCHANT_PayCallback pay_cb,
  void *pay_cb_cls,
  TALER_MERCHANT_PayRefundCallback abort_cb,
  void *abort_cb_cls)
{
  struct TALER_MERCHANT_Pay *ph;
  json_t *pay_obj;
  json_t *j_coins;
  CURL *eh;
  struct TALER_Amount total_fee;
  struct TALER_Amount total_amount;

  if (0 == num_coins)
  {
    GNUNET_break (0);
    return NULL;
  }
  j_coins = json_array ();
  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;

    if (GNUNET_SYSERR ==
        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 ( (GNUNET_OK !=
            TALER_amount_add (&total_fee,
                              &total_fee,
                              &fee)) ||
           (GNUNET_OK !=
            TALER_amount_add (&total_amount,
                              &total_amount,
                              &pc->amount_with_fee)) )
      {
        /* integer overflow */
        GNUNET_break (0);
        json_decref (j_coins);
        return NULL;
      }
    }

    /* create JSON for this coin */
    j_coin = json_pack (
      "{s:o, s:o,"                   /* contribution/coin_pub */
      " s:s, s:o,"          /* exchange_url / denom_pub */
      " s:o, s:o}",          /* ub_sig / coin_sig */
      "contribution",
      TALER_JSON_from_amount (&pc->amount_with_fee),
      "coin_pub",
      GNUNET_JSON_from_data_auto (&pc->coin_pub),
      "exchange_url",
      pc->exchange_url,
      "denom_pub",
      GNUNET_JSON_from_rsa_public_key (pc->denom_pub.rsa_public_key),
      "ub_sig",
      GNUNET_JSON_from_rsa_signature (pc->denom_sig.rsa_signature),
      "coin_sig",
      GNUNET_JSON_from_data_auto (&pc->coin_sig));
    if (0 !=
        json_array_append_new (j_coins,
                               j_coin))
    {
      GNUNET_break (0);
      json_decref (j_coins);
      return NULL;
    }
  }

  pay_obj = json_pack ("{"
                       " s:s," /* mode */
                       " s:o," /* coins */
                       " s:s," /* order_id */
                       " s:o," /* merchant_pub */
                       "}",
                       "mode",
                       mode,
                       "coins",
                       j_coins, /* reference consumed! */
                       "order_id",
                       order_id,
                       "merchant_pub",
                       GNUNET_JSON_from_data_auto (merchant_pub));
  if (NULL == pay_obj)
  {
    GNUNET_break (0);
    return NULL;
  }
  ph = GNUNET_new (struct TALER_MERCHANT_Pay);
  ph->ctx = ctx;
  ph->mode = mode;
  ph->abort_cb = abort_cb;
  ph->abort_cb_cls = abort_cb_cls;
  ph->pay_cb = pay_cb;
  ph->pay_cb_cls = pay_cb_cls;
  ph->url = TALER_url_join (merchant_url, "pay", NULL);
  if (NULL == ph->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not construct request URL.\n");
    json_decref (pay_obj);
    GNUNET_free (ph);
    return NULL;
  }
  ph->num_coins = num_coins;
  ph->coins = GNUNET_new_array (num_coins,
                                struct TALER_MERCHANT_PaidCoin);
  memcpy (ph->coins,
          coins,
          num_coins * sizeof (struct TALER_MERCHANT_PaidCoin));

  eh = curl_easy_init ();
  if (GNUNET_OK != TALER_curl_easy_post (&ph->post_ctx,
                                         eh,
                                         pay_obj))
  {
    GNUNET_break (0);
    json_decref (pay_obj);
    GNUNET_free (ph);
    return NULL;
  }

  json_decref (pay_obj);
  GNUNET_assert (CURLE_OK == curl_easy_setopt (eh,
                                               CURLOPT_URL,
                                               ph->url));
  ph->job = GNUNET_CURL_job_add2 (ctx,
                                  eh,
                                  ph->post_ctx.headers,
                                  &handle_pay_finished,
                                  ph);
  return ph;
}


/**
 * Pay a merchant.  API for wallets that have the coin's private
 * keys.
 * _NOTE_: this function does NOT calculate each coin amount in
 * order to match the contract total price.  This calculation is
 * to be made by the logic using this library.
 *
 * @param ctx the execution loop context
 * @param merchant_url base URL of the merchant's backend
 * @param h_contract_terms hashcode of the proposal being paid
 * @param amount total value of the contract to be paid to the
 *        merchant
 * @param max_fee maximum fee covered by the merchant
 *        (according to the contract)
 * @param merchant_pub the public key of the merchant
 *        (used to identify the merchant for refund requests)
 * @param merchant_sig signature from the merchant over the
 *        original contract
 * @param timestamp timestamp when the contract was finalized,
 *        must match approximately the current time of the merchant
 * @param refund_deadline date until which the merchant can issue
 *        a refund to the customer via the merchant (can be zero
 *        if refunds are not allowed)
 * @param pay_deadline maximum time limit to pay for this contract
 * @param h_wire hash of the merchant’s account details
 * @param order_id order id of the proposal being paid
 * @param num_coins number of coins used to pay
 * @param coins array of coins we use to pay
 * @param pay_cb the callback to call when a reply for this
 *        request is available
 * @param pay_cb_cls closure for @a pay_cb
 * @return a handle for this request
 */
static struct TALER_MERCHANT_Pay *
prepare_pay_generic (struct GNUNET_CURL_Context *ctx,
                     const char *merchant_url,
                     const struct GNUNET_HashCode *h_contract_terms,
                     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_Absolute timestamp,
                     struct GNUNET_TIME_Absolute refund_deadline,
                     struct GNUNET_TIME_Absolute pay_deadline,
                     const struct GNUNET_HashCode *h_wire,
                     const char *order_id,
                     unsigned int num_coins,
                     const struct TALER_MERCHANT_PayCoin *coins,
                     const char *mode,
                     TALER_MERCHANT_PayCallback pay_cb,
                     void *pay_cb_cls,
                     TALER_MERCHANT_PayRefundCallback abort_cb,
                     void *abort_cb_cls)
{
  struct TALER_DepositRequestPS dr;
  struct TALER_MERCHANT_PaidCoin pc[num_coins];

  (void) GNUNET_TIME_round_abs (&timestamp);
  (void) GNUNET_TIME_round_abs (&pay_deadline);
  (void) GNUNET_TIME_round_abs (&refund_deadline);

  if (GNUNET_YES !=
      TALER_amount_cmp_currency (amount,
                                 max_fee))
  {
    GNUNET_break (0);
    return NULL;
  }

  dr.purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_DEPOSIT);
  dr.purpose.size = htonl (sizeof (struct TALER_DepositRequestPS));
  dr.h_contract_terms = *h_contract_terms;
  dr.h_wire = *h_wire;
  dr.timestamp = GNUNET_TIME_absolute_hton (timestamp);
  dr.refund_deadline = GNUNET_TIME_absolute_hton (refund_deadline);
  dr.merchant = *merchant_pub;

  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;

    /* prepare 'dr' for this coin to generate coin signature */
    GNUNET_CRYPTO_eddsa_key_get_public (&coin->coin_priv.eddsa_priv,
                                        &dr.coin_pub.eddsa_pub);
    TALER_amount_hton (&dr.amount_with_fee,
                       &coin->amount_with_fee);
    if (GNUNET_SYSERR ==
        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_amount_hton (&dr.deposit_fee,
                       &fee);
    {
      TALER_LOG_DEBUG ("... amount_with_fee was %s\n",
                       TALER_amount2s (&coin->amount_with_fee));
      TALER_LOG_DEBUG ("... fee was %s\n",
                       TALER_amount2s (&fee));
    }

    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CRYPTO_eddsa_sign (&coin->coin_priv.eddsa_priv,
                                             &dr.purpose,
                                             &p->coin_sig.eddsa_signature));
    p->denom_pub = coin->denom_pub;
    p->denom_sig = coin->denom_sig;
    p->denom_value = coin->denom_value;
    p->coin_pub = dr.coin_pub;
    p->amount_with_fee = coin->amount_with_fee;
    p->amount_without_fee = coin->amount_without_fee;
    p->refund_fee = coin->refund_fee;
    p->exchange_url = coin->exchange_url;
  }
  return request_pay_generic (ctx,
                              merchant_url,
                              merchant_pub,
                              order_id,
                              num_coins,
                              pc,
                              mode,
                              pay_cb,
                              pay_cb_cls,
                              abort_cb,
                              abort_cb_cls);
}


/**
 * Pay a merchant.  API for wallets that have the coin's private keys.
 * _NOTE_: this function does NOT calculate each coin amount in order
 * to match the contract total price.  This calculation is to be made
 * by the logic using this library.
 *
 * @param ctx the execution loop context
 * @param merchant_url base URL of the merchant's backend
 * @param h_contract_terms hashcode of the proposal being paid
 * @param amount total value of the contract to be paid to the merchant
 * @param max_fee maximum fee covered by the merchant (according to the contract)
 * @param merchant_pub the public key of the merchant (used to identify the merchant for refund requests)
 * @param merchant_sig signature from the merchant over the original contract
 * @param timestamp timestamp when the contract was finalized, must match approximately the current time of the merchant
 * @param refund_deadline date until which the merchant can issue a refund to the customer via the merchant (can be zero if refunds are not allowed)
 * @param pay_deadline maximum time limit to pay for this contract
 * @param h_wire hash of the merchant’s account details
 * @param order_id order id of the proposal being paid
 * @param num_coins number of coins used to pay
 * @param coins array of coins we use to pay
 * @param pay_cb the callback to call when a reply for this request is available
 * @param pay_cb_cls closure for @a pay_cb
 * @return a handle for this request
 */
struct TALER_MERCHANT_Pay *
TALER_MERCHANT_pay_wallet (struct GNUNET_CURL_Context *ctx,
                           const char *merchant_url,
                           const struct GNUNET_HashCode *h_contract_terms,
                           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_Absolute timestamp,
                           struct GNUNET_TIME_Absolute refund_deadline,
                           struct GNUNET_TIME_Absolute pay_deadline,
                           const struct GNUNET_HashCode *h_wire,
                           const char *order_id,
                           unsigned int num_coins,
                           const struct TALER_MERCHANT_PayCoin *coins,
                           TALER_MERCHANT_PayCallback pay_cb,
                           void *pay_cb_cls)
{
  return prepare_pay_generic (ctx,
                              merchant_url,
                              h_contract_terms,
                              amount,
                              max_fee,
                              merchant_pub,
                              merchant_sig,
                              timestamp,
                              refund_deadline,
                              pay_deadline,
                              h_wire,
                              order_id,
                              num_coins,
                              coins,
                              "pay",
                              pay_cb,
                              pay_cb_cls,
                              NULL,
                              NULL);
}


/**
 * Run a payment abort operation, asking for refunds for coins
 * that were previously spend on a /pay that failed to go through.
 *
 * @param ctx execution context
 * @param merchant_url base URL of the merchant
 * @param h_wire hash of the merchant’s account details
 * @param h_contract hash of the contact of the merchant with the customer
 * @param transaction_id transaction id for the transaction between merchant and customer
 * @param amount total value of the contract to be paid to the merchant
 * @param max_fee maximum fee covered by the merchant (according to the contract)
 * @param merchant_pub the public key of the merchant (used to identify the merchant for refund requests)
 * @param merchant_sig signature from the merchant over the original contract
 * @param timestamp timestamp when the contract was finalized, must match approximately the current time of the merchant
 * @param refund_deadline date until which the merchant can issue a refund to the customer via the merchant (can be zero if refunds are not allowed)
 * @param pay_deadline maximum time limit to pay for this contract
 * @param num_coins number of coins used to pay
 * @param coins array of coins we use to pay
 * @param coin_sig the signature made with purpose #TALER_SIGNATURE_WALLET_COIN_DEPOSIT made by the customer with the coin’s private key.
 * @param payref_cb the callback to call when a reply for this request is available
 * @param payref_cb_cls closure for @a pay_cb
 * @return a handle for this request
 */
struct TALER_MERCHANT_Pay *
TALER_MERCHANT_pay_abort (struct GNUNET_CURL_Context *ctx,
                          const char *merchant_url,
                          const struct GNUNET_HashCode *h_contract,
                          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_Absolute timestamp,
                          struct GNUNET_TIME_Absolute refund_deadline,
                          struct GNUNET_TIME_Absolute pay_deadline,
                          const struct GNUNET_HashCode *h_wire,
                          const char *order_id,
                          unsigned int num_coins,
                          const struct TALER_MERCHANT_PayCoin *coins,
                          TALER_MERCHANT_PayRefundCallback payref_cb,
                          void *payref_cb_cls)
{
  struct TALER_MERCHANT_Pay *ph;

  ph = prepare_pay_generic (ctx,
                            merchant_url,
                            h_contract,
                            amount,
                            max_fee,
                            merchant_pub,
                            merchant_sig,
                            timestamp,
                            refund_deadline,
                            pay_deadline,
                            h_wire,
                            order_id,
                            num_coins,
                            coins,
                            "abort-refund",
                            NULL,
                            NULL,
                            payref_cb,
                            payref_cb_cls);
  if (NULL == ph)
    return NULL;
  ph->h_contract_terms = *h_contract;
  return ph;
}


/**
 * PAY a merchant.  API for frontends talking to backends. Here,
 * the frontend does not have the coin's private keys, but just
 * the public keys and signatures.  Note the subtle difference
 * in the type of @a coins compared to #TALER_MERCHANT_pay().
 *
 * @param ctx the execution loop context
 * @param merchant_url base URL of the merchant's backend
 * @param merchant_pub public key of the merchant
 * @param num_coins number of coins used to pay
 * @param coins array of coins we use to pay
 * @param pay_cb the callback to call when a reply for this request is available
 * @param pay_cb_cls closure for @a pay_cb
 * @return a handle for this request
 */
struct TALER_MERCHANT_Pay *
TALER_MERCHANT_pay_frontend (
  struct GNUNET_CURL_Context *ctx,
  const char *merchant_url,
  const struct TALER_MerchantPublicKeyP *merchant_pub,
  const char *order_id,
  unsigned int num_coins,
  const struct TALER_MERCHANT_PaidCoin *coins,
  TALER_MERCHANT_PayCallback pay_cb,
  void *pay_cb_cls)
{
  return request_pay_generic (ctx,
                              merchant_url,
                              merchant_pub,
                              order_id,
                              num_coins,
                              coins,
                              "pay",
                              pay_cb,
                              pay_cb_cls,
                              NULL,
                              NULL);
}


/**
 * Cancel a pay permission request.  This function cannot be used
 * on a request handle if a response is already served for it.
 *
 * @param pay the pay permission request handle
 */
void
TALER_MERCHANT_pay_cancel (struct TALER_MERCHANT_Pay *pay)
{
  if (NULL != pay->job)
  {
    GNUNET_CURL_job_cancel (pay->job);
    pay->job = NULL;
  }
  TALER_curl_easy_post_finished (&pay->post_ctx);
  GNUNET_free (pay->coins);
  GNUNET_free (pay->url);
  GNUNET_free (pay);
}


/* end of merchant_api_pay.c */