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
273
pub mod subcoin_params;

use crate::commands::blockchain::{Blockchain, BlockchainCmd};
use crate::commands::import_blocks::{ImportBlocks, ImportBlocksCmd};
use crate::commands::run::{Run, RunCmd};
use crate::commands::tools::Tools;
use crate::substrate_cli::SubstrateCli;
use clap::Parser;
#[cfg(feature = "benchmark")]
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use sc_cli::SubstrateCli as SubstrateCliT;
use sc_client_api::UsageProvider;
use sc_consensus_nakamoto::ImportConfig;
use sc_service::PartialComponents;
use std::sync::Arc;
use subcoin_primitives::CONFIRMATION_DEPTH;

#[derive(Debug, clap::Subcommand)]
pub enum Command {
    /// Run subcoin node.
    Run(Box<Run>),

    /// Import blocks from bitcoind database.
    ImportBlocks(ImportBlocks),

    /// Utility tools.
    #[command(subcommand)]
    Tools(Tools),

    /// Blockchain.
    #[command(subcommand)]
    Blockchain(Blockchain),

    /// Build a chain specification.
    BuildSpec(sc_cli::BuildSpecCmd),

    /// Validate blocks.
    CheckBlock(Box<sc_cli::CheckBlockCmd>),

    /// Export blocks.
    ExportBlocks(sc_cli::ExportBlocksCmd),

    /// Export the state of a given block into a chain spec.
    ExportState(sc_cli::ExportStateCmd),

    /// Remove the whole chain.
    PurgeChain(sc_cli::PurgeChainCmd),

    /// Revert the chain to a previous state.
    Revert(sc_cli::RevertCmd),

    /// Sub-commands concerned with benchmarking.
    #[cfg(feature = "benchmark")]
    #[command(subcommand)]
    Benchmark(Box<frame_benchmarking_cli::BenchmarkCmd>),

    /// Db meta columns information.
    ChainInfo(sc_cli::ChainInfoCmd),
}

/// Subcoin Client Node
#[derive(Debug, Parser)]
#[clap(version = env!("SUBSTRATE_CLI_IMPL_VERSION"))]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,

    #[allow(missing_docs)]
    #[clap(flatten)]
    pub storage_monitor: sc_storage_monitor::StorageMonitorParams,
}

