Skip to main content

soil_cli/commands/
chain_info_cmd.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7use crate::{CliConfiguration, DatabaseParams, PruningParams, Result as CliResult, SharedParams};
8use codec::{Decode, Encode};
9use soil_client::blockchain::Info;
10use soil_client::client_api::{backend::Backend as BackendT, blockchain::HeaderBackend};
11use std::{fmt::Debug, io};
12use subsoil::runtime::traits::{Block as BlockT, Header as HeaderT};
13
14/// The `chain-info` subcommand used to output db meta columns information.
15#[derive(Debug, Clone, clap::Parser)]
16pub struct ChainInfoCmd {
17	#[allow(missing_docs)]
18	#[clap(flatten)]
19	pub pruning_params: PruningParams,
20
21	#[allow(missing_docs)]
22	#[clap(flatten)]
23	pub shared_params: SharedParams,
24
25	#[allow(missing_docs)]
26	#[clap(flatten)]
27	pub database_params: DatabaseParams,
28}
29
30/// Serializable `chain-info` subcommand output.
31#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, serde::Serialize)]
32struct ChainInfo<B: BlockT> {
33	/// Best block hash.
34	best_hash: B::Hash,
35	/// Best block number.
36	best_number: <<B as BlockT>::Header as HeaderT>::Number,
37	/// Genesis block hash.
38	genesis_hash: B::Hash,
39	/// The head of the finalized chain.
40	finalized_hash: B::Hash,
41	/// Last finalized block number.
42	finalized_number: <<B as BlockT>::Header as HeaderT>::Number,
43}
44
45impl<B: BlockT> From<Info<B>> for ChainInfo<B> {
46	fn from(info: Info<B>) -> Self {
47		ChainInfo::<B> {
48			best_hash: info.best_hash,
49			best_number: info.best_number,
50			genesis_hash: info.genesis_hash,
51			finalized_hash: info.finalized_hash,
52			finalized_number: info.finalized_number,
53		}
54	}
55}
56
57impl ChainInfoCmd {
58	/// Run the `chain-info` subcommand
59	pub fn run<B>(&self, config: &soil_service::Configuration) -> CliResult<()>
60	where
61		B: BlockT,
62	{
63		let db_config = soil_client::db::DatabaseSettings {
64			trie_cache_maximum_size: config.trie_cache_maximum_size,
65			state_pruning: config.state_pruning.clone(),
66			source: config.database.clone(),
67			blocks_pruning: config.blocks_pruning,
68			pruning_filters: Default::default(),
69			metrics_registry: None,
70		};
71		let backend = soil_service::new_db_backend::<B>(db_config)?;
72		let info: ChainInfo<B> = backend.blockchain().info().into();
73		let mut out = io::stdout();
74		serde_json::to_writer_pretty(&mut out, &info)
75			.map_err(|e| format!("Error writing JSON: {}", e))?;
76		Ok(())
77	}
78}
79
80impl CliConfiguration for ChainInfoCmd {
81	fn shared_params(&self) -> &SharedParams {
82		&self.shared_params
83	}
84
85	fn pruning_params(&self) -> Option<&PruningParams> {
86		Some(&self.pruning_params)
87	}
88
89	fn database_params(&self) -> Option<&DatabaseParams> {
90		Some(&self.database_params)
91	}
92}