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

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

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

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see
  <http://www.gnu.org/licenses/>
*/
/**
 * @file lib/exchange_api_age_withdraw.c
 * @brief Implementation of /reserves/$RESERVE_PUB/age-withdraw requests
 * @author Özgür Kesim
 */

#include "platform.h"
#include <gnunet/gnunet_common.h>
#include <jansson.h>
#include <microhttpd.h> /* just for HTTP status codes */
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_json_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include <sys/wait.h>
#include "taler_curl_lib.h"
#include "taler_json_lib.h"
#include "taler_exchange_service.h"
#include "exchange_api_common.h"
#include "exchange_api_handle.h"
#include "taler_signatures.h"
#include "exchange_api_curl_defaults.h"

/**
 * A CoinCandidate is populated from a master secret
 */
struct CoinCandidate
{
  /**
   * Master key material for the coin candidates.
   */
  struct TALER_PlanchetMasterSecretP secret;

  /**
   * Age commitment for the coin candidates, calculated from the @e ps and a
   * given maximum age
   */
  struct TALER_AgeCommitmentProof age_commitment_proof;

  /**
   * Age commitment for the coin.
   */
  struct TALER_AgeCommitmentHash h_age_commitment;

  /**
   *  blinding secret
   */
  union TALER_DenominationBlindingKeyP blinding_key;

  /**
   * Private key of the coin we are withdrawing.
   */
  struct TALER_CoinSpendPrivateKeyP coin_priv;

  /**
   * Values of the @cipher selected
   */
  struct TALER_ExchangeWithdrawValues alg_values;

  /**
   * Hash of the public key of the coin we are signing.
   */
  struct TALER_CoinPubHashP h_coin_pub;


  /**
   * Blinded hash of the coin
   **/
  struct TALER_BlindedCoinHashP blinded_coin_h;

};


/**
 * Closure for a call to /csr-withdraw, contains data that is needed to process
 * the result.
 */
struct CSRClosure
{
  /* Points to the actual candidate in CoinData.coin_candidates, to continue
   * to build its contents based on the results from /csr-withdraw */
  struct CoinCandidate *candidate;

  /* The planchet to finally generate.  Points to the corresponding candidate
   * in CoindData.planchet_details */
  struct TALER_PlanchetDetail *planchet;

  /* Handler to the originating call to /age-withdraw, needed to either
   * cancel the running age-withdraw request (on failure of the current call
   * to /csr-withdraw), or to eventually perform the protocol, once all
   * csr-withdraw requests have successfully finished. */
  struct TALER_EXCHANGE_AgeWithdrawHandle *age_withdraw_handle;

  /* Denomination information, needed for CS coins for the
   * step after /csr-withdraw */
  const struct TALER_EXCHANGE_DenomPublicKey *denom_pub;

  /* Handler for the CS R request */
  struct TALER_EXCHANGE_CsRWithdrawHandle *csr_withdraw_handle;
};

/**
 * Data we keep per coin in the batch.
 */
struct CoinData
{
  /**
   * The denomination of the coin.  Must support age restriction, i.e
   * its .keys.age_mask MUST not be 0
   */
  struct TALER_EXCHANGE_DenomPublicKey denom_pub;

  /**
   * The Candidates for the coin
   */
  struct CoinCandidate coin_candidates[TALER_CNC_KAPPA];

  /**
   * Details of the planchet(s).
   */
  struct TALER_PlanchetDetail planchet_details[TALER_CNC_KAPPA];

  /**
   * Closure for each candidate of type CS for the preflight request to
   * /csr-withdraw
   */
  struct CSRClosure csr_cls[TALER_CNC_KAPPA];
};

/**
 * A /reserves/$RESERVE_PUB/age-withdraw request-handle for calls with
 * pre-blinded planchets.  Returned by TALER_EXCHANGE_age_withdraw_blinded.
 */
struct TALER_EXCHANGE_AgeWithdrawBlindedHandle
{

  /**
   * Reserve private key.
   */
  const struct TALER_ReservePrivateKeyP *reserve_priv;

  /**
   * Reserve public key, calculated
   */
  struct TALER_ReservePublicKeyP reserve_pub;

  /**
   * Signature of the reserve for the request, calculated after all
   * parameters for the coins are collected.
   */
  struct TALER_ReserveSignatureP reserve_sig;

