1use std::{collections::HashSet, sync::Arc};
20
21use async_trait::async_trait;
22use smol::lock::{Mutex, MutexGuard};
23use tinyjson::JsonValue;
24use tracing::debug;
25
26use darkfi::{
27 net::P2pPtr,
28 rpc::{
29 jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult, JsonSubscriber},
30 p2p_method::HandlerP2p,
31 server::RequestHandler,
32 },
33 system::StoppableTaskPtr,
34};
35
36use crate::Fud;
37
38pub struct ManagementRpcInterface {
39 fud: Arc<Fud>,
40 rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
41 dnet_sub: JsonSubscriber,
42}
43
44#[async_trait]
45impl RequestHandler<()> for ManagementRpcInterface {
46 async fn handle_request(&self, req: JsonRequest) -> JsonResult {
47 debug!(target: "fud::rpc::management_rpc", "--> {}", req.stringify().unwrap());
48
49 match req.method.as_str() {
50 "ping" => self.pong(req.id, req.params).await,
51 "dnet.switch" => self.dnet_switch(req.id, req.params).await,
52 "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
53 "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
54 _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
55 }
56 }
57
58 async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
59 self.rpc_connections.lock().await
60 }
61}
62
63impl HandlerP2p for ManagementRpcInterface {
64 fn p2p(&self) -> P2pPtr {
65 self.fud.p2p.clone()
66 }
67}
68
69impl ManagementRpcInterface {
71 pub fn new(fud: Arc<Fud>, dnet_sub: JsonSubscriber) -> Self {
72 Self { fud, rpc_connections: Mutex::new(HashSet::new()), dnet_sub }
73 }
74
75 pub async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
85 let Some(params) = params.get::<Vec<JsonValue>>() else {
86 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
87 };
88 if params.len() != 1 || !params[0].is_bool() {
89 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
90 }
91
92 let switch = params[0].get::<bool>().unwrap();
93
94 if *switch {
95 self.fud.p2p.dnet_enable();
96 } else {
97 self.fud.p2p.dnet_disable();
98 }
99
100 JsonResponse::new(JsonValue::Boolean(true), id).into()
101 }
102
103 pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
126 let Some(params) = params.get::<Vec<JsonValue>>() else {
127 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
128 };
129 if !params.is_empty() {
130 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
131 }
132
133 self.dnet_sub.clone().into()
134 }
135}