/*
  This file is part of TALER
  Copyright (C) 2014-2024 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 testing/testing_api_cmd_issue_receipts.c
 * @brief Implement the POST /charities test command.
 * @author Lukas Matyja
 */
#include <donau_config.h>
#include <taler/taler_json_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include <taler/taler_testing_lib.h>
#include "donau_testing_lib.h"


/**
 * State for a "status" CMD.
 */
struct StatusState
{
  /**
   * Handle to the "batch issue receipt status" operation.
   */
  struct DONAU_BatchIssueReceiptHandle *birh;

  /**
   * Reference to charity post command.
   */
  const char *charity_reference;

  /**
   * Issue amount
   */
  struct TALER_Amount amount;

  /**
   * Expected HTTP response code.
   */
  unsigned int expected_response_code;

  /**
   */
  bool uses_cs;

  /**
   * Interpreter state.
   */
  struct TALER_TESTING_Interpreter *is;

  /**
   * charity id
   */
  uint64_t charity_id;

  /**
   * charity id
   */
  unsigned long long year;

  /**
   * Private key of the charity, for signature.
   */
  struct DONAU_CharityPrivateKeyP charity_priv;

  /**
   * number of budi key pair.
   */
  uint32_t num_bkp;

  /**
   * budi key pair array
   */
  struct DONAU_BlindedUniqueDonorIdentifierKeyPair *bkps;

  /**
   * donau keys
   */
  struct DONAU_Keys *keys;

  /**
   * The salt used for @h_donor_tax_id.
   */
  const char *donor_tax_id;

  /**
   * The cleartext tax id of the user used for @h_donor_tax_id.
   */
  const char *donor_salt;

  /**
   * Hashed and salted tax id of the donor.
   */
  struct DONAU_HashDonorTaxId h_donor_tax_id;

  /**
   * Selected donation-unit pubkeys for this request
   */
  struct DONAU_DonationUnitPublicKey *selected_pks;

  /**
   * Array of donation receipts;
   */
  struct DONAU_DonationReceipt *receipts;

  /**
   * Blinding secrets
   */
  union GNUNET_CRYPTO_BlindingSecretP *blinding_secrets;

  /**
   * Blinding values. Cs-nonces, cipher.
   */
  const struct DONAU_BatchIssueValues **alg_values;

  /**
   * Array of hashed udis.
   */
  struct DONAU_UniqueDonorIdentifierHashP *h_udis;

  /**
   * Number of pending CS requests.
   */
  size_t cs_pending;
};


struct CSR_Data
{
  /**
   * Handle to the "batch issue receipt status" operation.
   */
  struct DONAU_CsRBatchIssueHandle *csr_handle;

  /**
   * CS-Nonce
   */
  union GNUNET_CRYPTO_BlindSessionNonce nonce;

  /**
   * batch issue receipt status state
   */
  struct StatusState *ss;

  /**
   * array position in batch issue receipt request (first position is zero)
   */
  size_t position;
};


/**
 * Check that the reserve balance and HTTP response code are
 * both acceptable.
 *
 * @param cls closure.
 * @param biresp HTTP response details
 */
static void
issue_receipts_status_cb (void *cls,
                          const struct DONAU_BatchIssueResponse *biresp)
{
  struct StatusState *ss = cls;

  ss->birh = NULL;
  if (ss->expected_response_code != biresp->hr.http_status)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected HTTP response code: %d in %s:%u\n",
                biresp->hr.http_status,
                __FILE__,
                __LINE__);
    json_dumpf (biresp->hr.reply,
                stderr,
                0);
    TALER_TESTING_interpreter_fail (ss->is);
    return;
  }
  {
    struct DONAU_BlindedDonationUnitSignature *blinded_sigs =
      biresp->details.ok.blinded_sigs;
    for (size_t i = 0; i < ss->num_bkp; i++)
    {
      struct DONAU_UniqueDonorIdentifierHashP checkudi_hash;

      GNUNET_assert (GNUNET_OK ==
                     DONAU_donation_unit_sig_unblind (
                       &ss->receipts[i].donation_unit_sig,
                       &blinded_sigs[i],
                       &ss->blinding_secrets[i],
                       &ss->h_udis[i],
                       ss->alg_values[i],
                       &ss->selected_pks[i]));

      /* check udi message */
      DONAU_unique_donor_id_hash (
        &ss->h_donor_tax_id,
        &ss->receipts[i].nonce,
        &checkudi_hash);
      GNUNET_assert (0 == GNUNET_CRYPTO_hash_cmp (&checkudi_hash.hash,
                                                  &ss->h_udis[i].hash));
      /* check signature */
      if (GNUNET_OK !=
          DONAU_donation_receipt_verify (
            &ss->selected_pks[i],
            &checkudi_hash,
            &ss->receipts[i].donation_unit_sig))
      {
        GNUNET_break_op (0);
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Donation receipt signature invalid!\n");
      }
      else
      {
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Donation receipt signature valid!\n");
      }
    }
  }
  TALER_TESTING_interpreter_next (ss->is);
}


