rpc.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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_trait::async_trait;
  19. use log::debug;
  20. use serde_json::{json, Value};
  21. use url::Url;
  22. use darkfi::{
  23. net,
  24. rpc::{
  25. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  26. server::RequestHandler,
  27. },
  28. };
  29. // ANCHOR: jsonrpc
  30. pub struct JsonRpcInterface {
  31. pub addr: Url,
  32. pub p2p: net::P2pPtr,
  33. }
  34. // ANCHOR_END: jsonrpc
  35. #[async_trait]
  36. impl RequestHandler for JsonRpcInterface {
  37. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  38. if req.params.as_array().is_none() {
  39. return JsonError::new(ErrorCode::InvalidRequest, None, req.id).into()
  40. }
  41. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  42. // ANCHOR: req_match
  43. match req.method.as_str() {
  44. Some("ping") => self.pong(req.id, req.params).await,
  45. Some("get_info") => self.get_info(req.id, req.params).await,
  46. Some(_) | None => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  47. }
  48. // ANCHOR_END: req_match
  49. }
  50. }
  51. impl JsonRpcInterface {
  52. // RPCAPI:
  53. // Replies to a ping method.
  54. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  55. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  56. // ANCHOR: pong
  57. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  58. JsonResponse::new(json!("pong"), id).into()
  59. }
  60. // ANCHOR_END: pong
  61. // RPCAPI:
  62. // Retrieves P2P network information.
  63. // --> {"jsonrpc": "2.0", "method": "get_info", "params": [], "id": 42}
  64. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  65. // ANCHOR: get_info
  66. async fn get_info(&self, id: Value, _params: Value) -> JsonResult {
  67. let resp = self.p2p.get_info().await;
  68. JsonResponse::new(resp, id).into()
  69. }
  70. // ANCHOR_END: get_info
  71. }