/*
  This file is part of TALER
  Copyright (C) 2023-2026 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_post-withdraw.c
 * @brief Implementation of /withdraw requests
 * @author Özgür Kesim
 */
#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/taler_curl_lib.h"
#include "taler/taler_error_codes.h"
#include "taler/taler_json_lib.h"
#include "exchange_api_common.h"
#include "exchange_api_handle.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"
#include "taler/taler_util.h"


/**
 * A /withdraw request-handle for calls with pre-blinded planchets.
 * Returned by TALER_EXCHANGE_post_withdraw_blinded_create.
 */
struct TALER_EXCHANGE_PostWithdrawBlindedHandle
{

  /**
   * 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 hash of all the planchets
   */
  struct TALER_HashBlindedPlanchetsP planchets_h;

  /**
   * Seed used for the derival of blinding factors for denominations
   * with Clause-Schnorr cipher.
   */
  const struct TALER_BlindingMasterSeedP *blinding_seed;

  /**
   * Total amount requested (without fee).
   */
  struct TALER_Amount amount;

  /**
   * Total withdraw fee
   */
  struct TALER_Amount fee;

  /**
   * Is this call for age-restricted coins, with age proof?
   */
  bool with_age_proof;

  /**
   * If @e with_age_proof is true or @max_age is > 0,
   * the age mask to use, extracted from the denominations.
   * MUST be the same for all denominations.
   */
  struct TALER_AgeMask age_mask;

  /**
   * The maximum age to commit to.  If @e with_age_proof
   * is true, the client will need to proof the correct setting
   * of age-restriction on the coins via an additional call
   * to /reveal-withdraw.
   */
  uint8_t max_age;

  /**
   * If @e with_age_proof is true, the hash of all the selected planchets
   */
  struct TALER_HashBlindedPlanchetsP selected_h;

  /**
   * Length of the either the @e blinded.input or
   * the @e blinded.with_age_proof_input array,
   * depending on @e with_age_proof.
   */
  size_t num_input;

  union
  {
    /**
     * The blinded planchet input candidates for age-restricted coins
     * for the call to /withdraw
     */
    const struct
    TALER_EXCHANGE_WithdrawBlindedAgeRestrictedCoinInput *with_age_proof_input;

    /**
     * The blinded planchet input for the call to /withdraw,
     * for age-unrestricted coins.
     */
    const struct TALER_EXCHANGE_WithdrawBlindedCoinInput *input;

  } blinded;

  /**
   * 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 withdraw response results.
   */
  TALER_EXCHANGE_PostWithdrawBlindedCallback callback;

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


/**
 * We got a 200 OK response for the /withdraw operation.
 * Extract the signatures and return them to the caller.
 *
 * @param wbh operation handle
 * @param j_response reply from the exchange
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors
 */
static enum GNUNET_GenericReturnValue
withdraw_blinded_ok (
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *wbh,
  const json_t *j_response)
{
  struct TALER_EXCHANGE_PostWithdrawBlindedResponse response = {
    .hr.reply = j_response,
    .hr.http_status = MHD_HTTP_OK,
  };
  const json_t *j_sigs;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("ev_sigs",
                                  &j_sigs),
    GNUNET_JSON_spec_end ()
  };

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

