forked from ordinals/ord
-
Notifications
You must be signed in to change notification settings - Fork 21
/
env.rs
178 lines (147 loc) Β· 4.39 KB
/
env.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use {super::*, colored::Colorize, std::net::TcpListener};
struct KillOnDrop(process::Child);
impl Drop for KillOnDrop {
fn drop(&mut self) {
assert!(Command::new("kill")
.arg(self.0.id().to_string())
.status()
.unwrap()
.success());
self.0.wait().unwrap();
}
}
#[derive(Debug, Parser)]
pub(crate) struct Env {
#[arg(default_value = "env", help = "Create env in <DIRECTORY>.")]
directory: PathBuf,
}
#[derive(Serialize)]
struct Info {
bitcoin_cli_command: Vec<String>,
bitcoind_port: u16,
ord_port: u16,
ord_wallet_command: Vec<String>,
}
impl Env {
pub(crate) fn run(self) -> SubcommandResult {
let bitcoind_port = TcpListener::bind("127.0.0.1:9000")
.ok()
.map(|listener| listener.local_addr().unwrap().port());
let ord_port = TcpListener::bind("127.0.0.1:9001")
.ok()
.map(|listener| listener.local_addr().unwrap().port());
let (bitcoind_port, ord_port) = (
bitcoind_port.unwrap_or(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port()),
ord_port.unwrap_or(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port()),
);
let relative = self.directory.to_str().unwrap().to_string();
let absolute = std::env::current_dir()?.join(&self.directory);
let absolute_str = absolute
.to_str()
.with_context(|| format!("directory `{}` is not valid unicode", absolute.display()))?;
fs::create_dir_all(&absolute)?;
fs::write(
absolute.join("bitcoin.conf"),
format!(
"regtest=1
datadir={absolute_str}
listen=0
txindex=1
[regtest]
rpcport={bitcoind_port}
",
),
)?;
let _bitcoind = KillOnDrop(
Command::new("bitcoind")
.arg(format!("-conf={}", absolute.join("bitcoin.conf").display()))
.stdout(Stdio::null())
.spawn()?,
);
loop {
if absolute.join("regtest/.cookie").try_exists()? {
break;
}
}
let rpc_url = format!("http:https://localhost:{bitcoind_port}");
let server_url = format!("http:https://127.0.0.1:{ord_port}");
let config = absolute.join("ord.yaml");
fs::write(
config,
serde_yaml::to_string(&Settings::for_env(&absolute, &rpc_url, &server_url))?,
)?;
let ord = std::env::current_exe()?;
let _ord = KillOnDrop(
Command::new(&ord)
.arg("--data-dir")
.arg(&absolute)
.arg("server")
.arg("--polling-interval=100ms")
.arg("--http-port")
.arg(ord_port.to_string())
.spawn()?,
);
thread::sleep(Duration::from_millis(250));
if !absolute.join("regtest/wallets/ord").try_exists()? {
let status = Command::new(&ord)
.arg("--data-dir")
.arg(&absolute)
.arg("wallet")
.arg("create")
.status()?;
ensure!(status.success(), "failed to create wallet: {status}");
let output = Command::new(&ord)
.arg("--data-dir")
.arg(&absolute)
.arg("wallet")
.arg("receive")
.output()?;
ensure!(
output.status.success(),
"failed to generate receive address: {status}"
);
let receive =
serde_json::from_slice::<crate::subcommand::wallet::receive::Output>(&output.stdout)?;
let address = receive.address.require_network(Network::Regtest)?;
let status = Command::new("bitcoin-cli")
.arg(format!("-datadir={relative}"))
.arg("generatetoaddress")
.arg("200")
.arg(address.to_string())
.status()?;
ensure!(status.success(), "failed to create wallet: {status}");
}
serde_json::to_writer_pretty(
File::create(self.directory.join("env.json"))?,
&Info {
bitcoind_port,
ord_port,
bitcoin_cli_command: vec!["bitcoin-cli".into(), format!("-datadir={relative}")],
ord_wallet_command: vec![
ord.to_str().unwrap().into(),
"--data-dir".into(),
absolute.to_str().unwrap().into(),
"wallet".into(),
],
},
)?;
eprintln!(
"{}
{server_url}
{}
bitcoin-cli -datadir='{relative}' getblockchaininfo
{}
{} --data-dir '{relative}' wallet balance",
"`ord` server URL:".blue().bold(),
"Example `bitcoin-cli` command:".blue().bold(),
"Example `ord` command:".blue().bold(),
ord.display(),
);
loop {
if SHUTTING_DOWN.load(atomic::Ordering::Relaxed) {
break Ok(None);
}
thread::sleep(Duration::from_millis(100));
}
}
}