#![cfg(any(test, feature = "runtime-benchmarks"))]

use crate::{keccak_256, Config, EcdsaSignature, EthereumAddress};

pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
    libsecp256k1::PublicKey::from_secret_key(secret)
}

pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress {
    let mut res = EthereumAddress::default();
    res.0
        .copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
    res
}

#[cfg(test)]
pub fn into_account_id<T: Config<I>, I: 'static>(address: EthereumAddress) -> T::AccountId {
    super::Pallet::<T, I>::into_account_id(address).unwrap()
}

pub fn sig<T: Config<I>, I: 'static>(
    secret: &libsecp256k1::SecretKey,
    what: &[u8],
) -> EcdsaSignature {
    let msg = keccak_256(&super::Pallet::<T, I>::ethereum_signable_message(
        &crate::to_ascii_hex(what)[..],
    ));

    let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);

    let mut r = [0u8; 65];
    r[0..64].copy_from_slice(&sig.serialize()[..]);
    r[64] = recovery_id.serialize();
    EcdsaSignature(r)
}
