diff --git a/src/cli/subcommands/attach_cmd.rs b/src/cli/subcommands/attach_cmd.rs index e7ddcbf38ec0..03b9f0c80b88 100644 --- a/src/cli/subcommands/attach_cmd.rs +++ b/src/cli/subcommands/attach_cmd.rs @@ -12,7 +12,7 @@ use crate::rpc_client::*; use crate::shim::{address::Address, message::Message}; use crate::{ chain::ChainEpochDelta, - rpc::{self, mpool_api::MpoolPushMessage, RpcMethodExt as _}, + rpc::{self, prelude::*}, }; use crate::{cli::humantoken, message::SignedMessage}; use boa_engine::{ diff --git a/src/cli/subcommands/auth_cmd.rs b/src/cli/subcommands/auth_cmd.rs index b5d8f84b3196..c095ffd66206 100644 --- a/src/cli/subcommands/auth_cmd.rs +++ b/src/cli/subcommands/auth_cmd.rs @@ -1,14 +1,10 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc_client::{ApiInfo, JsonRpcError}; +use crate::rpc_client::ApiInfo; use crate::{ auth::*, - rpc::{ - self, - auth_api::{AuthNew, AuthNewParams}, - RpcMethodExt as _, - }, + rpc::{self, auth::AuthNewParams, prelude::*}, }; use chrono::Duration; use clap::Subcommand; @@ -38,13 +34,13 @@ pub enum AuthCommands { }, } -fn process_perms(perm: String) -> Result, JsonRpcError> { +fn process_perms(perm: String) -> Result, rpc::ServerError> { Ok(match perm.as_str() { "admin" => ADMIN, "sign" => SIGN, "write" => WRITE, "read" => READ, - _ => return Err(JsonRpcError::invalid_params("unknown permission", None)), + _ => return Err(rpc::ServerError::invalid_params("unknown permission", None)), } .iter() .map(ToString::to_string) diff --git a/src/cli/subcommands/chain_cmd.rs b/src/cli/subcommands/chain_cmd.rs index a1fb49917055..e46bbd554994 100644 --- a/src/cli/subcommands/chain_cmd.rs +++ b/src/cli/subcommands/chain_cmd.rs @@ -4,8 +4,7 @@ use crate::blocks::{Tipset, TipsetKey}; use crate::lotus_json::{HasLotusJson, LotusJson}; use crate::message::ChainMessage; -use crate::rpc::chain_api::*; -use crate::rpc::{self, RpcMethodExt as _}; +use crate::rpc::{self, prelude::*}; use anyhow::bail; use cid::Cid; use clap::Subcommand; diff --git a/src/cli/subcommands/info_cmd.rs b/src/cli/subcommands/info_cmd.rs index 8f21e5a668fb..f07ad5d8165d 100644 --- a/src/cli/subcommands/info_cmd.rs +++ b/src/cli/subcommands/info_cmd.rs @@ -2,11 +2,9 @@ // SPDX-License-Identifier: Apache-2.0, MIT use crate::blocks::Tipset; +use crate::rpc::{self, prelude::*}; +use crate::rpc_client::ApiInfo; use crate::shim::econ::TokenAmount; -use crate::{ - rpc::{self, chain_api::ChainHead, RpcMethodExt as _}, - rpc_client::ApiInfo, -}; use chrono::{DateTime, Utc}; use clap::Subcommand; use futures::TryFutureExt as _; diff --git a/src/cli/subcommands/mpool_cmd.rs b/src/cli/subcommands/mpool_cmd.rs index 92855a97d706..7cd50c0e5f8d 100644 --- a/src/cli/subcommands/mpool_cmd.rs +++ b/src/cli/subcommands/mpool_cmd.rs @@ -1,18 +1,12 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use std::str::FromStr; +use std::str::FromStr as _; use crate::blocks::Tipset; use crate::lotus_json::LotusJson; use crate::message::SignedMessage; -use crate::rpc::mpool_api::MpoolPending; -use crate::rpc::types::ApiTipsetKey; -use crate::rpc::{ - self, - chain_api::{ChainGetMinBaseFee, ChainHead}, - RpcMethodExt as _, -}; +use crate::rpc::{self, prelude::*, types::ApiTipsetKey}; use crate::rpc_client::ApiInfo; use crate::shim::address::StrictAddress; use crate::shim::message::Message; diff --git a/src/cli/subcommands/send_cmd.rs b/src/cli/subcommands/send_cmd.rs index 32c5c69b0a9c..8741b73dd08a 100644 --- a/src/cli/subcommands/send_cmd.rs +++ b/src/cli/subcommands/send_cmd.rs @@ -3,8 +3,7 @@ use std::str::FromStr as _; -use crate::rpc::mpool_api::MpoolPushMessage; -use crate::rpc::{self, RpcMethodExt as _}; +use crate::rpc::{self, prelude::*}; use crate::rpc_client::ApiInfo; use crate::shim::address::{Address, StrictAddress}; use crate::shim::econ::TokenAmount; diff --git a/src/cli/subcommands/snapshot_cmd.rs b/src/cli/subcommands/snapshot_cmd.rs index dc8a7e58fdfa..55fbdb80f161 100644 --- a/src/cli/subcommands/snapshot_cmd.rs +++ b/src/cli/subcommands/snapshot_cmd.rs @@ -5,11 +5,7 @@ use super::*; use crate::chain_sync::SyncConfig; use crate::cli_shared::snapshot::{self, TrustedVendor}; use crate::rpc::types::ApiTipsetKey; -use crate::rpc::RpcMethodExt as _; -use crate::rpc::{ - self, - chain_api::{ChainExport, ChainExportParams, ChainGetTipSetByHeight, ChainHead}, -}; +use crate::rpc::{self, chain::ChainExportParams, prelude::*}; use crate::rpc_client::ApiInfo; use anyhow::Context as _; use chrono::DateTime; diff --git a/src/libp2p/service.rs b/src/libp2p/service.rs index 7c4fa81dc6fc..cd3f8b1f03cf 100644 --- a/src/libp2p/service.rs +++ b/src/libp2p/service.rs @@ -11,7 +11,7 @@ use crate::libp2p_bitswap::{ BitswapStoreRead, BitswapStoreReadWrite, }; use crate::message::SignedMessage; -use crate::{blocks::GossipBlock, rpc::net_api::NetInfoResult}; +use crate::{blocks::GossipBlock, rpc::net::NetInfoResult}; use crate::{chain::ChainStore, utils::encoding::from_slice_with_fallback}; use ahash::{HashMap, HashSet}; use cid::Cid; diff --git a/src/rpc/auth_layer.rs b/src/rpc/auth_layer.rs index 1d933523ca31..d9fdd1899463 100644 --- a/src/rpc/auth_layer.rs +++ b/src/rpc/auth_layer.rs @@ -4,8 +4,8 @@ use crate::auth::{verify_token, JWT_IDENTIFIER}; use crate::key_management::KeyStore; use crate::rpc::{ - auth_api, beacon_api, chain_api, common_api, eth_api, gas_api, mpool_api, net_api, node_api, - state_api, sync_api, wallet_api, RpcMethod as _, CANCEL_METHOD_NAME, + auth, beacon, chain, common, eth, gas, mpool, net, node, state, sync, wallet, RpcMethod as _, + CANCEL_METHOD_NAME, }; use ahash::{HashMap, HashMapExt as _}; use futures::future::BoxFuture; @@ -35,140 +35,134 @@ static ACCESS_MAP: Lazy> = Lazy::new(|| { let mut access = HashMap::new(); // Auth API - access.insert(auth_api::AuthNew::NAME, Access::Admin); - access.insert(auth_api::AuthVerify::NAME, Access::Read); + access.insert(auth::AuthNew::NAME, Access::Admin); + access.insert(auth::AuthVerify::NAME, Access::Read); // Beacon API - access.insert(beacon_api::BeaconGetEntry::NAME, Access::Read); + access.insert(beacon::BeaconGetEntry::NAME, Access::Read); // Chain API - access.insert(chain_api::ChainGetMessage::NAME, Access::Read); - access.insert(chain_api::ChainExport::NAME, Access::Read); - access.insert(chain_api::ChainReadObj::NAME, Access::Read); - access.insert(chain_api::ChainGetPath::NAME, Access::Read); - access.insert(chain_api::ChainHasObj::NAME, Access::Read); - access.insert(chain_api::ChainGetBlockMessages::NAME, Access::Read); - access.insert(chain_api::ChainGetTipSetByHeight::NAME, Access::Read); - access.insert(chain_api::ChainGetTipSetAfterHeight::NAME, Access::Read); - access.insert(chain_api::ChainGetGenesis::NAME, Access::Read); - access.insert(chain_api::ChainHead::NAME, Access::Read); - access.insert(chain_api::ChainGetBlock::NAME, Access::Read); - access.insert(chain_api::ChainGetTipSet::NAME, Access::Read); - access.insert(chain_api::ChainSetHead::NAME, Access::Admin); - access.insert(chain_api::ChainGetMinBaseFee::NAME, Access::Admin); - access.insert(chain_api::ChainGetMessagesInTipset::NAME, Access::Read); - access.insert(chain_api::ChainGetParentMessages::NAME, Access::Read); - access.insert(chain_api::CHAIN_NOTIFY, Access::Read); - access.insert(chain_api::ChainGetParentReceipts::NAME, Access::Read); + access.insert(chain::ChainGetMessage::NAME, Access::Read); + access.insert(chain::ChainExport::NAME, Access::Read); + access.insert(chain::ChainReadObj::NAME, Access::Read); + access.insert(chain::ChainGetPath::NAME, Access::Read); + access.insert(chain::ChainHasObj::NAME, Access::Read); + access.insert(chain::ChainGetBlockMessages::NAME, Access::Read); + access.insert(chain::ChainGetTipSetByHeight::NAME, Access::Read); + access.insert(chain::ChainGetTipSetAfterHeight::NAME, Access::Read); + access.insert(chain::ChainGetGenesis::NAME, Access::Read); + access.insert(chain::ChainHead::NAME, Access::Read); + access.insert(chain::ChainGetBlock::NAME, Access::Read); + access.insert(chain::ChainGetTipSet::NAME, Access::Read); + access.insert(chain::ChainSetHead::NAME, Access::Admin); + access.insert(chain::ChainGetMinBaseFee::NAME, Access::Admin); + access.insert(chain::ChainGetMessagesInTipset::NAME, Access::Read); + access.insert(chain::ChainGetParentMessages::NAME, Access::Read); + access.insert(chain::CHAIN_NOTIFY, Access::Read); + access.insert(chain::ChainGetParentReceipts::NAME, Access::Read); // Message Pool API - access.insert(mpool_api::MpoolGetNonce::NAME, Access::Read); - access.insert(mpool_api::MpoolPending::NAME, Access::Read); + access.insert(mpool::MpoolGetNonce::NAME, Access::Read); + access.insert(mpool::MpoolPending::NAME, Access::Read); // Lotus limits `MPOOL_PUSH`` to `Access::Write`. However, since messages // can always be pushed over the p2p protocol, limiting the RPC doesn't // improve security. - access.insert(mpool_api::MpoolPush::NAME, Access::Read); - access.insert(mpool_api::MpoolPushMessage::NAME, Access::Sign); + access.insert(mpool::MpoolPush::NAME, Access::Read); + access.insert(mpool::MpoolPushMessage::NAME, Access::Sign); // Sync API - access.insert(sync_api::SYNC_CHECK_BAD, Access::Read); - access.insert(sync_api::SYNC_MARK_BAD, Access::Admin); - access.insert(sync_api::SYNC_STATE, Access::Read); + access.insert(sync::SYNC_CHECK_BAD, Access::Read); + access.insert(sync::SYNC_MARK_BAD, Access::Admin); + access.insert(sync::SYNC_STATE, Access::Read); // Wallet API - access.insert(wallet_api::WALLET_BALANCE, Access::Write); - access.insert(wallet_api::WALLET_BALANCE, Access::Read); - access.insert(wallet_api::WALLET_DEFAULT_ADDRESS, Access::Read); - access.insert(wallet_api::WALLET_EXPORT, Access::Admin); - access.insert(wallet_api::WALLET_HAS, Access::Write); - access.insert(wallet_api::WALLET_IMPORT, Access::Admin); - access.insert(wallet_api::WALLET_LIST, Access::Write); - access.insert(wallet_api::WALLET_NEW, Access::Write); - access.insert(wallet_api::WALLET_SET_DEFAULT, Access::Write); - access.insert(wallet_api::WALLET_SIGN, Access::Sign); - access.insert(wallet_api::WALLET_VALIDATE_ADDRESS, Access::Read); - access.insert(wallet_api::WALLET_VERIFY, Access::Read); - access.insert(wallet_api::WALLET_DELETE, Access::Write); + access.insert(wallet::WALLET_BALANCE, Access::Write); + access.insert(wallet::WALLET_BALANCE, Access::Read); + access.insert(wallet::WALLET_DEFAULT_ADDRESS, Access::Read); + access.insert(wallet::WALLET_EXPORT, Access::Admin); + access.insert(wallet::WALLET_HAS, Access::Write); + access.insert(wallet::WALLET_IMPORT, Access::Admin); + access.insert(wallet::WALLET_LIST, Access::Write); + access.insert(wallet::WALLET_NEW, Access::Write); + access.insert(wallet::WALLET_SET_DEFAULT, Access::Write); + access.insert(wallet::WALLET_SIGN, Access::Sign); + access.insert(wallet::WALLET_VALIDATE_ADDRESS, Access::Read); + access.insert(wallet::WALLET_VERIFY, Access::Read); + access.insert(wallet::WALLET_DELETE, Access::Write); // State API - access.insert(state_api::STATE_CALL, Access::Read); - access.insert(state_api::STATE_REPLAY, Access::Read); - access.insert(state_api::STATE_GET_ACTOR, Access::Read); - access.insert(state_api::STATE_MARKET_BALANCE, Access::Read); - access.insert(state_api::STATE_MARKET_DEALS, Access::Read); - access.insert(state_api::STATE_MINER_INFO, Access::Read); - access.insert(state_api::MINER_GET_BASE_INFO, Access::Read); - access.insert(state_api::STATE_MINER_ACTIVE_SECTORS, Access::Read); - access.insert(state_api::STATE_MINER_FAULTS, Access::Read); - access.insert(state_api::STATE_MINER_RECOVERIES, Access::Read); - access.insert(state_api::STATE_MINER_POWER, Access::Read); - access.insert(state_api::STATE_MINER_DEADLINES, Access::Read); - access.insert(state_api::STATE_MINER_PROVING_DEADLINE, Access::Read); - access.insert(state_api::STATE_MINER_AVAILABLE_BALANCE, Access::Read); - access.insert(state_api::STATE_GET_RECEIPT, Access::Read); - access.insert(state_api::STATE_WAIT_MSG, Access::Read); - access.insert(state_api::STATE_SEARCH_MSG, Access::Read); - access.insert(state_api::STATE_SEARCH_MSG_LIMITED, Access::Read); - access.insert(state_api::STATE_NETWORK_NAME, Access::Read); - access.insert(state_api::STATE_NETWORK_VERSION, Access::Read); - access.insert(state_api::STATE_ACCOUNT_KEY, Access::Read); - access.insert(state_api::STATE_LOOKUP_ID, Access::Read); - access.insert(state_api::STATE_FETCH_ROOT, Access::Read); - access.insert(state_api::STATE_GET_RANDOMNESS_FROM_TICKETS, Access::Read); - access.insert(state_api::STATE_GET_RANDOMNESS_FROM_BEACON, Access::Read); - access.insert(state_api::STATE_READ_STATE, Access::Read); - access.insert(state_api::STATE_CIRCULATING_SUPPLY, Access::Read); - access.insert(state_api::STATE_SECTOR_GET_INFO, Access::Read); - access.insert(state_api::STATE_LIST_MESSAGES, Access::Read); - access.insert(state_api::STATE_LIST_MINERS, Access::Read); - access.insert(state_api::STATE_MINER_SECTOR_COUNT, Access::Read); - access.insert(state_api::STATE_VERIFIED_CLIENT_STATUS, Access::Read); - access.insert(state_api::STATE_MARKET_STORAGE_DEAL, Access::Read); - access.insert( - state_api::STATE_VM_CIRCULATING_SUPPLY_INTERNAL, - Access::Read, - ); - access.insert(state_api::MSIG_GET_AVAILABLE_BALANCE, Access::Read); - access.insert(state_api::MSIG_GET_PENDING, Access::Read); - access.insert( - state_api::STATE_DEAL_PROVIDER_COLLATERAL_BOUNDS, - Access::Read, - ); + access.insert(state::STATE_CALL, Access::Read); + access.insert(state::STATE_REPLAY, Access::Read); + access.insert(state::STATE_GET_ACTOR, Access::Read); + access.insert(state::STATE_MARKET_BALANCE, Access::Read); + access.insert(state::STATE_MARKET_DEALS, Access::Read); + access.insert(state::STATE_MINER_INFO, Access::Read); + access.insert(state::MINER_GET_BASE_INFO, Access::Read); + access.insert(state::STATE_MINER_ACTIVE_SECTORS, Access::Read); + access.insert(state::STATE_MINER_FAULTS, Access::Read); + access.insert(state::STATE_MINER_RECOVERIES, Access::Read); + access.insert(state::STATE_MINER_POWER, Access::Read); + access.insert(state::STATE_MINER_DEADLINES, Access::Read); + access.insert(state::STATE_MINER_PROVING_DEADLINE, Access::Read); + access.insert(state::STATE_MINER_AVAILABLE_BALANCE, Access::Read); + access.insert(state::STATE_GET_RECEIPT, Access::Read); + access.insert(state::STATE_WAIT_MSG, Access::Read); + access.insert(state::STATE_SEARCH_MSG, Access::Read); + access.insert(state::STATE_SEARCH_MSG_LIMITED, Access::Read); + access.insert(state::STATE_NETWORK_NAME, Access::Read); + access.insert(state::STATE_NETWORK_VERSION, Access::Read); + access.insert(state::STATE_ACCOUNT_KEY, Access::Read); + access.insert(state::STATE_LOOKUP_ID, Access::Read); + access.insert(state::STATE_FETCH_ROOT, Access::Read); + access.insert(state::STATE_GET_RANDOMNESS_FROM_TICKETS, Access::Read); + access.insert(state::STATE_GET_RANDOMNESS_FROM_BEACON, Access::Read); + access.insert(state::STATE_READ_STATE, Access::Read); + access.insert(state::STATE_CIRCULATING_SUPPLY, Access::Read); + access.insert(state::STATE_SECTOR_GET_INFO, Access::Read); + access.insert(state::STATE_LIST_MESSAGES, Access::Read); + access.insert(state::STATE_LIST_MINERS, Access::Read); + access.insert(state::STATE_MINER_SECTOR_COUNT, Access::Read); + access.insert(state::STATE_VERIFIED_CLIENT_STATUS, Access::Read); + access.insert(state::STATE_MARKET_STORAGE_DEAL, Access::Read); + access.insert(state::STATE_VM_CIRCULATING_SUPPLY_INTERNAL, Access::Read); + access.insert(state::MSIG_GET_AVAILABLE_BALANCE, Access::Read); + access.insert(state::MSIG_GET_PENDING, Access::Read); + access.insert(state::STATE_DEAL_PROVIDER_COLLATERAL_BOUNDS, Access::Read); // Gas API - access.insert(gas_api::GAS_ESTIMATE_GAS_LIMIT, Access::Read); - access.insert(gas_api::GAS_ESTIMATE_GAS_PREMIUM, Access::Read); - access.insert(gas_api::GAS_ESTIMATE_FEE_CAP, Access::Read); - access.insert(gas_api::GAS_ESTIMATE_MESSAGE_GAS, Access::Read); + access.insert(gas::GAS_ESTIMATE_GAS_LIMIT, Access::Read); + access.insert(gas::GAS_ESTIMATE_GAS_PREMIUM, Access::Read); + access.insert(gas::GAS_ESTIMATE_FEE_CAP, Access::Read); + access.insert(gas::GAS_ESTIMATE_MESSAGE_GAS, Access::Read); // Common API - access.insert(common_api::VERSION, Access::Read); - access.insert(common_api::SESSION, Access::Read); - access.insert(common_api::SHUTDOWN, Access::Admin); - access.insert(common_api::START_TIME, Access::Read); + access.insert(common::VERSION, Access::Read); + access.insert(common::SESSION, Access::Read); + access.insert(common::SHUTDOWN, Access::Admin); + access.insert(common::START_TIME, Access::Read); // Net API - access.insert(net_api::NET_ADDRS_LISTEN, Access::Read); - access.insert(net_api::NET_PEERS, Access::Read); - access.insert(net_api::NET_LISTENING, Access::Read); - access.insert(net_api::NET_INFO, Access::Read); - access.insert(net_api::NET_CONNECT, Access::Write); - access.insert(net_api::NET_DISCONNECT, Access::Write); - access.insert(net_api::NET_AGENT_VERSION, Access::Read); - access.insert(net_api::NET_AUTO_NAT_STATUS, Access::Read); - access.insert(net_api::NET_VERSION, Access::Read); + access.insert(net::NET_ADDRS_LISTEN, Access::Read); + access.insert(net::NET_PEERS, Access::Read); + access.insert(net::NET_LISTENING, Access::Read); + access.insert(net::NET_INFO, Access::Read); + access.insert(net::NET_CONNECT, Access::Write); + access.insert(net::NET_DISCONNECT, Access::Write); + access.insert(net::NET_AGENT_VERSION, Access::Read); + access.insert(net::NET_AUTO_NAT_STATUS, Access::Read); + access.insert(net::NET_VERSION, Access::Read); // Node API - access.insert(node_api::NODE_STATUS, Access::Read); + access.insert(node::NODE_STATUS, Access::Read); // Eth API - access.insert(eth_api::ETH_ACCOUNTS, Access::Read); - access.insert(eth_api::ETH_BLOCK_NUMBER, Access::Read); - access.insert(eth_api::ETH_CHAIN_ID, Access::Read); - access.insert(eth_api::ETH_GAS_PRICE, Access::Read); - access.insert(eth_api::ETH_GET_BALANCE, Access::Read); - access.insert(eth_api::ETH_SYNCING, Access::Read); - access.insert(eth_api::WEB3_CLIENT_VERSION, Access::Read); + access.insert(eth::ETH_ACCOUNTS, Access::Read); + access.insert(eth::ETH_BLOCK_NUMBER, Access::Read); + access.insert(eth::ETH_CHAIN_ID, Access::Read); + access.insert(eth::ETH_GAS_PRICE, Access::Read); + access.insert(eth::ETH_GET_BALANCE, Access::Read); + access.insert(eth::ETH_SYNCING, Access::Read); + access.insert(eth::WEB3_CLIENT_VERSION, Access::Read); // Pubsub API access.insert(CANCEL_METHOD_NAME, Access::Read); diff --git a/src/rpc/channel.rs b/src/rpc/channel.rs index dd1287a6fb5c..91aedf405d39 100644 --- a/src/rpc/channel.rs +++ b/src/rpc/channel.rs @@ -75,7 +75,7 @@ use std::sync::Arc; use tokio::sync::broadcast::error::RecvError; use tokio::sync::{mpsc, oneshot}; -use super::error::JsonRpcError; +use super::error::ServerError; pub const NOTIF_METHOD_NAME: &str = "xrpc.ch.val"; pub const CANCEL_METHOD_NAME: &str = "xrpc.cancel"; @@ -295,9 +295,9 @@ impl Default for RpcModule { let opt = channels.lock().remove(&sub_id); match opt { Some((_, _, channel_id)) => { - Ok::(channel_id) + Ok::(channel_id) } - None => Err::(JsonRpcError::from( + None => Err::(ServerError::from( anyhow::anyhow!("channel not found"), )), } diff --git a/src/rpc/error.rs b/src/rpc/error.rs index 387d586c5641..492051fbc884 100644 --- a/src/rpc/error.rs +++ b/src/rpc/error.rs @@ -8,12 +8,14 @@ use jsonrpsee::{ types::error::{self, ErrorCode, ErrorObjectOwned}, }; +/// An error returned _by the remote server_, not due to e.g serialization errors, +/// protocol errors, or the connection failing. #[derive(derive_more::From, derive_more::Into, Debug, PartialEq)] -pub struct JsonRpcError { +pub struct ServerError { inner: ErrorObjectOwned, } -impl JsonRpcError { +impl ServerError { pub fn new( code: i32, message: impl Display, @@ -31,7 +33,7 @@ impl JsonRpcError { } } -impl Display for JsonRpcError { +impl Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("JSON-RPC error:\n")?; f.write_fmt(format_args!("\tcode: {}\n", self.inner.code()))?; @@ -43,12 +45,12 @@ impl Display for JsonRpcError { } } -impl std::error::Error for JsonRpcError {} +impl std::error::Error for ServerError {} macro_rules! ctor { ($($ctor:ident { $code:expr })*) => { $( - impl JsonRpcError { + impl ServerError { pub fn $ctor(message: impl Display, data: impl Into>) -> Self { Self::new($code, message, data) } @@ -67,7 +69,7 @@ ctor! { macro_rules! from2internal { ($($ty:ty),* $(,)?) => { $( - impl From<$ty> for JsonRpcError { + impl From<$ty> for ServerError { fn from(it: $ty) -> Self { Self::internal_error(it, None) } @@ -97,19 +99,19 @@ from2internal! { tokio::task::JoinError, } -impl From for ClientError { - fn from(value: JsonRpcError) -> Self { +impl From for ClientError { + fn from(value: ServerError) -> Self { Self::Call(value.inner) } } -impl From> for JsonRpcError { +impl From> for ServerError { fn from(e: flume::SendError) -> Self { Self::internal_error(e, None) } } -impl From> for JsonRpcError { +impl From> for ServerError { fn from(e: tokio::sync::mpsc::error::SendError) -> Self { Self::internal_error(e, None) } diff --git a/src/rpc/auth_api.rs b/src/rpc/methods/auth.rs similarity index 85% rename from src/rpc/auth_api.rs rename to src/rpc/methods/auth.rs index 21c121256259..0d76db0566aa 100644 --- a/src/rpc/auth_api.rs +++ b/src/rpc/methods/auth.rs @@ -4,10 +4,7 @@ use crate::auth::*; use crate::lotus_json::lotus_json_with_self; use crate::lotus_json::LotusJson; -use crate::rpc::{ - reflect::SelfDescribingRpcModule, ApiVersion, Ctx, JsonRpcError, RPCState, RpcMethod, - RpcMethodExt as _, -}; +use crate::rpc::{ApiVersion, Ctx, RpcMethod, ServerError}; use anyhow::Result; use chrono::Duration; use fvm_ipld_blockstore::Blockstore; @@ -15,41 +12,13 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, DurationSeconds}; -pub fn register_all( - module: &mut SelfDescribingRpcModule>, -) { - AuthNew::register(module); - AuthVerify::register(module); -} - -#[serde_as] -#[derive(Deserialize, Serialize)] -pub struct AuthNewParams { - pub perms: Vec, - #[serde_as(as = "DurationSeconds")] - pub token_exp: Duration, -} -lotus_json_with_self!(AuthNewParams); - -/// `#[derive(JsonSchema)]` doesn't play nicely with [`serde_as`]. -/// -/// The correct solution is `token_exp: u64`, but the auth tests use negative -/// durations, so accept the tech debt for this for now -impl JsonSchema for AuthNewParams { - fn schema_name() -> String { - "AuthNewParams".into() - } - - fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - #[derive(JsonSchema)] - #[allow(dead_code)] - struct Helper { - perms: Vec, - token_exp: i64, - } - Helper::json_schema(gen) - } +macro_rules! for_each_method { + ($callback:ident) => { + $callback!(crate::rpc::auth::AuthNew); + $callback!(crate::rpc::auth::AuthVerify); + }; } +pub(crate) use for_each_method; /// RPC call to create a new JWT Token pub enum AuthNew {} @@ -62,7 +31,7 @@ impl RpcMethod<1> for AuthNew { async fn handle( ctx: Ctx, (params,): Self::Params, - ) -> Result { + ) -> Result { let ks = ctx.keystore.read().await; let ki = ks.get(JWT_IDENTIFIER)?; let token = create_token(params.perms, ki.private_key(), params.token_exp)?; @@ -80,7 +49,7 @@ impl RpcMethod<1> for AuthVerify { async fn handle( ctx: Ctx, (header_raw,): Self::Params, - ) -> Result { + ) -> Result { let ks = ctx.keystore.read().await; let token = header_raw.trim_start_matches("Bearer "); let ki = ks.get(JWT_IDENTIFIER)?; @@ -88,3 +57,32 @@ impl RpcMethod<1> for AuthVerify { Ok(perms) } } + +#[serde_as] +#[derive(Deserialize, Serialize)] +pub struct AuthNewParams { + pub perms: Vec, + #[serde_as(as = "DurationSeconds")] + pub token_exp: Duration, +} +lotus_json_with_self!(AuthNewParams); + +/// `#[derive(JsonSchema)]` doesn't play nicely with [`serde_as`]. +/// +/// The correct solution is `token_exp: u64`, but the auth tests use negative +/// durations, so accept the tech debt for this for now +impl JsonSchema for AuthNewParams { + fn schema_name() -> String { + "AuthNewParams".into() + } + + fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + #[derive(JsonSchema)] + #[allow(dead_code)] + struct Helper { + perms: Vec, + token_exp: i64, + } + Helper::json_schema(gen) + } +} diff --git a/src/rpc/beacon_api.rs b/src/rpc/methods/beacon.rs similarity index 75% rename from src/rpc/beacon_api.rs rename to src/rpc/methods/beacon.rs index 4f042130c7f5..fe3043d20aa3 100644 --- a/src/rpc/beacon_api.rs +++ b/src/rpc/methods/beacon.rs @@ -1,19 +1,17 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::{ - reflect::SelfDescribingRpcModule, ApiVersion, Ctx, JsonRpcError, RPCState, RpcMethod, - RpcMethodExt as _, -}; +use crate::rpc::{ApiVersion, Ctx, RpcMethod, ServerError}; use crate::{beacon::BeaconEntry, lotus_json::LotusJson, shim::clock::ChainEpoch}; use anyhow::Result; use fvm_ipld_blockstore::Blockstore; -pub fn register_all( - module: &mut SelfDescribingRpcModule>, -) { - BeaconGetEntry::register(module); +macro_rules! for_each_method { + ($callback:ident) => { + $callback!(crate::rpc::beacon::BeaconGetEntry); + }; } +pub(crate) use for_each_method; /// `BeaconGetEntry` returns the beacon entry for the given Filecoin epoch. If /// the entry has not yet been produced, the call will block until the entry @@ -30,7 +28,7 @@ impl RpcMethod<1> for BeaconGetEntry { async fn handle( ctx: Ctx, (first,): Self::Params, - ) -> Result { + ) -> Result { let (_, beacon) = ctx.beacon.beacon_for_epoch(first)?; let rr = beacon.max_beacon_round_for_epoch(ctx.state_manager.get_network_version(first), first); diff --git a/src/rpc/chain_api.rs b/src/rpc/methods/chain.rs similarity index 94% rename from src/rpc/chain_api.rs rename to src/rpc/methods/chain.rs index 1b1b3585bbf2..e65d13269c63 100644 --- a/src/rpc/chain_api.rs +++ b/src/rpc/methods/chain.rs @@ -15,10 +15,7 @@ use crate::lotus_json::LotusJson; use crate::lotus_json::{assert_all_snapshots, assert_unchanged_via_json}; use crate::message::{ChainMessage, SignedMessage}; use crate::rpc::types::ApiTipsetKey; -use crate::rpc::{ - reflect::SelfDescribingRpcModule, ApiVersion, Ctx, JsonRpcError, RPCState, RpcMethod, - RpcMethodExt as _, -}; +use crate::rpc::{ApiVersion, Ctx, RpcMethod, ServerError}; use crate::shim::clock::ChainEpoch; use crate::shim::error::ExitCode; use crate::shim::message::Message; @@ -42,27 +39,28 @@ use tokio::sync::{ Mutex, }; -pub fn register_all( - module: &mut SelfDescribingRpcModule>, -) { - ChainGetPath::register(module); - ChainGetParentMessages::register(module); - ChainGetMessage::register(module); - ChainGetParentReceipts::register(module); - ChainGetMessagesInTipset::register(module); - ChainExport::register(module); - ChainReadObj::register(module); - ChainHasObj::register(module); - ChainGetBlockMessages::register(module); - ChainGetTipSetByHeight::register(module); - ChainGetTipSetAfterHeight::register(module); - ChainGetGenesis::register(module); - ChainHead::register(module); - ChainGetBlock::register(module); - ChainGetTipSet::register(module); - ChainSetHead::register(module); - ChainGetMinBaseFee::register(module); +macro_rules! for_each_method { + ($callback:ident) => { + $callback!(crate::rpc::chain::ChainGetMessage); + $callback!(crate::rpc::chain::ChainGetParentMessages); + $callback!(crate::rpc::chain::ChainGetParentReceipts); + $callback!(crate::rpc::chain::ChainGetMessagesInTipset); + $callback!(crate::rpc::chain::ChainExport); + $callback!(crate::rpc::chain::ChainReadObj); + $callback!(crate::rpc::chain::ChainHasObj); + $callback!(crate::rpc::chain::ChainGetBlockMessages); + $callback!(crate::rpc::chain::ChainGetPath); + $callback!(crate::rpc::chain::ChainGetTipSetByHeight); + $callback!(crate::rpc::chain::ChainGetTipSetAfterHeight); + $callback!(crate::rpc::chain::ChainGetGenesis); + $callback!(crate::rpc::chain::ChainHead); + $callback!(crate::rpc::chain::ChainGetBlock); + $callback!(crate::rpc::chain::ChainGetTipSet); + $callback!(crate::rpc::chain::ChainSetHead); + $callback!(crate::rpc::chain::ChainGetMinBaseFee); + }; } +pub(crate) use for_each_method; pub enum ChainGetMessage {} impl RpcMethod<1> for ChainGetMessage { @@ -76,7 +74,7 @@ impl RpcMethod<1> for ChainGetMessage { async fn handle( ctx: Ctx, (LotusJson(msg_cid),): Self::Params, - ) -> Result { + ) -> Result { let chain_message: ChainMessage = ctx .state_manager .blockstore() @@ -101,7 +99,7 @@ impl RpcMethod<1> for ChainGetParentMessages { async fn handle( ctx: Ctx, (LotusJson(block_cid),): Self::Params, - ) -> Result { + ) -> Result { let store = ctx.state_manager.blockstore(); let block_header: CachingBlockHeader = store .get_cbor(&block_cid)? @@ -128,7 +126,7 @@ impl RpcMethod<1> for ChainGetParentReceipts { async fn handle( ctx: Ctx, (LotusJson(block_cid),): Self::Params, - ) -> Result { + ) -> Result { let store = ctx.state_manager.blockstore(); let block_header: CachingBlockHeader = store .get_cbor(&block_cid)? @@ -204,7 +202,7 @@ impl RpcMethod<1> for ChainGetMessagesInTipset { async fn handle( ctx: Ctx, (LotusJson(tsk),): Self::Params, - ) -> Result { + ) -> Result { let store = ctx.chain_store.blockstore(); let tipset = Tipset::load_required(store, &tsk)?; let messages = load_api_messages_from_tipset(store, &tipset)?; @@ -224,7 +222,7 @@ impl RpcMethod<1> for ChainExport { async fn handle( ctx: Ctx, (params,): Self::Params, - ) -> Result { + ) -> Result { let ChainExportParams { epoch, recent_roots, @@ -296,7 +294,7 @@ impl RpcMethod<1> for ChainReadObj { async fn handle( ctx: Ctx, (LotusJson(cid),): Self::Params, - ) -> Result { + ) -> Result { let bytes = ctx .state_manager .blockstore() @@ -318,7 +316,7 @@ impl RpcMethod<1> for ChainHasObj { async fn handle( ctx: Ctx, (LotusJson(cid),): Self::Params, - ) -> Result { + ) -> Result { Ok(ctx.state_manager.blockstore().get(&cid)?.is_some()) } } @@ -335,7 +333,7 @@ impl RpcMethod<1> for ChainGetBlockMessages { async fn handle( ctx: Ctx, (LotusJson(cid),): Self::Params, - ) -> Result { + ) -> Result { let blk: CachingBlockHeader = ctx .state_manager .blockstore() @@ -376,7 +374,7 @@ impl RpcMethod<2> for ChainGetPath { async fn handle( ctx: Ctx, (LotusJson(from), LotusJson(to)): Self::Params, - ) -> Result { + ) -> Result { impl_chain_get_path(&ctx.chain_store, &from, &to) .map(LotusJson) .map_err(Into::into) @@ -454,7 +452,7 @@ impl RpcMethod<2> for ChainGetTipSetByHeight { async fn handle( ctx: Ctx, (height, LotusJson(ApiTipsetKey(tsk))): Self::Params, - ) -> Result { + ) -> Result { let ts = ctx .state_manager .chain_store() @@ -480,7 +478,7 @@ impl RpcMethod<2> for ChainGetTipSetAfterHeight { async fn handle( ctx: Ctx, (height, LotusJson(ApiTipsetKey(tsk))): Self::Params, - ) -> Result { + ) -> Result { let ts = ctx .state_manager .chain_store() @@ -503,7 +501,7 @@ impl RpcMethod<0> for ChainGetGenesis { type Params = (); type Ok = Option>; - async fn handle(ctx: Ctx, (): Self::Params) -> Result { + async fn handle(ctx: Ctx, (): Self::Params) -> Result { let genesis = ctx.state_manager.chain_store().genesis_block_header(); Ok(Some(Tipset::from(genesis).into())) } @@ -518,7 +516,7 @@ impl RpcMethod<0> for ChainHead { type Params = (); type Ok = LotusJson; - async fn handle(ctx: Ctx, (): Self::Params) -> Result { + async fn handle(ctx: Ctx, (): Self::Params) -> Result { let heaviest = ctx.state_manager.chain_store().heaviest_tipset(); Ok((*heaviest).clone().into()) } @@ -536,7 +534,7 @@ impl RpcMethod<1> for ChainGetBlock { async fn handle( ctx: Ctx, (LotusJson(cid),): Self::Params, - ) -> Result { + ) -> Result { let blk: CachingBlockHeader = ctx .state_manager .blockstore() @@ -558,7 +556,7 @@ impl RpcMethod<1> for ChainGetTipSet { async fn handle( ctx: Ctx, (LotusJson(ApiTipsetKey(tsk)),): Self::Params, - ) -> Result { + ) -> Result { let ts = ctx .state_manager .chain_store() @@ -579,7 +577,7 @@ impl RpcMethod<1> for ChainSetHead { async fn handle( ctx: Ctx, (LotusJson(ApiTipsetKey(tsk)),): Self::Params, - ) -> Result { + ) -> Result { // This is basically a port of the reference implementation at // https://github.com/filecoin-project/lotus/blob/v1.23.0/node/impl/full/chain.go#L321 @@ -620,7 +618,7 @@ impl RpcMethod<1> for ChainGetMinBaseFee { async fn handle( ctx: Ctx, (lookback,): Self::Params, - ) -> Result { + ) -> Result { let mut current = ctx.state_manager.chain_store().heaviest_tipset(); let mut min_base_fee = current.block_headers().first().parent_base_fee.clone(); @@ -676,7 +674,7 @@ pub(crate) fn chain_notify( fn load_api_messages_from_tipset( store: &impl Blockstore, tipset: &Tipset, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let full_tipset = tipset .fill_from_blockstore(store) .context("Failed to load full tipset")?; diff --git a/src/rpc/common_api.rs b/src/rpc/methods/common.rs similarity index 81% rename from src/rpc/common_api.rs rename to src/rpc/methods/common.rs index 30341095d4b1..533dc72d049c 100644 --- a/src/rpc/common_api.rs +++ b/src/rpc/methods/common.rs @@ -3,7 +3,7 @@ #![allow(clippy::unused_async)] use crate::rpc::types::{APIVersion, Version}; -use crate::rpc::{error::JsonRpcError, RPCState}; +use crate::rpc::{error::ServerError, RPCState}; use fvm_ipld_blockstore::Blockstore; use once_cell::sync::Lazy; @@ -21,11 +21,11 @@ pub const DISCOVER: &str = "Filecoin.Discover"; pub const SESSION: &str = "Filecoin.Session"; /// The session UUID uniquely identifies the API node. -pub fn session() -> Result { +pub fn session() -> Result { Ok(SESSION_UUID.to_string()) } -pub fn version(block_delay: u64, forest_version: &'static str) -> Result { +pub fn version(block_delay: u64, forest_version: &'static str) -> Result { let v = SemVer::parse(forest_version).unwrap(); Ok(APIVersion { version: forest_version.to_string(), @@ -34,7 +34,7 @@ pub fn version(block_delay: u64, forest_version: &'static str) -> Result) -> Result<(), JsonRpcError> { +pub async fn shutdown(shutdown_send: Sender<()>) -> Result<(), ServerError> { // Trigger graceful shutdown if let Err(err) = shutdown_send.send(()).await { return Err(err.into()); @@ -45,6 +45,6 @@ pub async fn shutdown(shutdown_send: Sender<()>) -> Result<(), JsonRpcError> { /// gets start time from network pub fn start_time( data: &RPCState, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { Ok(data.start_time) } diff --git a/src/rpc/eth_api.rs b/src/rpc/methods/eth.rs similarity index 95% rename from src/rpc/eth_api.rs rename to src/rpc/methods/eth.rs index 74b8d6f37c95..a030147bbf31 100644 --- a/src/rpc/eth_api.rs +++ b/src/rpc/methods/eth.rs @@ -2,16 +2,16 @@ // SPDX-License-Identifier: Apache-2.0, MIT #![allow(clippy::unused_async)] -use super::gas_api; +use super::gas; use crate::blocks::{Tipset, TipsetKey}; use crate::chain::{index::ResolveNullTipset, ChainStore}; use crate::chain_sync::SyncStage; use crate::lotus_json::LotusJson; use crate::lotus_json::{lotus_json_with_self, HasLotusJson}; -use crate::rpc::error::JsonRpcError; -use crate::rpc::sync_api::sync_state; +use crate::rpc::error::ServerError; +use crate::rpc::sync::sync_state; use crate::rpc::types::RPCSyncState; -use crate::rpc::Ctx; +use crate::rpc::{self, Ctx}; use crate::shim::address::Address as FilecoinAddress; use crate::shim::{clock::ChainEpoch, state_tree::StateTree}; use anyhow::{bail, Context, Result}; @@ -251,12 +251,12 @@ impl HasLotusJson for EthSyncingResult { } } -pub async fn eth_accounts() -> Result, JsonRpcError> { +pub async fn eth_accounts() -> Result, ServerError> { // EthAccounts will always return [] since we don't expect Forest to manage private keys Ok(vec![]) } -pub async fn eth_block_number(data: Ctx) -> Result { +pub async fn eth_block_number(data: Ctx) -> Result { // `eth_block_number` needs to return the height of the latest committed tipset. // Ethereum clients expect all transactions included in this block to have execution outputs. // This is the parent of the head tipset. The head tipset is speculative, has not been @@ -281,18 +281,18 @@ pub async fn eth_block_number(data: Ctx) -> Result(data: Ctx) -> Result { +pub async fn eth_chain_id(data: Ctx) -> Result { Ok(format!( "{:#x}", data.state_manager.chain_config().eth_chain_id )) } -pub async fn eth_gas_price(data: Ctx) -> Result { +pub async fn eth_gas_price(data: Ctx) -> Result { let ts = data.state_manager.chain_store().heaviest_tipset(); let block0 = ts.block_headers().first(); let base_fee = &block0.parent_base_fee; - if let Ok(premium) = gas_api::estimate_gas_premium(&data, 10000).await { + if let Ok(premium) = gas::estimate_gas_premium(&data, 10000).await { let gas_price = base_fee.add(premium); Ok(GasPriceResult(gas_price.atto().clone())) } else { @@ -303,7 +303,7 @@ pub async fn eth_gas_price(data: Ctx) -> Result( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((address, block_param)): LotusJson<(Address, BlockNumberOrHash)> = params.parse()?; @@ -323,7 +323,7 @@ pub async fn eth_get_balance( pub async fn eth_syncing( _params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let RPCSyncState { active_syncs } = sync_state(data).await?; match active_syncs .iter() @@ -337,16 +337,16 @@ pub async fn eth_syncing( starting_block: base.epoch(), highest_block: target.epoch(), })), - _ => Err(JsonRpcError::internal_error( + _ => Err(ServerError::internal_error( "missing syncing information, try again", None, )), }, - None => Err(JsonRpcError::internal_error("sync state not found", None)), + None => Err(ServerError::internal_error("sync state not found", None)), } } -pub fn web3_client_version(forest_version: &str) -> Result { +pub fn web3_client_version(forest_version: &str) -> Result { Ok(forest_version.into()) } diff --git a/src/rpc/gas_api.rs b/src/rpc/methods/gas.rs similarity index 95% rename from src/rpc/gas_api.rs rename to src/rpc/methods/gas.rs index 70490dd8ac33..915fd591408b 100644 --- a/src/rpc/gas_api.rs +++ b/src/rpc/methods/gas.rs @@ -6,7 +6,7 @@ use crate::blocks::TipsetKey; use crate::chain::{BASE_FEE_MAX_CHANGE_DENOM, BLOCK_GAS_TARGET, MINIMUM_BASE_FEE}; use crate::lotus_json::LotusJson; use crate::message::{ChainMessage, Message as MessageTrait}; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::types::*; use crate::rpc::Ctx; use crate::shim::address::Address; @@ -31,7 +31,7 @@ pub const GAS_ESTIMATE_MESSAGE_GAS: &str = "Filecoin.GasEstimateMessageGas"; pub async fn gas_estimate_fee_cap( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((msg, max_queue_blks, tsk)): LotusJson<(Message, i64, ApiTipsetKey)> = params.parse()?; @@ -43,7 +43,7 @@ fn estimate_fee_cap( msg: Message, max_queue_blks: i64, _: ApiTipsetKey, -) -> Result { +) -> Result { let ts = data.state_manager.chain_store().heaviest_tipset(); let parent_base_fee = &ts.block_headers().first().parent_base_fee; @@ -62,7 +62,7 @@ fn estimate_fee_cap( pub async fn gas_estimate_gas_premium( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((nblocksincl, _sender, _gas_limit, _)): LotusJson<( u64, Address, @@ -78,7 +78,7 @@ pub async fn gas_estimate_gas_premium( pub async fn estimate_gas_premium( data: &Ctx, mut nblocksincl: u64, -) -> Result { +) -> Result { if nblocksincl == 0 { nblocksincl = 1; } @@ -161,7 +161,7 @@ pub async fn estimate_gas_premium( pub async fn gas_estimate_gas_limit( params: Params<'_>, data: Ctx, -) -> Result +) -> Result where DB: Blockstore + Send + Sync + 'static, { @@ -174,7 +174,7 @@ async fn estimate_gas_limit( data: &Ctx, msg: Message, _: ApiTipsetKey, -) -> Result +) -> Result where DB: Blockstore + Send + Sync + 'static, { @@ -217,7 +217,7 @@ where pub async fn gas_estimate_message_gas( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> +) -> Result, ServerError> where DB: Blockstore + Send + Sync + 'static, { @@ -234,7 +234,7 @@ pub async fn estimate_message_gas( msg: Message, _spec: Option, tsk: ApiTipsetKey, -) -> Result +) -> Result where DB: Blockstore + Send + Sync + 'static, { diff --git a/src/rpc/mpool_api.rs b/src/rpc/methods/mpool.rs similarity index 89% rename from src/rpc/mpool_api.rs rename to src/rpc/methods/mpool.rs index cf5d49383ded..a64ce581d5b9 100644 --- a/src/rpc/mpool_api.rs +++ b/src/rpc/methods/mpool.rs @@ -1,13 +1,13 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use super::gas_api::estimate_message_gas; -use super::RPCState; +use super::gas::estimate_message_gas; + use crate::lotus_json::LotusJson; use crate::message::SignedMessage; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::types::{ApiTipsetKey, MessageSendSpec}; -use crate::rpc::{reflect::SelfDescribingRpcModule, ApiVersion, Ctx, RpcMethod, RpcMethodExt as _}; +use crate::rpc::{ApiVersion, Ctx, RpcMethod}; use crate::shim::{ address::{Address, Protocol}, message::Message, @@ -16,14 +16,15 @@ use ahash::{HashSet, HashSetExt as _}; use cid::Cid; use fvm_ipld_blockstore::Blockstore; -pub fn register_all( - module: &mut SelfDescribingRpcModule>, -) { - MpoolGetNonce::register(module); - MpoolPending::register(module); - MpoolPush::register(module); - MpoolPushMessage::register(module); +macro_rules! for_each_method { + ($callback:ident) => { + $callback!(crate::rpc::mpool::MpoolGetNonce); + $callback!(crate::rpc::mpool::MpoolPending); + $callback!(crate::rpc::mpool::MpoolPush); + $callback!(crate::rpc::mpool::MpoolPushMessage); + }; } +pub(crate) use for_each_method; /// Gets next nonce for the specified sender. pub enum MpoolGetNonce {} @@ -38,7 +39,7 @@ impl RpcMethod<1> for MpoolGetNonce { async fn handle( ctx: Ctx, (address,): Self::Params, - ) -> Result { + ) -> Result { Ok(ctx.mpool.get_sequence(&address.into_inner())?) } } @@ -56,7 +57,7 @@ impl RpcMethod<1> for MpoolPending { async fn handle( ctx: Ctx, (LotusJson(ApiTipsetKey(tsk)),): Self::Params, - ) -> Result { + ) -> Result { let mut ts = ctx .state_manager .chain_store() @@ -131,7 +132,7 @@ impl RpcMethod<1> for MpoolPush { async fn handle( ctx: Ctx, (LotusJson(msg),): Self::Params, - ) -> Result { + ) -> Result { let cid = ctx.mpool.as_ref().push(msg).await?; Ok(cid.into()) } @@ -150,7 +151,7 @@ impl RpcMethod<2> for MpoolPushMessage { async fn handle( ctx: Ctx, (LotusJson(umsg), spec): Self::Params, - ) -> Result { + ) -> Result { let from = umsg.from; let mut keystore = ctx.keystore.as_ref().write().await; diff --git a/src/rpc/net_api.rs b/src/rpc/methods/net.rs similarity index 94% rename from src/rpc/net_api.rs rename to src/rpc/methods/net.rs index 3a6c99926ea4..3c4d2f98071d 100644 --- a/src/rpc/net_api.rs +++ b/src/rpc/methods/net.rs @@ -5,7 +5,7 @@ use std::str::FromStr; use crate::libp2p::{NetRPCMethods, NetworkMessage, PeerId}; use crate::lotus_json::lotus_json_with_self; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::{types::AddrInfo, Ctx}; use anyhow::Result; use cid::multibase; @@ -88,7 +88,7 @@ impl From for NatStatusResult { } } -pub async fn net_addrs_listen(data: Ctx) -> Result { +pub async fn net_addrs_listen(data: Ctx) -> Result { let (tx, rx) = oneshot::channel(); let req = NetworkMessage::JSONRPCRequest { method: NetRPCMethods::AddrsListen(tx), @@ -103,7 +103,7 @@ pub async fn net_addrs_listen(data: Ctx) -> Result(data: Ctx) -> Result, JsonRpcError> { +pub async fn net_peers(data: Ctx) -> Result, ServerError> { let (tx, rx) = oneshot::channel(); let req = NetworkMessage::JSONRPCRequest { method: NetRPCMethods::Peers(tx), @@ -124,11 +124,11 @@ pub async fn net_peers(data: Ctx) -> Result, J } // NET_LISTENING always returns true. -pub async fn net_listening() -> Result { +pub async fn net_listening() -> Result { Ok(true) } -pub async fn net_info(data: Ctx) -> Result { +pub async fn net_info(data: Ctx) -> Result { let (tx, rx) = oneshot::channel(); let req = NetworkMessage::JSONRPCRequest { method: NetRPCMethods::Info(tx), @@ -141,7 +141,7 @@ pub async fn net_info(data: Ctx) -> Result( params: Params<'_>, data: Ctx, -) -> Result<(), JsonRpcError> { +) -> Result<(), ServerError> { let (AddrInfo { id, addrs },) = params.parse()?; let (_, id) = multibase::decode(format!("{}{}", "z", id))?; @@ -165,7 +165,7 @@ pub async fn net_connect( pub async fn net_disconnect( params: Params<'_>, data: Ctx, -) -> Result<(), JsonRpcError> { +) -> Result<(), ServerError> { let (id,): (String,) = params.parse()?; let peer_id = PeerId::from_str(&id)?; @@ -184,7 +184,7 @@ pub async fn net_disconnect( pub async fn net_agent_version( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let (id,): (String,) = params.parse()?; let peer_id = PeerId::from_str(&id)?; @@ -205,7 +205,7 @@ pub async fn net_agent_version( pub async fn net_auto_nat_status( _params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let (tx, rx) = oneshot::channel(); let req = NetworkMessage::JSONRPCRequest { method: NetRPCMethods::AutoNATStatus(tx), @@ -218,7 +218,7 @@ pub async fn net_auto_nat_status( pub async fn net_version( _params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { Ok(format!( "{}", data.state_manager.chain_config().eth_chain_id diff --git a/src/rpc/node_api.rs b/src/rpc/methods/node.rs similarity index 97% rename from src/rpc/node_api.rs rename to src/rpc/methods/node.rs index bf99de28ce22..36f6e6bae6e6 100644 --- a/src/rpc/node_api.rs +++ b/src/rpc/methods/node.rs @@ -4,7 +4,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::Ctx; use fvm_ipld_blockstore::Blockstore; @@ -42,7 +42,7 @@ pub struct NodeStatus { lotus_json_with_self!(NodeStatus); -pub async fn node_status(data: Ctx) -> Result { +pub async fn node_status(data: Ctx) -> Result { let mut node_status = NodeStatusResult::default(); let head = data.state_manager.chain_store().heaviest_tipset(); diff --git a/src/rpc/state_api.rs b/src/rpc/methods/state.rs similarity index 95% rename from src/rpc/state_api.rs rename to src/rpc/methods/state.rs index b5f3580ae676..cceee23c344a 100644 --- a/src/rpc/state_api.rs +++ b/src/rpc/methods/state.rs @@ -5,7 +5,7 @@ use crate::cid_collections::CidHashSet; use crate::libp2p::NetworkMessage; use crate::lotus_json::LotusJson; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::types::*; use crate::rpc::Ctx; use crate::shim::{ @@ -87,7 +87,7 @@ pub const MSIG_GET_PENDING: &str = "Filecoin.MsigGetPending"; pub async fn miner_get_base_info( params: Params<'_>, data: Ctx, -) -> anyhow::Result>, JsonRpcError> { +) -> anyhow::Result>, ServerError> { let LotusJson((address, epoch, ApiTipsetKey(tsk))) = params.parse()?; let ts = data @@ -104,7 +104,7 @@ pub async fn miner_get_base_info( pub async fn state_call( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((message, ApiTipsetKey(key))) = params.parse()?; let state_manager = &data.state_manager; @@ -122,7 +122,7 @@ pub async fn state_call( pub async fn state_replay( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((cid, ApiTipsetKey(key))) = params.parse()?; let state_manager = &data.state_manager; @@ -140,7 +140,7 @@ pub async fn state_replay( } /// gets network name from state manager -pub async fn state_network_name(data: Ctx) -> Result { +pub async fn state_network_name(data: Ctx) -> Result { let state_manager = &data.state_manager; let heaviest_tipset = state_manager.chain_store().heaviest_tipset(); @@ -152,7 +152,7 @@ pub async fn state_network_name(data: Ctx) -> Result( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((ApiTipsetKey(tsk),)): LotusJson<(ApiTipsetKey,)> = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -164,7 +164,7 @@ pub async fn state_get_network_version( pub async fn state_account_key( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> +) -> Result, ServerError> where DB: Blockstore + Send + Sync + 'static, { @@ -185,7 +185,7 @@ where pub async fn state_lookup_id( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> +) -> Result, ServerError> where DB: Blockstore + Send + Sync + 'static, { @@ -204,7 +204,7 @@ where pub(crate) async fn state_get_actor( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -218,7 +218,7 @@ pub(crate) async fn state_get_actor( pub async fn state_market_balance( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((address, ApiTipsetKey(key))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -234,7 +234,7 @@ pub async fn state_market_balance( pub async fn state_market_deals( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((ApiTipsetKey(tsk),)): LotusJson<(ApiTipsetKey,)> = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -272,7 +272,7 @@ pub async fn state_market_deals( pub async fn state_miner_info( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((address, ApiTipsetKey(key))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -286,7 +286,7 @@ pub async fn state_miner_info( pub async fn state_miner_active_sectors( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((miner, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -321,7 +321,7 @@ pub async fn state_miner_active_sectors( pub async fn state_miner_sector_count( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((miner, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -357,7 +357,7 @@ pub async fn state_miner_sector_count( pub async fn state_miner_power( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((address, ApiTipsetKey(key))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -375,7 +375,7 @@ pub async fn state_miner_power( pub async fn state_miner_deadlines( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -401,7 +401,7 @@ pub async fn state_miner_deadlines( pub async fn state_miner_proving_deadline( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -420,7 +420,7 @@ pub async fn state_miner_proving_deadline( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((address, ApiTipsetKey(key))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -438,7 +438,7 @@ pub async fn state_miner_faults( pub async fn state_miner_recoveries( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((miner, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -456,7 +456,7 @@ pub async fn state_miner_recoveries( pub async fn state_miner_available_balance( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((miner_address, ApiTipsetKey(tsk))): LotusJson<(Address, ApiTipsetKey)> = params.parse()?; @@ -505,7 +505,7 @@ pub async fn state_miner_available_balance( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((cid, ApiTipsetKey(key))): LotusJson<(Cid, ApiTipsetKey)> = params.parse()?; let state_manager = &data.state_manager; @@ -523,7 +523,7 @@ pub async fn state_get_receipt( pub async fn state_wait_msg( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((cid, confidence)): LotusJson<(Cid, i64)> = params.parse()?; let state_manager = &data.state_manager; @@ -546,7 +546,7 @@ pub async fn state_wait_msg( pub async fn state_search_msg( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((cid,)): LotusJson<(Cid,)> = params.parse()?; let state_manager = &data.state_manager; @@ -571,7 +571,7 @@ pub async fn state_search_msg( pub async fn state_search_msg_limited( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((cid, look_back_limit)): LotusJson<(Cid, i64)> = params.parse()?; let state_manager = &data.state_manager; @@ -610,7 +610,7 @@ pub async fn state_search_msg_limited( pub async fn state_fetch_root( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((root_cid, save_to_file)): LotusJson<(Cid, Option)> = params.parse()?; let network_send = data.network_send.clone(); @@ -772,7 +772,7 @@ fn lock_pop(mutex: &Mutex>) -> Option { pub async fn state_get_randomness_from_tickets( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((personalization, rand_epoch, entropy, ApiTipsetKey(tsk))): LotusJson< RandomnessParams, > = params.parse()?; @@ -799,7 +799,7 @@ pub async fn state_get_randomness_from_tickets( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((personalization, rand_epoch, entropy, ApiTipsetKey(tsk))): LotusJson< RandomnessParams, > = params.parse()?; @@ -826,7 +826,7 @@ pub async fn state_get_randomness_from_beacon( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -851,7 +851,7 @@ pub async fn state_read_state( pub async fn state_circulating_supply( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((ApiTipsetKey(tsk),)) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -876,7 +876,7 @@ pub async fn state_circulating_supply( pub async fn msig_get_available_balance( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -896,7 +896,7 @@ pub async fn msig_get_available_balance( pub async fn msig_get_pending( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -926,7 +926,7 @@ pub async fn msig_get_pending( pub async fn state_sector_get_info( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((addr, sector_no, ApiTipsetKey(tsk))): LotusJson<(Address, u64, ApiTipsetKey)> = params.parse()?; @@ -945,7 +945,7 @@ pub async fn state_sector_get_info( pub(in crate::rpc) async fn state_verified_client_status( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((addr, ApiTipsetKey(tsk))) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -958,7 +958,7 @@ pub(in crate::rpc) async fn state_vm_circulating_supply_internal< >( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let LotusJson((ApiTipsetKey(tsk),)) = params.parse()?; let ts = data.chain_store.load_required_tipset_or_heaviest(&tsk)?; @@ -976,7 +976,7 @@ pub(in crate::rpc) async fn state_vm_circulating_supply_internal< pub(in crate::rpc) async fn state_list_messages( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((from_to, tsk, max_height)): LotusJson<(MessageFilter, ApiTipsetKey, i64)> = params.parse()?; @@ -1038,7 +1038,7 @@ pub(in crate::rpc) async fn state_list_messages( params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let LotusJson((ApiTipsetKey(tsk),)) = params.parse()?; let ts = data @@ -1064,7 +1064,7 @@ pub async fn state_list_miners( pub async fn state_market_storage_deal( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((deal_id, ApiTipsetKey(tsk))): LotusJson<(DealID, ApiTipsetKey)> = params.parse()?; @@ -1089,7 +1089,7 @@ pub async fn state_market_storage_deal( pub async fn state_deal_provider_collateral_bounds( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let deal_provider_collateral_num = BigInt::from(110); let deal_provider_collateral_denom = BigInt::from(100); diff --git a/src/rpc/sync_api.rs b/src/rpc/methods/sync.rs similarity index 98% rename from src/rpc/sync_api.rs rename to src/rpc/methods/sync.rs index 8fe2d17d9b6c..1458babb20e8 100644 --- a/src/rpc/sync_api.rs +++ b/src/rpc/methods/sync.rs @@ -4,7 +4,7 @@ use crate::chain_sync::SyncState; use crate::lotus_json::LotusJson; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::types::RPCSyncState; use crate::rpc::Ctx; @@ -22,7 +22,7 @@ pub const SYNC_STATE: &str = "Filecoin.SyncState"; pub async fn sync_check_bad( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((cid,)) = params.parse()?; Ok(data.bad_blocks.peek(&cid).unwrap_or_default()) @@ -32,7 +32,7 @@ pub async fn sync_check_bad( pub async fn sync_mark_bad( params: Params<'_>, data: Ctx, -) -> Result<(), JsonRpcError> { +) -> Result<(), ServerError> { let LotusJson((cid,)) = params.parse()?; data.bad_blocks @@ -45,7 +45,7 @@ async fn clone_state(state: &RwLock) -> SyncState { } /// Returns the current status of the `ChainSync` process. -pub async fn sync_state(data: Ctx) -> Result { +pub async fn sync_state(data: Ctx) -> Result { let active_syncs = nonempty![clone_state(data.sync_state.as_ref()).await]; Ok(RPCSyncState { active_syncs }) } diff --git a/src/rpc/wallet_api.rs b/src/rpc/methods/wallet.rs similarity index 94% rename from src/rpc/wallet_api.rs rename to src/rpc/methods/wallet.rs index e3464db98d4d..06b921610336 100644 --- a/src/rpc/wallet_api.rs +++ b/src/rpc/methods/wallet.rs @@ -6,7 +6,7 @@ use std::{convert::TryFrom, str::FromStr}; use crate::key_management::{Key, KeyInfo}; use crate::lotus_json::LotusJson; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; use crate::rpc::Ctx; use crate::shim::{ address::Address, @@ -37,7 +37,7 @@ pub const WALLET_DELETE: &str = "Filecoin.WalletDelete"; pub async fn wallet_balance( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let (addr_str,): (String,) = params.parse()?; let address = Address::from_str(&addr_str)?; @@ -63,7 +63,7 @@ pub async fn wallet_balance( pub async fn wallet_default_address( _params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let keystore = data.keystore.read().await; let addr = crate::key_management::get_default(&keystore)?; @@ -74,7 +74,7 @@ pub async fn wallet_default_address( pub async fn wallet_export( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let (addr_str,): (String,) = params.parse()?; let addr = Address::from_str(&addr_str)?; @@ -89,7 +89,7 @@ pub async fn wallet_export( pub async fn wallet_has( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let (addr_str,): (String,) = params.parse()?; let addr = Address::from_str(&addr_str)?; @@ -104,7 +104,7 @@ pub async fn wallet_has( pub async fn wallet_import( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let params: LotusJson> = params.parse()?; let key_info = params @@ -130,7 +130,7 @@ pub async fn wallet_import( pub async fn wallet_list( _params: Params<'_>, data: Ctx, -) -> Result>, JsonRpcError> { +) -> Result>, ServerError> { let keystore = data.keystore.read().await; Ok(crate::key_management::list_addrs(&keystore)?.into()) } @@ -139,7 +139,7 @@ pub async fn wallet_list( pub async fn wallet_new( params: Params<'_>, data: Ctx, -) -> Result { +) -> Result { let LotusJson((sig_raw,)): LotusJson<(SignatureType,)> = params.parse()?; let mut keystore = data.keystore.write().await; @@ -159,7 +159,7 @@ pub async fn wallet_new( pub async fn wallet_set_default( params: Params<'_>, data: Ctx, -) -> Result<(), JsonRpcError> { +) -> Result<(), ServerError> { let LotusJson((address,)): LotusJson<(Address,)> = params.parse()?; let mut keystore = data.keystore.write().await; @@ -175,7 +175,7 @@ pub async fn wallet_set_default( pub async fn wallet_sign( params: Params<'_>, data: Ctx, -) -> Result, JsonRpcError> +) -> Result, ServerError> where DB: Blockstore + Send + Sync + 'static, { @@ -207,7 +207,7 @@ where /// Validates whether a given string can be decoded as a well-formed address pub(in crate::rpc) async fn wallet_validate_address( params: Params<'_>, -) -> Result, JsonRpcError> { +) -> Result, ServerError> { let (addr_str,): (String,) = params.parse()?; let addr = Address::from_str(&addr_str)?; @@ -215,7 +215,7 @@ pub(in crate::rpc) async fn wallet_validate_address( } /// Verify a Signature, true if verified, false otherwise -pub async fn wallet_verify(params: Params<'_>) -> Result { +pub async fn wallet_verify(params: Params<'_>) -> Result { let LotusJson((address, msg, sig)): LotusJson<(Address, Vec, Signature)> = params.parse()?; @@ -226,7 +226,7 @@ pub async fn wallet_verify(params: Params<'_>) -> Result { pub async fn wallet_delete( params: Params<'_>, data: Ctx, -) -> Result<(), JsonRpcError> { +) -> Result<(), ServerError> { let (addr_str,): (String,) = params.parse()?; let mut keystore = data.keystore.write().await; diff --git a/src/rpc/mod.rs b/src/rpc/mod.rs index 392370582cd9..64f3db74fcea 100644 --- a/src/rpc/mod.rs +++ b/src/rpc/mod.rs @@ -5,28 +5,63 @@ mod auth_layer; mod channel; mod client; -// API handlers -pub mod auth_api; -pub mod beacon_api; -pub mod chain_api; -pub mod common_api; -pub mod eth_api; -pub mod gas_api; -pub mod mpool_api; -pub mod net_api; -pub mod node_api; -pub mod state_api; -pub mod sync_api; -pub mod wallet_api; - // Other RPC-specific modules pub use client::Client; -pub use error::JsonRpcError; +pub use error::ServerError; use reflect::Ctx; pub use reflect::{ApiVersion, RpcMethod, RpcMethodExt}; mod error; mod reflect; pub mod types; +pub use methods::*; + +/// Protocol or transport-specific error +#[allow(unused)] +pub use jsonrpsee::core::ClientError; + +#[allow(unused)] +/// All handler definitions. +/// +/// Usage guide: +/// ```ignore +/// use crate::rpc::{self, prelude::*}; +/// +/// let client = rpc::Client::from(..); +/// ChainHead::call(&client, ()).await?; +/// fn foo() -> rpc::ClientError {..} +/// fn bar() -> rpc::ServerError {..} +/// ``` +pub mod prelude { + use super::*; + + pub use reflect::RpcMethodExt as _; + + macro_rules! export { + ($ty:ty) => { + pub use $ty; + }; + } + auth::for_each_method!(export); + beacon::for_each_method!(export); + chain::for_each_method!(export); + mpool::for_each_method!(export); +} + +/// All the methods live in their own folder +mod methods { + pub mod auth; + pub mod beacon; + pub mod chain; + pub mod common; + pub mod eth; + pub mod gas; + pub mod mpool; + pub mod net; + pub mod node; + pub mod state; + pub mod sync; + pub mod wallet; +} use std::net::SocketAddr; use std::sync::Arc; @@ -35,7 +70,7 @@ use crate::key_management::KeyStore; use crate::rpc::auth_layer::AuthLayer; use crate::rpc::channel::RpcModule as FilRpcModule; pub use crate::rpc::channel::CANCEL_METHOD_NAME; -use crate::rpc::state_api::*; +use crate::rpc::state::*; use fvm_ipld_blockstore::Blockstore; use hyper::server::conn::AddrStream; @@ -104,7 +139,7 @@ where pubsub_module.register_channel("Filecoin.ChainNotify", { let state_clone = state.clone(); - move |params| chain_api::chain_notify(params, &state_clone) + move |params| chain::chain_notify(params, &state_clone) })?; module.merge(pubsub_module)?; @@ -164,10 +199,15 @@ where DB: Blockstore + Send + Sync + 'static, { let mut module = reflect::SelfDescribingRpcModule::new(state, ParamStructure::ByPosition); - chain_api::register_all(&mut module); - mpool_api::register_all(&mut module); - auth_api::register_all(&mut module); - beacon_api::register_all(&mut module); + macro_rules! register { + ($ty:ty) => { + <$ty>::register(&mut module); + }; + } + chain::for_each_method!(register); + mpool::for_each_method!(register); + auth::for_each_method!(register); + beacon::for_each_method!(register); module.finish() } @@ -181,13 +221,13 @@ fn register_methods( where DB: Blockstore + Send + Sync + 'static, { - use common_api::*; - use eth_api::*; - use gas_api::*; - use net_api::*; - use node_api::*; - use sync_api::*; - use wallet_api::*; + use common::*; + use eth::*; + use gas::*; + use net::*; + use node::*; + use sync::*; + use wallet::*; // Sync API module.register_async_method(SYNC_CHECK_BAD, sync_check_bad::)?; diff --git a/src/rpc/reflect/mod.rs b/src/rpc/reflect/mod.rs index 06aafe9f8af6..40461c5b1a77 100644 --- a/src/rpc/reflect/mod.rs +++ b/src/rpc/reflect/mod.rs @@ -25,7 +25,7 @@ mod parser; mod util; use self::{jsonrpc_types::RequestParameters, util::Optional as _}; -use super::error::JsonRpcError as Error; +use super::error::ServerError as Error; use fvm_ipld_blockstore::Blockstore; use jsonrpsee::{MethodsError, RpcModule}; use openrpc_types::{ContentDescriptor, Method, ParamListError, ParamStructure}; diff --git a/src/rpc/reflect/parser.rs b/src/rpc/reflect/parser.rs index ee5651a51a64..906a7a8ad099 100644 --- a/src/rpc/reflect/parser.rs +++ b/src/rpc/reflect/parser.rs @@ -6,7 +6,7 @@ use serde::Deserialize; use serde_json::{json, Value}; use super::{jsonrpc_types::RequestParameters, openrpc_types::ParamStructure, util::Optional as _}; -use crate::rpc::error::JsonRpcError; +use crate::rpc::error::ServerError; /// Parser for JSON-RPC parameters. /// Abstracts calling convention, checks for unexpected params etc, so that @@ -47,7 +47,7 @@ impl<'a> Parser<'a> { params: Option, names: &'a [&'a str], // in position order calling_convention: ParamStructure, - ) -> Result { + ) -> Result { Self::_new(params, names, calling_convention).map_err(Into::into) } fn _new( @@ -96,7 +96,7 @@ impl<'a> Parser<'a> { self.has_errored = true; Err(e) } - pub fn parse(&mut self) -> Result + pub fn parse(&mut self) -> Result where T: for<'de> Deserialize<'de>, { @@ -190,10 +190,10 @@ enum ParseError<'a> { MustBePositional, } -impl<'a> From> for JsonRpcError { +impl<'a> From> for ServerError { fn from(value: ParseError<'a>) -> Self { match value { - ParseError::Missing { index, name, ty } => JsonRpcError::invalid_params( + ParseError::Missing { index, name, ty } => ServerError::invalid_params( "missing required parameter", json!({ "index": index, @@ -206,7 +206,7 @@ impl<'a> From> for JsonRpcError { name, ty, error, - } => JsonRpcError::invalid_params( + } => ServerError::invalid_params( "error deserializing parameter", json!({ "index": index, @@ -216,16 +216,16 @@ impl<'a> From> for JsonRpcError { }), ), ParseError::UnexpectedPositional(n) => { - JsonRpcError::invalid_params("unexpected trailing arguments", json!({"count": n})) + ServerError::invalid_params("unexpected trailing arguments", json!({"count": n})) } ParseError::UnexpectedNamed(names) => { - JsonRpcError::invalid_params("unexpected named arguments", json!(names)) + ServerError::invalid_params("unexpected named arguments", json!(names)) } ParseError::MustBeNamed => { - JsonRpcError::invalid_params("this method only accepts arguments by-name", None) + ServerError::invalid_params("this method only accepts arguments by-name", None) } ParseError::MustBePositional => { - JsonRpcError::invalid_params("this method only accepts arguments by-position", None) + ServerError::invalid_params("this method only accepts arguments by-position", None) } } } diff --git a/src/rpc/snapshots/forest_filecoin__rpc__tests__openrpc.snap b/src/rpc/snapshots/forest_filecoin__rpc__tests__openrpc.snap index 35ef6ae3c034..5b61bd7a2f6b 100644 --- a/src/rpc/snapshots/forest_filecoin__rpc__tests__openrpc.snap +++ b/src/rpc/snapshots/forest_filecoin__rpc__tests__openrpc.snap @@ -3,45 +3,6 @@ source: src/rpc/mod.rs expression: spec --- methods: - - name: Filecoin.ChainGetPath - params: - - name: from - schema: - $ref: "#/components/schemas/forest_filecoin::lotus_json::cid::CidLotusJsonGeneric<64>" - required: true - - name: to - schema: - $ref: "#/components/schemas/forest_filecoin::lotus_json::cid::CidLotusJsonGeneric<64>" - required: true - paramStructure: by-position - result: - name: "Filecoin.ChainGetPath::Result" - schema: - type: array - items: - $ref: "#/components/schemas/PathChange_for_TipsetLotusJson" - nullable: true - required: true - - name: Filecoin.ChainGetParentMessages - params: - - name: block_cid - schema: - type: object - required: - - / - properties: - /: - $ref: "#/components/schemas/String" - required: true - paramStructure: by-position - result: - name: "Filecoin.ChainGetParentMessages::Result" - schema: - type: array - items: - $ref: "#/components/schemas/ApiMessageLotusJson" - nullable: true - required: true - name: Filecoin.ChainGetMessage params: - name: msg_cid @@ -92,6 +53,26 @@ methods: Version: $ref: "#/components/schemas/uint64" required: true + - name: Filecoin.ChainGetParentMessages + params: + - name: block_cid + schema: + type: object + required: + - / + properties: + /: + $ref: "#/components/schemas/String" + required: true + paramStructure: by-position + result: + name: "Filecoin.ChainGetParentMessages::Result" + schema: + type: array + items: + $ref: "#/components/schemas/ApiMessageLotusJson" + nullable: true + required: true - name: Filecoin.ChainGetParentReceipts params: - name: block_cid @@ -225,6 +206,25 @@ methods: SecpkMessages: $ref: "#/components/schemas/forest_filecoin::lotus_json::signed_message::SignedMessageLotusJson" required: true + - name: Filecoin.ChainGetPath + params: + - name: from + schema: + $ref: "#/components/schemas/forest_filecoin::lotus_json::cid::CidLotusJsonGeneric<64>" + required: true + - name: to + schema: + $ref: "#/components/schemas/forest_filecoin::lotus_json::cid::CidLotusJsonGeneric<64>" + required: true + paramStructure: by-position + result: + name: "Filecoin.ChainGetPath::Result" + schema: + type: array + items: + $ref: "#/components/schemas/PathChange_for_TipsetLotusJson" + nullable: true + required: true - name: Filecoin.ChainGetTipSetByHeight params: - name: height diff --git a/src/rpc_client/chain_ops.rs b/src/rpc_client/chain_ops.rs index 69e571cace65..5d0abc9df504 100644 --- a/src/rpc_client/chain_ops.rs +++ b/src/rpc_client/chain_ops.rs @@ -5,6 +5,6 @@ use super::{ApiInfo, RpcRequest}; impl ApiInfo { pub fn chain_notify_req() -> RpcRequest<()> { - RpcRequest::new(crate::rpc::chain_api::CHAIN_NOTIFY, ()) + RpcRequest::new(crate::rpc::chain::CHAIN_NOTIFY, ()) } } diff --git a/src/rpc_client/common_ops.rs b/src/rpc_client/common_ops.rs index 2e7277629ffe..f638018168f8 100644 --- a/src/rpc_client/common_ops.rs +++ b/src/rpc_client/common_ops.rs @@ -1,18 +1,17 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::common_api::{DISCOVER, SESSION, SHUTDOWN, START_TIME, VERSION}; +use super::{ApiInfo, RpcRequest, ServerError}; +use crate::rpc::common::{DISCOVER, SESSION, SHUTDOWN, START_TIME, VERSION}; use crate::rpc::types::{APIVersion, DiscoverResult}; use chrono::{DateTime, Utc}; -use super::{ApiInfo, JsonRpcError, RpcRequest}; - impl ApiInfo { pub fn version_req() -> RpcRequest { RpcRequest::new(VERSION, ()) } - pub async fn start_time(&self) -> Result, JsonRpcError> { + pub async fn start_time(&self) -> Result, ServerError> { self.call(Self::start_time_req()).await } @@ -20,7 +19,7 @@ impl ApiInfo { RpcRequest::new(START_TIME, ()) } - pub async fn shutdown(&self) -> Result<(), JsonRpcError> { + pub async fn shutdown(&self) -> Result<(), ServerError> { self.call(Self::shutdown_req()).await } diff --git a/src/rpc_client/eth_ops.rs b/src/rpc_client/eth_ops.rs index c7e42cb011ab..fdb5f6d34434 100644 --- a/src/rpc_client/eth_ops.rs +++ b/src/rpc_client/eth_ops.rs @@ -1,9 +1,8 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::eth_api::*; - use super::{ApiInfo, RpcRequest}; +use crate::rpc::eth::*; impl ApiInfo { pub fn eth_accounts_req() -> RpcRequest> { diff --git a/src/rpc_client/gas_ops.rs b/src/rpc_client/gas_ops.rs index 4744640642fc..5ca20487246d 100644 --- a/src/rpc_client/gas_ops.rs +++ b/src/rpc_client/gas_ops.rs @@ -1,16 +1,15 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT +use super::{ApiInfo, RpcRequest, ServerError}; use crate::{ rpc::{ - gas_api::*, + gas::*, types::{ApiTipsetKey, MessageSendSpec}, }, shim::message::Message, }; -use super::{ApiInfo, JsonRpcError, RpcRequest}; - impl ApiInfo { pub fn gas_estimate_message_gas_req( msg: Message, @@ -25,7 +24,7 @@ impl ApiInfo { msg: Message, spec: Option, tsk: ApiTipsetKey, - ) -> Result { + ) -> Result { self.call(Self::gas_estimate_message_gas_req(msg, spec, tsk)) .await } diff --git a/src/rpc_client/mod.rs b/src/rpc_client/mod.rs index a9bbffc24e24..238180fc62c9 100644 --- a/src/rpc_client/mod.rs +++ b/src/rpc_client/mod.rs @@ -1,20 +1,19 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -pub mod chain_ops; -pub mod common_ops; -pub mod eth_ops; -pub mod gas_ops; -pub mod net_ops; -pub mod node_ops; -pub mod state_ops; -pub mod sync_ops; -pub mod wallet_ops; +mod chain_ops; +mod common_ops; +mod eth_ops; +mod gas_ops; +mod net_ops; +mod node_ops; +mod state_ops; +mod sync_ops; +mod wallet_ops; use crate::libp2p::{Multiaddr, Protocol}; use crate::lotus_json::HasLotusJson; -pub use crate::rpc::JsonRpcError; -use crate::rpc::{self, ApiVersion}; +use crate::rpc::{self, ApiVersion, ServerError}; use anyhow::Context as _; use jsonrpsee::core::traits::ToRpcParams; use std::{env, fmt, marker::PhantomData, str::FromStr, time::Duration}; @@ -90,7 +89,7 @@ impl ApiInfo { } // TODO(aatifsyed): https://github.com/ChainSafe/forest/issues/4032 - // This function should return jsonrpsee::core::ClientError, + // This function should return rpc::ClientError, // but that change should wait until _after_ all the methods // have been migrated. // @@ -99,13 +98,13 @@ impl ApiInfo { pub async fn call( &self, req: RpcRequest, - ) -> Result { + ) -> Result { use jsonrpsee::core::ClientError; match rpc::Client::from(self.clone()).call(req).await { Ok(it) => Ok(it), Err(e) => match e { ClientError::Call(it) => Err(it.into()), - other => Err(JsonRpcError::internal_error(other, None)), + other => Err(ServerError::internal_error(other, None)), }, } } diff --git a/src/rpc_client/net_ops.rs b/src/rpc_client/net_ops.rs index 5b1d0849b841..47a579329d98 100644 --- a/src/rpc_client/net_ops.rs +++ b/src/rpc_client/net_ops.rs @@ -1,13 +1,12 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::net_api::*; +use super::{ApiInfo, RpcRequest, ServerError}; +use crate::rpc::net::*; use crate::rpc::types::AddrInfo; -use super::{ApiInfo, JsonRpcError, RpcRequest}; - impl ApiInfo { - pub async fn net_addrs_listen(&self) -> Result { + pub async fn net_addrs_listen(&self) -> Result { self.call(Self::net_addrs_listen_req()).await } @@ -15,7 +14,7 @@ impl ApiInfo { RpcRequest::new(NET_ADDRS_LISTEN, ()) } - pub async fn net_peers(&self) -> Result, JsonRpcError> { + pub async fn net_peers(&self) -> Result, ServerError> { self.call(Self::net_peers_req()).await } @@ -27,7 +26,7 @@ impl ApiInfo { RpcRequest::new_v1(NET_LISTENING, ()) } - pub async fn net_info(&self) -> Result { + pub async fn net_info(&self) -> Result { self.call(Self::net_info_req()).await } @@ -35,7 +34,7 @@ impl ApiInfo { RpcRequest::new(NET_INFO, ()) } - pub async fn net_connect(&self, addr: AddrInfo) -> Result<(), JsonRpcError> { + pub async fn net_connect(&self, addr: AddrInfo) -> Result<(), ServerError> { self.call(Self::net_connect_req(addr)).await } @@ -43,7 +42,7 @@ impl ApiInfo { RpcRequest::new(NET_CONNECT, (addr,)) } - pub async fn net_disconnect(&self, peer: String) -> Result<(), JsonRpcError> { + pub async fn net_disconnect(&self, peer: String) -> Result<(), ServerError> { self.call(Self::net_disconnect_req(peer)).await } @@ -51,7 +50,7 @@ impl ApiInfo { RpcRequest::new(NET_DISCONNECT, (peer,)) } - pub async fn net_agent_version(&self, peer: String) -> Result { + pub async fn net_agent_version(&self, peer: String) -> Result { self.call(Self::net_agent_version_req(peer)).await } @@ -59,7 +58,7 @@ impl ApiInfo { RpcRequest::new(NET_AGENT_VERSION, (peer,)) } - pub async fn net_auto_nat_status(&self) -> Result { + pub async fn net_auto_nat_status(&self) -> Result { self.call(Self::net_auto_nat_status_req()).await } diff --git a/src/rpc_client/node_ops.rs b/src/rpc_client/node_ops.rs index 601a0e8ecf2c..0f28df86568a 100644 --- a/src/rpc_client/node_ops.rs +++ b/src/rpc_client/node_ops.rs @@ -1,12 +1,12 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::node_api::{NodeStatus, NODE_STATUS}; +use crate::rpc::node::{NodeStatus, NODE_STATUS}; -use super::{ApiInfo, JsonRpcError, RpcRequest}; +use super::{ApiInfo, RpcRequest, ServerError}; impl ApiInfo { - pub async fn node_status(&self) -> Result { + pub async fn node_status(&self) -> Result { self.call(Self::node_status_req()).await } diff --git a/src/rpc_client/state_ops.rs b/src/rpc_client/state_ops.rs index 60207446e280..f8c642dd638e 100644 --- a/src/rpc_client/state_ops.rs +++ b/src/rpc_client/state_ops.rs @@ -7,7 +7,7 @@ use std::time::Duration; use crate::rpc::types::*; use crate::{ blocks::TipsetKey, - rpc::state_api::*, + rpc::state::*, shim::{ address::Address, clock::ChainEpoch, deal::DealID, econ::TokenAmount, message::Message, message::MethodNum, state_tree::ActorState, version::NetworkVersion, @@ -21,14 +21,14 @@ use fvm_shared2::piece::PaddedPieceSize; use libipld_core::ipld::Ipld; use num_bigint::BigInt; -use super::{ApiInfo, JsonRpcError, RpcRequest}; +use super::{ApiInfo, RpcRequest, ServerError}; impl ApiInfo { pub async fn state_get_actor( &self, address: Address, head: TipsetKey, - ) -> Result, JsonRpcError> { + ) -> Result, ServerError> { self.call(Self::state_get_actor_req(address, head)).await } @@ -43,7 +43,7 @@ impl ApiInfo { &self, root: Cid, opt_path: Option, - ) -> Result { + ) -> Result { self.call(Self::state_fetch_root_req(root, opt_path)).await } @@ -51,7 +51,7 @@ impl ApiInfo { RpcRequest::new(STATE_FETCH_ROOT, (root, opt_path)) } - pub async fn state_network_name(&self) -> Result { + pub async fn state_network_name(&self) -> Result { self.call(Self::state_network_name_req()).await } diff --git a/src/rpc_client/sync_ops.rs b/src/rpc_client/sync_ops.rs index 7bfc7b117d5a..9e7b1ec031d2 100644 --- a/src/rpc_client/sync_ops.rs +++ b/src/rpc_client/sync_ops.rs @@ -1,14 +1,14 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use crate::rpc::sync_api::*; +use crate::rpc::sync::*; use crate::rpc::types::RPCSyncState; use cid::Cid; -use super::{ApiInfo, JsonRpcError, RpcRequest}; +use super::{ApiInfo, RpcRequest, ServerError}; impl ApiInfo { - pub async fn sync_check_bad(&self, cid: Cid) -> Result { + pub async fn sync_check_bad(&self, cid: Cid) -> Result { self.call(Self::sync_check_bad_req(cid)).await } @@ -16,7 +16,7 @@ impl ApiInfo { RpcRequest::new(SYNC_CHECK_BAD, (cid,)) } - pub async fn sync_mark_bad(&self, cid: Cid) -> Result<(), JsonRpcError> { + pub async fn sync_mark_bad(&self, cid: Cid) -> Result<(), ServerError> { self.call(Self::sync_mark_bad_req(cid)).await } @@ -24,7 +24,7 @@ impl ApiInfo { RpcRequest::new(SYNC_MARK_BAD, (cid,)) } - pub async fn sync_status(&self) -> Result { + pub async fn sync_status(&self) -> Result { self.call(Self::sync_status_req()).await } diff --git a/src/rpc_client/wallet_ops.rs b/src/rpc_client/wallet_ops.rs index 9dd2fa1cd299..b0fa619a3dcb 100644 --- a/src/rpc_client/wallet_ops.rs +++ b/src/rpc_client/wallet_ops.rs @@ -1,10 +1,10 @@ // Copyright 2019-2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use super::{ApiInfo, JsonRpcError, RpcRequest}; +use super::{ApiInfo, RpcRequest, ServerError}; use crate::{ key_management::KeyInfo, - rpc::wallet_api::*, + rpc::wallet::*, shim::{ address::Address, crypto::{Signature, SignatureType}, @@ -12,7 +12,7 @@ use crate::{ }; impl ApiInfo { - pub async fn wallet_default_address(&self) -> Result, JsonRpcError> { + pub async fn wallet_default_address(&self) -> Result, ServerError> { self.call(Self::wallet_default_address_req()).await } @@ -20,7 +20,7 @@ impl ApiInfo { RpcRequest::new(WALLET_DEFAULT_ADDRESS, ()) } - pub async fn wallet_new(&self, signature_type: SignatureType) -> Result { + pub async fn wallet_new(&self, signature_type: SignatureType) -> Result { self.call(Self::wallet_new_req(signature_type)).await } @@ -28,7 +28,7 @@ impl ApiInfo { RpcRequest::new(WALLET_NEW, (signature_type,)) } - pub async fn wallet_balance(&self, address: String) -> Result { + pub async fn wallet_balance(&self, address: String) -> Result { self.call(Self::wallet_balance_req(address)).await } @@ -36,7 +36,7 @@ impl ApiInfo { RpcRequest::new(WALLET_BALANCE, (address,)) } - pub async fn wallet_export(&self, address: String) -> Result { + pub async fn wallet_export(&self, address: String) -> Result { self.call(Self::wallet_export_req(address)).await } @@ -44,7 +44,7 @@ impl ApiInfo { RpcRequest::new(WALLET_EXPORT, (address,)) } - pub async fn wallet_import(&self, key: Vec) -> Result { + pub async fn wallet_import(&self, key: Vec) -> Result { self.call(Self::wallet_import_req(key)).await } @@ -52,7 +52,7 @@ impl ApiInfo { RpcRequest::new(WALLET_IMPORT, key) } - pub async fn wallet_list(&self) -> Result, JsonRpcError> { + pub async fn wallet_list(&self) -> Result, ServerError> { self.call(Self::wallet_list_req()).await } @@ -60,7 +60,7 @@ impl ApiInfo { RpcRequest::new(WALLET_LIST, ()) } - pub async fn wallet_has(&self, key: String) -> Result { + pub async fn wallet_has(&self, key: String) -> Result { self.call(Self::wallet_has_req(key)).await } @@ -68,7 +68,7 @@ impl ApiInfo { RpcRequest::new(WALLET_HAS, (key,)) } - pub async fn wallet_set_default(&self, address: Address) -> Result<(), JsonRpcError> { + pub async fn wallet_set_default(&self, address: Address) -> Result<(), ServerError> { self.call(Self::wallet_set_default_req(address)).await } @@ -80,7 +80,7 @@ impl ApiInfo { &self, address: Address, data: Vec, - ) -> Result { + ) -> Result { self.call(Self::wallet_sign_req(address, data)).await } @@ -88,7 +88,7 @@ impl ApiInfo { RpcRequest::new(WALLET_SIGN, (address, data)) } - pub async fn wallet_validate_address(&self, address: String) -> Result { + pub async fn wallet_validate_address(&self, address: String) -> Result { self.call(Self::wallet_validate_address_req(address)).await } @@ -101,7 +101,7 @@ impl ApiInfo { address: Address, data: Vec, signature: Signature, - ) -> Result { + ) -> Result { self.call(Self::wallet_verify_req(address, data, signature)) .await } @@ -114,7 +114,7 @@ impl ApiInfo { RpcRequest::new(WALLET_VERIFY, (address, data, signature)) } - pub async fn wallet_delete(&self, address: String) -> Result<(), JsonRpcError> { + pub async fn wallet_delete(&self, address: String) -> Result<(), ServerError> { self.call(Self::wallet_delete_req(address)).await } diff --git a/src/tool/subcommands/api_cmd.rs b/src/tool/subcommands/api_cmd.rs index aa1abed1bed6..fdf71f27eeab 100644 --- a/src/tool/subcommands/api_cmd.rs +++ b/src/tool/subcommands/api_cmd.rs @@ -13,17 +13,12 @@ use crate::lotus_json::{HasLotusJson, LotusJson}; use crate::message::Message as _; use crate::message_pool::{MessagePool, MpoolRpcProvider}; use crate::networks::{parse_bootstrap_peers, ChainConfig, NetworkChain}; -use crate::rpc::beacon_api::BeaconGetEntry; -use crate::rpc::chain_api::*; -use crate::rpc::eth_api::Address as EthAddress; -use crate::rpc::eth_api::*; +use crate::rpc::beacon::BeaconGetEntry; +use crate::rpc::eth::Address as EthAddress; +use crate::rpc::eth::*; use crate::rpc::types::{ApiTipsetKey, MessageFilter, MessageLookup}; -use crate::rpc::{ - mpool_api::{MpoolGetNonce, MpoolPending}, - RpcMethodExt as _, -}; -use crate::rpc::{start_rpc, RPCState}; -use crate::rpc_client::{ApiInfo, JsonRpcError, RpcRequest, DEFAULT_PORT}; +use crate::rpc::{prelude::*, start_rpc, RPCState, ServerError}; +use crate::rpc_client::{ApiInfo, RpcRequest, DEFAULT_PORT}; use crate::shim::address::{CurrentNetwork, Network}; use crate::shim::{ address::{Address, Protocol}, @@ -193,7 +188,7 @@ enum EndpointStatus { } impl EndpointStatus { - fn from_json_error(err: JsonRpcError) -> Self { + fn from_json_error(err: ServerError) -> Self { match err.known_code() { ErrorCode::ParseError => Self::InvalidResponse, ErrorCode::OversizedRequest => Self::InvalidRequest, diff --git a/src/tool/subcommands/shed_cmd.rs b/src/tool/subcommands/shed_cmd.rs index d0587e640c49..1531e4cb802b 100644 --- a/src/tool/subcommands/shed_cmd.rs +++ b/src/tool/subcommands/shed_cmd.rs @@ -8,7 +8,7 @@ use crate::{ lotus_json::LotusJson, rpc::{ self, - chain_api::{ChainGetTipSetByHeight, ChainHead}, + chain::{ChainGetTipSetByHeight, ChainHead}, types::ApiTipsetKey, RpcMethodExt as _, }, diff --git a/src/wallet/subcommands/wallet_cmd.rs b/src/wallet/subcommands/wallet_cmd.rs index b2d660eadeca..0107ef8d432c 100644 --- a/src/wallet/subcommands/wallet_cmd.rs +++ b/src/wallet/subcommands/wallet_cmd.rs @@ -11,7 +11,7 @@ use crate::{ cli::humantoken, message::SignedMessage, rpc::{ - mpool_api::{MpoolGetNonce, MpoolPush, MpoolPushMessage}, + mpool::{MpoolGetNonce, MpoolPush, MpoolPushMessage}, types::ApiTipsetKey, RpcMethodExt as _, },