  /*
   * The denomination keys of the exchange
   */
  struct TALER_EXCHANGE_Keys *keys;

  /**
   * The age mask, extacted from the denominations.
   * MUST be the same for all denominations
   *
   */
  struct TALER_AgeMask age_mask;

  /**
   * Maximum age to commit to.
   */
  uint8_t max_age;

  /**
   * The commitment calculated as SHA512 hash over all blinded_coin_h
   */
  struct TALER_AgeWithdrawCommitmentHashP h_commitment;

  /**
   * Total amount requested (value plus withdraw fee).
   */
  struct TALER_Amount amount_with_fee;

  /**
   * Length of the @e blinded_input Array
   */
  size_t num_input;

  /**
   * The blinded planchet input for the call to /age-withdraw via
   * TALER_EXCHANGE_age_withdraw_blinded
   */
  const struct TALER_EXCHANGE_AgeWithdrawBlindedInput *blinded_input;

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

  /**
   * Context for curl.
   */
  struct GNUNET_CURL_Context *curl_ctx;

  /**
   * CURL handle for the request job.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Post Context
   */
  struct TALER_CURL_PostContext post_ctx;

  /**
   * Function to call with age-withdraw response results.
   */
  TALER_EXCHANGE_AgeWithdrawBlindedCallback callback;

  /**
   * Closure for @e blinded_callback
   */
  void *callback_cls;
};

/**
 * A /reserves/$RESERVE_PUB/age-withdraw request-handle for calls from
 * a wallet, i. e. when blinding data is available.
 */
struct TALER_EXCHANGE_AgeWithdrawHandle
{

  /**
   * Length of the @e coin_data Array
   */
  size_t num_coins;

  /**
   * The base-URL of the exchange.
   */
  const char *exchange_url;

  /**
   * Reserve private key.
   */
  const struct TALER_ReservePrivateKeyP *reserve_priv;

  /**
   * Reserve public key, calculated
   */
  struct TALER_ReservePublicKeyP reserve_pub;

  /**
   * Signature of the reserve for the request, calculated after all
   * parameters for the coins are collected.
   */
  struct TALER_ReserveSignatureP reserve_sig;

  /*
   * The denomination keys of the exchange
   */
  struct TALER_EXCHANGE_Keys *keys;

  /**
   * The age mask, extacted from the denominations.
   * MUST be the same for all denominations
   *
   */
  struct TALER_AgeMask age_mask;

  /**
   * Maximum age to commit to.
   */
  uint8_t max_age;

  /**
   * Array of per-coin data
   */
  struct CoinData *coin_data;

  /**
   * Context for curl.
   */
  struct GNUNET_CURL_Context *curl_ctx;

  struct
  {
    /**
     * Number of /csr-withdraw requests still pending.
     */
    unsigned int pending;

    /**
     * CURL handle for the request job.
     */
    struct GNUNET_CURL_Job *job;
  } csr;


  /**
   * Function to call with age-withdraw response results.
   */
  TALER_EXCHANGE_AgeWithdrawCallback callback;

  /**
   * Closure for @e age_withdraw_cb
   */
  void *callback_cls;

  /* The Handler for the actual call to the exchange */
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *protocol_handler;
};

/**
 * We got a 200 OK response for the /reserves/$RESERVE_PUB/age-withdraw operation.
 * Extract the noreveal_index and return it to the caller.
 *
 * @param awh operation handle
 * @param j_response reply from the exchange
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors
 */
static enum GNUNET_GenericReturnValue
reserve_age_withdraw_ok (
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh,
  const json_t *j_response)
{
  struct TALER_EXCHANGE_AgeWithdrawBlindedResponse response = {
    .hr.reply = j_response,
    .hr.http_status = MHD_HTTP_OK,
    .details.ok.h_commitment = awbh->h_commitment
  };
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_uint8 ("noreaveal_index",
                            &response.details.ok.noreveal_index),
    GNUNET_JSON_spec_fixed_auto ("exchange_sig",
                                 &response.details.ok.exchange_sig),
    GNUNET_JSON_spec_fixed_auto ("exchange_pub",
                                 &response.details.ok.exchange_pub)
  };

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

  if (GNUNET_OK !=
      TALER_exchange_online_age_withdraw_confirmation_verify (
        &awbh->h_commitment,
        response.details.ok.noreveal_index,
        &response.details.ok.exchange_pub,
        &response.details.ok.exchange_sig))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;

  }
  awbh->callback (awbh->callback_cls,
                  &response);
  /* make sure the callback isn't called again */
  awbh->callback = NULL;

  return GNUNET_OK;
}


