Răsfoiți Sursa

genev: Update to new RPC dependencies.

parazyd 3 ani în urmă
părinte
comite
b473599b9b

+ 3 - 3
bin/genev/genev-cli/Cargo.toml

@@ -9,6 +9,8 @@ homepage = "https://dark.fi"
 repository = "https://github.com/darkrenaissance/darkfi"
 
 [dependencies]
+genevd = {path = "../genevd"}
+
 darkfi = {path = "../../../", features = ["event-graph", "rpc", "bs58"]}
 darkfi-serial = {path = "../../../src/serial"}
 
@@ -17,7 +19,5 @@ clap = {version = "4.3.22", features = ["derive"]}
 libsqlite3-sys = {version = "0.26.0", features = ["bundled-sqlcipher-vendored-openssl"]}
 log = "0.4.20"
 simplelog = "0.12.1"
-serde = {version = "1.0.183", features = ["derive"]}
-serde_json = "1.0.105"
+tinyjson = "2.5.1"
 url = "2.4.0"
-

+ 7 - 15
bin/genev/genev-cli/src/main.rs

@@ -17,28 +17,18 @@
  */
 
 use clap::{Parser, Subcommand};
-
-use darkfi_serial::{SerialDecodable, SerialEncodable};
-use serde::Serialize;
-use simplelog::{ColorChoice, TermLogger, TerminalMode};
-use url::Url;
-
 use darkfi::{
     rpc::client::RpcClient,
     util::cli::{get_log_config, get_log_level},
     Result,
 };
+use simplelog::{ColorChoice, TermLogger, TerminalMode};
+use url::Url;
 
-use crate::rpc::Gen;
+use genevd::GenEvent;
 
 mod rpc;
-
-#[derive(SerialEncodable, SerialDecodable, Debug, Serialize)]
-pub struct BaseEvent {
-    pub nick: String,
-    pub title: String,
-    pub text: String,
-}
+use rpc::Gen;
 
 #[derive(Parser)]
 #[clap(name = "genev", version)]
