//! The `entry` module is a fundamental building block of Proof of History. It contains a
//! unique ID that is the hash of the Entry before it, plus the hash of the
//! transactions within it. Entries cannot be reordered, and its field `num_hashes`
//! represents an approximate amount of time since the last Entry was created.
use {
    crate::poh::Poh,
    crossbeam_channel::{Receiver, Sender},
    dlopen2::symbor::{Container, SymBorApi, Symbol},
    log::*,
    rand::{thread_rng, Rng},
    rayon::{prelude::*, ThreadPool},
    serde::{Deserialize, Serialize},
    solana_hash::Hash,
    solana_merkle_tree::MerkleTree,
    solana_runtime_transaction::transaction_with_meta::TransactionWithMeta,
    solana_transaction::{
        versioned::VersionedTransaction, Transaction, TransactionVerificationMode,
    },
    solana_transaction_error::TransactionResult as Result,
    std::{
        ffi::OsStr,
        iter::repeat_with,
        sync::{Arc, Once, OnceLock},
        time::Instant,
    },
    wincode::{containers::Pod, SchemaRead, SchemaWrite},
};

pub type EntrySender = Sender<Vec<Entry>>;
pub type EntryReceiver = Receiver<Vec<Entry>>;

static API: OnceLock<Container<Api>> = OnceLock::new();

pub fn init_poh() {
    init(OsStr::new("libpoh-simd.so"));
}

fn init(name: &OsStr) {
    static INIT_HOOK: Once = Once::new();

    info!("Loading {name:?}");
    INIT_HOOK.call_once(|| {
        let path;
        let lib_name = if let Some(perf_libs_path) = solana_perf::perf_libs::locate_perf_libs() {
            solana_perf::perf_libs::append_to_ld_library_path(
                perf_libs_path.to_str().unwrap_or("").to_string(),
            );
            path = perf_libs_path.join(name);
            path.as_os_str()
        } else {
            name
        };

        match unsafe { Container::load(lib_name) } {
            Ok(api) => _ = API.set(api),
            Err(err) => error!("Unable to load {lib_name:?}: {err}"),
        }
    })
}

pub fn api() -> Option<&'static Container<Api<'static>>> {
    {
        static INIT_HOOK: Once = Once::new();
        INIT_HOOK.call_once(|| {
            if std::env::var("TEST_PERF_LIBS").is_ok() {
                init_poh()
            }
        });
    }

    API.get()
}

#[derive(SymBorApi)]
pub struct Api<'a> {
    pub poh_verify_many_simd_avx512skx:
        Symbol<'a, unsafe extern "C" fn(hashes: *mut u8, num_hashes: *const u64)>,
    pub poh_verify_many_simd_avx2:
        Symbol<'a, unsafe extern "C" fn(hashes: *mut u8, num_hashes: *const u64)>,
}

/// Each Entry contains three pieces of data. The `num_hashes` field is the number
/// of hashes performed since the previous entry.  The `hash` field is the result
/// of hashing `hash` from the previous entry `num_hashes` times.  The `transactions`
/// field points to Transactions that took place shortly before `hash` was generated.
///
/// If you multiply `num_hashes` by the amount of time it takes to generate a new hash, you
/// get a duration estimate since the last `Entry`. Since processing power increases
/// over time, one should expect the duration `num_hashes` represents to decrease proportionally.
/// An upper bound on Duration can be estimated by assuming each hash was generated by the
/// world's fastest processor at the time the entry was recorded. Or said another way, it
/// is physically not possible for a shorter duration to have occurred if one assumes the
/// hash was computed by the world's fastest processor at that time. The hash chain is both
/// a Verifiable Delay Function (VDF) and a Proof of Work (not to be confused with Proof of
/// Work consensus!)
///
/// The solana core protocol currently requires an `Entry` to contain `transactions` that are
/// executable in parallel. Implemented in:
///
/// * For TPU: `solana_core::banking_stage::BankingStage::process_and_record_transactions()`
/// * For TVU: `solana_core::replay_stage::ReplayStage::replay_blockstore_into_bank()`
///
/// Until SIMD83 is activated:
/// All transactions in the `transactions` field have to follow the read/write locking restrictions
/// with regard to the accounts they reference. A single account can be either written by a single
/// transaction, or read by one or more transactions, but not both.
/// This enforcement is done via a call to `solana_runtime::accounts::Accounts::lock_accounts()`
/// with the `txs` argument holding all the `transactions` in the `Entry`.
#[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq, Clone, SchemaWrite, SchemaRead)]
pub struct Entry {
    /// The number of hashes since the previous Entry ID.
    pub num_hashes: u64,

