Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for fetching grandpa justifications for arbitrary blocks #658

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ tempfile.workspace = true
default = [ "cli" ]
header_commitment_corruption = [ "da-runtime/header_commitment_corruption" ]
fast-runtime = [ "da-runtime/fast-runtime" ]
# Enables grandpa_blockJustification RPC & the cli options associated with it
grandpa-justifications = [ "kate-rpc/grandpa-justifications" ]
testing-environment = [ "da-runtime/testing-environment" ]
cli = [ "clap", "clap-num", "clap_complete", "frame-benchmarking-cli" ]
runtime-benchmarks = [
Expand Down
37 changes: 29 additions & 8 deletions node/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,24 +58,26 @@ pub struct Cli {
/// Max size cannot exceed 10_000
#[arg(long, default_value_t = 64, value_parser=kate_max_cells_size_upper_bound)]
pub kate_max_cells_size: usize,

/// The interval, in blocks, at which Grandpa justifications are either imported or generated and stored in the backend.
#[cfg(feature = "grandpa-justifications")]
#[arg(long, default_value_t =512, value_parser=grandpa_justification_period_bounds)]
pub grandpa_justification_period: u32,
}

fn kate_max_cells_size_upper_bound(s: &str) -> Result<usize, String> {
clap_num::number_range(s, 0, 10_000)
}

#[cfg(feature = "grandpa-justifications")]
fn grandpa_justification_period_bounds(s: &str) -> Result<u32, String> {
clap_num::number_range(s, 1, u32::MAX)
}

/// Possible subcommands of the main binary.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/*
/// The custom inspect subcommand for decoding blocks and extrinsics.
#[command(
name = "inspect",
about = "Decode given block or extrinsic using current native runtime."
)]
Inspect(node_inspect::cli::InspectCmd),
*/
/// Sub-commands concerned with benchmarking.
/// The pallet benchmarking moved to the `pallet` sub-command.
#[command(subcommand)]
Expand Down Expand Up @@ -126,3 +128,22 @@ pub enum Subcommand {
/// Db meta columns information.
ChainInfo(sc_cli::ChainInfoCmd),
}

