Просмотр исходного кода

rpc: pass Url object to send_request function instead of &str

ghassmo 4 лет назад
Родитель
Сommit
e3a68e334b

+ 4 - 0
Cargo.lock

@@ -816,6 +816,7 @@ dependencies = [
  "spl-token",
  "thiserror",
  "tungstenite",
+ "url",
 ]
 
 [[package]]
@@ -1354,6 +1355,7 @@ dependencies = [
  "serde_json",
  "simplelog",
  "smol",
+ "url",
 ]
 
 [[package]]
@@ -1681,6 +1683,7 @@ dependencies = [
  "prettytable-rs",
  "serde_json",
  "simplelog",
+ "url",
 ]
 
 [[package]]
@@ -2847,6 +2850,7 @@ dependencies = [
  "smol",
  "termion",
  "tui",
+ "url",
 ]
 
 [[package]]

+ 1 - 0
bin/cashierd/Cargo.toml

@@ -26,6 +26,7 @@ log = "0.4.14"
 num_cpus = "1.13.1"
 simplelog = "0.11.2"
 thiserror = "1.0.30"
+url = "2.2.2"
 
 # Encoding and parsing
 serde = {version = "1.0.133", features = ["derive"], optional = true}

+ 3 - 4
bin/cashierd/src/service/eth.rs

@@ -10,6 +10,7 @@ use log::{debug, error, info, trace};
 use num_bigint::{BigUint, RandBigInt};
 use serde::{Deserialize, Serialize};
 use serde_json::{json, Value};
+use url::Url;
 
 use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion};
 
