jsonserver.rs 8.7 KB

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