Skip to content
New issue

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

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

Already on GitHub? # to your account

Add little command for easy access to JSON-RPC interface #180

Merged
merged 3 commits into from
Nov 12, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
46 changes: 40 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ tracing-subscriber = "0.2.18"
trin-core = { path = "trin-core" }
trin-history = { path = "trin-history" }
trin-state = { path = "trin-state" }
trin-cli = { path = "trin-cli" }

[dependencies.discv5]
version = "0.1.0-beta.10"
Expand All @@ -26,5 +27,6 @@ members = [
"trin-history",
"trin-state",
"trin-core",
"trin-cli",
"ethportal-peertest"
]
18 changes: 18 additions & 0 deletions trin-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "trin-cli"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
structopt="0.3.25"
trin-core = { path = "../trin-core" }
jsonrpc = "0.12.0"
serde_json = "1.0.68"
serde = "1.0.117"
thiserror = "1.0.29"

[[bin]]
name="trin-cli"
path="src/main.rs"
125 changes: 125 additions & 0 deletions trin-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use thiserror::Error;

use trin_core::cli::DEFAULT_WEB3_IPC_PATH;

#[derive(StructOpt, Debug)]
#[structopt(
name = "trin-cli",
version = "0.0.1",
author = "Ethereum Foundation",
about = "Run JSON-RPC commands against trin nodes"
)]
struct Config {
#[structopt(
default_value(DEFAULT_WEB3_IPC_PATH),
long,
help = "path to JSON-RPC endpoint"
)]
ipc: PathBuf,

#[structopt(help = "e.g. discv5_routingTableInfo", required = true)]
endpoint: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
let Config { ipc, endpoint } = Config::from_args();

eprintln!(
"Attempting RPC. endpoint={} file={}",
endpoint,
ipc.to_string_lossy()
);
let mut client = TrinClient::from_ipc(&ipc)?;

let req = client.build_request(endpoint.as_str());
let resp = client.make_request(req)?;

println!("{}", serde_json::to_string_pretty(&resp).unwrap());
Ok(())
}

fn build_request(method: &str, request_id: u64) -> jsonrpc::Request {
jsonrpc::Request {
method,
params: &[],
id: serde_json::json!(request_id),
jsonrpc: Some("2.0"),
}
}

pub trait TryClone {
fn try_clone(&self) -> std::io::Result<Self>
where
Self: Sized;
}

impl TryClone for UnixStream {
fn try_clone(&self) -> std::io::Result<Self> {
UnixStream::try_clone(self)
}
}

pub struct TrinClient<S>
where
S: std::io::Read + std::io::Write + TryClone,
{
stream: S,
request_id: u64,
}

impl TrinClient<UnixStream> {
fn from_ipc(path: &Path) -> std::io::Result<Self> {
// TODO: a nice error if this file does not exist
Ok(Self {
stream: UnixStream::connect(path)?,
request_id: 0,
})
}
}

#[derive(Error, Debug)]
pub enum JsonRpcError {
#[error("Received malformed response: {0}")]
Malformed(serde_json::Error),

#[error("Received empty response")]
Empty,
}

// TryClone is used because JSON-RPC responses are not followed by EOF. We must read bytes
// from the stream until a complete object is detected, and the simplest way of doing that
// with available APIs is to give ownership of a Read to a serde_json::Deserializer. If we
// gave it exclusive ownership that would require us to open a new connection for every
// command we wanted to send! By making a clone (or, by trying to) we can have our cake
Comment on lines +95 to +96
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess that's only important with an interactive REPL-type tool, rather than this CLI one-shot, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, definitely. I can drop it if you would prefer. This was originally added because I had grand plans of turning this into a client we could use in other parts of the codebase which want to make JSON-RPC calls, such as in the peer tester. You're right that it's unnecessary for current usage but I still think it's useful to have that long-term goal for TrinClient.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'm happy to keep it. Maybe just add that little bit of context to the comment.

// and eat it too.
impl<'a, S> TrinClient<S>
where
S: std::io::Read + std::io::Write + TryClone,
{
fn build_request(&mut self, method: &'a str) -> jsonrpc::Request<'a> {
let result = build_request(method, self.request_id);
self.request_id += 1;

result
}

fn make_request(&mut self, req: jsonrpc::Request) -> Result<serde_json::Value, JsonRpcError> {
let data = serde_json::to_vec(&req).unwrap();

self.stream.write_all(&data).unwrap();
self.stream.flush().unwrap();

let clone = self.stream.try_clone().unwrap();
let deser = serde_json::Deserializer::from_reader(clone);

if let Some(obj) = deser.into_iter::<serde_json::Value>().next() {
return obj.map_err(JsonRpcError::Malformed);
}

// this should only happen when they immediately send EOF
Err(JsonRpcError::Empty)
}
}