package edwardsKeys_test

import "seekia/internal/cryptography/edwardsKeys"
import "seekia/internal/encoding"

import "crypto/rand"

import "testing"

func TestSignAndVerify(t *testing.T) {

	testPublicKey, testPrivateKey, err := edwardsKeys.GetNewRandomPublicAndPrivateEdwardsKeys()
	if (err != nil) {
		t.Fatal("Failed to derive random Edwards identity keys: " + err.Error())
	}

	var hashToSign [32]byte
	_, err = rand.Read(hashToSign[:])
	if (err != nil){
		t.Fatal("rand.Read failed: " + err.Error())
	}

	signature := edwardsKeys.CreateSignature(testPrivateKey, hashToSign)

	isValid := edwardsKeys.VerifySignature(testPublicKey, signature, hashToSign)
	if (isValid == false) {
		t.Fatal("Failed to verify edwards signature.")
	}

	var randomHash [32]byte
	_, err = rand.Read(randomHash[:])
	if (err != nil){
		t.Fatal("rand.Read failed: " + err.Error())
	}

	isValid = edwardsKeys.VerifySignature(testPublicKey, signature, randomHash)
	if (isValid == true) {
		t.Fatal("Failed to detect invalid signature.")
	}
}

func TestDeriveKeys(t *testing.T){

	testSeed := "b69ca6c703030f7aa18dad0e327117920521e7925394d31ebd1a18a9933e6e74"

	testSeedBytes, err := encoding.DecodeHexStringToBytes(testSeed)
	if (err != nil){
		t.Fatal("Failed to decode test seed: " + err.Error())
	}

	if (len(testSeedBytes) != 32){
		t.Fatal("Invalid testSeedBytes: Not 32 bytes long.")
	}

	testSeedArray := [32]byte(testSeedBytes)

	expectedIdentityPublicKeyHex := "95a89a662cbe202d1de7376c58dbaaddf89300334b4fba6dcf5732e82ca0da0c"

	expectedIdentityPublicKeyBytes, err := encoding.DecodeHexStringToBytes(expectedIdentityPublicKeyHex)
	if (err != nil){
		t.Fatal("Failed to decode expectedIdentityPublicKeyHex: " + err.Error())
	}
	if (len(expectedIdentityPublicKeyBytes) != 32){
		t.Fatal("Invalid expectedIdentityPublicKeyBytes: Not 32 bytes long.")
	}

	expectedIdentityPublicKeyArray := [32]byte(expectedIdentityPublicKeyBytes)

	expectedIdentityPrivateKeyHex := "b69ca6c703030f7aa18dad0e327117920521e7925394d31ebd1a18a9933e6e7495a89a662cbe202d1de7376c58dbaaddf89300334b4fba6dcf5732e82ca0da0c"

	expectedIdentityPrivateKeyBytes, err := encoding.DecodeHexStringToBytes(expectedIdentityPrivateKeyHex)
	if (err != nil){
		t.Fatal("Failed to decode expectedIdentityPrivateKeyHex: " + err.Error())
	}
	if (len(expectedIdentityPrivateKeyBytes) != 64){
		t.Fatal("Invalid expectedIdentityPrivateKeyBytes: Not 32 bytes long.")
	}

	expectedIdentityPrivateKeyArray := [64]byte(expectedIdentityPrivateKeyBytes)

	identityPublicKey, identityPrivateKey := edwardsKeys.GetSeededEdwardsPublicAndPrivateKeys(testSeedArray)

	if (identityPublicKey != expectedIdentityPublicKeyArray){
		t.Fatal("Derived invalid identity public key.")
	}
	if (identityPrivateKey != expectedIdentityPrivateKeyArray){
		t.Fatal("Derived invalid identity private key.")
	}	
}



