rpc.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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, slice};
  19. use async_trait::async_trait;
  20. use smol::lock::{Mutex, MutexGuard};
  21. use tinyjson::JsonValue;
  22. use tracing::{debug, error};
  23. use darkfi::{
  24. event_graph::{proto::EventPut, Event, EventGraphPtr},
  25. net,
  26. rpc::{
  27. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult, JsonSubscriber},
  28. p2p_method::HandlerP2p,
  29. server::RequestHandler,
  30. },
  31. system::StoppableTaskPtr,
  32. util::encoding::base64,
  33. };
  34. use darkfi_serial::{deserialize, deserialize_async_partial, serialize_async};
  35. use genevd::GenEvent;
  36. pub struct JsonRpcInterface {
  37. _nickname: String,
  38. event_graph: EventGraphPtr,
  39. p2p: net::P2pPtr,
  40. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  41. dnet_sub: JsonSubscriber,
  42. deg_sub: JsonSubscriber,
  43. }
  44. #[async_trait]
  45. impl RequestHandler<()> for JsonRpcInterface {
  46. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  47. match req.method.as_str() {
  48. "add" => self.add(req.id, req.params).await,
  49. "list" => self.list(req.id, req.params).await,
  50. "ping" => self.pong(req.id, req.params).await,
  51. "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
  52. "dnet.switch" => self.dnet_switch(req.id, req.params).await,
  53. "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
  54. "deg.switch" => self.deg_switch(req.id, req.params).await,
  55. "deg.subscribe_events" => self.deg_subscribe_events(req.id, req.params).await,
  56. "eventgraph.get_info" => self.eg_get_info(req.id, req.params).await,
  57. _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  58. }
  59. }
  60. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  61. self.rpc_connections.lock().await
  62. }
  63. }
  64. impl HandlerP2p for JsonRpcInterface {
  65. fn p2p(&self) -> net::P2pPtr {
  66. self.p2p.clone()
  67. }
  68. }
  69. impl JsonRpcInterface {
  70. pub fn new(
  71. _nickname: String,
  72. event_graph: EventGraphPtr,
  73. p2p: net::P2pPtr,
  74. dnet_sub: JsonSubscriber,
  75. deg_sub: JsonSubscriber,
  76. ) -> Self {
  77. Self {
  78. _nickname,
  79. event_graph,
  80. p2p,
  81. rpc_connections: Mutex::new(HashSet::new()),
  82. dnet_sub,
  83. deg_sub,
  84. }
  85. }
  86. // RPCAPI:
  87. // Initializes a subscription to p2p dnet events.
  88. // Once a subscription is established, `darkirc` will send JSON-RPC notifications of
  89. // new network events to the subscriber.
  90. //
  91. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  92. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  93. pub async fn dnet_subscribe_events(&self, id: i64, params: JsonValue) -> JsonResult {
  94. let params = params.get::<Vec<JsonValue>>().unwrap();
  95. if !params.is_empty() {
  96. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  97. }
  98. self.dnet_sub.clone().into()
  99. }
  100. // RPCAPI:
  101. // Activate or deactivate dnet in the P2P stack.
  102. // By sending `true`, dnet will be activated, and by sending `false` dnet
  103. // will be deactivated. Returns `true` on success.
  104. //
  105. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  106. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  107. async fn dnet_switch(&self, id: i64, params: JsonValue) -> JsonResult {
  108. let params = params.get::<Vec<JsonValue>>().unwrap();
  109. if params.len() != 1 || !params[0].is_bool() {
  110. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  111. }
  112. let switch = params[0].get::<bool>().unwrap();
  113. if *switch {
  114. self.p2p.dnet_enable();
  115. } else {
  116. self.p2p.dnet_disable();
  117. }
  118. JsonResponse::new(JsonValue::Boolean(true), id).into()
  119. }
  120. // RPCAPI:
  121. // Initializes a subscription to deg events.
  122. // Once a subscription is established, apps using eventgraph will send JSON-RPC notifications of
  123. // new eventgraph events to the subscriber.
  124. //
  125. // --> {"jsonrpc": "2.0", "method": "deg.subscribe_events", "params": [], "id": 1}
  126. // <-- {"jsonrpc": "2.0", "method": "deg.subscribe_events", "params": [`event`]}
  127. pub async fn deg_subscribe_events(&self, id: i64, params: JsonValue) -> JsonResult {
  128. let params = params.get::<Vec<JsonValue>>().unwrap();
  129. if !params.is_empty() {
  130. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  131. }
  132. self.deg_sub.clone().into()
  133. }
  134. // RPCAPI:
  135. // Activate or deactivate deg in the EVENTGRAPH.
  136. // By sending `true`, deg will be activated, and by sending `false` deg
  137. // will be deactivated. Returns `true` on success.
  138. //
  139. // --> {"jsonrpc": "2.0", "method": "deg.switch", "params": [true], "id": 42}
  140. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  141. async fn deg_switch(&self, id: i64, params: JsonValue) -> JsonResult {
  142. let params = params.get::<Vec<JsonValue>>().unwrap();
  143. if params.len() != 1 || !params[0].is_bool() {
  144. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  145. }
  146. let switch = params[0].get::<bool>().unwrap();
  147. if *switch {
  148. self.event_graph.deg_enable().await;
  149. } else {
  150. self.event_graph.deg_disable().await;
  151. }
  152. JsonResponse::new(JsonValue::Boolean(true), id).into()
  153. }
  154. // RPCAPI:
  155. // Get EVENTGRAPH info.
  156. //
  157. // --> {"jsonrpc": "2.0", "method": "deg.switch", "params": [true], "id": 42}
  158. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  159. async fn eg_get_info(&self, id: i64, params: JsonValue) -> JsonResult {
  160. let params_ = params.get::<Vec<JsonValue>>().unwrap();
  161. if !params_.is_empty() {
  162. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  163. }
  164. self.event_graph.eventgraph_info(id, params).await
  165. }
  166. // RPCAPI:
  167. // Add a new event
  168. // --> {"jsonrpc": "2.0", "method": "add", "params": [], "id": 1}
  169. // <-- {"jsonrpc": "2.0", "result": [nickname, ...], "id": 1}
  170. async fn add(&self, id: i64, params: JsonValue) -> JsonResult {
  171. let params = params.get::<Vec<JsonValue>>().unwrap();
  172. if params.len() != 1 || !params[0].is_string() {
  173. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  174. }
  175. let b64 = params[0].get::<String>().unwrap();
  176. let dec = base64::decode(b64).unwrap();
  177. let genevent: GenEvent = deserialize(&dec).unwrap();
  178. // Build a DAG event and return it.
  179. let event = Event::new(serialize_async(&genevent).await, &self.event_graph).await;
  180. let current_genesis = self.event_graph.current_genesis.read().await;
  181. let dag_name = current_genesis.header.timestamp.to_string();
  182. if let Err(e) =
  183. self.event_graph.header_dag_insert(vec![event.header.clone()], &dag_name).await
  184. {
  185. error!("Failed inserting new header to Header DAG: {}", e);
  186. }
  187. if let Err(e) = self.event_graph.dag_insert(slice::from_ref(&event), &dag_name).await {
  188. error!("Failed inserting new event to DAG: {e}");
  189. } else {
  190. // Otherwise, broadcast it
  191. self.p2p.broadcast(&EventPut(event, vec![])).await;
  192. }
  193. let json = JsonValue::Boolean(true);
  194. JsonResponse::new(json, id).into()
  195. }
  196. // RPCAPI:
  197. // List events
  198. // --> {"jsonrpc": "2.0", "method": "list", "params": [], "id": 1}
  199. // <-- {"jsonrpc": "2.0", "result": [task_id, ...], "id": 1}
  200. async fn list(&self, id: i64, _params: JsonValue) -> JsonResult {
  201. debug!("Fetching all events");
  202. let mut seen_events = vec![];
  203. let dag_events = self.event_graph.order_events().await;
  204. for event in dag_events.iter() {
  205. let event_id = event.header.id();
  206. // Try to deserialize it. (Here we skip errors)
  207. let genevent: GenEvent = match deserialize_async_partial(event.content()).await {
  208. Ok((v, _)) => v,
  209. Err(e) => {
  210. error!("Failed deserializing incoming event: {e}");
  211. continue
  212. }
  213. };
  214. debug!("Marking event {event_id} as seen");
  215. seen_events.push(genevent);
  216. }
  217. let ser = darkfi_serial::serialize(&seen_events);
  218. let enc = JsonValue::String(base64::encode(&ser));
  219. JsonResponse::new(enc, id).into()
  220. }
  221. }