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
528
    ) -> Result<(), sp_inherents::Error> {
67
528
        TIMESTAMP.with(|x| {
68
528
            *x.borrow_mut() += container_chain_template_simple_runtime::SLOT_DURATION;
69
528
            inherent_data.put_data(sp_timestamp::INHERENT_IDENTIFIER, &*x.borrow())
70
528
        })
71
1056
    }
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
64
pub fn import_queue(
84
64
    parachain_config: &Configuration,
85
64
    node_builder: &NodeBuilder<NodeConfig>,
86
64
) -> (ParachainBlockImport, BasicQueue<Block>) {
87
64
    // The nimbus import queue ONLY checks the signature correctness
88
64
    // Any other checks corresponding to the author-correctness should be done
89
64
    // in the runtime
90
64
    let block_import =
91
64
        ParachainBlockImport::new(node_builder.client.clone(), node_builder.backend.clone());
92
64

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

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

            
107
64
    (block_import, import_queue)
108
64
}
109

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

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

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

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

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

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

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

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

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

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

            
168
    node_builder.network.start_network.start_network();
169

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
259
528
                timestamp += slot_duration;
260
528

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

            
267
528
                let downward_xcm_receiver = downward_xcm_receiver.clone();
268
528
                let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
269

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

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

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

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

            
325
528
                    Ok((time, mocked_parachain, mocked_authorities_noting))
326
528
                }
327
528
            },
328
        })?;
329
    }
330

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

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

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

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

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

            
351
    node_builder.network.start_network.start_network();
352

            
353
    Ok(node_builder.task_manager)
354
}