/*
  This file is part of TALER
  Copyright (C) 2014-2026 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file include/taler/exchange/post-withdraw.h
 * @brief C interface for POST /withdraw
 * @author Christian Grothoff
 */
#ifndef _TALER_EXCHANGE__POST_WITHDRAW_H
#define _TALER_EXCHANGE__POST_WITHDRAW_H

#include <taler/exchange/common.h>
#include <taler/exchange/get-keys.h>


/**
 * All the details about a coin that are generated during withdrawal and
 * that may be needed for future operations on the coin.
 */
struct TALER_EXCHANGE_WithdrawCoinPrivateDetails
{
  /**
   * The seed that the various secrets were derived from
   */
  struct TALER_PlanchetMasterSecretP secret;

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

  /**
   * Public key of the coin.
   */
  struct TALER_CoinSpendPublicKeyP coin_pub;

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

  /**
   * Value used to blind the key for the signature.
   * Needed for recoup operations.
   */
  union GNUNET_CRYPTO_BlindingSecretP blinding_key;

  /**
   * The age commitment, proof for the coin, derived from the
   * Master secret and maximum age in the originating request.
   * Only relevant for denominations with age-restriction support.
   */
  struct TALER_AgeCommitmentProof age_commitment_proof;

  /**
   * The hash of the age commitment.
   * Only relevant for denominations with age-restriction support.
   */
  struct TALER_AgeCommitmentHashP h_age_commitment;

  /**
   * Values contributed from the exchange during the
   * withdraw protocol.
   */
  struct TALER_ExchangeBlindingValues blinding_values;

  /**
   * The planchet constructed
   */
  struct TALER_PlanchetDetail planchet;

  /**
   * Signature over the coin.
   */
  struct TALER_DenominationSignature denom_sig;

};


/**
 * Details from an #MHD_HTTP_CREATED response to POST /withdraw,
 * indicating age-restricted withdrawal requiring a /reveal-withdraw step.
 */
struct TALER_EXCHANGE_WithdrawCreated
{
  /**
   * Index that should not be revealed during the reveal-withdraw
   * phase.
   */
  uint8_t noreveal_index;

  /**
   * The commitment of the withdraw request, needed for the
   * subsequent call to /reveal-withdraw and later calls to /recoup
   */
  struct TALER_HashBlindedPlanchetsP planchets_h;

  /**
   * The hash of the selected batch of blinded coin envelopes.
   */
  struct TALER_HashBlindedPlanchetsP selected_h;

  /**
   * The number of elements in @e coins, each referring to
   * TALER_CNC_KAPPA elements
   */
  size_t num_coins;

  /**
   * The computed details of the non-revealed @e num_coins coins to keep.
   */
  const struct TALER_EXCHANGE_WithdrawCoinPrivateDetails *coin_details;

  /**
   * Key used by the exchange to sign the response.
   */
  struct TALER_ExchangePublicKeyP exchange_pub;

  /**
   * The #TALER_CNC_KAPPA seeds that were used per batch of coin candidates
   */
  struct TALER_KappaWithdrawMasterSeedP kappa_seed;

};


/* *** High-level withdraw (with automatic blinding) *** */


/**
 * Handle for an operation to POST /withdraw (high-level variant).
 */
struct TALER_EXCHANGE_PostWithdrawHandle;


/**
 * Possible options we can set for the POST /withdraw request.
 */
enum TALER_EXCHANGE_PostWithdrawOption
{
  /**
   * End of list of options.
   */
  TALER_EXCHANGE_POST_WITHDRAW_OPTION_END = 0,

  /**
   * Upgrade the withdraw to an age-proof withdrawal, requiring an
   * additional call to POST /reveal-withdraw.
   * The @e details.max_age field gives the maximum age to (provably) commit to.
   */
  TALER_EXCHANGE_POST_WITHDRAW_OPTION_WITH_AGE_PROOF,

  /**
   * Provide an explicit blinding seed for CS denominations, overriding
   * the default derivation from the master seed.
   * Primarily intended for testing.
   * The @e details.blinding_seed field provides the seed.
   */
  TALER_EXCHANGE_POST_WITHDRAW_OPTION_BLINDING_SEED

};


/**
 * Value for an option we can set for the POST /withdraw request.
 */
