/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2023 Brett Sheffield <bacs@librecast.net> */

#include "test.h"
#include "testdata.h"
#include <librecast.h>
#include <librecast/crypto.h>

#define GRPBYTES 14 /* bytes for multicast group */

/* we need to be able to match an expected channel hash to the lower 14 bytes of
 * the address for MLD triggers etc. Ensure this isn't mangled */

int main(void)
{
	unsigned char rand[1024];
	unsigned char hash1[HASHSIZE];
	unsigned char hash2[HASHSIZE];
	lc_ctx_t *lctx;
	lc_channel_t *chan;
	struct in6_addr *addr;

	test_name("lc_channel_nnew(): ensure lower 14 bytes of address match hash");

	test_random_bytes(rand, sizeof rand);

	/* if we ask for fewer bytes from our hash function, this is just
	 * the full hash truncated */
	hash_generic(hash1, HASHSIZE, rand, sizeof rand);
	hash_generic(hash2, GRPBYTES, rand, sizeof rand);
	test_assert(!memcmp(hash1, hash2, GRPBYTES),
			"ensure our hash function truncates hashes predictably");

	/* ensure hash can be recreated */
	lctx = lc_ctx_new();
	chan = lc_channel_nnew(lctx, rand, sizeof rand);
	addr = lc_channel_in6addr(chan);
	test_assert(!memcmp(hash1, &addr->s6_addr[2], GRPBYTES), "address matches hash");
	lc_ctx_free(lctx);

	return test_status;
}
