Skip to content

Commit

Permalink
chore(jsonrpc): move request parsing logic to server (#6853)
Browse files Browse the repository at this point in the history
Tracking issue: #6850

Supercedes: #6849

Move request parsing logic from `jsonrpc-primitives` to the server.
  • Loading branch information
miraclx authored May 20, 2022
1 parent 1eed163 commit d18f345
Show file tree
Hide file tree
Showing 18 changed files with 262 additions and 278 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

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

2 changes: 0 additions & 2 deletions chain/jsonrpc-adversarial-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ edition = "2021"

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
near-primitives = { path = "../../core/primitives" }

near-jsonrpc-primitives = { path = "../jsonrpc-primitives" }
near-network-primitives = { path = "../network-primitives" }
deepsize = { version = "0.2.0", optional = true }

Expand Down
17 changes: 0 additions & 17 deletions chain/jsonrpc-adversarial-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,6 @@ pub struct SetRoutingTableRequest {
pub prune_edges: Option<bool>,
}

#[cfg(feature = "test_features")]
impl SetRoutingTableRequest {
pub fn parse(
value: Option<serde_json::Value>,
) -> Result<Self, near_jsonrpc_primitives::errors::RpcError> {
if let Some(value) = value {
serde_json::from_value(value).map_err(|err| {
near_jsonrpc_primitives::errors::RpcError::parse_error(format!("Error {:?}", err))
})
} else {
Err(near_jsonrpc_primitives::errors::RpcError::parse_error(
"Require at least one parameter".to_owned(),
))
}
}
}

#[derive(Deserialize)]
pub struct SetAdvOptionsRequest {
pub disable_edge_signature_verification: Option<bool>,
Expand Down
1 change: 0 additions & 1 deletion chain/jsonrpc-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ pub mod errors;
pub mod message;
pub(crate) mod metrics;
pub mod types;
pub(crate) mod utils;
13 changes: 0 additions & 13 deletions chain/jsonrpc-primitives/src/types/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,3 @@ impl From<RpcBlockError> for crate::errors::RpcError {
Self::new_internal_or_handler_error(error_data, error_data_value)
}
}

impl RpcBlockRequest {
pub fn parse(value: Option<Value>) -> Result<RpcBlockRequest, crate::errors::RpcParseError> {
let block_reference = if let Ok((block_id,)) =
crate::utils::parse_params::<(near_primitives::types::BlockId,)>(value.clone())
{
near_primitives::types::BlockReference::BlockId(block_id)
} else {
crate::utils::parse_params::<near_primitives::types::BlockReference>(value)?
};
Ok(RpcBlockRequest { block_reference })
}
}
13 changes: 0 additions & 13 deletions chain/jsonrpc-primitives/src/types/changes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Serialize, Deserialize)]
pub struct RpcStateChangesInBlockRequest {
Expand Down Expand Up @@ -41,18 +40,6 @@ pub enum RpcStateChangesError {
InternalError { error_message: String },
}

impl RpcStateChangesInBlockRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
}
}

impl RpcStateChangesInBlockByTypeRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
}
}

impl From<near_client_primitives::types::GetBlockError> for RpcStateChangesError {
fn from(error: near_client_primitives::types::GetBlockError) -> Self {
match error {
Expand Down
20 changes: 0 additions & 20 deletions chain/jsonrpc-primitives/src/types/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,6 @@ impl From<ChunkReference> for near_client_primitives::types::GetChunk {
}
}

impl RpcChunkRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
// Try to parse legacy positioned args and if it fails parse newer named args
let chunk_reference = if let Ok((chunk_id,)) =
crate::utils::parse_params::<(near_primitives::hash::CryptoHash,)>(value.clone())
{
ChunkReference::ChunkHash { chunk_id }
} else if let Ok(((block_id, shard_id),)) = crate::utils::parse_params::<((
near_primitives::types::BlockId,
near_primitives::types::ShardId,
),)>(value.clone())
{
ChunkReference::BlockShardId { block_id, shard_id }
} else {
crate::utils::parse_params::<ChunkReference>(value)?
};
Ok(Self { chunk_reference })
}
}

