Skip to content

Commit

Permalink
Switch block reporting changes (#261)
Browse files Browse the repository at this point in the history
* Switch block reporting changes

* Correct typo in name

* Bump types
  • Loading branch information
jacek-casper authored Mar 18, 2024
1 parent 7003df5 commit 05626a7
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 11 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 13 additions & 1 deletion resources/test/rpc_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,17 @@
"block_sync": {
"description": "The status of the block synchronizer builders.",
"$ref": "#/components/schemas/BlockSynchronizerStatus"
},
"latest_switch_block_hash": {
"description": "The hash of the latest switch block.",
"anyOf": [
{
"$ref": "#/components/schemas/BlockHash"
},
{
"type": "null"
}
]
}
},
"additionalProperties": false
Expand Down Expand Up @@ -1366,7 +1377,8 @@
"block_height": 6701,
"acquisition_state": "have block body(6701) for: block hash 5990..4983"
}
}
},
"latest_switch_block_hash": "0000000000000000000000000000000000000000000000000000000000000000"
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions resources/test/schema_status.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,17 @@
"$ref": "#/definitions/BlockSynchronizerStatus"
}
]
},
"latest_switch_block_hash": {
"description": "The hash of the latest switch block.",
"anyOf": [
{
"$ref": "#/definitions/BlockHash"
},
{
"type": "null"
}
]
}
},
"additionalProperties": false,
Expand Down
7 changes: 7 additions & 0 deletions rpc_sidecar/src/node_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@ pub trait NodeClient: Send + Sync {
parse_response::<ConsensusValidatorChanges>(&resp.into())?.ok_or(Error::EmptyEnvelope)
}

async fn read_latest_switch_block_header(&self) -> Result<Option<BlockHeader>, Error> {
let resp = self
.read_info(InformationRequest::LatestSwitchBlockHeader)
.await?;
parse_response::<BlockHeader>(&resp.into())
}

