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

use bytes;
use crypto::ec;
use crypto::sha256;
use hash;
use memio;

const randbuf: [_]u8 = [
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
	0xff, 0xff, 0xff, 0xff, 0x9f, 0x4e, 0x6c, 0xf9, 0x0f, 0xbc, 0xd7, 0xfa,
	0x68, 0x33, 0x0d, 0x62, 0x04, 0xdd, 0x61, 0x1c, 0x00, 0xd9, 0x69, 0xfb,
	0xa5, 0xcd, 0xb7, 0xa9, 0x9d, 0xca, 0x94, 0xfb, 0x50, 0x20, 0x5a, 0x6b,
];

@test fn validate() void = {
	let rnd = memio::fixed(randbuf);
	let k = p256priv();
	newkey(&k, &rnd)!;

	assert(bytes::equal(randbuf[ec::P256_SCALARSZ * 2..], privkey_buf(&k)));
	privkey_validate(&k)!;

	let p = p256pub();
	pubkey_derive(&p, &k);

	pubkey_validate_format(&p)!;
	pubkey_validate(&p)!;

	let hashfn = sha256::sha256();
	let hashbuf: [sha256::SZ * 2 + sha256::BLOCKSZ]u8 = [0...];

	let msghash: [sha256::SZ]u8 = [0...];
	hash::write(&hashfn, [0, 1, 2, 3]);
	hash::sum(&hashfn, msghash);

	let sig: [P256_SIGSZ]u8 = [0...];

	assert(sign(&k, msghash, &hashfn, hashbuf, sig)! == len(sig));
	verify(&p, msghash, sig)!;

	const save = sig[4];
	sig[4] = 0xff;
	assert(verify(&p, msghash, sig) is invalidsig);
	sig[4] = save;

	pubkey_buf(&p)[1] = 0xff;
	assert(verify(&p, msghash, sig) is invalidsig);
	assert(pubkey_validate(&p) is invalidkey);
};
