/*
   This file is part of TALER
   Copyright (C) 2022-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-reserves-RESERVE_PUB-purse.c
 * @brief Implementation of the client to create a
 *        purse for an account
 * @author Christian Grothoff
 */
#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 "taler/taler_json_lib.h"
#include "exchange_api_handle.h"
#include "exchange_api_common.h"
#include "taler/taler_signatures.h"
#include "exchange_api_curl_defaults.h"


/**
 * @brief A POST /reserves/$RESERVE_PUB/purse handle
 */
struct TALER_EXCHANGE_PostReservesPurseHandle
{

  /**
   * The keys of the exchange this request handle will use
   */
  struct TALER_EXCHANGE_Keys *keys;

  /**
   * Context for #TEH_curl_easy_post(). Keeps the data that must
   * persist for Curl to make the upload.
   */
  struct TALER_CURL_PostContext ctx;

  /**
   * The base URL for this request.
   */
  char *base_url;

  /**
   * The full URL for this request, set during _start.
   */
  char *url;

  /**
   * The exchange base URL (same as base_url, kept for conflict checks).
   */
  char *exchange_url;

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *curl_ctx;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Function to call with the result.
   */
  TALER_EXCHANGE_PostReservesPurseCallback cb;

  /**
   * Closure for @a cb.
   */
  TALER_EXCHANGE_POST_RESERVES_PURSE_RESULT_CLOSURE *cb_cls;

  /**
   * Private key for the contract.
   */
  struct TALER_ContractDiffiePrivateP contract_priv;

  /**
   * Private key for the purse.
   */
  struct TALER_PurseContractPrivateKeyP purse_priv;

  /**
   * Private key of the reserve.
   */
  struct TALER_ReservePrivateKeyP reserve_priv;

  /**
   * The encrypted contract (if any).
   */
  struct TALER_EncryptedContract econtract;

  /**
   * Expected value in the purse after fees.
   */
  struct TALER_Amount purse_value_after_fees;

  /**
   * Public key of the reserve public key.
   */
  struct TALER_ReservePublicKeyP reserve_pub;

  /**
   * Reserve signature affirming our merge.
   */
  struct TALER_ReserveSignatureP reserve_sig;

  /**
   * Merge capability key.
   */
  struct TALER_PurseMergePublicKeyP merge_pub;

  /**
   * Our merge signature (if any).
   */
  struct TALER_PurseMergeSignatureP merge_sig;

  /**
   * Public key of the purse.
   */
  struct TALER_PurseContractPublicKeyP purse_pub;

  /**
   * Request data we signed over.
   */
  struct TALER_PurseContractSignatureP purse_sig;

  /**
   * Hash over the purse's contract terms.
   */
  struct TALER_PrivateContractHashP h_contract_terms;

  /**
   * When does the purse expire.
   */
  struct GNUNET_TIME_Timestamp purse_expiration;

  /**
   * When does the purse get merged/created.
   */
  struct GNUNET_TIME_Timestamp merge_timestamp;

  /**
   * Our contract terms.
   */
  json_t *contract_terms;

  /**
   * Minimum age for the coins as per @e contract_terms.
   */
  uint32_t min_age;

  struct
  {

    /**
     * Are we paying for purse creation? Not yet a "real" option.
     */
    bool pay_for_purse;

    /**
     * Should we upload the contract?
     */
    bool upload_contract;
  } options;

};


