exchange

Base system with REST service to issue digital coins, run by the payment service provider
Log | Files | Refs | Submodules | README | LICENSE

taler-exchange-httpd_post-withdraw.c (58871B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2025 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify
      6   it under the terms of the GNU Affero General Public License as
      7   published by the Free Software Foundation; either version 3,
      8   or (at your option) any later version.
      9 
     10   TALER is distributed in the hope that it will be useful,
     11   but WITHOUT ANY WARRANTY; without even the implied warranty
     12   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     13   See the GNU Affero General Public License for more details.
     14 
     15   You should have received a copy of the GNU Affero General
     16   Public License along with TALER; see the file COPYING.  If not,
     17   see <http://www.gnu.org/licenses/>
     18 */
     19 /**
     20  * @file taler-exchange-httpd_post-withdraw.c
     21  * @brief Code to handle /withdraw requests
     22  * @note This endpoint is active since v26 of the protocol API
     23  * @author Özgür Kesim
     24  */
     25 
     26 #include <gnunet/gnunet_util_lib.h>
     27 #include <jansson.h>
     28 #include "taler-exchange-httpd.h"
     29 #include "exchange-database/iterate_withdraw_amounts_for_kyc_check.h"
     30 #include "taler/taler_json_lib.h"
     31 #include "taler/taler_kyclogic_lib.h"
     32 #include "taler/taler_mhd_lib.h"
     33 #include "taler-exchange-httpd_post-withdraw.h"
     34 #include "taler-exchange-httpd_common_kyc.h"
     35 #include "taler-exchange-httpd_responses.h"
     36 #include "taler-exchange-httpd_get-keys.h"
     37 #include "taler-exchange-httpd_secmod-helpers.h"
     38 #include "taler/taler_util.h"
     39 #include "exchange-database/do_withdraw.h"
     40 #include "exchange-database/get_withdraw.h"
     41 #include "exchange-database/get_reserve_origin.h"
     42 #include "exchange-database/rollback.h"
     43 
     44 /**
     45  * The different type of errors that might occur, sorted by name.
     46  * Some of them require idempotency checks, which are marked
     47  * in @e idempotency_check_required below.
     48  */
     49 enum WithdrawError
     50 {
     51   WITHDRAW_ERROR_NONE,
     52   WITHDRAW_ERROR_AGE_MASK_MISMATCH,
     53   WITHDRAW_ERROR_AGE_RESTRICTION_NOT_SUPPORTED_BY_DENOMINATION,
     54   WITHDRAW_ERROR_AGE_RESTRICTION_REQUIRED,
     55   WITHDRAW_ERROR_AMOUNT_OVERFLOW,
     56   WITHDRAW_ERROR_AMOUNT_PLUS_FEE_OVERFLOW,
     57   WITHDRAW_ERROR_BLINDING_SEED_REQUIRED,
     58   WITHDRAW_ERROR_CIPHER_MISMATCH,
     59   WITHDRAW_ERROR_CS_NONCE_MISMATCH,
     60   WITHDRAW_ERROR_CONFIRMATION_SIGN,
     61   WITHDRAW_ERROR_DB_FETCH_FAILED,
     62   WITHDRAW_ERROR_DB_INVARIANT_FAILURE,
     63   WITHDRAW_ERROR_DENOMINATION_EXPIRED,
     64   WITHDRAW_ERROR_DENOMINATION_KEY_UNKNOWN,
     65   WITHDRAW_ERROR_DENOMINATION_REVOKED,
     66   WITHDRAW_ERROR_DENOMINATION_SIGN,
     67   WITHDRAW_ERROR_DENOMINATION_VALIDITY_IN_FUTURE,
     68   WITHDRAW_ERROR_FEE_OVERFLOW,
     69   WITHDRAW_ERROR_IDEMPOTENT_PLANCHET,
     70   WITHDRAW_ERROR_INSUFFICIENT_FUNDS,
     71   WITHDRAW_ERROR_CRYPTO_HELPER,
     72   WITHDRAW_ERROR_KEYS_MISSING,
     73   WITHDRAW_ERROR_KYC_REQUIRED,
     74   WITHDRAW_ERROR_LEGITIMIZATION_RESULT,
     75   WITHDRAW_ERROR_MAXIMUM_AGE_TOO_LARGE,
     76   WITHDRAW_ERROR_NONCE_REUSE,
     77   WITHDRAW_ERROR_REQUEST_PARAMETER_MALFORMED,
     78   WITHDRAW_ERROR_RESERVE_CIPHER_UNKNOWN,
     79   WITHDRAW_ERROR_RESERVE_SIGNATURE_INVALID,
     80   WITHDRAW_ERROR_RESERVE_UNKNOWN,
     81 };
     82 
     83 /**
     84  * With the bits set in this value will be mark the errors
     85  * that require a check for idempotency before actually
     86  * returning an error.
     87  */
     88 static const uint64_t idempotency_check_required =
     89   0
     90   | (1LLU << WITHDRAW_ERROR_DENOMINATION_EXPIRED)
     91   | (1LLU << WITHDRAW_ERROR_DENOMINATION_KEY_UNKNOWN)
     92   | (1LLU << WITHDRAW_ERROR_DENOMINATION_REVOKED)
     93   | (1LLU << WITHDRAW_ERROR_INSUFFICIENT_FUNDS)
     94   | (1LLU << WITHDRAW_ERROR_KEYS_MISSING)
     95   | (1LLU << WITHDRAW_ERROR_KYC_REQUIRED);
     96 
     97 #define IDEMPOTENCY_CHECK_REQUIRED(ec) \
     98         (0LLU != (idempotency_check_required & (1LLU << (ec))))
     99 
    100 
    101 /**
    102  * Context for a /withdraw requests
    103  */
    104 struct WithdrawContext
    105 {
    106 
    107   /**
    108    * This struct is kept in a DLL.
    109    */
    110   struct WithdrawContext *prev;
    111   struct WithdrawContext *next;
    112 
    113   /**
    114      * Processing phase we are in.
    115      * The ordering here partially matters, as we progress through
    116      * them by incrementing the phase in the happy path.
    117      */
    118   enum
    119   {
    120     WITHDRAW_PHASE_PARSE = 0,
    121     WITHDRAW_PHASE_CHECK_KEYS,
    122     WITHDRAW_PHASE_CHECK_RESERVE_SIGNATURE,
    123     WITHDRAW_PHASE_RUN_LEGI_CHECK,
    124     WITHDRAW_PHASE_SUSPENDED,
    125     WITHDRAW_PHASE_CHECK_KYC_RESULT,
    126     WITHDRAW_PHASE_PREPARE_TRANSACTION,
    127     WITHDRAW_PHASE_RUN_TRANSACTION,
    128     WITHDRAW_PHASE_GENERATE_REPLY_SUCCESS,
    129     WITHDRAW_PHASE_GENERATE_REPLY_ERROR,
    130     WITHDRAW_PHASE_RETURN_NO,
    131     WITHDRAW_PHASE_RETURN_YES,
    132   } phase;
    133 
    134 
    135   /**
    136    * Handle for the legitimization check.
    137    */
    138   struct TEH_LegitimizationCheckHandle *lch;
    139 
    140   /**
    141    * Request context
    142    */
    143   const struct TEH_RequestContext *rc;
    144 
    145   /**
    146    * KYC status for the operation.
    147    */
    148   struct TALER_EXCHANGEDB_KycStatus kyc;
    149 
    150   /**
    151    * Current time for the DB transaction.
    152    */
    153   struct GNUNET_TIME_Timestamp now;
    154 
    155   /**
    156    * Set to the hash of the normalized payto URI that established
    157    * the reserve.
    158    */
    159   struct TALER_NormalizedPaytoHashP h_normalized_payto;
    160 
    161   /**
    162    * Captures all parameters provided in the JSON request
    163    */
    164   struct
    165   {
    166     /**
    167      * All fields (from the request or computed)
    168      * that we persist in the database.
    169      */
    170     struct TALER_EXCHANGEDB_Withdraw withdraw;
    171 
    172     /**
    173      * In some error cases we check for idempotency.
    174      * If we find an entry in the database, we mark this here.
    175      */
    176     bool is_idempotent;
    177 
    178     /**
    179      * In some error conditions the request is checked
    180      * for idempotency and the result from the database
    181      * is stored here.
    182      */
    183     struct TALER_EXCHANGEDB_Withdraw withdraw_idem;
    184 
    185     /**
    186      * Array of ``withdraw.num_coins`` hashes of the public keys
    187      * of the denominations to withdraw.
    188      */
    189     struct TALER_DenominationHashP *denoms_h;
    190 
    191     /**
    192      * Number of planchets.  If ``withdraw.max_age`` was _not_ set, this is equal to ``num_coins``.
    193      * Otherwise (``withdraw.max_age`` was set) it is ``withdraw.num_coins * kappa``.
    194      */
    195     size_t num_planchets;
    196 
    197     /**
    198      * Array of ``withdraw.num_planchets`` coin planchets.
    199      * Note that the size depends on the age restriction:
    200      * If ``withdraw.age_proof_required`` is false,
    201      * this is an array of length ``withdraw.num_coins``.
    202      * Otherwise it is an array of length ``kappa*withdraw.num_coins``,
    203      * arranged in runs of ``num_coins`` coins,
    204      * [0..num_coins)..[0..num_coins),
    205      * one for each #TALER_CNC_KAPPA value.
    206      */
    207     struct TALER_BlindedPlanchet *planchets;
    208 
    209     /**
    210      * If proof of age-restriction is required, the #TALER_CNC_KAPPA hashes
    211      * of the batches of ``withdraw.num_coins`` coins.
    212      */
    213     struct TALER_HashBlindedPlanchetsP kappa_planchets_h[TALER_CNC_KAPPA];
    214 
    215     /**
    216      * Total (over all coins) amount (excluding fee) committed to withdraw
    217      */
    218     struct TALER_Amount amount;
    219 
    220     /**
    221      * Total fees for the withdraw
    222      */
    223     struct TALER_Amount fee;
    224 
    225     /**
    226      * Array of length ``withdraw.num_cs_r_values`` of indices into
    227      * @e denoms_h of CS denominations.
    228      */
    229     uint32_t *cs_indices;
    230 
    231   } request;
    232 
    233 
    234   /**
    235    * Errors occurring during evaluation of the request are captured in this
    236    * struct.  In phase WITHDRAW_PHASE_GENERATE_REPLY_ERROR an appropriate error
    237    * message is prepared and sent to the client.
    238    */
    239   struct
    240   {
    241     /* The (internal) error code */
    242     enum WithdrawError code;
    243 
    244     /**
    245      * Some errors require details to be sent to the client.
    246      * These are captured in this union.
    247      * Each field is named according to the error that is using it, except
    248      * commented otherwise.
    249      */
    250     union
    251     {
    252       const char *request_parameter_malformed;
    253 
    254       const char *reserve_cipher_unknown;
    255 
    256       /**
    257        * For all errors related to a particular denomination, i.e.
    258        *  WITHDRAW_ERROR_DENOMINATION_KEY_UNKNOWN,
    259        *  WITHDRAW_ERROR_DENOMINATION_EXPIRED,
    260        *  WITHDRAW_ERROR_DENOMINATION_VALIDITY_IN_FUTURE,
    261        *  WITHDRAW_ERROR_AGE_RESTRICTION_NOT_SUPPORTED_BY_DENOMINATION,
    262        *  WITHDRAW_ERROR_AGE_MASK_MISMATCH,
    263        * we use this one field.
    264        */
    265       const struct TALER_DenominationHashP *denom_h;
    266 
    267       const char *db_fetch_context;
    268 
    269       struct
    270       {
    271         uint16_t max_allowed;
    272         uint32_t birthday;
    273       } maximum_age_too_large;
    274 
    275       /**
    276        * The lowest age required
    277        */
    278       uint16_t age_restriction_required;
    279 
    280       /**
    281        * Balance of the reserve
    282        */
    283       struct TALER_Amount insufficient_funds;
    284 
    285       enum TALER_ErrorCode ec_confirmation_sign;
    286 
    287       enum TALER_ErrorCode ec_denomination_sign;
    288 
    289       struct
    290       {
    291         struct MHD_Response *response;
    292         unsigned int http_status;
    293       } legitimization_result;
    294 
    295     } details;
    296   } error;
    297 };
    298 
    299 /**
    300  * The following macros set the given error code,
    301  * set the phase to WITHDRAW_PHASE_GENERATE_REPLY_ERROR,
    302  * and optionally set the given field (with an optionally given value).
    303  */
    304 #define SET_ERROR(wc, ec) \
    305         do \
    306         { GNUNET_static_assert (WITHDRAW_ERROR_NONE != ec); \
    307           (wc)->error.code = (ec);                          \
    308           (wc)->phase = WITHDRAW_PHASE_GENERATE_REPLY_ERROR; } while (0)
    309 
    310 #define SET_ERROR_WITH_FIELD(wc, ec, field) \
    311         do \
    312         { GNUNET_static_assert (WITHDRAW_ERROR_NONE != ec); \
    313           (wc)->error.code = (ec);                          \
    314           (wc)->error.details.field = (field);              \
    315           (wc)->phase = WITHDRAW_PHASE_GENERATE_REPLY_ERROR; } while (0)
    316 
    317 #define SET_ERROR_WITH_DETAIL(wc, ec, field, value) \
    318         do \
    319         { GNUNET_static_assert (WITHDRAW_ERROR_NONE != ec); \
    320           (wc)->error.code = (ec);                          \
    321           (wc)->error.details.field = (value);              \
    322           (wc)->phase = WITHDRAW_PHASE_GENERATE_REPLY_ERROR; } while (0)
    323 
    324 
    325 /**
    326  * All withdraw context is kept in a DLL.
    327  */
    328 static struct WithdrawContext *wc_head;
    329 static struct WithdrawContext *wc_tail;
    330 
    331 
    332 void
    333 TEH_withdraw_cleanup ()
    334 {
    335   struct WithdrawContext *wc;
    336 
    337   while (NULL != (wc = wc_head))
    338   {
    339     GNUNET_CONTAINER_DLL_remove (wc_head,
    340                                  wc_tail,
    341                                  wc);
    342     wc->phase = WITHDRAW_PHASE_RETURN_NO;
    343     MHD_resume_connection (wc->rc->connection);
    344   }
    345 }
    346 
    347 
    348 /**
    349  * Terminate the main loop by returning the final
    350  * result.
    351  *
    352  * @param[in,out] wc context to update phase for
    353  * @param mres MHD status to return
    354  */
    355 static void
    356 finish_loop (struct WithdrawContext *wc,
    357              enum MHD_Result mres)
    358 {
    359   wc->phase = (MHD_YES == mres)
    360     ? WITHDRAW_PHASE_RETURN_YES
    361     : WITHDRAW_PHASE_RETURN_NO;
    362 }
    363 
    364 
    365 /**
    366  * Check if the withdraw request is replayed
    367  * and we already have an answer.
    368  * If so, replay the existing answer and return the HTTP response.
    369  *
    370  * @param[in,out] wc parsed request data
    371  * @return true if the request is idempotent with an existing request
    372  *    false if we did not find the request in the DB and did not set @a mret
    373  */
    374 static bool
    375 withdraw_is_idempotent (
    376   struct WithdrawContext *wc)
    377 {
    378   enum GNUNET_DB_QueryStatus qs;
    379   uint8_t max_retries = 3;
    380 
    381   /* We should at most be called once */
    382   GNUNET_assert (! wc->request.is_idempotent);
    383   while (0 < max_retries--)
    384   {
    385     qs = TALER_EXCHANGEDB_get_withdraw (
    386       TEH_pg,
    387       &wc->request.withdraw.reserve_pub,
    388       &wc->request.withdraw.planchets_h,
    389       &wc->request.withdraw_idem);
    390     if (GNUNET_DB_STATUS_SOFT_ERROR != qs)
    391       break;
    392   }
    393 
    394   if (0 > qs)
    395   {
    396     GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR == qs);
    397     GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
    398     SET_ERROR_WITH_DETAIL (wc,
    399                            WITHDRAW_ERROR_DB_FETCH_FAILED,
    400                            db_fetch_context,
    401                            "get_withdraw");
    402     return true; /* Well, kind-of. */
    403   }
    404   if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    405     return false;
    406 
    407   wc->request.is_idempotent = true;
    408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
    409               "request is idempotent\n");
    410 
    411   /* Generate idempotent reply */
    412   TEH_METRICS_num_requests[TEH_MT_REQUEST_IDEMPOTENT_WITHDRAW]++;
    413   wc->phase = WITHDRAW_PHASE_GENERATE_REPLY_SUCCESS;
    414   return true;
    415 }
    416 
    417 
    418 /**
    419  * Function implementing withdraw transaction.  Runs the
    420  * transaction logic; IF it returns a non-error code, the transaction
    421  * logic MUST NOT queue a MHD response.  IF it returns an hard error,
    422  * the transaction logic MUST queue a MHD response and set @a mhd_ret.
    423  * IF it returns the soft error code, the function MAY be called again
    424  * to retry and MUST not queue a MHD response.
    425  *
    426  * @param cls a `struct WithdrawContext *`
    427  * @param connection MHD request which triggered the transaction
    428  * @param[out] mhd_ret set to MHD response status for @a connection,
    429  *             if transaction failed (!)
    430  * @return transaction status
    431  */
    432 static enum GNUNET_DB_QueryStatus
    433 withdraw_transaction (
    434   void *cls,
    435   struct MHD_Connection *connection,
    436   enum MHD_Result *mhd_ret)
    437 {
    438   struct WithdrawContext *wc = cls;
    439   enum GNUNET_DB_QueryStatus qs;
    440   bool balance_ok;
    441   bool age_ok;
    442   bool found;
    443   uint16_t noreveal_index;
    444   bool nonce_reuse;
    445   uint16_t allowed_maximum_age;
    446   uint32_t reserve_birthday;
    447   struct TALER_Amount insufficient_funds;
    448 
    449   qs = TALER_EXCHANGEDB_do_withdraw (TEH_pg,
    450                                      &wc->request.withdraw,
    451                                      &wc->now,
    452                                      &balance_ok,
    453                                      &insufficient_funds,
    454                                      &age_ok,
    455                                      &allowed_maximum_age,
    456                                      &reserve_birthday,
    457                                      &found,
    458                                      &noreveal_index,
    459                                      &nonce_reuse);
    460   if (0 > qs)
    461   {
    462     if (GNUNET_DB_STATUS_HARD_ERROR == qs)
    463       SET_ERROR_WITH_DETAIL (wc,
    464                              WITHDRAW_ERROR_DB_FETCH_FAILED,
    465                              db_fetch_context,
    466                              "do_withdraw");
    467     return qs;
    468   }
    469   if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    470   {
    471     SET_ERROR (wc,
    472                WITHDRAW_ERROR_RESERVE_UNKNOWN);
    473     return GNUNET_DB_STATUS_HARD_ERROR;
    474   }
    475 
    476   if (found)
    477   {
    478     /**
    479      * The request was idempotent and we got the previous noreveal_index.
    480      * We simply overwrite that value in our current withdraw object and
    481      * move on to reply success.
    482      */
    483     wc->request.withdraw.noreveal_index = noreveal_index;
    484     wc->phase = WITHDRAW_PHASE_GENERATE_REPLY_SUCCESS;
    485     return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
    486   }
    487 
    488   if (! age_ok)
    489   {
    490     if (wc->request.withdraw.age_proof_required)
    491     {
    492       wc->error.details.maximum_age_too_large.max_allowed = allowed_maximum_age;
    493       wc->error.details.maximum_age_too_large.birthday = reserve_birthday;
    494       SET_ERROR (wc,
    495                  WITHDRAW_ERROR_MAXIMUM_AGE_TOO_LARGE);
    496     }
    497     else
    498     {
    499       wc->error.details.age_restriction_required = allowed_maximum_age;
    500       SET_ERROR (wc,
    501                  WITHDRAW_ERROR_AGE_RESTRICTION_REQUIRED);
    502     }
    503     return GNUNET_DB_STATUS_HARD_ERROR;
    504   }
    505 
    506   if (! balance_ok)
    507   {
    508     TALER_EXCHANGEDB_rollback (TEH_pg);
    509     SET_ERROR_WITH_FIELD (wc,
    510                           WITHDRAW_ERROR_INSUFFICIENT_FUNDS,
    511                           insufficient_funds);
    512     return GNUNET_DB_STATUS_HARD_ERROR;
    513   }
    514 
    515   if (nonce_reuse)
    516   {
    517     GNUNET_break (0);
    518     SET_ERROR (wc,
    519                WITHDRAW_ERROR_NONCE_REUSE);
    520     return GNUNET_DB_STATUS_HARD_ERROR;
    521   }
    522 
    523   if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
    524     TEH_METRICS_num_success[TEH_MT_SUCCESS_WITHDRAW]++;
    525   return qs;
    526 }
    527 
    528 
    529 /**
    530  * The request was prepared successfully.
    531  * Run the main DB transaction.
    532  *
    533  * @param wc The context for the current withdraw request
    534  */
    535 static void
    536 phase_run_transaction (
    537   struct WithdrawContext *wc)
    538 {
    539   enum MHD_Result mhd_ret;
    540   enum GNUNET_GenericReturnValue ret;
    541 
    542   GNUNET_assert (WITHDRAW_PHASE_RUN_TRANSACTION ==
    543                  wc->phase);
    544   ret = TEH_DB_run_transaction (wc->rc->connection,
    545                                 "run withdraw",
    546                                 TEH_MT_REQUEST_WITHDRAW,
    547                                 &mhd_ret,
    548                                 &withdraw_transaction,
    549                                 wc);
    550   /* If the transaction has changed the phase, we don't alter it and return.*/
    551   if (WITHDRAW_PHASE_RUN_TRANSACTION != wc->phase)
    552     return;
    553   if (GNUNET_OK != ret)
    554   {
    555     /* The transaction failed without setting an error phase (preflight,
    556        start, hard commit failure or too many soft failures); a response
    557        was already queued by TEH_DB_run_transaction(). */
    558     GNUNET_break (0);
    559     finish_loop (wc,
    560                  mhd_ret);
    561     return;
    562   }
    563   wc->phase++;
    564 }
    565 
    566 
    567 /**
    568  * The request for withdraw was parsed successfully.
    569  * Sign and persist the chosen blinded coins for the reveal step.
    570  *
    571  * @param wc The context for the current withdraw request
    572  */
    573 static void
    574 phase_prepare_transaction (
    575   struct WithdrawContext *wc)
    576 {
    577   size_t offset = 0;
    578 
    579   wc->request.withdraw.denom_sigs
    580     = GNUNET_new_array (
    581         wc->request.withdraw.num_coins,
    582         struct TALER_BlindedDenominationSignature);
    583   /* Pick the challenge in case of age restriction  */
    584   if (wc->request.withdraw.age_proof_required)
    585   {
    586     wc->request.withdraw.noreveal_index =
    587       GNUNET_CRYPTO_random_u32 (TALER_CNC_KAPPA);
    588     /**
    589      * In case of age restriction, we use the corresponding offset in the planchet
    590      * array to the beginning of the coins corresponding to the noreveal_index.
    591      */
    592     offset = wc->request.withdraw.noreveal_index
    593              * wc->request.withdraw.num_coins;
    594     GNUNET_assert (offset + wc->request.withdraw.num_coins <=
    595                    wc->request.num_planchets);
    596   }
    597 
    598   /* Choose and sign the coins */
    599   {
    600     struct TEH_SECMOD_CoinSignData csds[wc->request.withdraw.num_coins];
    601     enum TALER_ErrorCode ec_denomination_sign;
    602 
    603     memset (csds,
    604             0,
    605             sizeof(csds));
    606 
    607     /* Pick the chosen blinded coins */
    608     for (uint32_t i = 0; i<wc->request.withdraw.num_coins; i++)
    609     {
    610       csds[i].bp = &wc->request.planchets[i + offset];
    611       csds[i].h_denom_pub = &wc->request.denoms_h[i];
    612     }
    613 
    614     ec_denomination_sign = TEH_SECMOD_denom_batch_sign (
    615       wc->request.withdraw.num_coins,
    616       csds,
    617       false,
    618       wc->request.withdraw.denom_sigs);
    619     if (TALER_EC_NONE != ec_denomination_sign)
    620     {
    621       GNUNET_break (0);
    622       SET_ERROR_WITH_FIELD (wc,
    623                             WITHDRAW_ERROR_DENOMINATION_SIGN,
    624                             ec_denomination_sign);
    625       return;
    626     }
    627 
    628     /* Save the hash value of the selected batch of coins */
    629     wc->request.withdraw.selected_h =
    630       wc->request.kappa_planchets_h[wc->request.withdraw.noreveal_index];
    631   }
    632 
    633   /**
    634    * For the denominations with cipher CS, calculate the R-values
    635    * and save the choices we made now, as at a later point, the
    636    * private keys for the denominations might now be available anymore
    637    * to make the same choice again.
    638    */
    639   if (0 <  wc->request.withdraw.num_cs_r_values)
    640   {
    641     size_t num_cs_r_values = wc->request.withdraw.num_cs_r_values;
    642     struct TEH_SECMOD_CsDeriveData cdds[num_cs_r_values];
    643     struct GNUNET_CRYPTO_CsSessionNonce nonces[num_cs_r_values];
    644 
    645     memset (nonces,
    646             0,
    647             sizeof(nonces));
    648     wc->request.withdraw.cs_r_values
    649       = GNUNET_new_array (
    650           num_cs_r_values,
    651           struct GNUNET_CRYPTO_CSPublicRPairP);
    652     wc->request.withdraw.cs_r_choices = 0;
    653 
    654     GNUNET_assert (! wc->request.withdraw.no_blinding_seed);
    655     TALER_cs_derive_nonces_from_seed (
    656       &wc->request.withdraw.blinding_seed,
    657       false,   /* not for melt */
    658       num_cs_r_values,
    659       wc->request.cs_indices,
    660       nonces);
    661 
    662     for (size_t i = 0; i < num_cs_r_values; i++)
    663     {
    664       size_t idx = wc->request.cs_indices[i];
    665 
    666       GNUNET_assert (idx < wc->request.withdraw.num_coins);
    667       cdds[i].h_denom_pub = &wc->request.denoms_h[idx];
    668       cdds[i].nonce = &nonces[i];
    669     }
    670 
    671     /**
    672      * Let the crypto helper generate the R-values and make the choices.
    673      */
    674     if (TALER_EC_NONE !=
    675         TEH_SECMOD_denom_cs_batch_r_pub_simple (
    676           wc->request.withdraw.num_cs_r_values,
    677           cdds,
    678           false,
    679           wc->request.withdraw.cs_r_values))
    680     {
    681       GNUNET_break (0);
    682       SET_ERROR (wc,
    683                  WITHDRAW_ERROR_CRYPTO_HELPER);
    684       return;
    685     }
    686 
    687     /* This invariant should hold because
    688        num_coins <= TALER_MAX_COINS. Still good
    689        to check explicitly. */
    690     GNUNET_assert (num_cs_r_values <= 64);
    691     /* Now save the choices for the selected bits */
    692     for (size_t i = 0; i < num_cs_r_values; i++)
    693     {
    694       size_t idx = wc->request.cs_indices[i];
    695       struct TALER_BlindedDenominationSignature *sig =
    696         &wc->request.withdraw.denom_sigs[idx];
    697       uint64_t bit = sig->blinded_sig->details.blinded_cs_answer.b;
    698 
    699       GNUNET_static_assert (
    700         TALER_MAX_COINS <=
    701         sizeof(wc->request.withdraw.cs_r_choices) * 8);
    702       GNUNET_assert (bit <= 1); /* well, should actually be 0 or 1 */
    703       wc->request.withdraw.cs_r_choices |= bit << i;
    704     }
    705   }
    706   wc->phase++;
    707 }
    708 
    709 
    710 /**
    711  * Check the KYC result.
    712  *
    713  * @param wc context for request processing
    714  */
    715 static void
    716 phase_check_kyc_result (struct WithdrawContext *wc)
    717 {
    718   /* return final positive response */
    719   if (! wc->kyc.ok)
    720   {
    721     SET_ERROR (wc,
    722                WITHDRAW_ERROR_KYC_REQUIRED);
    723     return;
    724   }
    725   wc->phase++;
    726 }
    727 
    728 
    729 /**
    730  * Function called with the result of a legitimization
    731  * check.
    732  *
    733  * @param cls closure
    734  * @param lcr legitimization check result
    735  */
    736 static void
    737 withdraw_legi_cb (
    738   void *cls,
    739   const struct TEH_LegitimizationCheckResult *lcr)
    740 {
    741   struct WithdrawContext *wc = cls;
    742 
    743   wc->lch = NULL;
    744   GNUNET_assert (WITHDRAW_PHASE_SUSPENDED ==
    745                  wc->phase);
    746   MHD_resume_connection (wc->rc->connection);
    747   GNUNET_CONTAINER_DLL_remove (wc_head,
    748                                wc_tail,
    749                                wc);
    750   TALER_MHD_daemon_trigger ();
    751   if (NULL != lcr->response)
    752   {
    753     wc->error.details.legitimization_result.response = lcr->response;
    754     wc->error.details.legitimization_result.http_status = lcr->http_status;
    755     SET_ERROR (wc,
    756                WITHDRAW_ERROR_LEGITIMIZATION_RESULT);
    757     return;
    758   }
    759   wc->kyc = lcr->kyc;
    760   wc->phase = WITHDRAW_PHASE_CHECK_KYC_RESULT;
    761 }
    762 
    763 
    764 /**
    765  * Function called to iterate over KYC-relevant transaction amounts for a
    766  * particular time range. Called within a database transaction, so must
    767  * not start a new one.
    768  *
    769  * @param cls closure, identifies the event type and account to iterate
    770  *        over events for
    771  * @param limit maximum time-range for which events should be fetched
    772  *        (timestamp in the past)
    773  * @param cb function to call on each event found, events must be returned
    774  *        in reverse chronological order
    775  * @param cb_cls closure for @a cb, of type struct WithdrawContext
    776  * @return transaction status
    777  */
    778 static enum GNUNET_DB_QueryStatus
    779 withdraw_amount_cb (
    780   void *cls,
    781   struct GNUNET_TIME_Absolute limit,
    782   TALER_KYCLOGIC_KycAmountCallback cb,
    783   void *cb_cls)
    784 {
    785   struct WithdrawContext *wc = cls;
    786   enum GNUNET_GenericReturnValue ret;
    787   enum GNUNET_DB_QueryStatus qs;
    788 
    789   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    790               "Signaling amount %s for KYC check during witdrawal\n",
    791               TALER_amount2s (&wc->request.withdraw.amount_with_fee));
    792 
    793   ret = cb (cb_cls,
    794             &wc->request.withdraw.amount_with_fee,
    795             wc->now.abs_time);
    796   GNUNET_break (GNUNET_SYSERR != ret);
    797   if (GNUNET_OK != ret)
    798     return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
    799 
    800   qs = TALER_EXCHANGEDB_iterate_withdraw_amounts_for_kyc_check (
    801     TEH_pg,
    802     &wc->h_normalized_payto,
    803     limit,
    804     cb,
    805     cb_cls);
    806   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    807               "Got %d additional transactions for this withdrawal and limit %llu\n",
    808               qs,
    809               (unsigned long long) limit.abs_value_us);
    810   GNUNET_break (qs >= 0);
    811   return qs;
    812 }
    813 
    814 
    815 /**
    816  * Do legitimization check.
    817  *
    818  * @param wc operation context
    819  */
    820 static void
    821 phase_run_legi_check (struct WithdrawContext *wc)
    822 {
    823   enum GNUNET_DB_QueryStatus qs;
    824   struct TALER_FullPayto payto_uri;
    825   struct TALER_FullPaytoHashP h_full_payto;
    826 
    827   /* Check if the money came from a wire transfer */
    828   qs = TALER_EXCHANGEDB_get_reserve_origin (
    829     TEH_pg,
    830     &wc->request.withdraw.reserve_pub,
    831     &h_full_payto,
    832     &payto_uri);
    833   if (qs < 0)
    834   {
    835     SET_ERROR_WITH_DETAIL (wc,
    836                            WITHDRAW_ERROR_DB_FETCH_FAILED,
    837                            db_fetch_context,
    838                            "reserves_get_origin");
    839     return;
    840   }
    841   /* If _no_ results, reserve was created by merge,
    842      in which case no KYC check is required as the
    843      merge already did that. */
    844   if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    845   {
    846     wc->phase = WITHDRAW_PHASE_PREPARE_TRANSACTION;
    847     return;
    848   }
    849   TALER_full_payto_normalize_and_hash (payto_uri,
    850                                        &wc->h_normalized_payto);
    851   wc->lch = TEH_legitimization_check (
    852     &wc->rc->async_scope_id,
    853     TALER_KYCLOGIC_KYC_TRIGGER_WITHDRAW,
    854     payto_uri,
    855     &wc->h_normalized_payto,
    856     NULL, /* no account pub: this is about the origin account */
    857     &withdraw_amount_cb,
    858     wc,
    859     &withdraw_legi_cb,
    860     wc);
    861   GNUNET_assert (NULL != wc->lch);
    862   GNUNET_free (payto_uri.full_payto);
    863   GNUNET_CONTAINER_DLL_insert (wc_head,
    864                                wc_tail,
    865                                wc);
    866   MHD_suspend_connection (wc->rc->connection);
    867   wc->phase = WITHDRAW_PHASE_SUSPENDED;
    868 }
    869 
    870 
    871 /**
    872  * Check if the given denomination is still or already valid, has not been
    873  * revoked and potentically supports age restriction.
    874  *
    875  * @param[in,out] wc context for the withdraw operation
    876  * @param ksh The handle to the current state of (denomination) keys in the exchange
    877  * @param denom_h Hash of the denomination key to check
    878  * @param[out] pdk denomination key found, might be NULL
    879  * @return true when denomation was found and valid,
    880  *         false when denomination was not valid and the state machine was advanced
    881  */
    882 static enum GNUNET_GenericReturnValue
    883 find_denomination (
    884   struct WithdrawContext *wc,
    885   struct TEH_KeyStateHandle *ksh,
    886   const struct TALER_DenominationHashP *denom_h,
    887   struct TEH_DenominationKey **pdk)
    888 {
    889   struct TEH_DenominationKey *dk;
    890 
    891   *pdk = NULL;
    892   dk = TEH_keys_denomination_by_hash_from_state (
    893     ksh,
    894     denom_h,
    895     NULL,
    896     NULL);
    897   if (NULL == dk)
    898   {
    899     SET_ERROR_WITH_FIELD (wc,
    900                           WITHDRAW_ERROR_DENOMINATION_KEY_UNKNOWN,
    901                           denom_h);
    902     return false;
    903   }
    904   if (GNUNET_TIME_absolute_is_past (
    905         dk->meta.expire_withdraw.abs_time))
    906   {
    907     SET_ERROR_WITH_FIELD (wc,
    908                           WITHDRAW_ERROR_DENOMINATION_EXPIRED,
    909                           denom_h);
    910     return false;
    911   }
    912   if (GNUNET_TIME_absolute_is_future (
    913         dk->meta.start.abs_time))
    914   {
    915     GNUNET_break_op (0);
    916     SET_ERROR_WITH_FIELD (wc,
    917                           WITHDRAW_ERROR_DENOMINATION_VALIDITY_IN_FUTURE,
    918                           denom_h);
    919     return false;
    920   }
    921   if (dk->recoup_possible)
    922   {
    923     SET_ERROR (wc,
    924                WITHDRAW_ERROR_DENOMINATION_REVOKED);
    925     return false;
    926   }
    927   /* In case of age withdraw, make sure that the denomination supports age restriction */
    928   if (wc->request.withdraw.age_proof_required)
    929   {
    930     if (0 == dk->denom_pub.age_mask.bits)
    931     {
    932       GNUNET_break_op (0);
    933       SET_ERROR_WITH_FIELD (wc,
    934                             WITHDRAW_ERROR_AGE_RESTRICTION_NOT_SUPPORTED_BY_DENOMINATION,
    935                             denom_h);
    936       return false;
    937     }
    938   }
    939   *pdk = dk;
    940   return true;
    941 }
    942 
    943 
    944 /**
    945  * Check if the given array of hashes of denomination_keys
    946  * a) belong to valid denominations
    947  * b) those are marked as age restricted, if the request is age restricted
    948  * c) calculate the total amount of the denominations including fees
    949  * for withdraw.
    950  *
    951  * @param wc context of the age withdrawal to check keys for
    952  */
    953 static void
    954 phase_check_keys (
    955   struct WithdrawContext *wc)
    956 {
    957   struct TEH_KeyStateHandle *ksh;
    958   bool is_cs_denom[wc->request.withdraw.num_coins];
    959   struct TALER_AgeMask age_mask = { 0 };
    960 
    961   memset (is_cs_denom,
    962           0,
    963           sizeof(is_cs_denom));
    964   ksh = TEH_keys_get_state ();
    965   if (NULL == ksh)
    966   {
    967     GNUNET_break (0);
    968     SET_ERROR (wc,
    969                WITHDRAW_ERROR_KEYS_MISSING);
    970     return;
    971   }
    972   wc->request.withdraw.denom_serials =
    973     GNUNET_new_array (wc->request.withdraw.num_coins,
    974                       uint64_t);
    975   GNUNET_assert (GNUNET_OK ==
    976                  TALER_amount_set_zero (TEH_currency,
    977                                         &wc->request.amount));
    978   GNUNET_assert (GNUNET_OK ==
    979                  TALER_amount_set_zero (TEH_currency,
    980                                         &wc->request.fee));
    981   GNUNET_assert (GNUNET_OK ==
    982                  TALER_amount_set_zero (TEH_currency,
    983                                         &wc->request.withdraw.amount_with_fee));
    984 
    985   for (unsigned int i = 0; i < wc->request.withdraw.num_coins; i++)
    986   {
    987     struct TEH_DenominationKey *dk;
    988 
    989     if (! find_denomination (wc,
    990                              ksh,
    991                              &wc->request.denoms_h[i],
    992                              &dk))
    993       return;
    994     /* All coins of an age-restricted withdraw must use the same age
    995        groups, as /reveal-withdraw derives their age commitments with
    996        one mask. */
    997     if (wc->request.withdraw.age_proof_required)
    998     {
    999       if (0 == i)
   1000         age_mask = dk->meta.age_mask;
   1001       if (age_mask.bits != dk->meta.age_mask.bits)
   1002       {
   1003         GNUNET_break_op (0);
   1004         SET_ERROR_WITH_DETAIL (wc,
   1005                                WITHDRAW_ERROR_AGE_MASK_MISMATCH,
   1006                                denom_h,
   1007                                &wc->request.denoms_h[i]);
   1008         return;
   1009       }
   1010     }
   1011     switch (dk->denom_pub.bsign_pub_key->cipher)
   1012     {
   1013     case GNUNET_CRYPTO_BSA_INVALID:
   1014       /* This should never happen (memory corruption?) */
   1015       GNUNET_assert (0);
   1016     case GNUNET_CRYPTO_BSA_RSA:
   1017       /* nothing to do here */
   1018       break;
   1019     case GNUNET_CRYPTO_BSA_CS:
   1020       if (wc->request.withdraw.no_blinding_seed)
   1021       {
   1022         GNUNET_break_op (0);
   1023         SET_ERROR (wc,
   1024                    WITHDRAW_ERROR_BLINDING_SEED_REQUIRED);
   1025         return;
   1026       }
   1027       wc->request.withdraw.num_cs_r_values++;
   1028       is_cs_denom[i] = true;
   1029       break;
   1030     }
   1031 
   1032     /* Ensure the ciphers from the planchets match the denominations'. */
   1033     if (wc->request.withdraw.age_proof_required)
   1034     {
   1035       for (uint8_t k = 0; k < TALER_CNC_KAPPA; k++)
   1036       {
   1037         size_t off = k * wc->request.withdraw.num_coins;
   1038 
   1039         if (dk->denom_pub.bsign_pub_key->cipher !=
   1040             wc->request.planchets[i + off].blinded_message->cipher)
   1041         {
   1042           GNUNET_break_op (0);
   1043           SET_ERROR (wc,
   1044                      WITHDRAW_ERROR_CIPHER_MISMATCH);
   1045           return;
   1046         }
   1047       }
   1048     }
   1049     else
   1050     {
   1051       if (dk->denom_pub.bsign_pub_key->cipher !=
   1052           wc->request.planchets[i].blinded_message->cipher)
   1053       {
   1054         GNUNET_break_op (0);
   1055         SET_ERROR (wc,
   1056                    WITHDRAW_ERROR_CIPHER_MISMATCH);
   1057         return;
   1058       }
   1059     }
   1060 
   1061     /* Accumulate the values */
   1062     if (0 > TALER_amount_add (&wc->request.amount,
   1063                               &wc->request.amount,
   1064                               &dk->meta.value))
   1065     {
   1066       GNUNET_break_op (0);
   1067       SET_ERROR (wc,
   1068                  WITHDRAW_ERROR_AMOUNT_OVERFLOW);
   1069       return;
   1070     }
   1071 
   1072     /* Accumulate the withdraw fees */
   1073     if (0 > TALER_amount_add (&wc->request.fee,
   1074                               &wc->request.fee,
   1075                               &dk->meta.fees.withdraw))
   1076     {
   1077       GNUNET_break_op (0);
   1078       SET_ERROR (wc,
   1079                  WITHDRAW_ERROR_FEE_OVERFLOW);
   1080       return;
   1081     }
   1082     wc->request.withdraw.denom_serials[i] = dk->meta.serial;
   1083   }
   1084 
   1085   /* Save the total amount including fees */
   1086   if (0 >  TALER_amount_add (
   1087         &wc->request.withdraw.amount_with_fee,
   1088         &wc->request.amount,
   1089         &wc->request.fee))
   1090   {
   1091     GNUNET_break_op (0);
   1092     SET_ERROR (wc,
   1093                WITHDRAW_ERROR_AMOUNT_PLUS_FEE_OVERFLOW);
   1094     return;
   1095   }
   1096 
   1097   /* Save the indices of CS denominations */
   1098   if (0 < wc->request.withdraw.num_cs_r_values)
   1099   {
   1100     size_t j = 0;
   1101 
   1102     wc->request.cs_indices = GNUNET_new_array (
   1103       wc->request.withdraw.num_cs_r_values,
   1104       uint32_t);
   1105 
   1106     for (size_t i = 0; i < wc->request.withdraw.num_coins; i++)
   1107     {
   1108       if (is_cs_denom[i])
   1109         wc->request.cs_indices[j++] = i;
   1110     }
   1111   }
   1112 
   1113   /* The helper signs a CS planchet under the nonce in the planchet; it
   1114      must be the one derived from the blinding seed for the coin's index
   1115      (ext-cs.md (E1)).  Otherwise the client chooses the nonce, and two
   1116      signatures under one nonce reveal the denomination private key. */
   1117   for (size_t i = 0; i < wc->request.withdraw.num_coins; i++)
   1118   {
   1119     struct GNUNET_CRYPTO_CsSessionNonce nonce;
   1120     size_t kappa = wc->request.withdraw.age_proof_required
   1121                    ? TALER_CNC_KAPPA
   1122                    : 1;
   1123 
   1124     if (! is_cs_denom[i])
   1125       continue;
   1126     TALER_cs_nonce_derive_indexed (&wc->request.withdraw.blinding_seed,
   1127                                    false,
   1128                                    (uint32_t) i,
   1129                                    &nonce);
   1130     for (size_t k = 0; k < kappa; k++)
   1131     {
   1132       const struct GNUNET_CRYPTO_BlindedMessage *bm
   1133         = wc->request.planchets[i + k * wc->request.withdraw.num_coins]
   1134           .blinded_message;
   1135 
   1136       if ( (GNUNET_CRYPTO_BSA_CS != bm->cipher) ||
   1137            (0 != GNUNET_memcmp (&nonce,
   1138                                 &bm->details.cs_blinded_message.nonce)) )
   1139       {
   1140         GNUNET_break_op (0);
   1141         SET_ERROR (wc,
   1142                    WITHDRAW_ERROR_CS_NONCE_MISMATCH);
   1143         return;
   1144       }
   1145     }
   1146   }
   1147 
   1148   wc->phase++;
   1149 }
   1150 
   1151 
   1152 /**
   1153  * Check that the client signature authorizing the withdrawal is valid.
   1154  *
   1155  * @param[in,out] wc request context to check
   1156  */
   1157 static void
   1158 phase_check_reserve_signature (
   1159   struct WithdrawContext *wc)
   1160 {
   1161   TEH_METRICS_num_verifications[TEH_MT_SIGNATURE_EDDSA]++;
   1162   if (GNUNET_OK !=
   1163       TALER_wallet_withdraw_verify (
   1164         &wc->request.amount,
   1165         &wc->request.fee,
   1166         &wc->request.withdraw.planchets_h,
   1167         wc->request.withdraw.no_blinding_seed
   1168         ? NULL
   1169         : &wc->request.withdraw.blinding_seed,
   1170         (wc->request.withdraw.age_proof_required)
   1171         ? &TEH_age_restriction_mask
   1172         : NULL,
   1173         (wc->request.withdraw.age_proof_required)
   1174         ? wc->request.withdraw.max_age
   1175         : 0,
   1176         &wc->request.withdraw.reserve_pub,
   1177         &wc->request.withdraw.reserve_sig))
   1178   {
   1179     GNUNET_break_op (0);
   1180     SET_ERROR (wc,
   1181                WITHDRAW_ERROR_RESERVE_SIGNATURE_INVALID);
   1182     return;
   1183   }
   1184   wc->phase++;
   1185 }
   1186 
   1187 
   1188 /**
   1189  * Free data inside of @a wd, but not @a wd itself.
   1190  *
   1191  * @param[in] wd withdraw data to free
   1192  */
   1193 static void
   1194 free_db_withdraw_data (struct TALER_EXCHANGEDB_Withdraw *wd)
   1195 {
   1196   if (NULL != wd->denom_sigs)
   1197   {
   1198     for (unsigned int i = 0; i<wd->num_coins; i++)
   1199       TALER_blinded_denom_sig_free (&wd->denom_sigs[i]);
   1200     GNUNET_free (wd->denom_sigs);
   1201   }
   1202   GNUNET_free (wd->denom_serials);
   1203   GNUNET_free (wd->cs_r_values);
   1204 }
   1205 
   1206 
   1207 /**
   1208  * Cleanup routine for withdraw request.
   1209  * The function is called upon completion of the request
   1210  * that should clean up @a rh_ctx. Can be NULL.
   1211  *
   1212  * @param rc request context to clean up
   1213  */
   1214 static void
   1215 clean_withdraw_rc (struct TEH_RequestContext *rc)
   1216 {
   1217   struct WithdrawContext *wc = rc->rh_ctx;
   1218 
   1219   if (NULL != wc->lch)
   1220   {
   1221     TEH_legitimization_check_cancel (wc->lch);
   1222     wc->lch = NULL;
   1223   }
   1224   GNUNET_free (wc->request.denoms_h);
   1225   if (NULL != wc->request.planchets)
   1226   {
   1227     /* num_planchets is set long before planchets is allocated,
   1228        so this needs the above guard */
   1229     for (unsigned int i = 0; i<wc->request.num_planchets; i++)
   1230       TALER_blinded_planchet_free (&wc->request.planchets[i]);
   1231     GNUNET_free (wc->request.planchets);
   1232   }
   1233   free_db_withdraw_data (&wc->request.withdraw);
   1234   GNUNET_free (wc->request.cs_indices);
   1235   if (wc->request.is_idempotent)
   1236     free_db_withdraw_data (&wc->request.withdraw_idem);
   1237   if ( (WITHDRAW_ERROR_LEGITIMIZATION_RESULT == wc->error.code) &&
   1238        (NULL != wc->error.details.legitimization_result.response) )
   1239   {
   1240     MHD_destroy_response (wc->error.details.legitimization_result.response);
   1241     wc->error.details.legitimization_result.response = NULL;
   1242   }
   1243   GNUNET_free (wc);
   1244 }
   1245 
   1246 
   1247 /**
   1248  * Generates response for the withdraw request.
   1249  *
   1250  * @param wc withdraw operation context
   1251  */
   1252 static void
   1253 phase_generate_reply_success (struct WithdrawContext *wc)
   1254 {
   1255   struct TALER_EXCHANGEDB_Withdraw *db_obj;
   1256 
   1257   db_obj = wc->request.is_idempotent
   1258     ? &wc->request.withdraw_idem
   1259     : &wc->request.withdraw;
   1260 
   1261   if (wc->request.withdraw.age_proof_required)
   1262   {
   1263     struct TALER_ExchangePublicKeyP pub;
   1264     struct TALER_ExchangeSignatureP sig;
   1265     enum TALER_ErrorCode ec_confirmation_sign;
   1266 
   1267     ec_confirmation_sign =
   1268       TALER_exchange_online_withdraw_age_confirmation_sign (
   1269         &TEH_keys_exchange_sign_,
   1270         &db_obj->planchets_h,
   1271         db_obj->noreveal_index,
   1272         &pub,
   1273         &sig);
   1274     if (TALER_EC_NONE != ec_confirmation_sign)
   1275     {
   1276       SET_ERROR_WITH_FIELD (wc,
   1277                             WITHDRAW_ERROR_CONFIRMATION_SIGN,
   1278                             ec_confirmation_sign);
   1279       return;
   1280     }
   1281 
   1282     finish_loop (wc,
   1283                  TALER_MHD_REPLY_JSON_PACK (
   1284                    wc->rc->connection,
   1285                    MHD_HTTP_CREATED,
   1286                    GNUNET_JSON_pack_uint64 ("noreveal_index",
   1287                                             db_obj->noreveal_index),
   1288                    GNUNET_JSON_pack_data_auto ("exchange_sig",
   1289                                                &sig),
   1290                    GNUNET_JSON_pack_data_auto ("exchange_pub",
   1291                                                &pub)));
   1292   }
   1293   else /* not age restricted */
   1294   {
   1295     json_t *sigs;
   1296 
   1297     sigs = json_array ();
   1298     GNUNET_assert (NULL != sigs);
   1299     for (unsigned int i = 0; i<db_obj->num_coins; i++)
   1300     {
   1301       GNUNET_assert (
   1302         0 ==
   1303         json_array_append_new (
   1304           sigs,
   1305           GNUNET_JSON_PACK (
   1306             TALER_JSON_pack_blinded_denom_sig (
   1307               NULL,
   1308               &db_obj->denom_sigs[i]))));
   1309     }
   1310     finish_loop (wc,
   1311                  TALER_MHD_REPLY_JSON_PACK (
   1312                    wc->rc->connection,
   1313                    MHD_HTTP_OK,
   1314                    GNUNET_JSON_pack_array_steal ("ev_sigs",
   1315                                                  sigs)));
   1316   }
   1317 
   1318   TEH_METRICS_withdraw_num_coins += db_obj->num_coins;
   1319 }
   1320 
   1321 
   1322 /**
   1323  * Reports an error, potentially with details.
   1324  * That is, it puts a error-type specific response into the MHD queue.
   1325  * It will do a idempotency check first, if needed for the error type.
   1326  *
   1327  * @param wc withdraw context
   1328  */
   1329 static void
   1330 phase_generate_reply_error (
   1331   struct WithdrawContext *wc)
   1332 {
   1333   GNUNET_assert (WITHDRAW_PHASE_GENERATE_REPLY_ERROR == wc->phase);
   1334   if (IDEMPOTENCY_CHECK_REQUIRED (wc->error.code) &&
   1335       withdraw_is_idempotent (wc))
   1336   {
   1337     return;
   1338   }
   1339 
   1340   switch (wc->error.code)
   1341   {
   1342   case WITHDRAW_ERROR_NONE:
   1343     break;
   1344   case WITHDRAW_ERROR_REQUEST_PARAMETER_MALFORMED:
   1345     finish_loop (wc,
   1346                  TALER_MHD_reply_with_error (
   1347                    wc->rc->connection,
   1348                    MHD_HTTP_BAD_REQUEST,
   1349                    TALER_EC_GENERIC_PARAMETER_MALFORMED,
   1350                    wc->error.details.request_parameter_malformed));
   1351     return;
   1352   case WITHDRAW_ERROR_KEYS_MISSING:
   1353     finish_loop (wc,
   1354                  TALER_MHD_reply_with_error (
   1355                    wc->rc->connection,
   1356                    MHD_HTTP_SERVICE_UNAVAILABLE,
   1357                    TALER_EC_EXCHANGE_GENERIC_KEYS_MISSING,
   1358                    NULL));
   1359     return;
   1360   case WITHDRAW_ERROR_DB_FETCH_FAILED:
   1361     finish_loop (wc,
   1362                  TALER_MHD_reply_with_error (
   1363                    wc->rc->connection,
   1364                    MHD_HTTP_INTERNAL_SERVER_ERROR,
   1365                    TALER_EC_GENERIC_DB_FETCH_FAILED,
   1366                    wc->error.details.db_fetch_context));
   1367     return;
   1368   case WITHDRAW_ERROR_DB_INVARIANT_FAILURE:
   1369     finish_loop (wc,
   1370                  TALER_MHD_reply_with_error (
   1371                    wc->rc->connection,
   1372                    MHD_HTTP_INTERNAL_SERVER_ERROR,
   1373                    TALER_EC_GENERIC_DB_INVARIANT_FAILURE,
   1374                    NULL));
   1375     return;
   1376   case WITHDRAW_ERROR_RESERVE_UNKNOWN:
   1377     finish_loop (wc,
   1378                  TALER_MHD_reply_with_error (
   1379                    wc->rc->connection,
   1380                    MHD_HTTP_NOT_FOUND,
   1381                    TALER_EC_EXCHANGE_GENERIC_RESERVE_UNKNOWN,
   1382                    NULL));
   1383     return;
   1384   case WITHDRAW_ERROR_DENOMINATION_SIGN:
   1385     finish_loop (wc,
   1386                  TALER_MHD_reply_with_ec (
   1387                    wc->rc->connection,
   1388                    wc->error.details.ec_denomination_sign,
   1389                    NULL));
   1390     return;
   1391   case WITHDRAW_ERROR_KYC_REQUIRED:
   1392     finish_loop (wc,
   1393                  TEH_RESPONSE_reply_kyc_required (
   1394                    wc->rc->connection,
   1395                    &wc->h_normalized_payto,
   1396                    &wc->kyc,
   1397                    false));
   1398     return;
   1399   case WITHDRAW_ERROR_DENOMINATION_KEY_UNKNOWN:
   1400     GNUNET_break_op (0);
   1401     finish_loop (wc,
   1402                  TEH_RESPONSE_reply_unknown_denom_pub_hash (
   1403                    wc->rc->connection,
   1404                    wc->error.details.denom_h));
   1405     return;
   1406   case WITHDRAW_ERROR_DENOMINATION_EXPIRED:
   1407     GNUNET_break_op (0);
   1408     finish_loop (wc,
   1409                  TEH_RESPONSE_reply_expired_denom_pub_hash (
   1410                    wc->rc->connection,
   1411                    wc->error.details.denom_h,
   1412                    TALER_EC_EXCHANGE_GENERIC_DENOMINATION_EXPIRED,
   1413                    "WITHDRAW"));
   1414     return;
   1415   case WITHDRAW_ERROR_DENOMINATION_VALIDITY_IN_FUTURE:
   1416     finish_loop (wc,
   1417                  TEH_RESPONSE_reply_expired_denom_pub_hash (
   1418                    wc->rc->connection,
   1419                    wc->error.details.denom_h,
   1420                    TALER_EC_EXCHANGE_GENERIC_DENOMINATION_VALIDITY_IN_FUTURE,
   1421                    "WITHDRAW"));
   1422     return;
   1423   case WITHDRAW_ERROR_DENOMINATION_REVOKED:
   1424     GNUNET_break_op (0);
   1425     finish_loop (wc,
   1426                  TALER_MHD_reply_with_error (
   1427                    wc->rc->connection,
   1428                    MHD_HTTP_GONE,
   1429                    TALER_EC_EXCHANGE_GENERIC_DENOMINATION_REVOKED,
   1430                    NULL));
   1431     return;
   1432   case WITHDRAW_ERROR_CIPHER_MISMATCH:
   1433     finish_loop (wc,
   1434                  TALER_MHD_reply_with_error (
   1435                    wc->rc->connection,
   1436                    MHD_HTTP_BAD_REQUEST,
   1437                    TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH,
   1438                    NULL));
   1439     return;
   1440   case WITHDRAW_ERROR_BLINDING_SEED_REQUIRED:
   1441     finish_loop (wc,
   1442                  TALER_MHD_reply_with_error (
   1443                    wc->rc->connection,
   1444                    MHD_HTTP_BAD_REQUEST,
   1445                    TALER_EC_GENERIC_PARAMETER_MISSING,
   1446                    "blinding_seed"));
   1447     return;
   1448   case WITHDRAW_ERROR_CRYPTO_HELPER:
   1449     finish_loop (wc,
   1450                  TALER_MHD_reply_with_error (
   1451                    wc->rc->connection,
   1452                    MHD_HTTP_INTERNAL_SERVER_ERROR,
   1453                    TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE,
   1454                    NULL));
   1455     return;
   1456   case WITHDRAW_ERROR_RESERVE_CIPHER_UNKNOWN:
   1457     finish_loop (wc,
   1458                  TALER_MHD_reply_with_error (
   1459                    wc->rc->connection,
   1460                    MHD_HTTP_BAD_REQUEST,
   1461                    TALER_EC_EXCHANGE_GENERIC_CIPHER_MISMATCH,
   1462                    "cipher"));
   1463     return;
   1464   case WITHDRAW_ERROR_AGE_RESTRICTION_NOT_SUPPORTED_BY_DENOMINATION:
   1465     {
   1466       char msg[256];
   1467 
   1468       GNUNET_snprintf (msg,
   1469                        sizeof(msg),
   1470                        "denomination %s does not support age restriction",
   1471                        GNUNET_h2s (&wc->error.details.denom_h->hash));
   1472       finish_loop (wc,
   1473                    TALER_MHD_reply_with_error (
   1474                      wc->rc->connection,
   1475                      MHD_HTTP_NOT_FOUND,
   1476                      TALER_EC_EXCHANGE_GENERIC_DENOMINATION_KEY_UNKNOWN,
   1477                      msg));
   1478       return;
   1479     }
   1480   case WITHDRAW_ERROR_AGE_MASK_MISMATCH:
   1481     {
   1482       char msg[256];
   1483 
   1484       GNUNET_snprintf (msg,
   1485                        sizeof(msg),
   1486                        "age mask of denomination %s differs from that of the first denomination",
   1487                        GNUNET_h2s (&wc->error.details.denom_h->hash));
   1488       finish_loop (wc,
   1489                    TALER_MHD_reply_with_error (
   1490                      wc->rc->connection,
   1491                      MHD_HTTP_BAD_REQUEST,
   1492                      TALER_EC_EXCHANGE_WITHDRAW_AGE_MASK_MISMATCH,
   1493                      msg));
   1494       return;
   1495     }
   1496   case WITHDRAW_ERROR_MAXIMUM_AGE_TOO_LARGE:
   1497     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1498                 "Generating JSON response with code %d\n",
   1499                 (int) TALER_EC_EXCHANGE_WITHDRAW_MAXIMUM_AGE_TOO_LARGE);
   1500     finish_loop (wc,
   1501                  TALER_MHD_REPLY_JSON_PACK (
   1502                    wc->rc->connection,
   1503                    MHD_HTTP_CONFLICT,
   1504                    TALER_MHD_PACK_EC (
   1505                      TALER_EC_EXCHANGE_WITHDRAW_MAXIMUM_AGE_TOO_LARGE),
   1506                    GNUNET_JSON_pack_uint64 (
   1507                      "allowed_maximum_age",
   1508                      wc->error.details.maximum_age_too_large.max_allowed),
   1509                    GNUNET_JSON_pack_uint64 (
   1510                      "reserve_birthday",
   1511                      wc->error.details.maximum_age_too_large.birthday)));
   1512     return;
   1513   case WITHDRAW_ERROR_AGE_RESTRICTION_REQUIRED:
   1514     finish_loop (wc,
   1515                  TEH_RESPONSE_reply_reserve_age_restriction_required (
   1516                    wc->rc->connection,
   1517                    wc->error.details.age_restriction_required));
   1518     return;
   1519   case WITHDRAW_ERROR_AMOUNT_OVERFLOW:
   1520     finish_loop (wc,
   1521                  TALER_MHD_reply_with_error (
   1522                    wc->rc->connection,
   1523                    MHD_HTTP_BAD_REQUEST,
   1524                    TALER_EC_EXCHANGE_WITHDRAW_AMOUNT_OVERFLOW,
   1525                    "amount"));
   1526     return;
   1527   case WITHDRAW_ERROR_FEE_OVERFLOW:
   1528     finish_loop (wc,
   1529                  TALER_MHD_reply_with_error (
   1530                    wc->rc->connection,
   1531                    MHD_HTTP_BAD_REQUEST,
   1532                    TALER_EC_EXCHANGE_WITHDRAW_AMOUNT_OVERFLOW,
   1533                    "fee"));
   1534     return;
   1535   case WITHDRAW_ERROR_AMOUNT_PLUS_FEE_OVERFLOW:
   1536     finish_loop (wc,
   1537                  TALER_MHD_reply_with_error (
   1538                    wc->rc->connection,
   1539                    MHD_HTTP_INTERNAL_SERVER_ERROR,
   1540                    TALER_EC_EXCHANGE_WITHDRAW_AMOUNT_FEE_OVERFLOW,
   1541                    "amount+fee"));
   1542     return;
   1543   case WITHDRAW_ERROR_CONFIRMATION_SIGN:
   1544     finish_loop (wc,
   1545                  TALER_MHD_reply_with_ec (
   1546                    wc->rc->connection,
   1547                    wc->error.details.ec_confirmation_sign,
   1548                    NULL));
   1549     return;
   1550   case WITHDRAW_ERROR_INSUFFICIENT_FUNDS:
   1551     finish_loop (wc,
   1552                  TEH_RESPONSE_reply_reserve_insufficient_balance (
   1553                    wc->rc->connection,
   1554                    TALER_EC_EXCHANGE_WITHDRAW_INSUFFICIENT_FUNDS,
   1555                    &wc->error.details.insufficient_funds,
   1556                    &wc->request.withdraw.amount_with_fee,
   1557                    &wc->request.withdraw.reserve_pub));
   1558     return;
   1559   case WITHDRAW_ERROR_IDEMPOTENT_PLANCHET:
   1560     finish_loop (wc,
   1561                  TALER_MHD_reply_with_error (
   1562                    wc->rc->connection,
   1563                    MHD_HTTP_BAD_REQUEST,
   1564                    TALER_EC_EXCHANGE_WITHDRAW_IDEMPOTENT_PLANCHET,
   1565                    NULL));
   1566     return;
   1567   case WITHDRAW_ERROR_CS_NONCE_MISMATCH:
   1568     finish_loop (wc,
   1569                  TALER_MHD_reply_with_error (
   1570                    wc->rc->connection,
   1571                    MHD_HTTP_BAD_REQUEST,
   1572                    TALER_EC_GENERIC_PARAMETER_MALFORMED,
   1573                    "coin_evs: nonce"));
   1574     return;
   1575   case WITHDRAW_ERROR_NONCE_REUSE:
   1576     finish_loop (wc,
   1577                  TALER_MHD_reply_with_error (
   1578                    wc->rc->connection,
   1579                    MHD_HTTP_CONFLICT,
   1580                    TALER_EC_EXCHANGE_WITHDRAW_NONCE_REUSE,
   1581                    NULL));
   1582     return;
   1583   case WITHDRAW_ERROR_RESERVE_SIGNATURE_INVALID:
   1584     finish_loop (wc,
   1585                  TALER_MHD_reply_with_error (
   1586                    wc->rc->connection,
   1587                    MHD_HTTP_FORBIDDEN,
   1588                    TALER_EC_EXCHANGE_WITHDRAW_RESERVE_SIGNATURE_INVALID,
   1589                    NULL));
   1590     return;
   1591   case WITHDRAW_ERROR_LEGITIMIZATION_RESULT: {
   1592       finish_loop (
   1593         wc,
   1594         MHD_queue_response (wc->rc->connection,
   1595                             wc->error.details.legitimization_result.http_status,
   1596                             wc->error.details.legitimization_result.response));
   1597       return;
   1598     }
   1599   }
   1600   GNUNET_break (0);
   1601   finish_loop (wc,
   1602                TALER_MHD_reply_with_error (
   1603                  wc->rc->connection,
   1604                  MHD_HTTP_INTERNAL_SERVER_ERROR,
   1605                  TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE,
   1606                  "error phase without error"));
   1607 }
   1608 
   1609 
   1610 /**
   1611  * Initializes the new context for the incoming withdraw request
   1612  *
   1613  * @param[in,out] wc withdraw request context
   1614  * @param root json body of the request
   1615  */
   1616 static void
   1617 withdraw_phase_parse (
   1618   struct WithdrawContext *wc,
   1619   const json_t *root)
   1620 {
   1621   const json_t *j_denoms_h;
   1622   const json_t *j_coin_evs;
   1623   const char *cipher;
   1624   bool no_max_age;
   1625   struct GNUNET_JSON_Specification spec[] = {
   1626     GNUNET_JSON_spec_string ("cipher",
   1627                              &cipher),
   1628     GNUNET_JSON_spec_fixed_auto  ("reserve_pub",
   1629                                   &wc->request.withdraw.reserve_pub),
   1630     GNUNET_JSON_spec_array_const ("denoms_h",
   1631                                   &j_denoms_h),
   1632     GNUNET_JSON_spec_array_const ("coin_evs",
   1633                                   &j_coin_evs),
   1634     GNUNET_JSON_spec_mark_optional (
   1635       GNUNET_JSON_spec_uint16 ("max_age",
   1636                                &wc->request.withdraw.max_age),
   1637       &no_max_age),
   1638     GNUNET_JSON_spec_mark_optional (
   1639       GNUNET_JSON_spec_fixed_auto ("blinding_seed",
   1640                                    &wc->request.withdraw.blinding_seed),
   1641       &wc->request.withdraw.no_blinding_seed),
   1642     GNUNET_JSON_spec_fixed_auto ("reserve_sig",
   1643                                  &wc->request.withdraw.reserve_sig),
   1644     GNUNET_JSON_spec_end ()
   1645   };
   1646   enum GNUNET_GenericReturnValue res;
   1647 
   1648   res = TALER_MHD_parse_json_data (wc->rc->connection,
   1649                                    root,
   1650                                    spec);
   1651   if (GNUNET_YES != res)
   1652   {
   1653     GNUNET_break_op (0);
   1654     wc->phase = (GNUNET_SYSERR == res)
   1655       ? WITHDRAW_PHASE_RETURN_NO
   1656       : WITHDRAW_PHASE_RETURN_YES;
   1657     return;
   1658   }
   1659 
   1660   /* For now, we only support cipher "ED25519" for signatures by the reserve */
   1661   if (0 != strcmp ("ED25519",
   1662                    cipher))
   1663   {
   1664     GNUNET_break_op (0);
   1665     SET_ERROR_WITH_DETAIL (wc,
   1666                            WITHDRAW_ERROR_RESERVE_CIPHER_UNKNOWN,
   1667                            reserve_cipher_unknown,
   1668                            cipher);
   1669     return;
   1670   }
   1671 
   1672   wc->request.withdraw.age_proof_required = ! no_max_age;
   1673 
   1674   if (wc->request.withdraw.age_proof_required)
   1675   {
   1676     /* The age value MUST be on the beginning of an age group */
   1677     if (wc->request.withdraw.max_age !=
   1678         TALER_get_lowest_age (&TEH_age_restriction_mask,
   1679                               wc->request.withdraw.max_age))
   1680     {
   1681       GNUNET_break_op (0);
   1682       SET_ERROR_WITH_DETAIL (
   1683         wc,
   1684         WITHDRAW_ERROR_REQUEST_PARAMETER_MALFORMED,
   1685         request_parameter_malformed,
   1686         "max_age must be the lower edge of an age group");
   1687       return;
   1688     }
   1689   }
   1690 
   1691   /* validate array size */
   1692   {
   1693     size_t num_coins = json_array_size (j_denoms_h);
   1694     size_t array_size = json_array_size (j_coin_evs);
   1695     const char *error;
   1696 
   1697     GNUNET_static_assert (
   1698       TALER_MAX_COINS < INT_MAX / TALER_CNC_KAPPA);
   1699 
   1700 #define BAIL_IF(cond, msg) \
   1701         if ((cond)) { \
   1702           GNUNET_break_op (0); \
   1703           error = (msg); break; \
   1704         }
   1705 
   1706     do {
   1707       BAIL_IF (0 == num_coins,
   1708                "denoms_h must not be empty")
   1709 
   1710       /**
   1711        * The wallet had committed to more than the maximum coins allowed, the
   1712        * reserve has been charged, but now the user can not withdraw any money
   1713        * from it.  Note that the user can't get their money back in this case!
   1714        */
   1715       BAIL_IF (num_coins > TALER_MAX_COINS,
   1716                "maximum number of coins that can be withdrawn has been exceeded")
   1717 
   1718       BAIL_IF ((! wc->request.withdraw.age_proof_required) &&
   1719                (num_coins != array_size),
   1720                "denoms_h and coin_evs must be arrays of the same size")
   1721 
   1722       BAIL_IF (wc->request.withdraw.age_proof_required &&
   1723                ((TALER_CNC_KAPPA * num_coins) != array_size),
   1724                "coin_evs must be an array of length "
   1725                TALER_CNC_KAPPA_STR
   1726                "*len(denoms_h)")
   1727 
   1728       wc->request.withdraw.num_coins = num_coins;
   1729       wc->request.num_planchets = array_size;
   1730       error = NULL;
   1731 
   1732     } while (0);
   1733 #undef BAIL_IF
   1734 
   1735     if (NULL != error)
   1736     {
   1737       SET_ERROR_WITH_DETAIL (wc,
   1738                              WITHDRAW_ERROR_REQUEST_PARAMETER_MALFORMED,
   1739                              request_parameter_malformed,
   1740                              error);
   1741       return;
   1742     }
   1743   }
   1744   /* extract the denomination hashes */
   1745   {
   1746     size_t idx;
   1747     json_t *value;
   1748 
   1749     wc->request.denoms_h
   1750       = GNUNET_new_array (wc->request.withdraw.num_coins,
   1751                           struct TALER_DenominationHashP);
   1752 
   1753     json_array_foreach (j_denoms_h, idx, value) {
   1754       struct GNUNET_JSON_Specification ispec[] = {
   1755         GNUNET_JSON_spec_fixed_auto (NULL,
   1756                                      &wc->request.denoms_h[idx]),
   1757         GNUNET_JSON_spec_end ()
   1758       };
   1759 
   1760       res = TALER_MHD_parse_json_data (wc->rc->connection,
   1761                                        value,
   1762                                        ispec);
   1763       if (GNUNET_YES != res)
   1764       {
   1765         GNUNET_break_op (0);
   1766         wc->phase = (GNUNET_SYSERR == res)
   1767           ? WITHDRAW_PHASE_RETURN_NO
   1768           : WITHDRAW_PHASE_RETURN_YES;
   1769         return;
   1770       }
   1771     }
   1772   }
   1773   /* Parse the blinded coin envelopes */
   1774   {
   1775     json_t *j_cev;
   1776     size_t idx;
   1777 
   1778     wc->request.planchets =
   1779       GNUNET_new_array (wc->request.num_planchets,
   1780                         struct  TALER_BlindedPlanchet);
   1781     json_array_foreach (j_coin_evs, idx, j_cev)
   1782     {
   1783       /* Now parse the individual envelopes and calculate the hash of
   1784        * the commitment along the way. */
   1785       struct GNUNET_JSON_Specification kspec[] = {
   1786         TALER_JSON_spec_blinded_planchet (NULL,
   1787                                           &wc->request.planchets[idx]),
   1788         GNUNET_JSON_spec_end ()
   1789       };
   1790 
   1791       res = TALER_MHD_parse_json_data (wc->rc->connection,
   1792                                        j_cev,
   1793                                        kspec);
   1794       if (GNUNET_OK != res)
   1795       {
   1796         GNUNET_break_op (0);
   1797         wc->phase = (GNUNET_SYSERR == res)
   1798           ? WITHDRAW_PHASE_RETURN_NO
   1799           : WITHDRAW_PHASE_RETURN_YES;
   1800         return;
   1801       }
   1802 
   1803       /* Check for duplicate planchets. Technically a bug on
   1804        * the client side that is harmless for us, but still
   1805        * not allowed per protocol */
   1806       for (size_t i = 0; i < idx; i++)
   1807       {
   1808         if (0 ==
   1809             TALER_blinded_planchet_cmp (
   1810               &wc->request.planchets[idx],
   1811               &wc->request.planchets[i]))
   1812         {
   1813           GNUNET_break_op (0);
   1814           SET_ERROR (wc,
   1815                      WITHDRAW_ERROR_IDEMPOTENT_PLANCHET);
   1816           return;
   1817         }
   1818       }       /* end duplicate check */
   1819     }       /* json_array_foreach over j_coin_evs */
   1820   }       /* scope of j_kappa_planchets, idx */
   1821 
   1822   /* Save the hash of the batch of planchets.  Needed for idempotency
   1823      checks. */
   1824   if (! wc->request.withdraw.age_proof_required)
   1825   {
   1826     TALER_wallet_blinded_planchets_hash (
   1827       wc->request.withdraw.num_coins,
   1828       wc->request.planchets,
   1829       wc->request.denoms_h,
   1830       &wc->request.withdraw.planchets_h);
   1831   }
   1832   else
   1833   {
   1834     struct GNUNET_HashContext *ctx;
   1835 
   1836     /**
   1837      * The age-proof-required case is a bit more involved,
   1838      * because we need to calculate and remember kappa hashes
   1839      * for each batch of coins.
   1840      */
   1841     ctx = GNUNET_CRYPTO_hash_context_start ();
   1842     GNUNET_assert (NULL != ctx);
   1843 
   1844     for (uint8_t k = 0; k < TALER_CNC_KAPPA; k++)
   1845     {
   1846       size_t off = k * wc->request.withdraw.num_coins;
   1847 
   1848       TALER_wallet_blinded_planchets_hash (
   1849         wc->request.withdraw.num_coins,
   1850         &wc->request.planchets[off],
   1851         wc->request.denoms_h,
   1852         &wc->request.kappa_planchets_h[k]);
   1853       GNUNET_CRYPTO_hash_context_read (
   1854         ctx,
   1855         &wc->request.kappa_planchets_h[k],
   1856         sizeof(wc->request.kappa_planchets_h[k]));
   1857     }
   1858     GNUNET_CRYPTO_hash_context_finish (
   1859       ctx,
   1860       &wc->request.withdraw.planchets_h.hash);
   1861   }
   1862   wc->phase = WITHDRAW_PHASE_CHECK_KEYS;
   1863 }
   1864 
   1865 
   1866 enum MHD_Result
   1867 TEH_handler_withdraw (
   1868   struct TEH_RequestContext *rc,
   1869   const json_t *root,
   1870   const char *const args[0])
   1871 {
   1872   struct WithdrawContext *wc = rc->rh_ctx;
   1873 
   1874   (void) args;
   1875   if (NULL == wc)
   1876   {
   1877     wc = GNUNET_new (struct WithdrawContext);
   1878     rc->rh_ctx = wc;
   1879     rc->rh_cleaner = &clean_withdraw_rc;
   1880     wc->rc = rc;
   1881     wc->now = GNUNET_TIME_timestamp_get ();
   1882   }
   1883   while (true)
   1884   {
   1885     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1886                 "withdrawal%s processing in phase %d\n",
   1887                 wc->request.withdraw.age_proof_required
   1888                      ? " (with required age proof)"
   1889                      : "",
   1890                 wc->phase);
   1891     switch (wc->phase)
   1892     {
   1893     case WITHDRAW_PHASE_PARSE:
   1894       withdraw_phase_parse (wc,
   1895                             root);
   1896       break;
   1897     case WITHDRAW_PHASE_CHECK_KEYS:
   1898       phase_check_keys (wc);
   1899       break;
   1900     case WITHDRAW_PHASE_CHECK_RESERVE_SIGNATURE:
   1901       phase_check_reserve_signature (wc);
   1902       break;
   1903     case WITHDRAW_PHASE_RUN_LEGI_CHECK:
   1904       phase_run_legi_check (wc);
   1905       break;
   1906     case WITHDRAW_PHASE_SUSPENDED:
   1907       return MHD_YES;
   1908     case WITHDRAW_PHASE_CHECK_KYC_RESULT:
   1909       phase_check_kyc_result (wc);
   1910       break;
   1911     case WITHDRAW_PHASE_PREPARE_TRANSACTION:
   1912       phase_prepare_transaction (wc);
   1913       break;
   1914     case WITHDRAW_PHASE_RUN_TRANSACTION:
   1915       phase_run_transaction (wc);
   1916       break;
   1917     case WITHDRAW_PHASE_GENERATE_REPLY_SUCCESS:
   1918       phase_generate_reply_success (wc);
   1919       break;
   1920     case WITHDRAW_PHASE_GENERATE_REPLY_ERROR:
   1921       phase_generate_reply_error (wc);
   1922       break;
   1923     case WITHDRAW_PHASE_RETURN_YES:
   1924       return MHD_YES;
   1925     case WITHDRAW_PHASE_RETURN_NO:
   1926       return MHD_NO;
   1927     }
   1928   }
   1929 }