rpc.rs 2.4 KB

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