/**
 * Function called when we're done processing the
 * HTTP /reserves/$RID/purse request.
 *
 * @param cls the `struct TALER_EXCHANGE_PostReservesPurseHandle`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_purse_create_with_merge_finished (void *cls,
                                         long response_code,
                                         const void *response)
{
  struct TALER_EXCHANGE_PostReservesPurseHandle *prph = cls;
  const json_t *j = response;
  struct TALER_EXCHANGE_PostReservesPurseResponse dr = {
    .hr.reply = j,
    .hr.http_status = (unsigned int) response_code,
    .reserve_sig = &prph->reserve_sig
  };

  prph->job = NULL;
  switch (response_code)
  {
  case 0:
    dr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  case MHD_HTTP_OK:
    {
      struct GNUNET_JSON_Specification spec[] = {
        TALER_JSON_spec_amount_any ("total_deposited",
                                    &dr.details.ok.total_deposited),
        GNUNET_JSON_spec_fixed_auto ("exchange_sig",
                                     &dr.details.ok.exchange_sig),
        GNUNET_JSON_spec_fixed_auto ("exchange_pub",
                                     &dr.details.ok.exchange_pub),
        GNUNET_JSON_spec_timestamp ("exchange_timestamp",
                                    &dr.details.ok.exchange_timestamp),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (j,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break_op (0);
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      if (GNUNET_OK !=
          TALER_EXCHANGE_test_signing_key (prph->keys,
                                           &dr.details.ok.exchange_pub))
      {
        GNUNET_break_op (0);
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      if (GNUNET_OK !=
          TALER_exchange_online_purse_created_verify (
            dr.details.ok.exchange_timestamp,
            prph->purse_expiration,
            &prph->purse_value_after_fees,
            &dr.details.ok.total_deposited,
            &prph->purse_pub,
            &prph->h_contract_terms,
            &dr.details.ok.exchange_pub,
            &dr.details.ok.exchange_sig))
      {
        GNUNET_break_op (0);
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
    }
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the exchange is buggy
       (or API version conflict); just pass JSON reply to the application */
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_FORBIDDEN:
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    /* 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 */
    break;
  case MHD_HTTP_NOT_FOUND:
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    /* Nothing really to verify, this should never
       happen, we should pass the JSON reply to the application */
    break;
  case MHD_HTTP_CONFLICT:
    dr.hr.ec = TALER_JSON_get_error_code (j);
    switch (dr.hr.ec)
    {
    case TALER_EC_EXCHANGE_RESERVES_PURSE_CREATE_CONFLICTING_META_DATA:
      if (GNUNET_OK !=
          TALER_EXCHANGE_check_purse_create_conflict_ (
            &prph->purse_sig,
            &prph->purse_pub,
            j))
      {
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      break;
    case TALER_EC_EXCHANGE_RESERVES_PURSE_MERGE_CONFLICTING_META_DATA:
      if (GNUNET_OK !=
          TALER_EXCHANGE_check_purse_merge_conflict_ (
            &prph->merge_sig,
            &prph->merge_pub,
            &prph->purse_pub,
            prph->exchange_url,
            j))
      {
        GNUNET_break_op (0);
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      break;
    case TALER_EC_EXCHANGE_RESERVES_PURSE_CREATE_INSUFFICIENT_FUNDS:
      /* nothing to verify */
      break;
    case TALER_EC_EXCHANGE_PURSE_ECONTRACT_CONFLICTING_META_DATA:
      if (GNUNET_OK !=
          TALER_EXCHANGE_check_purse_econtract_conflict_ (
            &prph->econtract.econtract_sig,
            &prph->purse_pub,
            j))
      {
        GNUNET_break_op (0);
        dr.hr.http_status = 0;
        dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        break;
      }
      break;
    default:
      /* unexpected EC! */
      GNUNET_break_op (0);
      dr.hr.http_status = 0;
      dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    } /* end inner (EC) switch */
    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 */
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    break;
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    if (GNUNET_OK !=
        TALER_EXCHANGE_parse_451 (&dr.details.unavailable_for_legal_reasons,
                                  j))
    {
      GNUNET_break_op (0);
      dr.hr.http_status = 0;
      dr.hr.ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      break;
    }
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    break;
  default:
    /* unexpected response code */
    dr.hr.ec = TALER_JSON_get_error_code (j);
    dr.hr.hint = TALER_JSON_get_error_hint (j);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u/%d for exchange deposit\n",
                (unsigned int) response_code,
                dr.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  if (NULL != prph->cb)
  {
    prph->cb (prph->cb_cls,
              &dr);
    prph->cb = NULL;
  }
  TALER_EXCHANGE_post_reserves_purse_cancel (prph);
}


struct TALER_EXCHANGE_PostReservesPurseHandle *
TALER_EXCHANGE_post_reserves_purse_create (
  struct GNUNET_CURL_Context *ctx,
  const char *url,
  struct TALER_EXCHANGE_Keys *keys,
  const struct TALER_ReservePrivateKeyP *reserve_priv,
  const struct TALER_PurseContractPrivateKeyP *purse_priv,
  const struct TALER_PurseMergePrivateKeyP *merge_priv,
  const struct TALER_ContractDiffiePrivateP *contract_priv,
  const json_t *contract_terms,
  bool pay_for_purse, // FIXME: turn into option?
  struct GNUNET_TIME_Timestamp merge_timestamp)
{
  struct TALER_EXCHANGE_PostReservesPurseHandle *prph;

  prph = GNUNET_new (struct TALER_EXCHANGE_PostReservesPurseHandle);
  prph->curl_ctx = ctx;
  prph->keys = TALER_EXCHANGE_keys_incref (keys);
  prph->base_url = GNUNET_strdup (url);
  prph->contract_terms = json_incref ((json_t *) contract_terms);
  prph->exchange_url = GNUNET_strdup (url);
  prph->contract_priv = *contract_priv;
  prph->reserve_priv = *reserve_priv;
  prph->purse_priv = *purse_priv;
  prph->options.pay_for_purse = pay_for_purse;

  if (GNUNET_OK !=
      TALER_JSON_contract_hash (contract_terms,
                                &prph->h_contract_terms))
  {
    GNUNET_break (0);
    TALER_EXCHANGE_keys_decref (prph->keys);
    GNUNET_free (prph->base_url);
    GNUNET_free (prph->exchange_url);
    GNUNET_free (prph);
    return NULL;
  }
  prph->merge_timestamp = merge_timestamp;
  GNUNET_CRYPTO_eddsa_key_get_public (&purse_priv->eddsa_priv,
                                      &prph->purse_pub.eddsa_pub);
  GNUNET_CRYPTO_eddsa_key_get_public (&reserve_priv->eddsa_priv,
                                      &prph->reserve_pub.eddsa_pub);
  GNUNET_CRYPTO_eddsa_key_get_public (&merge_priv->eddsa_priv,
                                      &prph->merge_pub.eddsa_pub);

  {
    struct GNUNET_JSON_Specification spec[] = {
      TALER_JSON_spec_amount_any ("amount",
                                  &prph->purse_value_after_fees),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_uint32 ("minimum_age",
                                 &prph->min_age),
        NULL),
      GNUNET_JSON_spec_timestamp ("pay_deadline",
                                  &prph->purse_expiration),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (contract_terms,
                           spec,
                           NULL, NULL))
    {
      GNUNET_break (0);
      TALER_EXCHANGE_keys_decref (prph->keys);
      GNUNET_free (prph->base_url);
      GNUNET_free (prph->exchange_url);
      GNUNET_free (prph);
      return NULL;
    }
  }

  TALER_wallet_purse_create_sign (prph->purse_expiration,
                                  &prph->h_contract_terms,
                                  &prph->merge_pub,
                                  prph->min_age,
                                  &prph->purse_value_after_fees,
                                  purse_priv,
                                  &prph->purse_sig);
  {
    struct TALER_NormalizedPayto payto_uri;

    payto_uri = TALER_reserve_make_payto (url,
                                          &prph->reserve_pub);
    TALER_wallet_purse_merge_sign (payto_uri,
                                   prph->merge_timestamp,
                                   &prph->purse_pub,
                                   merge_priv,
                                   &prph->merge_sig);
    GNUNET_free (payto_uri.normalized_payto);
  }
  return prph;
}


