superstruct the AttesterSlashing (#5636)

* `superstruct` Attester Fork Variants

* Push a little further

* Deal with Encode / Decode of AttesterSlashing

* not so sure about this..

* Stop Encode/Decode Bounds from Propagating Out

* Tons of Changes..

* More Conversions to AttestationRef

* Add AsReference trait (#15)

* Add AsReference trait

* Fix some snafus

* Got it Compiling! :D

* Got Tests Building

* Get beacon chain tests compiling

---------

Co-authored-by: Michael Sproul <micsproul@gmail.com>
This commit is contained in:
ethDreamer
2024-05-02 18:00:21 -05:00
committed by GitHub
parent 3b7132bc0d
commit e6c7f145dd
53 changed files with 1405 additions and 437 deletions

View File

@@ -25,14 +25,14 @@ pub fn get_attesting_indices<E: EthSpec>(
/// Shortcut for getting the attesting indices while fetching the committee from the state's cache.
pub fn get_attesting_indices_from_state<E: EthSpec>(
state: &BeaconState<E>,
att: &Attestation<E>,
att: AttestationRef<E>,
) -> Result<Vec<u64>, BeaconStateError> {
let committee = state.get_beacon_committee(att.data().slot, att.data().index)?;
match att {
Attestation::Base(att) => {
AttestationRef::Base(att) => {
get_attesting_indices::<E>(committee.committee, &att.aggregation_bits)
}
// TODO(electra) implement get_attesting_indices for electra
Attestation::Electra(_) => todo!(),
AttestationRef::Electra(_) => todo!(),
}
}

View File

@@ -9,12 +9,12 @@ type Result<T> = std::result::Result<T, BlockOperationError<Invalid>>;
/// Spec v0.12.1
pub fn get_indexed_attestation<E: EthSpec>(
committee: &[usize],
attestation: &Attestation<E>,
attestation: AttestationRef<E>,
) -> Result<IndexedAttestation<E>> {
let attesting_indices = match attestation {
Attestation::Base(att) => get_attesting_indices::<E>(committee, &att.aggregation_bits)?,
AttestationRef::Base(att) => get_attesting_indices::<E>(committee, &att.aggregation_bits)?,
// TODO(electra) implement get_attesting_indices for electra
Attestation::Electra(_) => todo!(),
AttestationRef::Electra(_) => todo!(),
};
Ok(IndexedAttestation::Base(IndexedAttestationBase {

View File

@@ -4,8 +4,9 @@ use crate::EpochCacheError;
use std::collections::{hash_map::Entry, HashMap};
use tree_hash::TreeHash;
use types::{
AbstractExecPayload, Attestation, AttestationData, BeaconState, BeaconStateError, BitList,
ChainSpec, Epoch, EthSpec, Hash256, IndexedAttestation, SignedBeaconBlock, Slot,
AbstractExecPayload, AttestationData, AttestationRef, BeaconState, BeaconStateError, BitList,
ChainSpec, Epoch, EthSpec, Hash256, IndexedAttestation, IndexedAttestationRef,
SignedBeaconBlock, Slot,
};
#[derive(Debug, PartialEq, Clone)]
@@ -153,13 +154,13 @@ impl<E: EthSpec> ConsensusContext<E> {
}
}
pub fn get_indexed_attestation(
&mut self,
pub fn get_indexed_attestation<'a>(
&'a mut self,
state: &BeaconState<E>,
attestation: &Attestation<E>,
) -> Result<&IndexedAttestation<E>, BlockOperationError<AttestationInvalid>> {
attestation: AttestationRef<'a, E>,
) -> Result<IndexedAttestationRef<E>, BlockOperationError<AttestationInvalid>> {
let aggregation_bits = match attestation {
Attestation::Base(attn) => {
AttestationRef::Base(attn) => {
let mut extended_aggregation_bits: BitList<E::MaxValidatorsPerCommitteePerSlot> =
BitList::with_capacity(attn.aggregation_bits.len())
.map_err(BeaconStateError::from)?;
@@ -171,7 +172,7 @@ impl<E: EthSpec> ConsensusContext<E> {
}
extended_aggregation_bits
}
Attestation::Electra(attn) => attn.aggregation_bits.clone(),
AttestationRef::Electra(attn) => attn.aggregation_bits.clone(),
};
let key = (attestation.data().clone(), aggregation_bits);
@@ -186,6 +187,7 @@ impl<E: EthSpec> ConsensusContext<E> {
Ok(vacant.insert(indexed_attestation))
}
}
.map(|indexed_attestation| (*indexed_attestation).to_ref())
}
pub fn num_cached_indexed_attestations(&self) -> usize {

View File

@@ -45,4 +45,4 @@ pub use per_epoch_processing::{
};
pub use per_slot_processing::{per_slot_processing, Error as SlotProcessingError};
pub use types::{EpochCache, EpochCacheError, EpochCacheKey};
pub use verify_operation::{SigVerifiedOp, VerifyOperation, VerifyOperationAt};
pub use verify_operation::{SigVerifiedOp, TransformPersist, VerifyOperation, VerifyOperationAt};

View File

@@ -247,13 +247,12 @@ where
) -> Result<()> {
self.sets
.sets
.reserve(block.message().body().attester_slashings().len() * 2);
.reserve(block.message().body().attester_slashings_len() * 2);
block
.message()
.body()
.attester_slashings()
.iter()
.try_for_each(|attester_slashing| {
let (set_1, set_2) = attester_slashing_signature_sets(
self.state,
@@ -277,13 +276,12 @@ where
) -> Result<()> {
self.sets
.sets
.reserve(block.message().body().attestations().len());
.reserve(block.message().body().attestations_len());
block
.message()
.body()
.attestations()
.iter()
.try_for_each(|attestation| {
let indexed_attestation = ctxt.get_indexed_attestation(self.state, attestation)?;

View File

@@ -13,7 +13,7 @@ fn error(reason: Invalid) -> BlockOperationError<Invalid> {
/// Verify an `IndexedAttestation`.
pub fn is_valid_indexed_attestation<E: EthSpec>(
state: &BeaconState<E>,
indexed_attestation: &IndexedAttestation<E>,
indexed_attestation: IndexedAttestationRef<E>,
verify_signatures: VerifySignatures,
spec: &ChainSpec,
) -> Result<()> {

View File

@@ -46,13 +46,16 @@ pub mod base {
///
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
pub fn process_attestations<E: EthSpec>(
pub fn process_attestations<'a, E: EthSpec, I>(
state: &mut BeaconState<E>,
attestations: &[Attestation<E>],
attestations: I,
verify_signatures: VerifySignatures,
ctxt: &mut ConsensusContext<E>,
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
) -> Result<(), BlockProcessingError>
where
I: Iterator<Item = AttestationRef<'a, E>>,
{
// Ensure required caches are all built. These should be no-ops during regular operation.
state.build_committee_cache(RelativeEpoch::Current, spec)?;
state.build_committee_cache(RelativeEpoch::Previous, spec)?;
@@ -63,7 +66,7 @@ pub mod base {
let proposer_index = ctxt.get_proposer_index(state, spec)?;
// Verify and apply each attestation.
for (i, attestation) in attestations.iter().enumerate() {
for (i, attestation) in attestations.enumerate() {
verify_attestation_for_block_inclusion(
state,
attestation,
@@ -74,7 +77,7 @@ pub mod base {
.map_err(|e| e.into_with_index(i))?;
match attestation {
Attestation::Base(att) => {
AttestationRef::Base(att) => {
let pending_attestation = PendingAttestation {
aggregation_bits: att.aggregation_bits.clone(),
data: att.data.clone(),
@@ -94,7 +97,7 @@ pub mod base {
.push(pending_attestation)?;
}
}
Attestation::Electra(_) => {
AttestationRef::Electra(_) => {
// TODO(electra) pending attestations are only phase 0
// so we should just raise a relevant error here
todo!()
@@ -110,24 +113,24 @@ pub mod altair_deneb {
use super::*;
use crate::common::update_progressive_balances_cache::update_progressive_balances_on_attestation;
pub fn process_attestations<E: EthSpec>(
pub fn process_attestations<'a, E: EthSpec, I>(
state: &mut BeaconState<E>,
attestations: &[Attestation<E>],
attestations: I,
verify_signatures: VerifySignatures,
ctxt: &mut ConsensusContext<E>,
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
attestations
.iter()
.enumerate()
.try_for_each(|(i, attestation)| {
process_attestation(state, attestation, i, ctxt, verify_signatures, spec)
})
) -> Result<(), BlockProcessingError>
where
I: Iterator<Item = AttestationRef<'a, E>>,
{
attestations.enumerate().try_for_each(|(i, attestation)| {
process_attestation(state, attestation, i, ctxt, verify_signatures, spec)
})
}
pub fn process_attestation<E: EthSpec>(
state: &mut BeaconState<E>,
attestation: &Attestation<E>,
attestation: AttestationRef<E>,
att_index: usize,
ctxt: &mut ConsensusContext<E>,
verify_signatures: VerifySignatures,
@@ -238,16 +241,19 @@ pub fn process_proposer_slashings<E: EthSpec>(
///
/// Returns `Ok(())` if the validation and state updates completed successfully, otherwise returns
/// an `Err` describing the invalid object or cause of failure.
pub fn process_attester_slashings<E: EthSpec>(
pub fn process_attester_slashings<'a, E: EthSpec, I>(
state: &mut BeaconState<E>,
attester_slashings: &[AttesterSlashing<E>],
attester_slashings: I,
verify_signatures: VerifySignatures,
ctxt: &mut ConsensusContext<E>,
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
) -> Result<(), BlockProcessingError>
where
I: Iterator<Item = AttesterSlashingRef<'a, E>>,
{
state.build_slashings_cache()?;
for (i, attester_slashing) in attester_slashings.iter().enumerate() {
for (i, attester_slashing) in attester_slashings.enumerate() {
let slashable_indices =
verify_attester_slashing(state, attester_slashing, verify_signatures, spec)
.map_err(|e| e.into_with_index(i))?;

View File

@@ -7,10 +7,10 @@ use ssz::DecodeError;
use std::borrow::Cow;
use tree_hash::TreeHash;
use types::{
AbstractExecPayload, AggregateSignature, AttesterSlashing, BeaconBlockRef, BeaconState,
AbstractExecPayload, AggregateSignature, AttesterSlashingRef, BeaconBlockRef, BeaconState,
BeaconStateError, ChainSpec, DepositData, Domain, Epoch, EthSpec, Fork, Hash256,
InconsistentFork, IndexedAttestation, ProposerSlashing, PublicKey, PublicKeyBytes, Signature,
SignedAggregateAndProof, SignedBeaconBlock, SignedBeaconBlockHeader,
InconsistentFork, IndexedAttestation, IndexedAttestationRef, ProposerSlashing, PublicKey,
PublicKeyBytes, Signature, SignedAggregateAndProof, SignedBeaconBlock, SignedBeaconBlockHeader,
SignedBlsToExecutionChange, SignedContributionAndProof, SignedRoot, SignedVoluntaryExit,
SigningData, Slot, SyncAggregate, SyncAggregatorSelectionData, Unsigned,
};
@@ -272,7 +272,7 @@ pub fn indexed_attestation_signature_set<'a, 'b, E, F>(
state: &'a BeaconState<E>,
get_pubkey: F,
signature: &'a AggregateSignature,
indexed_attestation: &'b IndexedAttestation<E>,
indexed_attestation: IndexedAttestationRef<'b, E>,
spec: &'a ChainSpec,
) -> Result<SignatureSet<'a>>
where
@@ -335,7 +335,7 @@ where
pub fn attester_slashing_signature_sets<'a, E, F>(
state: &'a BeaconState<E>,
get_pubkey: F,
attester_slashing: &'a AttesterSlashing<E>,
attester_slashing: AttesterSlashingRef<'a, E>,
spec: &'a ChainSpec,
) -> Result<(SignatureSet<'a>, SignatureSet<'a>)>
where
@@ -346,15 +346,15 @@ where
indexed_attestation_signature_set(
state,
get_pubkey.clone(),
attester_slashing.attestation_1.signature(),
&attester_slashing.attestation_1,
attester_slashing.attestation_1().signature(),
attester_slashing.attestation_1(),
spec,
)?,
indexed_attestation_signature_set(
state,
get_pubkey,
attester_slashing.attestation_2.signature(),
&attester_slashing.attestation_2,
attester_slashing.attestation_2().signature(),
attester_slashing.attestation_2(),
spec,
)?,
))

View File

@@ -388,7 +388,12 @@ async fn invalid_attestation_no_committee_for_index() {
.clone()
.deconstruct()
.0;
head_block.to_mut().body_mut().attestations_mut()[0]
head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.data_mut()
.index += 1;
let mut ctxt = ConsensusContext::new(state.slot());
@@ -423,10 +428,21 @@ async fn invalid_attestation_wrong_justified_checkpoint() {
.clone()
.deconstruct()
.0;
let old_justified_checkpoint = head_block.body().attestations()[0].data().source;
let old_justified_checkpoint = head_block
.body()
.attestations()
.next()
.unwrap()
.data()
.source;
let mut new_justified_checkpoint = old_justified_checkpoint;
new_justified_checkpoint.epoch += Epoch::new(1);
head_block.to_mut().body_mut().attestations_mut()[0]
head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.data_mut()
.source = new_justified_checkpoint;
@@ -467,7 +483,12 @@ async fn invalid_attestation_bad_aggregation_bitfield_len() {
.clone()
.deconstruct()
.0;
*head_block.to_mut().body_mut().attestations_mut()[0]
*head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.aggregation_bits_base_mut()
.unwrap() = Bitfield::with_capacity(spec.target_committee_size).unwrap();
@@ -502,8 +523,13 @@ async fn invalid_attestation_bad_signature() {
.clone()
.deconstruct()
.0;
*head_block.to_mut().body_mut().attestations_mut()[0].signature_mut() =
AggregateSignature::empty();
*head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.signature_mut() = AggregateSignature::empty();
let mut ctxt = ConsensusContext::new(state.slot());
let result = process_operations::process_attestations(
@@ -538,9 +564,14 @@ async fn invalid_attestation_included_too_early() {
.clone()
.deconstruct()
.0;
let new_attesation_slot = head_block.body().attestations()[0].data().slot
let new_attesation_slot = head_block.body().attestations().next().unwrap().data().slot
+ Slot::new(MainnetEthSpec::slots_per_epoch());
head_block.to_mut().body_mut().attestations_mut()[0]
head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.data_mut()
.slot = new_attesation_slot;
@@ -581,9 +612,14 @@ async fn invalid_attestation_included_too_late() {
.clone()
.deconstruct()
.0;
let new_attesation_slot = head_block.body().attestations()[0].data().slot
let new_attesation_slot = head_block.body().attestations().next().unwrap().data().slot
- Slot::new(MainnetEthSpec::slots_per_epoch());
head_block.to_mut().body_mut().attestations_mut()[0]
head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.data_mut()
.slot = new_attesation_slot;
@@ -621,7 +657,12 @@ async fn invalid_attestation_target_epoch_slot_mismatch() {
.clone()
.deconstruct()
.0;
head_block.to_mut().body_mut().attestations_mut()[0]
head_block
.to_mut()
.body_mut()
.attestations_mut()
.next()
.unwrap()
.data_mut()
.target
.epoch += Epoch::new(1);
@@ -657,7 +698,7 @@ async fn valid_insert_attester_slashing() {
let mut ctxt = ConsensusContext::new(state.slot());
let result = process_operations::process_attester_slashings(
&mut state,
&[attester_slashing],
[attester_slashing.to_ref()].into_iter(),
VerifySignatures::True,
&mut ctxt,
&spec,
@@ -673,13 +714,20 @@ async fn invalid_attester_slashing_not_slashable() {
let harness = get_harness::<MainnetEthSpec>(EPOCH_OFFSET, VALIDATOR_COUNT).await;
let mut attester_slashing = harness.make_attester_slashing(vec![1, 2]);
attester_slashing.attestation_1 = attester_slashing.attestation_2.clone();
match &mut attester_slashing {
AttesterSlashing::Base(ref mut attester_slashing) => {
attester_slashing.attestation_1 = attester_slashing.attestation_2.clone();
}
AttesterSlashing::Electra(ref mut attester_slashing) => {
attester_slashing.attestation_1 = attester_slashing.attestation_2.clone();
}
}
let mut state = harness.get_current_state();
let mut ctxt = ConsensusContext::new(state.slot());
let result = process_operations::process_attester_slashings(
&mut state,
&[attester_slashing],
[attester_slashing.to_ref()].into_iter(),
VerifySignatures::True,
&mut ctxt,
&spec,
@@ -701,16 +749,20 @@ async fn invalid_attester_slashing_1_invalid() {
let harness = get_harness::<MainnetEthSpec>(EPOCH_OFFSET, VALIDATOR_COUNT).await;
let mut attester_slashing = harness.make_attester_slashing(vec![1, 2]);
*attester_slashing
.attestation_1
.attesting_indices_base_mut()
.unwrap() = VariableList::from(vec![2, 1]);
match &mut attester_slashing {
AttesterSlashing::Base(ref mut attester_slashing) => {
attester_slashing.attestation_1.attesting_indices = VariableList::from(vec![2, 1]);
}
AttesterSlashing::Electra(ref mut attester_slashing) => {
attester_slashing.attestation_1.attesting_indices = VariableList::from(vec![2, 1]);
}
}
let mut state = harness.get_current_state();
let mut ctxt = ConsensusContext::new(state.slot());
let result = process_operations::process_attester_slashings(
&mut state,
&[attester_slashing],
[attester_slashing.to_ref()].into_iter(),
VerifySignatures::True,
&mut ctxt,
&spec,
@@ -735,16 +787,20 @@ async fn invalid_attester_slashing_2_invalid() {
let harness = get_harness::<MainnetEthSpec>(EPOCH_OFFSET, VALIDATOR_COUNT).await;
let mut attester_slashing = harness.make_attester_slashing(vec![1, 2]);
*attester_slashing
.attestation_2
.attesting_indices_base_mut()
.unwrap() = VariableList::from(vec![2, 1]);
match &mut attester_slashing {
AttesterSlashing::Base(ref mut attester_slashing) => {
attester_slashing.attestation_2.attesting_indices = VariableList::from(vec![2, 1]);
}
AttesterSlashing::Electra(ref mut attester_slashing) => {
attester_slashing.attestation_2.attesting_indices = VariableList::from(vec![2, 1]);
}
}
let mut state = harness.get_current_state();
let mut ctxt = ConsensusContext::new(state.slot());
let result = process_operations::process_attester_slashings(
&mut state,
&[attester_slashing],
[attester_slashing.to_ref()].into_iter(),
VerifySignatures::True,
&mut ctxt,
&spec,

View File

@@ -17,11 +17,11 @@ fn error(reason: Invalid) -> BlockOperationError<Invalid> {
/// Optionally verifies the aggregate signature, depending on `verify_signatures`.
pub fn verify_attestation_for_block_inclusion<'ctxt, E: EthSpec>(
state: &BeaconState<E>,
attestation: &Attestation<E>,
attestation: AttestationRef<'ctxt, E>,
ctxt: &'ctxt mut ConsensusContext<E>,
verify_signatures: VerifySignatures,
spec: &ChainSpec,
) -> Result<&'ctxt IndexedAttestation<E>> {
) -> Result<IndexedAttestationRef<'ctxt, E>> {
let data = attestation.data();
verify!(
@@ -61,11 +61,11 @@ pub fn verify_attestation_for_block_inclusion<'ctxt, E: EthSpec>(
/// Spec v0.12.1
pub fn verify_attestation_for_state<'ctxt, E: EthSpec>(
state: &BeaconState<E>,
attestation: &Attestation<E>,
attestation: AttestationRef<'ctxt, E>,
ctxt: &'ctxt mut ConsensusContext<E>,
verify_signatures: VerifySignatures,
spec: &ChainSpec,
) -> Result<&'ctxt IndexedAttestation<E>> {
) -> Result<IndexedAttestationRef<'ctxt, E>> {
let data = attestation.data();
verify!(
@@ -87,7 +87,7 @@ pub fn verify_attestation_for_state<'ctxt, E: EthSpec>(
///
/// Spec v0.12.1
fn verify_casper_ffg_vote<E: EthSpec>(
attestation: &Attestation<E>,
attestation: AttestationRef<E>,
state: &BeaconState<E>,
) -> Result<()> {
let data = attestation.data();

View File

@@ -18,12 +18,12 @@ fn error(reason: Invalid) -> BlockOperationError<Invalid> {
/// invalidity.
pub fn verify_attester_slashing<E: EthSpec>(
state: &BeaconState<E>,
attester_slashing: &AttesterSlashing<E>,
attester_slashing: AttesterSlashingRef<'_, E>,
verify_signatures: VerifySignatures,
spec: &ChainSpec,
) -> Result<Vec<u64>> {
let attestation_1 = &attester_slashing.attestation_1;
let attestation_2 = &attester_slashing.attestation_2;
let attestation_1 = attester_slashing.attestation_1();
let attestation_2 = attester_slashing.attestation_2();
// Spec: is_slashable_attestation_data
verify!(
@@ -45,7 +45,7 @@ pub fn verify_attester_slashing<E: EthSpec>(
/// Returns Ok(indices) if `indices.len() > 0`
pub fn get_slashable_indices<E: EthSpec>(
state: &BeaconState<E>,
attester_slashing: &AttesterSlashing<E>,
attester_slashing: AttesterSlashingRef<'_, E>,
) -> Result<Vec<u64>> {
get_slashable_indices_modular(state, attester_slashing, |_, validator| {
validator.is_slashable_at(state.current_epoch())
@@ -56,14 +56,14 @@ pub fn get_slashable_indices<E: EthSpec>(
/// for determining whether a given validator should be considered slashable.
pub fn get_slashable_indices_modular<F, E: EthSpec>(
state: &BeaconState<E>,
attester_slashing: &AttesterSlashing<E>,
attester_slashing: AttesterSlashingRef<'_, E>,
is_slashable: F,
) -> Result<Vec<u64>>
where
F: Fn(u64, &Validator) -> bool,
{
let attestation_1 = &attester_slashing.attestation_1;
let attestation_2 = &attester_slashing.attestation_2;
let attestation_1 = attester_slashing.attestation_1();
let attestation_2 = attester_slashing.attestation_2();
let attesting_indices_1 = attestation_1
.attesting_indices_iter()

View File

@@ -12,30 +12,132 @@ use smallvec::{smallvec, SmallVec};
use ssz::{Decode, Encode};
use ssz_derive::{Decode, Encode};
use std::marker::PhantomData;
use types::{AttesterSlashing, AttesterSlashingOnDisk, AttesterSlashingRefOnDisk};
use types::{
AttesterSlashing, BeaconState, ChainSpec, Epoch, EthSpec, Fork, ForkVersion, ProposerSlashing,
BeaconState, ChainSpec, Epoch, EthSpec, Fork, ForkVersion, ProposerSlashing,
SignedBlsToExecutionChange, SignedVoluntaryExit,
};
const MAX_FORKS_VERIFIED_AGAINST: usize = 2;
pub trait TransformPersist {
type Persistable: Encode + Decode;
type PersistableRef<'a>: Encode
where
Self: 'a;
/// Returns a reference to the object in a form that implements `Encode`
fn as_persistable_ref(&self) -> Self::PersistableRef<'_>;
/// Converts the object back into its original form.
fn from_persistable(persistable: Self::Persistable) -> Self;
}
/// Wrapper around an operation type that acts as proof that its signature has been checked.
///
/// The inner `op` field is private, meaning instances of this type can only be constructed
/// by calling `validate`.
#[derive(Derivative, Debug, Clone, Encode, Decode)]
#[derive(Derivative, Debug, Clone)]
#[derivative(
PartialEq,
Eq,
Hash(bound = "T: Encode + Decode + std::hash::Hash, E: EthSpec")
Hash(bound = "T: TransformPersist + std::hash::Hash, E: EthSpec")
)]
pub struct SigVerifiedOp<T: Encode + Decode, E: EthSpec> {
pub struct SigVerifiedOp<T: TransformPersist, E: EthSpec> {
op: T,
verified_against: VerifiedAgainst,
#[ssz(skip_serializing, skip_deserializing)]
//#[ssz(skip_serializing, skip_deserializing)]
_phantom: PhantomData<E>,
}
impl<T: TransformPersist, E: EthSpec> Encode for SigVerifiedOp<T, E> {
fn is_ssz_fixed_len() -> bool {
<T::Persistable as Encode>::is_ssz_fixed_len()
&& <VerifiedAgainst as Encode>::is_ssz_fixed_len()
}
#[allow(clippy::expect_used)]
fn ssz_fixed_len() -> usize {
if <Self as Encode>::is_ssz_fixed_len() {
<T::Persistable as Encode>::ssz_fixed_len()
.checked_add(<VerifiedAgainst as Encode>::ssz_fixed_len())
.expect("encode ssz_fixed_len length overflow")
} else {
ssz::BYTES_PER_LENGTH_OFFSET
}
}
#[allow(clippy::expect_used)]
fn ssz_bytes_len(&self) -> usize {
if <Self as Encode>::is_ssz_fixed_len() {
<Self as Encode>::ssz_fixed_len()
} else {
let persistable = self.op.as_persistable_ref();
persistable
.ssz_bytes_len()
.checked_add(self.verified_against.ssz_bytes_len())
.expect("ssz_bytes_len length overflow")
}
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
let mut encoder = ssz::SszEncoder::container(buf, <Self as Encode>::ssz_fixed_len());
let persistable = self.op.as_persistable_ref();
encoder.append(&persistable);
encoder.append(&self.verified_against);
encoder.finalize();
}
}
impl<T: TransformPersist, E: EthSpec> Decode for SigVerifiedOp<T, E> {
fn is_ssz_fixed_len() -> bool {
<T::Persistable as Decode>::is_ssz_fixed_len()
&& <VerifiedAgainst as Decode>::is_ssz_fixed_len()
}
#[allow(clippy::expect_used)]
fn ssz_fixed_len() -> usize {
if <Self as Decode>::is_ssz_fixed_len() {
<T::Persistable as Decode>::ssz_fixed_len()
.checked_add(<VerifiedAgainst as Decode>::ssz_fixed_len())
.expect("decode ssz_fixed_len length overflow")
} else {
ssz::BYTES_PER_LENGTH_OFFSET
}
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
let mut builder = ssz::SszDecoderBuilder::new(bytes);
// Register types based on whether they are fixed or variable length
if <T::Persistable as Decode>::is_ssz_fixed_len() {
builder.register_type::<T::Persistable>()?;
} else {
builder.register_anonymous_variable_length_item()?;
}
if <VerifiedAgainst as Decode>::is_ssz_fixed_len() {
builder.register_type::<VerifiedAgainst>()?;
} else {
builder.register_anonymous_variable_length_item()?;
}
let mut decoder = builder.build()?;
// Decode each component
let persistable: T::Persistable = decoder.decode_next()?;
let verified_against: VerifiedAgainst = decoder.decode_next()?;
// Use TransformPersist to convert persistable back into the original type
let op = T::from_persistable(persistable);
Ok(SigVerifiedOp {
op,
verified_against,
_phantom: PhantomData,
})
}
}
/// Information about the fork versions that this message was verified against.
///
/// In general it is not safe to assume that a `SigVerifiedOp` constructed at some point in the past
@@ -109,7 +211,7 @@ where
}
/// Trait for operations that can be verified and transformed into a `SigVerifiedOp`.
pub trait VerifyOperation<E: EthSpec>: Encode + Decode + Sized {
pub trait VerifyOperation<E: EthSpec>: TransformPersist + Sized {
type Error;
fn validate(
@@ -152,15 +254,15 @@ impl<E: EthSpec> VerifyOperation<E> for AttesterSlashing<E> {
state: &BeaconState<E>,
spec: &ChainSpec,
) -> Result<SigVerifiedOp<Self, E>, Self::Error> {
verify_attester_slashing(state, &self, VerifySignatures::True, spec)?;
verify_attester_slashing(state, self.to_ref(), VerifySignatures::True, spec)?;
Ok(SigVerifiedOp::new(self, state))
}
#[allow(clippy::arithmetic_side_effects)]
fn verification_epochs(&self) -> SmallVec<[Epoch; MAX_FORKS_VERIFIED_AGAINST]> {
smallvec![
self.attestation_1.data().target.epoch,
self.attestation_2.data().target.epoch
self.attestation_1().data().target.epoch,
self.attestation_2().data().target.epoch
]
}
}
@@ -237,3 +339,55 @@ impl<E: EthSpec> VerifyOperationAt<E> for SignedVoluntaryExit {
Ok(SigVerifiedOp::new(self, state))
}
}
impl TransformPersist for SignedVoluntaryExit {
type Persistable = Self;
type PersistableRef<'a> = &'a Self;
fn as_persistable_ref(&self) -> Self::PersistableRef<'_> {
self
}
fn from_persistable(persistable: Self::Persistable) -> Self {
persistable
}
}
impl<E: EthSpec> TransformPersist for AttesterSlashing<E> {
type Persistable = AttesterSlashingOnDisk<E>;
type PersistableRef<'a> = AttesterSlashingRefOnDisk<'a, E>;
fn as_persistable_ref(&self) -> Self::PersistableRef<'_> {
self.to_ref().into()
}
fn from_persistable(persistable: Self::Persistable) -> Self {
persistable.into()
}
}
impl TransformPersist for ProposerSlashing {
type Persistable = Self;
type PersistableRef<'a> = &'a Self;
fn as_persistable_ref(&self) -> Self::PersistableRef<'_> {
self
}
fn from_persistable(persistable: Self::Persistable) -> Self {
persistable
}
}
impl TransformPersist for SignedBlsToExecutionChange {
type Persistable = Self;
type PersistableRef<'a> = &'a Self;
fn as_persistable_ref(&self) -> Self::PersistableRef<'_> {
self
}
fn from_persistable(persistable: Self::Persistable) -> Self {
persistable
}
}