    /// The SHA-256 hash `num_hashes` after the previous Entry ID.
    #[wincode(with = "Pod<Hash>")]
    pub hash: Hash,

    /// An unordered list of transactions that were observed before the Entry ID was
    /// generated. They may have been observed before a previous Entry ID but were
    /// pushed back into this list to ensure deterministic interpretation of the ledger.
    #[wincode(with = "Vec<crate::wincode::VersionedTransaction>")]
    pub transactions: Vec<VersionedTransaction>,
}

pub struct EntrySummary {
    pub num_hashes: u64,
    pub hash: Hash,
    pub num_transactions: u64,
}

impl From<&Entry> for EntrySummary {
    fn from(entry: &Entry) -> Self {
        Self {
            num_hashes: entry.num_hashes,
            hash: entry.hash,
            num_transactions: entry.transactions.len() as u64,
        }
    }
}

/// Typed entry to distinguish between transaction and tick entries
pub enum EntryType<Tx: TransactionWithMeta> {
    Transactions(Vec<Tx>),
    Tick(Hash),
}

impl Entry {
    /// Creates the next Entry `num_hashes` after `start_hash`.
    pub fn new(prev_hash: &Hash, mut num_hashes: u64, transactions: Vec<Transaction>) -> Self {
        // If you passed in transactions, but passed in num_hashes == 0, then
        // next_hash will generate the next hash and set num_hashes == 1
        if num_hashes == 0 && !transactions.is_empty() {
            num_hashes = 1;
        }

        let transactions = transactions.into_iter().map(Into::into).collect::<Vec<_>>();
        let hash = next_hash(prev_hash, num_hashes, &transactions);
        Entry {
            num_hashes,
            hash,
            transactions,
        }
    }

    pub fn new_mut(
        start_hash: &mut Hash,
        num_hashes: &mut u64,
        transactions: Vec<Transaction>,
    ) -> Self {
        let entry = Self::new(start_hash, *num_hashes, transactions);
        *start_hash = entry.hash;
        *num_hashes = 0;

        entry
    }

    #[cfg(test)]
    pub fn new_tick(num_hashes: u64, hash: &Hash) -> Self {
        Entry {
            num_hashes,
            hash: *hash,
            transactions: vec![],
        }
    }

    /// Verifies self.hash is the result of hashing a `start_hash` `self.num_hashes` times.
    /// If the transaction is not a Tick, then hash that as well.
    pub fn verify(&self, start_hash: &Hash) -> bool {
        let ref_hash = next_hash(start_hash, self.num_hashes, &self.transactions);
        if self.hash != ref_hash {
            warn!(
                "next_hash is invalid expected: {:?} actual: {:?}",
                self.hash, ref_hash
            );
            return false;
        }
        true
    }

    pub fn is_tick(&self) -> bool {
        self.transactions.is_empty()
    }
}

pub fn hash_transactions(transactions: &[VersionedTransaction]) -> Hash {
    // a hash of a slice of transactions only needs to hash the signatures
    let signatures: Vec<_> = transactions
        .iter()
        .flat_map(|tx| tx.signatures.iter())
        .collect();
    let merkle_tree = MerkleTree::new(&signatures);
    if let Some(root_hash) = merkle_tree.get_root() {
        *root_hash
    } else {
        Hash::default()
    }
}

/// Creates the hash `num_hashes` after `start_hash`. If the transaction contains
/// a signature, the final hash will be a hash of both the previous ID and
/// the signature.  If num_hashes is zero and there's no transaction data,
///  start_hash is returned.
pub fn next_hash(
    start_hash: &Hash,
    num_hashes: u64,
    transactions: &[VersionedTransaction],
) -> Hash {
    if num_hashes == 0 && transactions.is_empty() {
        return *start_hash;
    }

    let mut poh = Poh::new(*start_hash, None);
    poh.hash(num_hashes.saturating_sub(1));
    if transactions.is_empty() {
        poh.tick().unwrap().hash
    } else {
        poh.record(hash_transactions(transactions)).unwrap().hash
    }
}

pub struct EntryVerificationState {
    verification_status: bool,
    poh_duration_us: u64,
}

pub struct EntrySigVerificationState<Tx: TransactionWithMeta> {
    verification_status: bool,
    entries: Option<Vec<EntryType<Tx>>>,
}

impl<Tx: TransactionWithMeta> EntrySigVerificationState<Tx> {
    pub fn entries(&mut self) -> Option<Vec<EntryType<Tx>>> {
        self.entries.take()
    }
    pub fn status(&self) -> bool {
        self.verification_status
    }
}

impl EntryVerificationState {
    pub fn status(&self) -> bool {
        self.verification_status
    }