impl From<near_client_primitives::types::GetChunkError> for RpcChunkError {
fn from(error: near_client_primitives::types::GetChunkError) -> Self {
match error {
Expand Down
9 changes: 0 additions & 9 deletions chain/jsonrpc-primitives/src/types/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,6 @@ pub struct RpcProtocolConfigRequest {
pub block_reference: near_primitives::types::BlockReference,
}

impl RpcProtocolConfigRequest {
pub fn parse(
value: Option<Value>,
) -> Result<RpcProtocolConfigRequest, crate::errors::RpcParseError> {
crate::utils::parse_params::<near_primitives::types::BlockReference>(value)
.map(|block_reference| RpcProtocolConfigRequest { block_reference })
}
}

#[derive(Serialize, Deserialize, Debug)]
pub struct RpcProtocolConfigResponse {
#[serde(flatten)]
Expand Down
7 changes: 0 additions & 7 deletions chain/jsonrpc-primitives/src/types/gas_price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,3 @@ impl From<RpcGasPriceError> for crate::errors::RpcError {
Self::new_internal_or_handler_error(error_data, error_data_value)
}
}

impl RpcGasPriceRequest {
pub fn parse(value: Option<Value>) -> Result<RpcGasPriceRequest, crate::errors::RpcParseError> {
crate::utils::parse_params::<(MaybeBlockId,)>(value)
.map(|(block_id,)| RpcGasPriceRequest { block_id })
}
}
18 changes: 0 additions & 18 deletions chain/jsonrpc-primitives/src/types/light_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,6 @@ pub enum RpcLightClientNextBlockError {
EpochOutOfBounds { epoch_id: near_primitives::types::EpochId },
}

impl RpcLightClientExecutionProofRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<Self>(value)?)
}
}

impl RpcLightClientNextBlockRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
if let Ok((last_block_hash,)) =
crate::utils::parse_params::<(near_primitives::hash::CryptoHash,)>(value.clone())
{
Ok(Self { last_block_hash })
} else {
Ok(crate::utils::parse_params::<Self>(value)?)
}
}
}

impl From<Option<near_primitives::views::LightClientBlockView>>
for RpcLightClientNextBlockResponse
{
Expand Down
81 changes: 0 additions & 81 deletions chain/jsonrpc-primitives/src/types/query.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Max size of the query path (soft-deprecated)
const QUERY_DATA_MAX_SIZE: usize = 10 * 1024;

#[derive(Serialize, Deserialize, Debug)]
pub struct RpcQueryRequest {
Expand Down Expand Up @@ -89,83 +85,6 @@ pub enum QueryResponseKind {
AccessKeyList(near_primitives::views::AccessKeyList),
}

impl RpcQueryRequest {
pub fn parse(value: Option<Value>) -> Result<RpcQueryRequest, crate::errors::RpcParseError> {
let query_request = if let Ok((path, data)) =
crate::utils::parse_params::<(String, String)>(value.clone())
{
// Handle a soft-deprecated version of the query API, which is based on
// positional arguments with a "path"-style first argument.
//
// This whole block can be removed one day, when the new API is 100% adopted.
let data = near_primitives_core::serialize::from_base(&data)
.map_err(|err| crate::errors::RpcParseError(err.to_string()))?;
let query_data_size = path.len() + data.len();
if query_data_size > QUERY_DATA_MAX_SIZE {
return Err(crate::errors::RpcParseError(format!(
"Query data size {} is too large",
query_data_size
)));
}

let mut path_parts = path.splitn(3, '/');
let make_err =
|| crate::errors::RpcParseError("Not enough query parameters provided".to_string());
let query_command = path_parts.next().ok_or_else(make_err)?;
let account_id = path_parts
.next()
.ok_or_else(make_err)?
.parse()
.map_err(|err| crate::errors::RpcParseError(format!("{}", err)))?;
let maybe_extra_arg = path_parts.next();

let request = match query_command {
"account" => near_primitives::views::QueryRequest::ViewAccount { account_id },
"access_key" => match maybe_extra_arg {
None => near_primitives::views::QueryRequest::ViewAccessKeyList { account_id },
Some(pk) => near_primitives::views::QueryRequest::ViewAccessKey {
account_id,
public_key: pk.parse().map_err(|_| {
crate::errors::RpcParseError("Invalid public key".to_string())
})?,
},
},
"code" => near_primitives::views::QueryRequest::ViewCode { account_id },
"contract" => near_primitives::views::QueryRequest::ViewState {
account_id,
prefix: data.into(),
},
"call" => match maybe_extra_arg {
Some(method_name) => near_primitives::views::QueryRequest::CallFunction {
account_id,
method_name: method_name.to_string(),
args: data.into(),
},
None => {
return Err(crate::errors::RpcParseError(
"Method name is missing".to_string(),
))
}
},
_ => {
return Err(crate::errors::RpcParseError(format!(
"Unknown path {}",
query_command
)))
}
};
// Use Finality::None here to make backward compatibility tests work
RpcQueryRequest {
request,
block_reference: near_primitives::types::BlockReference::latest(),
}
} else {
crate::utils::parse_params::<RpcQueryRequest>(value)?
};
Ok(query_request)
}
}

impl From<near_client_primitives::types::QueryError> for RpcQueryError {
fn from(error: near_client_primitives::types::QueryError) -> Self {
match error {
Expand Down
8 changes: 0 additions & 8 deletions chain/jsonrpc-primitives/src/types/receipts.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReceiptReference {
Expand Down Expand Up @@ -33,13 +32,6 @@ impl From<ReceiptReference> for near_client_primitives::types::GetReceipt {
}
}

impl RpcReceiptRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let receipt_reference = crate::utils::parse_params::<ReceiptReference>(value)?;
Ok(Self { receipt_reference })
}
}

impl From<near_client_primitives::types::GetReceiptError> for RpcReceiptError {
fn from(error: near_client_primitives::types::GetReceiptError) -> Self {
match error {
Expand Down
13 changes: 0 additions & 13 deletions chain/jsonrpc-primitives/src/types/sandbox.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
use near_primitives::state_record::StateRecord;
use near_primitives::types::BlockHeightDelta;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Deserialize, Serialize, Debug)]
pub struct RpcSandboxPatchStateRequest {
pub records: Vec<StateRecord>,
}

impl RpcSandboxPatchStateRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcSandboxPatchStateRequest>(value)?)
}
}

#[derive(Deserialize, Serialize, Debug)]
pub struct RpcSandboxPatchStateResponse {}

Expand Down Expand Up @@ -50,12 +43,6 @@ pub struct RpcSandboxFastForwardRequest {
pub delta_height: BlockHeightDelta,
}

impl RpcSandboxFastForwardRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcSandboxFastForwardRequest>(value)?)
}
}

