Skip to content

Commit

Permalink
refactor: consolidate crate::rpc_api into crate::rpc (#4134)
Browse files Browse the repository at this point in the history
  • Loading branch information
aatifsyed authored Apr 2, 2024
1 parent ba9f121 commit 5fd30d2
Show file tree
Hide file tree
Showing 36 changed files with 635 additions and 709 deletions.
2 changes: 1 addition & 1 deletion src/cli/subcommands/net_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::libp2p::{Multiaddr, Protocol};
use crate::rpc_api::data_types::AddrInfo;
use crate::rpc::types::AddrInfo;
use crate::rpc_client::ApiInfo;
use ahash::{HashMap, HashSet};
use cid::multibase;
Expand Down
4 changes: 2 additions & 2 deletions src/cli/subcommands/snapshot_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
use super::*;
use crate::chain_sync::SyncConfig;
use crate::cli_shared::snapshot::{self, TrustedVendor};
use crate::rpc_api::chain_api::ChainExportParams;
use crate::rpc_api::data_types::ApiTipsetKey;
use crate::rpc::chain_api::ChainExportParams;
use crate::rpc::types::ApiTipsetKey;
use crate::rpc_client::ApiInfo;
use anyhow::Context as _;
use chrono::DateTime;
Expand Down
2 changes: 1 addition & 1 deletion src/cli/subcommands/sync_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
time::Duration,
};

use crate::{chain_sync::SyncStage, rpc_api::data_types::RPCSyncState, rpc_client::*};
use crate::{chain_sync::SyncStage, rpc::types::RPCSyncState, rpc_client::*};
use cid::Cid;
use clap::Subcommand;
use itertools::Itertools as _;
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ mod message_pool;
mod metrics;
mod networks;
mod rpc;
mod rpc_api;
mod rpc_client;
mod shim;
mod state_manager;
Expand Down
2 changes: 1 addition & 1 deletion src/libp2p/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::libp2p_bitswap::{
BitswapStoreRead, BitswapStoreReadWrite,
};
use crate::message::SignedMessage;
use crate::{blocks::GossipBlock, rpc_api::net_api::NetInfoResult};
use crate::{blocks::GossipBlock, rpc::net_api::NetInfoResult};
use crate::{chain::ChainStore, utils::encoding::from_slice_with_fallback};
use ahash::{HashMap, HashSet};
use cid::Cid;
Expand Down
17 changes: 16 additions & 1 deletion src/rpc/auth_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,28 @@
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::auth::*;
use crate::lotus_json::lotus_json_with_self;
use crate::lotus_json::LotusJson;
use crate::rpc::error::JsonRpcError;
use crate::rpc::Ctx;
use crate::rpc_api::auth_api::*;
use anyhow::Result;
use chrono::Duration;
use fvm_ipld_blockstore::Blockstore;
use jsonrpsee::types::Params;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DurationSeconds};

pub const AUTH_NEW: &str = "Filecoin.AuthNew";
#[serde_as]
#[derive(Deserialize, Serialize)]
pub struct AuthNewParams {
pub perms: Vec<String>,
#[serde_as(as = "DurationSeconds<i64>")]
pub token_exp: Duration,
}
lotus_json_with_self!(AuthNewParams);

pub const AUTH_VERIFY: &str = "Filecoin.AuthVerify";

/// RPC call to create a new JWT Token
pub async fn auth_new<DB: Blockstore>(
Expand Down
7 changes: 4 additions & 3 deletions src/rpc/auth_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@

use crate::auth::{verify_token, JWT_IDENTIFIER};
use crate::key_management::KeyStore;
use crate::rpc::CANCEL_METHOD_NAME;
use crate::rpc_api::*;

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, CANCEL_METHOD_NAME,
};
use futures::future::BoxFuture;
use futures::FutureExt;
use hyper::header::{HeaderValue, AUTHORIZATION};
Expand Down
2 changes: 2 additions & 0 deletions src/rpc/beacon_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use anyhow::Result;
use fvm_ipld_blockstore::Blockstore;
use jsonrpsee::types::Params;

