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