mega-state-test 1.6.1

Self-contained EEST-compatible state-test fixtures and runner for mega-evm
#![allow(missing_docs)]

use alloy_rlp::{RlpEncodable, RlpMaxEncodedLen};
use hash_db::Hasher;
use k256::ecdsa::SigningKey;
use mega_evm::{
    revm::{
        context::result::{EVMError, ExecutionResult},
        database::{EmptyDB, PlainAccount, State},
        primitives::{keccak256, Address, Log, B256, U256},
    },
    MegaHaltReason, MegaTransactionError,
};
use plain_hasher::PlainHasher;
use std::convert::Infallible;
use triehash::sec_trie_root;

#[derive(Debug)]
pub struct TestValidationResult {
    pub logs_root: B256,
    pub state_root: B256,
}

pub fn compute_test_roots(
    exec_result: &Result<
        ExecutionResult<MegaHaltReason>,
        EVMError<Infallible, MegaTransactionError>,
    >,
    db: &State<EmptyDB>,
) -> TestValidationResult {
    TestValidationResult {
        logs_root: log_rlp_hash(exec_result.as_ref().map(|r| r.logs()).unwrap_or_default()),
        state_root: state_merkle_trie_root(db.cache.trie_account()),
    }
}

pub fn log_rlp_hash(logs: &[Log]) -> B256 {
    let mut out = Vec::with_capacity(alloy_rlp::list_length(logs));
    alloy_rlp::encode_list(logs, &mut out);
    keccak256(&out)
}

pub fn state_merkle_trie_root<'a>(
    accounts: impl IntoIterator<Item = (Address, &'a PlainAccount)>,
) -> B256 {
    trie_root(
        accounts
            .into_iter()
            .map(|(address, acc)| (address, alloy_rlp::encode_fixed_size(&TrieAccount::new(acc)))),
    )
}

#[derive(RlpEncodable, RlpMaxEncodedLen)]
struct TrieAccount {
    nonce: u64,
    balance: U256,
    root_hash: B256,
    code_hash: B256,
}

impl TrieAccount {
    fn new(acc: &PlainAccount) -> Self {
        Self {
            nonce: acc.info.nonce,
            balance: acc.info.balance,
            root_hash: sec_trie_root::<KeccakHasher, _, _, _>(
                acc.storage
                    .iter()
                    .filter(|(_k, &v)| !v.is_zero())
                    .map(|(k, v)| (k.to_be_bytes::<32>(), alloy_rlp::encode_fixed_size(v))),
            ),
            code_hash: acc.info.code_hash,
        }
    }
}

#[inline]
pub fn trie_root<I, A, B>(input: I) -> B256
where
    I: IntoIterator<Item = (A, B)>,
    A: AsRef<[u8]>,
    B: AsRef<[u8]>,
{
    sec_trie_root::<KeccakHasher, _, _, _>(input)
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeccakHasher;

impl Hasher for KeccakHasher {
    type Out = B256;
    type StdHasher = PlainHasher;
    const LENGTH: usize = 32;

    #[inline]
    fn hash(x: &[u8]) -> Self::Out {
        keccak256(x)
    }
}

/// Recover the address from a private key ([`SigningKey`]).
pub fn recover_address(private_key: &[u8]) -> Option<Address> {
    let key = SigningKey::from_slice(private_key).ok()?;
    let public_key = key.verifying_key().to_encoded_point(false);
    Some(Address::from_raw_public_key(&public_key.as_bytes()[1..]))
}

#[cfg(test)]
mod tests {
    use super::*;
    use mega_evm::revm::primitives::{address, hex};

    #[test]
    fn sanity_test() {
        assert_eq!(
            Some(address!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")),
            recover_address(&hex!(
                "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
            ))
        )
    }
}