rpc.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 async_std::sync::{Arc, Mutex};
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use serde_json::{json, Value};
  22. use darkfi::{
  23. event_graph::{
  24. model::{Event, EventId, ModelPtr},
  25. protocol_event::SeenPtr,
  26. },
  27. net,
  28. rpc::{
  29. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  30. server::RequestHandler,
  31. },
  32. util::time::Timestamp,
  33. };
  34. use crate::genevent::GenEvent;
  35. pub struct JsonRpcInterface {
  36. _nickname: String,
  37. missed_events: Arc<Mutex<Vec<Event<GenEvent>>>>,
  38. model: ModelPtr<GenEvent>,
  39. seen: SeenPtr<EventId>,
  40. p2p: net::P2pPtr,
  41. }
  42. #[async_trait]
  43. impl RequestHandler for JsonRpcInterface {
  44. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  45. if !req.params.is_array() {
  46. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  47. }
  48. match req.method.as_str() {
  49. Some("add") => self.add(req.id, req.params).await,
  50. Some("list") => self.list(req.id, req.params).await,
  51. Some("ping") => self.pong(req.id, req.params).await,
  52. Some("dnet_switch") => self.dnet_switch(req.id, req.params).await,
  53. Some("dnet_info") => self.dnet_info(req.id, req.params).await,
  54. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  55. }
  56. }
  57. }
  58. impl JsonRpcInterface {
  59. pub fn new(
  60. _nickname: String,
  61. missed_events: Arc<Mutex<Vec<Event<GenEvent>>>>,
  62. model: ModelPtr<GenEvent>,
  63. seen: SeenPtr<EventId>,
  64. p2p: net::P2pPtr,
  65. ) -> Self {
  66. Self { _nickname, missed_events, model, seen, p2p }
  67. }
  68. // RPCAPI:
  69. // Replies to a ping method.
  70. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  71. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  72. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  73. JsonResponse::new(json!("pong"), id).into()
  74. }
  75. // RPCAPI:
  76. // Activate or deactivate dnet in the P2P stack.
  77. // By sending `true`, dnet will be activated, and by sending `false` dnet
  78. // will be deactivated. Returns `true` on success.
  79. //
  80. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  81. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  82. async fn dnet_switch(&self, id: Value, params: Value) -> JsonResult {
  83. let params = params.as_array().unwrap();
  84. if params.len() != 1 && params[0].as_bool().is_none() {
  85. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  86. }
  87. if params[0].as_bool().unwrap() {
  88. self.p2p.dnet_enable().await;
  89. } else {
  90. self.p2p.dnet_disable().await;
  91. }
  92. JsonResponse::new(json!(true), id).into()
  93. }
  94. // RPCAPI:
  95. // Retrieves P2P network information.
  96. // --> {"jsonrpc": "2.0", "method": "dnet_info", "params": [], "id": 42}
  97. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  98. async fn dnet_info(&self, id: Value, _params: Value) -> JsonResult {
  99. let dnet_info = self.p2p.dnet_info().await;
  100. JsonResponse::new(net::P2p::map_dnet_info(dnet_info), id).into()
  101. }
  102. // RPCAPI:
  103. // Add a new event
  104. // --> {"jsonrpc": "2.0", "method": "add", "params": [], "id": 1}
  105. // <-- {"jsonrpc": "2.0", "result": [nickname, ...], "id": 1}
  106. async fn add(&self, id: Value, params: Value) -> JsonResult {
  107. let genevent = GenEvent {
  108. nick: params[0].get("nick").unwrap().to_string(),
  109. title: params[0].get("title").unwrap().to_string(),
  110. text: params[0].get("text").unwrap().to_string(),
  111. };
  112. let event = Event {
  113. previous_event_hash: self.model.lock().await.get_head_hash(),
  114. action: genevent,
  115. timestamp: Timestamp::current_time(),
  116. };
  117. if !self.seen.push(&event.hash()).await {
  118. let json = json!(false);
  119. return JsonResponse::new(json, id).into()
  120. }
  121. self.p2p.broadcast(&event).await;
  122. let json = json!(true);
  123. JsonResponse::new(json, id).into()
  124. }
  125. // RPCAPI:
  126. // List events
  127. // --> {"jsonrpc": "2.0", "method": "list", "params": [], "id": 1}
  128. // <-- {"jsonrpc": "2.0", "result": [task_id, ...], "id": 1}
  129. async fn list(&self, id: Value, _params: Value) -> JsonResult {
  130. debug!("fetching all events");
  131. let msd = self.missed_events.lock().await.clone();
  132. let ser = darkfi_serial::serialize(&msd);
  133. let json = json!(ser);
  134. JsonResponse::new(json, id).into()
  135. }
  136. }