/**
 * FIXME: This function should be common to batch- and age-withdraw
 *
 * We got a 409 CONFLICT response for the /reserves/$RESERVE_PUB/age-withdraw operation.
 * Check the signatures on the batch withdraw transactions in the provided
 * history and that the balances add up.  We don't do anything directly
 * with the information, as the JSON will be returned to the application.
 * However, our job is ensuring that the exchange followed the protocol, and
 * this in particular means checking all of the signatures in the history.
 *
 * @param keys The denomination keys from the exchange
 * @param reserve_pub The reserve's public key
 * @param requested_amount The requested amount
 * @param json reply from the exchange
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors
 */
static enum GNUNET_GenericReturnValue
reserve_age_withdraw_payment_required (
  struct TALER_EXCHANGE_Keys *keys,
  const struct TALER_ReservePublicKeyP *reserve_pub,
  const struct TALER_Amount *requested_amount,
  const json_t *json)
{
  struct TALER_Amount balance;
  struct TALER_Amount total_in_from_history;
  struct TALER_Amount total_out_from_history;
  json_t *history;
  size_t len;
  struct GNUNET_JSON_Specification spec[] = {
    TALER_JSON_spec_amount_any ("balance",
                                &balance),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  history = json_object_get (json,
                             "history");
  if (NULL == history)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  /* go over transaction history and compute
     total incoming and outgoing amounts */
  len = json_array_size (history);
  {
    struct TALER_EXCHANGE_ReserveHistoryEntry *rhistory;

    /* Use heap allocation as "len" may be very big and thus this may
       not fit on the stack. Use "GNUNET_malloc_large" as a malicious
       exchange may theoretically try to crash us by giving a history
       that does not fit into our memory. */
    rhistory = GNUNET_malloc_large (
      sizeof (struct TALER_EXCHANGE_ReserveHistoryEntry)
      * len);
    if (NULL == rhistory)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }

    if (GNUNET_OK !=
        TALER_EXCHANGE_parse_reserve_history (
          keys,
          history,
          reserve_pub,
          balance.currency,
          &total_in_from_history,
          &total_out_from_history,
          len,
          rhistory))
    {
      GNUNET_break_op (0);
      TALER_EXCHANGE_free_reserve_history (len,
                                           rhistory);
      return GNUNET_SYSERR;
    }
    TALER_EXCHANGE_free_reserve_history (len,
                                         rhistory);
  }

  /* Check that funds were really insufficient */
  if (0 >= TALER_amount_cmp (requested_amount,
                             &balance))
  {
    /* Requested amount is smaller or equal to reported balance,
       so this should not have failed. */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP /reserves/$RESERVE_PUB/age-withdraw request.
 *
 * @param cls the `struct TALER_EXCHANGE_AgeWithdrawHandle`
 * @param response_code The HTTP response code
 * @param response response data
 */
static void
handle_reserve_age_withdraw_blinded_finished (
  void *cls,
  long response_code,
  const void *response)
{
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh = cls;
  const json_t *j_response = response;
  struct TALER_EXCHANGE_AgeWithdrawBlindedResponse awbr = {
    .hr.reply = j_response,
    .hr.http_status = (unsigned int) response_code
  };

  awbh->job = NULL;
  switch (response_code)
  {
  case 0:
    awbr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK !=
        reserve_age_withdraw_ok (awbh,
                                 j_response))
    {
      GNUNET_break_op (0);
      awbr.hr.http_status = 0;
      awbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    GNUNET_assert (NULL == awbh->callback);
    TALER_EXCHANGE_age_withdraw_blinded_cancel (awbh);
    return;
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
    /* only validate reply is well-formed */
    {
      uint64_t ptu;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_uint64 ("legitimization_uuid",
                                 &ptu),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j_response,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        awbr.hr.http_status = 0;
        awbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
    }
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_FORBIDDEN:
    GNUNET_break_op (0);
    /* Nothing really to verify, exchange says one of the signatures is
       invalid; as we checked them, this should never happen, we
       should pass the JSON reply to the application */
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_NOT_FOUND:
    /* Nothing really to verify, the exchange basically just says
       that it doesn't know this reserve.  Can happen if we
       query before the wire transfer went through.
       We should simply pass the JSON reply to the application. */
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_CONFLICT:
    /* The exchange says that the reserve has insufficient funds;
       check the signatures in the history... */
    if (GNUNET_OK !=
        reserve_age_withdraw_payment_required (awbh->keys,
                                               &awbh->reserve_pub,
                                               &awbh->amount_with_fee,
                                               j_response))
    {
      GNUNET_break_op (0);
      awbr.hr.http_status = 0;
      awbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    }
    else
    {
      awbr.hr.ec = TALER_JSON_get_error_code (j_response);
      awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    }
    break;
  case MHD_HTTP_GONE:
    /* could happen if denomination was revoked */
    /* Note: one might want to check /keys for revocation
       signature here, alas tricky in case our /keys
       is outdated => left to clients */
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    awbr.hr.ec = TALER_JSON_get_error_code (j_response);
    awbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange age-withdraw\n",
                (unsigned int) response_code,
                (int) awbr.hr.ec);
    break;
  }
  awbh->callback (awbh->callback_cls,
                  &awbr);
  TALER_EXCHANGE_age_withdraw_blinded_cancel (awbh);
}


/**
 * Runs the actual age-withdraw operation with the blinded planchets.
 *
 * @param[in,out] awh age withdraw handler
 */
static void
perform_protocol (
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh)
{
#define FAIL_IF(cond) \
  do { \
    if ((cond)) \
    { \
      GNUNET_break (! (cond)); \
      goto ERROR; \
    } \
  } while(0)

  struct GNUNET_HashContext *coins_hctx;
  json_t *j_denoms = NULL;
  json_t *j_array_candidates = NULL;
  json_t *j_request_body = NULL;
  CURL *curlh = NULL;

  FAIL_IF (GNUNET_OK !=
           TALER_amount_set_zero (awbh->keys->currency,
                                  &awbh->amount_with_fee));
  /* Accumulate total value with fees */
  for (size_t i = 0; i < awbh->num_input; i++)
  {
    struct TALER_Amount coin_total;
    const struct TALER_EXCHANGE_DenomPublicKey *dpub =
      awbh->blinded_input[i].denom_pub;

    FAIL_IF (0 >
             TALER_amount_add (&coin_total,
                               &dpub->fees.withdraw,
                               &dpub->value));
    FAIL_IF (0 >
             TALER_amount_add (&awbh->amount_with_fee,
                               &awbh->amount_with_fee,
                               &coin_total));
  }

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Attempting to age-withdraw from reserve %s with maximum age %d\n",
              TALER_B2S (&awbh->reserve_pub),
              awbh->max_age);

  coins_hctx = GNUNET_CRYPTO_hash_context_start ();
  FAIL_IF (NULL == coins_hctx);


  j_denoms = json_array ();
  j_array_candidates = json_array ();
  FAIL_IF ((NULL == j_denoms) ||
           (NULL == j_array_candidates));

  for (size_t i  = 0; i< awbh->num_input; i++)
  {
    /* Build the denomination array */
    {
      const struct TALER_EXCHANGE_DenomPublicKey *denom =
        awbh->blinded_input[i].denom_pub;
      json_t *jdenom = GNUNET_JSON_PACK (
        TALER_JSON_pack_denom_pub (NULL,
                                   &denom->key));

      FAIL_IF (NULL == jdenom);
      FAIL_IF (0 < json_array_append_new (j_denoms,
                                          jdenom));

      /* Build the candidate array */
      {
        json_t *j_can = json_array ();
        FAIL_IF (NULL == j_can);

        for (size_t k = 0; k < TALER_CNC_KAPPA; k++)
        {
          struct TALER_BlindedCoinHashP bch;
          const struct TALER_PlanchetDetail *planchet =
            &awbh->blinded_input[i].planchet_details[k];
          json_t *jc = GNUNET_JSON_PACK (
            TALER_JSON_pack_blinded_planchet (
              NULL,
              &planchet->blinded_planchet));

          FAIL_IF (NULL == jc);
          FAIL_IF (0 < json_array_append_new (j_can,
                                              jc));

          TALER_coin_ev_hash (&planchet->blinded_planchet,
                              &planchet->denom_pub_hash,
                              &bch);

          GNUNET_CRYPTO_hash_context_read (coins_hctx,
                                           &bch,
                                           sizeof(bch));
        }
      }
    }
  }

  /* Build the hash of the commitment */
  GNUNET_CRYPTO_hash_context_finish (coins_hctx,
                                     &awbh->h_commitment.hash);

  /* Sign the request */
  TALER_wallet_age_withdraw_sign (&awbh->h_commitment,
                                  &awbh->amount_with_fee,
                                  &awbh->age_mask,
                                  awbh->max_age,
                                  awbh->reserve_priv,
                                  &awbh->reserve_sig);

  /* Initiate the POST-request */
  j_request_body = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_array_steal ("denoms_h", j_denoms),
    GNUNET_JSON_pack_array_steal ("blinded_coin_evs", j_array_candidates),
    GNUNET_JSON_pack_uint64 ("max_age", awbh->max_age),
    GNUNET_JSON_pack_data_auto ("reserve_sig", &awbh->reserve_sig));
  FAIL_IF (NULL == j_request_body);

  curlh = TALER_EXCHANGE_curl_easy_get_ (awbh->request_url);
  FAIL_IF (NULL == curlh);
  FAIL_IF (GNUNET_OK !=
           TALER_curl_easy_post (&awbh->post_ctx,
                                 curlh,
                                 j_request_body));
  json_decref (j_request_body);
  j_request_body = NULL;

  awbh->job = GNUNET_CURL_job_add2 (
    awbh->curl_ctx,
    curlh,
    awbh->post_ctx.headers,
    &handle_reserve_age_withdraw_blinded_finished,
    awbh);
  FAIL_IF (NULL == awbh->job);

  /* No errors, return */
  return;

