jsonserver.rs 7.8 KB

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