Przeglądaj źródła

basic daocli and daod hello_world() over rpc

lunar-mining 4 lat temu
rodzic
commit
94b7f97ebd
8 zmienionych plików z 302 dodań i 1 usunięć
  1. 37 0
      Cargo.lock
  2. 2 0
      Cargo.toml
  3. 29 0
      bin/dao-cli/Cargo.toml
  4. 90 0
      bin/dao-cli/src/main.rs
  5. 28 0
      bin/daod/Cargo.toml
  6. 96 0
      bin/daod/src/main.rs
  7. 19 0
      src/cli/cli_parser.rs
  8. 1 1
      src/cli/mod.rs

+ 37 - 0
Cargo.lock

@@ -1337,6 +1337,43 @@ dependencies = [
  "zeroize",
  "zeroize",
 ]
 ]
 
 
+[[package]]
+name = "daocli"
+version = "0.1.0"
+dependencies = [
+ "async-channel",
+ "async-executor",
+ "async-std",
+ "async-trait",
+ "clap 3.0.7",
+ "darkfi",
+ "easy-parallel",
+ "futures",
+ "log",
+ "num_cpus",
+ "serde_json",
+ "simplelog",
+ "smol",
+]
+
+[[package]]
+name = "daod"
+version = "0.1.0"
+dependencies = [
+ "async-channel",
+ "async-executor",
+ "async-std",
+ "async-trait",
+ "darkfi",
+ "easy-parallel",
+ "futures",
+ "log",
+ "num_cpus",
+ "serde_json",
+ "simplelog",
+ "smol",
+]
+
 [[package]]
 [[package]]
 name = "darkfi"
 name = "darkfi"
 version = "0.3.0"
 version = "0.3.0"

+ 2 - 0
Cargo.toml

@@ -20,6 +20,8 @@ members = [
     "bin/gatewayd",
     "bin/gatewayd",
     "bin/ircd",
     "bin/ircd",
     "bin/map",
     "bin/map",
+    "bin/daod",
+    "bin/daocli",
 ]
 ]
 
 
 [dependencies]
 [dependencies]

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

@@ -0,0 +1,29 @@
+[package]
+name = "daocli"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies.darkfi]
+path = "../../"
+features = ["rpc", "cli"]
+
+[dependencies]
+# Async
+smol = "1.2.5"
+futures = "0.3.19"
+async-std = {version = "1.10.0", features = ["attributes"]}
+async-trait = "0.1.52"
+async-channel = "1.6.1"
+async-executor = "1.4.1"
+easy-parallel = "3.2.0"
+
+# Misc
+clap = {version = "3.0.7", features = ["derive"]}
+log = "0.4.14"
+num_cpus = "1.13.1"
+simplelog = "0.11.2"
+
+# Encoding and parsing
+serde_json = "1.0.74"

+ 90 - 0
bin/dao-cli/src/main.rs

@@ -0,0 +1,90 @@
+use async_executor::Executor;
+use clap::{IntoApp, Parser};
+use darkfi::{
+    cli::{CliDao, CliDaoSubCommands, Config},
+    rpc::{jsonrpc, jsonrpc::JsonResult},
+    util::async_util,
+    Error, Result,
+};
+use log::{debug, error};
+use serde_json::{json, Value};
+use std::sync::Arc;
+
+pub struct Client {
+    url: String,
+}
+
+impl Client {
+    pub fn new(url: String) -> Self {
+        Self { url }
+    }
+
+    async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
+        let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
+            Ok(v) => v,
+            Err(e) => return Err(e),
+        };
+
+        match reply {
+            JsonResult::Resp(r) => {
+                debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
+                Ok(r.result)
+            }
+
+            JsonResult::Err(e) => {
+                debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
+                Err(Error::JsonRpcError(e.error.message.to_string()))
+            }
+
+            JsonResult::Notif(n) => {
+                debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
+                Err(Error::JsonRpcError("Unexpected reply".to_string()))
+            }
+        }
+    }
+
+    // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
+    // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
+    async fn say_hello(&self) -> Result<Value> {
+        let req = jsonrpc::request(json!("say_hello"), json!([]));
+        Ok(self.request(req).await?)
+    }
+}
+
+async fn start(options: CliDao) -> Result<()> {
+    let rpc_addr = "tcp://127.0.0.1:7777";
+    let client = Client::new(rpc_addr.to_string());
+    match options.command {
+        Some(CliDaoSubCommands::Hello {}) => {
+            let reply = client.say_hello().await?;
+            println!("Server replied: {}", &reply.to_string());
+            return Ok(());
+        }
+        None => {}
+    }
+    error!("Please run 'dao help' to see usage.");
+
+    Err(Error::MissingParams)
+}
+
+#[async_std::main]
+async fn main() -> Result<()> {
+    let args = CliDao::parse();
+    let matches = CliDao::into_app().get_matches();
+
+    //let config_path = if args.config.is_some() {
+    //    expand_path(&args.config.clone().unwrap())?
+    //} else {
+    //    join_config_path(&PathBuf::from("drk.toml"))?
+    //};
+
+    // Spawn config file if it's not in place already.
+    //spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
+
+    //let (lvl, conf) = log_config(matches)?;
+    //TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
+
+    //let config = Config::<DrkConfig>::load(config_path)?;
+
+    start(args).await
+}