enum GNUNET_GenericReturnValue
TALER_EXCHANGE_post_reserves_purse_set_options_ (
  struct TALER_EXCHANGE_PostReservesPurseHandle *prph,
  unsigned int num_options,
  const struct TALER_EXCHANGE_PostReservesPurseOptionValue options[])
{
  for (unsigned int i = 0; i < num_options; i++)
  {
    const struct TALER_EXCHANGE_PostReservesPurseOptionValue *opt = &options[i];

    switch (opt->option)
    {
    case TALER_EXCHANGE_POST_RESERVES_PURSE_OPTION_END:
      return GNUNET_OK;
    case TALER_EXCHANGE_POST_RESERVES_PURSE_OPTION_UPLOAD_CONTRACT:
      prph->options.upload_contract = true;
      break;
    }
  }
  return GNUNET_OK;
}


enum TALER_ErrorCode
TALER_EXCHANGE_post_reserves_purse_start (
  struct TALER_EXCHANGE_PostReservesPurseHandle *prph,
  TALER_EXCHANGE_PostReservesPurseCallback cb,
  TALER_EXCHANGE_POST_RESERVES_PURSE_RESULT_CLOSURE *cb_cls)
{
  char arg_str[sizeof (prph->reserve_pub) * 2 + 32];
  CURL *eh;
  json_t *body;
  struct TALER_Amount purse_fee;
  enum TALER_WalletAccountMergeFlags flags;

  prph->cb = cb;
  prph->cb_cls = cb_cls;
  if (prph->options.pay_for_purse)
  {
    const struct TALER_EXCHANGE_GlobalFee *gf;

    flags = TALER_WAMF_MODE_CREATE_WITH_PURSE_FEE;
    gf = TALER_EXCHANGE_get_global_fee (
      prph->keys,
      GNUNET_TIME_timestamp_get ());
    purse_fee = gf->fees.purse;
  }
  else
  {
    flags = TALER_WAMF_MODE_CREATE_FROM_PURSE_QUOTA;
    GNUNET_assert (GNUNET_OK ==
                   TALER_amount_set_zero (prph->purse_value_after_fees.currency,
                                          &purse_fee));
  }

  TALER_wallet_account_merge_sign (prph->merge_timestamp,
                                   &prph->purse_pub,
                                   prph->purse_expiration,
                                   &prph->h_contract_terms,
                                   &prph->purse_value_after_fees,
                                   &purse_fee,
                                   prph->min_age,
                                   flags,
                                   &prph->reserve_priv,
                                   &prph->reserve_sig);


  if (prph->options.upload_contract)
  {
    TALER_CRYPTO_contract_encrypt_for_deposit (
      &prph->purse_pub,
      &prph->contract_priv,
      prph->contract_terms,
      &prph->econtract.econtract,
      &prph->econtract.econtract_size);
    GNUNET_CRYPTO_ecdhe_key_get_public (
      &prph->contract_priv.ecdhe_priv,
      &prph->econtract.contract_pub.ecdhe_pub);
    TALER_wallet_econtract_upload_sign (
      prph->econtract.econtract,
      prph->econtract.econtract_size,
      &prph->econtract.contract_pub,
      &prph->purse_priv,
      &prph->econtract.econtract_sig);
  }

  body = GNUNET_JSON_PACK (
    TALER_JSON_pack_amount ("purse_value",
                            &prph->purse_value_after_fees),
    GNUNET_JSON_pack_uint64 ("min_age",
                             prph->min_age),
    GNUNET_JSON_pack_allow_null (
      TALER_JSON_pack_econtract ("econtract",
                                 prph->options.upload_contract
                                 ? &prph->econtract
                                 : NULL)),
    GNUNET_JSON_pack_allow_null (
      prph->options.pay_for_purse
      ? TALER_JSON_pack_amount ("purse_fee",
                                &purse_fee)
      : GNUNET_JSON_pack_string ("dummy2",
                                 NULL)),
    GNUNET_JSON_pack_data_auto ("merge_pub",
                                &prph->merge_pub),
    GNUNET_JSON_pack_data_auto ("merge_sig",
                                &prph->merge_sig),
    GNUNET_JSON_pack_data_auto ("reserve_sig",
                                &prph->reserve_sig),
    GNUNET_JSON_pack_data_auto ("purse_pub",
                                &prph->purse_pub),
    GNUNET_JSON_pack_data_auto ("purse_sig",
                                &prph->purse_sig),
    GNUNET_JSON_pack_data_auto ("h_contract_terms",
                                &prph->h_contract_terms),
    GNUNET_JSON_pack_timestamp ("merge_timestamp",
                                prph->merge_timestamp),
    GNUNET_JSON_pack_timestamp ("purse_expiration",
                                prph->purse_expiration));
  if (NULL == body)
    return TALER_EC_GENERIC_ALLOCATION_FAILURE;

  {
    char pub_str[sizeof (prph->reserve_pub) * 2];
    char *end;

    end = GNUNET_STRINGS_data_to_string (
      &prph->reserve_pub,
      sizeof (prph->reserve_pub),
      pub_str,
      sizeof (pub_str));
    *end = '\0';
    GNUNET_snprintf (arg_str,
                     sizeof (arg_str),
                     "reserves/%s/purse",
                     pub_str);
  }
  prph->url = TALER_url_join (prph->base_url,
                              arg_str,
                              NULL);
  if (NULL == prph->url)
  {
    GNUNET_break (0);
    return TALER_EC_GENERIC_CONFIGURATION_INVALID;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "URL for purse create_with_merge: `%s'\n",
              prph->url);
  eh = TALER_EXCHANGE_curl_easy_get_ (prph->url);
  if ( (NULL == eh) ||
       (GNUNET_OK !=
        TALER_curl_easy_post (&prph->ctx,
                              eh,
                              body)) )
  {
    GNUNET_break (0);
    json_decref (body);
    if (NULL != eh)
      curl_easy_cleanup (eh);
    return TALER_EC_GENERIC_CURL_ALLOCATION_FAILURE;
  }
  json_decref (body);
  prph->job = GNUNET_CURL_job_add2 (prph->curl_ctx,
                                    eh,
                                    prph->ctx.headers,
                                    &handle_purse_create_with_merge_finished,
                                    prph);
  if (NULL == prph->job)
    return TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE;
  return TALER_EC_NONE;
}


void
TALER_EXCHANGE_post_reserves_purse_cancel (
  struct TALER_EXCHANGE_PostReservesPurseHandle *prph)
{
  if (NULL != prph->job)
  {
    GNUNET_CURL_job_cancel (prph->job);
    prph->job = NULL;
  }
  GNUNET_free (prph->url);
  GNUNET_free (prph->base_url);
  GNUNET_free (prph->exchange_url);
  TALER_curl_easy_post_finished (&prph->ctx);
  TALER_EXCHANGE_keys_decref (prph->keys);
  GNUNET_free (prph->econtract.econtract);
  json_decref (prph->contract_terms);
  GNUNET_free (prph);
}


/* end of exchange_api_post-reserves-RESERVE_PUB-purse.c */