struct TALER_EXCHANGE_PostWithdrawOptionValue
{
  /**
   * Type of the option being set.
   */
  enum TALER_EXCHANGE_PostWithdrawOption option;

  /**
   * Specific option value.
   */
  union
  {
    /**
     * Value if @e option is
     * #TALER_EXCHANGE_POST_WITHDRAW_OPTION_WITH_AGE_PROOF.
     */
    uint8_t max_age;

    /**
     * Value if @e option is
     * #TALER_EXCHANGE_POST_WITHDRAW_OPTION_BLINDING_SEED.
     */
    struct TALER_BlindingMasterSeedP blinding_seed;

  } details;

};


/**
 * Set up POST /withdraw operation (high-level variant, with automatic
 * blinding/unblinding).
 * Note that you must explicitly start the operation after setup.
 *
 * This API is typically used by a wallet.  Note that to ensure that
 * no money is lost in case of hardware failures, the provided
 * arguments should be committed to persistent storage
 * prior to calling this function.
 *
 * Note that a client can opaquely set a maximum age on the coins
 * (if the denominations do support it), that remains opaque to the exchange.
 * Only when the corresponding reserve has a birthday associated with it, the
 * exchange might require a _proof_ for the correct age-restriction to be set.
 * In that case, the exchange will respond with 409 and the client will need
 * to use the WITH_AGE_PROOF option instead.
 *
 * @param curl_ctx The curl context
 * @param exchange_url The base url of the exchange
 * @param keys The denomination keys from the exchange
 * @param reserve_priv The private key to the reserve
 * @param num_coins Number of coins to withdraw in a batch
 * @param denoms_pub Array of @e num_coins of denominations of the coins to withdraw
 * @param seed seed from which @e num_coins secrets for each coin are derived from
 * @param opaque_max_age The age to commit to opaquely; if not zero, the denominations MUST support age restriction
 * @return handle to operation, NULL on error
 */
struct TALER_EXCHANGE_PostWithdrawHandle *
TALER_EXCHANGE_post_withdraw_create (
  struct GNUNET_CURL_Context *curl_ctx,
  const char *exchange_url,
  struct TALER_EXCHANGE_Keys *keys,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  size_t num_coins,
  const struct TALER_EXCHANGE_DenomPublicKey denoms_pub[static num_coins],
  const struct TALER_WithdrawMasterSeedP *seed,
  uint8_t opaque_max_age);


/**
 * Terminate the list of options.
 *
 * @return the terminating object
 */
#define TALER_EXCHANGE_post_withdraw_option_end_()                 \
        (const struct TALER_EXCHANGE_PostWithdrawOptionValue)      \
        {                                                          \
          .option = TALER_EXCHANGE_POST_WITHDRAW_OPTION_END        \
        }

/**
 * Upgrade the withdraw to an age-proof withdrawal.
 *
 * @param age the maximum age to commit to
 * @return representation of the option
 */
#define TALER_EXCHANGE_post_withdraw_option_with_age_proof(age)               \
        (const struct TALER_EXCHANGE_PostWithdrawOptionValue)                 \
        {                                                                     \
          .option = TALER_EXCHANGE_POST_WITHDRAW_OPTION_WITH_AGE_PROOF,      \
          .details.max_age = (age)                                            \
        }

/**
 * Set an explicit blinding seed for CS denominations.
 * Primarily for testing purposes.
 *
 * @param s pointer to the blinding seed
 * @return representation of the option
 */
#define TALER_EXCHANGE_post_withdraw_option_blinding_seed(s)                  \
        (const struct TALER_EXCHANGE_PostWithdrawOptionValue)                 \
        {                                                                     \
          .option = TALER_EXCHANGE_POST_WITHDRAW_OPTION_BLINDING_SEED,       \
          .details.blinding_seed = *(s)                                       \
        }


/**
 * Set the requested options for the operation.
 *
 * If any option fails, other options may or may not be applied.
 *
 * @param pwh the request to set the options for
 * @param num_options length of the @a options array
 * @param options an array of options
 * @return #GNUNET_OK on success,
 *         #GNUNET_NO on failure,
 *         #GNUNET_SYSERR on internal error
 */
enum GNUNET_GenericReturnValue
TALER_EXCHANGE_post_withdraw_set_options_ (
  struct TALER_EXCHANGE_PostWithdrawHandle *pwh,
  unsigned int num_options,
  const struct TALER_EXCHANGE_PostWithdrawOptionValue options[]);