+ 28 - 0
bin/daod/Cargo.toml

@@ -0,0 +1,28 @@
+[package]
+name = "daod"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies.darkfi]
+path = "../../"
+features = ["rpc"]
+
+[dependencies]
+# Async
+smol = "1.2.5"
+futures = "0.3.19"
+async-std = {version = "1.10.0", features = ["attributes"]}
+async-trait = "0.1.52"
+async-channel = "1.6.1"
+async-executor = "1.4.1"
+easy-parallel = "3.2.0"
+
+# Misc
+log = "0.4.14"
+num_cpus = "1.13.1"
+simplelog = "0.11.2"
+
+# Encoding and parsing
+serde_json = "1.0.74"

+ 96 - 0
bin/daod/src/main.rs

@@ -0,0 +1,96 @@
+use async_executor::Executor;
+use async_trait::async_trait;
+use darkfi::{
+    rpc::{
+        jsonrpc::{error as jsonerr, response as jsonresp, ErrorCode::*, JsonRequest, JsonResult},
+        rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
+    },
+    util::expand_path,
+    Result,
+};
+use easy_parallel::Parallel;
+use log::debug;
+use serde_json::{json, Value};
+use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
+use std::{
+    net::{IpAddr, Ipv4Addr, SocketAddr},
+    sync::Arc,
+};
+
+async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
+    let rpc_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7777);
+    let server_config = RpcServerConfig {
+        socket_addr: rpc_addr,
+        use_tls: false,
+        // this is all random filler that is meaningless bc tls is disabled
+        // TODO: cleanup
+        identity_path: expand_path("../..")?,
+        identity_pass: "test".to_string(),
+    };
+
+    let rpc_interface = Arc::new(JsonRpcInterface {});
+
+    listen_and_serve(server_config, rpc_interface, executor).await?;
+    Ok(())
+}
+
+struct JsonRpcInterface {}
+
+#[async_trait]
+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));
+        }
+
+        debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
+
+        match req.method.as_str() {
+            Some("say_hello") => return self.say_hello(req.id, req.params).await,
+            Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
+        }
+    }
+}
+
+impl JsonRpcInterface {
+    // --> {"method": "say_hello", "params": []}
+    // <-- {"result": "hello world"}
+    async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
+        JsonResult::Resp(jsonresp(json!("hello world"), id))
+    }
+}
+
+#[async_std::main]
+async fn main() -> Result<()> {
+    //let args = CliDao::parse();
+
+    //let matches = CliDao::into_app().get_matches();
+
+    TermLogger::init(
+        LevelFilter::Debug,
+        simplelog::Config::default(),
+        TerminalMode::Mixed,
+        ColorChoice::Auto,
+    )?;
+
+    //let rpc_addr = "tcp:://127.0.0.1:7777";
+    //let client = Arc::new(Client::new(rpc_addr.to_string()));
+
+    let nthreads = num_cpus::get();
+    let (signal, shutdown) = async_channel::unbounded::<()>();
+    let ex = Arc::new(Executor::new());
+    //let ex2 = ex.clone();
+    let ex3 = ex.clone();
+    let (_, result) = Parallel::new()
+        .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
+        .finish(|| {
+            smol::future::block_on(async move {
+                start(ex3.clone()).await?;
+                //client.run_client(client.clone(), ex2.clone()).await?;
+                drop(signal);
+                Ok::<(), darkfi::Error>(())
+            })
+        });
+
+    result
+}

+ 19 - 0
src/cli/cli_parser.rs

@@ -83,6 +83,13 @@ pub enum CliDrkSubCommands {
     },
     },
 }
 }
 
 
+#[derive(Subcommand)]
+pub enum CliDaoSubCommands {
+    /// Say hello to the RPC
+    Hello {}
+}
+
+
 /// Drk cli
 /// Drk cli
 #[derive(Parser)]
 #[derive(Parser)]
 #[clap(name = "drk")]
 #[clap(name = "drk")]
@@ -157,3 +164,15 @@ pub struct CliIrcd {
     #[clap(short, parse(from_occurrences))]
     #[clap(short, parse(from_occurrences))]
     pub verbose: u8,
     pub verbose: u8,
 }
 }
+
+/// DAO cli
+#[derive(Parser)]
+#[clap(name = "dao")]
+pub struct CliDao {
+    /// Increase verbosity
+    #[clap(short, parse(from_occurrences))]
+    pub verbose: u8,
+    #[clap(subcommand)]
+    pub command: Option<CliDaoSubCommands>,
+}
+

+ 1 - 1
src/cli/mod.rs

@@ -3,4 +3,4 @@ pub mod cli_parser;
 
 
 pub use cli_config::{CashierdConfig, Config, DarkfidConfig, DrkConfig, GatewaydConfig};
 pub use cli_config::{CashierdConfig, Config, DarkfidConfig, DrkConfig, GatewaydConfig};
 
 
-pub use cli_parser::{CliCashierd, CliDarkfid, CliDrk, CliDrkSubCommands, CliGatewayd, CliIrcd};
+pub use cli_parser::{CliCashierd, CliDarkfid, CliDrk, CliDrkSubCommands, CliGatewayd, CliIrcd, CliDao, CliDaoSubCommands};