    pub fn poh_duration_us(&self) -> u64 {
        self.poh_duration_us
    }
}

pub fn verify_transactions<Tx: TransactionWithMeta + Send + Sync>(
    entries: Vec<Entry>,
    thread_pool: &ThreadPool,
    verify: Arc<dyn Fn(VersionedTransaction) -> Result<Tx> + Send + Sync>,
) -> Result<Vec<EntryType<Tx>>> {
    thread_pool.install(|| {
        entries
            .into_par_iter()
            .map(|entry| {
                if entry.transactions.is_empty() {
                    Ok(EntryType::Tick(entry.hash))
                } else {
                    Ok(EntryType::Transactions(
                        entry
                            .transactions
                            .into_par_iter()
                            .map(verify.as_ref())
                            .collect::<Result<Vec<_>>>()?,
                    ))
                }
            })
            .collect()
    })
}

pub fn start_verify_transactions<Tx: TransactionWithMeta + Send + Sync + 'static>(
    entries: Vec<Entry>,
    skip_verification: bool,
    thread_pool: &ThreadPool,
    verify: Arc<
        dyn Fn(VersionedTransaction, TransactionVerificationMode) -> Result<Tx> + Send + Sync,
    >,
) -> Result<EntrySigVerificationState<Tx>> {
    start_verify_transactions_cpu(entries, skip_verification, thread_pool, verify)
}

fn start_verify_transactions_cpu<Tx: TransactionWithMeta + Send + Sync + 'static>(
    entries: Vec<Entry>,
    skip_verification: bool,
    thread_pool: &ThreadPool,
    verify: Arc<
        dyn Fn(VersionedTransaction, TransactionVerificationMode) -> Result<Tx> + Send + Sync,
    >,
) -> Result<EntrySigVerificationState<Tx>> {
    let verify_func = {
        let mode = if skip_verification {
            TransactionVerificationMode::HashOnly
        } else {
            TransactionVerificationMode::FullVerification
        };

        move |versioned_tx| verify(versioned_tx, mode)
    };

    let entries = verify_transactions(entries, thread_pool, Arc::new(verify_func))?;

    Ok(EntrySigVerificationState {
        verification_status: true,
        entries: Some(entries),
    })
}

fn compare_hashes(computed_hash: Hash, ref_entry: &Entry) -> bool {
    let actual = if !ref_entry.transactions.is_empty() {
        let tx_hash = hash_transactions(&ref_entry.transactions);
        let mut poh = Poh::new(computed_hash, None);
        poh.record(tx_hash).unwrap().hash
    } else if ref_entry.num_hashes > 0 {
        let mut poh = Poh::new(computed_hash, None);
        poh.tick().unwrap().hash
    } else {
        computed_hash
    };
    actual == ref_entry.hash
}

// an EntrySlice is a slice of Entries
pub trait EntrySlice {
    /// Verifies the hashes and counts of a slice of transactions are all consistent.
    fn verify_cpu(&self, start_hash: &Hash, thread_pool: &ThreadPool) -> EntryVerificationState;
    fn verify_cpu_generic(
        &self,
        start_hash: &Hash,
        thread_pool: &ThreadPool,
    ) -> EntryVerificationState;
    fn verify_cpu_x86_simd(
        &self,
        start_hash: &Hash,
        simd_len: usize,
        thread_pool: &ThreadPool,
    ) -> EntryVerificationState;
    fn verify(&self, start_hash: &Hash, thread_pool: &ThreadPool) -> EntryVerificationState;
    /// Checks that each entry tick has the correct number of hashes. Entry slices do not
    /// necessarily end in a tick, so `tick_hash_count` is used to carry over the hash count
    /// for the next entry slice.
    fn verify_tick_hash_count(&self, tick_hash_count: &mut u64, hashes_per_tick: u64) -> bool;
    /// Counts tick entries
    fn tick_count(&self) -> u64;
}

impl EntrySlice for [Entry] {
    fn verify(&self, start_hash: &Hash, thread_pool: &ThreadPool) -> EntryVerificationState {
        self.verify_cpu(start_hash, thread_pool)
    }

    fn verify_cpu_generic(
        &self,
        start_hash: &Hash,
        thread_pool: &ThreadPool,
    ) -> EntryVerificationState {
        let now = Instant::now();
        let genesis = [Entry {
            num_hashes: 0,
            hash: *start_hash,
            transactions: vec![],
        }];
        let entry_pairs = genesis.par_iter().chain(self).zip(self);
        let res = thread_pool.install(|| {
            entry_pairs.all(|(x0, x1)| {
                let r = x1.verify(&x0.hash);
                if !r {
                    warn!(
                        "entry invalid!: x0: {:?}, x1: {:?} num txs: {}",
                        x0.hash,
                        x1.hash,
                        x1.transactions.len()
                    );
                }
                r
            })
        });
        let poh_duration_us = now.elapsed().as_micros() as u64;
        EntryVerificationState {
            verification_status: res,
            poh_duration_us,
        }
    }