async fn read_node_status(&self) -> Result<NodeStatus, Error> {
let resp = self.read_info(InformationRequest::NodeStatus).await?;
parse_response::<NodeStatus>(&resp.into())?.ok_or(Error::EmptyEnvelope)
Expand Down
93 changes: 87 additions & 6 deletions rpc_sidecar/src/rpcs/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,12 @@ impl RpcWithOptionalParams for GetEraInfoBySwitchBlock {
node_client: Arc<dyn NodeClient>,
maybe_params: Option<Self::OptionalRequestParams>,
) -> Result<Self::ResponseResult, RpcError> {
let identifier = maybe_params.map(|params| params.block_identifier);
let block_header = common::get_block_header(&*node_client, identifier).await?;
let block_header = match maybe_params {
Some(params) => {
common::get_block_header(&*node_client, Some(params.block_identifier)).await?
}
None => common::get_latest_switch_block_header(&*node_client).await?,
};
let era_summary = if block_header.is_switch_block() {
Some(get_era_summary_by_block(node_client, &block_header).await?)
} else {
Expand Down Expand Up @@ -334,8 +338,13 @@ impl RpcWithOptionalParams for GetEraSummary {
node_client: Arc<dyn NodeClient>,
maybe_params: Option<Self::OptionalRequestParams>,
) -> Result<Self::ResponseResult, RpcError> {
let identifier = maybe_params.map(|params| params.block_identifier);
let block_header = common::get_block_header(&*node_client, identifier).await?;
let block_header = match maybe_params {
Some(params) => {
common::get_block_header(&*node_client, Some(params.block_identifier)).await?
}
None => common::get_latest_switch_block_header(&*node_client).await?,
};

let era_summary = get_era_summary_by_block(node_client, &block_header).await?;

Ok(Self::ResponseResult {
Expand Down Expand Up @@ -547,6 +556,7 @@ mod tests {
let resp = GetEraSummary::do_handle_request(
Arc::new(ValidEraSummaryMock {
block: Block::V2(block.clone()),
expect_no_block_identifier: true,
}),
None,
)
Expand All @@ -568,6 +578,38 @@ mod tests {
);
}

#[tokio::test]
async fn should_read_block_era_summary_with_block_id() {
let rng = &mut TestRng::new();
let block = TestBlockBuilder::new().build(rng);

let resp = GetEraSummary::do_handle_request(
Arc::new(ValidEraSummaryMock {
block: Block::V2(block.clone()),
expect_no_block_identifier: false,
}),
Some(GetEraSummaryParams {
block_identifier: BlockIdentifier::Hash(*block.hash()),
}),
)
.await
.expect("should handle request");

assert_eq!(
resp,
GetEraSummaryResult {
api_version: CURRENT_API_VERSION,
era_summary: EraSummary {
block_hash: *block.hash(),
era_id: block.era_id(),
stored_value: StoredValue::EraInfo(EraInfo::new()),
state_root_hash: *block.state_root_hash(),
merkle_proof: String::from("00000000"),
}
}
);
}

#[tokio::test]
async fn should_read_block_era_info_by_switch_block() {
let rng = &mut TestRng::new();
Expand All @@ -576,6 +618,7 @@ mod tests {
let resp = GetEraInfoBySwitchBlock::do_handle_request(
Arc::new(ValidEraSummaryMock {
block: Block::V2(block.clone()),
expect_no_block_identifier: true,
}),
None,
)
Expand All @@ -597,6 +640,38 @@ mod tests {
);
}

#[tokio::test]
async fn should_read_block_era_info_by_switch_block_with_block_id() {
let rng = &mut TestRng::new();
let block = TestBlockBuilder::new().switch_block(true).build(rng);

let resp = GetEraInfoBySwitchBlock::do_handle_request(
Arc::new(ValidEraSummaryMock {
block: Block::V2(block.clone()),
expect_no_block_identifier: false,
}),
Some(GetEraInfoParams {
block_identifier: BlockIdentifier::Hash(*block.hash()),
}),
)
.await
.expect("should handle request");

assert_eq!(
resp,
GetEraInfoResult {
api_version: CURRENT_API_VERSION,
era_summary: Some(EraSummary {
block_hash: *block.hash(),
era_id: block.era_id(),
stored_value: StoredValue::EraInfo(EraInfo::new()),
state_root_hash: *block.state_root_hash(),
merkle_proof: String::from("00000000"),
})
}
);
}

#[tokio::test]
async fn should_read_none_block_era_info_by_switch_block_for_non_switch() {
let rng = &mut TestRng::new();
Expand All @@ -605,6 +680,7 @@ mod tests {
let resp = GetEraInfoBySwitchBlock::do_handle_request(
Arc::new(ValidEraSummaryMock {
block: Block::V2(block.clone()),
expect_no_block_identifier: true,
}),
None,
)
Expand Down Expand Up @@ -669,6 +745,7 @@ mod tests {

struct ValidEraSummaryMock {
block: Block,
expect_no_block_identifier: bool,
}

#[async_trait]
Expand All @@ -677,10 +754,14 @@ mod tests {
&self,
req: BinaryRequest,
) -> Result<BinaryResponseAndRequest, ClientError> {
let expected_tag = if self.expect_no_block_identifier {
InformationRequestTag::LatestSwitchBlockHeader
} else {
InformationRequestTag::BlockHeader
};
match req {
BinaryRequest::Get(GetRequest::Information { info_type_tag, .. })
if InformationRequestTag::try_from(info_type_tag)
== Ok(InformationRequestTag::BlockHeader) =>
if InformationRequestTag::try_from(info_type_tag) == Ok(expected_tag) =>
{
Ok(BinaryResponseAndRequest::new(
BinaryResponse::from_value(
Expand Down
19 changes: 19 additions & 0 deletions rpc_sidecar/src/rpcs/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,25 @@ pub async fn get_block_header(
}
}

pub async fn get_latest_switch_block_header(
node_client: &dyn NodeClient,
) -> Result<BlockHeader, Error> {
match node_client
.read_latest_switch_block_header()
.await
.map_err(|err| Error::NodeRequest("latest switch block header", err))?
{
Some(header) => Ok(header),
None => {
let available_range = node_client
.read_available_block_range()
.await
.map_err(|err| Error::NodeRequest("available block range", err))?;
Err(Error::NoBlockFound(None, available_range))
}
}
}

pub async fn resolve_account_hash(
node_client: &dyn NodeClient,
account_hash: AccountHash,
Expand Down
10 changes: 7 additions & 3 deletions rpc_sidecar/src/rpcs/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use serde::{Deserialize, Serialize};
use casper_types::{
binary_port::MinimalBlockInfo,
execution::{ExecutionResult, ExecutionResultV2},
ActivationPoint, AvailableBlockRange, Block, BlockSynchronizerStatus, ChainspecRawBytes,
Deploy, DeployHash, Digest, EraId, ExecutionInfo, NextUpgrade, Peers, ProtocolVersion,
PublicKey, TimeDiff, Timestamp, Transaction, TransactionHash, ValidatorChange,
ActivationPoint, AvailableBlockRange, Block, BlockHash, BlockSynchronizerStatus,
ChainspecRawBytes, Deploy, DeployHash, Digest, EraId, ExecutionInfo, NextUpgrade, Peers,
ProtocolVersion, PublicKey, TimeDiff, Timestamp, Transaction, TransactionHash, ValidatorChange,
};

use super::{
Expand Down Expand Up @@ -84,6 +84,7 @@ static GET_STATUS_RESULT: Lazy<GetStatusResult> = Lazy::new(|| GetStatusResult {
last_progress: Timestamp::from(0),
available_block_range: AvailableBlockRange::RANGE_0_0,
block_sync: BlockSynchronizerStatus::example().clone(),
latest_switch_block_hash: Some(BlockHash::default()),
#[cfg(not(test))]
build_version: version_string(),

Expand Down Expand Up @@ -450,6 +451,8 @@ pub struct GetStatusResult {
pub available_block_range: AvailableBlockRange,
/// The status of the block synchronizer builders.
pub block_sync: BlockSynchronizerStatus,
/// The hash of the latest switch block.
pub latest_switch_block_hash: Option<BlockHash>,
}

impl DocExample for GetStatusResult {
Expand Down Expand Up @@ -488,6 +491,7 @@ impl RpcWithoutParams for GetStatus {
last_progress: status.last_progress,
available_block_range: status.available_block_range,
block_sync: status.block_sync,
latest_switch_block_hash: status.latest_switch_block_hash,
build_version: status.build_version,
})
}
Expand Down

0 comments on commit 05626a7

Please sign in to comment.