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

fud: update default ports, move management rpc methods to another rpc server

epiphany 7 месяцев назад
Родитель
Сommit
1f8445bbf4

+ 1 - 1
bin/dnet/dnet_config.toml

@@ -13,7 +13,7 @@
 #[[nodes]]
 #name = "fud"
 #host = "localhost"
-#port = 13336
+#port = 9706
 #type = "NORMAL"
 
 #[[nodes]]

+ 1 - 1
bin/fud/fu/src/main.rs

@@ -58,7 +58,7 @@ struct Args {
     /// Increase verbosity (-vvv supported)
     verbose: u8,
 
-    #[clap(short, long, default_value = "tcp://127.0.0.1:13336")]
+    #[clap(short, long, default_value = "tcp://127.0.0.1:9705")]
     /// fud JSON-RPC endpoint
     endpoint: Url,
 

+ 30 - 22
bin/fud/fud/fud_config.toml

@@ -60,10 +60,18 @@ btc_electrum_nodes = [
 # JSON-RPC settings
 [rpc]
 # JSON-RPC listen URL
-rpc_listen = "tcp://127.0.0.1:13336"
+rpc_listen = "tcp://127.0.0.1:9705"
 
 # Disabled RPC methods
-rpc_disabled_methods = ["p2p.get_info"]
+#rpc_disabled_methods = []
+
+# Management JSON-RPC settings
+[management_rpc]
+# JSON-RPC listen URL
+rpc_listen = "tcp://127.0.0.1:9706"
+
+# Disabled RPC methods
+#rpc_disabled_methods = []
 
 # P2P network settings
 [net]
@@ -92,7 +100,7 @@ hostlist = "~/.local/share/darkfi/fud/p2p_hostlist.tsv"
 # format ["host", ["scheme", "scheme"], [port, port]].
 # If scheme is left empty it will default to "tcp+tls".
 # If ports are left empty all ports from this peer will be blocked.
-#blacklist = [["example.com", ["tcp"], [8551, 23331]]]
+#blacklist = [["example.com", ["tcp"], [8551, 9700]]]
 
 # Whitelisted transports for outbound connections
 active_profiles = ["tor"]
@@ -115,36 +123,36 @@ active_profiles = ["tor"]
 [net.profiles."tcp+tls"]
 ## Seed nodes to connect to
 seeds = [
-    "tcp+tls://lilith0.dark.fi:24441",
-    "tcp+tls://lilith1.dark.fi:24441",
+    "tcp+tls://lilith0.dark.fi:9700",
+    "tcp+tls://lilith1.dark.fi:9700",
 ]
 
 ## Manual peers to connect to
 #peers = []
 
 ## P2P accept addresses
-#inbound = ["tcp+tls://0.0.0.0:24441", "tcp+tls://[::]:24441"]
+#inbound = ["tcp+tls://0.0.0.0:9700", "tcp+tls://[::]:9700"]
 
 ## Addresses we want to advertise to peers (optional)
 ## These should be reachable externally
-#external_addrs = ["tcp+tls://my.resolveable.address:24441"]
+#external_addrs = ["tcp+tls://my.resolveable.address:9700"]
 
 [net.profiles."tor"]
 ## Seed nodes to connect to
 seeds = [
-    "tor://g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:24442",
-    "tor://yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:24442",
+    "tor://g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:9701",
+    "tor://yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:9701",
 ]
 
 ## Manual peers to connect to
 #peers = []
 
 ## P2P accept addresses
-#inbound = ["tcp://127.0.0.1:24441"]
+#inbound = ["tcp://127.0.0.1:9701"]
 
 ## Addresses we want to advertise to peers (optional)
 ## These should be reachable externally
-#external_addrs = ["tor://youraddress.onion:24441"]
+#external_addrs = ["tor://youraddress.onion:9701"]
 
 [net.profiles."i2p"]
 ## Seed nodes to connect to
@@ -154,17 +162,17 @@ seeds = [
 #peers = []
 
 ## P2P accept addresses
-#inbound = ["tcp://127.0.0.1:24441"]
+#inbound = ["tcp://127.0.0.1:9702"]
 
 ## Addresses we want to advertise to peers (optional)
 ## These should be reachable externally
-#external_addrs = ["i2p://youraddress.b32.i2p:24441"]
+#external_addrs = ["i2p://youraddress.b32.i2p:9702"]
 
 [net.profiles."socks5"]
 ## Seed nodes to connect to
 seeds = [
-    "socks5://127.0.0.1:9050/g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:24442",
-    "socks5://127.0.0.1:9050/yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:24442",
+    "socks5://127.0.0.1:9050/g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:9701",
+    "socks5://127.0.0.1:9050/yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:9701",
 ]
 
 ## Manual peers to connect to
@@ -173,8 +181,8 @@ seeds = [
 [net.profiles."socks5+tls"]
 ## Seed nodes to connect to
 seeds = [
-    #"socks5+tls://127.0.0.1:9050/lilith0.dark.fi:24441",
-    #"socks5+tls://127.0.0.1:1080/lilith1.dark.fi:24441"
+    #"socks5+tls://127.0.0.1:9050/lilith0.dark.fi:9700",
+    #"socks5+tls://127.0.0.1:1080/lilith1.dark.fi:9700"
 ]
 
 ## Manual peers to connect to
@@ -183,8 +191,8 @@ seeds = [
 [net.profiles."tor+tls"]
 ## Seed nodes to connect to
 seeds = [
-    "tor+tls://lilith0.dark.fi:24441",
-    "tor+tls://lilith1.dark.fi:24441"
+    "tor+tls://lilith0.dark.fi:9700",
+    "tor+tls://lilith1.dark.fi:9700"
 ]
 
 ## Manual peers to connect to
@@ -192,13 +200,13 @@ seeds = [
 
 [net.profiles."tcp"]
 ## Seed nodes to connect to
-#seeds = ["tcp://127.0.0.1:24442"]
+#seeds = ["tcp://127.0.0.1:9700"]
 
 ## Manual peers to connect to
 #peers = []
 
 ## P2P accept addresses
-#inbound = ["tcp://127.0.0.1:24441"]
+#inbound = ["tcp://127.0.0.1:9700"]
 
 ## Addresses we want to advertise to peers
-#external_addrs = ["tcp://127.0.0.1:24441"]
+#external_addrs = ["tcp://127.0.0.1:9700"]

+ 27 - 5
bin/fud/fud/src/main.rs

@@ -39,7 +39,7 @@ use darkfi::{
 };
 use fud::{
     proto::ProtocolFud,
-    rpc::JsonRpcInterface,
+    rpc::{management::ManagementRpcInterface, DefaultRpcInterface},
     settings::{Args, CONFIG_FILE, CONFIG_FILE_CONTENTS},
     Fud,
 };
@@ -117,8 +117,8 @@ async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
     );
 
     let rpc_settings: RpcSettings = args.rpc.into();
-    info!(target: "fud", "Starting JSON-RPC server on {}", rpc_settings.listen);
-    let rpc_interface = Arc::new(JsonRpcInterface::new(fud.clone(), dnet_sub, event_sub));
+    info!(target: "fud", "Starting main JSON-RPC server on {}", rpc_settings.listen);
+    let rpc_interface = Arc::new(DefaultRpcInterface::new(fud.clone(), event_sub));
     let rpc_task = StoppableTask::new();
     let rpc_interface_ = rpc_interface.clone();
     rpc_task.clone().start(
@@ -126,7 +126,26 @@ async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
         |res| async move {
             match res {
                 Ok(()) | Err(Error::RpcServerStopped) => rpc_interface_.stop_connections().await,
-                Err(e) => error!(target: "fud", "Failed starting sync JSON-RPC server: {e}"),
+                Err(e) => error!(target: "fud", "Failed starting main JSON-RPC server: {e}"),
+            }
+        },
+        Error::RpcServerStopped,
+        ex.clone(),
+    );
+
+    let management_rpc_settings: RpcSettings = args.management_rpc.into();
+    info!(target: "fud", "Starting management JSON-RPC server on {}", management_rpc_settings.listen);
+    let management_rpc_interface = Arc::new(ManagementRpcInterface::new(fud.clone(), dnet_sub));
+    let management_rpc_task = StoppableTask::new();
+    let management_rpc_interface_ = management_rpc_interface.clone();
+    management_rpc_task.clone().start(
+        listen_and_serve(management_rpc_settings, management_rpc_interface, None, ex.clone()),
+        |res| async move {
+            match res {
+                Ok(()) | Err(Error::RpcServerStopped) => {
+                    management_rpc_interface_.stop_connections().await
+                }
+                Err(e) => error!(target: "fud", "Failed starting management JSON-RPC server: {e}"),
             }
         },
         Error::RpcServerStopped,
@@ -164,9 +183,12 @@ async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
 
     fud.stop().await;
 
-    info!(target: "fud", "Stopping JSON-RPC server...");
+    info!(target: "fud", "Stopping main JSON-RPC server...");
     rpc_task.stop().await;
 
+    info!(target: "fud", "Stopping management JSON-RPC server...");
+    management_rpc_task.stop().await;
+
     info!(target: "fud", "Stopping P2P network...");
     p2p.stop().await;
 

+ 135 - 0
bin/fud/fud/src/rpc/management.rs

@@ -0,0 +1,135 @@
+/* This file is part of DarkFi (https://dark.fi)
+ *
+ * Copyright (C) 2020-2026 Dyne.org foundation
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+use std::{collections::HashSet, sync::Arc};
+
+use async_trait::async_trait;
+use smol::lock::{Mutex, MutexGuard};
+use tinyjson::JsonValue;
+use tracing::debug;
+
+use darkfi::{
+    net::P2pPtr,
+    rpc::{
+        jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult, JsonSubscriber},
+        p2p_method::HandlerP2p,
+        server::RequestHandler,
+    },
+    system::StoppableTaskPtr,
+};
+
+use crate::Fud;
+
+pub struct ManagementRpcInterface {
+    fud: Arc<Fud>,
+    rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
+    dnet_sub: JsonSubscriber,
+}
+
+#[async_trait]
+impl RequestHandler<()> for ManagementRpcInterface {
+    async fn handle_request(&self, req: JsonRequest) -> JsonResult {
+        debug!(target: "fud::rpc::management_rpc", "--> {}", req.stringify().unwrap());
+
+        match req.method.as_str() {
+            "ping" => self.pong(req.id, req.params).await,
+            "dnet.switch" => self.dnet_switch(req.id, req.params).await,
+            "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
+            "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
+            _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
+        }
+    }
+
+    async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
+        self.rpc_connections.lock().await
+    }
+}
+
+impl HandlerP2p for ManagementRpcInterface {
+    fn p2p(&self) -> P2pPtr {
+        self.fud.p2p.clone()
+    }
+}
+
+/// Fud management RPC methods
+impl ManagementRpcInterface {
+    pub fn new(fud: Arc<Fud>, dnet_sub: JsonSubscriber) -> Self {
+        Self { fud, rpc_connections: Mutex::new(HashSet::new()), dnet_sub }
+    }
+
+    // RPCAPI:
+    // Activate or deactivate dnet in the P2P stack.
+    // By sending `true`, dnet will be activated, and by sending `false` dnet
+    // will be deactivated.
+    //
+    // Returns `true` on success.
+    //
+    // --> {"jsonrpc": "2.0", "method": "dnet.switch", "params": [true], "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
+    pub async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
+        let Some(params) = params.get::<Vec<JsonValue>>() else {
+            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
+        };
+        if params.len() != 1 || !params[0].is_bool() {
+            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
+        }
+
+        let switch = params[0].get::<bool>().unwrap();
+
+        if *switch {
+            self.fud.p2p.dnet_enable();
+        } else {
+            self.fud.p2p.dnet_disable();
+        }
+
+        JsonResponse::new(JsonValue::Boolean(true), id).into()
+    }
+
+    // RPCAPI:
+    // Initializes a subscription to P2P dnet events.
+    // Once a subscription is established, `fud` will send JSON-RPC
+    // notifications of new network events to the subscriber.
+    //
+    // --> {
+    //       "jsonrpc": "2.0",
+    //       "method": "dnet.subscribe_events",
+    //       "params": [],
+    //       "id": 1
+    //     }
+    // <-- {
+    //       "jsonrpc": "2.0",
+    //       "method": "dnet.subscribe_events",
+    //       "params": [
+    //         {
+    //           "chan": {"Channel": "Info"},
+    //           "cmd": "command",
+    //           "time": 1767016282
+    //         }
+    //       ]
+    //     }
+    pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
+        let Some(params) = params.get::<Vec<JsonValue>>() else {
+            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
+        };
+        if !params.is_empty() {
+            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
+        }
+
+        self.dnet_sub.clone().into()
+    }
+}

+ 16 - 56
bin/fud/fud/src/rpc.rs → bin/fud/fud/src/rpc/mod.rs

@@ -16,13 +16,14 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
-use async_trait::async_trait;
-use smol::lock::{Mutex, MutexGuard};
 use std::{
     collections::{HashMap, HashSet},
     path::PathBuf,
     sync::Arc,
 };
+
+use async_trait::async_trait;
+use smol::lock::{Mutex, MutexGuard};
 use tinyjson::JsonValue;
 use tracing::error;
 
@@ -42,15 +43,17 @@ use darkfi::{
 
 use crate::{util::FileSelection, Fud};
 
-pub struct JsonRpcInterface {
+/// Management JSON-RPC
+pub mod management;
+
+pub struct DefaultRpcInterface {
     fud: Arc<Fud>,
     rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
-    dnet_sub: JsonSubscriber,
     event_sub: JsonSubscriber,
 }
 
 #[async_trait]
-impl RequestHandler<()> for JsonRpcInterface {
+impl RequestHandler<()> for DefaultRpcInterface {
     async fn handle_request(&self, req: JsonRequest) -> JsonResult {
         return match req.method.as_str() {
             "ping" => self.pong(req.id, req.params).await,
@@ -65,9 +68,6 @@ impl RequestHandler<()> for JsonRpcInterface {
             "verify" => self.verify(req.id, req.params).await,
             "lookup" => self.lookup(req.id, req.params).await,
 
-            "dnet.switch" => self.dnet_switch(req.id, req.params).await,
-            "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
-            "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
             _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
         }
     }
@@ -77,16 +77,16 @@ impl RequestHandler<()> for JsonRpcInterface {
     }
 }
 
-impl HandlerP2p for JsonRpcInterface {
+impl HandlerP2p for DefaultRpcInterface {
     fn p2p(&self) -> P2pPtr {
         self.fud.p2p.clone()
     }
 }
 
 /// Fud RPC methods
-impl JsonRpcInterface {
-    pub fn new(fud: Arc<Fud>, dnet_sub: JsonSubscriber, event_sub: JsonSubscriber) -> Self {
-        Self { fud, rpc_connections: Mutex::new(HashSet::new()), dnet_sub, event_sub }
+impl DefaultRpcInterface {
+    pub fn new(fud: Arc<Fud>, event_sub: JsonSubscriber) -> Self {
+        Self { fud, rpc_connections: Mutex::new(HashSet::new()), event_sub }
     }
 
     // RPCAPI:
@@ -192,51 +192,11 @@ impl JsonRpcInterface {
         self.event_sub.clone().into()
     }
 
-    // RPCAPI:
-    // Activate or deactivate dnet in the P2P stack.
-    // By sending `true`, dnet will be activated, and by sending `false` dnet
-    // will be deactivated. Returns `true` on success.
-    //
-    // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    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()
-        }
-
-        let switch = params[0].get::<bool>().unwrap();
-
-        if *switch {
-            self.fud.p2p.dnet_enable();
-        } else {
-            self.fud.p2p.dnet_disable();
-        }
-
-        JsonResponse::new(JsonValue::Boolean(true), id).into()
-    }
-
-    // RPCAPI:
-    // Initializes a subscription to p2p dnet events.
-    // Once a subscription is established, `fud` will send JSON-RPC notifications of
-    // new network events to the subscriber.
-    //
-    // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
-    // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
-    pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
-        let params = params.get::<Vec<JsonValue>>().unwrap();
-        if !params.is_empty() {
-            return JsonError::new(ErrorCode::InvalidParams, None, id).into()
-        }
-
-        self.dnet_sub.clone().into()
-    }
-
     // RPCAPI:
     // Returns resources.
     //
     // --> {"jsonrpc": "2.0", "method": "list_buckets", "params": [], "id": 1}
-    // <-- {"jsonrpc": "2.0", "result": [[["abcdef", ["tcp://127.0.0.1:13337"]]]], "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": [[["abcdef", ["tcp://127.0.0.1:9700"]]]], "id": 1}
     pub async fn list_resources(&self, id: u16, params: JsonValue) -> JsonResult {
         let params = params.get::<Vec<JsonValue>>().unwrap();
         if !params.is_empty() {
@@ -256,7 +216,7 @@ impl JsonRpcInterface {
     // Returns the current buckets.
     //
     // --> {"jsonrpc": "2.0", "method": "list_buckets", "params": [], "id": 1}
-    // <-- {"jsonrpc": "2.0", "result": [["abcdef", ["tcp://127.0.0.1:13337"]]], "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": [["abcdef", ["tcp://127.0.0.1:9700"]]], "id": 1}
     pub async fn list_buckets(&self, id: u16, params: JsonValue) -> JsonResult {
         let params = params.get::<Vec<JsonValue>>().unwrap();
         if !params.is_empty() {
@@ -285,7 +245,7 @@ impl JsonRpcInterface {
     // Returns the content of the seeders router.
     //
     // --> {"jsonrpc": "2.0", "method": "list_seeders", "params": [], "id": 1}
-    // <-- {"jsonrpc": "2.0", "result": {"seeders": {"abcdefileid": [["abcdef", ["tcp://127.0.0.1:13337"]]]}}, "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": {"seeders": {"abcdefileid": [["abcdef", ["tcp://127.0.0.1:9700"]]]}}, "id": 1}
     pub async fn list_seeders(&self, id: u16, params: JsonValue) -> JsonResult {
         let params = params.get::<Vec<JsonValue>>().unwrap();
         if !params.is_empty() {
@@ -376,7 +336,7 @@ impl JsonRpcInterface {
     // Lookup a resource's seeders.
     //
     // --> {"jsonrpc": "2.0", "method": "lookup", "params": ["1211...abfd"], "id": 1}
-    // <-- {"jsonrpc": "2.0", "result": {"seeders": {"abcdefileid": [["abcdef", ["tcp://127.0.0.1:13337"]]]}}, "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": {"seeders": {"abcdefileid": [["abcdef", ["tcp://127.0.0.1:9701"]]]}}, "id": 1}
     pub async fn lookup(&self, id: u16, params: JsonValue) -> JsonResult {
         let params = params.get::<Vec<JsonValue>>().unwrap();
         if params.len() != 1 || !params[0].is_string() {

+ 5 - 1
bin/fud/fud/src/settings.rs

@@ -61,9 +61,13 @@ pub struct Args {
     pub net: SettingsOpt,
 
     #[structopt(flatten)]
-    /// JSON-RPC settings
+    /// Main JSON-RPC settings
     pub rpc: RpcSettingsOpt,
 
+    #[structopt(flatten)]
+    /// Management JSON-RPC settings
+    pub management_rpc: RpcSettingsOpt,
+
     #[structopt(flatten)]
     /// DHT settings
     pub dht: DhtSettingsOpt,