Addressed Paul's comments regarding head_state.

This commit is contained in:
Luke Anderson 2019-09-13 18:58:08 +10:00
parent c254ac8c2e
commit b0e3ce7885
No known key found for this signature in database
GPG Key ID: 44408169EC61E228
5 changed files with 21 additions and 24 deletions

View File

@ -8,7 +8,7 @@ use std::sync::Arc;
use store::Store; use store::Store;
use types::{BeaconBlock, BeaconState, Epoch, EthSpec, Hash256, Slot, Validator}; use types::{BeaconBlock, BeaconState, Epoch, EthSpec, Hash256, Slot, Validator};
#[derive(Serialize)] #[derive(Serialize, Encode)]
pub struct HeadResponse { pub struct HeadResponse {
pub slot: Slot, pub slot: Slot,
pub block_root: Hash256, pub block_root: Hash256,
@ -184,7 +184,7 @@ pub struct StateResponse<T: EthSpec> {
/// the current head by skipping slots. /// the current head by skipping slots.
pub fn get_state<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult { pub fn get_state<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult {
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain.clone())?; let head_state = beacon_chain.head().beacon_state;
let (key, value) = match UrlQuery::from_request(&req) { let (key, value) = match UrlQuery::from_request(&req) {
Ok(query) => { Ok(query) => {
@ -253,7 +253,7 @@ pub fn get_current_finalized_checkpoint<T: BeaconChainTypes + 'static>(
req: Request<Body>, req: Request<Body>,
) -> ApiResult { ) -> ApiResult {
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain)?; let head_state = beacon_chain.head().beacon_state;
let checkpoint = head_state.finalized_checkpoint.clone(); let checkpoint = head_state.finalized_checkpoint.clone();

View File

@ -182,16 +182,6 @@ pub fn get_beacon_chain_from_request<T: BeaconChainTypes + 'static>(
Ok(beacon_chain.clone()) Ok(beacon_chain.clone())
} }
pub fn get_head_state<T: BeaconChainTypes + 'static>(
bc: Arc<BeaconChain<T>>,
) -> Result<BeaconState<T::EthSpec>, ApiError> {
let mut head_state = bc.head().beacon_state;
head_state
.build_all_caches(&bc.spec)
.map_err(|e| ApiError::ServerError(format!("Unable to build state cache: {:?}", e)))?;
Ok(head_state)
}
pub fn get_logger_from_request(req: &Request<Body>) -> slog::Logger { pub fn get_logger_from_request(req: &Request<Body>) -> slog::Logger {
let log = req let log = req
.extensions() .extensions()

View File

@ -1,3 +1,4 @@
use crate::response_builder::ResponseBuilder;
use crate::{helpers::*, success_response, ApiError, ApiResult, DBPath}; use crate::{helpers::*, success_response, ApiError, ApiResult, DBPath};
use beacon_chain::BeaconChainTypes; use beacon_chain::BeaconChainTypes;
use http::HeaderValue; use http::HeaderValue;

View File

@ -1,4 +1,5 @@
use crate::helpers::*; use crate::helpers::*;
use crate::response_builder::ResponseBuilder;
use crate::{success_response, ApiResult}; use crate::{success_response, ApiResult};
use beacon_chain::BeaconChainTypes; use beacon_chain::BeaconChainTypes;
use hyper::{Body, Request}; use hyper::{Body, Request};
@ -16,11 +17,5 @@ pub fn get_version(_req: Request<Body>) -> ApiResult {
/// Read the genesis time from the current beacon chain state. /// Read the genesis time from the current beacon chain state.
pub fn get_genesis_time<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult { pub fn get_genesis_time<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult {
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain)?; ResponseBuilder::new(&req).body(&beacon_chain.head().beacon_state.genesis_time)
let gen_time: u64 = head_state.genesis_time;
let body = Body::from(
serde_json::to_string(&gen_time)
.expect("Genesis should time always have a valid JSON serialization."),
);
Ok(success_response(body))
} }

View File

@ -1,4 +1,5 @@
use super::{success_response, ApiResult}; use super::{success_response, ApiResult};
use crate::response_builder::ResponseBuilder;
use crate::{helpers::*, ApiError, UrlQuery}; use crate::{helpers::*, ApiError, UrlQuery};
use beacon_chain::BeaconChainTypes; use beacon_chain::BeaconChainTypes;
use bls::{AggregateSignature, PublicKey, Signature}; use bls::{AggregateSignature, PublicKey, Signature};
@ -35,7 +36,7 @@ pub fn get_validator_duties<T: BeaconChainTypes + 'static>(req: Request<Body>) -
let log = get_logger_from_request(&req); let log = get_logger_from_request(&req);
slog::trace!(log, "Validator duties requested of API: {:?}", &req); slog::trace!(log, "Validator duties requested of API: {:?}", &req);
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain.clone())?; let mut head_state = beacon_chain.head().beacon_state;
slog::trace!(log, "Got head state from request."); slog::trace!(log, "Got head state from request.");
// Parse and check query parameters // Parse and check query parameters
@ -72,6 +73,10 @@ pub fn get_validator_duties<T: BeaconChainTypes + 'static>(req: Request<Body>) -
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
let mut duties: Vec<ValidatorDuty> = Vec::new(); let mut duties: Vec<ValidatorDuty> = Vec::new();
// Build cache for the requested epoch
head_state
.build_committee_cache(relative_epoch, &beacon_chain.spec)
.map_err(|e| ApiError::ServerError(format!("Unable to build committee cache: {:?}", e)))?;
// Get a list of all validators for this epoch // Get a list of all validators for this epoch
let validator_proposers: Vec<usize> = epoch let validator_proposers: Vec<usize> = epoch
.slot_iter(T::EthSpec::slots_per_epoch()) .slot_iter(T::EthSpec::slots_per_epoch())
@ -79,7 +84,6 @@ pub fn get_validator_duties<T: BeaconChainTypes + 'static>(req: Request<Body>) -
head_state head_state
.get_beacon_proposer_index(slot, relative_epoch, &beacon_chain.spec) .get_beacon_proposer_index(slot, relative_epoch, &beacon_chain.spec)
.map_err(|e| { .map_err(|e| {
// TODO: why are we getting an uninitialized state error here???
ApiError::ServerError(format!( ApiError::ServerError(format!(
"Unable to get proposer index for validator: {:?}", "Unable to get proposer index for validator: {:?}",
e e
@ -181,13 +185,13 @@ pub fn get_new_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -
serde_json::to_string(&new_block) serde_json::to_string(&new_block)
.expect("We should always be able to serialize a new block that we produced."), .expect("We should always be able to serialize a new block that we produced."),
); );
Ok(success_response(body)) ResponseBuilder::new(&req).body(&new_block)
} }
/// HTTP Handler to produce a new Attestation from the current state, ready to be signed by a validator. /// HTTP Handler to produce a new Attestation from the current state, ready to be signed by a validator.
pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult { pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult {
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain.clone())?; let mut head_state = beacon_chain.head().beacon_state;
let query = UrlQuery::from_request(&req)?; let query = UrlQuery::from_request(&req)?;
let val_pk_str = query let val_pk_str = query
@ -195,6 +199,9 @@ pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) ->
.map(|(_key, value)| value)?; .map(|(_key, value)| value)?;
let val_pk = parse_pubkey(val_pk_str.as_str())?; let val_pk = parse_pubkey(val_pk_str.as_str())?;
head_state
.update_pubkey_cache()
.map_err(|e| ApiError::ServerError(format!("Unable to build pubkey cache: {:?}", e)))?;
// Get the validator index from the supplied public key // Get the validator index from the supplied public key
// If it does not exist in the index, we cannot continue. // If it does not exist in the index, we cannot continue.
let val_index = head_state let val_index = head_state
@ -206,6 +213,10 @@ pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) ->
"The provided validator public key does not correspond to a validator index.".into(), "The provided validator public key does not correspond to a validator index.".into(),
))?; ))?;
// Build cache for the requested epoch
head_state
.build_committee_cache(RelativeEpoch::Current, &beacon_chain.spec)
.map_err(|e| ApiError::ServerError(format!("Unable to build committee cache: {:?}", e)))?;
// Get the duties of the validator, to make sure they match up. // Get the duties of the validator, to make sure they match up.
// If they don't have duties this epoch, then return an error // If they don't have duties this epoch, then return an error
let val_duty = head_state let val_duty = head_state