From cf46ca6184f07fcd02715dc00406d596c10c15a9 Mon Sep 17 00:00:00 2001 From: Jacek Malec <145967538+jacek-casper@users.noreply.github.com> Date: Fri, 23 Aug 2024 15:38:18 +0100 Subject: [PATCH] Rename PayloadType --- binary_port/src/binary_response.rs | 6 +- .../src/binary_response_and_request.rs | 6 +- binary_port/src/binary_response_header.rs | 7 +- binary_port/src/lib.rs | 4 +- binary_port/src/payload_type.rs | 460 ----------------- binary_port/src/response_type.rs | 462 ++++++++++++++++++ node/BINARY_PORT_PROTOCOL.md | 22 +- node/src/components/binary_port.rs | 7 +- .../reactor/main_reactor/tests/binary_port.rs | 80 +-- 9 files changed, 530 insertions(+), 524 deletions(-) delete mode 100644 binary_port/src/payload_type.rs create mode 100644 binary_port/src/response_type.rs diff --git a/binary_port/src/binary_response.rs b/binary_port/src/binary_response.rs index 407aa5b4d6..38cd9339e9 100644 --- a/binary_port/src/binary_response.rs +++ b/binary_port/src/binary_response.rs @@ -6,7 +6,7 @@ use casper_types::{ use crate::{ binary_response_header::BinaryResponseHeader, error_code::ErrorCode, - payload_type::{PayloadEntity, PayloadType}, + response_type::{PayloadEntity, ResponseType}, }; #[cfg(test)] @@ -40,7 +40,7 @@ impl BinaryResponse { /// Creates new binary response from raw bytes. pub fn from_raw_bytes( - payload_type: PayloadType, + payload_type: ResponseType, payload: Vec, protocol_version: ProtocolVersion, ) -> Self { @@ -59,7 +59,7 @@ impl BinaryResponse { BinaryResponse::new_error(ErrorCode::InternalError, protocol_version), |payload| BinaryResponse { payload, - header: BinaryResponseHeader::new(Some(V::PAYLOAD_TYPE), protocol_version), + header: BinaryResponseHeader::new(Some(V::RESPONSE_TYPE), protocol_version), }, ) } diff --git a/binary_port/src/binary_response_and_request.rs b/binary_port/src/binary_response_and_request.rs index e677bd1fec..c92bd2e7f7 100644 --- a/binary_port/src/binary_response_and_request.rs +++ b/binary_port/src/binary_response_and_request.rs @@ -5,7 +5,7 @@ use casper_types::{ use crate::{ binary_response::BinaryResponse, original_request_context::OriginalRequestContext, - payload_type::PayloadEntity, PayloadType, + response_type::PayloadEntity, ResponseType, }; use crate::record_id::RecordId; @@ -44,7 +44,7 @@ impl BinaryResponseAndRequest { protocol_version: ProtocolVersion, ) -> BinaryResponseAndRequest { let response = BinaryResponse::from_raw_bytes( - PayloadType::from_record_id(record_id, false), + ResponseType::from_record_id(record_id, false), data.to_bytes().unwrap(), protocol_version, ); @@ -58,7 +58,7 @@ impl BinaryResponseAndRequest { protocol_version: ProtocolVersion, ) -> BinaryResponseAndRequest { let response = BinaryResponse::from_raw_bytes( - PayloadType::from_record_id(record_id, true), + ResponseType::from_record_id(record_id, true), bincode::serialize(data).unwrap(), protocol_version, ); diff --git a/binary_port/src/binary_response_header.rs b/binary_port/src/binary_response_header.rs index 131ac77bb3..e816c7990f 100644 --- a/binary_port/src/binary_response_header.rs +++ b/binary_port/src/binary_response_header.rs @@ -1,4 +1,4 @@ -use crate::{error_code::ErrorCode, payload_type::PayloadType}; +use crate::{error_code::ErrorCode, response_type::ResponseType}; use casper_types::{ bytesrepr::{self, FromBytes, ToBytes}, ProtocolVersion, @@ -19,7 +19,10 @@ pub struct BinaryResponseHeader { impl BinaryResponseHeader { /// Creates new binary response header representing success. - pub fn new(returned_data_type: Option, protocol_version: ProtocolVersion) -> Self { + pub fn new( + returned_data_type: Option, + protocol_version: ProtocolVersion, + ) -> Self { Self { protocol_version, error: ErrorCode::NoError as u16, diff --git a/binary_port/src/lib.rs b/binary_port/src/lib.rs index 4bb6aa556c..07045a9e52 100644 --- a/binary_port/src/lib.rs +++ b/binary_port/src/lib.rs @@ -17,9 +17,9 @@ mod key_prefix; mod minimal_block_info; mod node_status; mod original_request_context; -mod payload_type; mod purse_identifier; pub mod record_id; +mod response_type; mod speculative_execution_result; mod state_request; mod type_wrappers; @@ -42,9 +42,9 @@ pub use information_request::{ pub use key_prefix::KeyPrefix; pub use minimal_block_info::MinimalBlockInfo; pub use node_status::NodeStatus; -pub use payload_type::{PayloadEntity, PayloadType}; pub use purse_identifier::PurseIdentifier; pub use record_id::{RecordId, UnknownRecordId}; +pub use response_type::{PayloadEntity, ResponseType}; pub use speculative_execution_result::SpeculativeExecutionResult; pub use state_request::GlobalStateRequest; pub use type_wrappers::{ diff --git a/binary_port/src/payload_type.rs b/binary_port/src/payload_type.rs deleted file mode 100644 index 53daab508c..0000000000 --- a/binary_port/src/payload_type.rs +++ /dev/null @@ -1,460 +0,0 @@ -//! The payload type. - -use core::{convert::TryFrom, fmt}; - -#[cfg(test)] -use rand::Rng; -#[cfg(feature = "json-schema")] -use schemars::JsonSchema; - -#[cfg(test)] -use casper_types::testing::TestRng; -use casper_types::{ - contracts::ContractPackage, - execution::{ExecutionResult, ExecutionResultV1}, - Account, AvailableBlockRange, BlockBody, BlockBodyV1, BlockHeader, BlockHeaderV1, - BlockSignatures, BlockSignaturesV1, BlockSynchronizerStatus, ChainspecRawBytes, Deploy, - NextUpgrade, Package, Peers, ProtocolVersion, SignedBlock, StoredValue, Transaction, Transfer, -}; - -use crate::{ - global_state_query_result::GlobalStateQueryResult, - node_status::NodeStatus, - speculative_execution_result::SpeculativeExecutionResult, - type_wrappers::{ - ConsensusStatus, ConsensusValidatorChanges, GetTrieFullResult, LastProgress, NetworkName, - ReactorStateName, RewardResponse, - }, - AddressableEntityWithByteCode, BalanceResponse, ContractWithWasm, DictionaryQueryResult, - RecordId, TransactionWithExecutionInfo, Uptime, -}; - -/// A type of the payload being returned in a binary response. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[repr(u8)] -#[cfg_attr(feature = "json-schema", derive(JsonSchema))] -pub enum PayloadType { - /// Legacy version of the block header. - BlockHeaderV1, - /// Block header. - BlockHeader, - /// Legacy version of the block body. - BlockBodyV1, - /// Block body. - BlockBody, - /// Legacy version of the approvals hashes. - ApprovalsHashesV1, - /// Approvals hashes - ApprovalsHashes, - /// Legacy version of the block signatures. - BlockSignaturesV1, - /// Block signatures. - BlockSignatures, - /// Deploy. - Deploy, - /// Transaction. - Transaction, - /// Legacy version of the execution result. - ExecutionResultV1, - /// Execution result. - ExecutionResult, - /// Wasm V1 execution result. - WasmV1Result, - /// Transfers. - Transfers, - /// Finalized deploy approvals. - FinalizedDeployApprovals, - /// Finalized approvals. - FinalizedApprovals, - /// Block with signatures. - SignedBlock, - /// Transaction with approvals and execution info. - TransactionWithExecutionInfo, - /// Peers. - Peers, - /// Last progress. - LastProgress, - /// State of the reactor. - ReactorState, - /// Network name. - NetworkName, - /// Consensus validator changes. - ConsensusValidatorChanges, // return type in `effects.rs` will be turned into dedicated type. - /// Status of the block synchronizer. - BlockSynchronizerStatus, - /// Available block range. - AvailableBlockRange, - /// Information about the next network upgrade. - NextUpgrade, - /// Consensus status. - ConsensusStatus, // return type in `effects.rs` will be turned into dedicated type. - /// Chainspec represented as raw bytes. - ChainspecRawBytes, - /// Uptime. - Uptime, - /// Result of checking if given block is in the highest available block range. - HighestBlockSequenceCheckResult, - /// Result of the speculative execution, - SpeculativeExecutionResult, - /// Result of querying global state, - GlobalStateQueryResult, - /// Result of querying global state for all values under a specified key. - StoredValues, - /// Result of querying global state for a full trie. - GetTrieFullResult, - /// Node status. - NodeStatus, - /// Result of querying for a dictionary item. - DictionaryQueryResult, - /// Balance query response. - BalanceResponse, - /// Reward response. - Reward, - /// Protocol version. - ProtocolVersion, - /// Contract package. - ContractPackage, - /// Contract with Wasm. - ContractWithWasm, - /// Account. - Account, - /// Package. - Package, - /// Addressable entity with bytecode. - AddressableEntityWithByteCode, -} - -impl PayloadType { - pub fn from_record_id(record_id: RecordId, is_legacy: bool) -> Self { - match (is_legacy, record_id) { - (true, RecordId::BlockHeader) => Self::BlockHeaderV1, - (true, RecordId::BlockBody) => Self::BlockBodyV1, - (true, RecordId::ApprovalsHashes) => Self::ApprovalsHashesV1, - (true, RecordId::BlockMetadata) => Self::BlockSignaturesV1, - (true, RecordId::Transaction) => Self::Deploy, - (true, RecordId::ExecutionResult) => Self::ExecutionResultV1, - (true, RecordId::Transfer) => Self::Transfers, - (true, RecordId::FinalizedTransactionApprovals) => Self::FinalizedDeployApprovals, - (false, RecordId::BlockHeader) => Self::BlockHeader, - (false, RecordId::BlockBody) => Self::BlockBody, - (false, RecordId::ApprovalsHashes) => Self::ApprovalsHashes, - (false, RecordId::BlockMetadata) => Self::BlockSignatures, - (false, RecordId::Transaction) => Self::Transaction, - (false, RecordId::ExecutionResult) => Self::ExecutionResult, - (false, RecordId::Transfer) => Self::Transfers, - (false, RecordId::FinalizedTransactionApprovals) => Self::FinalizedApprovals, - } - } - - #[cfg(test)] - pub(crate) fn random(rng: &mut TestRng) -> Self { - Self::try_from(rng.gen_range(0..45)).unwrap() - } -} - -impl TryFrom for PayloadType { - type Error = (); - - fn try_from(v: u8) -> Result { - match v { - x if x == PayloadType::BlockHeaderV1 as u8 => Ok(PayloadType::BlockHeaderV1), - x if x == PayloadType::BlockHeader as u8 => Ok(PayloadType::BlockHeader), - x if x == PayloadType::BlockBodyV1 as u8 => Ok(PayloadType::BlockBodyV1), - x if x == PayloadType::BlockBody as u8 => Ok(PayloadType::BlockBody), - x if x == PayloadType::ApprovalsHashesV1 as u8 => Ok(PayloadType::ApprovalsHashesV1), - x if x == PayloadType::ApprovalsHashes as u8 => Ok(PayloadType::ApprovalsHashes), - x if x == PayloadType::BlockSignaturesV1 as u8 => Ok(PayloadType::BlockSignaturesV1), - x if x == PayloadType::BlockSignatures as u8 => Ok(PayloadType::BlockSignatures), - x if x == PayloadType::Deploy as u8 => Ok(PayloadType::Deploy), - x if x == PayloadType::Transaction as u8 => Ok(PayloadType::Transaction), - x if x == PayloadType::ExecutionResultV1 as u8 => Ok(PayloadType::ExecutionResultV1), - x if x == PayloadType::ExecutionResult as u8 => Ok(PayloadType::ExecutionResult), - x if x == PayloadType::Transfers as u8 => Ok(PayloadType::Transfers), - x if x == PayloadType::FinalizedDeployApprovals as u8 => { - Ok(PayloadType::FinalizedDeployApprovals) - } - x if x == PayloadType::FinalizedApprovals as u8 => Ok(PayloadType::FinalizedApprovals), - x if x == PayloadType::SignedBlock as u8 => Ok(PayloadType::SignedBlock), - x if x == PayloadType::TransactionWithExecutionInfo as u8 => { - Ok(PayloadType::TransactionWithExecutionInfo) - } - x if x == PayloadType::Peers as u8 => Ok(PayloadType::Peers), - x if x == PayloadType::Uptime as u8 => Ok(PayloadType::Uptime), - x if x == PayloadType::LastProgress as u8 => Ok(PayloadType::LastProgress), - x if x == PayloadType::ReactorState as u8 => Ok(PayloadType::ReactorState), - x if x == PayloadType::NetworkName as u8 => Ok(PayloadType::NetworkName), - x if x == PayloadType::ConsensusValidatorChanges as u8 => { - Ok(PayloadType::ConsensusValidatorChanges) - } - x if x == PayloadType::BlockSynchronizerStatus as u8 => { - Ok(PayloadType::BlockSynchronizerStatus) - } - x if x == PayloadType::AvailableBlockRange as u8 => { - Ok(PayloadType::AvailableBlockRange) - } - x if x == PayloadType::NextUpgrade as u8 => Ok(PayloadType::NextUpgrade), - x if x == PayloadType::ConsensusStatus as u8 => Ok(PayloadType::ConsensusStatus), - x if x == PayloadType::ChainspecRawBytes as u8 => Ok(PayloadType::ChainspecRawBytes), - x if x == PayloadType::HighestBlockSequenceCheckResult as u8 => { - Ok(PayloadType::HighestBlockSequenceCheckResult) - } - x if x == PayloadType::SpeculativeExecutionResult as u8 => { - Ok(PayloadType::SpeculativeExecutionResult) - } - x if x == PayloadType::GlobalStateQueryResult as u8 => { - Ok(PayloadType::GlobalStateQueryResult) - } - x if x == PayloadType::StoredValues as u8 => Ok(PayloadType::StoredValues), - x if x == PayloadType::GetTrieFullResult as u8 => Ok(PayloadType::GetTrieFullResult), - x if x == PayloadType::NodeStatus as u8 => Ok(PayloadType::NodeStatus), - x if x == PayloadType::DictionaryQueryResult as u8 => { - Ok(PayloadType::DictionaryQueryResult) - } - x if x == PayloadType::WasmV1Result as u8 => Ok(PayloadType::WasmV1Result), - x if x == PayloadType::BalanceResponse as u8 => Ok(PayloadType::BalanceResponse), - x if x == PayloadType::Reward as u8 => Ok(PayloadType::Reward), - x if x == PayloadType::ProtocolVersion as u8 => Ok(PayloadType::ProtocolVersion), - x if x == PayloadType::ContractPackage as u8 => Ok(PayloadType::ContractPackage), - x if x == PayloadType::ContractWithWasm as u8 => Ok(PayloadType::ContractWithWasm), - x if x == PayloadType::Account as u8 => Ok(PayloadType::Account), - x if x == PayloadType::Package as u8 => Ok(PayloadType::Package), - x if x == PayloadType::AddressableEntityWithByteCode as u8 => { - Ok(PayloadType::AddressableEntityWithByteCode) - } - _ => Err(()), - } - } -} - -impl From for u8 { - fn from(value: PayloadType) -> Self { - value as u8 - } -} - -impl fmt::Display for PayloadType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - PayloadType::BlockHeaderV1 => write!(f, "BlockHeaderV1"), - PayloadType::BlockHeader => write!(f, "BlockHeader"), - PayloadType::BlockBodyV1 => write!(f, "BlockBodyV1"), - PayloadType::BlockBody => write!(f, "BlockBody"), - PayloadType::ApprovalsHashesV1 => write!(f, "ApprovalsHashesV1"), - PayloadType::ApprovalsHashes => write!(f, "ApprovalsHashes"), - PayloadType::BlockSignaturesV1 => write!(f, "BlockSignaturesV1"), - PayloadType::BlockSignatures => write!(f, "BlockSignatures"), - PayloadType::Deploy => write!(f, "Deploy"), - PayloadType::Transaction => write!(f, "Transaction"), - PayloadType::ExecutionResultV1 => write!(f, "ExecutionResultV1"), - PayloadType::ExecutionResult => write!(f, "ExecutionResult"), - PayloadType::Transfers => write!(f, "Transfers"), - PayloadType::FinalizedDeployApprovals => write!(f, "FinalizedDeployApprovals"), - PayloadType::FinalizedApprovals => write!(f, "FinalizedApprovals"), - PayloadType::SignedBlock => write!(f, "SignedBlock"), - PayloadType::TransactionWithExecutionInfo => write!(f, "TransactionWithExecutionInfo"), - PayloadType::Peers => write!(f, "Peers"), - PayloadType::LastProgress => write!(f, "LastProgress"), - PayloadType::ReactorState => write!(f, "ReactorState"), - PayloadType::NetworkName => write!(f, "NetworkName"), - PayloadType::ConsensusValidatorChanges => write!(f, "ConsensusValidatorChanges"), - PayloadType::BlockSynchronizerStatus => write!(f, "BlockSynchronizerStatus"), - PayloadType::AvailableBlockRange => write!(f, "AvailableBlockRange"), - PayloadType::NextUpgrade => write!(f, "NextUpgrade"), - PayloadType::ConsensusStatus => write!(f, "ConsensusStatus"), - PayloadType::ChainspecRawBytes => write!(f, "ChainspecRawBytes"), - PayloadType::Uptime => write!(f, "Uptime"), - PayloadType::HighestBlockSequenceCheckResult => { - write!(f, "HighestBlockSequenceCheckResult") - } - PayloadType::SpeculativeExecutionResult => write!(f, "SpeculativeExecutionResult"), - PayloadType::GlobalStateQueryResult => write!(f, "GlobalStateQueryResult"), - PayloadType::StoredValues => write!(f, "StoredValues"), - PayloadType::GetTrieFullResult => write!(f, "GetTrieFullResult"), - PayloadType::NodeStatus => write!(f, "NodeStatus"), - PayloadType::WasmV1Result => write!(f, "WasmV1Result"), - PayloadType::DictionaryQueryResult => write!(f, "DictionaryQueryResult"), - PayloadType::BalanceResponse => write!(f, "BalanceResponse"), - PayloadType::Reward => write!(f, "Reward"), - PayloadType::ProtocolVersion => write!(f, "ProtocolVersion"), - PayloadType::ContractPackage => write!(f, "ContractPackage"), - PayloadType::ContractWithWasm => write!(f, "Contract"), - PayloadType::Account => write!(f, "Account"), - PayloadType::Package => write!(f, "Package"), - PayloadType::AddressableEntityWithByteCode => { - write!(f, "AddressableEntityWithByteCode") - } - } - } -} - -/// Represents an entity that can be sent as a payload. -pub trait PayloadEntity { - /// Returns the payload type of the entity. - const PAYLOAD_TYPE: PayloadType; -} - -impl PayloadEntity for Transaction { - const PAYLOAD_TYPE: PayloadType = PayloadType::Transaction; -} - -impl PayloadEntity for Deploy { - const PAYLOAD_TYPE: PayloadType = PayloadType::Deploy; -} - -impl PayloadEntity for BlockHeader { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockHeader; -} - -impl PayloadEntity for BlockHeaderV1 { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockHeaderV1; -} - -impl PayloadEntity for BlockBody { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockBody; -} - -impl PayloadEntity for BlockBodyV1 { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockBodyV1; -} - -impl PayloadEntity for BlockSignatures { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockSignatures; -} - -impl PayloadEntity for BlockSignaturesV1 { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockSignaturesV1; -} - -impl PayloadEntity for ExecutionResult { - const PAYLOAD_TYPE: PayloadType = PayloadType::ExecutionResult; -} - -impl PayloadEntity for ExecutionResultV1 { - const PAYLOAD_TYPE: PayloadType = PayloadType::ExecutionResultV1; -} - -impl PayloadEntity for SignedBlock { - const PAYLOAD_TYPE: PayloadType = PayloadType::SignedBlock; -} - -impl PayloadEntity for TransactionWithExecutionInfo { - const PAYLOAD_TYPE: PayloadType = PayloadType::TransactionWithExecutionInfo; -} - -impl PayloadEntity for Peers { - const PAYLOAD_TYPE: PayloadType = PayloadType::Peers; -} - -impl PayloadEntity for Vec { - const PAYLOAD_TYPE: PayloadType = PayloadType::Transfers; -} - -impl PayloadEntity for AvailableBlockRange { - const PAYLOAD_TYPE: PayloadType = PayloadType::AvailableBlockRange; -} - -impl PayloadEntity for ChainspecRawBytes { - const PAYLOAD_TYPE: PayloadType = PayloadType::ChainspecRawBytes; -} - -impl PayloadEntity for ConsensusValidatorChanges { - const PAYLOAD_TYPE: PayloadType = PayloadType::ConsensusValidatorChanges; -} - -impl PayloadEntity for GlobalStateQueryResult { - const PAYLOAD_TYPE: PayloadType = PayloadType::GlobalStateQueryResult; -} - -impl PayloadEntity for DictionaryQueryResult { - const PAYLOAD_TYPE: PayloadType = PayloadType::DictionaryQueryResult; -} - -impl PayloadEntity for Vec { - const PAYLOAD_TYPE: PayloadType = PayloadType::StoredValues; -} - -impl PayloadEntity for GetTrieFullResult { - const PAYLOAD_TYPE: PayloadType = PayloadType::GetTrieFullResult; -} - -impl PayloadEntity for SpeculativeExecutionResult { - const PAYLOAD_TYPE: PayloadType = PayloadType::SpeculativeExecutionResult; -} - -impl PayloadEntity for NodeStatus { - const PAYLOAD_TYPE: PayloadType = PayloadType::NodeStatus; -} - -impl PayloadEntity for NextUpgrade { - const PAYLOAD_TYPE: PayloadType = PayloadType::NextUpgrade; -} - -impl PayloadEntity for Uptime { - const PAYLOAD_TYPE: PayloadType = PayloadType::Uptime; -} - -impl PayloadEntity for LastProgress { - const PAYLOAD_TYPE: PayloadType = PayloadType::LastProgress; -} - -impl PayloadEntity for ReactorStateName { - const PAYLOAD_TYPE: PayloadType = PayloadType::ReactorState; -} - -impl PayloadEntity for NetworkName { - const PAYLOAD_TYPE: PayloadType = PayloadType::NetworkName; -} - -impl PayloadEntity for BlockSynchronizerStatus { - const PAYLOAD_TYPE: PayloadType = PayloadType::BlockSynchronizerStatus; -} - -impl PayloadEntity for ConsensusStatus { - const PAYLOAD_TYPE: PayloadType = PayloadType::ConsensusStatus; -} - -impl PayloadEntity for BalanceResponse { - const PAYLOAD_TYPE: PayloadType = PayloadType::BalanceResponse; -} - -impl PayloadEntity for RewardResponse { - const PAYLOAD_TYPE: PayloadType = PayloadType::Reward; -} - -impl PayloadEntity for ProtocolVersion { - const PAYLOAD_TYPE: PayloadType = PayloadType::ProtocolVersion; -} - -impl PayloadEntity for ContractPackage { - const PAYLOAD_TYPE: PayloadType = PayloadType::ContractPackage; -} - -impl PayloadEntity for ContractWithWasm { - const PAYLOAD_TYPE: PayloadType = PayloadType::ContractWithWasm; -} - -impl PayloadEntity for Account { - const PAYLOAD_TYPE: PayloadType = PayloadType::Account; -} - -impl PayloadEntity for Package { - const PAYLOAD_TYPE: PayloadType = PayloadType::Package; -} - -impl PayloadEntity for AddressableEntityWithByteCode { - const PAYLOAD_TYPE: PayloadType = PayloadType::AddressableEntityWithByteCode; -} - -#[cfg(test)] -mod tests { - use super::*; - use casper_types::testing::TestRng; - - #[test] - fn convert_u8_roundtrip() { - let rng = &mut TestRng::new(); - - let val = PayloadType::random(rng); - assert_eq!(PayloadType::try_from(val as u8), Ok(val)); - } -} diff --git a/binary_port/src/response_type.rs b/binary_port/src/response_type.rs new file mode 100644 index 0000000000..b3b3147047 --- /dev/null +++ b/binary_port/src/response_type.rs @@ -0,0 +1,462 @@ +//! The payload type. + +use core::{convert::TryFrom, fmt}; + +#[cfg(test)] +use rand::Rng; +#[cfg(feature = "json-schema")] +use schemars::JsonSchema; + +#[cfg(test)] +use casper_types::testing::TestRng; +use casper_types::{ + contracts::ContractPackage, + execution::{ExecutionResult, ExecutionResultV1}, + Account, AvailableBlockRange, BlockBody, BlockBodyV1, BlockHeader, BlockHeaderV1, + BlockSignatures, BlockSignaturesV1, BlockSynchronizerStatus, ChainspecRawBytes, Deploy, + NextUpgrade, Package, Peers, ProtocolVersion, SignedBlock, StoredValue, Transaction, Transfer, +}; + +use crate::{ + global_state_query_result::GlobalStateQueryResult, + node_status::NodeStatus, + speculative_execution_result::SpeculativeExecutionResult, + type_wrappers::{ + ConsensusStatus, ConsensusValidatorChanges, GetTrieFullResult, LastProgress, NetworkName, + ReactorStateName, RewardResponse, + }, + AddressableEntityWithByteCode, BalanceResponse, ContractWithWasm, DictionaryQueryResult, + RecordId, TransactionWithExecutionInfo, Uptime, +}; + +/// A type of the payload being returned in a binary response. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u8)] +#[cfg_attr(feature = "json-schema", derive(JsonSchema))] +pub enum ResponseType { + /// Legacy version of the block header. + BlockHeaderV1, + /// Block header. + BlockHeader, + /// Legacy version of the block body. + BlockBodyV1, + /// Block body. + BlockBody, + /// Legacy version of the approvals hashes. + ApprovalsHashesV1, + /// Approvals hashes + ApprovalsHashes, + /// Legacy version of the block signatures. + BlockSignaturesV1, + /// Block signatures. + BlockSignatures, + /// Deploy. + Deploy, + /// Transaction. + Transaction, + /// Legacy version of the execution result. + ExecutionResultV1, + /// Execution result. + ExecutionResult, + /// Wasm V1 execution result. + WasmV1Result, + /// Transfers. + Transfers, + /// Finalized deploy approvals. + FinalizedDeployApprovals, + /// Finalized approvals. + FinalizedApprovals, + /// Block with signatures. + SignedBlock, + /// Transaction with approvals and execution info. + TransactionWithExecutionInfo, + /// Peers. + Peers, + /// Last progress. + LastProgress, + /// State of the reactor. + ReactorState, + /// Network name. + NetworkName, + /// Consensus validator changes. + ConsensusValidatorChanges, // return type in `effects.rs` will be turned into dedicated type. + /// Status of the block synchronizer. + BlockSynchronizerStatus, + /// Available block range. + AvailableBlockRange, + /// Information about the next network upgrade. + NextUpgrade, + /// Consensus status. + ConsensusStatus, // return type in `effects.rs` will be turned into dedicated type. + /// Chainspec represented as raw bytes. + ChainspecRawBytes, + /// Uptime. + Uptime, + /// Result of checking if given block is in the highest available block range. + HighestBlockSequenceCheckResult, + /// Result of the speculative execution, + SpeculativeExecutionResult, + /// Result of querying global state, + GlobalStateQueryResult, + /// Result of querying global state for all values under a specified key. + StoredValues, + /// Result of querying global state for a full trie. + GetTrieFullResult, + /// Node status. + NodeStatus, + /// Result of querying for a dictionary item. + DictionaryQueryResult, + /// Balance query response. + BalanceResponse, + /// Reward response. + Reward, + /// Protocol version. + ProtocolVersion, + /// Contract package. + ContractPackage, + /// Contract with Wasm. + ContractWithWasm, + /// Account. + Account, + /// Package. + Package, + /// Addressable entity with bytecode. + AddressableEntityWithByteCode, +} + +impl ResponseType { + pub fn from_record_id(record_id: RecordId, is_legacy: bool) -> Self { + match (is_legacy, record_id) { + (true, RecordId::BlockHeader) => Self::BlockHeaderV1, + (true, RecordId::BlockBody) => Self::BlockBodyV1, + (true, RecordId::ApprovalsHashes) => Self::ApprovalsHashesV1, + (true, RecordId::BlockMetadata) => Self::BlockSignaturesV1, + (true, RecordId::Transaction) => Self::Deploy, + (true, RecordId::ExecutionResult) => Self::ExecutionResultV1, + (true, RecordId::Transfer) => Self::Transfers, + (true, RecordId::FinalizedTransactionApprovals) => Self::FinalizedDeployApprovals, + (false, RecordId::BlockHeader) => Self::BlockHeader, + (false, RecordId::BlockBody) => Self::BlockBody, + (false, RecordId::ApprovalsHashes) => Self::ApprovalsHashes, + (false, RecordId::BlockMetadata) => Self::BlockSignatures, + (false, RecordId::Transaction) => Self::Transaction, + (false, RecordId::ExecutionResult) => Self::ExecutionResult, + (false, RecordId::Transfer) => Self::Transfers, + (false, RecordId::FinalizedTransactionApprovals) => Self::FinalizedApprovals, + } + } + + #[cfg(test)] + pub(crate) fn random(rng: &mut TestRng) -> Self { + Self::try_from(rng.gen_range(0..45)).unwrap() + } +} + +impl TryFrom for ResponseType { + type Error = (); + + fn try_from(v: u8) -> Result { + match v { + x if x == ResponseType::BlockHeaderV1 as u8 => Ok(ResponseType::BlockHeaderV1), + x if x == ResponseType::BlockHeader as u8 => Ok(ResponseType::BlockHeader), + x if x == ResponseType::BlockBodyV1 as u8 => Ok(ResponseType::BlockBodyV1), + x if x == ResponseType::BlockBody as u8 => Ok(ResponseType::BlockBody), + x if x == ResponseType::ApprovalsHashesV1 as u8 => Ok(ResponseType::ApprovalsHashesV1), + x if x == ResponseType::ApprovalsHashes as u8 => Ok(ResponseType::ApprovalsHashes), + x if x == ResponseType::BlockSignaturesV1 as u8 => Ok(ResponseType::BlockSignaturesV1), + x if x == ResponseType::BlockSignatures as u8 => Ok(ResponseType::BlockSignatures), + x if x == ResponseType::Deploy as u8 => Ok(ResponseType::Deploy), + x if x == ResponseType::Transaction as u8 => Ok(ResponseType::Transaction), + x if x == ResponseType::ExecutionResultV1 as u8 => Ok(ResponseType::ExecutionResultV1), + x if x == ResponseType::ExecutionResult as u8 => Ok(ResponseType::ExecutionResult), + x if x == ResponseType::Transfers as u8 => Ok(ResponseType::Transfers), + x if x == ResponseType::FinalizedDeployApprovals as u8 => { + Ok(ResponseType::FinalizedDeployApprovals) + } + x if x == ResponseType::FinalizedApprovals as u8 => { + Ok(ResponseType::FinalizedApprovals) + } + x if x == ResponseType::SignedBlock as u8 => Ok(ResponseType::SignedBlock), + x if x == ResponseType::TransactionWithExecutionInfo as u8 => { + Ok(ResponseType::TransactionWithExecutionInfo) + } + x if x == ResponseType::Peers as u8 => Ok(ResponseType::Peers), + x if x == ResponseType::Uptime as u8 => Ok(ResponseType::Uptime), + x if x == ResponseType::LastProgress as u8 => Ok(ResponseType::LastProgress), + x if x == ResponseType::ReactorState as u8 => Ok(ResponseType::ReactorState), + x if x == ResponseType::NetworkName as u8 => Ok(ResponseType::NetworkName), + x if x == ResponseType::ConsensusValidatorChanges as u8 => { + Ok(ResponseType::ConsensusValidatorChanges) + } + x if x == ResponseType::BlockSynchronizerStatus as u8 => { + Ok(ResponseType::BlockSynchronizerStatus) + } + x if x == ResponseType::AvailableBlockRange as u8 => { + Ok(ResponseType::AvailableBlockRange) + } + x if x == ResponseType::NextUpgrade as u8 => Ok(ResponseType::NextUpgrade), + x if x == ResponseType::ConsensusStatus as u8 => Ok(ResponseType::ConsensusStatus), + x if x == ResponseType::ChainspecRawBytes as u8 => Ok(ResponseType::ChainspecRawBytes), + x if x == ResponseType::HighestBlockSequenceCheckResult as u8 => { + Ok(ResponseType::HighestBlockSequenceCheckResult) + } + x if x == ResponseType::SpeculativeExecutionResult as u8 => { + Ok(ResponseType::SpeculativeExecutionResult) + } + x if x == ResponseType::GlobalStateQueryResult as u8 => { + Ok(ResponseType::GlobalStateQueryResult) + } + x if x == ResponseType::StoredValues as u8 => Ok(ResponseType::StoredValues), + x if x == ResponseType::GetTrieFullResult as u8 => Ok(ResponseType::GetTrieFullResult), + x if x == ResponseType::NodeStatus as u8 => Ok(ResponseType::NodeStatus), + x if x == ResponseType::DictionaryQueryResult as u8 => { + Ok(ResponseType::DictionaryQueryResult) + } + x if x == ResponseType::WasmV1Result as u8 => Ok(ResponseType::WasmV1Result), + x if x == ResponseType::BalanceResponse as u8 => Ok(ResponseType::BalanceResponse), + x if x == ResponseType::Reward as u8 => Ok(ResponseType::Reward), + x if x == ResponseType::ProtocolVersion as u8 => Ok(ResponseType::ProtocolVersion), + x if x == ResponseType::ContractPackage as u8 => Ok(ResponseType::ContractPackage), + x if x == ResponseType::ContractWithWasm as u8 => Ok(ResponseType::ContractWithWasm), + x if x == ResponseType::Account as u8 => Ok(ResponseType::Account), + x if x == ResponseType::Package as u8 => Ok(ResponseType::Package), + x if x == ResponseType::AddressableEntityWithByteCode as u8 => { + Ok(ResponseType::AddressableEntityWithByteCode) + } + _ => Err(()), + } + } +} + +impl From for u8 { + fn from(value: ResponseType) -> Self { + value as u8 + } +} + +impl fmt::Display for ResponseType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ResponseType::BlockHeaderV1 => write!(f, "BlockHeaderV1"), + ResponseType::BlockHeader => write!(f, "BlockHeader"), + ResponseType::BlockBodyV1 => write!(f, "BlockBodyV1"), + ResponseType::BlockBody => write!(f, "BlockBody"), + ResponseType::ApprovalsHashesV1 => write!(f, "ApprovalsHashesV1"), + ResponseType::ApprovalsHashes => write!(f, "ApprovalsHashes"), + ResponseType::BlockSignaturesV1 => write!(f, "BlockSignaturesV1"), + ResponseType::BlockSignatures => write!(f, "BlockSignatures"), + ResponseType::Deploy => write!(f, "Deploy"), + ResponseType::Transaction => write!(f, "Transaction"), + ResponseType::ExecutionResultV1 => write!(f, "ExecutionResultV1"), + ResponseType::ExecutionResult => write!(f, "ExecutionResult"), + ResponseType::Transfers => write!(f, "Transfers"), + ResponseType::FinalizedDeployApprovals => write!(f, "FinalizedDeployApprovals"), + ResponseType::FinalizedApprovals => write!(f, "FinalizedApprovals"), + ResponseType::SignedBlock => write!(f, "SignedBlock"), + ResponseType::TransactionWithExecutionInfo => write!(f, "TransactionWithExecutionInfo"), + ResponseType::Peers => write!(f, "Peers"), + ResponseType::LastProgress => write!(f, "LastProgress"), + ResponseType::ReactorState => write!(f, "ReactorState"), + ResponseType::NetworkName => write!(f, "NetworkName"), + ResponseType::ConsensusValidatorChanges => write!(f, "ConsensusValidatorChanges"), + ResponseType::BlockSynchronizerStatus => write!(f, "BlockSynchronizerStatus"), + ResponseType::AvailableBlockRange => write!(f, "AvailableBlockRange"), + ResponseType::NextUpgrade => write!(f, "NextUpgrade"), + ResponseType::ConsensusStatus => write!(f, "ConsensusStatus"), + ResponseType::ChainspecRawBytes => write!(f, "ChainspecRawBytes"), + ResponseType::Uptime => write!(f, "Uptime"), + ResponseType::HighestBlockSequenceCheckResult => { + write!(f, "HighestBlockSequenceCheckResult") + } + ResponseType::SpeculativeExecutionResult => write!(f, "SpeculativeExecutionResult"), + ResponseType::GlobalStateQueryResult => write!(f, "GlobalStateQueryResult"), + ResponseType::StoredValues => write!(f, "StoredValues"), + ResponseType::GetTrieFullResult => write!(f, "GetTrieFullResult"), + ResponseType::NodeStatus => write!(f, "NodeStatus"), + ResponseType::WasmV1Result => write!(f, "WasmV1Result"), + ResponseType::DictionaryQueryResult => write!(f, "DictionaryQueryResult"), + ResponseType::BalanceResponse => write!(f, "BalanceResponse"), + ResponseType::Reward => write!(f, "Reward"), + ResponseType::ProtocolVersion => write!(f, "ProtocolVersion"), + ResponseType::ContractPackage => write!(f, "ContractPackage"), + ResponseType::ContractWithWasm => write!(f, "Contract"), + ResponseType::Account => write!(f, "Account"), + ResponseType::Package => write!(f, "Package"), + ResponseType::AddressableEntityWithByteCode => { + write!(f, "AddressableEntityWithByteCode") + } + } + } +} + +/// Represents an entity that can be sent as a payload. +pub trait PayloadEntity { + /// Returns the payload type of the entity. + const RESPONSE_TYPE: ResponseType; +} + +impl PayloadEntity for Transaction { + const RESPONSE_TYPE: ResponseType = ResponseType::Transaction; +} + +impl PayloadEntity for Deploy { + const RESPONSE_TYPE: ResponseType = ResponseType::Deploy; +} + +impl PayloadEntity for BlockHeader { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockHeader; +} + +impl PayloadEntity for BlockHeaderV1 { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockHeaderV1; +} + +impl PayloadEntity for BlockBody { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockBody; +} + +impl PayloadEntity for BlockBodyV1 { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockBodyV1; +} + +impl PayloadEntity for BlockSignatures { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockSignatures; +} + +impl PayloadEntity for BlockSignaturesV1 { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockSignaturesV1; +} + +impl PayloadEntity for ExecutionResult { + const RESPONSE_TYPE: ResponseType = ResponseType::ExecutionResult; +} + +impl PayloadEntity for ExecutionResultV1 { + const RESPONSE_TYPE: ResponseType = ResponseType::ExecutionResultV1; +} + +impl PayloadEntity for SignedBlock { + const RESPONSE_TYPE: ResponseType = ResponseType::SignedBlock; +} + +impl PayloadEntity for TransactionWithExecutionInfo { + const RESPONSE_TYPE: ResponseType = ResponseType::TransactionWithExecutionInfo; +} + +impl PayloadEntity for Peers { + const RESPONSE_TYPE: ResponseType = ResponseType::Peers; +} + +impl PayloadEntity for Vec { + const RESPONSE_TYPE: ResponseType = ResponseType::Transfers; +} + +impl PayloadEntity for AvailableBlockRange { + const RESPONSE_TYPE: ResponseType = ResponseType::AvailableBlockRange; +} + +impl PayloadEntity for ChainspecRawBytes { + const RESPONSE_TYPE: ResponseType = ResponseType::ChainspecRawBytes; +} + +impl PayloadEntity for ConsensusValidatorChanges { + const RESPONSE_TYPE: ResponseType = ResponseType::ConsensusValidatorChanges; +} + +impl PayloadEntity for GlobalStateQueryResult { + const RESPONSE_TYPE: ResponseType = ResponseType::GlobalStateQueryResult; +} + +impl PayloadEntity for DictionaryQueryResult { + const RESPONSE_TYPE: ResponseType = ResponseType::DictionaryQueryResult; +} + +impl PayloadEntity for Vec { + const RESPONSE_TYPE: ResponseType = ResponseType::StoredValues; +} + +impl PayloadEntity for GetTrieFullResult { + const RESPONSE_TYPE: ResponseType = ResponseType::GetTrieFullResult; +} + +impl PayloadEntity for SpeculativeExecutionResult { + const RESPONSE_TYPE: ResponseType = ResponseType::SpeculativeExecutionResult; +} + +impl PayloadEntity for NodeStatus { + const RESPONSE_TYPE: ResponseType = ResponseType::NodeStatus; +} + +impl PayloadEntity for NextUpgrade { + const RESPONSE_TYPE: ResponseType = ResponseType::NextUpgrade; +} + +impl PayloadEntity for Uptime { + const RESPONSE_TYPE: ResponseType = ResponseType::Uptime; +} + +impl PayloadEntity for LastProgress { + const RESPONSE_TYPE: ResponseType = ResponseType::LastProgress; +} + +impl PayloadEntity for ReactorStateName { + const RESPONSE_TYPE: ResponseType = ResponseType::ReactorState; +} + +impl PayloadEntity for NetworkName { + const RESPONSE_TYPE: ResponseType = ResponseType::NetworkName; +} + +impl PayloadEntity for BlockSynchronizerStatus { + const RESPONSE_TYPE: ResponseType = ResponseType::BlockSynchronizerStatus; +} + +impl PayloadEntity for ConsensusStatus { + const RESPONSE_TYPE: ResponseType = ResponseType::ConsensusStatus; +} + +impl PayloadEntity for BalanceResponse { + const RESPONSE_TYPE: ResponseType = ResponseType::BalanceResponse; +} + +impl PayloadEntity for RewardResponse { + const RESPONSE_TYPE: ResponseType = ResponseType::Reward; +} + +impl PayloadEntity for ProtocolVersion { + const RESPONSE_TYPE: ResponseType = ResponseType::ProtocolVersion; +} + +impl PayloadEntity for ContractPackage { + const RESPONSE_TYPE: ResponseType = ResponseType::ContractPackage; +} + +impl PayloadEntity for ContractWithWasm { + const RESPONSE_TYPE: ResponseType = ResponseType::ContractWithWasm; +} + +impl PayloadEntity for Account { + const RESPONSE_TYPE: ResponseType = ResponseType::Account; +} + +impl PayloadEntity for Package { + const RESPONSE_TYPE: ResponseType = ResponseType::Package; +} + +impl PayloadEntity for AddressableEntityWithByteCode { + const RESPONSE_TYPE: ResponseType = ResponseType::AddressableEntityWithByteCode; +} + +#[cfg(test)] +mod tests { + use super::*; + use casper_types::testing::TestRng; + + #[test] + fn convert_u8_roundtrip() { + let rng = &mut TestRng::new(); + + let val = ResponseType::random(rng); + assert_eq!(ResponseType::try_from(val as u8), Ok(val)); + } +} diff --git a/node/BINARY_PORT_PROTOCOL.md b/node/BINARY_PORT_PROTOCOL.md index d1fc124cd8..3f974dea83 100644 --- a/node/BINARY_PORT_PROTOCOL.md +++ b/node/BINARY_PORT_PROTOCOL.md @@ -5,12 +5,12 @@ This page specifies the communication protocol between the [RPC Sidecar](https:/ The communication protocol between the Sidecar and the binary port is a binary protocol that follows a simple request-response model. The protocol consists of one party (the client) sending requests to another party (the server) and the server sending responses back to the client. Both requests and responses are wrapped in envelopes containing a version and a payload type tag. The versioning scheme is based on [SemVer](https://semver.org/). See [versioning](#versioning) for more details. The payload type tags are used to interpret the contents of the payloads. ### Request format -| Size in bytes | Field | Description | -|---------------|-----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Size in bytes | Field | Description | +|---------------|-----------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 2 | Version of the binary port header | Version of the binary port header serialized as a single u16 number. Upon receiving the request, the binary port component will first read data from this field and check it against the currently supported version. In case of a version mismatch, the appropriate error response will be sent. | -| 12 | Chain protocol version | Chain protocol version as a u32 triplet (major, minor, patch). This parameter is used to determine whether an incoming request is compatible (according to semver rules) with the current chain protocol version. If not, the appropriate error response will be sent. | -| 1 | BinaryRequestTag | Tag identifying the request. | -| Variable | RequestPayload | Payload to be interpreted according to the `BinaryRequestTag`. | +| 12 | Chain protocol version | Chain protocol version as a u32 triplet (major, minor, patch). This parameter is used to determine whether an incoming request is compatible (according to semver rules) with the current chain protocol version. If not, the appropriate error response will be sent. | +| 1 | BinaryRequestTag | Tag identifying the request. | +| Variable | RequestPayload | Payload to be interpreted according to the `BinaryRequestTag`. | Request bytes can be constructed from the bytesrepr-serialized `BinaryRequestHeader` followed by the bytesrepr-serialized `BinaryRequest`. @@ -19,13 +19,13 @@ Request bytes can be constructed from the bytesrepr-serialized `BinaryRequestHea ### Response format | Size in bytes | Field | Description | |-----------------|-----------------|--------------------------------------------------------------------------| -| 2 | Request ID | Request ID as a u16 number. | -| 4 | LengthOfRequest | Length of the request (encoded as bytes) for this response. | -| LengthOfRequest | RequestBytes | The request, encoded as bytes, corresponding to this response. | +| 2 | Request ID | Request ID as a u16 number. | +| 4 | LengthOfRequest | Length of the request (encoded as bytes) for this response. | +| LengthOfRequest | RequestBytes | The request, encoded as bytes, corresponding to this response. | | 12 | ProtocolVersion | Protocol version as a u32 triplet (major, minor, patch). | | 2 | ErrorCode | Error code, where 0 indicates success. | -| 1-2 | PayloadType | Optional payload type tag (first byte being 1 indicates that it exists). | -| Variable | Payload | Payload to be interpreted according to the `PayloadTag`. | +| 1-2 | ResponseType | Optional payload type tag (first byte being 1 indicates that it exists).| +| Variable | Payload | Payload to be interpreted according to the `PayloadTag`. | `BinaryResponseAndRequest` object can be bytesrepr-deserialized from these bytes. @@ -34,7 +34,7 @@ Request bytes can be constructed from the bytesrepr-serialized `BinaryRequestHea ## Versioning Versioning is based on the protocol version of the Casper Platform. The request/response model was designed to support **backward-compatible** changes to some parts, which are allowed to change between **MINOR** versions: - addition of a new [`BinaryRequestTag`](#request-format) with its own payload -- addition of a new [`PayloadType`](#response-format) with its own payload +- addition of a new [`ResponseType`](#response-format) with its own payload - addition of a new [`RecordId`](#request-model-details) - addition of a new [`InformationRequestTag`](#request-model-details) - addition of a new [`ErrorCode`](#response-format) diff --git a/node/src/components/binary_port.rs b/node/src/components/binary_port.rs index d1ddfdd5d5..10eb435e9a 100644 --- a/node/src/components/binary_port.rs +++ b/node/src/components/binary_port.rs @@ -14,7 +14,7 @@ use casper_binary_port::{ ContractWithWasm, DictionaryItemIdentifier, DictionaryQueryResult, EntityIdentifier, EraIdentifier, ErrorCode, GetRequest, GetTrieFullResult, GlobalStateQueryResult, GlobalStateRequest, InformationRequest, InformationRequestTag, KeyPrefix, NodeStatus, - PackageIdentifier, PayloadType, PurseIdentifier, ReactorStateName, RecordId, RewardResponse, + PackageIdentifier, PurseIdentifier, ReactorStateName, RecordId, ResponseType, RewardResponse, TransactionWithExecutionInfo, }; use casper_storage::{ @@ -221,7 +221,7 @@ where let Ok(serialized) = bincode::serialize(&transfers) else { return BinaryResponse::new_error(ErrorCode::InternalError, protocol_version); }; - BinaryResponse::from_raw_bytes(PayloadType::Transfers, serialized, protocol_version) + BinaryResponse::from_raw_bytes(ResponseType::Transfers, serialized, protocol_version) } GetRequest::Record { record_type_tag, @@ -233,7 +233,8 @@ where let Some(db_bytes) = effect_builder.get_raw_data(record_id, key).await else { return BinaryResponse::new_empty(protocol_version); }; - let payload_type = PayloadType::from_record_id(record_id, db_bytes.is_legacy()); + let payload_type = + ResponseType::from_record_id(record_id, db_bytes.is_legacy()); BinaryResponse::from_raw_bytes( payload_type, db_bytes.into_raw_bytes(), diff --git a/node/src/reactor/main_reactor/tests/binary_port.rs b/node/src/reactor/main_reactor/tests/binary_port.rs index cbed01109a..9896e85c0f 100644 --- a/node/src/reactor/main_reactor/tests/binary_port.rs +++ b/node/src/reactor/main_reactor/tests/binary_port.rs @@ -12,8 +12,8 @@ use casper_binary_port::{ ConsensusValidatorChanges, ContractWithWasm, DictionaryItemIdentifier, DictionaryQueryResult, EntityIdentifier, EraIdentifier, ErrorCode, GetRequest, GetTrieFullResult, GlobalStateQueryResult, GlobalStateRequest, InformationRequest, InformationRequestTag, - KeyPrefix, LastProgress, NetworkName, NodeStatus, PackageIdentifier, PayloadType, - PurseIdentifier, ReactorStateName, RecordId, RewardResponse, Uptime, + KeyPrefix, LastProgress, NetworkName, NodeStatus, PackageIdentifier, PurseIdentifier, + ReactorStateName, RecordId, ResponseType, RewardResponse, Uptime, }; use casper_storage::global_state::state::CommitProvider; use casper_types::{ @@ -362,7 +362,7 @@ struct TestCase { fn validate_metadata( response: &BinaryResponse, - expected_payload_type: Option, + expected_payload_type: Option, ) -> bool { response.is_success() && response.returned_data_type_tag() @@ -384,7 +384,7 @@ where fn assert_response( response: &BinaryResponse, - payload_type: Option, + payload_type: Option, validator: F, ) -> bool where @@ -562,7 +562,7 @@ fn block_header_info(hash: BlockHash) -> TestCase { .expect("should convert"), ), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::BlockHeader), |header| { + assert_response::(response, Some(ResponseType::BlockHeader), |header| { header.block_hash() == hash }) }), @@ -578,7 +578,7 @@ fn signed_block_info(hash: BlockHash) -> TestCase { .expect("should convert"), ), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::SignedBlock), |header| { + assert_response::(response, Some(ResponseType::SignedBlock), |header| { *header.block().hash() == hash }) }), @@ -593,7 +593,7 @@ fn peers() -> TestCase { key: vec![], }), asserter: Box::new(|response| { - assert_response::(response, Some(PayloadType::Peers), |peers| { + assert_response::(response, Some(ResponseType::Peers), |peers| { !peers.into_inner().is_empty() }) }), @@ -608,7 +608,7 @@ fn uptime() -> TestCase { key: vec![], }), asserter: Box::new(|response| { - assert_response::(response, Some(PayloadType::Uptime), |uptime| { + assert_response::(response, Some(ResponseType::Uptime), |uptime| { uptime.into_inner() > 0 }) }), @@ -625,7 +625,7 @@ fn last_progress() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::LastProgress), + Some(ResponseType::LastProgress), |last_progress| last_progress.into_inner().millis() > 0, ) }), @@ -642,7 +642,7 @@ fn reactor_state() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::ReactorState), + Some(ResponseType::ReactorState), |reactor_state| matches!(reactor_state.into_inner().as_str(), "Validate"), ) }), @@ -659,7 +659,7 @@ fn network_name() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::NetworkName), + Some(ResponseType::NetworkName), |network_name| &network_name.into_inner() == "casper-example", ) }), @@ -676,7 +676,7 @@ fn consensus_validator_changes() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::ConsensusValidatorChanges), + Some(ResponseType::ConsensusValidatorChanges), |cvc| cvc.into_inner().is_empty(), ) }), @@ -693,7 +693,7 @@ fn block_synchronizer_status() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::BlockSynchronizerStatus), + Some(ResponseType::BlockSynchronizerStatus), |bss| bss.historical().is_none() && bss.forward().is_none(), ) }), @@ -710,7 +710,7 @@ fn available_block_range(expected_height: u64) -> TestCase { asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::AvailableBlockRange), + Some(ResponseType::AvailableBlockRange), |abr| abr.low() == 0 && abr.high() >= expected_height, ) }), @@ -738,7 +738,7 @@ fn consensus_status() -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::ConsensusStatus), + Some(ResponseType::ConsensusStatus), |_| true, ) }), @@ -755,7 +755,7 @@ fn chainspec_raw_bytes(network_chainspec_raw_bytes: ChainspecRawBytes) -> TestCa asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::ChainspecRawBytes), + Some(ResponseType::ChainspecRawBytes), |crb| crb == network_chainspec_raw_bytes, ) }), @@ -770,7 +770,7 @@ fn latest_switch_block_header() -> TestCase { key: vec![], }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::BlockHeader), |header| { + assert_response::(response, Some(ResponseType::BlockHeader), |header| { header.is_switch_block() }) }), @@ -787,7 +787,7 @@ fn node_status(expected_version: ProtocolVersion) -> TestCase { asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::NodeStatus), + Some(ResponseType::NodeStatus), |node_status| { node_status.protocol_version == expected_version && !node_status.peers.into_inner().is_empty() @@ -812,7 +812,7 @@ fn get_block_header(expected: BlockHeader) -> TestCase { key: expected.block_hash().to_bytes().unwrap(), }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::BlockHeader), |header| { + assert_response::(response, Some(ResponseType::BlockHeader), |header| { header == expected }) }), @@ -827,7 +827,7 @@ fn get_block_transfers(expected: BlockHeader) -> TestCase { key: expected.block_hash().to_bytes().unwrap(), }), asserter: Box::new(move |response| { - validate_metadata(response, Some(PayloadType::Transfers)) + validate_metadata(response, Some(ResponseType::Transfers)) && bincode::deserialize::>(response.payload()).is_ok() }), } @@ -844,7 +844,7 @@ fn get_era_summary(state_root_hash: Digest) -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::GlobalStateQueryResult), + Some(ResponseType::GlobalStateQueryResult), |res| { let (value, _) = res.into_inner(); matches!(value, StoredValue::EraInfo(_)) @@ -864,7 +864,7 @@ fn get_all_bids(state_root_hash: Digest) -> TestCase { asserter: Box::new(|response| { assert_response::, _>( response, - Some(PayloadType::StoredValues), + Some(ResponseType::StoredValues), |res| res.iter().all(|v| matches!(v, StoredValue::BidKind(_))), ) }), @@ -880,7 +880,7 @@ fn get_trie(digest: Digest) -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::GetTrieFullResult), + Some(ResponseType::GetTrieFullResult), |res| res.into_inner().is_some(), ) }), @@ -899,7 +899,7 @@ fn get_dictionary_item_by_addr(state_root_hash: Digest, addr: DictionaryAddr) -> asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::DictionaryQueryResult), + Some(ResponseType::DictionaryQueryResult), |res| { matches!( res.into_inner(), @@ -930,7 +930,7 @@ fn get_dictionary_item_by_seed_uref( asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::DictionaryQueryResult), + Some(ResponseType::DictionaryQueryResult), |res| { let expected_key = Key::dictionary(seed_uref, dictionary_item_key.as_bytes()); matches!( @@ -964,7 +964,7 @@ fn get_dictionary_item_by_legacy_named_key( asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::DictionaryQueryResult), + Some(ResponseType::DictionaryQueryResult), |res| matches!(res.into_inner(),(_, res) if res.value().as_cl_value().is_some()), ) }), @@ -992,7 +992,7 @@ fn get_dictionary_item_by_named_key( asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::DictionaryQueryResult), + Some(ResponseType::DictionaryQueryResult), |res| matches!(res.into_inner(),(_, res) if res.value().as_cl_value().is_some()), ) }), @@ -1009,7 +1009,7 @@ fn get_balance(state_root_hash: Digest, account_hash: AccountHash) -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::BalanceResponse), + Some(ResponseType::BalanceResponse), |res| res.available_balance == U512::one(), ) }), @@ -1050,7 +1050,7 @@ fn get_named_keys_by_prefix(state_root_hash: Digest, entity_addr: EntityAddr) -> asserter: Box::new(|response| { assert_response::, _>( response, - Some(PayloadType::StoredValues), + Some(ResponseType::StoredValues), |res| res.iter().all(|v| matches!(v, StoredValue::NamedKey(_))), ) }), @@ -1075,7 +1075,7 @@ fn get_reward( key: key.to_bytes().expect("should serialize key"), }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::Reward), |reward| { + assert_response::(response, Some(ResponseType::Reward), |reward| { // test fixture sets delegation rate to 0 reward.amount() > U512::zero() && reward.delegation_rate() == 0 }) @@ -1095,7 +1095,7 @@ fn get_protocol_version(expected: ProtocolVersion) -> TestCase { asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::ProtocolVersion), + Some(ResponseType::ProtocolVersion), |version| expected == version, ) }), @@ -1118,7 +1118,7 @@ fn get_entity(state_root_hash: Digest, entity_addr: EntityAddr) -> TestCase { asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::AddressableEntityWithByteCode), + Some(ResponseType::AddressableEntityWithByteCode), |res| res.bytecode().is_some(), ) }), @@ -1141,7 +1141,7 @@ fn get_entity_without_bytecode(state_root_hash: Digest, entity_addr: EntityAddr) asserter: Box::new(|response| { assert_response::( response, - Some(PayloadType::AddressableEntityWithByteCode), + Some(ResponseType::AddressableEntityWithByteCode), |res| res.bytecode().is_none(), ) }), @@ -1165,7 +1165,7 @@ fn get_entity_pre_migration_account( key: key.to_bytes().expect("should serialize key"), }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::Account), |res| { + assert_response::(response, Some(ResponseType::Account), |res| { res.account_hash() == account_hash }) }), @@ -1191,7 +1191,7 @@ fn get_entity_post_migration_account( asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::AddressableEntityWithByteCode), + Some(ResponseType::AddressableEntityWithByteCode), |_| true, ) }), @@ -1217,7 +1217,7 @@ fn get_entity_pre_migration_contract( asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::ContractWithWasm), + Some(ResponseType::ContractWithWasm), |res| res.wasm().is_some(), ) }), @@ -1243,7 +1243,7 @@ fn get_entity_post_migration_contract( asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::AddressableEntityWithByteCode), + Some(ResponseType::AddressableEntityWithByteCode), |res| res.bytecode().is_some(), ) }), @@ -1263,7 +1263,7 @@ fn get_package(state_root_hash: Digest, package_addr: PackageAddr) -> TestCase { key: key.to_bytes().expect("should serialize key"), }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::Package), |_| true) + assert_response::(response, Some(ResponseType::Package), |_| true) }), } } @@ -1286,7 +1286,7 @@ fn get_package_pre_migration( asserter: Box::new(move |response| { assert_response::( response, - Some(PayloadType::ContractPackage), + Some(ResponseType::ContractPackage), |_| true, ) }), @@ -1309,7 +1309,7 @@ fn get_package_post_migration( key: key.to_bytes().expect("should serialize key"), }), asserter: Box::new(move |response| { - assert_response::(response, Some(PayloadType::Package), |_| true) + assert_response::(response, Some(ResponseType::Package), |_| true) }), } }