/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
    let Cli {
        command,
        storage_monitor,
    } = Cli::parse();

    match command {
        Command::Run(run) => {
            let run_cmd = RunCmd::new(*run);
            let runner = SubstrateCli.create_runner(&run_cmd)?;
            runner.run_node_until_exit(|config| async move {
                run_cmd.start(config, storage_monitor).await
            })
        }
        Command::ImportBlocks(cmd) => {
            let bitcoin_network = cmd.common_params.bitcoin_network();
            let import_config = ImportConfig {
                execute_block: cmd.execute_transactions,
                ..cmd.common_params.import_config()
            };
            let chain_spec_id = cmd.common_params.chain.chain_spec_id();
            let maybe_prometheus_config = cmd
                .prometheus_params
                .prometheus_config(9615, chain_spec_id.to_string());
            let import_blocks_cmd = ImportBlocksCmd::new(&cmd);
            let runner = SubstrateCli.create_runner(&import_blocks_cmd)?;
            let data_dir = cmd.data_dir;
            runner.async_run(|config| {
                let subcoin_service::NodeComponents {
                    client,
                    task_manager,
                    ..
                } = subcoin_service::new_node(subcoin_service::SubcoinConfiguration {
                    network: bitcoin_network,
                    config: &config,
                    no_hardware_benchmarks: true,
                    storage_monitor,
                })?;
                let spawn_handle = task_manager.spawn_handle();
                spawn_handle.spawn("finalizer", None, {
                    let client = client.clone();
                    let spawn_handle = task_manager.spawn_handle();
                    subcoin_service::SubcoinFinalizer::new(
                        client,
                        spawn_handle,
                        CONFIRMATION_DEPTH,
                        Arc::new(subcoin_network::OfflineSync),
                        None,
                    )
                    .run()
                });
                Ok((
                    import_blocks_cmd.run(
                        client,
                        data_dir,
                        import_config,
                        spawn_handle,
                        maybe_prometheus_config,
                    ),
                    task_manager,
                ))
            })
        }
        Command::Tools(tools) => tools.run(),
        Command::Blockchain(blockchain) => {
            let cmd = BlockchainCmd::new(blockchain);
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.async_run(|config| {
                let subcoin_service::NodeComponents {
                    client,
                    task_manager,
                    ..
                } = subcoin_service::new_node(subcoin_service::SubcoinConfiguration {
                    network: bitcoin::Network::Bitcoin,
                    config: &config,
                    no_hardware_benchmarks: true,
                    storage_monitor,
                })?;
                Ok((cmd.run(client), task_manager))
            })
        }
        Command::BuildSpec(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
        }
        Command::CheckBlock(cmd) => {
            let runner = SubstrateCli.create_runner(&*cmd)?;
            runner.async_run(|config| {
                let PartialComponents {
                    client,
                    task_manager,
                    import_queue,
                    ..
                } = subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;
                Ok((cmd.run(client, import_queue), task_manager))
            })
        }
        Command::ExportBlocks(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.async_run(|config| {
                let PartialComponents {
                    client,
                    task_manager,
                    ..
                } = subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;
                Ok((cmd.run(client, config.database), task_manager))
            })
        }
        Command::ExportState(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.async_run(|config| {
                let PartialComponents {
                    client,
                    task_manager,
                    ..
                } = subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;

                let run_cmd = async move {
                    tracing::info!("Exporting raw state...");
                    // let block_id = cmd.input.as_ref().map(|b| b.parse()).transpose()?;
                    // let hash = match block_id {
                    // Some(id) => client.expect_block_hash_from_id(&id)?,
                    // None => client.usage_info().chain.best_hash,
                    let hash = client.usage_info().chain.best_hash;
                    // };
                    let _raw_state = sc_service::chain_ops::export_raw_state(client, hash).unwrap();

                    tracing::info!("Raw state exported successfully");

                    Ok(())
                };

                Ok((run_cmd, task_manager))
            })
        }
        Command::PurgeChain(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.sync_run(|config| cmd.run(config.database))
        }
        Command::Revert(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.async_run(|config| {
                let PartialComponents {
                    client,
                    task_manager,
                    backend,
                    ..
                } = subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;
                Ok((cmd.run(client, backend, None), task_manager))
            })
        }
        #[cfg(feature = "benchmark")]
        Command::Benchmark(cmd) => {
            let runner = SubstrateCli.create_runner(&*cmd)?;

            runner.sync_run(|config| {
                // This switch needs to be in the client, since the client decides
                // which sub-commands it wants to support.
                match *cmd {
                    BenchmarkCmd::Pallet(_cmd) => {
                        unimplemented!("")
                    }
                    BenchmarkCmd::Block(cmd) => {
                        let PartialComponents { client, .. } =
                            subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;
                        cmd.run(client)
                    }
                    #[cfg(not(feature = "runtime-benchmarks"))]
                    BenchmarkCmd::Storage(_) => Err(
                        "Storage benchmarking can be enabled with `--features runtime-benchmarks`."
                            .into(),
                    ),
                    #[cfg(feature = "runtime-benchmarks")]
                    BenchmarkCmd::Storage(cmd) => {
                        let PartialComponents {
                            client, backend, ..
                        } = subcoin_service::new_partial(&config, bitcoin::Network::Bitcoin)?;
                        let db = backend.expose_db();
                        let storage = backend.expose_storage();

                        cmd.run(config, client, db, storage)
                    }
                    BenchmarkCmd::Overhead(_cmd) => {
                        unimplemented!("")
                    }
                    BenchmarkCmd::Extrinsic(_cmd) => {
                        unimplemented!("")
                    }
                    BenchmarkCmd::Machine(cmd) => {
                        cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())
                    }
                }
            })
        }
        Command::ChainInfo(cmd) => {
            let runner = SubstrateCli.create_runner(&cmd)?;
            runner.sync_run(|config| cmd.run::<subcoin_runtime::interface::OpaqueBlock>(&config))
        }
    }
}