#include <string.h>

#include "crypto.h"
#include "crypto-internal.h"

void
sigsum_hash_key (struct sigsum_hash *kh, const struct sigsum_pubkey *key)
{
  struct sigsum_hash_ctx ctx;
  _sigsum_hash_init (&ctx);
  _sigsum_hash_update (&ctx, sizeof (key->k), key->k);
  _sigsum_hash_digest (&ctx, kh);
}

const struct sigsum_pubkey *
sigsum_key_map_lookup (const struct sigsum_key_map *map,
		       const struct sigsum_hash *key_hash,
		       size_t *idx)
{
  size_t i;

  /* Do a linear search for a hash with matching first byte. In the
     typical case, there will only be a single iteration of the below
     memcmp loop. Could be changed to use binary search, but that is
     likely overkill. */
  for (i = 0; i < map->num_keys && map->keys[i].hash.h[0] < key_hash->h[0]; i++)
    ;
  for (; i < map->num_keys; i++)
    {
      int c = memcmp (map->keys[i].hash.h, key_hash->h, sizeof (key_hash->h));
      if (!c)
	{
	  if (idx)
	    *idx = i;
	  return &map->keys[i].key;
	}
      if (c > 0)
	break;
    }
  return NULL;
}