pub const BEACON_GET_ENTRY: &str = "Filecoin.BeaconGetEntry";

/// `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
/// becomes available
Expand Down
130 changes: 125 additions & 5 deletions src/rpc/chain_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,23 @@
// SPDX-License-Identifier: Apache-2.0, MIT
#![allow(clippy::unused_async)]

#[cfg(test)]
use crate::blocks::RawBlockHeader;
use crate::blocks::{CachingBlockHeader, Tipset, TipsetKey};
use crate::chain::index::ResolveNullTipset;
use crate::chain::{ChainStore, HeadChange};
use crate::cid_collections::CidHashSet;
use crate::lotus_json::lotus_json_with_self;
use crate::lotus_json::HasLotusJson;
use crate::lotus_json::LotusJson;
#[cfg(test)]
use crate::lotus_json::{assert_all_snapshots, assert_unchanged_via_json};
use crate::message::ChainMessage;
use crate::rpc::types::{ApiHeadChange, ApiMessage, ApiReceipt, ApiTipsetKey, BlockMessages};
use crate::rpc::{
error::JsonRpcError,
reflect::{Ctx, RpcMethod},
};
use crate::rpc_api::data_types::{ApiHeadChange, ApiMessage, ApiReceipt};
use crate::rpc_api::{
chain_api::*,
data_types::{ApiTipsetKey, BlockMessages},
};
use crate::shim::clock::ChainEpoch;
use crate::shim::message::Message;
use crate::utils::io::VoidAsyncWriter;
Expand All @@ -29,13 +31,131 @@ use hex::ToHex;
use jsonrpsee::types::error::ErrorObjectOwned;
use jsonrpsee::types::Params;
use once_cell::sync::Lazy;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{
broadcast::{self, Receiver as Subscriber},
Mutex,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainExportParams {
pub epoch: ChainEpoch,
pub recent_roots: i64,
pub output_path: PathBuf,
#[serde(with = "crate::lotus_json")]
pub tipset_keys: ApiTipsetKey,
pub skip_checksum: bool,
pub dry_run: bool,
}

lotus_json_with_self!(ChainExportParams);

pub type ChainExportResult = Option<String>;

pub const CHAIN_GET_MESSAGE: &str = "Filecoin.ChainGetMessage";
pub const CHAIN_EXPORT: &str = "Filecoin.ChainExport";
pub const CHAIN_READ_OBJ: &str = "Filecoin.ChainReadObj";
pub const CHAIN_HAS_OBJ: &str = "Filecoin.ChainHasObj";
pub const CHAIN_GET_BLOCK_MESSAGES: &str = "Filecoin.ChainGetBlockMessages";
pub const CHAIN_GET_TIPSET_BY_HEIGHT: &str = "Filecoin.ChainGetTipSetByHeight";
pub const CHAIN_GET_TIPSET_AFTER_HEIGHT: &str = "Filecoin.ChainGetTipSetAfterHeight";
pub const CHAIN_GET_GENESIS: &str = "Filecoin.ChainGetGenesis";
pub const CHAIN_HEAD: &str = "Filecoin.ChainHead";
pub const CHAIN_GET_BLOCK: &str = "Filecoin.ChainGetBlock";
pub const CHAIN_GET_TIPSET: &str = "Filecoin.ChainGetTipSet";
pub const CHAIN_GET_PATH: &str = "Filecoin.ChainGetPath";
pub const CHAIN_SET_HEAD: &str = "Filecoin.ChainSetHead";
pub const CHAIN_GET_MIN_BASE_FEE: &str = "Filecoin.ChainGetMinBaseFee";
pub const CHAIN_GET_MESSAGES_IN_TIPSET: &str = "Filecoin.ChainGetMessagesInTipset";
pub const CHAIN_GET_PARENT_MESSAGES: &str = "Filecoin.ChainGetParentMessages";
pub const CHAIN_NOTIFY: &str = "Filecoin.ChainNotify";
pub const CHAIN_GET_PARENT_RECEIPTS: &str = "Filecoin.ChainGetParentReceipts";

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PathChange<T = Arc<Tipset>> {
Revert(T),
Apply(T),
}
impl HasLotusJson for PathChange {
type LotusJson = PathChange<LotusJson<Tipset>>;

#[cfg(test)]
fn snapshots() -> Vec<(serde_json::Value, Self)> {
use serde_json::json;
vec![(
json!({
"revert": {
"Blocks": [
{
"BeaconEntries": null,
"ForkSignaling": 0,
"Height": 0,
"Messages": { "/": "baeaaaaa" },
"Miner": "f00",
"ParentBaseFee": "0",
"ParentMessageReceipts": { "/": "baeaaaaa" },
"ParentStateRoot": { "/":"baeaaaaa" },
"ParentWeight": "0",
"Parents": [{"/":"bafyreiaqpwbbyjo4a42saasj36kkrpv4tsherf2e7bvezkert2a7dhonoi"}],
"Timestamp": 0,
"WinPoStProof": null
}
],
"Cids": [
{ "/": "bafy2bzaceag62hjj3o43lf6oyeox3fvg5aqkgl5zagbwpjje3ajwg6yw4iixk" }
],
"Height": 0
}
}),
Self::Revert(Arc::new(Tipset::from(RawBlockHeader::default()))),
)]
}

fn into_lotus_json(self) -> Self::LotusJson {
match self {
PathChange::Revert(it) => PathChange::Revert(LotusJson(Tipset::clone(&it))),
PathChange::Apply(it) => PathChange::Apply(LotusJson(Tipset::clone(&it))),
}
}

fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
match lotus_json {
PathChange::Revert(it) => PathChange::Revert(it.into_inner().into()),
PathChange::Apply(it) => PathChange::Apply(it.into_inner().into()),
}
}
}