  if (wbh->num_input != json_array_size (j_sigs))
  {
    /* Number of coins generated does not match our expectation */
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  {
    struct TALER_BlindedDenominationSignature denoms_sig[wbh->num_input];

    memset (denoms_sig,
            0,
            sizeof(denoms_sig));

    /* Reconstruct the coins and unblind the signatures */
    {
      json_t *j_sig;
      size_t i;

      json_array_foreach (j_sigs, i, j_sig)
      {
        struct GNUNET_JSON_Specification ispec[] = {
          TALER_JSON_spec_blinded_denom_sig (NULL,
                                             &denoms_sig[i]),
          GNUNET_JSON_spec_end ()
        };

        if (GNUNET_OK !=
            GNUNET_JSON_parse (j_sig,
                               ispec,
                               NULL, NULL))
        {
          GNUNET_break_op (0);
          for (size_t k = 0; k < i; k++)
            TALER_blinded_denom_sig_free (&denoms_sig[k]);
          return GNUNET_SYSERR;
        }
      }
    }

    response.details.ok.num_sigs = wbh->num_input;
    response.details.ok.blinded_denom_sigs = denoms_sig;
    response.details.ok.planchets_h = wbh->planchets_h;
    wbh->callback (
      wbh->callback_cls,
      &response);
    /* Make sure the callback isn't called again */
    wbh->callback = NULL;
    /* Free resources */
    for (size_t i = 0; i < wbh->num_input; i++)
      TALER_blinded_denom_sig_free (&denoms_sig[i]);
  }

  return GNUNET_OK;
}


/**
 * We got a 201 CREATED response for the /withdraw operation.
 * Extract the noreveal_index and return it to the caller.
 *
 * @param wbh operation handle
 * @param j_response reply from the exchange
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on errors
 */
static enum GNUNET_GenericReturnValue
withdraw_blinded_created (
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *wbh,
  const json_t *j_response)
{
  struct TALER_EXCHANGE_PostWithdrawBlindedResponse response = {
    .hr.reply = j_response,
    .hr.http_status = MHD_HTTP_CREATED,
    .details.created.planchets_h = wbh->planchets_h,
    .details.created.num_coins = wbh->num_input,
  };
  struct TALER_ExchangeSignatureP exchange_sig;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_uint8 ("noreveal_index",
                            &response.details.created.noreveal_index),
    GNUNET_JSON_spec_fixed_auto ("exchange_sig",
                                 &exchange_sig),
    GNUNET_JSON_spec_fixed_auto ("exchange_pub",
                                 &response.details.created.exchange_pub),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK!=
      GNUNET_JSON_parse (j_response,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (response.details.created.noreveal_index >= TALER_CNC_KAPPA)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_EXCHANGE_test_signing_key (
        wbh->keys,
        &response.details.created.exchange_pub))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      TALER_exchange_online_withdraw_age_confirmation_verify (
        &wbh->planchets_h,
        response.details.created.noreveal_index,
        &response.details.created.exchange_pub,
        &exchange_sig))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  wbh->callback (wbh->callback_cls,
                 &response);
  /* make sure the callback isn't called again */
  wbh->callback = NULL;

  return GNUNET_OK;
}


/**
 * Function called when we're done processing the
 * HTTP /withdraw request.
 *
 * @param cls the `struct TALER_EXCHANGE_PostWithdrawBlindedHandle`
 * @param response_code The HTTP response code
 * @param response response data
 */
