rpc.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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 async_trait::async_trait;
  19. use darkfi::{net::P2pPtr, system::StoppableTaskPtr};
  20. use smol::lock::MutexGuard;
  21. use std::collections::HashSet;
  22. use tracing::{debug, error};
  23. use darkfi::rpc::{
  24. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  25. p2p_method::HandlerP2p,
  26. server::RequestHandler,
  27. util::JsonValue,
  28. };
  29. use crate::{dchatmsg::DchatMsg, Dchat};
  30. #[async_trait]
  31. impl RequestHandler<()> for Dchat {
  32. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  33. debug!(target: "dchat::rpc", "--> {}", req.stringify().unwrap());
  34. // ANCHOR: req_match
  35. match req.method.as_str() {
  36. "send" => self.send(req.id, req.params).await,
  37. "recv" => self.recv(req.id).await,
  38. "ping" => self.pong(req.id, req.params).await,
  39. "p2p.get_info" => self.p2p_get_info(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. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  43. }
  44. // ANCHOR_END: req_match
  45. }
  46. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  47. self.rpc_connections.lock().await
  48. }
  49. }
  50. impl Dchat {
  51. // RPCAPI:
  52. // TODO
  53. // --> {"jsonrpc": "2.0", "method": "send", "params": [true], "id": 42}
  54. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  55. async fn send(&self, id: i64, params: JsonValue) -> JsonResult {
  56. let msg = params[0].get::<String>().unwrap().to_string();
  57. let dchatmsg = DchatMsg { msg };
  58. if let Err(e) = self.p2p.broadcast(&dchatmsg).await {
  59. error!(target: "dchatd::rpc", "Message broadcast was not admitted: {e}");
  60. }
  61. JsonResponse::new(JsonValue::Boolean(true), id).into()
  62. }
  63. // RPCAPI:
  64. // TODO
  65. // --> {"jsonrpc": "2.0", "method": "inbox", "params": [true], "id": 42}
  66. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  67. async fn recv(&self, id: i64) -> JsonResult {
  68. let buffer = self.recv_msgs.lock().await;
  69. let msgs: Vec<JsonValue> =
  70. buffer.iter().map(|x| JsonValue::String(x.msg.clone())).collect();
  71. JsonResponse::new(JsonValue::Array(msgs), id).into()
  72. }
  73. // RPCAPI:
  74. // Activate or deactivate dnet in the P2P stack.
  75. // By sending `true`, dnet will be activated, and by sending `false` dnet will
  76. // be deactivated. Returns `true` on success.
  77. //
  78. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  79. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  80. async fn dnet_switch(&self, id: i64, params: JsonValue) -> JsonResult {
  81. let params = params.get::<Vec<JsonValue>>().unwrap();
  82. if params.len() != 1 || !params[0].is_bool() {
  83. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  84. }
  85. let switch = params[0].get::<bool>().unwrap();
  86. if *switch {
  87. self.p2p.dnet_enable();
  88. } else {
  89. self.p2p.dnet_disable();
  90. }
  91. JsonResponse::new(JsonValue::Boolean(true), id).into()
  92. }
  93. //
  94. // RPCAPI:
  95. // Initializes a subscription to p2p dnet events.
  96. // Once a subscription is established, `darkirc` will send JSON-RPC notifications of
  97. // new network events to the subscriber.
  98. //
  99. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  100. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  101. pub async fn dnet_subscribe_events(&self, id: i64, params: JsonValue) -> JsonResult {
  102. let params = params.get::<Vec<JsonValue>>().unwrap();
  103. if !params.is_empty() {
  104. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  105. }
  106. self.dnet_sub.clone().into()
  107. }
  108. }
  109. impl HandlerP2p for Dchat {
  110. fn p2p(&self) -> P2pPtr {
  111. self.p2p.clone()
  112. }
  113. }