Skip to main content

dash_platform_queries/
block_info_from_metadata.rs

1use crate::Error;
2use dapi_grpc::platform::v0::ResponseMetadata;
3use dpp::block::block_info::BlockInfo;
4use dpp::block::epoch::MAX_EPOCH;
5use drive::error::proof::ProofError;
6
7/// Constructs a `BlockInfo` structure from the provided response metadata. This function
8/// translates metadata received from a platform response into a format that is specific to the
9/// application's needs, particularly focusing on block-related information. It ensures that
10/// the epoch value from the metadata does not exceed `MAX_EPOCH`,
11/// as this is a constraint for the `Epoch` type used in the `BlockInfo` structure.
12///
13/// # Parameters
14/// - `response_metadata`: A reference to `ResponseMetadata` obtained from a platform response.
15///   This metadata includes various block-related information such as time in milliseconds,
16///   height, core chain locked height, and epoch.
17///
18/// # Returns
19/// If successful, returns `Ok(BlockInfo)` where `BlockInfo` contains:
20/// - `time_ms`: The timestamp of the block in milliseconds.
21/// - `height`: The height of the block.
22/// - `core_height`: The core chain locked height, indicating the height of the block in the core blockchain that is considered final and securely linked to this block.
23/// - `epoch`: The epoch number, converted to an `Epoch` struct via a 16-bit number.
24///
25/// # Errors
26/// Returns an error if:
27/// - The `epoch` value in the response metadata exceeds `MAX_EPOCH`. This is considered a data validity error as it indicates Platform returned an unexpectedly high epoch number.
28///
29/// The function encapsulates errors into the application's own `Error` type, providing a unified interface for error handling across the application.
30pub fn block_info_from_metadata(response_metadata: &ResponseMetadata) -> Result<BlockInfo, Error> {
31    if response_metadata.epoch > MAX_EPOCH as u32 {
32        return Err(
33            drive::error::Error::Proof(ProofError::InvalidMetadata(format!(
34                "platform returned an epoch {} that was higher than the maximum allowed epoch",
35                response_metadata.epoch
36            )))
37            .into(),
38        );
39    }
40
41    Ok(BlockInfo {
42        time_ms: response_metadata.time_ms,
43        height: response_metadata.height,
44        core_height: response_metadata.core_chain_locked_height,
45        epoch: (response_metadata.epoch as u16).try_into()?,
46    })
47}