    fn verify_cpu_x86_simd(
        &self,
        start_hash: &Hash,
        simd_len: usize,
        thread_pool: &ThreadPool,
    ) -> EntryVerificationState {
        use solana_hash::HASH_BYTES;
        let now = Instant::now();
        let genesis = [Entry {
            num_hashes: 0,
            hash: *start_hash,
            transactions: vec![],
        }];

        let aligned_len = self.len().div_ceil(simd_len) * simd_len;
        let mut hashes_bytes = vec![0u8; HASH_BYTES * aligned_len];
        genesis
            .iter()
            .chain(self)
            .enumerate()
            .for_each(|(i, entry)| {
                if i < self.len() {
                    let start = i * HASH_BYTES;
                    let end = start + HASH_BYTES;
                    hashes_bytes[start..end].copy_from_slice(&entry.hash.to_bytes());
                }
            });
        let mut hashes_chunked: Vec<_> = hashes_bytes.chunks_mut(simd_len * HASH_BYTES).collect();

        let mut num_hashes: Vec<u64> = self
            .iter()
            .map(|entry| entry.num_hashes.saturating_sub(1))
            .collect();
        num_hashes.resize(aligned_len, 0);
        let num_hashes: Vec<_> = num_hashes.chunks(simd_len).collect();

        let res = thread_pool.install(|| {
            hashes_chunked
                .par_iter_mut()
                .zip(num_hashes)
                .enumerate()
                .all(|(i, (chunk, num_hashes))| {
                    match simd_len {
                        8 => unsafe {
                            (api().unwrap().poh_verify_many_simd_avx2)(
                                chunk.as_mut_ptr(),
                                num_hashes.as_ptr(),
                            );
                        },
                        16 => unsafe {
                            (api().unwrap().poh_verify_many_simd_avx512skx)(
                                chunk.as_mut_ptr(),
                                num_hashes.as_ptr(),
                            );
                        },
                        _ => {
                            panic!("unsupported simd len: {simd_len}");
                        }
                    }
                    let entry_start = i * simd_len;
                    // The last chunk may produce indexes larger than what we have in the reference entries
                    // because it is aligned to simd_len.
                    let entry_end = std::cmp::min(entry_start + simd_len, self.len());
                    self[entry_start..entry_end]
                        .iter()
                        .enumerate()
                        .all(|(j, ref_entry)| {
                            let start = j * HASH_BYTES;
                            let end = start + HASH_BYTES;
                            let hash = <[u8; HASH_BYTES]>::try_from(&chunk[start..end])
                                .map(Hash::new_from_array)
                                .unwrap();
                            compare_hashes(hash, ref_entry)
                        })
                })
        });
        let poh_duration_us = now.elapsed().as_micros() as u64;
        EntryVerificationState {
            verification_status: res,
            poh_duration_us,
        }
    }

    fn verify_cpu(&self, start_hash: &Hash, thread_pool: &ThreadPool) -> EntryVerificationState {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let (has_avx2, has_avx512) = (
            is_x86_feature_detected!("avx2"),
            is_x86_feature_detected!("avx512f"),
        );
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        let (has_avx2, has_avx512) = (false, false);

        if api().is_some() {
            if has_avx512 && self.len() >= 128 {
                self.verify_cpu_x86_simd(start_hash, 16, thread_pool)
            } else if has_avx2 && self.len() >= 48 {
                self.verify_cpu_x86_simd(start_hash, 8, thread_pool)
            } else {
                self.verify_cpu_generic(start_hash, thread_pool)
            }
        } else {
            self.verify_cpu_generic(start_hash, thread_pool)
        }
    }

    fn verify_tick_hash_count(&self, tick_hash_count: &mut u64, hashes_per_tick: u64) -> bool {
        // When hashes_per_tick is 0, hashing is disabled.
        if hashes_per_tick == 0 {
            return true;
        }

        for entry in self {
            *tick_hash_count = tick_hash_count.saturating_add(entry.num_hashes);
            if entry.is_tick() {
                if *tick_hash_count != hashes_per_tick {
                    warn!(
                        "invalid tick hash count!: entry: {entry:#?}, tick_hash_count: \
                         {tick_hash_count}, hashes_per_tick: {hashes_per_tick}"
                    );
                    return false;
                }
                *tick_hash_count = 0;
            }
        }
        *tick_hash_count < hashes_per_tick
    }

