config.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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::{
  19. fmt,
  20. path::{Path, PathBuf},
  21. str::FromStr,
  22. };
  23. use serde::Deserialize;
  24. use structopt::StructOpt;
  25. use tracing::{debug, error};
  26. use url::Url;
  27. use darkfi::{rpc::settings::RpcSettingsOpt, util::file::load_file, Error, Result};
  28. /// Represents an explorer configuration
  29. #[derive(Clone, Debug, Deserialize, StructOpt)]
  30. pub struct ExplorerConfig {
  31. /// Current active network
  32. #[allow(dead_code)] // Part of the config file
  33. pub network: String,
  34. /// Supported network configurations
  35. pub network_config: NetworkConfigs,
  36. /// Path to the configuration if read from a file
  37. pub path: Option<String>,
  38. }
  39. impl ExplorerConfig {
  40. /// Creates a new configuration from a given file path.
  41. /// If the file cannot be loaded or parsed, an error is returned.
  42. pub fn new(config_path: String) -> Result<Self> {
  43. // Load the configuration file from the specified path
  44. let config_content = load_file(Path::new(&config_path)).map_err(|err| {
  45. Error::ConfigError(format!(
  46. "Failed to read the configuration file {config_path}: {err:?}"
  47. ))
  48. })?;
  49. // Parse the loaded content into a configuration instance
  50. let mut config = toml::from_str::<Self>(&config_content).map_err(|e| {
  51. error!(target: "explorerd::config", "Failed parsing TOML config: {e}");
  52. Error::ConfigError(format!("Failed to parse the configuration file {config_path}"))
  53. })?;
  54. // Set the configuration path
  55. config.path = Some(config_path);
  56. debug!(target: "explorerd::config", "Successfully loaded configuration: {config:?}");
  57. Ok(config)
  58. }
  59. /// Returns the currently active network configuration.
  60. #[allow(dead_code)] // Test case currently using
  61. pub fn active_network_config(&self) -> Option<ExplorerNetworkConfig> {
  62. self.get_network_config(self.network.as_str())
  63. }
  64. /// Returns the network configuration for specified network.
  65. pub fn get_network_config(&self, network: &str) -> Option<ExplorerNetworkConfig> {
  66. match network {
  67. "localnet" => self.network_config.localnet.clone(),
  68. "testnet" => self.network_config.testnet.clone(),
  69. "mainnet" => self.network_config.mainnet.clone(),
  70. _ => None,
  71. }
  72. }
  73. }
  74. /// Provides a default `ExplorerConfig` configuration using the `testnet` network.
  75. impl Default for ExplorerConfig {
  76. fn default() -> Self {
  77. Self {
  78. network: String::from("testnet"),
  79. network_config: NetworkConfigs::default(),
  80. path: None,
  81. }
  82. }
  83. }
  84. /// Attempts to convert a [`PathBuff`] to an [`ExplorerConfig`] by loading and parsing from specified file path.
  85. impl TryFrom<&PathBuf> for ExplorerConfig {
  86. type Error = Error;
  87. fn try_from(path: &PathBuf) -> Result<Self> {
  88. let path_str = path.to_str().ok_or_else(|| {
  89. Error::ConfigError("Unable to convert PathBuf to a valid UTF-8 path string".to_string())
  90. })?;
  91. // Create configuration and return
  92. ExplorerConfig::new(path_str.to_string())
  93. }
  94. }
  95. /// Deserializes a `&str` containing explorer content in TOML format into an [`ExplorerConfig`] instance.
  96. impl FromStr for ExplorerConfig {
  97. type Err = String;
  98. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  99. let config: ExplorerConfig =
  100. toml::from_str(s).map_err(|e| format!("Failed to parse ExplorerdConfig: {e}"))?;
  101. Ok(config)
  102. }
  103. }
  104. /// Represents network configurations for localnet, testnet, and mainnet.
  105. #[derive(Debug, Clone, Deserialize, StructOpt)]
  106. pub struct NetworkConfigs {
  107. /// Local network configuration
  108. pub localnet: Option<ExplorerNetworkConfig>,
  109. /// Testnet network configuration
  110. pub testnet: Option<ExplorerNetworkConfig>,
  111. /// Mainnet network configuration
  112. pub mainnet: Option<ExplorerNetworkConfig>,
  113. }
  114. /// Provides a default `NetworkConfigs` configuration using the `testnet` network.
  115. impl Default for NetworkConfigs {
  116. fn default() -> Self {
  117. NetworkConfigs {
  118. localnet: None,
  119. testnet: Some(ExplorerNetworkConfig::default()),
  120. mainnet: None,
  121. }
  122. }
  123. }
  124. /// Deserializes a `&str` containing network configs content in TOML format into an [`NetworkConfigs`] instance.
  125. impl FromStr for NetworkConfigs {
  126. type Err = String;
  127. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  128. let config: NetworkConfigs =
  129. toml::from_str(s).map_err(|e| format!("Failed to parse NetworkConfigs: {e}"))?;
  130. Ok(config)
  131. }
  132. }
  133. /// Struct representing the configuration for an explorer network.
  134. #[derive(Clone, Deserialize, StructOpt)]
  135. #[structopt()]
  136. #[serde(default)]
  137. pub struct ExplorerNetworkConfig {
  138. #[structopt(flatten)]
  139. /// JSON-RPC settings used to set up a server that the explorer listens on for incoming RPC requests.
  140. pub rpc: RpcSettingsOpt,
  141. #[structopt(long, default_value = "~/.local/share/darkfi/explorerd/testnet")]
  142. /// Path to the explorer's database.
  143. pub database: String,
  144. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  145. /// Endpoint of the DarkFi node JSON-RPC server to sync with.
  146. pub endpoint: Url,
  147. }
  148. /// Attempts to convert a tuple `(PathBuf, &str)` representing a configuration file path
  149. /// and network name into an `ExplorerNetworkConfig`.
  150. impl TryFrom<(&PathBuf, &String)> for ExplorerNetworkConfig {
  151. type Error = Error;
  152. fn try_from(path_and_network: (&PathBuf, &String)) -> Result<Self> {
  153. // Load the ExplorerConfig from the given file path
  154. let config: ExplorerConfig = path_and_network.0.try_into()?;
  155. // Retrieve the network configuration for the specified network
  156. match config.get_network_config(path_and_network.1) {
  157. Some(config) => Ok(config),
  158. None => Err(Error::ConfigError(format!(
  159. "Failed to retrieve network configuration for network: {}",
  160. path_and_network.1
  161. ))),
  162. }
  163. }
  164. }
  165. /// Provides a default `ExplorerNetworkConfig` instance using `structopt` default values defined
  166. /// in the `ExplorerNetworkConfig` struct.
  167. impl Default for ExplorerNetworkConfig {
  168. fn default() -> Self {
  169. Self::from_iter(&[""])
  170. }
  171. }
  172. /// Provides a user-friendly debug view of the `ExplorerdNetworkConfig` configuration.
  173. impl fmt::Debug for ExplorerNetworkConfig {
  174. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  175. let mut debug_struct = f.debug_struct("ExplorerdConfig");
  176. debug_struct
  177. .field("rpc_listen", &self.rpc.rpc_listen.to_string().trim_end_matches('/'))
  178. .field("db_path", &self.database)
  179. .field("endpoint", &self.endpoint.to_string().trim_end_matches('/'));
  180. debug_struct.finish()
  181. }
  182. }
  183. /// Deserializes a `&str` containing network config content in TOML format into an [`ExplorerNetworkConfig`] instance.
  184. impl FromStr for ExplorerNetworkConfig {
  185. type Err = String;
  186. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  187. let config: ExplorerNetworkConfig = toml::from_str(s)
  188. .map_err(|e| format!("Failed to parse ExplorerdNetworkConfig: {e}"))?;
  189. Ok(config)
  190. }
  191. }
  192. #[cfg(test)]
  193. /// Contains test cases for validating the functionality and correctness of the `ExplorerConfig`
  194. /// and related components using a configuration loaded from a TOML file.
  195. mod tests {
  196. use std::path::Path;
  197. use super::*;
  198. use crate::test_utils::init_logger;
  199. /// Validates the functionality of initializing and interacting with `ExplorerConfig`
  200. /// loaded from a TOML file, ensuring correctness of the network-specific configurations.
  201. #[test]
  202. fn test_explorerd_config_from_file() {
  203. // Constants for expected configurations
  204. const CONFIG_PATH: &str = "explorerd_config.toml";
  205. const ACTIVE_NETWORK: &str = "testnet";
  206. const NETWORK_CONFIGS: &[(&str, &str, &str, &str)] = &[
  207. (
  208. "localnet",
  209. "~/.local/share/darkfi/explorerd/localnet",
  210. "tcp://127.0.0.1:8240/",
  211. "tcp://127.0.0.1:14567/",
  212. ),
  213. (
  214. "testnet",
  215. "~/.local/share/darkfi/explorerd/testnet",
  216. "tcp://127.0.0.1:8340/",
  217. "tcp://127.0.0.1:14667/",
  218. ),
  219. (
  220. "mainnet",
  221. "~/.local/share/darkfi/explorerd/mainnet",
  222. "tcp://127.0.0.1:8440/",
  223. "tcp://127.0.0.1:14767/",
  224. ),
  225. ];
  226. init_logger(simplelog::LevelFilter::Info, vec!["sled", "runtime", "net"]);
  227. // Ensure the configuration file exists
  228. assert!(Path::new(CONFIG_PATH).exists());
  229. // Load the configuration
  230. let config = ExplorerConfig::new(CONFIG_PATH.to_string())
  231. .expect("Failed to load configuration from file");
  232. // Validate the expected network
  233. assert_eq!(config.network, ACTIVE_NETWORK);
  234. // Validate the path is correctly set
  235. assert_eq!(config.path.as_deref(), Some(CONFIG_PATH));
  236. // Validate that `active_network_config` correctly retrieves the testnet configuration
  237. let active_config = config.active_network_config();
  238. assert!(active_config.is_some(), "Active network configuration should not be None.");
  239. let active_config = active_config.unwrap();
  240. assert_eq!(active_config.database, NETWORK_CONFIGS[1].1); // Testnet database
  241. assert_eq!(active_config.endpoint.to_string(), NETWORK_CONFIGS[1].2);
  242. assert_eq!(&active_config.rpc.rpc_listen.to_string(), NETWORK_CONFIGS[1].3);
  243. // Validate all network configurations values (localnet, testnet, mainnet)
  244. for &(network, expected_db, expected_endpoint, expected_rpc) in NETWORK_CONFIGS {
  245. let network_config = config.get_network_config(network);
  246. if let Some(config) = network_config {
  247. assert_eq!(config.database, expected_db);
  248. assert_eq!(config.endpoint.to_string(), expected_endpoint);
  249. assert_eq!(config.rpc.rpc_listen.to_string(), expected_rpc);
  250. } else {
  251. assert!(network_config.is_none(), "{network} configuration is missing");
  252. }
  253. }
  254. // Validate (path, network).try_into()
  255. let config_path_buf = &PathBuf::from(CONFIG_PATH);
  256. let mainnet_string = &String::from("mainnet");
  257. let mainnet_config: ExplorerNetworkConfig = (config_path_buf, mainnet_string)
  258. .try_into()
  259. .expect("Failed to load explorer network config");
  260. assert_eq!(mainnet_config.database, NETWORK_CONFIGS[2].1); // Mainnet database
  261. assert_eq!(mainnet_config.endpoint.to_string(), NETWORK_CONFIGS[2].2);
  262. assert_eq!(&mainnet_config.rpc.rpc_listen.to_string(), NETWORK_CONFIGS[2].3);
  263. }
  264. }