ERROR:
  if (NULL != j_denoms)
    json_decref (j_denoms);
  if (NULL != j_array_candidates)
    json_decref (j_array_candidates);
  if (NULL != j_request_body)
    json_decref (j_request_body);
  if (NULL != curlh)
    curl_easy_cleanup (curlh);
  TALER_EXCHANGE_age_withdraw_blinded_cancel (awbh);
  return;
#undef FAIL_IF
}


/**
 * @brief Callback to copy the results from the call to TALER_age_withdraw_blinded
 * to the result for the originating call from TALER_age_withdraw.
 *
 * @param cls struct TALER_AgeWithdrawHandle
 * @param awbr The response
 */
static void
copy_results (
  void *cls,
  const struct TALER_EXCHANGE_AgeWithdrawBlindedResponse *awbr)
{
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh = cls;
  uint8_t idx =  awbr->details.ok.noreveal_index;
  struct TALER_ExchangeWithdrawValues alg_values[awh->num_coins];
  struct TALER_EXCHANGE_AgeWithdrawResponse resp = {
    .hr = awbr->hr,
    .details = {
      .ok = { .noreveal_index = awbr->details.ok.noreveal_index,
              .h_commitment = awbr->details.ok.h_commitment,
              .exchange_pub = awbr->details.ok.exchange_pub,
              .exchange_sig = awbr->details.ok.exchange_sig,
              .num_alg_values = awh->num_coins,
              .alg_values = alg_values},
    },
  };

  for (size_t n = 0; n< awh->num_coins; n++)
    alg_values[n] = awh->coin_data[n].coin_candidates[idx].alg_values;

  awh->callback (awh->callback_cls,
                 &resp);

  awh->callback = NULL;
}


