rpc.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. use async_trait::async_trait;
  2. use log::debug;
  3. use serde_json::{json, Value};
  4. use url::Url;
  5. use darkfi::{
  6. net,
  7. rpc::{
  8. jsonrpc,
  9. jsonrpc::{ErrorCode, JsonRequest, JsonResult},
  10. rpcserver::RequestHandler,
  11. },
  12. };
  13. pub struct JsonRpcInterface {
  14. pub addr: Url,
  15. pub p2p: net::P2pPtr,
  16. }
  17. #[async_trait]
  18. impl RequestHandler for JsonRpcInterface {
  19. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  20. if req.params.as_array().is_none() {
  21. return jsonrpc::error(ErrorCode::InvalidRequest, None, req.id).into()
  22. }
  23. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  24. match req.method.as_str() {
  25. Some("ping") => self.pong(req.id, req.params).await,
  26. Some("get_info") => self.get_info(req.id, req.params).await,
  27. Some(_) | None => jsonrpc::error(ErrorCode::MethodNotFound, None, req.id).into(),
  28. }
  29. }
  30. }
  31. impl JsonRpcInterface {
  32. // RPCAPI:
  33. // Replies to a ping method.
  34. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  35. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  36. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  37. jsonrpc::response(json!("pong"), id).into()
  38. }
  39. // RPCAPI:
  40. // Retrieves P2P network information.
  41. // --> {"jsonrpc": "2.0", "method": "get_info", "params": [], "id": 42}
  42. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  43. async fn get_info(&self, id: Value, _params: Value) -> JsonResult {
  44. let resp = self.p2p.get_info().await;
  45. jsonrpc::response(resp, id).into()
  46. }
  47. }