jsonserver.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. use crate::cli::cli_config;
  2. use crate::rpc::adapter::RpcAdapter;
  3. use crate::{Error, Result};
  4. use async_executor::Executor;
  5. use async_native_tls::TlsAcceptor;
  6. use async_std::sync::Mutex;
  7. use http_types::{Request, Response, StatusCode};
  8. use log::*;
  9. use smol::Async;
  10. use std::net::TcpListener;
  11. use std::sync::Arc;
  12. /// Listens for incoming connections and serves them.
  13. pub async fn listen(
  14. executor: Arc<Executor<'_>>,
  15. rpc: Arc<RpcInterface>,
  16. listener: Async<TcpListener>,
  17. tls: Option<TlsAcceptor>,
  18. ) -> Result<()> {
  19. // Format the full host address.
  20. let host = match &tls {
  21. None => format!("http://{}", listener.get_ref().local_addr()?),
  22. Some(_) => format!("https://{}", listener.get_ref().local_addr()?),
  23. };
  24. println!("Listening on {}", host);
  25. loop {
  26. // Accept the next connection.
  27. debug!(target: "rpc", "waiting for stream accept [START]");
  28. let (stream, _) = listener.accept().await?;
  29. debug!(target: "rpc", "stream accepted [END]");
  30. // Spawn a background task serving this connection.
  31. let task = match &tls {
  32. None => {
  33. let stream = async_dup::Arc::new(stream);
  34. let rpc = rpc.clone();
  35. executor.spawn(async move {
  36. if let Err(err) = async_h1::accept(stream, move |req| {
  37. let rpc = rpc.clone();
  38. rpc.serve(req)
  39. })
  40. .await
  41. {
  42. println!("Connection error: {:#?}", err);
  43. }
  44. })
  45. }
  46. Some(tls) => {
  47. // In case of HTTPS, establish a secure TLS connection first.
  48. match tls.accept(stream).await {
  49. Ok(stream) => {
  50. let _stream = async_dup::Arc::new(async_dup::Mutex::new(stream));
  51. executor.spawn(async move {
  52. /*if let Err(err) = async_h1::accept(stream, serve).await {
  53. println!("Connection error: {:#?}", err);
  54. }*/
  55. unimplemented!();
  56. })
  57. }
  58. Err(err) => {
  59. println!("Failed to establish secure TLS connection: {:#?}", err);
  60. continue;
  61. }
  62. }
  63. }
  64. };
  65. // Detach the task to let it run in the background.
  66. task.detach();
  67. }
  68. }
  69. pub async fn start(
  70. executor: Arc<Executor<'_>>,
  71. config: Arc<cli_config::Config>,
  72. adapter: RpcAdapter,
  73. ) -> Result<()> {
  74. let rpc = RpcInterface::new(adapter)?;
  75. let rpc_url: std::net::SocketAddr = config.rpc_url.parse()?;
  76. let http = listen(
  77. executor.clone(),
  78. rpc.clone(),
  79. Async::<TcpListener>::bind(rpc_url)?,
  80. None,
  81. );
  82. let http_task = executor.spawn(http);
  83. *rpc.started.lock().await = true;
  84. rpc.wait_for_quit().await?;
  85. http_task.cancel().await;
  86. Ok(())
  87. }
  88. // json RPC server goes here
  89. #[allow(dead_code)]
  90. pub struct RpcInterface {
  91. pub started: Mutex<bool>,
  92. stop_send: async_channel::Sender<()>,
  93. stop_recv: async_channel::Receiver<()>,
  94. adapter: RpcAdapter,
  95. }
  96. impl RpcInterface {
  97. pub fn new(adapter: RpcAdapter) -> Result<Arc<Self>> {
  98. let (stop_send, stop_recv) = async_channel::unbounded::<()>();
  99. Ok(Arc::new(Self {
  100. //p2p,
  101. started: Mutex::new(false),
  102. stop_send,
  103. stop_recv,
  104. adapter,
  105. }))
  106. }
  107. pub async fn serve(self: Arc<Self>, mut req: Request) -> http_types::Result<Response> {
  108. info!("RPC serving {}", req.url());
  109. let request = req.body_string().await?;
  110. let io = self.handle_input().await?;
  111. let response = io
  112. .handle_request_sync(&request)
  113. .ok_or(Error::BadOperationType)?;
  114. let mut res = Response::new(StatusCode::Ok);
  115. res.insert_header("Content-Type", "text/plain");
  116. res.set_body(response);
  117. Ok(res)
  118. }
  119. pub async fn handle_input(self: Arc<Self>) -> Result<jsonrpc_core::IoHandler> {
  120. debug!(target: "rpc", "JsonRpcInterface::handle_input() [START]");
  121. let mut io = jsonrpc_core::IoHandler::new();
  122. io.add_sync_method("say_hello", |_| {
  123. Ok(jsonrpc_core::Value::String("Hello World!".into()))
  124. });
  125. let self1 = self.clone();
  126. io.add_method("get_key", move |_| {
  127. let self2 = self1.clone();
  128. async move {
  129. self2.adapter.get_key().await?;
  130. Ok(jsonrpc_core::Value::String("Getting cashier key...".into()))
  131. }
  132. });
  133. let self1 = self.clone();
  134. io.add_method("get_cash_key", move |_| {
  135. let self2 = self1.clone();
  136. async move {
  137. self2.adapter.get_cash_key().await?;
  138. Ok(jsonrpc_core::Value::String("Getting cashier key...".into()))
  139. }
  140. });
  141. let self1 = self.clone();
  142. io.add_method("get_info", move |_| {
  143. let self2 = self1.clone();
  144. async move {
  145. self2.adapter.get_info().await;
  146. Ok(jsonrpc_core::Value::Null)
  147. }
  148. });
  149. let self1 = self.clone();
  150. io.add_method("stop", move |_| {
  151. let self2 = self1.clone();
  152. async move {
  153. self2.adapter.stop().await;
  154. Ok(jsonrpc_core::Value::Null)
  155. }
  156. });
  157. let self1 = self.clone();
  158. io.add_method("create_wallet", move |_| {
  159. let self2 = self1.clone();
  160. async move {
  161. println!(
  162. "Attempting wallet generation at path {:?}",
  163. self2.adapter.wallet.path
  164. );
  165. self2.adapter.init_db().await?;
  166. Ok(jsonrpc_core::Value::String("Created wallet".into()))
  167. }
  168. });
  169. let self1 = self.clone();
  170. io.add_method("key_gen", move |_| {
  171. let self2 = self1.clone();
  172. async move {
  173. println!("Key generation method called...");
  174. self2.adapter.key_gen().await?;
  175. Ok(jsonrpc_core::Value::String(
  176. "Key generation successful".into(),
  177. ))
  178. }
  179. });
  180. let self1 = self.clone();
  181. io.add_method("cash_key_gen", move |_| {
  182. let self2 = self1.clone();
  183. async move {
  184. println!("Key generation method called...");
  185. self2.adapter.cash_key_gen().await?;
  186. Ok(jsonrpc_core::Value::String(
  187. "Attempted key generation".into(),
  188. ))
  189. }
  190. });
  191. let self1 = self.clone();
  192. io.add_method("test_wallet", move |_| {
  193. let self2 = self1.clone();
  194. async move {
  195. println!("Test wallet method called...");
  196. self2.adapter.test_wallet().await?;
  197. Ok(jsonrpc_core::Value::String("Test wallet".into()))
  198. }
  199. });
  200. let self1 = self.clone();
  201. io.add_method("create_cashier_wallet", move |_| {
  202. let self2 = self1.clone();
  203. async move {
  204. println!("New wallet method called...");
  205. self2.adapter.init_cashier_db().await?;
  206. println!("Wallet created at path {:?}", self2.adapter.wallet.path);
  207. Ok(jsonrpc_core::Value::String("Created cashier wallet".into()))
  208. }
  209. });
  210. debug!(target: "rpc", "JsonRpcInterface::handle_input() [END]");
  211. Ok(io)
  212. }
  213. pub async fn wait_for_quit(self: Arc<Self>) -> Result<()> {
  214. Ok(self.stop_recv.recv().await?)
  215. }
  216. }