Skip to content

Commit

Permalink
production complete, compiles
Browse files Browse the repository at this point in the history
  • Loading branch information
dapplion committed Nov 11, 2023
1 parent 1ee564f commit 3ce84b5
Show file tree
Hide file tree
Showing 13 changed files with 398 additions and 156 deletions.
56 changes: 43 additions & 13 deletions beacon_node/beacon_chain/src/beacon_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ use task_executor::{ShutdownReason, TaskExecutor};
use tokio_stream::Stream;
use tree_hash::TreeHash;
use types::beacon_state::CloneConfig;
use types::light_client_update::{FINALIZED_ROOT_INDEX, NEXT_SYNC_COMMITTEE_INDEX};
use types::light_client_bootstrap::LightClientBootstrap;
use types::light_client_update::LightClientUpdate;
use types::*;

pub type ForkChoiceError = fork_choice::Error<crate::ForkChoiceStoreError>;
Expand Down Expand Up @@ -1172,6 +1173,26 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
self.state_at_slot(load_slot, StateSkipConfig::WithoutStateRoots)
}

/// Returns a `LightclientBootstrap` message at `block_root`. Attempts to reconstruct the
/// message from pre-calculated branches first.
pub fn get_lightclient_bootstrap(
&self,
block_root: Hash256,
) -> Result<LightClientBootstrap<T::EthSpec>, Error> {
self.lightclient_server_cache
.produce_bootstrap(self.store.clone(), &self.spec, block_root)
}

/// Returns the best `LightclientUpdate` available given the rules of `is_better_update()`.
/// For historical updates, only returns pre-computed messages.
pub fn get_lightclient_update(
&self,
sync_committee_period: u64,
) -> Result<LightClientUpdate<T::EthSpec>, Error> {
self.lightclient_server_cache
.produce_update(self.store.clone(), sync_committee_period)
}

/// Returns the current heads of the `BeaconChain`. For the canonical head, see `Self::head`.
///
/// Returns `(block_root, block_slot)`.
Expand Down Expand Up @@ -2834,7 +2855,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
parent_block: SignedBlindedBeaconBlock<T::EthSpec>,
parent_eth1_finalization_data: Eth1FinalizationData,
mut consensus_context: ConsensusContext<T::EthSpec>,
) -> Result<(Hash256, LightclientBlockUpdates), BlockError<T::EthSpec>> {
) -> Result<Hash256, BlockError<T::EthSpec>> {
// ----------------------------- BLOCK NOT YET ATTESTABLE ----------------------------------
// Everything in this initial section is on the hot path between processing the block and
// being able to attest to it. DO NOT add any extra processing in this initial section
Expand Down Expand Up @@ -2985,11 +3006,6 @@ impl<T: BeaconChainTypes> BeaconChain<T> {

let db_write_timer = metrics::start_timer(&metrics::BLOCK_PROCESSING_DB_WRITE);

ops.extend(
self.lightclient_server_cache
.import_block(block_root, &state)?,
);

// Store the block and its state, and execute the confirmation batch for the intermediate
// states, which will delete their temporary flags.
// If the write fails, revert fork choice to the version from disk, else we can
Expand Down Expand Up @@ -3058,6 +3074,22 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
};
let current_finalized_checkpoint = state.finalized_checkpoint();

// compute state proofs for light client updates before inserting the state into the
// snapshot cache.
self.lightclient_server_cache
.cache_state_data(
self.store.clone(),
&self.spec,
block,
block_root,
// mutable reference on the state is needed to compute merkle proofs
&mut state,
parent_block.slot(),
)
.unwrap_or_else(|e| {
error!(self.log, "error caching lightclient data {:?}", e);
});

self.snapshot_cache
.try_write_for(BLOCK_PROCESSING_CACHE_LOCK_TIMEOUT)
.ok_or(Error::SnapshotCacheLockTimeout)
Expand Down Expand Up @@ -3111,15 +3143,13 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
current_slot,
);

let lightclient_updates = self
.lightclient_server_cache
.produce_latest_updates_on_block(self.store, &block)
self.lightclient_server_cache
.recompute_and_cache_updates(self.store.clone(), &self.spec, block)
.unwrap_or_else(|e| {
error!(self.log, "error producing lightclient updates {:?}", e);
(None, None)
error!(self.log, "error computing lightclient updates {:?}", e);
});

Ok((block_root, lightclient_updates))
Ok(block_root)
}

