Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
revert error codes
  • Loading branch information
niklasad1 committed Apr 20, 2022
commit 2ab97f79956355a77b293d66dccc3ad5b25dd692
38 changes: 34 additions & 4 deletions client/beefy/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use futures::{task::SpawnError, FutureExt, StreamExt};
use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
proc_macros::rpc,
types::{error::CallError, ErrorObject},
PendingSubscription,
};
use log::warn;
Expand All @@ -49,7 +50,36 @@ pub enum Error {
RpcTaskFailure(#[from] SpawnError),
}

/// Provides RPC methods for interacting with BEEFY.
/// The error codes returned by jsonrpc.
pub enum ErrorCode {
/// Returned when BEEFY RPC endpoint is not ready.
NotReady = 1,
/// Returned on BEEFY RPC background task failure.
TaskFailure = 2,
}

impl From<Error> for ErrorCode {
fn from(error: Error) -> Self {
match error {
Error::EndpointNotReady => ErrorCode::NotReady,
Error::RpcTaskFailure(_) => ErrorCode::TaskFailure,
}
}
}

impl From<Error> for JsonRpseeError {
fn from(error: Error) -> Self {
let message = error.to_string();
let code = ErrorCode::from(error);
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
code as i32,
message,
None::<()>,
)))
}
}

// Provides RPC methods for interacting with BEEFY.
#[rpc(client, server)]
pub trait BeefyApi<Notification, Hash> {
/// Returns the block most recently finalized by BEEFY, alongside side its justification.
Expand Down Expand Up @@ -129,7 +159,7 @@ where
.as_ref()
.cloned()
.ok_or(Error::EndpointNotReady)
.map_err(|e| JsonRpseeError::to_call_error(e))
.map_err(Into::into)
}
}

Expand Down Expand Up @@ -172,7 +202,7 @@ mod tests {
async fn uninitialized_rpc_handler() {
let (rpc, _) = setup_io_handler();
let request = r#"{"jsonrpc":"2.0","method":"beefy_getFinalizedHead","params":[],"id":1}"#;
let expected_response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"BEEFY RPC endpoint not ready"},"id":1}"#.to_string();
let expected_response = r#"{"jsonrpc":"2.0","error":{"code":1,"message":"BEEFY RPC endpoint not ready"},"id":1}"#.to_string();
let (result, _) = rpc.raw_json_request(&request).await.unwrap();

assert_eq!(expected_response, result,);
Expand All @@ -197,7 +227,7 @@ mod tests {
.to_string();
let not_ready = "{\
\"jsonrpc\":\"2.0\",\
\"error\":{\"code\":-32000,\"message\":\"BEEFY RPC endpoint not ready\"},\
\"error\":{\"code\":1,\"message\":\"BEEFY RPC endpoint not ready\"},\
\"id\":1\
}"
.to_string();
Expand Down
9 changes: 7 additions & 2 deletions client/consensus/babe/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use futures::TryFutureExt;
use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
proc_macros::rpc,
types::{error::CallError, ErrorObject},
};

use sc_consensus_babe::{authorship, Config, Epoch};
Expand Down Expand Up @@ -172,7 +173,11 @@ pub enum Error {

impl From<Error> for JsonRpseeError {
fn from(error: Error) -> Self {
JsonRpseeError::to_call_error(error)
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
1234,
error.to_string(),
None::<()>,
)))
}
}

Expand Down Expand Up @@ -267,7 +272,7 @@ mod tests {

let request = r#"{"jsonrpc":"2.0","method":"babe_epochAuthorship","params":[],"id":1}"#;
let (response, _) = api.raw_json_request(request).await.unwrap();
let expected = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"RPC call is unsafe to be called externally"},"id":1}"#;
let expected = r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"RPC call is unsafe to be called externally"},"id":1}"#;

assert_eq!(&response, expected);
}
Expand Down
13 changes: 10 additions & 3 deletions client/finality-grandpa/rpc/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use jsonrpsee::types::error::{CallError, ErrorObject};
use jsonrpsee::{
core::Error as JsonRpseeError,
types::error::{CallError, ErrorObject},
};

#[derive(Debug, thiserror::Error)]
/// Top-level error type for the RPC handler
Expand Down Expand Up @@ -58,11 +61,15 @@ impl From<Error> for ErrorCode {
}
}

impl From<Error> for CallError {
impl From<Error> for JsonRpseeError {
fn from(error: Error) -> Self {
let message = error.to_string();
let code = ErrorCode::from(error);
Self::Custom(ErrorObject::owned(code as i32, message, None::<()>))
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
code as i32,
message,
None::<()>,
)))
}
}

Expand Down
14 changes: 8 additions & 6 deletions client/finality-grandpa/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use log::warn;
use std::sync::Arc;

