rpc.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::collections::HashSet;
  19. use async_trait::async_trait;
  20. use darkfi::{
  21. event_graph::util::recreate_from_replayer_log,
  22. net::P2pPtr,
  23. rpc::{
  24. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  25. p2p_method::HandlerP2p,
  26. server::RequestHandler,
  27. util::JsonValue,
  28. },
  29. system::StoppableTaskPtr,
  30. };
  31. use smol::lock::MutexGuard;
  32. use tracing::debug;
  33. use super::DarkIrc;
  34. #[async_trait]
  35. impl RequestHandler<()> for DarkIrc {
  36. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  37. debug!(target: "darkirc::rpc", "--> {}", req.stringify().unwrap());
  38. match req.method.as_str() {
  39. "ping" => self.pong(req.id, req.params).await,
  40. "dnet.switch" => self.dnet_switch(req.id, req.params).await,
  41. "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
  42. "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
  43. "p2p.set_outbound_connections" => {
  44. self.set_outbound_connections(req.id, req.params).await
  45. }
  46. "deg.switch" => self.deg_switch(req.id, req.params).await,
  47. "deg.subscribe_events" => self.deg_subscribe_events(req.id, req.params).await,
  48. "eventgraph.get_info" => self.eg_get_info(req.id, req.params).await,
  49. "eventgraph.replay" => self.eg_rep_info(req.id, req.params).await,
  50. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  51. }
  52. }
  53. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  54. self.rpc_connections.lock().await
  55. }
  56. }
  57. impl DarkIrc {
  58. // RPCAPI:
  59. // Activate or deactivate dnet in the P2P stack.
  60. // By sending `true`, dnet will be activated, and by sending `false` dnet
  61. // will be deactivated. Returns `true` on success.
  62. //
  63. // --> {"jsonrpc": "2.0", "method": "dnet.switch", "params": [true], "id": 42}
  64. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  65. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  66. let Some(params) = params.get::<Vec<JsonValue>>() else {
  67. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  68. };
  69. if params.len() != 1 || !params[0].is_bool() {
  70. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  71. }
  72. let switch = params[0].get::<bool>().unwrap();
  73. if *switch {
  74. self.p2p.dnet_enable();
  75. } else {
  76. self.p2p.dnet_disable();
  77. }
  78. JsonResponse::new(JsonValue::Boolean(true), id).into()
  79. }
  80. // RPCAPI:
  81. // Set the number of outbound connections for the P2P stack.
  82. // Takes a positive integer representing the desired number of outbound connection slots.
  83. // Returns `true` on success. If the number is greater than current, new slots are added.
  84. // If the number is less than current, slots are removed (prioritizing empty slots).
  85. //
  86. // --> {"jsonrpc": "2.0", "method": "p2p.set_outbound_connections", "params": [5], "id": 42}
  87. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  88. async fn set_outbound_connections(&self, id: u16, params: JsonValue) -> JsonResult {
  89. let Some(params) = params.get::<Vec<JsonValue>>() else {
  90. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  91. };
  92. if params.len() != 1 || !params[0].is_number() {
  93. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  94. }
  95. let n_f64 = params[0].get::<f64>().unwrap();
  96. let n = *n_f64 as u32;
  97. if *n_f64 != n as f64 || n == 0 {
  98. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  99. }
  100. if let Err(e) = self.p2p.session_outbound().set_outbound_connections(n as usize).await {
  101. return JsonError::new(ErrorCode::InternalError, Some(e.to_string()), id).into()
  102. }
  103. JsonResponse::new(JsonValue::Boolean(true), id).into()
  104. }
  105. // RPCAPI:
  106. // Initializes a subscription to p2p dnet events.
  107. // Once a subscription is established, `darkirc` will send JSON-RPC notifications of
  108. // new network events to the subscriber.
  109. //
  110. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  111. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  112. pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  113. let Some(params) = params.get::<Vec<JsonValue>>() else {
  114. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  115. };
  116. if !params.is_empty() {
  117. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  118. }
  119. self.dnet_sub.clone().into()
  120. }
  121. // RPCAPI:
  122. // Initializes a subscription to deg events.
  123. // Once a subscription is established, apps using eventgraph will send JSON-RPC notifications of
  124. // new eventgraph events to the subscriber.
  125. //
  126. // --> {"jsonrpc": "2.0", "method": "deg.subscribe_events", "params": [], "id": 1}
  127. // <-- {"jsonrpc": "2.0", "method": "deg.subscribe_events", "params": [`event`]}
  128. pub async fn deg_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  129. let Some(params) = params.get::<Vec<JsonValue>>() else {
  130. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  131. };
  132. if !params.is_empty() {
  133. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  134. }
  135. self.deg_sub.clone().into()
  136. }
  137. // RPCAPI:
  138. // Activate or deactivate deg in the EVENTGRAPH.
  139. // By sending `true`, deg will be activated, and by sending `false` deg
  140. // will be deactivated. Returns `true` on success.
  141. //
  142. // --> {"jsonrpc": "2.0", "method": "deg.switch", "params": [true], "id": 42}
  143. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  144. async fn deg_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  145. let Some(params) = params.get::<Vec<JsonValue>>() else {
  146. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  147. };
  148. if params.len() != 1 || !params[0].is_bool() {
  149. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  150. }
  151. let switch = params[0].get::<bool>().unwrap();
  152. if *switch {
  153. self.event_graph.deg_enable().await;
  154. } else {
  155. self.event_graph.deg_disable().await;
  156. }
  157. JsonResponse::new(JsonValue::Boolean(true), id).into()
  158. }
  159. // RPCAPI:
  160. // Get EVENTGRAPH info.
  161. //
  162. // --> {"jsonrpc": "2.0", "method": "deg.switch", "params": [true], "id": 42}
  163. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  164. async fn eg_get_info(&self, id: u16, params: JsonValue) -> JsonResult {
  165. let Some(params_) = params.get::<Vec<JsonValue>>() else {
  166. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  167. };
  168. if !params_.is_empty() {
  169. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  170. }
  171. self.event_graph.eventgraph_info(id, params).await
  172. }
  173. // RPCAPI:
  174. // Get replayed EVENTGRAPH info.
  175. //
  176. // --> {"jsonrpc": "2.0", "method": "eventgraph.replay", "params": ..., "id": 42}
  177. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  178. async fn eg_rep_info(&self, id: u16, params: JsonValue) -> JsonResult {
  179. let Some(params_) = params.get::<Vec<JsonValue>>() else {
  180. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  181. };
  182. if !params_.is_empty() {
  183. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  184. }
  185. recreate_from_replayer_log(&self.replay_datastore).await
  186. }
  187. }
  188. impl HandlerP2p for DarkIrc {
  189. fn p2p(&self) -> P2pPtr {
  190. self.p2p.clone()
  191. }
  192. }