// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

use bytes;
use encoding::hex;
use strings;

@test fn roundtrip() void = {
	let seed: seed = [1...];
	let priv_key: privkey = [0...];
	privkey_init(&priv_key, &seed);
	let pub_key = privkey_getpubkey(&priv_key);

	const msg = strings::toutf8("hello, world!");
	let sig = sign(&priv_key, msg);
	assert(verify_buf(&pub_key, msg, &sig) is void);

	let bad_pub_key = pub_key;
	bad_pub_key[0] ^= 1;
	const bad_msg = strings::toutf8("HELLO, WORLD!");
	let bad_sig = sig;
	bad_sig[0] ^= 1;

	assert(verify_buf(&bad_pub_key, msg, &sig) is invalidsig);
	assert(verify_buf(&pub_key, bad_msg, &sig) is invalidsig);
	assert(verify_buf(&pub_key, msg, &bad_sig) is invalidsig);
};

@test fn golden() void = {
	let priv_key = hex::decodestr("8ed7a797b9cea8a8370d419136bcdf683b759d2e3c6947f17e13e2485aa9d420b49f3a78b1c6a7fca8f3466f33bc0e929f01fba04306c2a7465f46c3759316d9")!;
	defer free(priv_key);
	const pub_key = privkey_getpubkey(priv_key);

	let msg = hex::decodestr("a750c232933dc14b1184d86d8b4ce72e16d69744ba69818b6ac33b1d823bb2c3")!;
	defer free(msg);

	let good_sig = hex::decodestr("04266c033b91c1322ceb3446c901ffcf3cc40c4034e887c9597ca1893ba7330becbbd8b48142ef35c012c6ba51a66df9308cb6268ad6b1e4b03e70102495790b")!;
	defer free(good_sig);

	const sig = sign(priv_key, msg);
	assert(bytes::equal(sig, good_sig));
	assert(verify_buf(pub_key, msg, sig) is void);
};

@test fn issue716() void = {
	// See https://todo.sr.ht/~sircmpwn/hare/716
	let pubkey: [_]u8 = [
		0x51, 0xe2, 0xf3, 0x79, 0xb1, 0x52, 0x37, 0x59, 0x19, 0x0e, 0x08, 0xc8,
		0xcb, 0xd3, 0xab, 0xb6, 0xbd, 0x2d, 0xf7, 0x71, 0x22, 0x87, 0x95, 0xa7,
		0x52, 0x5a, 0x1b, 0x67, 0xb1, 0x7f, 0x2d, 0x26,
	];
	let signature: [_]u8 = [
		0xae, 0x81, 0x01, 0x87, 0x46, 0xba, 0x6d, 0xcb, 0x5e, 0x40, 0xda, 0x4d,
		0x5a, 0x9b, 0xaa, 0x15, 0xc3, 0x9c, 0x84, 0xd7, 0x3d, 0x98, 0xf2, 0x85,
		0x0a, 0x82, 0x5e, 0x37, 0xc5, 0x92, 0xa6, 0x4d, 0x2b, 0x93, 0x64, 0x80,
		0xe8, 0xde, 0x2e, 0x3b, 0x4b, 0x69, 0x50, 0x3b, 0xda, 0xa2, 0x4d, 0xcd,
		0x7f, 0x73, 0xbe, 0x92, 0x2d, 0x7c, 0x90, 0xc4, 0x85, 0x27, 0xff, 0x68,
		0xfc, 0x6a, 0x53, 0x0b,
	];
	let msg: []u8 = [
		0xaa, 0xaf, 0x0a, 0xa9, 0x77, 0xf1, 0x29, 0x40, 0x28, 0xed, 0xef, 0xa9,
		0x7c, 0x22, 0x80, 0x60, 0x84, 0x96, 0x53, 0xef, 0x54, 0x42, 0x29, 0x9b,
		0x07, 0xf8, 0x88, 0xaa, 0xb1, 0x04, 0xe2, 0x4d,
	];
	assert(verify_buf(&pubkey, msg, &signature) is void);
};