use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
core::{async_trait, RpcResult},
proc_macros::rpc,
PendingSubscription,
};
Expand Down Expand Up @@ -99,8 +99,7 @@ where
ProofProvider: RpcFinalityProofProvider<Block> + Send + Sync + 'static,
{
async fn round_state(&self) -> RpcResult<ReportedRoundStates> {
ReportedRoundStates::from(&self.authority_set, &self.voter_state)
.map_err(|e| JsonRpseeError::to_call_error(e))
ReportedRoundStates::from(&self.authority_set, &self.voter_state).map_err(Into::into)
}

fn subscribe_justifications(&self, pending: PendingSubscription) {
Expand All @@ -127,8 +126,11 @@ where
) -> RpcResult<Option<EncodedFinalityProof>> {
self.finality_proof_provider
.rpc_prove_finality(block)
.map_err(|finality_err| error::Error::ProveFinalityFailed(finality_err))
.map_err(|e| JsonRpseeError::to_call_error(e))
.map_err(|e| {
warn!("Error proving finality: {}", e);
error::Error::ProveFinalityFailed(e)
})
.map_err(Into::into)
}
}

Expand Down Expand Up @@ -281,7 +283,7 @@ mod tests {
#[tokio::test]
async fn uninitialized_rpc_handler() {
let (rpc, _) = setup_io_handler(EmptyVoterState);
let expected_response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"GRANDPA RPC endpoint not ready"},"id":0}"#.to_string();
let expected_response = r#"{"jsonrpc":"2.0","error":{"code":1,"message":"GRANDPA RPC endpoint not ready"},"id":0}"#.to_string();
let request = r#"{"jsonrpc":"2.0","method":"grandpa_roundState","params":[],"id":0}"#;
let (result, _) = rpc.raw_json_request(&request).await.unwrap();

Expand Down
12 changes: 8 additions & 4 deletions client/rpc-api/src/offchain/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@

//! Offchain RPC errors.

use jsonrpsee::types::error::{CallError, ErrorObject};
use jsonrpsee::{
core::Error as JsonRpseeError,
types::error::{CallError, ErrorObject},
};

