forked from romanz/electrs
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathelectrum.rs
More file actions
233 lines (193 loc) · 7.77 KB
/
electrum.rs
File metadata and controls
233 lines (193 loc) · 7.77 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
pub mod common;
use std::io::{Read, Write};
use std::net::TcpStream;
use common::Result;
use bitcoind::bitcoincore_rpc::RpcApi;
use electrumd::jsonrpc::serde_json::json;
use electrumd::ElectrumD;
use electrs::chain::Address;
#[cfg(not(feature = "liquid"))]
use bitcoin::address;
/// Test the Electrum RPC server using an headless Electrum wallet
/// This only runs on Bitcoin (non-Liquid) mode.
#[cfg_attr(not(feature = "liquid"), test)]
#[cfg_attr(feature = "liquid", allow(dead_code))]
fn test_electrum() -> Result<()> {
// Spawn an Electrs Electrum RPC server
let (electrum_server, electrum_addr, mut tester) = common::init_electrum_tester().unwrap();
// Spawn an headless Electrum wallet RPC daemon, connected to Electrs
let mut electrum_wallet_conf = electrumd::Conf::default();
let server_arg = format!("{}:t", electrum_addr.to_string());
electrum_wallet_conf.args = if std::env::var_os("RUST_LOG").is_some() {
vec!["-v", "--server", &server_arg]
} else {
vec!["--server", &server_arg]
};
electrum_wallet_conf.view_stdout = true;
let electrum_wallet = ElectrumD::with_conf(electrumd::exe_path()?, &electrum_wallet_conf)?;
let notify_wallet = || {
electrum_server.notify();
std::thread::sleep(std::time::Duration::from_millis(200));
};
let assert_balance = |confirmed: f64, unconfirmed: f64| {
let balance = electrum_wallet.call("getbalance", &json!([])).unwrap();
log::info!("balance: {}", balance);
assert_eq!(
balance["confirmed"].as_str(),
Some(confirmed.to_string().as_str())
);
if unconfirmed != 0.0 {
assert_eq!(
balance["unconfirmed"].as_str(),
Some(unconfirmed.to_string().as_str())
);
} else {
assert!(balance["unconfirmed"].is_null())
}
};
let newaddress = || -> Address {
#[cfg(not(feature = "liquid"))]
type ParseAddrType = Address<address::NetworkUnchecked>;
#[cfg(feature = "liquid")]
type ParseAddrType = Address;
let addr = electrum_wallet
.call("createnewaddress", &json!([]))
.unwrap()
.as_str()
.expect("missing address")
.parse::<ParseAddrType>()
.expect("invalid address");
#[cfg(not(feature = "liquid"))]
let addr = addr.assume_checked();
addr
};
log::info!(
"Electrum wallet version: {:?}",
electrum_wallet.call("version", &json!([]))?
);
// Send some funds and verify that the balance checks out
let addr1 = newaddress();
let addr2 = newaddress();
assert_balance(0.0, 0.0);
let txid1 = tester.send(&addr1, "0.1 BTC".parse().unwrap())?;
notify_wallet();
assert_balance(0.0, 0.1);
tester.mine()?;
notify_wallet();
assert_balance(0.1, 0.0);
let txid2 = tester.send(&addr2, "0.2 BTC".parse().unwrap())?;
notify_wallet();
assert_balance(0.1, 0.2);
tester.mine()?;
notify_wallet();
assert_balance(0.3, 0.0);
// Verify that the transaction history checks out
let history = electrum_wallet.call("onchain_history", &json!([]))?;
log::debug!("history = {:#?}", history);
assert_eq!(
history["transactions"][0]["txid"].as_str(),
Some(txid1.to_string().as_str())
);
assert_eq!(history["transactions"][0]["height"].as_u64(), Some(102));
assert_eq!(history["transactions"][0]["bc_value"].as_str(), Some("0.1"));
assert_eq!(
history["transactions"][1]["txid"].as_str(),
Some(txid2.to_string().as_str())
);
assert_eq!(history["transactions"][1]["height"].as_u64(), Some(103));
assert_eq!(history["transactions"][1]["bc_value"].as_str(), Some("0.2"));
// Send an outgoing payment
electrum_wallet.call(
"broadcast",
&json!([electrum_wallet.call(
"payto",
&json!({
"destination": tester.node_client().get_new_address(None, None)?,
"amount": 0.16,
"fee": 0.001,
}),
)?]),
)?;
notify_wallet();
assert_balance(0.139, 0.0);
tester.mine()?;
notify_wallet();
assert_balance(0.139, 0.0);
Ok(())
}
/// Test the Electrum RPC server using a raw TCP socket
/// This only runs on Bitcoin (non-Liquid) mode.
#[cfg_attr(not(feature = "liquid"), test)]
#[cfg_attr(feature = "liquid", allow(dead_code))]
#[ignore = "must be launched singularly, otherwise conflict with the other server"]
fn test_electrum_raw() {
// Spawn an Electrs Electrum RPC server
let (_electrum_server, electrum_addr, mut _tester) = common::init_electrum_tester().unwrap();
std::thread::sleep(std::time::Duration::from_millis(1000));
let mut stream = TcpStream::connect(electrum_addr).unwrap();
let write = "{\"jsonrpc\": \"2.0\", \"method\": \"server.version\", \"id\": 0}";
let s = write_and_read(&mut stream, write);
let expected = "{\"id\":0,\"jsonrpc\":\"2.0\",\"result\":[\"electrs-esplora 0.4.1\",\"1.4\"]}";
assert_eq!(s, expected);
let write = "[{\"jsonrpc\": \"2.0\", \"method\": \"server.version\", \"id\": 0}]";
let s = write_and_read(&mut stream, write);
let expected =
"[{\"id\":0,\"jsonrpc\":\"2.0\",\"result\":[\"electrs-esplora 0.4.1\",\"1.4\"]}]";
assert_eq!(s, expected);
}
fn write_and_read(stream: &mut TcpStream, write: &str) -> String {
stream.write_all(write.as_bytes()).unwrap();
stream.write(b"\n").unwrap();
stream.flush().unwrap();
let mut result = vec![];
loop {
let mut buf = [0u8];
stream.read_exact(&mut buf).unwrap();
if buf[0] == b'\n' {
break;
} else {
result.push(buf[0]);
}
}
std::str::from_utf8(&result).unwrap().to_string()
}
/// Test that verifies the acceptor thread handles channel closure gracefully
/// This test simulates the production scenario where the main RPC thread exits
/// while the acceptor thread is still running. Without the fix, this would cause
/// a panic at the acceptor.send().expect() call. With the fix, the acceptor thread
/// should exit gracefully when the channel is closed.
#[test]
fn test_acceptor_panic_on_channel_close() {
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
// Use the existing init_electrum_tester function which properly sets up the server
let (electrum_server, electrum_addr, _tester) = common::init_electrum_tester().unwrap();
// Give the server a moment to start up
thread::sleep(Duration::from_millis(100));
// Start a thread that continuously tries to connect to the server
// This will keep the acceptor thread busy accepting connections
let addr = electrum_addr;
let connection_thread = thread::spawn(move || {
for _ in 0..100 {
if let Ok(_stream) = TcpStream::connect(addr) {
// Keep the connection open briefly
thread::sleep(Duration::from_millis(10));
}
thread::sleep(Duration::from_millis(1));
}
});
// Give the connection thread time to start making connections
thread::sleep(Duration::from_millis(50));
// Now immediately stop the server by dropping it
// This will close the receiver channel, but the acceptor thread might still be running
// and trying to send new connections, which should cause a panic
drop(electrum_server);
// Give some time for the acceptor thread to potentially panic
thread::sleep(Duration::from_millis(500));
// Wait for the connection thread to finish
let _ = connection_thread.join();
// If we reach here without panicking, the test passes
// This test verifies that the acceptor thread gracefully handles channel closure
// instead of panicking when the main RPC thread exits
}