main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{fs::File, io::Write};
  19. use clap::Parser;
  20. use darkfi::{
  21. blockchain::{
  22. block_store::{Block, BlockDifficulty, BlockRanks, BlockStore},
  23. contract_store::ContractStore,
  24. header_store::{Header, HeaderHash, HeaderStore},
  25. tx_store::TxStore,
  26. Blockchain,
  27. },
  28. cli_desc,
  29. tx::Transaction,
  30. util::{path::expand_path, time::Timestamp},
  31. Result,
  32. };
  33. use darkfi_sdk::{
  34. blockchain::block_epoch,
  35. crypto::{ContractId, MerkleTree},
  36. tx::TransactionHash,
  37. };
  38. use num_bigint::BigUint;
  39. #[derive(Parser)]
  40. #[command(about = cli_desc!())]
  41. struct Args {
  42. #[arg(short, long, default_value = "../../../contrib/localnet/darkfid-single-node/")]
  43. /// Path containing the node folders
  44. path: String,
  45. #[arg(short, long, default_values = ["darkfid"])]
  46. /// Node folder name (supports multiple values)
  47. node: Vec<String>,
  48. #[arg(short, long, default_value = "")]
  49. /// Node blockchain folder
  50. blockchain: String,
  51. #[arg(short, long)]
  52. /// Export all contents into a JSON file
  53. export: bool,
  54. }
  55. #[derive(Debug)]
  56. struct HeaderInfo {
  57. _hash: HeaderHash,
  58. _version: u8,
  59. _previous: HeaderHash,
  60. _height: u64,
  61. _timestamp: Timestamp,
  62. _nonce: u64,
  63. _tree: MerkleTree,
  64. }
  65. impl HeaderInfo {
  66. pub fn new(_hash: HeaderHash, header: &Header) -> HeaderInfo {
  67. HeaderInfo {
  68. _hash,
  69. _version: header.version,
  70. _previous: header.previous,
  71. _height: header.height,
  72. _timestamp: header.timestamp,
  73. _nonce: header.nonce,
  74. _tree: header.tree.clone(),
  75. }
  76. }
  77. }
  78. #[derive(Debug)]
  79. struct HeaderStoreInfo {
  80. _headers: Vec<HeaderInfo>,
  81. }
  82. impl HeaderStoreInfo {
  83. pub fn new(headerstore: &HeaderStore) -> HeaderStoreInfo {
  84. let mut _headers = Vec::new();
  85. let result = headerstore.get_all();
  86. match result {
  87. Ok(iter) => {
  88. for (hash, header) in iter.iter() {
  89. _headers.push(HeaderInfo::new(*hash, header));
  90. }
  91. }
  92. Err(e) => println!("Error: {:?}", e),
  93. }
  94. HeaderStoreInfo { _headers }
  95. }
  96. }
  97. #[derive(Debug)]
  98. struct BlockInfo {
  99. _hash: HeaderHash,
  100. _header: HeaderHash,
  101. _txs: Vec<TransactionHash>,
  102. _signature: String,
  103. }
  104. impl BlockInfo {
  105. pub fn new(_hash: HeaderHash, block: &Block) -> BlockInfo {
  106. BlockInfo {
  107. _hash,
  108. _header: block.header,
  109. _txs: block.txs.clone(),
  110. _signature: format!("{:?}", block.signature),
  111. }
  112. }
  113. }
  114. #[derive(Debug)]
  115. struct OrderInfo {
  116. _height: u64,
  117. _hash: HeaderHash,
  118. }
  119. impl OrderInfo {
  120. pub fn new(_height: u64, _hash: HeaderHash) -> OrderInfo {
  121. OrderInfo { _height, _hash }
  122. }
  123. }
  124. #[derive(Debug)]
  125. struct BlockRanksInfo {
  126. _target_rank: BigUint,
  127. _targets_rank: BigUint,
  128. _hash_rank: BigUint,
  129. _hashes_rank: BigUint,
  130. }
  131. impl BlockRanksInfo {
  132. pub fn new(ranks: &BlockRanks) -> BlockRanksInfo {
  133. BlockRanksInfo {
  134. _target_rank: ranks.target_rank.clone(),
  135. _targets_rank: ranks.targets_rank.clone(),
  136. _hash_rank: ranks.hash_rank.clone(),
  137. _hashes_rank: ranks.hashes_rank.clone(),
  138. }
  139. }
  140. }
  141. #[derive(Debug)]
  142. struct BlockDifficultyInfo {
  143. _height: u64,
  144. _timestamp: Timestamp,
  145. _difficulty: BigUint,
  146. _cummulative_difficulty: BigUint,
  147. _ranks: BlockRanksInfo,
  148. }
  149. impl BlockDifficultyInfo {
  150. pub fn new(difficulty: &BlockDifficulty) -> BlockDifficultyInfo {
  151. BlockDifficultyInfo {
  152. _height: difficulty.height,
  153. _timestamp: difficulty.timestamp,
  154. _difficulty: difficulty.difficulty.clone(),
  155. _cummulative_difficulty: difficulty.cummulative_difficulty.clone(),
  156. _ranks: BlockRanksInfo::new(&difficulty.ranks),
  157. }
  158. }
  159. }
  160. #[derive(Debug)]
  161. struct BlockStoreInfo {
  162. _main: Vec<BlockInfo>,
  163. _order: Vec<OrderInfo>,
  164. _difficulty: Vec<BlockDifficultyInfo>,
  165. }
  166. impl BlockStoreInfo {
  167. pub fn new(blockstore: &BlockStore) -> BlockStoreInfo {
  168. let mut _main = Vec::new();
  169. let result = blockstore.get_all();
  170. match result {
  171. Ok(iter) => {
  172. for (hash, block) in iter.iter() {
  173. _main.push(BlockInfo::new(*hash, block));
  174. }
  175. }
  176. Err(e) => println!("Error: {:?}", e),
  177. }
  178. let mut _order = Vec::new();
  179. let result = blockstore.get_all_order();
  180. match result {
  181. Ok(iter) => {
  182. for (height, hash) in iter.iter() {
  183. _order.push(OrderInfo::new(*height, *hash));
  184. }
  185. }
  186. Err(e) => println!("Error: {:?}", e),
  187. }
  188. let mut _difficulty = Vec::new();
  189. let result = blockstore.get_all_difficulty();
  190. match result {
  191. Ok(iter) => {
  192. for (_, difficulty) in iter.iter() {
  193. _difficulty.push(BlockDifficultyInfo::new(difficulty));
  194. }
  195. }
  196. Err(e) => println!("Error: {:?}", e),
  197. }
  198. BlockStoreInfo { _main, _order, _difficulty }
  199. }
  200. }
  201. #[derive(Debug)]
  202. struct TxInfo {
  203. _hash: TransactionHash,
  204. _payload: Transaction,
  205. }
  206. impl TxInfo {
  207. pub fn new(_hash: TransactionHash, tx: &Transaction) -> TxInfo {
  208. TxInfo { _hash, _payload: tx.clone() }
  209. }
  210. }
  211. #[derive(Debug)]
  212. struct TxLocationInfo {
  213. _hash: TransactionHash,
  214. _block_height: u64,
  215. _index: u64,
  216. }
  217. impl TxLocationInfo {
  218. pub fn new(_hash: TransactionHash, _block_height: u64, _index: u64) -> TxLocationInfo {
  219. TxLocationInfo { _hash, _block_height, _index }
  220. }
  221. }
  222. #[derive(Debug)]
  223. struct PendingOrderInfo {
  224. _order: u64,
  225. _hash: TransactionHash,
  226. }
  227. impl PendingOrderInfo {
  228. pub fn new(_order: u64, _hash: TransactionHash) -> PendingOrderInfo {
  229. PendingOrderInfo { _order, _hash }
  230. }
  231. }
  232. #[derive(Debug)]
  233. struct TxStoreInfo {
  234. _main: Vec<TxInfo>,
  235. _location: Vec<TxLocationInfo>,
  236. _pending: Vec<TxInfo>,
  237. _pending_order: Vec<PendingOrderInfo>,
  238. }
  239. impl TxStoreInfo {
  240. pub fn new(txstore: &TxStore) -> TxStoreInfo {
  241. let mut _main = Vec::new();
  242. let result = txstore.get_all();
  243. match result {
  244. Ok(iter) => {
  245. for (hash, tx) in iter.iter() {
  246. _main.push(TxInfo::new(*hash, tx));
  247. }
  248. }
  249. Err(e) => println!("Error: {:?}", e),
  250. }
  251. let mut _location = Vec::new();
  252. let result = txstore.get_all_location();
  253. match result {
  254. Ok(iter) => {
  255. for (hash, location) in iter.iter() {
  256. _location.push(TxLocationInfo::new(*hash, location.0, location.1));
  257. }
  258. }
  259. Err(e) => println!("Error: {:?}", e),
  260. }
  261. let mut _pending = Vec::new();
  262. let result = txstore.get_all_pending();
  263. match result {
  264. Ok(iter) => {
  265. for (hash, tx) in iter.iter() {
  266. _pending.push(TxInfo::new(*hash, tx));
  267. }
  268. }
  269. Err(e) => println!("Error: {:?}", e),
  270. }
  271. let mut _pending_order = Vec::new();
  272. let result = txstore.get_all_pending_order();
  273. match result {
  274. Ok(iter) => {
  275. for (order, hash) in iter.iter() {
  276. _pending_order.push(PendingOrderInfo::new(*order, *hash));
  277. }
  278. }
  279. Err(e) => println!("Error: {:?}", e),
  280. }
  281. TxStoreInfo { _main, _location, _pending, _pending_order }
  282. }
  283. }
  284. #[derive(Debug)]
  285. struct ContractStateInfo {
  286. _id: ContractId,
  287. _state_hashes: Vec<blake3::Hash>,
  288. }
  289. impl ContractStateInfo {
  290. pub fn new(_id: ContractId, state_hashes: &[blake3::Hash]) -> ContractStateInfo {
  291. ContractStateInfo { _id, _state_hashes: state_hashes.to_vec() }
  292. }
  293. }
  294. #[derive(Debug)]
  295. struct WasmInfo {
  296. _id: ContractId,
  297. _bincode_hash: blake3::Hash,
  298. }
  299. impl WasmInfo {
  300. pub fn new(_id: ContractId, bincode: &[u8]) -> WasmInfo {
  301. let _bincode_hash = blake3::hash(bincode);
  302. WasmInfo { _id, _bincode_hash }
  303. }
  304. }
  305. #[derive(Debug)]
  306. struct ContractStoreInfo {
  307. _state: Vec<ContractStateInfo>,
  308. _wasm: Vec<WasmInfo>,
  309. }
  310. impl ContractStoreInfo {
  311. pub fn new(contractsstore: &ContractStore) -> ContractStoreInfo {
  312. let mut _state = Vec::new();
  313. let result = contractsstore.get_all_states();
  314. match result {
  315. Ok(iter) => {
  316. for (id, state_hash) in iter.iter() {
  317. _state.push(ContractStateInfo::new(*id, state_hash));
  318. }
  319. }
  320. Err(e) => println!("Error: {:?}", e),
  321. }
  322. let mut _wasm = Vec::new();
  323. let result = contractsstore.get_all_wasm();
  324. match result {
  325. Ok(iter) => {
  326. for (id, bincode) in iter.iter() {
  327. _wasm.push(WasmInfo::new(*id, bincode));
  328. }
  329. }
  330. Err(e) => println!("Error: {:?}", e),
  331. }
  332. ContractStoreInfo { _state, _wasm }
  333. }
  334. }
  335. #[derive(Debug)]
  336. struct BlockchainInfo {
  337. _headers: HeaderStoreInfo,
  338. _blocks: BlockStoreInfo,
  339. _transactions: TxStoreInfo,
  340. _contracts: ContractStoreInfo,
  341. }
  342. impl BlockchainInfo {
  343. pub fn new(blockchain: &Blockchain) -> BlockchainInfo {
  344. BlockchainInfo {
  345. _headers: HeaderStoreInfo::new(&blockchain.headers),
  346. _blocks: BlockStoreInfo::new(&blockchain.blocks),
  347. _transactions: TxStoreInfo::new(&blockchain.transactions),
  348. _contracts: ContractStoreInfo::new(&blockchain.contracts),
  349. }
  350. }
  351. }
  352. fn statistics(folder: &str, node: &str, blockchain: &str) -> Result<()> {
  353. println!("Retrieving blockchain statistics for {node}...");
  354. // Node folder
  355. let folder = folder.to_owned() + node;
  356. // Initialize or load sled database
  357. let path = folder.to_owned() + blockchain;
  358. let db_path = expand_path(&path).unwrap();
  359. let sled_db = sled::open(db_path)?;
  360. // Retrieve statistics
  361. let blockchain = Blockchain::new(&sled_db)?;
  362. let (height, block) = blockchain.last()?;
  363. let epoch = block_epoch(height);
  364. let blocks = blockchain.len();
  365. let txs = blockchain.txs_len();
  366. drop(sled_db);
  367. // Print statistics
  368. println!("Latest height: {height}");
  369. println!("Epoch: {epoch}");
  370. println!("Latest block: {block}");
  371. println!("Total blocks: {blocks}");
  372. println!("Total transactions: {txs}");
  373. Ok(())
  374. }
  375. fn export(folder: &str, node: &str, blockchain: &str) -> Result<()> {
  376. println!("Exporting data for {node}...");
  377. // Node folder
  378. let folder = folder.to_owned() + node;
  379. // Initialize or load sled database
  380. let path = folder.to_owned() + blockchain;
  381. let db_path = expand_path(&path).unwrap();
  382. let sled_db = sled::open(db_path)?;
  383. // Data export
  384. let blockchain = Blockchain::new(&sled_db)?;
  385. let info = BlockchainInfo::new(&blockchain);
  386. let info_string = format!("{:#?}", info);
  387. let file_name = node.to_owned() + "_db";
  388. let mut file = File::create(file_name.clone())?;
  389. file.write_all(info_string.as_bytes())?;
  390. drop(sled_db);
  391. println!("Data exported to file: {file_name}");
  392. Ok(())
  393. }
  394. fn main() -> Result<()> {
  395. // Parse arguments
  396. let args = Args::parse();
  397. println!("Node folder path: {}", args.path);
  398. // Export data for each node
  399. for node in args.node {
  400. if args.export {
  401. export(&args.path, &node, &args.blockchain)?;
  402. continue
  403. }
  404. statistics(&args.path, &node, &args.blockchain)?;
  405. }
  406. Ok(())
  407. }