/* GNU Guix --- Functional package management for GNU
   Copyright © 2020 Maxime Devos <maxime.devos@student.kuleuven.be>

   This file is part of GNU Guix.

   GNU Guix 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 of the License, or (at
   your option) any later version.

   GNU Guix 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 GNU Guix.  If not, see <http://www.gnu.org/licenses/>. */

#include <gnunet/gnunet_config.h>
#include <gnunet/gnunet_crypto_lib.h>
#include <stdint.h>
#include "rehash_crypto.h"

int
GNUNET_REHASH_cleartext_query_from_hash (
  enum GNUNET_REHASH_Hash_Type out_type,
  enum GNUNET_REHASH_Hash_Type in_type,
  const char *data,
  size_t data_size,
  struct GNUNET_HashCode *query)
{
  size_t query_size;
  char *query_data;
  struct GNUNET_REHASH_Request *header;
  char *footer;
  if (data_size > 64)
    /* Don't allocate much.
       There are no hashes of size > 64. */
    return GNUNET_NO;

  /* Allocation */
  query_size = sizeof (struct GNUNET_REHASH_Request) + data_size;
  query_data = GNUNET_malloc(query_size);
  header = (struct GNUNET_REHASH_Request *) query_data;
  footer = query_data + sizeof (struct GNUNET_REHASH_Request);

  /* Preparing data structures */
  header->key_type = htonl(in_type);
  header->value_type = htonl(out_type);
  memcpy(footer, data, data_size);

  /* Perform! */
  GNUNET_CRYPTO_hash(query_data, query_size, query);
  /* Deallocation */
  GNUNET_free(query_data);

  return GNUNET_OK;
}

int
GNUNET_REHASH_obfuscated_query_from_hash (
  enum GNUNET_REHASH_Hash_Type out_type,
  enum GNUNET_REHASH_Hash_Type in_type,
  const char *data,
  size_t data_size,
  struct GNUNET_HashCode *query)
{
  struct GNUNET_HashCode cleartext;
  if (GNUNET_OK != GNUNET_REHASH_cleartext_query_from_hash (
    out_type, in_type, data, data_size, &cleartext))
    return GNUNET_NO;
  /* Obfuscated query is used as key in the DHT,
     cleartext query is used for encrypting the
     data, such that only nodes that know the
     original query can parse the resulting data. */
  GNUNET_CRYPTO_hash (&cleartext, sizeof(struct GNUNET_HashCode), query);
  return GNUNET_OK;
}
