Files
lighthouse/validator_client/slashing_protection/src/interchange_test.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

324 lines
12 KiB
Rust

use crate::{
interchange::{Interchange, SignedAttestation, SignedBlock},
test_utils::{pubkey, DEFAULT_GENESIS_VALIDATORS_ROOT},
SigningRoot, SlashingDatabase,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use tempfile::tempdir;
use types::{Epoch, FixedBytesExtended, Hash256, PublicKeyBytes, Slot};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
pub struct MultiTestCase {
pub name: String,
pub genesis_validators_root: Hash256,
pub steps: Vec<TestCase>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
pub struct TestCase {
pub should_succeed: bool,
pub contains_slashable_data: bool,
pub interchange: Interchange,
pub blocks: Vec<TestBlock>,
pub attestations: Vec<TestAttestation>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
pub struct TestBlock {
pub pubkey: PublicKeyBytes,
pub slot: Slot,
pub signing_root: Hash256,
pub should_succeed: bool,
pub should_succeed_complete: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "arbitrary-fuzz", derive(arbitrary::Arbitrary))]
pub struct TestAttestation {
pub pubkey: PublicKeyBytes,
pub source_epoch: Epoch,
pub target_epoch: Epoch,
pub signing_root: Hash256,
pub should_succeed: bool,
pub should_succeed_complete: bool,
}
impl MultiTestCase {
pub fn new(name: &str, steps: Vec<TestCase>) -> Self {
MultiTestCase {
name: name.into(),
genesis_validators_root: DEFAULT_GENESIS_VALIDATORS_ROOT,
steps,
}
}
pub fn single(name: &str, test_case: TestCase) -> Self {
Self::new(name, vec![test_case])
}
pub fn gvr(mut self, genesis_validators_root: Hash256) -> Self {
self.genesis_validators_root = genesis_validators_root;
self
}
pub fn run(&self, minify: bool) {
let dir = tempdir().unwrap();
let slashing_db_file = dir.path().join("slashing_protection.sqlite");
let slashing_db = SlashingDatabase::create(&slashing_db_file).unwrap();
for test_case in &self.steps {
// If the test case is marked as containing slashable data, then the spec allows us to
// fail to import the file. However, we minify on import and ignore slashable data, so
// we should be capable of importing no matter what.
let allow_import_failure = false;
let interchange = if minify {
let minified = test_case.interchange.minify().unwrap();
check_minification_invariants(&test_case.interchange, &minified);
minified
} else {
test_case.interchange.clone()
};
match slashing_db.import_interchange_info(interchange, self.genesis_validators_root) {
Ok(import_outcomes) => {
let none_failed = import_outcomes.iter().all(|o| !o.failed());
assert!(
none_failed,
"test `{}` failed to import some records: {:#?}",
self.name, import_outcomes
);
if !test_case.should_succeed {
panic!(
"test `{}` succeeded on import when it should have failed",
self.name
);
}
}
Err(e) => {
if test_case.should_succeed && !allow_import_failure {
panic!(
"test `{}` failed on import when it should have succeeded, error: {:?}",
self.name, e
);
}
break;
}
}
for (i, block) in test_case.blocks.iter().enumerate() {
match slashing_db.check_and_insert_block_signing_root(
&block.pubkey,
block.slot,
SigningRoot::from(block.signing_root),
) {
Ok(safe) if !block.should_succeed => {
panic!(
"block {} from `{}` succeeded when it should have failed: {:?}",
i, self.name, safe
);
}
Err(e) if block.should_succeed => {
panic!(
"block {} from `{}` failed when it should have succeeded: {:?}",
i, self.name, e
);
}
_ => (),
}
}
for (i, att) in test_case.attestations.iter().enumerate() {
match slashing_db.check_and_insert_attestation_signing_root(
&att.pubkey,
att.source_epoch,
att.target_epoch,
SigningRoot::from(att.signing_root),
) {
Ok(safe) if !att.should_succeed => {
panic!(
"attestation {} from `{}` succeeded when it should have failed: {:?}",
i, self.name, safe
);
}
Err(e) if att.should_succeed => {
panic!(
"attestation {} from `{}` failed when it should have succeeded: {:?}",
i, self.name, e
);
}
_ => (),
}
}
}
}
}
impl TestCase {
pub fn new(interchange: Interchange) -> Self {
TestCase {
should_succeed: true,
contains_slashable_data: false,
interchange,
blocks: vec![],
attestations: vec![],
}
}
pub fn should_fail(mut self) -> Self {
self.should_succeed = false;
self
}
pub fn contains_slashable_data(mut self) -> Self {
self.contains_slashable_data = true;
self
}
pub fn with_blocks(self, blocks: impl IntoIterator<Item = (usize, u64, bool, bool)>) -> Self {
self.with_signing_root_blocks(blocks.into_iter().map(
|(index, slot, should_succeed, should_succeed_complete)| {
(index, slot, 0, should_succeed, should_succeed_complete)
},
))
}
pub fn with_signing_root_blocks(
mut self,
blocks: impl IntoIterator<Item = (usize, u64, u64, bool, bool)>,
) -> Self {
self.blocks.extend(blocks.into_iter().map(
|(pk, slot, signing_root, should_succeed, should_succeed_complete)| {
assert!(
!should_succeed || should_succeed_complete,
"if should_succeed is true then should_succeed_complete must also be true"
);
TestBlock {
pubkey: pubkey(pk),
slot: Slot::new(slot),
signing_root: Hash256::from_low_u64_be(signing_root),
should_succeed,
should_succeed_complete,
}
},
));
self
}
pub fn with_attestations(
self,
attestations: impl IntoIterator<Item = (usize, u64, u64, bool, bool)>,
) -> Self {
self.with_signing_root_attestations(attestations.into_iter().map(
|(id, source, target, succeed, succeed_complete)| {
(id, source, target, 0, succeed, succeed_complete)
},
))
}
pub fn with_signing_root_attestations(
mut self,
attestations: impl IntoIterator<Item = (usize, u64, u64, u64, bool, bool)>,
) -> Self {
self.attestations.extend(attestations.into_iter().map(
|(pk, source, target, signing_root, should_succeed, should_succeed_complete)| {
assert!(
!should_succeed || should_succeed_complete,
"if should_succeed is true then should_succeed_complete must also be true"
);
TestAttestation {
pubkey: pubkey(pk),
source_epoch: Epoch::new(source),
target_epoch: Epoch::new(target),
signing_root: Hash256::from_low_u64_be(signing_root),
should_succeed,
should_succeed_complete,
}
},
));
self
}
}
pub fn check_minification_invariants(interchange: &Interchange, minified: &Interchange) {
// Metadata should be unchanged.
assert_eq!(interchange.metadata, minified.metadata);
// Minified data should contain one entry per *unique* public key.
let uniq_pubkeys = get_uniq_pubkeys(interchange);
assert_eq!(uniq_pubkeys, get_uniq_pubkeys(minified));
assert_eq!(uniq_pubkeys.len(), minified.data.len());
for &pubkey in uniq_pubkeys.iter() {
// Minified data should contain 1 block per validator, unless the validator never signed any
// blocks. All of those blocks should have slots <= the slot of the minified block.
let original_blocks = get_blocks_of_validator(interchange, pubkey);
let minified_blocks = get_blocks_of_validator(minified, pubkey);
if original_blocks.is_empty() {
assert!(minified_blocks.is_empty());
} else {
// Should have exactly 1 block.
assert_eq!(minified_blocks.len(), 1);
// That block should have no signing root (it's synthetic).
let mini_block = minified_blocks.first().unwrap();
assert_eq!(mini_block.signing_root, None);
// All original blocks should have slots <= the mini block.
assert!(original_blocks
.iter()
.all(|block| block.slot <= mini_block.slot));
}
// Minified data should contain 1 attestation per validator, unless the validator never
// signed any attestations. All attestations should have source and target <= the source
// and target of the minified attestation.
let original_attestations = get_attestations_of_validator(interchange, pubkey);
let minified_attestations = get_attestations_of_validator(minified, pubkey);
if original_attestations.is_empty() {
assert!(minified_attestations.is_empty());
} else {
assert_eq!(minified_attestations.len(), 1);
let mini_attestation = minified_attestations.first().unwrap();
assert_eq!(mini_attestation.signing_root, None);
assert!(original_attestations
.iter()
.all(|att| att.source_epoch <= mini_attestation.source_epoch
&& att.target_epoch <= mini_attestation.target_epoch));
}
}
}
fn get_uniq_pubkeys(interchange: &Interchange) -> HashSet<PublicKeyBytes> {
interchange.data.iter().map(|data| data.pubkey).collect()
}
fn get_blocks_of_validator(interchange: &Interchange, pubkey: PublicKeyBytes) -> Vec<&SignedBlock> {
interchange
.data
.iter()
.filter(|data| data.pubkey == pubkey)
.flat_map(|data| data.signed_blocks.iter())
.collect()
}
fn get_attestations_of_validator(
interchange: &Interchange,
pubkey: PublicKeyBytes,
) -> Vec<&SignedAttestation> {
interchange
.data
.iter()
.filter(|data| data.pubkey == pubkey)
.flat_map(|data| data.signed_attestations.iter())
.collect()
}