statistics.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 tinyjson::JsonValue;
  19. use darkfi::{Error, Result};
  20. use darkfi_sdk::blockchain::block_epoch;
  21. use crate::ExplorerDb;
  22. #[derive(Debug, Clone)]
  23. /// Structure representing basic statistic extracted from the database.
  24. pub struct BaseStatistics {
  25. /// Current blockchain height
  26. pub height: u32,
  27. /// Current blockchain epoch (based on current height)
  28. pub epoch: u8,
  29. /// Blockchains' last block hash
  30. pub last_block: String,
  31. /// Blockchain total blocks
  32. pub total_blocks: usize,
  33. /// Blockchain total transactions
  34. pub total_txs: usize,
  35. }
  36. impl BaseStatistics {
  37. /// Auxiliary function to convert `BaseStatistics` into a `JsonValue` array.
  38. pub fn to_json_array(&self) -> JsonValue {
  39. JsonValue::Array(vec![
  40. JsonValue::Number(self.height as f64),
  41. JsonValue::Number(self.epoch as f64),
  42. JsonValue::String(self.last_block.clone()),
  43. JsonValue::Number(self.total_blocks as f64),
  44. JsonValue::Number(self.total_txs as f64),
  45. ])
  46. }
  47. }
  48. impl ExplorerDb {
  49. /// Fetch current database basic statistics.
  50. pub fn get_base_statistics(&self) -> Result<Option<BaseStatistics>> {
  51. let last_block = self.last_block();
  52. Ok(last_block
  53. // Throw database error if last_block retrievals fails
  54. .map_err(|e| {
  55. Error::DatabaseError(format!(
  56. "[get_base_statistics] Retrieving last block failed: {:?}",
  57. e
  58. ))
  59. })?
  60. // Calculate base statistics and return result
  61. .map(|(height, header_hash)| {
  62. let epoch = block_epoch(height);
  63. let total_blocks = self.get_block_count();
  64. let total_txs = self.get_transaction_count();
  65. BaseStatistics { height, epoch, last_block: header_hash, total_blocks, total_txs }
  66. }))
  67. }
  68. }