impl Cli {
/// Partially clones the Cli options, excluding the subcommand.
/// WARNING: Use with caution and only if you're certain about its effects.
pub fn partial_clone(&self) -> Cli {
Cli {
subcommand: None,
run: self.run.clone(),
no_hardware_benchmarks: self.no_hardware_benchmarks,
unsafe_da_sync: self.unsafe_da_sync,
storage_monitor: self.storage_monitor.clone(),
kate_rpc_enabled: self.kate_rpc_enabled,
kate_rpc_metrics_enabled: self.kate_rpc_metrics_enabled,
kate_max_cells_size: self.kate_max_cells_size,
#[cfg(feature = "grandpa-justifications")]
grandpa_justification_period: self.grandpa_justification_period,
}
}
}
40 changes: 5 additions & 35 deletions node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,7 @@ pub fn run() -> Result<()> {
task_manager,
import_queue,
..
} = new_partial(
&config,
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli.partial_clone())?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Expand All @@ -222,13 +216,7 @@ pub fn run() -> Result<()> {
client,
task_manager,
..
} = new_partial(
&config,
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli.partial_clone())?;
Ok((cmd.run(client, config.database), task_manager))
})
},
Expand All @@ -239,13 +227,7 @@ pub fn run() -> Result<()> {
client,
task_manager,
..
} = new_partial(
&config,
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli.partial_clone())?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
},
Expand All @@ -257,13 +239,7 @@ pub fn run() -> Result<()> {
task_manager,
import_queue,
..
} = new_partial(
&config,
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli.partial_clone())?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Expand All @@ -279,13 +255,7 @@ pub fn run() -> Result<()> {
task_manager,
backend,
..
} = new_partial(
&config,
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli.partial_clone())?;
let aux_revert = Box::new(|client: Arc<FullClient>, backend, blocks| {
sc_consensus_babe::revert(client.clone(), backend, blocks)?;
sc_consensus_grandpa::revert(client, blocks)?;
Expand Down
9 changes: 8 additions & 1 deletion node/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ where
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashingFor<Block>>,
{
#[cfg(feature = "grandpa-justifications")]
use kate_rpc::justifications::{GrandpaJustifications, GrandpaServer};
use kate_rpc::metrics::KateApiMetricsServer;
use kate_rpc::{Kate, KateApiServer};
use mmr_rpc::{Mmr, MmrApiServer};
Expand Down Expand Up @@ -235,13 +237,18 @@ where

if is_dev_chain || kate_rpc_enabled || kate_rpc_metrics_enabled {
io.merge(KateApiServer::into_rpc(Kate::<C, Block>::new(
client,
client.clone(),
kate_max_cells_size,
)))?;
}

#[cfg(feature = "testing-environment")]
io.merge(TestingApiServer::into_rpc(TestingEnv))?;

#[cfg(feature = "grandpa-justifications")]
io.merge(GrandpaServer::into_rpc(
GrandpaJustifications::<C, Block>::new(client),
))?;

Ok(io)
}
52 changes: 26 additions & 26 deletions node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,7 @@ pub fn create_extrinsic(
#[allow(clippy::type_complexity)]
pub fn new_partial(
config: &Configuration,
unsafe_da_sync: bool,
kate_max_cells_size: usize,
kate_rpc_enabled: bool,
kate_rpc_metrics_enabled: bool,
cli: Cli,
) -> Result<
sc_service::PartialComponents<
FullClient,
Expand Down Expand Up @@ -248,9 +245,14 @@ pub fn new_partial(
client.clone(),
);

#[cfg(not(feature = "grandpa-justifications"))]
let grandpa_justification_period = GRANDPA_JUSTIFICATION_PERIOD;
#[cfg(feature = "grandpa-justifications")]
let grandpa_justification_period = cli.grandpa_justification_period;

let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import(
client.clone(),
GRANDPA_JUSTIFICATION_PERIOD,
grandpa_justification_period,
&(client.clone() as Arc<_>),
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
Expand All @@ -263,7 +265,7 @@ pub fn new_partial(
client.clone(),
)?;

let da_block_import = BlockImport::new(client.clone(), block_import, unsafe_da_sync);
let da_block_import = BlockImport::new(client.clone(), block_import, cli.unsafe_da_sync);

let slot_duration = babe_link.config().slot_duration();
let (import_queue, babe_worker_handle) =
Expand Down Expand Up @@ -330,9 +332,9 @@ pub fn new_partial(
subscription_executor,
finality_provider: finality_proof_provider.clone(),
},
kate_max_cells_size,
kate_rpc_enabled,
kate_rpc_metrics_enabled,
kate_max_cells_size: cli.kate_max_cells_size,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice if we create a KateDeps here, in the same way of node_rpc::BabeDeps and node_rpc::GrandpaDeps (see some lines avobe).

kate_rpc_enabled: cli.kate_rpc_enabled,
kate_rpc_metrics_enabled: cli.kate_rpc_metrics_enabled,
};

node_rpc::create_full(deps, rpc_backend.clone()).map_err(Into::into)
Expand Down Expand Up @@ -375,10 +377,7 @@ pub fn new_full_base(
config: Configuration,
disable_hardware_benchmarks: bool,
with_startup_data: impl FnOnce(&BlockImport, &sc_consensus_babe::BabeLink<Block>),
unsafe_da_sync: bool,
kate_max_cells_size: usize,
kate_rpc_enabled: bool,
kate_rpc_metrics_enabled: bool,
cli: Cli,
) -> Result<NewFullBase, ServiceError> {
let hwbench = if !disable_hardware_benchmarks {
config.database.path().map(|database_path| {
Expand All @@ -389,6 +388,11 @@ pub fn new_full_base(
None
};

#[cfg(not(feature = "grandpa-justifications"))]
let grandpa_justification_period = GRANDPA_JUSTIFICATION_PERIOD;
#[cfg(feature = "grandpa-justifications")]
let grandpa_justification_period = cli.grandpa_justification_period;

let sc_service::PartialComponents {
client,
backend,
Expand All @@ -398,13 +402,7 @@ pub fn new_full_base(
select_chain,
transaction_pool,
other: (rpc_builder, import_setup, rpc_setup, mut telemetry),
} = new_partial(
&config,
unsafe_da_sync,
kate_max_cells_size,
kate_rpc_enabled,
kate_rpc_metrics_enabled,
)?;
} = new_partial(&config, cli)?;

let shared_voter_state = rpc_setup;
let auth_disc_publish_non_global_ips = config.network.allow_non_globals_in_dht;
Expand Down Expand Up @@ -582,7 +580,7 @@ pub fn new_full_base(
let grandpa_config = sc_consensus_grandpa::Config {
// Considering our block_time of 20 seconds, we may consider increasing this to 2 seconds without introducing delay in finality.
gossip_duration: std::time::Duration::from_millis(1000),
justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD,
justification_generation_period: grandpa_justification_period,
name: Some(name),
observer_enabled: false,
keystore,
Expand Down Expand Up @@ -655,20 +653,22 @@ pub fn new_full_base(
/// Builds a new service for a full client.
pub fn new_full(config: Configuration, cli: Cli) -> Result<TaskManager, ServiceError> {
let database_path = config.database.path().map(Path::to_path_buf);
let storage_param = cli.storage_monitor.clone();
let task_manager = new_full_base(
config,
cli.no_hardware_benchmarks,
|_, _| (),
cli.unsafe_da_sync,
cli.kate_max_cells_size,
cli.kate_rpc_enabled,
cli.kate_rpc_metrics_enabled,
cli,
// cli.unsafe_da_sync,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove commented code

// cli.kate_max_cells_size,
// cli.kate_rpc_enabled,
// cli.kate_rpc_metrics_enabled,
)
.map(|NewFullBase { task_manager, .. }| task_manager)?;

if let Some(database_path) = database_path {
sc_storage_monitor::StorageMonitorService::try_spawn(
cli.storage_monitor,
storage_param,
database_path,
&task_manager.spawn_essential_handle(),
)
Expand Down
2 changes: 2 additions & 0 deletions rpc/kate-rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ sp-runtime = { workspace = true, default-features = false }

[features]
default = [ "std" ]
# enables grandpa_blockJustification RPC & the cli options associated with it
grandpa-justifications = []
std = [
"avail-base/std",
"avail-core/std",
Expand Down
85 changes: 85 additions & 0 deletions rpc/kate-rpc/src/justifications.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use jsonrpsee::{
core::{async_trait, RpcResult},
proc_macros::rpc,
types::error::ErrorObject,
};
use sc_client_api::BlockBackend;
use sp_runtime::traits::Block as BlockT;
use std::{marker::PhantomData, sync::Arc};

/// GRANDPA consensus engine_id
pub const GRANDPA_ENGINE_ID: [u8; 4] = *b"FRNK";

#[rpc(client, server)]
pub trait Grandpa<Block>
where
Block: BlockT,
{
#[method(name = "grandpa_blockJustification")]
async fn block_justification(&self, block_number: u32) -> RpcResult<Vec<u8>>;
}

pub struct GrandpaJustifications<Client, Block: BlockT> {
client: Arc<Client>,
_block: PhantomData<Block>,
}

impl<Client, Block: BlockT> GrandpaJustifications<Client, Block> {
pub fn new(client: Arc<Client>) -> Self {
Self {
client,
_block: PhantomData,
}
}
}

/// Error type for this RPC API.
pub enum Error {
/// Generic justification error.
JustificationError,
}

impl From<Error> for i32 {
fn from(e: Error) -> i32 {
match e {
Error::JustificationError => 1,
}
}
}

macro_rules! internal_err {
($($arg:tt)*) => {{
ErrorObject::owned(
Error::JustificationError.into(),
format!($($arg)*),
None::<()>
)
}}
}

#[async_trait]
impl<Client, Block> GrandpaServer<Block> for GrandpaJustifications<Client, Block>
where
Block: BlockT,
Client: Send + Sync + 'static,
Client: BlockBackend<Block>,
{
async fn block_justification(&self, block_number: u32) -> RpcResult<Vec<u8>> {
// Fetch the block hash
let block_hash = self
.client
.block_hash(block_number.into())
.map_err(|e| internal_err!("Failed to fetch block hash: {e:?}"))?
.ok_or_else(|| internal_err!("Block hash not found for block #{block_number}"))?;

// Fetch the justification for the block hash
let justification = self
.client
.justifications(block_hash)
.map_err(|e| internal_err!("Failed to fetch justifications: {e:?}"))?
.and_then(|just| just.into_justification(GRANDPA_ENGINE_ID));

justification
.ok_or_else(|| internal_err!("Cannot fetch justification for block #{block_number}"))
}
}
Loading
Loading