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
    node_builder.network.start_network.start_network();
170

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
260
538
                timestamp += slot_duration;
261
538

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

            
268
538
                let downward_xcm_receiver = downward_xcm_receiver.clone();
269
538
                let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
270

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

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

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

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

            
326
538
                    Ok((time, mocked_parachain, mocked_authorities_noting))
327
538
                }
328
538
            },
329
        })?;
330
    }
331

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

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

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

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

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

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

            
354
    Ok(node_builder.task_manager)
355
}