Decouples light-sync state from chain spec (#9491)

* Decouples light-sync state from chain spec

This decouples the light-sync state from chain spec. First, the
light-sync state currently only works with BABE+Grandpa, so not
all *Substrate* based chains can use this feature. The next problem was
also that this pulled the `sc-consensus-babe` and `sc-finality-grandpa`
crate into `sc-chain-spec`.

If a chain now wants to support the light-sync state, it needs to add
the `LightSyncStateExtension` to the chain spec as an extension. This is
documented in the crate level docs of `sc-sync-state-rpc`. If this
extension is not available, `SyncStateRpc` fails at initialization.

* Fix compilation for browser

* Fmt
This commit is contained in:
Bastian Köcher
2021-08-04 15:38:14 +02:00
committed by GitHub
parent 2f4db88b41
commit 6e4d30e8ad
17 changed files with 211 additions and 149 deletions
+100 -23
View File
@@ -17,10 +17,31 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! A RPC handler to create sync states for light clients.
//!
//! Currently only usable with BABE + GRANDPA.
//!
//! # Usage
//!
//! To use the light sync state, it needs to be added as an extension to the chain spec:
//!
//! ```
//! use sc_sync_state_rpc::LightSyncStateExtension;
//!
//! #[derive(Default, Clone, serde::Serialize, serde::Deserialize, sc_chain_spec::ChainSpecExtension)]
//! #[serde(rename_all = "camelCase")]
//! pub struct Extensions {
//! light_sync_state: LightSyncStateExtension,
//! }
//!
//! type ChainSpec = sc_chain_spec::GenericChainSpec<(), Extensions>;
//! ```
//!
//! If the [`LightSyncStateExtension`] is not added as an extension to the chain spec,
//! the [`SyncStateRpcHandler`] will fail at instantiation.
#![deny(unused_crate_dependencies)]
use sc_client_api::StorageData;
use sp_blockchain::HeaderBackend;
use sp_runtime::{
generic::BlockId,
@@ -35,17 +56,24 @@ type SharedAuthoritySet<TBl> =
type SharedEpochChanges<TBl> =
sc_consensus_epochs::SharedEpochChanges<TBl, sc_consensus_babe::Epoch>;
/// Error type used by this crate.
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
enum Error<Block: BlockT> {
pub enum Error<Block: BlockT> {
#[error(transparent)]
Blockchain(#[from] sp_blockchain::Error),
#[error("Failed to load the block weight for block {0:?}")]
LoadingBlockWeightFailed(<Block as BlockT>::Hash),
LoadingBlockWeightFailed(Block::Hash),
#[error("JsonRpc error: {0}")]
JsonRpc(String),
#[error(
"The light sync state extension is not provided by the chain spec. \
Read the `sc-sync-state-rpc` crate docs on how to do this!"
)]
LightSyncStateExtensionNotFound,
}
impl<Block: BlockT> From<Error<Block>> for jsonrpc_core::Error {
@@ -58,6 +86,40 @@ impl<Block: BlockT> From<Error<Block>> for jsonrpc_core::Error {
}
}
/// Serialize the given `val` by encoding it with SCALE codec and serializing it as hex.
fn serialize_encoded<S: serde::Serializer, T: codec::Encode>(
val: &T,
s: S,
) -> Result<S::Ok, S::Error> {
let encoded = StorageData(val.encode());
serde::Serialize::serialize(&encoded, s)
}
/// The light sync state extension.
///
/// This represents a JSON serialized [`LightSyncState`]. It is required to be added to the
/// chain-spec as an extension.
pub type LightSyncStateExtension = Option<serde_json::Value>;
/// Hardcoded infomation that allows light clients to sync quickly.
#[derive(serde::Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct LightSyncState<Block: BlockT> {
/// The header of the best finalized block.
#[serde(serialize_with = "serialize_encoded")]
pub finalized_block_header: <Block as BlockT>::Header,
/// The epoch changes tree for babe.
#[serde(serialize_with = "serialize_encoded")]
pub babe_epoch_changes: sc_consensus_epochs::EpochChangesFor<Block, sc_consensus_babe::Epoch>,
/// The babe weight of the finalized block.
pub babe_finalized_block_weight: sc_consensus_babe::BabeBlockWeight,
/// The authority set for grandpa.
#[serde(serialize_with = "serialize_encoded")]
pub grandpa_authority_set:
sc_finality_grandpa::AuthoritySet<<Block as BlockT>::Hash, NumberFor<Block>>,
}
/// An api for sync state RPC calls.
#[rpc]
pub trait SyncStateRpcApi {
@@ -67,31 +129,37 @@ pub trait SyncStateRpcApi {
}
/// The handler for sync state RPC calls.
pub struct SyncStateRpcHandler<TBl: BlockT, TCl> {
pub struct SyncStateRpcHandler<Block: BlockT, Backend> {
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
client: Arc<TCl>,
shared_authority_set: SharedAuthoritySet<TBl>,
shared_epoch_changes: SharedEpochChanges<TBl>,
client: Arc<Backend>,
shared_authority_set: SharedAuthoritySet<Block>,
shared_epoch_changes: SharedEpochChanges<Block>,
deny_unsafe: sc_rpc_api::DenyUnsafe,
}
impl<TBl, TCl> SyncStateRpcHandler<TBl, TCl>
impl<Block, Backend> SyncStateRpcHandler<Block, Backend>
where
TBl: BlockT,
TCl: HeaderBackend<TBl> + sc_client_api::AuxStore + 'static,
Block: BlockT,
Backend: HeaderBackend<Block> + sc_client_api::AuxStore + 'static,
{
/// Create a new handler.
pub fn new(
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
client: Arc<TCl>,
shared_authority_set: SharedAuthoritySet<TBl>,
shared_epoch_changes: SharedEpochChanges<TBl>,
client: Arc<Backend>,
shared_authority_set: SharedAuthoritySet<Block>,
shared_epoch_changes: SharedEpochChanges<Block>,
deny_unsafe: sc_rpc_api::DenyUnsafe,
) -> Self {
Self { chain_spec, client, shared_authority_set, shared_epoch_changes, deny_unsafe }
) -> Result<Self, Error<Block>> {
if sc_chain_spec::get_extension::<LightSyncStateExtension>(chain_spec.extensions())
.is_some()
{
Ok(Self { chain_spec, client, shared_authority_set, shared_epoch_changes, deny_unsafe })
} else {
Err(Error::<Block>::LightSyncStateExtensionNotFound)
}
}
fn build_sync_state(&self) -> Result<sc_chain_spec::LightSyncState<TBl>, Error<TBl>> {
fn build_sync_state(&self) -> Result<LightSyncState<Block>, Error<Block>> {
let finalized_hash = self.client.info().finalized_hash;
let finalized_header = self
.client
@@ -102,7 +170,7 @@ where
sc_consensus_babe::aux_schema::load_block_weight(&*self.client, finalized_hash)?
.ok_or_else(|| Error::LoadingBlockWeightFailed(finalized_hash))?;
Ok(sc_chain_spec::LightSyncState {
Ok(LightSyncState {
finalized_block_header: finalized_header,
babe_epoch_changes: self.shared_epoch_changes.shared_data().clone(),
babe_finalized_block_weight: finalized_block_weight,
@@ -111,10 +179,10 @@ where
}
}
impl<TBl, TCl> SyncStateRpcApi for SyncStateRpcHandler<TBl, TCl>
impl<Block, Backend> SyncStateRpcApi for SyncStateRpcHandler<Block, Backend>
where
TBl: BlockT,
TCl: HeaderBackend<TBl> + sc_client_api::AuxStore + 'static,
Block: BlockT,
Backend: HeaderBackend<Block> + sc_client_api::AuxStore + 'static,
{
fn system_gen_sync_spec(&self, raw: bool) -> jsonrpc_core::Result<jsonrpc_core::Value> {
if let Err(err) = self.deny_unsafe.check_if_safe() {
@@ -123,12 +191,21 @@ where
let mut chain_spec = self.chain_spec.cloned_box();
let sync_state = self.build_sync_state().map_err(map_error::<TBl, Error<TBl>>)?;
let sync_state = self.build_sync_state().map_err(map_error::<Block, Error<Block>>)?;
chain_spec.set_light_sync_state(sync_state.to_serializable());
let string = chain_spec.as_json(raw).map_err(map_error::<TBl, _>)?;
let extension = sc_chain_spec::get_extension_mut::<LightSyncStateExtension>(
chain_spec.extensions_mut(),
)
.ok_or_else(|| {
Error::<Block>::JsonRpc("Could not find `LightSyncState` chain-spec extension!".into())
})?;
serde_json::from_str(&string).map_err(|err| map_error::<TBl, _>(err))
*extension =
Some(serde_json::to_value(&sync_state).map_err(|err| map_error::<Block, _>(err))?);
let json_string = chain_spec.as_json(raw).map_err(map_error::<Block, _>)?;
serde_json::from_str(&json_string).map_err(|err| map_error::<Block, _>(err))
}
}