Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 16474ee

Browse files
authored
grandpa-rpc: use FinalityProofProvider to check finality for rpc (#6215)
* grandpa-rpc: use FinalityProofProvider to check finality for rpc * grandpa-rpc: minor tidy * grandpa-rpc: remove dyn FinalityProofProvider * grandpa-rpc: remove unused dependencies * node: move finality_proof_provider setup * grandpa-rpc: print error reported by finality_proof_provider * grandpa-rpc: add note about unnecessary encode/decode * grandpa-rpc: dont encode/decode and use correct hash * grandpa-rpc: set_id is optional * grandpa-rpc: create test for prove_finality * grandpa-rpc: set visibility back to how it was * grandpa-rpc: remove unused dependency * grandpa-rpc: minor tidy * grandpa: doc strings * grandpa-rpc: rename to prove_finality * grandpa-rpc: use current set id if none is provided * grandpa-rpc: remove unnecessary check in test * node: group finality_proof_provider in rpc_setup * grandpa: make prove_finality concrete in FinalityProofProvider * grandpa-rpc: wrap finality output in struct and store as Bytes * grandpa-rpc: exhaustive error codes and wrap * grandpa-rpc: let prove_finality take a range instead of a starting point * grandpa-rpc: fix test for changed API * grandpa-rpc: fix line length * grandpa: fix reviewer nits * node/rpc: fix reviewer comments
1 parent b28d202 commit 16474ee

File tree

10 files changed

+263
-31
lines changed

10 files changed

+263
-31
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bin/node/cli/src/service.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,10 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
5858
grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
5959
sc_consensus_babe::BabeLink<Block>,
6060
),
61-
grandpa::SharedVoterState,
61+
(
62+
grandpa::SharedVoterState,
63+
Arc<GrandpaFinalityProofProvider<FullBackend, Block>>,
64+
),
6265
)
6366
>, ServiceError> {
6467
let (client, backend, keystore, task_manager) =
@@ -108,8 +111,10 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
108111
let justification_stream = grandpa_link.justification_stream();
109112
let shared_authority_set = grandpa_link.shared_authority_set().clone();
110113
let shared_voter_state = grandpa::SharedVoterState::empty();
114+
let finality_proof_provider =
115+
GrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone());
111116

112-
let rpc_setup = shared_voter_state.clone();
117+
let rpc_setup = (shared_voter_state.clone(), finality_proof_provider.clone());
113118

114119
let babe_config = babe_link.config().clone();
115120
let shared_epoch_changes = babe_link.epoch_changes().clone();
@@ -135,6 +140,7 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
135140
shared_authority_set: shared_authority_set.clone(),
136141
justification_stream: justification_stream.clone(),
137142
subscription_executor,
143+
finality_provider: finality_proof_provider.clone(),
138144
},
139145
};
140146

@@ -174,8 +180,7 @@ pub fn new_full_base(
174180
other: (rpc_extensions_builder, import_setup, rpc_setup),
175181
} = new_partial(&config)?;
176182

177-
let finality_proof_provider =
178-
GrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone());
183+
let (shared_voter_state, finality_proof_provider) = rpc_setup;
179184

