rpc.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. use std::{net::SocketAddr, sync::Arc};
  2. use async_executor::Executor;
  3. use async_trait::async_trait;
  4. use log::debug;
  5. use serde_json::{json, Value};
  6. use darkfi::rpc::{
  7. jsonrpc,
  8. jsonrpc::{ErrorCode, JsonRequest, JsonResult},
  9. rpcserver::RequestHandler,
  10. };
  11. pub struct JsonRpcInterface {
  12. pub addr: SocketAddr,
  13. }
  14. #[async_trait]
  15. impl RequestHandler for JsonRpcInterface {
  16. async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
  17. if req.params.as_array().is_none() {
  18. return jsonrpc::error(ErrorCode::InvalidRequest, None, req.id).into()
  19. }
  20. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  21. match req.method.as_str() {
  22. Some("ping") => self.pong(req.id, req.params).await,
  23. //Some("get_info") => self.get_info(req.id, req.params).await,
  24. Some(_) | None => jsonrpc::error(ErrorCode::MethodNotFound, None, req.id).into(),
  25. }
  26. }
  27. }
  28. impl JsonRpcInterface {
  29. // RPCAPI:
  30. // Replies to a ping method.
  31. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  32. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  33. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  34. jsonrpc::response(json!("pong"), id).into()
  35. }
  36. }