1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#![deny(unused_crate_dependencies)]
use sc_client_api::StorageData;
use sp_blockchain::HeaderBackend;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, NumberFor},
};
use std::sync::Arc;
use jsonrpc_derive::rpc;
type SharedAuthoritySet<TBl> =
sc_finality_grandpa::SharedAuthoritySet<<TBl as BlockT>::Hash, NumberFor<TBl>>;
type SharedEpochChanges<TBl> =
sc_consensus_epochs::SharedEpochChanges<TBl, sc_consensus_babe::Epoch>;
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error<Block: BlockT> {
#[error(transparent)]
Blockchain(#[from] sp_blockchain::Error),
#[error("Failed to load the block weight for block {0:?}")]
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 {
fn from(error: Error<Block>) -> Self {
let message = match error {
Error::JsonRpc(s) => s,
_ => error.to_string(),
};
jsonrpc_core::Error { message, code: jsonrpc_core::ErrorCode::ServerError(1), data: None }
}
}
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)
}
pub type LightSyncStateExtension = Option<serde_json::Value>;
#[derive(serde::Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct LightSyncState<Block: BlockT> {
#[serde(serialize_with = "serialize_encoded")]
pub finalized_block_header: <Block as BlockT>::Header,
#[serde(serialize_with = "serialize_encoded")]
pub babe_epoch_changes: sc_consensus_epochs::EpochChangesFor<Block, sc_consensus_babe::Epoch>,
pub babe_finalized_block_weight: sc_consensus_babe::BabeBlockWeight,
#[serde(serialize_with = "serialize_encoded")]
pub grandpa_authority_set:
sc_finality_grandpa::AuthoritySet<<Block as BlockT>::Hash, NumberFor<Block>>,
}
#[rpc]
pub trait SyncStateRpcApi {
#[rpc(name = "sync_state_genSyncSpec", returns = "jsonrpc_core::Value")]
fn system_gen_sync_spec(&self, raw: bool) -> jsonrpc_core::Result<jsonrpc_core::Value>;
}
pub struct SyncStateRpcHandler<Block: BlockT, Backend> {
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
client: Arc<Backend>,
shared_authority_set: SharedAuthoritySet<Block>,
shared_epoch_changes: SharedEpochChanges<Block>,
deny_unsafe: sc_rpc_api::DenyUnsafe,
}
impl<Block, Backend> SyncStateRpcHandler<Block, Backend>
where
Block: BlockT,
Backend: HeaderBackend<Block> + sc_client_api::AuxStore + 'static,
{
pub fn new(
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
client: Arc<Backend>,
shared_authority_set: SharedAuthoritySet<Block>,
shared_epoch_changes: SharedEpochChanges<Block>,
deny_unsafe: sc_rpc_api::DenyUnsafe,
) -> 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<LightSyncState<Block>, Error<Block>> {
let finalized_hash = self.client.info().finalized_hash;
let finalized_header = self
.client
.header(BlockId::Hash(finalized_hash))?
.ok_or_else(|| sp_blockchain::Error::MissingHeader(finalized_hash.to_string()))?;
let finalized_block_weight =
sc_consensus_babe::aux_schema::load_block_weight(&*self.client, finalized_hash)?
.ok_or_else(|| Error::LoadingBlockWeightFailed(finalized_hash))?;
Ok(LightSyncState {
finalized_block_header: finalized_header,
babe_epoch_changes: self.shared_epoch_changes.shared_data().clone(),
babe_finalized_block_weight: finalized_block_weight,
grandpa_authority_set: self.shared_authority_set.clone_inner(),
})
}
}
impl<Block, Backend> SyncStateRpcApi for SyncStateRpcHandler<Block, Backend>
where
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() {
return Err(err.into())
}
let mut chain_spec = self.chain_spec.cloned_box();
let sync_state = self.build_sync_state().map_err(map_error::<Block, Error<Block>>)?;
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())
})?;
*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))
}
}
fn map_error<Block: BlockT, S: ToString>(error: S) -> jsonrpc_core::Error {
Error::<Block>::JsonRpc(error.to_string()).into()
}