#[derive(Deserialize, Serialize)]
pub struct RpcSandboxFastForwardResponse {}

Expand Down
26 changes: 0 additions & 26 deletions chain/jsonrpc-primitives/src/types/transactions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;

use near_primitives::types::AccountId;

#[derive(Debug, Clone)]
pub struct RpcBroadcastTransactionRequest {
pub signed_transaction: near_primitives::transaction::SignedTransaction,
Expand Down Expand Up @@ -53,30 +51,6 @@ pub struct RpcBroadcastTxSyncResponse {
pub transaction_hash: near_primitives::hash::CryptoHash,
}

impl RpcBroadcastTransactionRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let signed_transaction = crate::utils::parse_signed_transaction(value)?;
Ok(Self { signed_transaction })
}
}

impl RpcTransactionStatusCommonRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
if let Ok((hash, account_id)) = crate::utils::parse_params::<(
near_primitives::hash::CryptoHash,
AccountId,
)>(value.clone())
{
let transaction_info = TransactionInfo::TransactionId { hash, account_id };
Ok(Self { transaction_info })
} else {
let signed_transaction = crate::utils::parse_signed_transaction(value)?;
let transaction_info = TransactionInfo::Transaction(signed_transaction);
Ok(Self { transaction_info })
}
}
}

impl From<near_client_primitives::types::TxStatusError> for RpcTransactionError {
fn from(error: near_client_primitives::types::TxStatusError) -> Self {
match error {
Expand Down
22 changes: 0 additions & 22 deletions chain/jsonrpc-primitives/src/types/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,28 +63,6 @@ impl From<actix::MailboxError> for RpcValidatorError {
}
}

impl RpcValidatorRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
let epoch_reference = if let Ok((block_id,)) =
crate::utils::parse_params::<(near_primitives::types::MaybeBlockId,)>(value.clone())
{
match block_id {
Some(id) => near_primitives::types::EpochReference::BlockId(id),
None => near_primitives::types::EpochReference::Latest,
}
} else {
crate::utils::parse_params::<near_primitives::types::EpochReference>(value)?
};
Ok(Self { epoch_reference })
}
}

impl RpcValidatorsOrderedRequest {
pub fn parse(value: Option<Value>) -> Result<Self, crate::errors::RpcParseError> {
Ok(crate::utils::parse_params::<RpcValidatorsOrderedRequest>(value)?)
}
}

impl From<RpcValidatorError> for crate::errors::RpcError {
fn from(error: RpcValidatorError) -> Self {
let error_data = match &error {
Expand Down
Loading

0 comments on commit d18f345

Please sign in to comment.