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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// This file is part of Substrate.

// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::cli::{Cli, Subcommand};
use crate::service;
use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;

fn set_default_ss58_version() {
    sp_core::crypto::set_default_ss58_version(sp_core::crypto::Ss58AddressFormat::from(
        framenode_runtime::SS58Prefix::get() as u16,
    ));
}

impl SubstrateCli for Cli {
    fn impl_name() -> String {
        "SORA".into()
    }

    fn impl_version() -> String {
        env!("SUBSTRATE_CLI_IMPL_VERSION").into()
    }

    fn description() -> String {
        env!("CARGO_PKG_DESCRIPTION").into()
    }

    fn author() -> String {
        env!("CARGO_PKG_AUTHORS").into()
    }

    fn support_url() -> String {
        "https://github.com/sora-xor/sora2-network/issues/new".into()
    }

    fn copyright_start_year() -> i32 {
        2017
    }

    fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
        #[cfg(feature = "private-net")]
        let chain_spec = match id {
            "" | "local" => Some(framenode_chain_spec::local_testnet_config(3, 3)),
            "docker-local" => Some(framenode_chain_spec::local_testnet_config(1, 1)),
            // dev doesn't use json chain spec to make development easier
            // "dev" => framenode_chain_spec::dev_net(),
            // "dev-coded" => Ok(framenode_chain_spec::dev_net_coded()),
            "dev" => Some(framenode_chain_spec::dev_net_coded()),
            "test" => Some(framenode_chain_spec::test_net()?),
            "test-coded" => Some(framenode_chain_spec::staging_net_coded(true)),
            "staging" => Some(framenode_chain_spec::staging_net()?),
            "staging-coded" => Some(framenode_chain_spec::staging_net_coded(false)),
            "bridge-staging" => Some(framenode_chain_spec::bridge_staging_net()?),
            "bridge-staging-coded" => Some(framenode_chain_spec::bridge_staging_net_coded()),
            "bridge-dev" => Some(framenode_chain_spec::bridge_dev_net_coded()),
            _ => None,
        };

        #[cfg(not(feature = "private-net"))]
        let mut chain_spec = None;

        #[cfg(not(feature = "private-net"))]
        if id == "main" {
            chain_spec = Some(framenode_chain_spec::main_net()?);
        }

        #[cfg(feature = "main-net-coded")]
        if id == "main-coded" {
            chain_spec = Some(framenode_chain_spec::main_net_coded());
        }

        let chain_spec = if let Some(chain_spec) = chain_spec {
            chain_spec
        } else {
            framenode_chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(id))?
        };

        Ok(Box::new(chain_spec))
    }

    fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
        &framenode_runtime::VERSION
    }
}