/**
 * @brief Prepares and executes TALER_EXCHANGE_age_withdraw_blinded.
 * If there were CS-denominations involved, started once the all calls
 * to /csr-withdraw are done.
 */
static void
call_age_withdraw_blinded (
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh)
{
  struct TALER_EXCHANGE_AgeWithdrawBlindedInput blinded_input[awh->num_coins];

  /* Prepare the blinded planchets as input */
  for (size_t n = 0; n < awh->num_coins; n++)
  {
    blinded_input[n].denom_pub = &awh->coin_data[n].denom_pub;
    for (uint8_t i = 0; i < TALER_CNC_KAPPA; i++)
      blinded_input[n].planchet_details[i] =
        awh->coin_data[n].planchet_details[i];
  }

  awh->protocol_handler =
    TALER_EXCHANGE_age_withdraw_blinded (
      awh->curl_ctx,
      awh->keys,
      awh->exchange_url,
      awh->reserve_priv,
      awh->num_coins,
      blinded_input,
      copy_results,
      awh);
}


/**
 * Prepares the request URL for the age-withdraw request
 *
 * @param awh The handler
 * @param exchange_url The base-URL to the exchange
 */
static
enum GNUNET_GenericReturnValue
prepare_url (
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh,
  const char *exchange_url)
{
  char arg_str[sizeof (struct TALER_ReservePublicKeyP) * 2 + 32];
  char pub_str[sizeof (struct TALER_ReservePublicKeyP) * 2];
  char *end;

  end = GNUNET_STRINGS_data_to_string (
    &awbh->reserve_pub,
    sizeof (awbh->reserve_pub),
    pub_str,
    sizeof (pub_str));
  *end = '\0';
  GNUNET_snprintf (arg_str,
                   sizeof (arg_str),
                   "reserves/%s/age-withdraw",
                   pub_str);

  awbh->request_url = TALER_url_join (exchange_url,
                                      arg_str,
                                      NULL);
  if (NULL == awbh->request_url)
  {
    GNUNET_break (0);
    TALER_EXCHANGE_age_withdraw_blinded_cancel (awbh);
    return GNUNET_SYSERR;
  }

  return GNUNET_OK;
}


