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        }
54    }
55
56    pub fn to_file(&self, path: &impl AsRef<Path>) -> Result<(), TestError> {
57        if let Some(parent_dir) = path.as_ref().parent() {
58            fs::create_dir_all(parent_dir)?;
59        }
60
61        let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path)?;
62
63        file.write_all(toml::to_string_pretty(&self).unwrap().as_bytes())?;
64        file.flush()?;
65
66        Ok(())
67    }
68}
69
70impl Default for TestConfig {
71    fn default() -> Self {
72        Self {
73            mnemonic: DEFAULT_TEST_MNEMONIC.to_string(),
74            bitcoins: DEFAULT_BITCOINS,
75            esplora: None,
76            rpc: None,
77        }
78    }
79}