jsonrpc.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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, sync::Arc};
  19. use async_trait::async_trait;
  20. use smol::{
  21. channel::{Receiver, Sender},
  22. lock::{Mutex, MutexGuard},
  23. net::TcpListener,
  24. Executor,
  25. };
  26. use tinyjson::JsonValue;
  27. use tracing::warn;
  28. use url::Url;
  29. use darkfi::{
  30. rpc::{
  31. client::RpcClient,
  32. jsonrpc::*,
  33. server::{listen_and_serve, RequestHandler},
  34. settings::RpcSettings,
  35. },
  36. system::{msleep, StoppableTask, StoppableTaskPtr},
  37. util::logger::{setup_test_logger, Level},
  38. Error, Result,
  39. };
  40. struct RpcSrv {
  41. stop_sub: (Sender<()>, Receiver<()>),
  42. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  43. }
  44. impl RpcSrv {
  45. async fn pong(&self, id: u16, _params: JsonValue) -> JsonResult {
  46. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  47. }
  48. async fn kill(&self, id: u16, _params: JsonValue) -> JsonResult {
  49. self.stop_sub.0.send(()).await.unwrap();
  50. JsonResponse::new(JsonValue::String("bye".to_string()), id).into()
  51. }
  52. }
  53. #[async_trait]
  54. impl RequestHandler<()> for RpcSrv {
  55. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  56. assert!(req.params.is_array());
  57. return match req.method.as_str() {
  58. "ping" => self.pong(req.id, req.params).await,
  59. "kill" => self.kill(req.id, req.params).await,
  60. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  61. }
  62. }
  63. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  64. self.rpc_connections.lock().await
  65. }
  66. }
  67. /// Initialize the logging mechanism
  68. fn init_logger() {
  69. // We check this error so we can execute same file tests in parallel,
  70. // otherwise second one fails to init logger here.
  71. if setup_test_logger(
  72. &[],
  73. false,
  74. //Level::Info,
  75. //Level::Verbose
  76. Level::Debug,
  77. //Level::Trace,
  78. )
  79. .is_err()
  80. {
  81. warn!("Logger already initialized");
  82. }
  83. }
  84. #[test]
  85. fn jsonrpc_reqrep() -> Result<()> {
  86. init_logger();
  87. let executor = Arc::new(Executor::new());
  88. smol::block_on(executor.run(async {
  89. // Find an available port
  90. let listener = TcpListener::bind("127.0.0.1:0").await?;
  91. let sockaddr = listener.local_addr()?;
  92. let rpc_settings = RpcSettings {
  93. listen: Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?,
  94. ..RpcSettings::default()
  95. };
  96. drop(listener);
  97. let rpcsrv = Arc::new(RpcSrv {
  98. stop_sub: smol::channel::unbounded(),
  99. rpc_connections: Mutex::new(HashSet::new()),
  100. });
  101. let rpcsrv_ = Arc::clone(&rpcsrv);
  102. let rpc_task = StoppableTask::new();
  103. rpc_task.clone().start(
  104. listen_and_serve(rpc_settings.clone(), rpcsrv.clone(), None, executor.clone()),
  105. |res| async move {
  106. match res {
  107. Ok(()) | Err(Error::RpcServerStopped) => rpcsrv_.stop_connections().await,
  108. Err(e) => eprintln!("Failed starting JSON-RPC server: {e}"),
  109. }
  110. },
  111. Error::RpcServerStopped,
  112. executor.clone(),
  113. );
  114. msleep(500).await;
  115. let client = RpcClient::new(rpc_settings.listen, executor.clone()).await?;
  116. let req = JsonRequest::new("ping", vec![].into());
  117. let rep = client.request(req).await?;
  118. let rep = String::try_from(rep).unwrap();
  119. assert_eq!(&rep, "pong");
  120. let req = JsonRequest::new("kill", vec![].into());
  121. let rep = client.request(req).await?;
  122. let rep = String::try_from(rep).unwrap();
  123. assert_eq!(&rep, "bye");
  124. Ok(())
  125. }))
  126. }
  127. #[test]
  128. fn http_jsonrpc_reqrep() -> Result<()> {
  129. init_logger();
  130. let executor = Arc::new(Executor::new());
  131. smol::block_on(executor.run(async {
  132. // Find an available port
  133. let listener = TcpListener::bind("127.0.0.1:0").await?;
  134. let sockaddr = listener.local_addr()?;
  135. let rpc_settings = RpcSettings {
  136. listen: Url::parse(&format!("http+tcp://127.0.0.1:{}", sockaddr.port()))?,
  137. ..RpcSettings::default()
  138. };
  139. drop(listener);
  140. let rpcsrv = Arc::new(RpcSrv {
  141. stop_sub: smol::channel::unbounded(),
  142. rpc_connections: Mutex::new(HashSet::new()),
  143. });
  144. let rpcsrv_ = Arc::clone(&rpcsrv);
  145. let rpc_task = StoppableTask::new();
  146. rpc_task.clone().start(
  147. listen_and_serve(rpc_settings.clone(), rpcsrv.clone(), None, executor.clone()),
  148. |res| async move {
  149. match res {
  150. Ok(()) | Err(Error::RpcServerStopped) => rpcsrv_.stop_connections().await,
  151. Err(e) => eprintln!("Failed starting JSON-RPC server: {e}"),
  152. }
  153. },
  154. Error::RpcServerStopped,
  155. executor.clone(),
  156. );
  157. msleep(500).await;
  158. let client = RpcClient::new(rpc_settings.listen, executor.clone()).await?;
  159. let req = JsonRequest::new("ping", vec![].into());
  160. let rep = client.request(req).await?;
  161. let rep = String::try_from(rep).unwrap();
  162. assert_eq!(&rep, "pong");
  163. let req = JsonRequest::new("kill", vec![].into());
  164. let rep = client.request(req).await?;
  165. let rep = String::try_from(rep).unwrap();
  166. assert_eq!(&rep, "bye");
  167. Ok(())
  168. }))
  169. }