/**
 * @brief Function called when CSR withdraw retrieval is finished
 *
 * @param cls the `struct CSRClosure *`
 * @param csrr replies from the /csr-withdraw request
 */
static void
csr_withdraw_done (
  void *cls,
  const struct TALER_EXCHANGE_CsRWithdrawResponse *csrr)
{
  struct CSRClosure *csr = cls;
  struct CoinCandidate *can;
  struct TALER_PlanchetDetail *planchet;
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh;

  GNUNET_assert (NULL != csr);
  awh = csr->age_withdraw_handle;
  planchet = csr->planchet;
  can = csr->candidate;

  GNUNET_assert (NULL != can);
  GNUNET_assert (NULL != planchet);
  GNUNET_assert (NULL != awh);

  csr->csr_withdraw_handle = NULL;

  switch (csrr->hr.http_status)
  {
  case MHD_HTTP_OK:
    {
      bool success = false;
      /* Complete the initialization of the coin with CS denomination */
      can->alg_values = csrr->details.ok.alg_values;
      TALER_planchet_setup_coin_priv (&can->secret,
                                      &can->alg_values,
                                      &can->coin_priv);
      TALER_planchet_blinding_secret_create (&can->secret,
                                             &can->alg_values,
                                             &can->blinding_key);
      /* This initializes the 2nd half of the
         can->planchet_detail.blinded_planchet! */
      do {
        if (GNUNET_OK !=
            TALER_planchet_prepare (&csr->denom_pub->key,
                                    &can->alg_values,
                                    &can->blinding_key,
                                    &can->coin_priv,
                                    &can->h_age_commitment,
                                    &can->h_coin_pub,
                                    planchet))
        {
          GNUNET_break (0);
          TALER_EXCHANGE_age_withdraw_cancel (awh);
          break;
        }

        if (GNUNET_OK !=
            TALER_coin_ev_hash (&planchet->blinded_planchet,
                                &planchet->denom_pub_hash,
                                &can->blinded_coin_h))
        {
          GNUNET_break (0);
          TALER_EXCHANGE_age_withdraw_cancel (awh);
          break;
        }

        success = true;
      } while(0);

      awh->csr.pending--;

      /* No more pending requests to /csr-withdraw, we can now perform the
       * actual age-withdraw operation */
      if (0 == awh->csr.pending && success)
        call_age_withdraw_blinded (awh);
      return;
    }
  default:
    break;
  }

  TALER_EXCHANGE_age_withdraw_cancel (awh);
}


