-
Notifications
You must be signed in to change notification settings - Fork 137
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
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
// 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) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
.There was a problem hiding this comment.
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.