referrerpolicy=no-referrer-when-downgrade

staging_node_inspect/
lib.rs

1// This file is part of Substrate.
2//
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5//
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! A CLI extension for substrate node, adding sub-command to pretty print debug info
20//! about blocks and extrinsics.
21//!
22//! The blocks and extrinsics can either be retrieved from the database (on-chain),
23//! or a raw SCALE-encoding can be provided.
24
25#![warn(missing_docs)]
26
27pub mod cli;
28pub mod command;
29
30use codec::{Decode, Encode};
31use sc_client_api::BlockBackend;
32use sp_blockchain::HeaderBackend;
33use sp_core::hexdisplay::HexDisplay;
34use sp_runtime::{
35	generic::BlockId,
36	traits::{Block, Hash, HashingFor, NumberFor},
37};
38use std::{fmt, fmt::Debug, marker::PhantomData, str::FromStr};
39
40/// A helper type for a generic block input.
41pub type BlockAddressFor<TBlock> =
42	BlockAddress<<HashingFor<TBlock> as Hash>::Output, NumberFor<TBlock>>;
43
44/// A Pretty formatter implementation.
45pub trait PrettyPrinter<TBlock: Block> {
46	/// Nicely format block.
47	fn fmt_block(&self, fmt: &mut fmt::Formatter, block: &TBlock) -> fmt::Result;
48	/// Nicely format extrinsic.
49	fn fmt_extrinsic(&self, fmt: &mut fmt::Formatter, extrinsic: &TBlock::Extrinsic)
50		-> fmt::Result;
51}
52
53/// Default dummy debug printer.
54#[derive(Default)]
55pub struct DebugPrinter;
56impl<TBlock: Block> PrettyPrinter<TBlock> for DebugPrinter {
57	fn fmt_block(&self, fmt: &mut fmt::Formatter, block: &TBlock) -> fmt::Result {
58		writeln!(fmt, "Header:")?;
59		writeln!(fmt, "{:?}", block.header())?;
60		writeln!(fmt, "Block bytes: {:?}", HexDisplay::from(&block.encode()))?;
61		writeln!(fmt, "Extrinsics ({})", block.extrinsics().len())?;
62		for (idx, ex) in block.extrinsics().iter().enumerate() {
63			writeln!(fmt, "- {}:", idx)?;
64			<DebugPrinter as PrettyPrinter<TBlock>>::fmt_extrinsic(self, fmt, ex)?;
65		}
66		Ok(())
67	}
68
69	fn fmt_extrinsic(
70		&self,
71		fmt: &mut fmt::Formatter,
72		extrinsic: &TBlock::Extrinsic,
73	) -> fmt::Result {
74		writeln!(fmt, " {:#?}", extrinsic)?;
75		writeln!(fmt, " Bytes: {:?}", HexDisplay::from(&extrinsic.encode()))?;
76		Ok(())
77	}
78}
79
80/// Aggregated error for `Inspector` operations.
81#[derive(Debug, thiserror::Error)]
82pub enum Error {
83	/// Could not decode Block or Extrinsic.
84	#[error(transparent)]
85	Codec(#[from] codec::Error),
86	/// Error accessing blockchain DB.
87	#[error(transparent)]
88	Blockchain(#[from] sp_blockchain::Error),
89	/// Given block has not been found.
90	#[error("{0}")]
91	NotFound(String),
92}
93
94/// A helper trait to access block headers and bodies.
95pub trait ChainAccess<TBlock: Block>: HeaderBackend<TBlock> + BlockBackend<TBlock> {}
96
97impl<T, TBlock> ChainAccess<TBlock> for T
98where
99	TBlock: Block,
100	T: sp_blockchain::HeaderBackend<TBlock> + sc_client_api::BlockBackend<TBlock>,
101{
102}
103
104/// Blockchain inspector.
105pub struct Inspector<TBlock: Block, TPrinter: PrettyPrinter<TBlock> = DebugPrinter> {
106	printer: TPrinter,
107	chain: Box<dyn ChainAccess<TBlock>>,
108	_block: PhantomData<TBlock>,
109}
110
111impl<TBlock: Block, TPrinter: PrettyPrinter<TBlock>> Inspector<TBlock, TPrinter> {
112	/// Create new instance of the inspector with default printer.
113	pub fn new(chain: impl ChainAccess<TBlock> + 'static) -> Self
114	where
115		TPrinter: Default,
116	{
117		Self::with_printer(chain, Default::default())
118	}
119
120	/// Customize pretty-printing of the data.
121	pub fn with_printer(chain: impl ChainAccess<TBlock> + 'static, printer: TPrinter) -> Self {
122		Inspector { chain: Box::new(chain) as _, printer, _block: Default::default() }
123	}
124
125	/// Get a pretty-printed block.
126	pub fn block(&self, input: BlockAddressFor<TBlock>) -> Result<String, Error> {
127		struct BlockPrinter<'a, A, B>(A, &'a B);
128		impl<'a, A: Block, B: PrettyPrinter<A>> fmt::Display for BlockPrinter<'a, A, B> {
129			fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
130				self.1.fmt_block(fmt, &self.0)
131			}
132		}
133
134		let block = self.get_block(input)?;
135		Ok(format!("{}", BlockPrinter(block, &self.printer)))
136	}
137
138	fn get_block(&self, input: BlockAddressFor<TBlock>) -> Result<TBlock, Error> {
139		Ok(match input {
140			BlockAddress::Bytes(bytes) => TBlock::decode(&mut &*bytes)?,
141			BlockAddress::Number(number) => {
142				let id = BlockId::number(number);
143				let hash = self.chain.expect_block_hash_from_id(&id)?;
144				let not_found = format!("Could not find block {:?}", id);
145				let body = self
146					.chain
147					.block_body(hash)?
148					.ok_or_else(|| Error::NotFound(not_found.clone()))?;
149				let header =
150					self.chain.header(hash)?.ok_or_else(|| Error::NotFound(not_found.clone()))?;
151				TBlock::new(header, body)
152			},
153			BlockAddress::Hash(hash) => {
154				let not_found = format!("Could not find block {:?}", BlockId::<TBlock>::Hash(hash));
155				let body = self
156					.chain
157					.block_body(hash)?
158					.ok_or_else(|| Error::NotFound(not_found.clone()))?;
159				let header =
160					self.chain.header(hash)?.ok_or_else(|| Error::NotFound(not_found.clone()))?;
161				TBlock::new(header, body)
162			},
163		})
164	}
165
166	/// Get a pretty-printed extrinsic.
167	pub fn extrinsic(
168		&self,
169		input: ExtrinsicAddress<<HashingFor<TBlock> as Hash>::Output, NumberFor<TBlock>>,
170	) -> Result<String, Error> {
171		struct ExtrinsicPrinter<'a, A: Block, B>(A::Extrinsic, &'a B);
172		impl<'a, A: Block, B: PrettyPrinter<A>> fmt::Display for ExtrinsicPrinter<'a, A, B> {
173			fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
174				self.1.fmt_extrinsic(fmt, &self.0)
175			}
176		}
177
178		let ext = match input {
179			ExtrinsicAddress::Block(block, index) => {
180				let block = self.get_block(block)?;
181				block.extrinsics().get(index).cloned().ok_or_else(|| {
182					Error::NotFound(format!(
183						"Could not find extrinsic {} in block {:?}",
184						index, block
185					))
186				})?
187			},
188			ExtrinsicAddress::Bytes(bytes) => TBlock::Extrinsic::decode(&mut &*bytes)?,
189		};
190
191		Ok(format!("{}", ExtrinsicPrinter(ext, &self.printer)))
192	}
193}
194
195/// A block to retrieve.
196#[derive(Debug, Clone, PartialEq)]
197pub enum BlockAddress<Hash, Number> {
198	/// Get block by hash.
199	Hash(Hash),
200	/// Get block by number.
201	Number(Number),
202	/// Raw SCALE-encoded bytes.
203	Bytes(Vec<u8>),
204}
205
206impl<Hash: FromStr, Number: FromStr> FromStr for BlockAddress<Hash, Number> {
207	type Err = String;
208
209	fn from_str(s: &str) -> Result<Self, Self::Err> {
210		// try to parse hash first
211		if let Ok(hash) = s.parse() {
212			return Ok(Self::Hash(hash))
213		}
214
215		// then number
216		if let Ok(number) = s.parse() {
217			return Ok(Self::Number(number))
218		}
219
220		// then assume it's bytes (hex-encoded)
221		sp_core::bytes::from_hex(s).map(Self::Bytes).map_err(|e| {
222			format!(
223				"Given string does not look like hash or number. It could not be parsed as bytes either: {}",
224				e
225			)
226		})
227	}
228}
229
230/// An extrinsic address to decode and print out.
231#[derive(Debug, Clone, PartialEq)]
232pub enum ExtrinsicAddress<Hash, Number> {
233	/// Extrinsic as part of existing block.
234	Block(BlockAddress<Hash, Number>, usize),
235	/// Raw SCALE-encoded extrinsic bytes.
236	Bytes(Vec<u8>),
237}
238
239impl<Hash: FromStr + Debug, Number: FromStr + Debug> FromStr for ExtrinsicAddress<Hash, Number> {
240	type Err = String;
241
242	fn from_str(s: &str) -> Result<Self, Self::Err> {
243		// first try raw bytes
244		if let Ok(bytes) = sp_core::bytes::from_hex(s).map(Self::Bytes) {
245			return Ok(bytes)
246		}
247
248		// split by a bunch of different characters
249		let mut it = s.split(|c| c == '.' || c == ':' || c == ' ');
250		let block = it
251			.next()
252			.expect("First element of split iterator is never empty; qed")
253			.parse()?;
254
255		let index = it
256			.next()
257			.ok_or("Extrinsic index missing: example \"5:0\"")?
258			.parse()
259			.map_err(|e| format!("Invalid index format: {}", e))?;
260
261		Ok(Self::Block(block, index))
262	}
263}
264
265#[cfg(test)]
266mod tests {
267	use super::*;
268	use sp_core::hash::H160 as Hash;
269
270	#[test]
271	fn should_parse_block_strings() {
272		type BlockAddress = super::BlockAddress<Hash, u64>;
273
274		let b0 = BlockAddress::from_str("3BfC20f0B9aFcAcE800D73D2191166FF16540258");
275		let b1 = BlockAddress::from_str("1234");
276		let b2 = BlockAddress::from_str("0");
277		let b3 = BlockAddress::from_str("0x0012345f");
278
279		assert_eq!(
280			b0,
281			Ok(BlockAddress::Hash("3BfC20f0B9aFcAcE800D73D2191166FF16540258".parse().unwrap()))
282		);
283		assert_eq!(b1, Ok(BlockAddress::Number(1234)));
284		assert_eq!(b2, Ok(BlockAddress::Number(0)));
285		assert_eq!(b3, Ok(BlockAddress::Bytes(vec![0, 0x12, 0x34, 0x5f])));
286	}
287
288	#[test]
289	fn should_parse_extrinsic_address() {
290		type BlockAddress = super::BlockAddress<Hash, u64>;
291		type ExtrinsicAddress = super::ExtrinsicAddress<Hash, u64>;
292
293		let e0 = ExtrinsicAddress::from_str("1234");
294		let b0 = ExtrinsicAddress::from_str("3BfC20f0B9aFcAcE800D73D2191166FF16540258:5");
295		let b1 = ExtrinsicAddress::from_str("1234:0");
296		let b2 = ExtrinsicAddress::from_str("0 0");
297		let b3 = ExtrinsicAddress::from_str("0x0012345f");
298
299		assert_eq!(e0, Ok(ExtrinsicAddress::Bytes(vec![0x12, 0x34])));
300		assert_eq!(
301			b0,
302			Ok(ExtrinsicAddress::Block(
303				BlockAddress::Hash("3BfC20f0B9aFcAcE800D73D2191166FF16540258".parse().unwrap()),
304				5
305			))
306		);
307		assert_eq!(b1, Ok(ExtrinsicAddress::Block(BlockAddress::Number(1234), 0)));
308		assert_eq!(b2, Ok(ExtrinsicAddress::Bytes(vec![0, 0])));
309		assert_eq!(b3, Ok(ExtrinsicAddress::Bytes(vec![0, 0x12, 0x34, 0x5f])));
310	}
311}