@@ -347,11 +348,9 @@ impl EthClient {
 
     async fn request(&self, r: jsonrpc::JsonRequest) -> EthResult<Value> {
         debug!(target: "ETH RPC", "--> {}", serde_json::to_string(&r)?);
+        let url = Url::parse(&format!("unix://{}", self.socket_path)).map_err(Error::from)?;
         let reply: JsonResult =
-            match jsonrpc::send_request(&format!("unix://{}", self.socket_path), json!(r))
-                .await
-                .map_err(EthFailed::from)
-            {
+            match jsonrpc::send_request(&url, json!(r)).await.map_err(EthFailed::from) {
                 Ok(v) => v,
                 Err(e) => return Err(e),
             };

+ 1 - 0
bin/dao-cli/Cargo.toml

@@ -24,6 +24,7 @@ clap = {version = "3.0.7", features = ["derive"]}
 log = "0.4.14"
 num_cpus = "1.13.1"
 simplelog = "0.11.2"
+url = "2.2.2"
 
 # Encoding and parsing
 serde_json = "1.0.74"

+ 8 - 4
bin/dao-cli/src/main.rs

@@ -1,14 +1,17 @@
 use async_executor::Executor;
+use std::sync::Arc;
+
 use clap::{IntoApp, Parser, Subcommand};
+use log::{debug, error};
+use serde_json::{json, Value};
+use url::Url;
+
 use darkfi::{
     cli::Config,
     rpc::{jsonrpc, jsonrpc::JsonResult},
     util::async_util,
     Error, Result,
 };
-use log::{debug, error};
-use serde_json::{json, Value};
-use std::sync::Arc;
 
 #[derive(Subcommand)]
 pub enum CliDaoSubCommands {
@@ -36,7 +39,8 @@ impl Client {
     }
 
     async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
-        let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
+        let reply: JsonResult = match jsonrpc::send_request(&Url::parse(&self.url)?, json!(r)).await
+        {
             Ok(v) => v,
             Err(e) => return Err(e),
         };

+ 3 - 3
bin/darkfid/src/main.rs

@@ -66,7 +66,7 @@ pub const ETH_NATIVE_TOKEN_ID: &str = "0x000000000000000000000000000000000000000
 #[derive(Clone, Debug)]
 pub struct Cashier {
     pub name: String,
-    pub rpc_url: String,
+    pub rpc_url: Url,
     pub public_key: PublicKey,
 }
 
@@ -758,7 +758,7 @@ async fn start(
 
         cashiers.push(Cashier {
             name: "localCashier".into(),
-            rpc_url: "tcp://127.0.0.1:9000".into(),
+            rpc_url: Url::parse("tcp://127.0.0.1:9000")?,
             public_key: cashier_public,
         });
 
@@ -774,7 +774,7 @@ async fn start(
 
             cashiers.push(Cashier {
                 name: cashier.name,
-                rpc_url: cashier.rpc_url,
+                rpc_url: Url::parse(&cashier.rpc_url)?,
                 public_key: cashier_public,
             });
 

+ 1 - 0
bin/drk/Cargo.toml

@@ -16,6 +16,7 @@ clap = {version = "3.0.7", features = ["derive"]}
 log = "0.4.14"
 simplelog = "0.11.2"
 prettytable-rs = "0.8.0"
+url = "2.2.2"
 
 # Encoding and parsing
 serde_json = "1.0.74"

+ 4 - 3
bin/drk/src/main.rs

@@ -5,6 +5,7 @@ use log::{debug, error};
 use prettytable::{cell, format, row, Table};
 use serde_json::{json, Value};
 use simplelog::{ColorChoice, TermLogger, TerminalMode};
+use url::Url;
 
 use darkfi::{
     cli::{
@@ -120,11 +121,11 @@ pub struct CliDrk {
 const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../drk_config.toml");
 
 struct Drk {
-    url: String,
+    url: Url,
 }
 
 impl Drk {
-    pub fn new(url: String) -> Self {
+    pub fn new(url: Url) -> Self {
         Self { url }
     }
 
@@ -292,7 +293,7 @@ impl Drk {
 }
 
 async fn start(config: &DrkConfig, options: CliDrk) -> Result<()> {
-    let client = Drk::new(config.darkfid_rpc_url.clone());
+    let client = Drk::new(Url::parse(&config.darkfid_rpc_url)?);
 
     match options.command {
         Some(CliDrkSubCommands::Hello {}) => {

+ 6 - 6
bin/ircd/src/main.rs

@@ -82,7 +82,7 @@ async fn process_user_input(
 ) -> Result<()> {
     if line.is_empty() {
         warn!("Received empty line from {}. Closing connection.", peer_addr);
-        return Err(Error::ChannelStopped);
+        return Err(Error::ChannelStopped)
     }
     assert!(&line[(line.len() - 1)..] == "\n");
     // Remove the \n character
@@ -92,7 +92,7 @@ async fn process_user_input(
 
     if let Err(err) = connection.update(line, p2p.clone()).await {
         warn!("Connection error: {} for {}", err, peer_addr);
-        return Err(Error::ChannelStopped);
+        return Err(Error::ChannelStopped)
     }
 
     Ok(())
@@ -103,14 +103,14 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
         Ok(listener) => listener,
         Err(err) => {
             error!("Bind listener failed: {}", err);
-            return Err(Error::OperationFailed);
+            return Err(Error::OperationFailed)
         }
     };
     let local_addr = match listener.get_ref().local_addr() {
         Ok(addr) => addr,
         Err(err) => {
             error!("Failed to get local address: {}", err);
-            return Err(Error::OperationFailed);
+            return Err(Error::OperationFailed)
         }
     };
     info!("Listening on {}", local_addr);
@@ -177,7 +177,7 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
             Ok((s, a)) => (s, a),
             Err(err) => {
                 error!("Error listening for connections: {}", err);
-                return Err(Error::ServiceStopped);
+                return Err(Error::ServiceStopped)
             }
         };
         info!("Accepted client: {}", peer_addr);
@@ -198,7 +198,7 @@ struct JsonRpcInterface {
 impl RequestHandler for JsonRpcInterface {
     async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
         if req.params.as_array().is_none() {
-            return JsonResult::Err(jsonerr(InvalidParams, None, req.id));
+            return JsonResult::Err(jsonerr(InvalidParams, None, req.id))
         }
 
         debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());

+ 1 - 0
bin/map/Cargo.toml

@@ -24,6 +24,7 @@ rand = "0.6.5"
 simplelog = "0.11.2"
 log = "0.4.14"
 num_cpus = "1.13.1"
+url = "2.2.2"
 
 # Encoding and parsing
 serde_json = "1.0.74"

+ 5 - 4
bin/map/src/main.rs

@@ -27,6 +27,7 @@ use tui::{
     backend::{Backend, TermionBackend},
     Terminal,
 };
+use url::Url;
 
 use map::{
     model::{Connection, IdList, InfoList, NodeInfo},
@@ -39,11 +40,11 @@ use map::{
 const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../map_config.toml");
 
 struct Map {
-    url: String,
+    url: Url,
 }
 
 impl Map {
-    pub fn new(url: String) -> Self {
+    pub fn new(url: Url) -> Self {
         Self { url }
     }
 
@@ -140,7 +141,7 @@ async fn run_rpc(config: &MapConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -
     }
     for node in rpc_vec {
         debug!("Created client: {}", node.node_id);
-        let client = Map::new(node.node_id);
+        let client = Map::new(Url::parse(&node.node_id)?);
         ex.spawn(poll(client, model.clone())).detach();
     }
 
@@ -264,7 +265,7 @@ async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io
             match k.unwrap() {
                 Key::Char('q') => {
                     terminal.clear()?;
-                    return Ok(());
+                    return Ok(())
                 }
                 Key::Char('j') => {
                     view.id_list.next();

+ 8 - 9
src/rpc/jsonrpc.rs

@@ -11,7 +11,7 @@ use serde_json::{json, Value};
 use smol::Async;
 use url::Url;
 
-use crate::Error;
+use crate::{Error, Result};
 
 #[derive(Debug, Clone)]
 pub enum ErrorCode {
@@ -141,15 +141,14 @@ pub fn notification(m: Value, p: Value) -> JsonNotification {
     JsonNotification { jsonrpc: json!("2.0"), method: m, params: p }
 }
 
-pub async fn send_request(uri: &str, data: Value) -> Result<JsonResult, Error> {
+pub async fn send_request(uri: &Url, data: Value) -> Result<JsonResult> {
     // let mut use_tor = false;
     // let mut use_nym = false;
     let mut use_tcp = false;
     let mut use_tls = false;
     let mut use_unix = false;
 
-    let parsed_uri = Url::parse(uri)?;
-    match parsed_uri.scheme() {
+    match uri.scheme() {
         "tor" => unimplemented!(),
         "nym" => unimplemented!(),
         "tcp" => use_tcp = true,
@@ -163,13 +162,13 @@ pub async fn send_request(uri: &str, data: Value) -> Result<JsonResult, Error> {
     let data_str = serde_json::to_string(&data)?;
 
     if use_tcp || use_tls {
-        let host = parsed_uri
+        let host = uri
             .host()
             .ok_or_else(|| Error::UrlParseError(format!("Missing host in {}", uri)))?
             .to_string();
-        let port = parsed_uri
-            .port()
-            .ok_or_else(|| Error::UrlParseError(format!("Missing port in {}", uri)))?;
+
+        let port =
+            uri.port().ok_or_else(|| Error::UrlParseError(format!("Missing port in {}", uri)))?;
 
         let socket_addr = {
             let host = host.clone();
@@ -195,7 +194,7 @@ pub async fn send_request(uri: &str, data: Value) -> Result<JsonResult, Error> {
     }
 
     if use_unix {
-        let mut stream = Async::<UnixStream>::connect(parsed_uri.path()).await?;
+        let mut stream = Async::<UnixStream>::connect(uri.path()).await?;
         stream.write_all(data_str.as_bytes()).await?;
 
         bytes_read = stream.read(&mut buf[..]).await?;