Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batching with array #108

Open
wants to merge 4 commits into
base: new-index
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 58 additions & 41 deletions src/electrum/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,48 +546,16 @@ impl Connection {
match msg {
Message::Request(line) => {
let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
match (
cmd.get("method"),
cmd.get("params").unwrap_or_else(|| &empty_params),
cmd.get("id"),
) {
(
Some(&Value::String(ref method)),
&Value::Array(ref params),
Some(ref id),
) => {
conditionally_log_rpc_event!(
self,
json!({
"event": "rpc request",
"id": id,
"method": method,
"params": if let Some(RpcLogging::Full) = self.rpc_logging {
json!(params)
} else {
Value::Null
}
})
);

let reply = self.handle_command(method, params, id)?;

conditionally_log_rpc_event!(
self,
json!({
"event": "rpc response",
"method": method,
"payload_size": reply.to_string().as_bytes().len(),
"duration_micros": start_time.elapsed().as_micros(),
"id": id,
})
);

self.send_values(&[reply])?
}
_ => {
bail!("invalid command: {}", cmd)
if let Value::Array(arr) = cmd {
let mut result = Vec::with_capacity(arr.len());
for el in arr {
let reply = self.handle_value(el, &empty_params, start_time)?;
result.push(reply)
}
self.send_values(&[Value::Array(result)])?
} else {
let reply = self.handle_value(cmd, &empty_params, start_time)?;
self.send_values(&[reply])?
}
}
Message::PeriodicUpdate => {
Expand All @@ -601,6 +569,55 @@ impl Connection {
}
}

fn handle_value(
&mut self,
cmd: Value,
empty_params: &Value,
start_time: Instant,
) -> Result<Value> {
Ok(
match (
cmd.get("method"),
cmd.get("params").unwrap_or_else(|| empty_params),
cmd.get("id"),
) {
(Some(&Value::String(ref method)), &Value::Array(ref params), Some(ref id)) => {
conditionally_log_rpc_event!(
self,
json!({
"event": "rpc request",
"id": id,
"method": method,
"params": if let Some(RpcLogging::Full) = self.rpc_logging {
json!(params)
} else {
Value::Null
}
})
);

let reply = self.handle_command(method, params, id)?;

conditionally_log_rpc_event!(
self,
json!({
"event": "rpc response",
"method": method,
"payload_size": reply.to_string().as_bytes().len(),
"duration_micros": start_time.elapsed().as_micros(),
"id": id,
})
);

reply
}
_ => {
bail!("invalid command: {}", cmd)
}
},
)
}

fn parse_requests(mut reader: BufReader<TcpStream>, tx: &SyncSender<Message>) -> Result<()> {
loop {
let mut line = Vec::<u8>::new();
Expand Down
44 changes: 44 additions & 0 deletions tests/electrum.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
pub mod common;
use std::io::{Read, Write};
use std::net::TcpStream;

use common::Result;

use bitcoind::bitcoincore_rpc::RpcApi;
Expand Down Expand Up @@ -137,3 +140,44 @@ fn test_electrum() -> Result<()> {

Ok(())
}

/// 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_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()
}
Loading