jsonrpc.rs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 async_std::{net::TcpListener, sync::Arc, task};
  19. use async_trait::async_trait;
  20. use smol::channel::{Receiver, Sender};
  21. use tinyjson::JsonValue;
  22. use url::Url;
  23. use darkfi::{
  24. net::transport::Listener,
  25. rpc::{
  26. client::RpcClient,
  27. jsonrpc::*,
  28. server::{accept, RequestHandler},
  29. },
  30. Result,
  31. };
  32. struct RpcSrv {
  33. stop_sub: (Sender<()>, Receiver<()>),
  34. }
  35. impl RpcSrv {
  36. async fn pong(&self, id: JsonValue, _params: JsonValue) -> JsonResult {
  37. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  38. }
  39. async fn kill(&self, id: JsonValue, _params: JsonValue) -> JsonResult {
  40. self.stop_sub.0.send(()).await.unwrap();
  41. JsonResponse::new(JsonValue::String("bye".to_string()), id).into()
  42. }
  43. }
  44. #[async_trait]
  45. impl RequestHandler for RpcSrv {
  46. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  47. assert!(req.params.is_array());
  48. let method = String::try_from(req.method).unwrap();
  49. let params = req.params;
  50. match method.as_str() {
  51. "ping" => return self.pong(req.id, params).await,
  52. "kill" => return self.kill(req.id, params).await,
  53. _ => {
  54. return JsonError::new(
  55. ErrorCode::MethodNotFound,
  56. None,
  57. *req.id.get::<f64>().unwrap() as u16,
  58. )
  59. .into()
  60. }
  61. }
  62. }
  63. }
  64. #[async_std::test]
  65. async fn jsonrpc_reqrep() -> Result<()> {
  66. // Find an available port
  67. let listener = TcpListener::bind("127.0.0.1:0").await?;
  68. let sockaddr = listener.local_addr()?;
  69. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  70. drop(listener);
  71. let rpcsrv = Arc::new(RpcSrv { stop_sub: smol::channel::unbounded() });
  72. let listener = Listener::new(endpoint.clone()).await?.listen().await?;
  73. task::spawn(async move {
  74. while let Ok((stream, peer_addr)) = listener.next().await {
  75. let _rh = rpcsrv.clone();
  76. task::spawn(async move {
  77. let _ = accept(stream, peer_addr.clone(), _rh).await;
  78. });
  79. }
  80. });
  81. let client = RpcClient::new(endpoint, None).await?;
  82. let req = JsonRequest::new("ping", JsonValue::from(vec![]));
  83. let rep = client.request(req).await?;
  84. let rep = String::try_from(rep).unwrap();
  85. assert_eq!(&rep, "pong");
  86. let req = JsonRequest::new("kill", JsonValue::from(vec![]));
  87. let rep = client.request(req).await?;
  88. let rep = String::try_from(rep).unwrap();
  89. assert_eq!(&rep, "bye");
  90. Ok(())
  91. }