/**
 * Runs phase two, the actual issue receipts operation.
 * Started once the preparation for CS-donation-units is
 * done.
 * @param cls closure.
 */
static void
phase_two (void *cls)
{
  struct StatusState *ss = cls;
  const struct DONAU_BlindedUniqueDonorIdentifierKeyPair *bkps = ss->bkps;
  ss->birh = DONAU_charity_issue_receipt (
    TALER_TESTING_interpreter_get_context (ss->is),
    TALER_TESTING_get_donau_url (ss->is),
    &ss->charity_priv,
    ss->charity_id,
    ss->year,
    ss->num_bkp,
    bkps,
    &issue_receipts_status_cb,
    ss);
}


/**
 * Function called when stage 1 of CS issue is finished (request r_pub's)
 *
 * @param cls the `struct CSR_Data *`
 * @param csrresp replies from the /csr-issue request
 */
static void
cs_stage_two_callback (
  void *cls,
  const struct DONAU_CsRBatchIssueResponse *csrresp)
{
  struct CSR_Data *csr_data = cls;
  struct DONAU_BlindedUniqueDonorIdentifier *blinded_udi =
    &csr_data->ss->bkps[csr_data->position].blinded_udi;

  if (csrresp->hr.http_status != MHD_HTTP_CREATED)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected HTTP response code: %d in %s:%u\n",
                csrresp->hr.http_status,
                __FILE__,
                __LINE__);
    json_dumpf (csrresp->hr.reply,
                stderr,
                0);
    TALER_TESTING_interpreter_fail (csr_data->ss->is);
    return;
  }

  {
    struct DONAU_DonationUnitPublicKey *cs_pk =
      &csr_data->ss->keys->donation_unit_keys[csr_data->position].key;
    struct DONAU_BatchIssueValues *alg_values = GNUNET_new (struct
                                                            DONAU_BatchIssueValues);
    struct DONAU_BudiMasterSecretP ps;
    struct DONAU_UniqueDonorIdentifierHashP *udi_hash =
      &csr_data->ss->h_udis[csr_data->position];
    union GNUNET_CRYPTO_BlindingSecretP *blinding_secret =
      &csr_data->ss->blinding_secrets[csr_data->position];
    struct DONAU_UniqueDonorIdentifierNonce *udi_nonce =
      &csr_data->ss->receipts[csr_data->position].nonce;

    GNUNET_assert (GNUNET_CRYPTO_BSA_CS == cs_pk->bsign_pub_key->cipher);

    DONAU_donation_unit_ewv_copy (alg_values,
                                  &csrresp->details.ok.
                                  alg_values);
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
                                &ps,
                                sizeof (ps));
    DONAU_budi_secret_create (&ps,
                              alg_values,
                              blinding_secret);
    GNUNET_assert (GNUNET_OK ==
                   DONAU_donation_unit_blind (
                     cs_pk,
                     blinding_secret,
                     &csr_data->nonce,        /* nonce only needed for cs */
                     udi_nonce,
                     &csr_data->ss->h_donor_tax_id,
                     alg_values,
                     udi_hash,
                     blinded_udi));
    csr_data->ss->alg_values[csr_data->position] = alg_values;
    csr_data->ss->cs_pending--;
  }
  if (0 == csr_data->ss->cs_pending)
    phase_two (csr_data->ss);
}


/**
 * Run the command.
 *
 * @param cls closure.
 * @param cmd the command being executed.
 * @param is the interpreter state.
 */
static void
status_run (void *cls,
            const struct TALER_TESTING_Command *cmd,
            struct TALER_TESTING_Interpreter *is)
{
  struct StatusState *ss = cls;

  (void) cmd;
  ss->is = is;