    fn tick_count(&self) -> u64 {
        self.iter().filter(|e| e.is_tick()).count() as u64
    }
}

pub fn next_entry_mut(start: &mut Hash, num_hashes: u64, transactions: Vec<Transaction>) -> Entry {
    let entry = Entry::new(start, num_hashes, transactions);
    *start = entry.hash;
    entry
}

pub fn create_ticks(num_ticks: u64, hashes_per_tick: u64, mut hash: Hash) -> Vec<Entry> {
    repeat_with(|| next_entry_mut(&mut hash, hashes_per_tick, vec![]))
        .take(num_ticks as usize)
        .collect()
}

pub fn create_random_ticks(num_ticks: u64, max_hashes_per_tick: u64, mut hash: Hash) -> Vec<Entry> {
    repeat_with(|| {
        let hashes_per_tick = thread_rng().gen_range(1..max_hashes_per_tick);
        next_entry_mut(&mut hash, hashes_per_tick, vec![])
    })
    .take(num_ticks as usize)
    .collect()
}

/// Creates the next Tick or Transaction Entry `num_hashes` after `start_hash`.
pub fn next_entry(prev_hash: &Hash, num_hashes: u64, transactions: Vec<Transaction>) -> Entry {
    let transactions = transactions.into_iter().map(Into::into).collect::<Vec<_>>();
    next_versioned_entry(prev_hash, num_hashes, transactions)
}

/// Creates the next Tick or Transaction Entry `num_hashes` after `start_hash`.
pub fn next_versioned_entry(
    prev_hash: &Hash,
    num_hashes: u64,
    transactions: Vec<VersionedTransaction>,
) -> Entry {
    assert!(num_hashes > 0 || transactions.is_empty());
    Entry {
        num_hashes,
        hash: next_hash(prev_hash, num_hashes, &transactions),
        transactions,
    }
}

pub fn thread_pool_for_tests() -> ThreadPool {
    // Allocate fewer threads for unit tests
    // Unit tests typically aren't creating massive blocks to verify, and
    // multiple tests could be running in parallel so any further parallelism
    // will do more harm than good
    rayon::ThreadPoolBuilder::new()
        .num_threads(4)
        .thread_name(|i| format!("solEntryTest{i:02}"))
        .build()
        .expect("new rayon threadpool")
}

