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