rpc.rs 1.6 KB

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