/// Check block's consistentency with any configured weak subjectivity checkpoint.
Expand Down
6 changes: 3 additions & 3 deletions beacon_node/beacon_chain/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::eth1_finalization_cache::Eth1FinalizationCache;
use crate::fork_choice_signal::ForkChoiceSignalTx;
use crate::fork_revert::{reset_fork_choice_to_finalization, revert_to_fork_boundary};
use crate::head_tracker::HeadTracker;
use crate::lightclient_proofs_cache::LightclientServerCache;
use crate::migrate::{BackgroundMigrator, MigratorConfig};
use crate::persisted_beacon_chain::PersistedBeaconChain;
use crate::shuffling_cache::{BlockShufflingIds, ShufflingCache};
Expand Down Expand Up @@ -832,8 +833,6 @@ where
observed_proposer_slashings: <_>::default(),
observed_attester_slashings: <_>::default(),
observed_bls_to_execution_changes: <_>::default(),
latest_seen_finality_update: <_>::default(),
latest_seen_optimistic_update: <_>::default(),
eth1_chain: self.eth1_chain,
execution_layer: self.execution_layer,
genesis_validators_root,
Expand Down Expand Up @@ -861,6 +860,7 @@ where
validator_pubkey_cache: TimeoutRwLock::new(validator_pubkey_cache),
attester_cache: <_>::default(),
early_attester_cache: <_>::default(),
lightclient_server_cache: LightclientServerCache::new(),
shutdown_sender: self
.shutdown_sender
.ok_or("Cannot build without a shutdown sender.")?,
Expand Down Expand Up @@ -1192,4 +1192,4 @@ mod test {
"validator count should be correct"
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use derivative::Derivative;
use slot_clock::SlotClock;
use std::time::Duration;
use strum::AsRefStr;
use types::{
light_client_update::Error as LightClientUpdateError, LightClientFinalityUpdate, Slot,
};
use types::{light_client_update::Error as LightClientUpdateError, LightClientFinalityUpdate};

/// Returned when a light client finality update was not successfully verified. It might not have been verified for
/// two reasons:
Expand Down Expand Up @@ -69,7 +67,10 @@ impl<T: BeaconChainTypes> VerifiedLightClientFinalityUpdate<T> {
chain: &BeaconChain<T>,
seen_timestamp: Duration,
) -> Result<Self, Error> {
let latest_finality_update = chain.lightclient_server_cache.get_latest_finality_update();
let latest_finality_update = chain
.lightclient_server_cache
.get_latest_finality_update()
.ok_or(Error::FailedConstructingUpdate)?;

// verify that no other finality_update with a lower or equal
// finalized_header.slot was already forwarded on the network
Expand All @@ -94,7 +95,7 @@ impl<T: BeaconChainTypes> VerifiedLightClientFinalityUpdate<T> {
}

// verify that the gossiped finality update is the same as the locally constructed one.
if latest_finality_update != &rcv_finality_update {
if latest_finality_update != rcv_finality_update {
return Err(Error::InvalidLightClientFinalityUpdate);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use eth2::types::Hash256;
use slot_clock::SlotClock;
use std::time::Duration;
use strum::AsRefStr;
use types::{
light_client_update::Error as LightClientUpdateError, LightClientOptimisticUpdate, Slot,
};
use types::{light_client_update::Error as LightClientUpdateError, LightClientOptimisticUpdate};

/// Returned when a light client optimistic update was not successfully verified. It might not have been verified for
/// two reasons:
Expand Down Expand Up @@ -90,17 +88,19 @@ impl<T: BeaconChainTypes> VerifiedLightClientOptimisticUpdate<T> {

let latest_optimistic_update = chain
.lightclient_server_cache
.get_latest_optimistic_update();
.get_latest_optimistic_update()
.ok_or(Error::FailedConstructingUpdate)?;

// verify that the gossiped optimistic update is the same as the locally constructed one.
if latest_optimistic_update != &rcv_optimistic_update {
if latest_optimistic_update != rcv_optimistic_update {
return Err(Error::InvalidLightClientOptimisticUpdate);
}

let parent_root = rcv_optimistic_update.attested_header.parent_root;
Ok(Self {
light_client_optimistic_update: rcv_optimistic_update,
// TODO: why is the parent_root necessary here?
parent_root: rcv_optimistic_update.attested_header.parent_root,
parent_root,
seen_timestamp,
})
}
Expand Down
Loading

0 comments on commit 3ce84b5

Please sign in to comment.