Skip to content

Commit

Permalink
Optimise single validator lookup query
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Jul 11, 2023
1 parent 7be4dbd commit efbabe3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
13 changes: 10 additions & 3 deletions beacon_node/http_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod sync_committees;
mod task_spawner;
pub mod test_utils;
mod ui;
mod validator;
mod validator_inclusion;
mod version;

Expand Down Expand Up @@ -72,6 +73,7 @@ use types::{
SignedContributionAndProof, SignedValidatorRegistrationData, SignedVoluntaryExit, Slot,
SyncCommitteeMessage, SyncContributionData,
};
use validator::pubkey_to_validator_index;
use version::{
add_consensus_version_header, execution_optimistic_finalized_fork_versioned_response,
fork_versioned_response, inconsistent_fork_rejection, unsupported_version_rejection, V1, V2,
Expand Down Expand Up @@ -777,9 +779,14 @@ pub fn serve<T: BeaconChainTypes>(
&chain,
|state, execution_optimistic, finalized| {
let index_opt = match &validator_id {
ValidatorId::PublicKey(pubkey) => {
state.validators().iter().position(|v| v.pubkey == *pubkey)
}
ValidatorId::PublicKey(pubkey) => pubkey_to_validator_index(
&chain, state, pubkey,
)
.map_err(|e| {
warp_utils::reject::custom_not_found(format!(
"unable to access pubkey cache: {e:?}",
))
})?,
ValidatorId::Index(index) => Some(*index as usize),
};

Expand Down
21 changes: 21 additions & 0 deletions beacon_node/http_api/src/validator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use beacon_chain::{BeaconChain, BeaconChainError, BeaconChainTypes};
use types::*;

/// Uses the `chain.validator_pubkey_cache` to resolve a pubkey to a validator
/// index and then ensures that the validator exists in the given `state`.
pub fn pubkey_to_validator_index<T: BeaconChainTypes>(
chain: &BeaconChain<T>,
state: &BeaconState<T::EthSpec>,
pubkey: &PublicKeyBytes,
) -> Result<Option<usize>, BeaconChainError> {
chain
.validator_index(pubkey)?
.filter(|&index| {
state
.validators()
.get(index)
.map_or(false, |v| v.pubkey == *pubkey)
})
.map(Result::Ok)
.transpose()
}

0 comments on commit efbabe3

Please sign in to comment.