#[cfg(test)]
impl<T> quickcheck::Arbitrary for PathChange<T>
where
T: quickcheck::Arbitrary,
{
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let inner = T::arbitrary(g);
g.choose(&[PathChange::Apply(inner.clone()), PathChange::Revert(inner)])
.unwrap()
.clone()
}
}

#[test]
fn snapshots() {
assert_all_snapshots::<PathChange>()
}

#[cfg(test)]
quickcheck::quickcheck! {
fn quickcheck(val: PathChange) -> () {
assert_unchanged_via_json(val)
}
}

pub async fn chain_get_message<DB: Blockstore>(
params: Params<'_>,
data: Ctx<DB>,
Expand Down
8 changes: 7 additions & 1 deletion src/rpc/common_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// SPDX-License-Identifier: Apache-2.0, MIT
#![allow(clippy::unused_async)]

use crate::rpc::types::{APIVersion, Version};
use crate::rpc::{error::JsonRpcError, RPCState};
use crate::rpc_api::data_types::{APIVersion, Version};

use fvm_ipld_blockstore::Blockstore;
use once_cell::sync::Lazy;
Expand All @@ -14,6 +14,12 @@ use uuid::Uuid;

static SESSION_UUID: Lazy<Uuid> = Lazy::new(Uuid::new_v4);

pub const VERSION: &str = "Filecoin.Version";
pub const SHUTDOWN: &str = "Filecoin.Shutdown";
pub const START_TIME: &str = "Filecoin.StartTime";
pub const DISCOVER: &str = "Filecoin.Discover";
pub const SESSION: &str = "Filecoin.Session";

/// The session UUID uniquely identifies the API node.
pub fn session() -> Result<String, JsonRpcError> {
Ok(SESSION_UUID.to_string())
Expand Down
Loading

0 comments on commit 5fd30d2

Please sign in to comment.