/**
 * Set the requested options for the operation.
 *
 * If any option fails, other options may or may not be applied.
 *
 * @param pwh the request to set the options for
 * @param ... the list of the options, each created by a
 *            TALER_EXCHANGE_post_withdraw_option_NAME(VALUE) macro
 * @return #GNUNET_OK on success,
 *         #GNUNET_NO on failure,
 *         #GNUNET_SYSERR on internal error
 */
#define TALER_EXCHANGE_post_withdraw_set_options(pwh,...)              \
        TALER_EXCHANGE_post_withdraw_set_options_ (                    \
          pwh,                                                         \
          TALER_EXCHANGE_COMMON_OPTIONS_ARRAY_MAX_SIZE,                \
          ((const struct TALER_EXCHANGE_PostWithdrawOptionValue[])     \
           {__VA_ARGS__,                                               \
            TALER_EXCHANGE_post_withdraw_option_end_ ()}               \
          ))


/**
 * Response from a POST /withdraw request (high-level variant).
 */
struct TALER_EXCHANGE_PostWithdrawResponse
{
  /**
   * HTTP response data.
   */
  struct TALER_EXCHANGE_HttpResponse hr;

  /**
   * Details about the response
   */
  union
  {
    /**
     * Details if the status is #MHD_HTTP_OK
     */
    struct
    {
      /**
       * Number of signatures returned.
       */
      unsigned int num_sigs;

      /**
       * The computed details of the @e num_sigs coins to keep,
       * including the denomination-signatures in their @e .denom_sig field.
       */
      const struct TALER_EXCHANGE_WithdrawCoinPrivateDetails *coin_details;

      /**
       * The commitment of the withdraw request, needed for the later calls to /recoup
       */
      struct TALER_HashBlindedPlanchetsP planchets_h;

    } ok;

    /**
     * Details if the status is MHD_HTTP_CREATED, i.e. in case of
     * age-restriction.  The response is input to prepare the required
     * follow-up call to /reveal-withdraw.
     */
    struct TALER_EXCHANGE_WithdrawCreated created;

    /**
     * Details if the status is #MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS.
     */
    struct TALER_EXCHANGE_KycNeededRedirect unavailable_for_legal_reasons;

  } details;
};


#ifndef TALER_EXCHANGE_POST_WITHDRAW_RESULT_CLOSURE
/**
 * Type of the closure used by
 * the #TALER_EXCHANGE_PostWithdrawCallback.
 */
#define TALER_EXCHANGE_POST_WITHDRAW_RESULT_CLOSURE void
#endif /* TALER_EXCHANGE_POST_WITHDRAW_RESULT_CLOSURE */

/**
 * Type of the function that receives the result of a
 * POST /withdraw request (high-level variant).
 *
 * @param cls closure
 * @param result result returned by the HTTP server
 */
typedef void
(*TALER_EXCHANGE_PostWithdrawCallback)(
  TALER_EXCHANGE_POST_WITHDRAW_RESULT_CLOSURE *cls,
  const struct TALER_EXCHANGE_PostWithdrawResponse *result);


/**
 * Start POST /withdraw operation (high-level variant).
 *
 * @param[in,out] pwh operation to start
 * @param cb function to call with the exchange's result
 * @param cb_cls closure for @a cb
 * @return status code, #TALER_EC_NONE on success
 */
enum TALER_ErrorCode
TALER_EXCHANGE_post_withdraw_start (
  struct TALER_EXCHANGE_PostWithdrawHandle *pwh,
  TALER_EXCHANGE_PostWithdrawCallback cb,
  TALER_EXCHANGE_POST_WITHDRAW_RESULT_CLOSURE *cb_cls);


/**
 * Cancel POST /withdraw operation (high-level variant).  This function must
 * not be called by clients after the TALER_EXCHANGE_PostWithdrawCallback has
 * been invoked (as in those cases it'll be called internally by the
 * implementation already).
 *
 * @param[in] pwh operation to cancel
 */
void
TALER_EXCHANGE_post_withdraw_cancel (
  struct TALER_EXCHANGE_PostWithdrawHandle *pwh);


#endif /* _TALER_EXCHANGE__POST_WITHDRAW_H */
