rpc.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 log::debug;
  21. use smol::lock::MutexGuard;
  22. use darkfi::{
  23. net::P2pPtr,
  24. rpc::{
  25. jsonrpc::{
  26. ErrorCode::{InvalidParams, MethodNotFound},
  27. JsonError, JsonRequest, JsonResponse, JsonResult,
  28. },
  29. p2p_method::HandlerP2p,
  30. server::RequestHandler,
  31. util::JsonValue,
  32. },
  33. system::StoppableTaskPtr,
  34. };
  35. use crate::DamNode;
  36. #[async_trait]
  37. impl RequestHandler<()> for DamNode {
  38. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  39. debug!(target: "damd::rpc", "--> {}", req.stringify().unwrap());
  40. match req.method.as_str() {
  41. // =====================
  42. // Miscellaneous methods
  43. // =====================
  44. "ping" => self.pong(req.id, req.params).await,
  45. "dnet.switch" => self.dnet_switch(req.id, req.params).await,
  46. "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
  47. "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
  48. // =================
  49. // Protocols methods
  50. // =================
  51. "protocols.subscribe_foo" => self.protocols_subscribe_foo(req.id, req.params).await,
  52. "protocols.subscribe_attack_foo" => {
  53. self.protocols_subscribe_attack_foo(req.id, req.params).await
  54. }
  55. "protocols.subscribe_bar" => self.protocols_subscribe_bar(req.id, req.params).await,
  56. "protocols.subscribe_attack_bar" => {
  57. self.protocols_subscribe_attack_bar(req.id, req.params).await
  58. }
  59. // =============
  60. // Flood control
  61. // =============
  62. "flood.switch" => self.flood_switch(req.id, req.params).await,
  63. // ==============
  64. // Invalid method
  65. // ==============
  66. _ => JsonError::new(MethodNotFound, None, req.id).into(),
  67. }
  68. }
  69. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  70. self.rpc_connections.lock().await
  71. }
  72. }
  73. impl DamNode {
  74. // RPCAPI:
  75. // Activate or deactivate dnet in the P2P stack.
  76. // By sending `true`, dnet will be activated, and by sending `false` dnet
  77. // will be deactivated. Returns `true` on success.
  78. //
  79. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  80. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  81. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  82. let params = params.get::<Vec<JsonValue>>().unwrap();
  83. if params.len() != 1 || !params[0].is_bool() {
  84. return JsonError::new(InvalidParams, None, id).into()
  85. }
  86. let switch = params[0].get::<bool>().unwrap();
  87. if *switch {
  88. self.p2p_handler.p2p.dnet_enable();
  89. } else {
  90. self.p2p_handler.p2p.dnet_disable();
  91. }
  92. JsonResponse::new(JsonValue::Boolean(true), id).into()
  93. }
  94. // RPCAPI:
  95. // Initializes a subscription to p2p dnet events.
  96. // Once a subscription is established, `damd` will send JSON-RPC notifications of
  97. // new network events to the subscriber.
  98. //
  99. // --> {"jsonrpc": "2.0", "method": "protocols.subscribe_foo", "params": [], "id": 1}
  100. // <-- {"jsonrpc": "2.0", "method": "protocols.subscribe_foo", "params": [`event`]}
  101. pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  102. let params = params.get::<Vec<JsonValue>>().unwrap();
  103. if !params.is_empty() {
  104. return JsonError::new(InvalidParams, None, id).into()
  105. }
  106. self.subscribers.get("dnet").unwrap().clone().into()
  107. }
  108. // RPCAPI:
  109. // Initializes a subscription to new incoming `Foo` messages.
  110. // Once a subscription is established, `damd` will send JSON-RPC notifications of
  111. // new incoming `Foo` messages to the subscriber.
  112. //
  113. // --> {"jsonrpc": "2.0", "method": "protocols.subscribe_foo", "params": [], "id": 1}
  114. // <-- {"jsonrpc": "2.0", "method": "protocols.subscribe_foo", "params": [`message`]}
  115. pub async fn protocols_subscribe_foo(&self, id: u16, params: JsonValue) -> JsonResult {
  116. self.get_subscriber(id, params, "foo").await
  117. }
  118. // RPCAPI:
  119. // Initializes a subscription to new outgoing attack `Foo` messages.
  120. // Once a subscription is established, `damd` will send JSON-RPC notifications of
  121. // new outgoing attack `Foo` messages to the subscriber.
  122. //
  123. // --> {"jsonrpc": "2.0", "method": "protocols.subscribe_attack_foo", "params": [], "id": 1}
  124. // <-- {"jsonrpc": "2.0", "method": "protocols.subscribe_attack_foo", "params": [`message`]}
  125. pub async fn protocols_subscribe_attack_foo(&self, id: u16, params: JsonValue) -> JsonResult {
  126. self.get_subscriber(id, params, "attack_foo").await
  127. }
  128. // RPCAPI:
  129. // Initializes a subscription to new incoming `Bar` messages.
  130. // Once a subscription is established, `damd` will send JSON-RPC notifications of
  131. // new incoming `Bar` messages to the subscriber.
  132. //
  133. // --> {"jsonrpc": "2.0", "method": "protocols.subscribe_bar", "params": [], "id": 1}
  134. // <-- {"jsonrpc": "2.0", "method": "protocols.subscribe_bar", "params": [`message`]}
  135. pub async fn protocols_subscribe_bar(&self, id: u16, params: JsonValue) -> JsonResult {
  136. self.get_subscriber(id, params, "bar").await
  137. }
  138. // RPCAPI:
  139. // Initializes a subscription to new outgoing attack `Bar` messages.
  140. // Once a subscription is established, `damd` will send JSON-RPC notifications of
  141. // new outgoing attack `Bar` messages to the subscriber.
  142. //
  143. // --> {"jsonrpc": "2.0", "method": "protocols.subscribe_attack_bar", "params": [], "id": 1}
  144. // <-- {"jsonrpc": "2.0", "method": "protocols.subscribe_attack_bar", "params": [`message`]}
  145. pub async fn protocols_subscribe_attack_bar(&self, id: u16, params: JsonValue) -> JsonResult {
  146. self.get_subscriber(id, params, "attack_bar").await
  147. }
  148. async fn get_subscriber(&self, id: u16, params: JsonValue, sub: &str) -> JsonResult {
  149. let params = params.get::<Vec<JsonValue>>().unwrap();
  150. if !params.is_empty() {
  151. return JsonError::new(InvalidParams, None, id).into()
  152. }
  153. self.subscribers.get(sub).unwrap().clone().into()
  154. }
  155. // RPCAPI:
  156. // Activate or deactivate damd flooder.
  157. // By sending `true`, flooder will be activated, and by sending `false` flooder
  158. // will be deactivated. Returns `true` on success.
  159. //
  160. // --> {"jsonrpc": "2.0", "method": "flood", "params": [true], "id": 42}
  161. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  162. async fn flood_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  163. let params = params.get::<Vec<JsonValue>>().unwrap();
  164. if params.len() != 1 || !params[0].is_bool() {
  165. return JsonError::new(InvalidParams, None, id).into()
  166. }
  167. let switch = params[0].get::<bool>().unwrap();
  168. if *switch {
  169. self.flooder.start(&self.subscribers).await;
  170. } else {
  171. self.flooder.stop().await;
  172. }
  173. JsonResponse::new(JsonValue::Boolean(true), id).into()
  174. }
  175. }
  176. impl HandlerP2p for DamNode {
  177. fn p2p(&self) -> P2pPtr {
  178. self.p2p_handler.p2p.clone()
  179. }
  180. }