/**
 * @brief Prepare the coins for the call to age-withdraw and calculates
 * the total amount with fees.
 *
 * For denomination with CS as cipher, initiates the preflight to retrieve the
 * csr-parameter via /csr-withdraw.
 *
 * @param awh The handler to the age-withdraw
 * @param num_coins The number of coins in @e coin_inputs
 * @param coin_inputs The input for the individual coin(-candidates)
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
static
enum GNUNET_GenericReturnValue
prepare_coins (
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh,
  size_t num_coins,
  const struct TALER_EXCHANGE_AgeWithdrawCoinInput coin_inputs[
    static num_coins])
{
#define FAIL_IF(cond) \
  do { \
    if ((cond)) \
    { \
      GNUNET_break (! (cond)); \
      goto ERROR; \
    } \
  } while(0)

  GNUNET_assert (0 < num_coins);
  awh->age_mask = coin_inputs[0].denom_pub->key.age_mask;

  awh->coin_data = GNUNET_new_array (awh->num_coins,
                                     struct CoinData);

  for (size_t i = 0; i < num_coins; i++)
  {
    struct CoinData *cd = &awh->coin_data[i];
    const struct TALER_EXCHANGE_AgeWithdrawCoinInput *input = &coin_inputs[i];
    cd->denom_pub = *input->denom_pub;

    /* The mask must be the same for all coins */
    FAIL_IF (awh->age_mask.bits != input->denom_pub->key.age_mask.bits);

    TALER_denom_pub_deep_copy (&cd->denom_pub.key,
                               &input->denom_pub->key);

    for (uint8_t k = 0; k < TALER_CNC_KAPPA; k++)
    {
      struct CoinCandidate *can = &cd->coin_candidates[k];
      struct TALER_PlanchetDetail *planchet = &cd->planchet_details[k];

      can->secret = input->secrets[k];

      /* Derive the age restriction from the given secret and
       * the maximum age */
      FAIL_IF (GNUNET_OK !=
               TALER_age_restriction_from_secret (
                 &can->secret,
                 &input->denom_pub->key.age_mask,
                 awh->max_age,
                 &can->age_commitment_proof));

      TALER_age_commitment_hash (&can->age_commitment_proof.commitment,
                                 &can->h_age_commitment);

      switch (input->denom_pub->key.cipher)
      {
      case TALER_DENOMINATION_RSA:
        {
          can->alg_values.cipher = TALER_DENOMINATION_RSA;
          TALER_planchet_setup_coin_priv (&can->secret,
                                          &can->alg_values,
                                          &can->coin_priv);
          TALER_planchet_blinding_secret_create (&can->secret,
                                                 &can->alg_values,
                                                 &can->blinding_key);
          FAIL_IF (GNUNET_OK !=
                   TALER_planchet_prepare (&cd->denom_pub.key,
                                           &can->alg_values,
                                           &can->blinding_key,
                                           &can->coin_priv,
                                           &can->h_age_commitment,
                                           &can->h_coin_pub,
                                           planchet));
          FAIL_IF (GNUNET_OK !=
                   TALER_coin_ev_hash (&planchet->blinded_planchet,
                                       &planchet->denom_pub_hash,
                                       &can->blinded_coin_h));
          break;
        }
      case TALER_DENOMINATION_CS:
        {
          struct CSRClosure *cls = &cd->csr_cls[k];
          /**
           * Save the handler and the denomination for the callback
           * after the call to csr-withdraw */
          cls->age_withdraw_handle = awh;
          cls->candidate = can;
          cls->planchet = planchet;
          cls->denom_pub = &cd->denom_pub;

          TALER_cs_withdraw_nonce_derive (
            &can->secret,
            &planchet->blinded_planchet.details.cs_blinded_planchet.nonce);

          /* Note that we only initialize the first half
             of the blinded_planchet here; the other part
             will be done after the /csr-withdraw request! */
          planchet->blinded_planchet.cipher = TALER_DENOMINATION_CS;
          cls->csr_withdraw_handle =
            TALER_EXCHANGE_csr_withdraw (
              awh->curl_ctx,
              awh->exchange_url,
              &cd->denom_pub,
              &planchet->blinded_planchet.details.cs_blinded_planchet.nonce,
              &csr_withdraw_done,
              &cls);
          FAIL_IF (NULL == cls->csr_withdraw_handle);

          awh->csr.pending++;
          break;
        }
      default:
        FAIL_IF (1);
      }
    }
  }
  return GNUNET_OK;

ERROR:
  TALER_EXCHANGE_age_withdraw_cancel (awh);
  return GNUNET_SYSERR;
