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

#include "test.h"
#include <key.h>
#include <errno.h>
#include <librecast/key.h>
#include <librecast/net.h>

int main(void)
{
	char name[] = "sign capability token";
	lc_ctx_t *lctx;
	lc_channel_t *chan;
	lc_token_t token;
	uint8_t capbits = 0;
	int rc;

	test_name(name);

	/* context & channel */
	lctx = lc_ctx_new();
	chan = lc_channel_new(lctx, "Trans Women are Women");

	/* create authority keypair */
	key_combo_t authring;
	rc = key_gen_keys(&authring);
	test_assert(rc == 0, "key_gen_keys() - AUTHORITY");

	/* create bearer keypair */
	key_combo_t bearring;
	rc = key_gen_keys(&bearring);
	test_assert(rc == 0, "key_gen_keys() - BEARER");

	rc = lc_token_new(&token, &authring.s, bearring.s.pk, chan, capbits, 60);
	test_assert(rc == 0, "lc_token_new()");

	/* check signature */
	unsigned char *cap = (unsigned char *)&token;
	unsigned long long caplen = sizeof token - crypto_sign_BYTES;
	test_assert(crypto_sign_verify_detached(token.sig, cap, caplen, authring.s.pk) == 0,
			"crypto_sign_open() - verify signature");

	/* check bearer key and capbits */
	test_assert(memcmp(token.bearkey, bearring.s.pk, crypto_sign_PUBLICKEYBYTES) == 0, "bearerkey match");
	test_assert(token.capbits == capbits, "capbits set");

	return test_status;
}
