rpc.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  9. server::RequestHandler,
  10. },
  11. };
  12. // ANCHOR: jsonrpc
  13. pub struct JsonRpcInterface {
  14. pub addr: Url,
  15. pub p2p: net::P2pPtr,
  16. }
  17. // ANCHOR_END: jsonrpc
  18. #[async_trait]
  19. impl RequestHandler for JsonRpcInterface {
  20. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  21. if req.params.as_array().is_none() {
  22. return JsonError::new(ErrorCode::InvalidRequest, None, req.id).into()
  23. }
  24. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  25. // ANCHOR: req_match
  26. match req.method.as_str() {
  27. Some("ping") => self.pong(req.id, req.params).await,
  28. Some("get_info") => self.get_info(req.id, req.params).await,
  29. Some(_) | None => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  30. }
  31. // ANCHOR_END: req_match
  32. }
  33. }
  34. impl JsonRpcInterface {
  35. // RPCAPI:
  36. // Replies to a ping method.
  37. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  38. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  39. // ANCHOR: pong
  40. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  41. JsonResponse::new(json!("pong"), id).into()
  42. }
  43. // ANCHOR_END: pong
  44. // RPCAPI:
  45. // Retrieves P2P network information.
  46. // --> {"jsonrpc": "2.0", "method": "get_info", "params": [], "id": 42}
  47. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  48. // ANCHOR: get_info
  49. async fn get_info(&self, id: Value, _params: Value) -> JsonResult {
  50. let resp = self.p2p.get_info().await;
  51. JsonResponse::new(resp, id).into()
  52. }
  53. // ANCHOR_END: get_info
  54. }