@@ -76,13 +66,15 @@ async fn main() -> Result<()> {
     match args.command {
         Some(subcmd) => match subcmd {
             SubCmd::Add { values } => {
-                let event = BaseEvent {
+                let event = GenEvent {
                     nick: values[0].clone(),
                     title: values[1].clone(),
                     text: values[2..].join(" "),
                 };
+
                 return gen.add(event).await
             }
+
             SubCmd::List => {
                 let events = gen.list().await?;
                 for event in events {

+ 13 - 11
bin/genev/genev-cli/src/rpc.rs

@@ -16,16 +16,16 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
-use log::debug;
-use serde_json::json;
-
 use darkfi::{
     event_graph::model::Event,
     rpc::{client::RpcClient, jsonrpc::JsonRequest},
+    util::encoding::base64,
     Result,
 };
-
-use crate::BaseEvent;
+use darkfi_serial::{deserialize, serialize};
+use genevd::GenEvent;
+use log::debug;
+use tinyjson::JsonValue;
 
 pub struct Gen {
     pub rpc_client: RpcClient,
@@ -37,8 +37,10 @@ impl Gen {
     }
 
     /// Add a new task.
-    pub async fn add(&self, event: BaseEvent) -> Result<()> {
-        let req = JsonRequest::new("add", json!([event]));
+    pub async fn add(&self, event: GenEvent) -> Result<()> {
+        let event = JsonValue::String(base64::encode(&serialize(&event)));
+
+        let req = JsonRequest::new("add", JsonValue::from(vec![event]));
         let rep = self.rpc_client.request(req).await?;
 
         debug!("Got reply: {:?}", rep);
@@ -46,14 +48,14 @@ impl Gen {
     }
 
     /// Get current open tasks ids.
-    pub async fn list(&self) -> Result<Vec<Event<BaseEvent>>> {
-        let req = JsonRequest::new("list", json!([]));
+    pub async fn list(&self) -> Result<Vec<Event<GenEvent>>> {
+        let req = JsonRequest::new("list", JsonValue::from(vec![]));
         let rep = self.rpc_client.request(req).await?;
 
         debug!("reply: {:?}", rep);
 
-        let bytes: Vec<u8> = serde_json::from_value(rep)?;
-        let events: Vec<Event<BaseEvent>> = darkfi_serial::deserialize(&bytes)?;
+        let bytes: Vec<u8> = base64::decode(rep.get::<String>().unwrap()).unwrap();
+        let events: Vec<Event<GenEvent>> = deserialize(&bytes)?;
 
         Ok(events)
     }

+ 9 - 1
bin/genev/genevd/Cargo.toml

@@ -8,6 +8,14 @@ license = "AGPL-3.0-only"
 homepage = "https://dark.fi"
 repository = "https://github.com/darkrenaissance/darkfi"
 
+[lib]
+name = "genevd"
+path = "src/lib.rs"
+
+[[bin]]
+name = "genevd"
+path = "src/main.rs"
+
 [dependencies]
 darkfi = {path = "../../../", features = ["event-graph", "rpc", "bs58", "util"]}
 darkfi-serial = {path = "../../../src/serial"}
@@ -16,7 +24,7 @@ darkfi-serial = {path = "../../../src/serial"}
 async-trait = "0.1.73"
 libsqlite3-sys = {version = "0.26.0", features = ["bundled-sqlcipher-vendored-openssl"]}
 log = "0.4.20"
-serde_json = "1.0.105"
+tinyjson = "2.5.1"
 url = "2.4.0"
 
 # Daemon

+ 0 - 0
bin/genev/genevd/src/genevent.rs → bin/genev/genevd/src/lib.rs


+ 5 - 10
bin/genev/genevd/src/main.rs

@@ -20,10 +20,6 @@ use async_std::{
     stream::StreamExt,
     sync::{Arc, Mutex},
 };
-
-use log::info;
-use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
-
 use darkfi::{
     async_daemonize, cli_desc,
     event_graph::{
@@ -36,14 +32,13 @@ use darkfi::{
     rpc::server::listen_and_serve,
     Result,
 };
-
-mod genevent;
-mod rpc;
-
-use genevent::GenEvent;
+use genevd::GenEvent;
+use log::info;
+use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
 use url::Url;
 
-use crate::rpc::JsonRpcInterface;
+mod rpc;
+use rpc::JsonRpcInterface;
 
 const CONFIG_FILE: &str = "genev_config.toml";
 const CONFIG_FILE_CONTENTS: &str = include_str!("../../genev_config.toml");

+ 31 - 48
bin/genev/genevd/src/rpc.rs

@@ -19,7 +19,7 @@
 use async_std::sync::{Arc, Mutex};
 use async_trait::async_trait;
 use log::debug;
-use serde_json::{json, Value};
+use tinyjson::JsonValue;
 
 use darkfi::{
     event_graph::{
@@ -31,10 +31,10 @@ use darkfi::{
         jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
         server::RequestHandler,
     },
-    util::time::Timestamp,
+    util::{encoding::base64, time::Timestamp},
 };
-
-use crate::genevent::GenEvent;
+use darkfi_serial::deserialize;
+use genevd::GenEvent;
 
 pub struct JsonRpcInterface {
     _nickname: String,
@@ -47,17 +47,13 @@ pub struct JsonRpcInterface {
 #[async_trait]
 impl RequestHandler for JsonRpcInterface {
     async fn handle_request(&self, req: JsonRequest) -> JsonResult {
-        if !req.params.is_array() {
-            return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
-        }
-
         match req.method.as_str() {
-            Some("add") => self.add(req.id, req.params).await,
-            Some("list") => self.list(req.id, req.params).await,
-            Some("ping") => self.pong(req.id, req.params).await,
-            Some("dnet_switch") => self.dnet_switch(req.id, req.params).await,
-            Some("dnet_info") => self.dnet_info(req.id, req.params).await,
-            Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
+            "add" => self.add(req.id, req.params).await,
+            "list" => self.list(req.id, req.params).await,
+
+            "ping" => self.pong(req.id, req.params).await,
+            "dnet_switch" => self.dnet_switch(req.id, req.params).await,
+            _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
         }
     }
 }
@@ -73,14 +69,6 @@ impl JsonRpcInterface {
         Self { _nickname, missed_events, model, seen, p2p }
     }
 
-    // RPCAPI:
-    // Replies to a ping method.
-    // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
-    async fn pong(&self, id: Value, _params: Value) -> JsonResult {
-        JsonResponse::new(json!("pong"), id).into()
-    }
-
     // RPCAPI:
     // Activate or deactivate dnet in the P2P stack.
     // By sending `true`, dnet will be activated, and by sending `false` dnet
@@ -88,41 +76,36 @@ impl JsonRpcInterface {
     //
     // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
     // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    async fn dnet_switch(&self, id: Value, params: Value) -> JsonResult {
-        let params = params.as_array().unwrap();
-
-        if params.len() != 1 && params[0].as_bool().is_none() {
+    async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
+        let params = params.get::<Vec<JsonValue>>().unwrap();
+        if params.len() != 1 || !params[0].is_bool() {
             return JsonError::new(ErrorCode::InvalidParams, None, id).into()
         }
 
-        if params[0].as_bool().unwrap() {
+        let switch = params[0].get::<bool>().unwrap();
+
+        if *switch {
             self.p2p.dnet_enable().await;
         } else {
             self.p2p.dnet_disable().await;
         }
 
-        JsonResponse::new(json!(true), id).into()
-    }
-
-    // RPCAPI:
-    // Retrieves P2P network information.
-    // --> {"jsonrpc": "2.0", "method": "dnet_info", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
-    async fn dnet_info(&self, id: Value, _params: Value) -> JsonResult {
-        let dnet_info = self.p2p.dnet_info().await;
-        JsonResponse::new(net::P2p::map_dnet_info(dnet_info), id).into()
+        JsonResponse::new(JsonValue::Boolean(true), id).into()
     }
 
     // RPCAPI:
     // Add a new event
     // --> {"jsonrpc": "2.0", "method": "add", "params": [], "id": 1}
     // <-- {"jsonrpc": "2.0", "result": [nickname, ...], "id": 1}
-    async fn add(&self, id: Value, params: Value) -> JsonResult {
-        let genevent = GenEvent {
-            nick: params[0].get("nick").unwrap().to_string(),
-            title: params[0].get("title").unwrap().to_string(),
-            text: params[0].get("text").unwrap().to_string(),
-        };
+    async fn add(&self, id: u16, params: JsonValue) -> JsonResult {
+        let params = params.get::<Vec<JsonValue>>().unwrap();
+        if params.len() != 1 || !params[0].is_string() {
+            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
+        }
+
+        let b64 = params[0].get::<String>().unwrap();
+        let dec = base64::decode(&b64).unwrap();
+        let genevent: GenEvent = deserialize(&dec).unwrap();
 
         let event = Event {
             previous_event_hash: self.model.lock().await.get_head_hash(),
@@ -131,13 +114,13 @@ impl JsonRpcInterface {
         };
 
         if !self.seen.push(&event.hash()).await {
-            let json = json!(false);
+            let json = JsonValue::Boolean(false);
             return JsonResponse::new(json, id).into()
         }
 
         self.p2p.broadcast(&event).await;
 
-        let json = json!(true);
+        let json = JsonValue::Boolean(true);
         JsonResponse::new(json, id).into()
     }
 
@@ -145,13 +128,13 @@ impl JsonRpcInterface {
     // List events
     // --> {"jsonrpc": "2.0", "method": "list", "params": [], "id": 1}
     // <-- {"jsonrpc": "2.0", "result": [task_id, ...], "id": 1}
-    async fn list(&self, id: Value, _params: Value) -> JsonResult {
+    async fn list(&self, id: u16, _params: JsonValue) -> JsonResult {
         debug!("fetching all events");
         let msd = self.missed_events.lock().await.clone();
 
         let ser = darkfi_serial::serialize(&msd);
+        let enc = JsonValue::String(base64::encode(&ser));
 
-        let json = json!(ser);
-        JsonResponse::new(json, id).into()
+        JsonResponse::new(enc, id).into()
     }
 }