180185
let (network, network_status_sinks, system_rpc_tx, network_starter) =
181186
sc_service::build_network(sc_service::BuildNetworkParams {
@@ -220,7 +225,6 @@ pub fn new_full_base(
220225
})?;
221226

222227
let (block_import, grandpa_link, babe_link) = import_setup;
223-
let shared_voter_state = rpc_setup;
224228

225229
(with_startup_data)(&block_import, &babe_link);
226230

bin/node/rpc/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ sp-block-builder = { version = "2.0.0-rc6", path = "../../../primitives/block-bu
3030
sp-blockchain = { version = "2.0.0-rc6", path = "../../../primitives/blockchain" }
3131
sp-consensus = { version = "0.8.0-rc6", path = "../../../primitives/consensus/common" }
3232
sp-consensus-babe = { version = "0.8.0-rc6", path = "../../../primitives/consensus/babe" }
33+
sp-runtime = { version = "2.0.0-rc6", path = "../../../primitives/runtime" }
3334
sp-transaction-pool = { version = "2.0.0-rc6", path = "../../../primitives/transaction-pool" }
3435
substrate-frame-rpc-system = { version = "2.0.0-rc6", path = "../../../utils/frame/rpc/system" }

bin/node/rpc/src/lib.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ use node_primitives::{Block, BlockNumber, AccountId, Index, Balance, Hash};
3636
use sc_consensus_babe::{Config, Epoch};
3737
use sc_consensus_babe_rpc::BabeRpcHandler;
3838
use sc_consensus_epochs::SharedEpochChanges;
39-
use sc_finality_grandpa::{SharedVoterState, SharedAuthoritySet, GrandpaJustificationStream};
39+
use sc_finality_grandpa::{
40+
SharedVoterState, SharedAuthoritySet, FinalityProofProvider, GrandpaJustificationStream
41+
};
4042
use sc_finality_grandpa_rpc::GrandpaRpcHandler;
4143
use sc_keystore::KeyStorePtr;
4244
pub use sc_rpc_api::DenyUnsafe;
@@ -71,7 +73,7 @@ pub struct BabeDeps {
7173
}
7274

7375
/// Extra dependencies for GRANDPA
74-
pub struct GrandpaDeps {
76+
pub struct GrandpaDeps<B> {
7577
/// Voting round info.
7678
pub shared_voter_state: SharedVoterState,
7779
/// Authority set info.
@@ -80,10 +82,12 @@ pub struct GrandpaDeps {
8082
pub justification_stream: GrandpaJustificationStream<Block>,
8183
/// Executor to drive the subscription manager in the Grandpa RPC handler.
8284
pub subscription_executor: SubscriptionTaskExecutor,
85+
/// Finality proof provider.
86+
pub finality_provider: Arc<FinalityProofProvider<B, Block>>,
8387
}
8488

8589
/// Full client dependencies.
86-
pub struct FullDeps<C, P, SC> {
90+
pub struct FullDeps<C, P, SC, B> {
8791
/// The client instance to use.
8892
pub client: Arc<C>,
8993
/// Transaction pool instance.
@@ -95,15 +99,15 @@ pub struct FullDeps<C, P, SC> {
9599
/// BABE specific dependencies.
96100
pub babe: BabeDeps,
97101
/// GRANDPA specific dependencies.
98-
pub grandpa: GrandpaDeps,
102+
pub grandpa: GrandpaDeps<B>,
99103
}
100104

101105
/// A IO handler that uses all Full RPC extensions.
102106
pub type IoHandler = jsonrpc_core::IoHandler<sc_rpc::Metadata>;
103107

104108
/// Instantiate all Full RPC extensions.
105-
pub fn create_full<C, P, SC>(
106-
deps: FullDeps<C, P, SC>,
109+
pub fn create_full<C, P, SC, B>(
110+
deps: FullDeps<C, P, SC, B>,
107111
) -> jsonrpc_core::IoHandler<sc_rpc_api::Metadata> where
108112
C: ProvideRuntimeApi<Block>,
109113
C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static,
@@ -115,6 +119,8 @@ pub fn create_full<C, P, SC>(
115119
C::Api: BlockBuilder<Block>,
116120
P: TransactionPool + 'static,
117121
SC: SelectChain<Block> +'static,
122+
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
123+
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
118124
{
119125
use substrate_frame_rpc_system::{FullSystem, SystemApi};
120126
use pallet_contracts_rpc::{Contracts, ContractsApi};
@@ -140,6 +146,7 @@ pub fn create_full<C, P, SC>(
140146
shared_authority_set,
141147
justification_stream,
142148
subscription_executor,
149+
finality_provider,
143150
} = grandpa;
144151

145152
io.extend_with(
@@ -173,6 +180,7 @@ pub fn create_full<C, P, SC>(
173180
shared_voter_state,
174181
justification_stream,
175182
subscription_executor,
183+
finality_provider,
176184
)
177185
)
178186
);

client/finality-grandpa/rpc/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
1010
[dependencies]
1111
sc-finality-grandpa = { version = "0.8.0-rc6", path = "../" }
1212
sc-rpc = { version = "2.0.0-rc6", path = "../../rpc" }
13+
sp-blockchain = { version = "2.0.0-rc6", path = "../../../primitives/blockchain" }
1314
sp-core = { version = "2.0.0-rc6", path = "../../../primitives/core" }
1415
sp-runtime = { version = "2.0.0-rc6", path = "../../../primitives/runtime" }
1516
finality-grandpa = { version = "0.12.3", features = ["derive-codec"] }
@@ -23,12 +24,12 @@ serde_json = "1.0.50"
2324
log = "0.4.8"
2425
derive_more = "0.99.2"
2526
parity-scale-codec = { version = "1.3.0", features = ["derive"] }
27+
sc-client-api = { version = "2.0.0-rc6", path = "../../api" }
2628

2729
[dev-dependencies]
2830
sc-block-builder = { version = "0.8.0-rc6", path = "../../block-builder" }
2931
sc-network-test = { version = "0.8.0-rc6", path = "../../network/test" }
3032
sc-rpc = { version = "2.0.0-rc6", path = "../../rpc", features = ["test-helpers"] }
31-
sp-blockchain = { version = "2.0.0-rc6", path = "../../../primitives/blockchain" }
3233
sp-consensus = { version = "0.8.0-rc6", path = "../../../primitives/consensus/common" }
3334
sp-core = { version = "2.0.0-rc6", path = "../../../primitives/core" }
3435
sp-finality-grandpa = { version = "2.0.0-rc6", path = "../../../primitives/finality-grandpa" }

client/finality-grandpa/rpc/src/error.rs

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
// You should have received a copy of the GNU General Public License
1717
// along with this program. If not, see <https://www.gnu.org/licenses/>.
1818

19-
use crate::NOT_READY_ERROR_CODE;
20-
2119
#[derive(derive_more::Display, derive_more::From)]
2220
/// Top-level error type for the RPC handler
2321
pub enum Error {
@@ -30,13 +28,41 @@ pub enum Error {
3028
/// GRANDPA reports voter state with round id or weights larger than 32-bits.
3129
#[display(fmt = "GRANDPA reports voter state as unreasonably large")]
3230
VoterStateReportsUnreasonablyLargeNumbers,
31+
/// GRANDPA prove finality failed.
32+
#[display(fmt = "GRANDPA prove finality rpc failed: {}", _0)]
33+
ProveFinalityFailed(sp_blockchain::Error),
34+
}
35+
36+
/// The error codes returned by jsonrpc.
37+
pub enum ErrorCode {
38+
/// Returned when Grandpa RPC endpoint is not ready.
39+
NotReady = 1,
40+
/// Authority set ID is larger than 32-bits.
41+
AuthoritySetTooLarge,
42+
/// Voter state with round id or weights larger than 32-bits.
43+
VoterStateTooLarge,
44+
/// Failed to prove finality.
45+
ProveFinality,
46+
}
47+
48+
impl From<Error> for ErrorCode {
49+
fn from(error: Error) -> Self {
50+
match error {
51+
Error::EndpointNotReady => ErrorCode::NotReady,
52+
Error::AuthoritySetIdReportedAsUnreasonablyLarge => ErrorCode::AuthoritySetTooLarge,
53+
Error::VoterStateReportsUnreasonablyLargeNumbers => ErrorCode::VoterStateTooLarge,
54+
Error::ProveFinalityFailed(_) => ErrorCode::ProveFinality,
55+
}
56+
}
3357
}
3458

3559
impl From<Error> for jsonrpc_core::Error {
3660
fn from(error: Error) -> Self {
61+
let message = format!("{}", error);
62+
let code = ErrorCode::from(error);
3763
jsonrpc_core::Error {
38-
message: format!("{}", error),
39-
code: jsonrpc_core::ErrorCode::ServerError(NOT_READY_ERROR_CODE),
64+
message,
65+
code: jsonrpc_core::ErrorCode::ServerError(code as i64),
4066
data: None,
4167
}
4268
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// This file is part of Substrate.
2+
3+
// Copyright (C) 2020 Parity Technologies (UK) Ltd.
4+
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5+
6+
// This program is free software: you can redistribute it and/or modify
7+
// it under the terms of the GNU General Public License as published by
8+
// the Free Software Foundation, either version 3 of the License, or
9+
// (at your option) any later version.
10+
11+
// This program is distributed in the hope that it will be useful,
12+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
// GNU General Public License for more details.
15+
16+
// You should have received a copy of the GNU General Public License
17+
// along with this program. If not, see <https://www.gnu.org/licenses/>.
18+
19+
use serde::{Serialize, Deserialize};
20+
21+
use sc_finality_grandpa::FinalityProofProvider;
22+
use sp_runtime::traits::{Block as BlockT, NumberFor};
23+
24+
#[derive(Serialize, Deserialize)]
25+
pub struct EncodedFinalityProofs(pub sp_core::Bytes);
26+
27+
/// Local trait mainly to allow mocking in tests.
28+
pub trait RpcFinalityProofProvider<Block: BlockT> {
29+
/// Return finality proofs for the given authorities set id, if it is provided, otherwise the
30+
/// current one will be used.
31+
fn rpc_prove_finality(
32+
&self,
33+
begin: Block::Hash,
34+
end: Block::Hash,
35+
authorities_set_id: u64,
36+
) -> Result<Option<EncodedFinalityProofs>, sp_blockchain::Error>;
37+
}
38+
39+
impl<B, Block> RpcFinalityProofProvider<Block> for FinalityProofProvider<B, Block>
40+
where
41+
Block: BlockT,
42+
NumberFor<Block>: finality_grandpa::BlockNumberOps,
43+
B: sc_client_api::backend::Backend<Block> + Send + Sync + 'static,
44+
{
45+
fn rpc_prove_finality(
46+
&self,
47+
begin: Block::Hash,
48+
end: Block::Hash,
49+
authorities_set_id: u64,
50+
) -> Result<Option<EncodedFinalityProofs>, sp_blockchain::Error> {
51+
self.prove_finality(begin, end, authorities_set_id)
52+
.map(|x| x.map(|y| EncodedFinalityProofs(y.into())))
53+
}
54+
}

0 commit comments

Comments
 (0)