static void
handle_withdraw_blinded_finished (
  void *cls,
  long response_code,
  const void *response)
{
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *wbh = cls;
  const json_t *j_response = response;
  struct TALER_EXCHANGE_PostWithdrawBlindedResponse wbr = {
    .hr.reply = j_response,
    .hr.http_status = (unsigned int) response_code
  };

  wbh->job = NULL;
  switch (response_code)
  {
  case 0:
    wbr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      if (GNUNET_OK !=
          withdraw_blinded_ok (
            wbh,
            j_response))
      {
        GNUNET_break_op (0);
        wbr.hr.http_status = 0;
        wbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      GNUNET_assert (NULL == wbh->callback);
      TALER_EXCHANGE_post_withdraw_blinded_cancel (wbh);
      return;
    }
  case MHD_HTTP_CREATED:
    if (GNUNET_OK !=
        withdraw_blinded_created (
          wbh,
          j_response))
    {
      GNUNET_break_op (0);
      wbr.hr.http_status = 0;
      wbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    GNUNET_assert (NULL == wbh->callback);
    TALER_EXCHANGE_post_withdraw_blinded_cancel (wbh);
    return;
  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 */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.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 */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.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. */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_CONFLICT:
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    if (TALER_EC_EXCHANGE_GENERIC_INSUFFICIENT_FUNDS ==
        wbr.hr.ec)
    {
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_amount_any (
          "balance",
          &wbr.details.conflict.details.generic_insufficient_funds.balance),
        TALER_JSON_spec_amount_any (
          "requested_amount",
          &wbr.details.conflict.details.generic_insufficient_funds.
          requested_amount),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j_response,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        wbr.hr.http_status = 0;
        wbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
    }
    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 */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_PRECONDITION_FAILED:
    /* could happen if we were too early and the denomination
       is not yet available */
    /* Note: one might want to check the "Date" header to
       see if our clock is very far off */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    if (GNUNET_OK !=
        TALER_EXCHANGE_parse_451 (&wbr.details.unavailable_for_legal_reasons,
                                  j_response))
    {
      GNUNET_break_op (0);
      wbr.hr.http_status = 0;
      wbr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_NOT_IMPLEMENTED:
    /* Server does not implement a feature (usually the cipher) */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_BAD_GATEWAY:
    /* Server could not talk to another component, usually this
       indicates a problem with the secmod helper */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  case MHD_HTTP_SERVICE_UNAVAILABLE:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    break;
  default:
    /* unexpected response code */
    GNUNET_break_op (0);
    wbr.hr.ec = TALER_JSON_get_error_code (j_response);
    wbr.hr.hint = TALER_JSON_get_error_hint (j_response);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange withdraw\n",
                (unsigned int) response_code,
                (int) wbr.hr.ec);
    break;
  }
  wbh->callback (wbh->callback_cls,
                 &wbr);
  TALER_EXCHANGE_post_withdraw_blinded_cancel (wbh);
}


struct TALER_EXCHANGE_PostWithdrawBlindedHandle *
TALER_EXCHANGE_post_withdraw_blinded_create (
  struct GNUNET_CURL_Context *curl_ctx,
  struct TALER_EXCHANGE_Keys *keys,
  const char *exchange_url,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  const struct TALER_BlindingMasterSeedP *blinding_seed,
  size_t num_input,
  const struct TALER_EXCHANGE_WithdrawBlindedCoinInput *blinded_input)
{
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *wbh =
    GNUNET_new (struct TALER_EXCHANGE_PostWithdrawBlindedHandle);

  wbh->keys = TALER_EXCHANGE_keys_incref (keys);
  wbh->curl_ctx = curl_ctx;
  wbh->reserve_priv = reserve_priv;
  wbh->request_url = TALER_url_join (exchange_url,
                                     "withdraw",
                                     NULL);
  GNUNET_CRYPTO_eddsa_key_get_public (
    &wbh->reserve_priv->eddsa_priv,
    &wbh->reserve_pub.eddsa_pub);
  wbh->num_input = num_input;
  wbh->blinded.input = blinded_input;
  wbh->blinding_seed = blinding_seed;

  return wbh;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_post_withdraw_blinded_set_options_ (
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *pwbh,
  unsigned int num_options,
  const struct TALER_EXCHANGE_PostWithdrawBlindedOptionValue options[])
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_PostWithdrawBlindedOptionValue *opt =
      &options[i];
    switch (opt->option)
    {
    case TALER_EXCHANGE_POST_WITHDRAW_BLINDED_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_POST_WITHDRAW_BLINDED_OPTION_WITH_AGE_PROOF:
      pwbh->with_age_proof = true;
      pwbh->max_age = opt->details.with_age_proof.max_age;
      pwbh->blinded.with_age_proof_input = opt->details.with_age_proof.input;
      break;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_withdraw_blinded_start (
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *pwbh,
  TALER_EXCHANGE_PostWithdrawBlindedCallback cb,
  TALER_EXCHANGE_POST_WITHDRAW_BLINDED_RESULT_CLOSURE *cb_cls)
{
  json_t *j_denoms = NULL;
  json_t *j_planchets = NULL;
  json_t *j_request_body = NULL;
  CURL *curlh = NULL;
  struct GNUNET_HashContext *coins_hctx = NULL;
  struct TALER_BlindedCoinHashP bch;

  pwbh->callback = cb;
  pwbh->callback_cls = cb_cls;
#define FAIL_IF(cond) \
        do { \
          if ((cond)) \
          { \
            GNUNET_break (! (cond)); \
            goto ERROR; \
          } \
        } while (0)

  GNUNET_assert (0 < pwbh->num_input);

  FAIL_IF (GNUNET_OK !=
           TALER_amount_set_zero (pwbh->keys->currency,
                                  &pwbh->amount));
  FAIL_IF (GNUNET_OK !=
           TALER_amount_set_zero (pwbh->keys->currency,
                                  &pwbh->fee));

  /* Accumulate total value with fees */
  for (size_t i = 0; i < pwbh->num_input; i++)
  {
    const struct TALER_EXCHANGE_DenomPublicKey *dpub =
      pwbh->with_age_proof ?
      pwbh->blinded.with_age_proof_input[i].denom_pub :
      pwbh->blinded.input[i].denom_pub;

    FAIL_IF (0 >
             TALER_amount_add (&pwbh->amount,
                               &pwbh->amount,
                               &dpub->value));
    FAIL_IF (0 >
             TALER_amount_add (&pwbh->fee,
                               &pwbh->fee,
                               &dpub->fees.withdraw));

    if (GNUNET_CRYPTO_BSA_CS ==
        dpub->key.bsign_pub_key->cipher)
      GNUNET_assert (NULL != pwbh->blinding_seed);

  }

  if (pwbh->with_age_proof || pwbh->max_age > 0)
  {
    pwbh->age_mask =
      pwbh->blinded.with_age_proof_input[0].denom_pub->key.age_mask;

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

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

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

  for (size_t i  = 0; i< pwbh->num_input; i++)
  {
    /* Build the denomination array */
    const struct TALER_EXCHANGE_DenomPublicKey *denom_pub =
      pwbh->with_age_proof ?
      pwbh->blinded.with_age_proof_input[i].denom_pub :
      pwbh->blinded.input[i].denom_pub;
    const struct TALER_DenominationHashP *denom_h = &denom_pub->h_key;
    json_t *jdenom;

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

    jdenom = GNUNET_JSON_from_data_auto (denom_h);
    FAIL_IF (NULL == jdenom);
    FAIL_IF (0 > json_array_append_new (j_denoms,
                                        jdenom));
  }


  /* Build the planchet array and calculate the hash over all planchets. */
  if (! pwbh->with_age_proof)
  {
    for (size_t i  = 0; i< pwbh->num_input; i++)
    {
      const struct TALER_PlanchetDetail *planchet =
        &pwbh->blinded.input[i].planchet_details;
      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_planchets,
                                          jc));

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

      GNUNET_CRYPTO_hash_context_read (coins_hctx,
                                       &bch,
                                       sizeof(bch));
    }
  }
  else
  { /* Age restricted case with required age-proof. */

    /**
     * We collect the run of all coin candidates for the same γ index
     * first, then γ+1 etc.
     */
    for (size_t k = 0; k < TALER_CNC_KAPPA; k++)
    {
      struct GNUNET_HashContext *batch_ctx;
      struct TALER_BlindedCoinHashP batch_h;

      batch_ctx = GNUNET_CRYPTO_hash_context_start ();
      FAIL_IF (NULL == batch_ctx);

      for (size_t i  = 0; i< pwbh->num_input; i++)
      {
        const struct TALER_PlanchetDetail *planchet =
          &pwbh->blinded.with_age_proof_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_planchets,
                   jc));

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

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

      GNUNET_CRYPTO_hash_context_finish (
        batch_ctx,
        &batch_h.hash);
      GNUNET_CRYPTO_hash_context_read (
        coins_hctx,
        &batch_h,
        sizeof(batch_h));
    }
  }

  GNUNET_CRYPTO_hash_context_finish (
    coins_hctx,
    &pwbh->planchets_h.hash);
  coins_hctx = NULL;

  TALER_wallet_withdraw_sign (
    &pwbh->amount,
    &pwbh->fee,
    &pwbh->planchets_h,
    pwbh->blinding_seed,
    pwbh->with_age_proof ? &pwbh->age_mask: NULL,
    pwbh->with_age_proof ? pwbh->max_age : 0,
    pwbh->reserve_priv,
    &pwbh->reserve_sig);

  /* Initiate the POST-request */
  j_request_body = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("cipher",
                             "ED25519"),
    GNUNET_JSON_pack_data_auto ("reserve_pub",
                                &pwbh->reserve_pub),
    GNUNET_JSON_pack_array_steal ("denoms_h",
                                  j_denoms),
    GNUNET_JSON_pack_array_steal ("coin_evs",
                                  j_planchets),
    GNUNET_JSON_pack_allow_null (
      pwbh->with_age_proof
      ? GNUNET_JSON_pack_uint64 ("max_age",
                                 pwbh->max_age)
      : GNUNET_JSON_pack_string ("max_age",
                                 NULL) ),
    GNUNET_JSON_pack_data_auto ("reserve_sig",
                                &pwbh->reserve_sig));
  FAIL_IF (NULL == j_request_body);

  if (NULL != pwbh->blinding_seed)
  {
    json_t *j_seed = GNUNET_JSON_PACK (
      GNUNET_JSON_pack_data_auto ("blinding_seed",
                                  pwbh->blinding_seed));
    GNUNET_assert (NULL != j_seed);
    GNUNET_assert (0 ==
                   json_object_update_new (
                     j_request_body,
                     j_seed));
  }

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

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

  return TALER_EC_NONE;

ERROR:
  if (NULL != coins_hctx)
    GNUNET_CRYPTO_hash_context_abort (coins_hctx);
  if (NULL != j_denoms)
    json_decref (j_denoms);
  if (NULL != j_planchets)
    json_decref (j_planchets);
  if (NULL != j_request_body)
    json_decref (j_request_body);
  if (NULL != curlh)
    curl_easy_cleanup (curlh);
  return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
#undef FAIL_IF
}


void
TALER_EXCHANGE_post_withdraw_blinded_cancel (
  struct TALER_EXCHANGE_PostWithdrawBlindedHandle *pwbh)
{
  if (NULL == pwbh)
    return;
  if (NULL != pwbh->job)
  {
    GNUNET_CURL_job_cancel (pwbh->job);
    pwbh->job = NULL;
  }
  GNUNET_free (pwbh->request_url);
  TALER_EXCHANGE_keys_decref (pwbh->keys);
  TALER_curl_easy_post_finished (&pwbh->post_ctx);
  GNUNET_free (pwbh);
}


/* exchange_api_post-withdraw_blinded.c */
