Files
lighthouse/validator_client/slashing_protection/src/test_utils.rs
Eitan Seri-Levi 99e53b88c3 Migrate from ethereum-types to alloy-primitives (#6078)
* Remove use of ethers_core::RlpStream

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into remove_use_of_ethers_core

* Remove old code

* Simplify keccak call

* Remove unused package

* Merge branch 'unstable' of https://github.com/ethDreamer/lighthouse into remove_use_of_ethers_core

* Merge branch 'unstable' into remove_use_of_ethers_core

* Run clippy

* Merge branch 'remove_use_of_ethers_core' of https://github.com/dospore/lighthouse into remove_use_of_ethers_core

* Check all cargo fmt

* migrate to alloy primitives init

* fix deps

* integrate alloy-primitives

* resolve dep issues

* more changes based on dep changes

* add TODOs

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into remove_use_of_ethers_core

* Revert lock

* Add BeaconBlocksByRange v3

* continue migration

* Revert "Add BeaconBlocksByRange v3"

This reverts commit e3ce7fc5ea.

* impl hash256 extended trait

* revert some uneeded diffs

* merge conflict resolved

* fix subnet id rshift calc

* rename to FixedBytesExtended

* debugging

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into migrate-to-alloy-primitives

* fix failed test

* fixing more tests

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into remove_use_of_ethers_core

* introduce a shim to convert between the two u256 types

* move alloy to wrokspace

* align alloy versions

* update

* update web3signer test certs

* refactor

* resolve failing tests

* linting

* fix graffiti string test

* fmt

* fix ef test

* resolve merge conflicts

* remove udep and revert cert

* cargo patch

* cyclic dep

* fix build error

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into migrate-to-alloy-primitives

* resolve conflicts, update deps

* merge unstable

* fmt

* fix deps

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into migrate-to-alloy-primitives

* resolve merge conflicts

* resolve conflicts, make necessary changes

* Remove patch

* fmt

* remove file

* merge conflicts

* sneaking in a smol change

* bump versions

* Merge remote-tracking branch 'origin/unstable' into migrate-to-alloy-primitives

* Updates for peerDAS

* Update ethereum_hashing to prevent dupe

* updated alloy-consensus, removed TODOs

* cargo update

* endianess fix

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into migrate-to-alloy-primitives

* fmt

* fix merge

* fix test

* fixed_bytes crate

* minor fixes

* convert u256 to i64

* panic free mixin to_low_u64_le

* from_str_radix

* computbe_subnet api and ensuring we use big-endian

* Merge branch 'unstable' of https://github.com/sigp/lighthouse into migrate-to-alloy-primitives

* fix test

* Simplify subnet_id test

* Simplify some more tests

* Add tests to fixed_bytes crate

* Merge branch 'unstable' into migrate-to-alloy-primitives
2024-09-02 08:03:24 +00:00

160 lines
4.9 KiB
Rust

use crate::*;
use tempfile::{tempdir, TempDir};
use types::{test_utils::generate_deterministic_keypair, AttestationData, BeaconBlockHeader};
pub const DEFAULT_VALIDATOR_INDEX: usize = 0;
pub const DEFAULT_DOMAIN: Hash256 = Hash256::ZERO;
pub const DEFAULT_GENESIS_VALIDATORS_ROOT: Hash256 = Hash256::ZERO;
pub fn pubkey(index: usize) -> PublicKeyBytes {
generate_deterministic_keypair(index).pk.compress()
}
pub struct Test<T> {
pubkey: PublicKeyBytes,
data: T,
domain: Hash256,
expected: Result<Safe, NotSafe>,
}
impl<T> Test<T> {
pub fn single(data: T) -> Self {
Self::with_pubkey(pubkey(DEFAULT_VALIDATOR_INDEX), data)
}
pub fn with_pubkey(pubkey: PublicKeyBytes, data: T) -> Self {
Self {
pubkey,
data,
domain: DEFAULT_DOMAIN,
expected: Ok(Safe::Valid),
}
}
pub fn with_domain(mut self, domain: Hash256) -> Self {
self.domain = domain;
self
}
pub fn expect_result(mut self, result: Result<Safe, NotSafe>) -> Self {
self.expected = result;
self
}
pub fn expect_invalid_att(self, error: InvalidAttestation) -> Self {
self.expect_result(Err(NotSafe::InvalidAttestation(error)))
}
pub fn expect_invalid_block(self, error: InvalidBlock) -> Self {
self.expect_result(Err(NotSafe::InvalidBlock(error)))
}
pub fn expect_same_data(self) -> Self {
self.expect_result(Ok(Safe::SameData))
}
}
pub struct StreamTest<T> {
/// Validators to register.
pub registered_validators: Vec<PublicKeyBytes>,
/// Vector of cases and the value expected when calling `check_and_insert_X`.
pub cases: Vec<Test<T>>,
}
impl<T> Default for StreamTest<T> {
fn default() -> Self {
Self {
registered_validators: vec![pubkey(DEFAULT_VALIDATOR_INDEX)],
cases: vec![],
}
}
}
impl StreamTest<AttestationData> {
pub fn run(&self) {
let dir = tempdir().unwrap();
let slashing_db_file = dir.path().join("slashing_protection.sqlite");
let slashing_db = SlashingDatabase::create(&slashing_db_file).unwrap();
for pubkey in &self.registered_validators {
slashing_db.register_validator(*pubkey).unwrap();
}
check_registration_invariants(&slashing_db, &self.registered_validators);
for (i, test) in self.cases.iter().enumerate() {
assert_eq!(
slashing_db.check_and_insert_attestation(&test.pubkey, &test.data, test.domain),
test.expected,
"attestation {} not processed as expected",
i
);
}
roundtrip_database(&dir, &slashing_db, self.registered_validators.is_empty());
}
}
impl StreamTest<BeaconBlockHeader> {
pub fn run(&self) {
let dir = tempdir().unwrap();
let slashing_db_file = dir.path().join("slashing_protection.sqlite");
let slashing_db = SlashingDatabase::create(&slashing_db_file).unwrap();
for pubkey in &self.registered_validators {
slashing_db.register_validator(*pubkey).unwrap();
}
check_registration_invariants(&slashing_db, &self.registered_validators);
for (i, test) in self.cases.iter().enumerate() {
assert_eq!(
slashing_db.check_and_insert_block_proposal(&test.pubkey, &test.data, test.domain),
test.expected,
"attestation {} not processed as expected",
i
);
}
roundtrip_database(&dir, &slashing_db, self.registered_validators.is_empty());
}
}
// This function roundtrips the database, but applies minification in order to be compatible with
// the implicit minification done on import.
fn roundtrip_database(dir: &TempDir, db: &SlashingDatabase, is_empty: bool) {
let exported = db
.export_all_interchange_info(DEFAULT_GENESIS_VALIDATORS_ROOT)
.unwrap();
let new_db =
SlashingDatabase::create(&dir.path().join("roundtrip_slashing_protection.sqlite")).unwrap();
new_db
.import_interchange_info(exported.clone(), DEFAULT_GENESIS_VALIDATORS_ROOT)
.unwrap();
let reexported = new_db
.export_all_interchange_info(DEFAULT_GENESIS_VALIDATORS_ROOT)
.unwrap();
assert!(exported
.minify()
.unwrap()
.equiv(&reexported.minify().unwrap()));
assert_eq!(is_empty, exported.is_empty());
}
fn check_registration_invariants(
slashing_db: &SlashingDatabase,
registered_validators: &[PublicKeyBytes],
) {
slashing_db
.check_validator_registrations(registered_validators.iter())
.unwrap();
let registered_list = slashing_db
.with_transaction(|txn| slashing_db.list_all_registered_validators(txn))
.unwrap()
.into_iter()
.map(|(_, pubkey)| pubkey)
.collect::<Vec<_>>();
assert_eq!(registered_validators, registered_list);
}