#undef FAIL_IF
};

struct TALER_EXCHANGE_AgeWithdrawHandle *
TALER_EXCHANGE_age_withdraw (
  struct GNUNET_CURL_Context *curl_ctx,
  struct TALER_EXCHANGE_Keys *keys,
  const char *exchange_url,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  size_t num_coins,
  const struct TALER_EXCHANGE_AgeWithdrawCoinInput coin_inputs[const static
                                                               num_coins],
  uint8_t max_age,
  TALER_EXCHANGE_AgeWithdrawCallback res_cb,
  void *res_cb_cls)
{
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh;

  awh = GNUNET_new (struct TALER_EXCHANGE_AgeWithdrawHandle);
  awh->exchange_url = exchange_url;
  awh->keys = keys;
  awh->curl_ctx = curl_ctx;
  awh->reserve_priv = reserve_priv;
  awh->callback = res_cb;
  awh->callback_cls = res_cb_cls;
  awh->num_coins = num_coins;
  awh->max_age = max_age;


  if (GNUNET_OK != prepare_coins (awh,
                                  num_coins,
                                  coin_inputs))
    return NULL;

  /* If there were no CS denominations, we can now perform the actual
   * age-withdraw protocol.  Otherwise, there are calls to /csr-withdraw
   * in flight and once they finish, the age-withdraw-protocol will be
   * called from within the csr_withdraw_done-function.
   */
  if (0 == awh->csr.pending)
    call_age_withdraw_blinded (awh);

  return awh;
}


void
TALER_EXCHANGE_age_withdraw_cancel (
  struct TALER_EXCHANGE_AgeWithdrawHandle *awh)
{
  /* Cleanup coin data */
  for (unsigned int i = 0; i<awh->num_coins; i++)
  {
    struct CoinData *cd = &awh->coin_data[i];

    for (uint8_t k = 0; k < TALER_CNC_KAPPA; k++)
    {
      struct TALER_PlanchetDetail *planchet = &cd->planchet_details[k];
      struct CSRClosure *cls = &cd->csr_cls[k];

      if (NULL != cls->csr_withdraw_handle)
      {
        TALER_EXCHANGE_csr_withdraw_cancel (cls->csr_withdraw_handle);
        cls->csr_withdraw_handle = NULL;
      }
      TALER_blinded_planchet_free (&planchet->blinded_planchet);
    }
    TALER_denom_pub_free (&cd->denom_pub.key);
  }
  GNUNET_free (awh->coin_data);

  TALER_EXCHANGE_age_withdraw_blinded_cancel (awh->protocol_handler);
  awh->protocol_handler = NULL;
  GNUNET_free (awh);
}


struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *
TALER_EXCHANGE_age_withdraw_blinded (
  struct GNUNET_CURL_Context *curl_ctx,
  struct TALER_EXCHANGE_Keys *keys,
  const char *exchange_url,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  unsigned int num_input,
  const struct TALER_EXCHANGE_AgeWithdrawBlindedInput blinded_input[static
                                                                    num_input],
  TALER_EXCHANGE_AgeWithdrawBlindedCallback res_cb,
  void *res_cb_cls)
{
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh =
    GNUNET_new (struct TALER_EXCHANGE_AgeWithdrawBlindedHandle);

  awbh->num_input = num_input;
  awbh->blinded_input = blinded_input;
  awbh->keys = TALER_EXCHANGE_keys_incref (keys);
  awbh->curl_ctx = curl_ctx;
  awbh->reserve_priv = reserve_priv;
  awbh->callback = res_cb;
  awbh->callback_cls = res_cb_cls;

  GNUNET_CRYPTO_eddsa_key_get_public (&awbh->reserve_priv->eddsa_priv,
                                      &awbh->reserve_pub.eddsa_pub);

  if (GNUNET_OK != prepare_url (awbh,
                                exchange_url))
    return NULL;

  perform_protocol (awbh);
  return awbh;
}


void
TALER_EXCHANGE_age_withdraw_blinded_cancel (
  struct TALER_EXCHANGE_AgeWithdrawBlindedHandle *awbh)
{
  if (NULL == awbh)
    return;

  // TODO[oec]: curl stuff Cleanup

  TALER_EXCHANGE_keys_decref (awbh->keys);
}


/* exchange_api_age_withdraw.c */