1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
18

            
19
#[allow(deprecated)]
20
use {
21
    container_chain_template_simple_runtime::{opaque::Block, RuntimeApi},
22
    cumulus_client_cli::CollatorOptions,
23
    cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport,
24
    cumulus_client_parachain_inherent::{MockValidationDataInherentDataProvider, MockXcmConfig},
25
    cumulus_client_service::{prepare_node_config, ParachainHostFunctions},
26
    cumulus_primitives_core::{
27
        relay_chain::well_known_keys as RelayWellKnownKeys, CollectCollationInfo, ParaId,
28
    },
29
    nimbus_primitives::NimbusId,
30
    node_common::service::{ManualSealConfiguration, NodeBuilder, NodeBuilderConfig, Sealing},
31
    parity_scale_codec::Encode,
32
    polkadot_parachain_primitives::primitives::HeadData,
33
    polkadot_primitives::UpgradeGoAhead,
34
    sc_consensus::BasicQueue,
35
    sc_executor::WasmExecutor,
36
    sc_service::{Configuration, TFullBackend, TFullClient, TaskManager},
37
    sp_api::ProvideRuntimeApi,
38
    sp_blockchain::HeaderBackend,
39
    sp_consensus_slots::{Slot, SlotDuration},
40
    sp_core::{Pair, H256},
41
    std::{sync::Arc, time::Duration},
42
};
43

            
44
type ParachainExecutor = WasmExecutor<ParachainHostFunctions>;
45
type ParachainClient = TFullClient<Block, RuntimeApi, ParachainExecutor>;
46
type ParachainBackend = TFullBackend<Block>;
47
type ParachainBlockImport = TParachainBlockImport<Block, Arc<ParachainClient>, ParachainBackend>;
48

            
49
pub struct NodeConfig;
50
impl NodeBuilderConfig for NodeConfig {
51
    type Block = Block;
52
    type RuntimeApi = RuntimeApi;
53
    type ParachainExecutor = ParachainExecutor;
54
}
55

            
56
thread_local!(static TIMESTAMP: std::cell::RefCell<u64> = const { std::cell::RefCell::new(0) });
57

            
58
/// Provide a mock duration starting at 0 in millisecond for timestamp inherent.
59
/// Each call will increment timestamp by slot_duration making Aura think time has passed.
60
struct MockTimestampInherentDataProvider;
61
#[async_trait::async_trait]
62
impl sp_inherents::InherentDataProvider for MockTimestampInherentDataProvider {
63
    async fn provide_inherent_data(
64
        &self,
65
        inherent_data: &mut sp_inherents::InherentData,
66
538
    ) -> Result<(), sp_inherents::Error> {
67
538
        TIMESTAMP.with(|x| {
68
538
            *x.borrow_mut() += container_chain_template_simple_runtime::SLOT_DURATION;
69
538
            inherent_data.put_data(sp_timestamp::INHERENT_IDENTIFIER, &*x.borrow())
70
538
        })
71
1076
    }
72

            
73
    async fn try_handle_error(
74
        &self,
75
        _identifier: &sp_inherents::InherentIdentifier,
76
        _error: &[u8],
77
    ) -> Option<Result<(), sp_inherents::Error>> {
78
        // The pallet never reports error.
79
        None
80
    }
81
}
82

            
83
66
pub fn import_queue(
84
66
    parachain_config: &Configuration,
85
66
    node_builder: &NodeBuilder<NodeConfig>,
86
66
) -> (ParachainBlockImport, BasicQueue<Block>) {
87
66
    // The nimbus import queue ONLY checks the signature correctness
88
66
    // Any other checks corresponding to the author-correctness should be done
89
66
    // in the runtime
90
66
    let block_import =
91
66
        ParachainBlockImport::new(node_builder.client.clone(), node_builder.backend.clone());
92
66

            
93
66
    let import_queue = nimbus_consensus::import_queue(
94
66
        node_builder.client.clone(),
95
66
        block_import.clone(),
96
66
        move |_, _| async move {
97
            let time = sp_timestamp::InherentDataProvider::from_system_time();
98

            
99
            Ok((time,))
100
66
        },
101
66
        &node_builder.task_manager.spawn_essential_handle(),
102
66
        parachain_config.prometheus_registry(),
103
66
        false,
104
66
        false,
105
66
    )
106
66
    .expect("function never fails");
107
66

            
108
66
    (block_import, import_queue)
109
66
}
110

            
111
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
112
///
113
/// This is the actual implementation that is abstract over the executor and the runtime api.
114
#[sc_tracing::logging::prefix_logs_with("Parachain")]
115
pub async fn start_parachain_node(
116
    parachain_config: Configuration,
117
    polkadot_config: Configuration,
118
    collator_options: CollatorOptions,
119
    para_id: ParaId,
120
    hwbench: Option<sc_sysinfo::HwBench>,
121
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
122
    let parachain_config = prepare_node_config(parachain_config);
123

            
124
    // Create a `NodeBuilder` which helps setup parachain nodes common systems.
125
    let mut node_builder = NodeConfig::new_builder(&parachain_config, hwbench.clone())?;
126

            
127
    let (_, import_queue) = import_queue(&parachain_config, &node_builder);
128

            
129
    // Relay chain interface
130
    let (relay_chain_interface, _collator_key) = node_builder
131
        .build_relay_chain_interface(&parachain_config, polkadot_config, collator_options.clone())
132
        .await?;
133

            
134
    // Build cumulus network, allowing to access network-related services.
135
    let node_builder = node_builder
136
        .build_cumulus_network::<_, sc_network::NetworkWorker<_, _>>(
137
            &parachain_config,
138
            para_id,
139
            import_queue,
140
            relay_chain_interface.clone(),
141
        )
142
        .await?;
143

            
144
    let rpc_builder = {
145
        let client = node_builder.client.clone();
146
        let transaction_pool = node_builder.transaction_pool.clone();
147

            
148
        Box::new(move |_| {
149
            let deps = crate::rpc::FullDeps {
150
                client: client.clone(),
151
                pool: transaction_pool.clone(),
152
                command_sink: None,
153
                xcm_senders: None,
154
            };
155

            
156
            crate::rpc::create_full(deps).map_err(Into::into)
157
        })
158
    };
159

            
160
    let node_builder = node_builder.spawn_common_tasks(parachain_config, rpc_builder)?;
161

            
162
    let relay_chain_slot_duration = Duration::from_secs(6);
163
    let node_builder = node_builder.start_full_node(
164
        para_id,
165
        relay_chain_interface.clone(),
166
        relay_chain_slot_duration,
167
    )?;
168

            
169
    Ok((node_builder.task_manager, node_builder.client))
170
}
171

            
172
/// Helper function to generate a crypto pair from seed
173
66
fn get_aura_id_from_seed(seed: &str) -> NimbusId {
174
66
    sp_core::sr25519::Pair::from_string(&format!("//{}", seed), None)
175
66
        .expect("static values are valid; qed")
176
66
        .public()
177
66
        .into()
178
66
}
179

            
180
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
181
///
182
/// This is the actual implementation that is abstract over the executor and the runtime api.
183
#[sc_tracing::logging::prefix_logs_with("Parachain Dev Node")]
184
pub async fn start_dev_node(
185
    parachain_config: Configuration,
186
    sealing: Sealing,
187
    para_id: ParaId,
188
    hwbench: Option<sc_sysinfo::HwBench>,
189
) -> sc_service::error::Result<TaskManager> {
190
    let parachain_config = prepare_node_config(parachain_config);
191

            
192
    // Create a `NodeBuilder` which helps setup parachain nodes common systems.
193
    let node_builder = NodeConfig::new_builder(&parachain_config, hwbench.clone())?;
194

            
195
    let (parachain_block_import, import_queue) = import_queue(&parachain_config, &node_builder);
196

            
197
    // Build a Substrate Network. (not cumulus since it is a dev node, it mocks
198
    // the relaychain)
199
    let mut node_builder = node_builder
200
        .build_substrate_network::<sc_network::NetworkWorker<_, _>>(
201
            &parachain_config,
202
            import_queue,
203
        )?;
204

            
205
    let mut command_sink = None;
206
    let mut xcm_senders = None;
207

            
208
    if parachain_config.role.is_authority() {
209
        let client = node_builder.client.clone();
210
        let (downward_xcm_sender, downward_xcm_receiver) = flume::bounded::<Vec<u8>>(100);
211
        let (hrmp_xcm_sender, hrmp_xcm_receiver) = flume::bounded::<(ParaId, Vec<u8>)>(100);
212
        xcm_senders = Some((downward_xcm_sender, hrmp_xcm_sender));
213

            
214
        let authorities = vec![get_aura_id_from_seed("alice")];
215

            
216
        command_sink = node_builder.install_manual_seal(ManualSealConfiguration {
217
            block_import: parachain_block_import,
218
            sealing,
219
            soft_deadline: None,
220
            select_chain: sc_consensus::LongestChain::new(node_builder.backend.clone()),
221
            consensus_data_provider: Some(Box::new(
222
                tc_consensus::ContainerManualSealAuraConsensusDataProvider::new(
223
                    SlotDuration::from_millis(
224
                        container_chain_template_simple_runtime::SLOT_DURATION,
225
                    ),
226
                    authorities.clone(),
227
                ),
228
            )),
229
538
            create_inherent_data_providers: move |block: H256, ()| {
230
538
                let current_para_block = client
231
538
                    .number(block)
232
538
                    .expect("Header lookup should succeed")
233
538
                    .expect("Header passed in as parent should be present in backend.");
234
538

            
235
538
                let hash = client
236
538
                    .hash(current_para_block.saturating_sub(1))
237
538
                    .expect("Hash of the desired block must be present")
238
538
                    .expect("Hash of the desired block should exist");
239
538

            
240
538
                let para_header = client
241
538
                    .expect_header(hash)
242
538
                    .expect("Expected parachain header should exist")
243
538
                    .encode();
244
538

            
245
538
                let para_head_data: Vec<u8> = HeadData(para_header).encode();
246
538
                let client_set_aside_for_cidp = client.clone();
247
538
                let client_for_xcm = client.clone();
248
538
                let authorities_for_cidp = authorities.clone();
249
538
                let para_head_key = RelayWellKnownKeys::para_head(para_id);
250
538
                let relay_slot_key = RelayWellKnownKeys::CURRENT_SLOT.to_vec();
251
538
                let slot_duration = container_chain_template_simple_runtime::SLOT_DURATION;
252
538

            
253
538
                let mut timestamp = 0u64;
254
538
                TIMESTAMP.with(|x| {
255
538
                    timestamp = x.clone().take();
256
538
                });
257
538

            
258
538
                timestamp += slot_duration;
259
538

            
260
538
                let relay_slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
261
538
						timestamp.into(),
262
538
						SlotDuration::from_millis(slot_duration),
263
538
                    );
264
538
                let relay_slot = u64::from(*relay_slot);
265
538

            
266
538
                let downward_xcm_receiver = downward_xcm_receiver.clone();
267
538
                let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
268

            
269
538
                async move {
270
538
                    let mocked_authorities_noting =
271
538
                        ccp_authorities_noting_inherent::MockAuthoritiesNotingInherentDataProvider {
272
538
                            current_para_block,
273
538
                            relay_offset: 1000,
274
538
                            relay_blocks_per_para_block: 2,
275
538
                            orchestrator_para_id: crate::chain_spec::ORCHESTRATOR,
276
538
                            container_para_id: para_id,
277
538
                            authorities: authorities_for_cidp
278
538
                    };
279
538

            
280
538
                    let mut additional_keys = mocked_authorities_noting.get_key_values();
281
538
                    additional_keys.append(&mut vec![(para_head_key, para_head_data), (relay_slot_key, Slot::from(relay_slot).encode())]);
282
538

            
283
538
                    let time = MockTimestampInherentDataProvider;
284
538
                    let current_para_head = client_set_aside_for_cidp
285
538
                            .header(block)
286
538
                            .expect("Header lookup should succeed")
287
538
                            .expect("Header passed in as parent should be present in backend.");
288
538
                    let should_send_go_ahead = match client_set_aside_for_cidp
289
538
                            .runtime_api()
290
538
                            .collect_collation_info(block, &current_para_head)
291
                    {
292
538
                            Ok(info) => info.new_validation_code.is_some(),
293
                            Err(e) => {
294
                                    log::error!("Failed to collect collation info: {:?}", e);
295
                                    false
296
                            },
297
                    };
298

            
299
538
                    let mocked_parachain = MockValidationDataInherentDataProvider {
300
538
                        current_para_block,
301
538
                        current_para_block_head: None,
302
538
                        relay_offset: 1000,
303
538
                        relay_blocks_per_para_block: 2,
304
538
                        // TODO: Recheck
305
538
                        para_blocks_per_relay_epoch: 10,
306
538
                        relay_randomness_config: (),
307
538
                        xcm_config: MockXcmConfig::new(
308
538
                            &*client_for_xcm,
309
538
                            block,
310
538
                            Default::default(),
311
538
                        ),
312
538
                        raw_downward_messages: downward_xcm_receiver.drain().collect(),
313
538
                        raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
314
538
                        additional_key_values: Some(additional_keys),
315
538
                        para_id,
316
538
                        upgrade_go_ahead: should_send_go_ahead.then(|| {
317
2
                            log::info!(
318
2
                                "Detected pending validation code, sending go-ahead signal."
319
                            );
320
2
                            UpgradeGoAhead::GoAhead
321
538
                        }),
322
538
                    };
323
538

            
324
538
                    Ok((time, mocked_parachain, mocked_authorities_noting))
325
538
                }
326
538
            },
327
        })?;
328
    }
329

            
330
    let rpc_builder = {
331
        let client = node_builder.client.clone();
332
        let transaction_pool = node_builder.transaction_pool.clone();
333

            
334
132
        Box::new(move |_| {
335
132
            let deps = crate::rpc::FullDeps {
336
132
                client: client.clone(),
337
132
                pool: transaction_pool.clone(),
338
132
                command_sink: command_sink.clone(),
339
132
                xcm_senders: xcm_senders.clone(),
340
132
            };
341
132

            
342
132
            crate::rpc::create_full(deps).map_err(Into::into)
343
132
        })
344
    };
345

            
346
    let node_builder = node_builder.spawn_common_tasks(parachain_config, rpc_builder)?;
347

            
348
    log::info!("Development Service Ready");
349

            
350
    Ok(node_builder.task_manager)
351
}