  /* Get charity id and the charity private key from trait */
  {
    const struct TALER_TESTING_Command *charity_post_cmd;
    const uint64_t *charity_id;
    const struct DONAU_CharityPrivateKeyP *charity_priv;


    charity_post_cmd = TALER_TESTING_interpreter_lookup_command (is,
                                                                 ss->
                                                                 charity_reference);

    if (GNUNET_OK !=
        TALER_TESTING_get_trait_charity_id (charity_post_cmd, &charity_id) ||
        GNUNET_OK != TALER_TESTING_get_trait_charity_priv (charity_post_cmd,
                                                           &charity_priv))
    {
      GNUNET_break (0);
      TALER_TESTING_interpreter_fail (is);
      return;
    }
    ss->charity_id = (uint64_t) *(charity_id);
    ss->charity_priv = *(charity_priv);
  }

  /* Get donau keys from trait */
  {
    const struct TALER_TESTING_Command *keys_cmd;
    struct DONAU_Keys *keys;

    keys_cmd = TALER_TESTING_interpreter_lookup_command (is,
                                                         "get-donau");

    if (GNUNET_OK !=
        TALER_TESTING_get_trait_donau_keys (keys_cmd, &keys))
    {
      GNUNET_break (0);
      TALER_TESTING_interpreter_fail (is);
      return;
    }
    ss->keys = keys;
  }

  /* Get the donation_unit_keys for requested amount */
  {
    enum GNUNET_GenericReturnValue sret;

    sret = DONAU_select_donation_unit_keys_for_amount (
      ss->keys,
      &ss->amount,
      ss->year,
      &ss->selected_pks,
      &ss->num_bkp);

    if (GNUNET_SYSERR == sret)
    {
      GNUNET_break (0);
      TALER_TESTING_interpreter_fail (is);
      return;
    }
    if ((GNUNET_NO == sret) || (0 == ss->num_bkp))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Could not compose exact amount from donation units\n");
      TALER_TESTING_interpreter_fail (is);
      return;
    }
  }

  ss->bkps =
    GNUNET_new_array (ss->num_bkp, struct
                      DONAU_BlindedUniqueDonorIdentifierKeyPair);
  ss->blinding_secrets =
    GNUNET_new_array (ss->num_bkp, union GNUNET_CRYPTO_BlindingSecretP);
  ss->receipts =
    GNUNET_new_array (ss->num_bkp, struct DONAU_DonationReceipt);
  ss->alg_values =
    GNUNET_new_array (ss->num_bkp, const struct DONAU_BatchIssueValues *);
  ss->h_udis =
    GNUNET_new_array (ss->num_bkp, struct DONAU_UniqueDonorIdentifierHashP);
  for (size_t cnt = 0; cnt < ss->num_bkp; cnt++)
  {
    struct DONAU_UniqueDonorIdentifierNonce *udi_nonce
      = &ss->receipts[cnt].nonce;
    struct DONAU_BlindedUniqueDonorIdentifier *blinded_udi
      = &ss->bkps[cnt].blinded_udi;
    struct DONAU_UniqueDonorIdentifierHashP *udi_hash
      = &ss->h_udis[cnt];
    struct DONAU_BudiMasterSecretP ps;
    const struct DONAU_BatchIssueValues *alg_values;

    DONAU_donation_unit_pub_hash (&ss->selected_pks[cnt],
                                  &ss->bkps[cnt].h_donation_unit_pub);
    ss->receipts[cnt].h_donation_unit_pub = ss->bkps[cnt].h_donation_unit_pub;
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
                                &ps,
                                sizeof (ps));
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
                                udi_nonce,
                                sizeof (*udi_nonce));
    switch (ss->selected_pks[cnt].bsign_pub_key->cipher)
    {
    case GNUNET_CRYPTO_BSA_RSA:
      alg_values = DONAU_donation_unit_ewv_rsa_singleton ();
      DONAU_budi_secret_create (&ps,
                                alg_values,
                                &ss->blinding_secrets[cnt]);
      GNUNET_assert (GNUNET_OK ==
                     DONAU_donation_unit_blind (
                       &ss->selected_pks[cnt],
                       &ss->blinding_secrets[cnt],
                       NULL,                    /* no cs-nonce needed for rsa */
                       udi_nonce,
                       &ss->h_donor_tax_id,
                       alg_values,
                       udi_hash,
                       blinded_udi));
      ss->alg_values[cnt] = alg_values;
      break;
    case GNUNET_CRYPTO_BSA_CS:
      {
        struct CSR_Data *csr_data = GNUNET_new (struct CSR_Data);

        TALER_cs_withdraw_nonce_derive ( // FIXME: write new method
          (struct TALER_PlanchetMasterSecretP *) &ps,
          &csr_data->nonce.cs_nonce);
        csr_data->ss = ss;
        csr_data->position = cnt;
        csr_data->csr_handle = DONAU_csr_issue (
          TALER_TESTING_interpreter_get_context (is),
          TALER_TESTING_get_donau_url (is),
          &ss->selected_pks[cnt],
          &csr_data->nonce.cs_nonce,
          &cs_stage_two_callback,
          csr_data);
        if (NULL == csr_data->csr_handle)
        {
          GNUNET_break (0);
        }
        ss->cs_pending++;
        break;
      }
    default:
      GNUNET_break (0);
    }
  }
  if (0 == ss->cs_pending)
    phase_two (ss);
}