/// Offchain RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
Expand All @@ -37,14 +40,15 @@ pub enum Error {
/// Base error code for all offchain errors.
const BASE_ERROR: i32 = 5000;

impl From<Error> for CallError {
impl From<Error> for JsonRpseeError {
fn from(e: Error) -> Self {
match e {
Error::UnavailableStorageKind => Self::Custom(ErrorObject::owned(
Error::UnavailableStorageKind => CallError::Custom(ErrorObject::owned(
BASE_ERROR + 1,
"This storage kind is not available yet",
None::<()>,
)),
))
.into(),
Error::UnsafeRpcCalled(e) => e.into(),
}
}
Expand Down
16 changes: 13 additions & 3 deletions client/rpc-api/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@
//! Contains a `DenyUnsafe` type that can be used to deny potentially unsafe
//! RPC when accessed externally.

use jsonrpsee::{core::Error as JsonRpseeError, types::error::CallError};
use jsonrpsee::{
core::Error as JsonRpseeError,
types::{
error::{CallError, ErrorCode},
ErrorObject,
},
};

/// Signifies whether a potentially unsafe RPC should be denied.
#[derive(Clone, Copy, Debug)]
Expand Down Expand Up @@ -57,12 +63,16 @@ impl std::error::Error for UnsafeRpcError {}

impl From<UnsafeRpcError> for CallError {
fn from(e: UnsafeRpcError) -> CallError {
CallError::from_std_error(e)
CallError::Custom(ErrorObject::owned(
ErrorCode::MethodNotFound.code(),
e.to_string(),
None::<()>,
))
}
}

impl From<UnsafeRpcError> for JsonRpseeError {
fn from(e: UnsafeRpcError) -> JsonRpseeError {
JsonRpseeError::to_call_error(e)
JsonRpseeError::Call(e.into())
}
}
2 changes: 1 addition & 1 deletion client/rpc-api/src/state/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl From<Error> for JsonRpseeError {
Error::InvalidCount { .. } =>
CallError::Custom(ErrorObject::owned(BASE_ERROR + 2, e.to_string(), None::<()>))
.into(),
e => e.into(),
e => Self::to_call_error(e),
}
}
}
17 changes: 12 additions & 5 deletions client/rpc-api/src/system/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
//! System RPC module errors.

use crate::system::helpers::Health;
use jsonrpsee::types::error::{CallError, ErrorObject};
use jsonrpsee::{
core::Error as JsonRpseeError,
types::error::{CallError, ErrorObject},
};

/// System RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
Expand All @@ -42,13 +45,17 @@ const NOT_HEALTHY_ERROR: i32 = BASE_ERROR + 1;
// Peer argument is malformatted.
const MALFORMATTED_PEER_ARG_ERROR: i32 = BASE_ERROR + 2;

impl From<Error> for CallError {
impl From<Error> for JsonRpseeError {
fn from(e: Error) -> Self {
match e {
Error::NotHealthy(ref h) =>
Self::Custom(ErrorObject::owned(NOT_HEALTHY_ERROR, e.to_string(), Some(h))),
Error::MalformattedPeerArg(e) =>
Self::Custom(ErrorObject::owned(MALFORMATTED_PEER_ARG_ERROR + 2, e, None::<()>)),
CallError::Custom(ErrorObject::owned(NOT_HEALTHY_ERROR, e.to_string(), Some(h))),
Error::MalformattedPeerArg(e) => CallError::Custom(ErrorObject::owned(
MALFORMATTED_PEER_ARG_ERROR + 2,
e,
None::<()>,
)),
}
.into()
}
}
9 changes: 5 additions & 4 deletions client/rpc/src/author/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,17 @@ where
async fn submit_extrinsic(&self, ext: Bytes) -> RpcResult<TxHash<P>> {
let xt = match Decode::decode(&mut &ext[..]) {
Ok(xt) => xt,
Err(err) => return Err(JsonRpseeError::to_call_error(err)),
Err(err) => return Err(Error::Client(Box::new(err)).into()),
};
let best_block_hash = self.client.info().best_hash;
self.pool
.submit_one(&generic::BlockId::hash(best_block_hash), TX_SOURCE, xt)
.await
.map_err(|e| {
e.into_pool_error()
.map(|e| JsonRpseeError::to_call_error(e))
.unwrap_or_else(|e| JsonRpseeError::to_call_error(e))
.map(|e| Error::Pool(e))
.unwrap_or_else(|e| Error::Verification(Box::new(e)))
.into()
})
}

Expand Down Expand Up @@ -134,7 +135,7 @@ where
.client
.runtime_api()
.decode_session_keys(&generic::BlockId::Hash(best_block_hash), session_keys.to_vec())
.map_err(|e| JsonRpseeError::to_call_error(e))?
.map_err(|e| Error::Client(Box::new(e)))?
.ok_or_else(|| Error::InvalidSessionKeys)?;

Ok(SyncCryptoStore::has_keys(&*self.keystore, &keys))
Expand Down
4 changes: 2 additions & 2 deletions client/rpc/src/author/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ async fn author_submit_transaction_should_not_cause_error() {

assert_matches!(
api.call::<_, H256>("author_submitExtrinsic", [xt]).await,
Err(RpcError::Call(CallError::Custom(err))) if err.message().contains("Already imported")
Err(RpcError::Call(CallError::Custom(err))) if err.message().contains("Already Imported") && err.code() == 1013
);
}

Expand Down Expand Up @@ -159,7 +159,7 @@ async fn author_should_return_watch_validation_error() {

assert_matches!(
failed_sub,
Err(RpcError::Call(CallError::Custom(err))) if err.message().contains("Transaction pool error")
Err(RpcError::Call(CallError::Custom(err))) if err.message().contains("Invalid Transaction") && err.code() == 1010
);
}

Expand Down
6 changes: 2 additions & 4 deletions client/rpc/src/offchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ impl<T: OffchainStorage + 'static> OffchainApiServer for Offchain<T> {

let prefix = match kind {
StorageKind::PERSISTENT => sp_offchain::STORAGE_PREFIX,
StorageKind::LOCAL =>
return Err(JsonRpseeError::to_call_error(Error::UnavailableStorageKind)),
StorageKind::LOCAL => return Err(JsonRpseeError::from(Error::UnavailableStorageKind)),
};
self.storage.write().set(prefix, &*key, &*value);
Ok(())
Expand All @@ -67,8 +66,7 @@ impl<T: OffchainStorage + 'static> OffchainApiServer for Offchain<T> {

let prefix = match kind {
StorageKind::PERSISTENT => sp_offchain::STORAGE_PREFIX,
StorageKind::LOCAL =>
return Err(JsonRpseeError::to_call_error(Error::UnavailableStorageKind)),
StorageKind::LOCAL => return Err(JsonRpseeError::from(Error::UnavailableStorageKind)),
};

Ok(self.storage.read().get(prefix, &*key).map(Into::into))
Expand Down
8 changes: 4 additions & 4 deletions client/rpc/src/offchain/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ fn offchain_calls_considered_unsafe() {

assert_matches!(
offchain.set_local_storage(StorageKind::PERSISTENT, key.clone(), value.clone()),
Err(JsonRpseeError::Call(CallError::Failed(err))) => {
assert_eq!(err.to_string(), "RPC call is unsafe to be called externally")
Err(JsonRpseeError::Call(CallError::Custom(err))) => {
assert_eq!(err.message(), "RPC call is unsafe to be called externally")
}
);
assert_matches!(
offchain.get_local_storage(StorageKind::PERSISTENT, key),
Err(JsonRpseeError::Call(CallError::Failed(err))) => {
assert_eq!(err.to_string(), "RPC call is unsafe to be called externally")
Err(JsonRpseeError::Call(CallError::Custom(err))) => {
assert_eq!(err.message(), "RPC call is unsafe to be called externally")
}
);
}
Loading