/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
    let cli = Cli::from_args();

    match &cli.subcommand {
        Some(Subcommand::Key(cmd)) => cmd.run(&cli),
        Some(Subcommand::BuildSpec(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
        }
        Some(Subcommand::CheckBlock(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.async_run(|mut config| {
                let PartialComponents {
                    client,
                    task_manager,
                    import_queue,
                    ..
                } = service::new_partial(&mut config, None)?;
                Ok((cmd.run(client, import_queue), task_manager))
            })
        }
        Some(Subcommand::ExportBlocks(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.async_run(|mut config| {
                let PartialComponents {
                    client,
                    task_manager,
                    ..
                } = service::new_partial(&mut config, None)?;
                Ok((cmd.run(client, config.database), task_manager))
            })
        }
        Some(Subcommand::ExportState(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.async_run(|mut config| {
                let PartialComponents {
                    client,
                    task_manager,
                    ..
                } = service::new_partial(&mut config, None)?;
                Ok((cmd.run(client, config.chain_spec), task_manager))
            })
        }
        Some(Subcommand::ImportBlocks(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.async_run(|mut config| {
                let PartialComponents {
                    client,
                    task_manager,
                    import_queue,
                    ..
                } = service::new_partial(&mut config, None)?;
                Ok((cmd.run(client, import_queue), task_manager))
            })
        }
        Some(Subcommand::PurgeChain(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.sync_run(|config| cmd.run(config.database))
        }
        Some(Subcommand::Revert(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            runner.async_run(|mut config| {
                let PartialComponents {
                    client,
                    task_manager,
                    backend,
                    ..
                } = service::new_partial(&mut config, None)?;
                Ok((cmd.run(client, backend, None), task_manager))
            })
        }
        #[cfg(feature = "runtime-benchmarks")]
        Some(Subcommand::Benchmark(cmd)) => {
            use frame_benchmarking_cli::BenchmarkCmd;
            use sc_chain_spec::ChainType;
            use sc_service::Error;
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();
            let chain_spec = &runner.config().chain_spec;

            match cmd {
                BenchmarkCmd::Storage(cmd) => runner.sync_run(|mut config| {
                    let PartialComponents {
                        client, backend, ..
                    } = service::new_partial(&mut config, None)?;
                    let db = backend.expose_db();
                    let storage = backend.expose_storage();
                    cmd.run(config, client, db, storage)
                }),
                BenchmarkCmd::Block(cmd) => runner.sync_run(|mut config| {
                    let PartialComponents { client, .. } = service::new_partial(&mut config, None)?;

                    cmd.run(client)
                }),
                BenchmarkCmd::Pallet(cmd) => {
                    if !matches!(chain_spec.chain_type(), ChainType::Development) {
                        return Err(Error::Other("Available only for dev chain".into()).into());
                    }

                    runner.sync_run(|config| {
                        cmd.run::<framenode_runtime::Block, service::ExecutorDispatch>(config)
                    })
                }
                #[allow(unreachable_patterns)]
                _ => Err(Error::Other("Command not implemented".into()).into()),
            }
        }
        #[cfg(feature = "try-runtime")]
        Some(Subcommand::TryRuntime(cmd)) => {
            use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
            type HostFunctionsOf<E> = ExtendedHostFunctions<
                sp_io::SubstrateHostFunctions,
                <E as NativeExecutionDispatch>::ExtendHostFunctions,
            >;
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();

            use sc_service::TaskManager;
            let registry = &runner
                .config()
                .prometheus_config
                .as_ref()
                .map(|cfg| &cfg.registry);
            let task_manager = TaskManager::new(runner.config().tokio_handle.clone(), *registry)
                .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?;

            runner.async_run(|_config| {
                Ok((
                    cmd.run::<framenode_runtime::Block, HostFunctionsOf<service::ExecutorDispatch>>(),
                    task_manager,
                ))
            })
        }
        #[cfg(feature = "private-net")]
        Some(Subcommand::ForkOff(cmd)) => {
            let runner = cli.create_runner(cmd)?;
            set_default_ss58_version();

            use sc_service::TaskManager;
            let registry = &runner
                .config()
                .prometheus_config
                .as_ref()
                .map(|cfg| &cfg.registry);
            let task_manager = TaskManager::new(runner.config().tokio_handle.clone(), *registry)
                .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?;

            runner.async_run(|config| Ok((cmd.run(config), task_manager)))
        }
        None => {
            let runner = cli.create_runner(&cli.run)?;
            set_default_ss58_version();
            runner.run_node_until_exit(|config| async move {
                #[cfg(feature = "wip")] // Bridges
                return service::new_full(config, cli.disable_beefy, None)
                    .map_err(sc_cli::Error::Service);
                // Disable BEEFY on production.
                // BEEFY is still work in progress and probably will contain breaking changes, so it's better to enable it when it's ready
                // Also before enabling it we need to ensure that validators updated their session keys
                #[cfg(not(feature = "wip"))] // Bridges
                service::new_full(config, true, None).map_err(sc_cli::Error::Service)
            })
        }
    }
}