This repository has been archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
service.rs
240 lines (210 loc) · 8.04 KB
/
service.rs
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
use std::sync::Arc;
use std::time::Duration;
use substrate_client::LongestChain;
use futures::prelude::*;
use gather_runtime::{self, GenesisConfig, opaque::Block, RuntimeApi};
use substrate_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};
use transaction_pool::{self, txpool::{Pool as TransactionPool}};
use inherents::InherentDataProviders;
use network::{construct_simple_protocol};
use substrate_executor::native_executor_instance;
pub use substrate_executor::NativeExecutor;
use aura_primitives::sr25519::{AuthorityPair as AuraPair};
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};
use crate::config::GatherConfig;
use serde_json;
// Our native executor instance.
native_executor_instance!(
pub Executor,
gather_runtime::api::dispatch,
gather_runtime::native_version,
);
construct_simple_protocol! {
/// Demo protocol attachment for substrate.
pub struct NodeProtocol where Block = Block { }
}
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
macro_rules! new_full_start {
($config:expr) => {{
use gather_emailer::make_lettre_transport;
type RpcExtension = jsonrpc_core::IoHandler<substrate_rpc::Metadata>;
let mut import_setup = None;
let emailer = make_lettre_transport($config.custom.email.clone())?;
let emailer_config = serde_json::to_vec(&$config.custom.email).expect("We can always serialise the config");
let inherent_data_providers = inherents::InherentDataProviders::new();
let builder = substrate_service::ServiceBuilder::new_full::<
gather_runtime::opaque::Block, gather_runtime::RuntimeApi, crate::service::Executor
>($config)?
.with_select_chain(|_config, backend| {
Ok(substrate_client::LongestChain::new(backend.clone()))
})?
.with_transaction_pool(|config, client|
Ok(transaction_pool::txpool::Pool::new(config, transaction_pool::FullChainApi::new(client)))
)?
.with_import_queue(|_config, client, mut select_chain, transaction_pool| {
let select_chain = select_chain.take()
.ok_or_else(|| substrate_service::Error::SelectChainRequired)?;
let (grandpa_block_import, grandpa_link) =
grandpa::block_import::<_, _, _, gather_runtime::RuntimeApi, _, _>(
client.clone(), &*client, select_chain
)?;
let import_queue = aura::import_queue::<_, _, AuraPair, _>(
aura::SlotDuration::get_or_compute(&*client)?,
Box::new(grandpa_block_import.clone()),
Some(Box::new(grandpa_block_import.clone())),
None,
client,
inherent_data_providers.clone(),
Some(transaction_pool),
)?;
import_setup = Some((grandpa_block_import, grandpa_link));
Ok(import_queue)
})?
.with_rpc_extensions(|client, pool, backend| -> RpcExtension {
use srml_system_rpc::{System, SystemApi};
use crate::rpc::{GatherApi, Gather};
use substrate_client::backend::Backend;
use substrate_client::backend::OffchainStorage;
use substrate_offchain::STORAGE_PREFIX;
let mut io = jsonrpc_core::IoHandler::default();
io.extend_with(
SystemApi::to_delegate(System::new(client.clone(), pool))
);
if let Some(mut storage) = backend.offchain_storage() {
// write email configuration to storage
storage.set(STORAGE_PREFIX, b"email_config", &emailer_config);
io.extend_with(
GatherApi::<gather_runtime::AccountId>::to_delegate(Gather::new(storage.clone(), emailer))
);
}
io
})?;
(builder, import_setup, inherent_data_providers)
}}
}
/// Builds a new service for a full client.
pub fn new_full(config: Configuration<GatherConfig, GenesisConfig>)
-> Result<impl AbstractService, ServiceError>
{
let is_authority = config.roles.is_authority();
let force_authoring = config.force_authoring;
let name = config.name.clone();
let disable_grandpa = config.disable_grandpa;
let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);
let (block_import, grandpa_link) =
import_setup.take()
.expect("Link Half and Block Import are present for Full Services or setup failed before. qed");
let service = builder.with_network_protocol(|_| Ok(NodeProtocol::new()))?
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
)?
.build()?;
if is_authority {
let proposer = basic_authorship::ProposerFactory {
client: service.client(),
transaction_pool: service.transaction_pool(),
};
let client = service.client();
let select_chain = service.select_chain()
.ok_or(ServiceError::SelectChainRequired)?;
let aura = aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(
aura::SlotDuration::get_or_compute(&*client)?,
client,
select_chain,
block_import,
proposer,
service.network(),
inherent_data_providers.clone(),
force_authoring,
service.keystore(),
)?;
let select = aura.select(service.on_exit()).then(|_| Ok(()));
// the AURA authoring task is considered essential, i.e. if it
// fails we take down the service with it.
service.spawn_essential_task(select);
}
let grandpa_config = grandpa::Config {
// FIXME #1578 make this available through chainspec
gossip_duration: Duration::from_millis(333),
justification_period: 512,
name: Some(name),
keystore: Some(service.keystore()),
};
match (is_authority, disable_grandpa) {
(false, false) => {
// start the lightweight GRANDPA observer
service.spawn_task(Box::new(grandpa::run_grandpa_observer(
grandpa_config,
grandpa_link,
service.network(),
service.on_exit(),
)?));
},
(true, false) => {
// start the full GRANDPA voter
let voter_config = grandpa::GrandpaParams {
config: grandpa_config,
link: grandpa_link,
network: service.network(),
inherent_data_providers: inherent_data_providers.clone(),
on_exit: service.on_exit(),
telemetry_on_connect: Some(service.telemetry_on_connect_stream()),
voting_rule: grandpa::VotingRulesBuilder::default().build(),
};
// the GRANDPA voter task is considered infallible, i.e.
// if it fails we take down the service with it.
service.spawn_essential_task(grandpa::run_grandpa_voter(voter_config)?);
},
(_, true) => {
grandpa::setup_disabled_grandpa(
service.client(),
&inherent_data_providers,
service.network(),
)?;
},
}
Ok(service)
}
/// Builds a new service for a light client.
pub fn new_light<C: Send + Default + 'static>(config: Configuration<C, GenesisConfig>)
-> Result<impl AbstractService, ServiceError>
{
let inherent_data_providers = InherentDataProviders::new();
ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?
.with_select_chain(|_config, backend| {
Ok(LongestChain::new(backend.clone()))
})?
.with_transaction_pool(|config, client|
Ok(TransactionPool::new(config, transaction_pool::FullChainApi::new(client)))
)?
.with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _tx_pool| {
let fetch_checker = fetcher
.map(|fetcher| fetcher.checker().clone())
.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;
let grandpa_block_import = grandpa::light_block_import::<_, _, _, RuntimeApi, _>(
client.clone(), backend, Arc::new(fetch_checker), client.clone()
)?;
let finality_proof_import = grandpa_block_import.clone();
let finality_proof_request_builder =
finality_proof_import.create_finality_proof_request_builder();
let import_queue = aura::import_queue::<_, _, AuraPair, ()>(
aura::SlotDuration::get_or_compute(&*client)?,
Box::new(grandpa_block_import),
None,
Some(Box::new(finality_proof_import)),
client,
inherent_data_providers.clone(),
None,
)?;
Ok((import_queue, finality_proof_request_builder))
})?
.with_network_protocol(|_| Ok(NodeProtocol::new()))?
.with_finality_proof_provider(|client, backend|
Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
)?
.build()
}