rpc.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 std::collections::HashSet;
  19. use darkfi::{
  20. rpc::{
  21. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  22. server::RequestHandler,
  23. util::JsonValue,
  24. },
  25. system::StoppableTaskPtr,
  26. };
  27. use darkfi_serial::async_trait;
  28. use smol::lock::MutexGuard;
  29. use super::Swapd;
  30. #[async_trait]
  31. impl RequestHandler for Swapd {
  32. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  33. match req.method.as_str() {
  34. "ping" => self.pong(req.id, req.params).await,
  35. "hello" => self.hello(req.id, req.params).await,
  36. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  37. }
  38. }
  39. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  40. self.rpc_connections.lock().await
  41. }
  42. }
  43. impl Swapd {
  44. // RPCAPI:
  45. // Use this kind of comment in order to have the RPC spec automatically
  46. // generated in the mdbook. You should be able to write any kind of
  47. // markdown in here.
  48. //
  49. // At the bottom, you should have the reqrep in JSON:
  50. //
  51. // --> {"jsonrpc": "2.0", "method": "hello", "params": ["hello"], "id": 42}
  52. // --> {"jsonrpc": "2.0", "result": "hello", "id": 42}
  53. async fn hello(&self, id: u16, params: JsonValue) -> JsonResult {
  54. let params = params.get::<Vec<JsonValue>>().unwrap();
  55. if params.len() != 1 || !params[0].is_string() {
  56. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  57. }
  58. JsonResponse::new(params[0].clone(), id).into()
  59. }
  60. }