/**
 * Cleanup the state from a "issue receipt status" CMD, and possibly
 * cancel a pending operation thereof.
 *
 * @param cls closure.
 * @param cmd the command which is being cleaned up.
 */
static void
cleanup (void *cls,
         const struct TALER_TESTING_Command *cmd)
{
  struct StatusState *ss = cls;

  if (NULL != ss->birh)
  {
    // log incomplete command
    TALER_TESTING_command_incomplete (ss->is,
                                      cmd->label);
    DONAU_charity_issue_receipt_cancel (ss->birh);
    ss->birh = NULL;
  }

  if (ss->selected_pks)
    GNUNET_array_grow (ss->selected_pks, ss->num_bkp, 0);

  GNUNET_free (ss->h_udis);
  GNUNET_free (ss->alg_values);
  GNUNET_free (ss->blinding_secrets);
  GNUNET_free (ss->bkps);
  GNUNET_free (ss);
}


/**
 * Offer internal data from a "deposit" CMD, to other commands.
 *
 * @param cls closure.
 * @param[out] ret result.
 * @param trait name of the trait.
 * @param index index number of the object to offer.
 * @return #GNUNET_OK on success.
 */
static enum GNUNET_GenericReturnValue
issue_receipts_traits (void *cls,
                       const void **ret,
                       const char *trait,
                       unsigned int index)
{
  struct StatusState *ss = cls;
  struct TALER_TESTING_Trait traits[] = {
    TALER_TESTING_make_trait_donor_salt (ss->donor_salt),
    TALER_TESTING_make_trait_donor_tax_id (ss->donor_tax_id),
    TALER_TESTING_make_trait_salted_tax_id_hash (
      (const struct DONAU_HashDonorTaxId *) &ss->h_donor_tax_id),
    TALER_TESTING_make_trait_donation_receipts (
      (const struct DONAU_DonationReceipt **) &ss->receipts),
    TALER_TESTING_make_trait_number_receipts ((const size_t *) &ss->num_bkp),
    TALER_TESTING_trait_end ()
  };

  return TALER_TESTING_get_trait (traits,
                                  ret,
                                  trait,
                                  index);
}


struct TALER_TESTING_Command
TALER_TESTING_cmd_issue_receipts (const char *label,
                                  const char *charity_reference,
                                  const bool uses_cs,
                                  const uint64_t year,
                                  const char *donor_tax_id,
                                  const char *salt,
                                  const char *issue_amount,
                                  unsigned int expected_response_code)
{
  struct StatusState *ss;

  ss = GNUNET_new (struct StatusState);

  ss->year = year;
  ss->charity_reference = charity_reference;
  ss->expected_response_code = expected_response_code;
  ss->uses_cs = uses_cs;
  ss->donor_salt = (const char*) salt;
  ss->donor_tax_id = (const char*) donor_tax_id;
  if (GNUNET_OK !=
      TALER_string_to_amount (issue_amount,
                              &ss->amount))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to parse amount `%s' at %s\n",
                issue_amount,
                label);
    GNUNET_assert (0);
  }

  if (! DONAU_compute_salted_tax_id_hash (donor_tax_id,
                                          salt,
                                          ss->h_donor_tax_id.hash))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Hash was not received");
    GNUNET_assert (0);
  }

  {
    struct TALER_TESTING_Command cmd = {
      .cls = ss,
      .label = label,
      .run = &status_run,
      .cleanup = &cleanup,
      .traits = &issue_receipts_traits
    };

    return cmd;

  }
}
