Skip to main content

smplx_test/
config.rs

1use std::fs;
2use std::fs::OpenOptions;
3use std::io::Read;
4use std::io::Write;
5use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9use smplx_regtest::RegtestConfig;
10
11use super::error::TestError;
12
13pub const TEST_ENV_NAME: &str = "SIMPLEX_TEST_ENV";
14pub const DEFAULT_TEST_MNEMONIC: &str = "exist carry drive collect lend cereal occur much tiger just involve mean";
15pub const DEFAULT_BITCOINS: u64 = 10_000_000;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(default)]
19pub struct TestConfig {
20    pub mnemonic: String,
21    pub bitcoins: u64,
22    pub esplora: Option<EsploraConfig>,
23    pub rpc: Option<RpcConfig>,
24}
25
26#[derive(Debug, Default, Clone, Serialize, Deserialize)]
27pub struct EsploraConfig {
28    pub url: String,
29    pub network: String,
30}
31
32#[derive(Debug, Default, Clone, Serialize, Deserialize)]
33pub struct RpcConfig {
34    pub url: String,
35    pub username: String,
36    pub password: String,
37}
38
39impl TestConfig {
40    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, TestError> {
41        let mut content = String::new();
42        let mut file = OpenOptions::new().read(true).open(path)?;
43
44        file.read_to_string(&mut content)?;
45
46        Ok(toml::from_str(&content)?)
47    }
48
49    pub fn to_regtest_config(&self) -> RegtestConfig {
50        RegtestConfig {
51            mnemonic: self.mnemonic.clone(),
52            bitcoins: self.bitcoins,
53            rpc_port: None,
54            esplora_port: None,
55            rpc_user: None,
56            rpc_password: None,
57        }
58    }
59
60    pub fn to_file(&self, path: &impl AsRef<Path>) -> Result<(), TestError> {
61        if let Some(parent_dir) = path.as_ref().parent() {
62            fs::create_dir_all(parent_dir)?;
63        }
64
65        let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path)?;
66
67        file.write_all(toml::to_string_pretty(&self).unwrap().as_bytes())?;
68        file.flush()?;
69
70        Ok(())
71    }
72}
73
74impl Default for TestConfig {
75    fn default() -> Self {
76        Self {
77            mnemonic: DEFAULT_TEST_MNEMONIC.to_string(),
78            bitcoins: DEFAULT_BITCOINS,
79            esplora: None,
80            rpc: None,
81        }
82    }
83}