#[cfg(feature = "dev-context-only-utils")]
pub fn thread_pool_for_benches() -> ThreadPool {
    rayon::ThreadPoolBuilder::new()
        .num_threads(num_cpus::get())
        .thread_name(|i| format!("solEntryBnch{i:02}"))
        .build()
        .expect("new rayon threadpool")
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        agave_reserved_account_keys::ReservedAccountKeys,
        rayon::ThreadPoolBuilder,
        solana_hash::Hash,
        solana_keypair::Keypair,
        solana_measure::measure::Measure,
        solana_message::SimpleAddressLoader,
        solana_perf::test_tx::test_tx,
        solana_pubkey::Pubkey,
        solana_runtime_transaction::runtime_transaction::RuntimeTransaction,
        solana_sha256_hasher::hash,
        solana_signer::Signer,
        solana_system_transaction as system_transaction,
        solana_transaction::{
            sanitized::{MessageHash, SanitizedTransaction},
            versioned::VersionedTransaction,
        },
        solana_transaction_error::TransactionResult as Result,
    };

    #[test]
    fn test_entry_verify() {
        let zero = Hash::default();
        let one = hash(zero.as_ref());
        assert!(Entry::new_tick(0, &zero).verify(&zero)); // base case, never used
        assert!(!Entry::new_tick(0, &zero).verify(&one)); // base case, bad
        assert!(next_entry(&zero, 1, vec![]).verify(&zero)); // inductive step
        assert!(!next_entry(&zero, 1, vec![]).verify(&one)); // inductive step, bad
    }

    fn test_verify_transactions<Tx: TransactionWithMeta + Send + Sync + 'static>(
        entries: Vec<Entry>,
        skip_verification: bool,
        thread_pool: &ThreadPool,
        verify: Arc<
            dyn Fn(VersionedTransaction, TransactionVerificationMode) -> Result<Tx> + Send + Sync,
        >,
    ) -> bool {
        let verify_func = {
            let verify = verify.clone();
            let verification_mode = if skip_verification {
                TransactionVerificationMode::HashOnly
            } else {
                TransactionVerificationMode::FullVerification
            };
            move |versioned_tx: VersionedTransaction| -> Result<Tx> {
                verify(versioned_tx, verification_mode)
            }
        };

        let cpu_verify_result =
            verify_transactions(entries.clone(), thread_pool, Arc::new(verify_func));

        cpu_verify_result.is_ok()
    }

    #[test]
    fn test_entry_transaction_verify() {
        let zero = Hash::default();

        // First, verify entries
        let keypair = Keypair::new();
        let tx0 = system_transaction::transfer(&keypair, &keypair.pubkey(), 0, zero);
        let tx1 = system_transaction::transfer(&keypair, &keypair.pubkey(), 1, zero);
        let e0 = Entry::new(&zero, 0, vec![tx0, tx1]);
        assert!(e0.verify(&zero));
        let tx2 = system_transaction::transfer(&keypair, &keypair.pubkey(), 2, zero);
        let tx3 = system_transaction::transfer(&keypair, &keypair.pubkey(), 3, zero);
        let e1 = Entry::new(&zero, 0, vec![tx2, tx3]);
        assert!(e1.verify(&zero));

        let es = vec![e0, e1];
        let thread_pool = ThreadPoolBuilder::new().build().unwrap();

        // Next, verify entry slice
        let verify_transaction = {
            move |versioned_tx: VersionedTransaction,
                  _mode: TransactionVerificationMode|
                  -> Result<RuntimeTransaction<SanitizedTransaction>> {
                let sanitized_tx = {
                    let message_hash = versioned_tx.verify_and_hash_message()?;
                    RuntimeTransaction::try_create(
                        versioned_tx,
                        MessageHash::Precomputed(message_hash),
                        None,
                        SimpleAddressLoader::Disabled,
                        &ReservedAccountKeys::empty_key_set(),
                        true,
                    )
                }?;

                sanitized_tx.verify()?;

                Ok(sanitized_tx)
            }
        };

        assert!(test_verify_transactions(
            es,
            false,
            &thread_pool,
            Arc::new(verify_transaction)
        ));
    }

    #[test]
    fn test_transaction_reorder_attack() {
        let zero = Hash::default();

        // First, verify entries
        let keypair = Keypair::new();
        let tx0 = system_transaction::transfer(&keypair, &keypair.pubkey(), 0, zero);
        let tx1 = system_transaction::transfer(&keypair, &keypair.pubkey(), 1, zero);
        let mut e0 = Entry::new(&zero, 0, vec![tx0.clone(), tx1.clone()]);
        assert!(e0.verify(&zero));

        // Next, swap two transactions and ensure verification fails.
        e0.transactions[0] = tx1.into(); // <-- attack
        e0.transactions[1] = tx0.into();
        assert!(!e0.verify(&zero));
    }

    #[test]
    fn test_transaction_signing() {
        let thread_pool = thread_pool_for_tests();

        use solana_signature::Signature;
        let zero = Hash::default();

        let keypair = Keypair::new();
        let tx0 = system_transaction::transfer(&keypair, &keypair.pubkey(), 0, zero);
        let tx1 = system_transaction::transfer(&keypair, &keypair.pubkey(), 1, zero);

        // Verify entry with 2 transactions
        let mut e0 = [Entry::new(&zero, 0, vec![tx0, tx1])];
        assert!(e0.verify(&zero, &thread_pool).status());

        // Clear signature of the first transaction, see that it does not verify
        let orig_sig = e0[0].transactions[0].signatures[0];
        e0[0].transactions[0].signatures[0] = Signature::default();
        assert!(!e0.verify(&zero, &thread_pool).status());

        // restore original signature
        e0[0].transactions[0].signatures[0] = orig_sig;
        assert!(e0.verify(&zero, &thread_pool).status());

        // Resize signatures and see verification fails.
        let len = e0[0].transactions[0].signatures.len();
        e0[0].transactions[0]
            .signatures
            .resize(len - 1, Signature::default());
        assert!(!e0.verify(&zero, &thread_pool).status());

        // Pass an entry with no transactions
        let e0 = [Entry::new(&zero, 0, vec![])];
        assert!(e0.verify(&zero, &thread_pool).status());
    }

    #[test]
    fn test_next_entry() {
        let zero = Hash::default();
        let tick = next_entry(&zero, 1, vec![]);
        assert_eq!(tick.num_hashes, 1);
        assert_ne!(tick.hash, zero);

        let tick = next_entry(&zero, 0, vec![]);
        assert_eq!(tick.num_hashes, 0);
        assert_eq!(tick.hash, zero);

        let keypair = Keypair::new();
        let tx0 = system_transaction::transfer(&keypair, &Pubkey::new_unique(), 42, zero);
        let entry0 = next_entry(&zero, 1, vec![tx0.clone()]);
        assert_eq!(entry0.num_hashes, 1);
        assert_eq!(entry0.hash, next_hash(&zero, 1, &[tx0.into()]));
    }

    #[test]
    #[should_panic]
    fn test_next_entry_panic() {
        let zero = Hash::default();
        let keypair = Keypair::new();
        let tx = system_transaction::transfer(&keypair, &keypair.pubkey(), 0, zero);
        next_entry(&zero, 0, vec![tx]);
    }

    #[test]
    fn test_verify_slice1() {
        agave_logger::setup();
        let thread_pool = thread_pool_for_tests();

        let zero = Hash::default();
        let one = hash(zero.as_ref());
        // base case
        assert!(vec![][..].verify(&zero, &thread_pool).status());
        // singleton case 1
        assert!(vec![Entry::new_tick(0, &zero)][..]
            .verify(&zero, &thread_pool)
            .status());
        // singleton case 2, bad
        assert!(!vec![Entry::new_tick(0, &zero)][..]
            .verify(&one, &thread_pool)
            .status());
        // inductive step
        assert!(vec![next_entry(&zero, 0, vec![]); 2][..]
            .verify(&zero, &thread_pool)
            .status());

        let mut bad_ticks = vec![next_entry(&zero, 0, vec![]); 2];
        bad_ticks[1].hash = one;
        // inductive step, bad
        assert!(!bad_ticks.verify(&zero, &thread_pool).status());
    }

    #[test]
    fn test_verify_slice_with_hashes1() {
        agave_logger::setup();
        let thread_pool = thread_pool_for_tests();

        let zero = Hash::default();
        let one = hash(zero.as_ref());
        let two = hash(one.as_ref());
        // base case
        assert!(vec![][..].verify(&one, &thread_pool).status());
        // singleton case 1
        assert!(vec![Entry::new_tick(1, &two)][..]
            .verify(&one, &thread_pool)
            .status());
        // singleton case 2, bad
        assert!(!vec![Entry::new_tick(1, &two)][..]
            .verify(&two, &thread_pool)
            .status());

        let mut ticks = vec![next_entry(&one, 1, vec![])];
        ticks.push(next_entry(&ticks.last().unwrap().hash, 1, vec![]));
        // inductive step
        assert!(ticks.verify(&one, &thread_pool).status());

        let mut bad_ticks = vec![next_entry(&one, 1, vec![])];
        bad_ticks.push(next_entry(&bad_ticks.last().unwrap().hash, 1, vec![]));
        bad_ticks[1].hash = one;
        // inductive step, bad
        assert!(!bad_ticks.verify(&one, &thread_pool).status());
    }

    #[test]
    fn test_verify_slice_with_hashes_and_transactions() {
        agave_logger::setup();
        let thread_pool = thread_pool_for_tests();

        let zero = Hash::default();
        let one = hash(zero.as_ref());
        let two = hash(one.as_ref());
        let alice_keypair = Keypair::new();
        let bob_keypair = Keypair::new();
        let tx0 = system_transaction::transfer(&alice_keypair, &bob_keypair.pubkey(), 1, one);
        let tx1 = system_transaction::transfer(&bob_keypair, &alice_keypair.pubkey(), 1, one);
        // base case
        assert!(vec![][..].verify(&one, &thread_pool).status());
        // singleton case 1
        assert!(vec![next_entry(&one, 1, vec![tx0.clone()])][..]
            .verify(&one, &thread_pool)
            .status());
        // singleton case 2, bad
        assert!(!vec![next_entry(&one, 1, vec![tx0.clone()])][..]
            .verify(&two, &thread_pool)
            .status());

        let mut ticks = vec![next_entry(&one, 1, vec![tx0.clone()])];
        ticks.push(next_entry(
            &ticks.last().unwrap().hash,
            1,
            vec![tx1.clone()],
        ));

        // inductive step
        assert!(ticks.verify(&one, &thread_pool).status());

        let mut bad_ticks = vec![next_entry(&one, 1, vec![tx0])];
        bad_ticks.push(next_entry(&bad_ticks.last().unwrap().hash, 1, vec![tx1]));
        bad_ticks[1].hash = one;
        // inductive step, bad
        assert!(!bad_ticks.verify(&one, &thread_pool).status());
    }

    #[test]
    fn test_verify_tick_hash_count() {
        let hashes_per_tick = 10;
        let tx = VersionedTransaction::default();

        let no_hash_tx_entry = Entry {
            transactions: vec![tx.clone()],
            ..Entry::default()
        };
        let single_hash_tx_entry = Entry {
            transactions: vec![tx.clone()],
            num_hashes: 1,
            ..Entry::default()
        };
        let partial_tx_entry = Entry {
            num_hashes: hashes_per_tick - 1,
            transactions: vec![tx.clone()],
            ..Entry::default()
        };
        let full_tx_entry = Entry {
            num_hashes: hashes_per_tick,
            transactions: vec![tx.clone()],
            ..Entry::default()
        };
        let max_hash_tx_entry = Entry {
            transactions: vec![tx],
            num_hashes: u64::MAX,
            ..Entry::default()
        };

        let no_hash_tick_entry = Entry::new_tick(0, &Hash::default());
        let single_hash_tick_entry = Entry::new_tick(1, &Hash::default());
        let partial_tick_entry = Entry::new_tick(hashes_per_tick - 1, &Hash::default());
        let full_tick_entry = Entry::new_tick(hashes_per_tick, &Hash::default());
        let max_hash_tick_entry = Entry::new_tick(u64::MAX, &Hash::default());

        // empty batch should succeed if hashes_per_tick hasn't been reached
        let mut tick_hash_count = 0;
        let mut entries = vec![];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, 0);

        // empty batch should fail if hashes_per_tick has been reached
        tick_hash_count = hashes_per_tick;
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, hashes_per_tick);
        tick_hash_count = 0;

        // validation is disabled when hashes_per_tick == 0
        entries = vec![max_hash_tx_entry.clone()];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, 0));
        assert_eq!(tick_hash_count, 0);

        // partial tick should fail
        entries = vec![partial_tick_entry.clone()];
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, hashes_per_tick - 1);
        tick_hash_count = 0;

        // full tick entry should succeed
        entries = vec![no_hash_tx_entry, full_tick_entry.clone()];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, 0);

        // oversized tick entry should fail
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick - 1));
        assert_eq!(tick_hash_count, hashes_per_tick);
        tick_hash_count = 0;

        // partial tx entry without tick entry should succeed
        entries = vec![partial_tx_entry];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, hashes_per_tick - 1);
        tick_hash_count = 0;

        // full tx entry with tick entry should succeed
        entries = vec![full_tx_entry.clone(), no_hash_tick_entry];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, 0);

        // full tx entry with oversized tick entry should fail
        entries = vec![full_tx_entry.clone(), single_hash_tick_entry.clone()];
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, hashes_per_tick + 1);
        tick_hash_count = 0;

        // full tx entry without tick entry should fail
        entries = vec![full_tx_entry];
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, hashes_per_tick);
        tick_hash_count = 0;

        // tx entry and a tick should succeed
        entries = vec![single_hash_tx_entry.clone(), partial_tick_entry];
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, 0);

        // many tx entries and a tick should succeed
        let tx_entries: Vec<Entry> = (0..hashes_per_tick - 1)
            .map(|_| single_hash_tx_entry.clone())
            .collect();
        entries = [tx_entries, vec![single_hash_tick_entry]].concat();
        assert!(entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, 0);

        // check overflow saturation should fail
        entries = vec![full_tick_entry.clone(), max_hash_tick_entry];
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, u64::MAX);
        tick_hash_count = 0;

        // check overflow saturation should fail
        entries = vec![max_hash_tx_entry, full_tick_entry];
        assert!(!entries.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick));
        assert_eq!(tick_hash_count, u64::MAX);
    }

    #[test]
    fn test_poh_verify_fuzz() {
        agave_logger::setup();
        for _ in 0..100 {
            let mut time = Measure::start("ticks");
            let num_ticks = thread_rng().gen_range(1..100);
            info!("create {num_ticks} ticks:");
            let mut entries = create_random_ticks(num_ticks, 100, Hash::default());
            time.stop();

            let mut modified = false;
            if thread_rng().gen_ratio(1, 2) {
                modified = true;
                let modify_idx = thread_rng().gen_range(0..num_ticks) as usize;
                entries[modify_idx].hash = hash(&[1, 2, 3]);
            }

            info!("done.. {time}");
            let mut time = Measure::start("poh");
            let res = entries
                .verify(&Hash::default(), &thread_pool_for_tests())
                .status();
            assert_eq!(res, !modified);
            time.stop();
            info!("{time} {res}");
        }
    }

    #[test]
    fn test_hash_transactions() {
        let mut transactions: Vec<_> = [test_tx(), test_tx(), test_tx()]
            .into_iter()
            .map(VersionedTransaction::from)
            .collect();

        // Test different permutations of the transactions have different final hashes.
        // i.e. that **order** of transactions is included in the hash.
        let hash1 = hash_transactions(&transactions);
        transactions.swap(0, 1);
        let hash2 = hash_transactions(&transactions);
        assert_ne!(hash1, hash2);
    }
}
