dfi.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. #[macro_use]
  2. extern crate clap;
  3. use async_executor::Executor;
  4. use async_native_tls::TlsAcceptor;
  5. use async_std::sync::Mutex;
  6. use easy_parallel::Parallel;
  7. use http_types::{Request, Response, StatusCode};
  8. use log::*;
  9. use serde_json::json;
  10. use smol::Async;
  11. use std::net::SocketAddr;
  12. use std::net::TcpListener;
  13. use std::sync::Arc;
  14. use sapvi::{net, Result};
  15. /// Listens for incoming connections and serves them.
  16. async fn listen(
  17. executor: Arc<Executor<'_>>,
  18. rpc: Arc<RpcInterface>,
  19. listener: Async<TcpListener>,
  20. tls: Option<TlsAcceptor>,
  21. ) -> Result<()> {
  22. // Format the full host address.
  23. let host = match &tls {
  24. None => format!("http://{}", listener.get_ref().local_addr()?),
  25. Some(_) => format!("https://{}", listener.get_ref().local_addr()?),
  26. };
  27. println!("Listening on {}", host);
  28. loop {
  29. // Accept the next connection.
  30. let (stream, _) = listener.accept().await?;
  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. struct RpcInterface {
  71. p2p: Arc<net::P2p>,
  72. started: Mutex<bool>,
  73. stop_send: async_channel::Sender<()>,
  74. stop_recv: async_channel::Receiver<()>,
  75. }
  76. impl RpcInterface {
  77. fn new(p2p: Arc<net::P2p>) -> Arc<Self> {
  78. let (stop_send, stop_recv) = async_channel::unbounded::<()>();
  79. Arc::new(Self {
  80. p2p,
  81. started: Mutex::new(false),
  82. stop_send,
  83. stop_recv,
  84. })
  85. }
  86. async fn serve(self: Arc<Self>, mut req: Request) -> http_types::Result<Response> {
  87. info!("RPC serving {}", req.url());
  88. let request = req.body_string().await?;
  89. let mut io = jsonrpc_core::IoHandler::new();
  90. io.add_sync_method("say_hello", |_| {
  91. Ok(jsonrpc_core::Value::String("Hello World!".into()))
  92. });
  93. let self2 = self.clone();
  94. io.add_method("get_info", move |_| {
  95. let self2 = self2.clone();
  96. async move {
  97. Ok(json!({
  98. "started": *self2.started.lock().await,
  99. "connections": self2.p2p.connections_count().await
  100. }))
  101. }
  102. });
  103. let stop_send = self.stop_send.clone();
  104. io.add_method("stop", move |_| {
  105. let stop_send = stop_send.clone();
  106. async move {
  107. let _ = stop_send.send(()).await;
  108. Ok(jsonrpc_core::Value::Null)
  109. }
  110. });
  111. let response = io
  112. .handle_request_sync(&request)
  113. .ok_or(sapvi::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. async fn wait_for_quit(self: Arc<Self>) -> Result<()> {
  120. Ok(self.stop_recv.recv().await?)
  121. }
  122. }
  123. async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<()> {
  124. let p2p = net::P2p::new(options.network_settings);
  125. let rpc = RpcInterface::new(p2p.clone());
  126. let http = listen(
  127. executor.clone(),
  128. rpc.clone(),
  129. Async::<TcpListener>::bind(([127, 0, 0, 1], options.rpc_port))?,
  130. None,
  131. );
  132. let http_task = executor.spawn(http);
  133. *rpc.started.lock().await = true;
  134. p2p.clone().start(executor.clone()).await?;
  135. p2p.run(executor).await?;
  136. rpc.wait_for_quit().await?;
  137. http_task.cancel().await;
  138. Ok(())
  139. }
  140. /*
  141. async fn start2(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<()> {
  142. let connections = Arc::new(Mutex::new(HashMap::new()));
  143. let stored_addrs = Arc::new(Mutex::new(Vec::new()));
  144. let executor2 = executor.clone();
  145. let stored_addrs2 = stored_addrs.clone();
  146. let mut server_task = None;
  147. if let Some(accept_addr) = options.accept_addr {
  148. let accept_addr = accept_addr.clone();
  149. let protocol = ServerProtocol::new(connections.clone(), accept_addr, stored_addrs2);
  150. server_task = Some(executor.spawn(async move {
  151. protocol.start(executor2).await?;
  152. Ok::<(), sapvi::Error>(())
  153. }));
  154. }
  155. let mut seed_protocols = Vec::with_capacity(options.seed_addrs.len());
  156. // Normally we query this from a server
  157. let accept_addr = options.accept_addr.clone();
  158. for seed_addr in options.seed_addrs.iter() {
  159. let protocol = SeedProtocol::new(seed_addr.clone(), accept_addr, stored_addrs.clone());
  160. protocol.clone().start(executor.clone()).await;
  161. seed_protocols.push(protocol);
  162. }
  163. debug!("Waiting for seed node queries to finish...");
  164. for seed_protocol in seed_protocols {
  165. seed_protocol.await_finish().await;
  166. }
  167. debug!("Seed nodes queried.");
  168. let mut client_slots = vec![];
  169. for i in 0..options.connection_slots {
  170. debug!("Starting connection slot {}", i);
  171. let client = Channel::new(
  172. connections.clone(),
  173. accept_addr.clone(),
  174. stored_addrs.clone(),
  175. );
  176. client.clone().start(executor.clone()).await;
  177. client_slots.push(client);
  178. }
  179. for remote_addr in options.manual_connects {
  180. debug!("Starting connection (manual) to {}", remote_addr);
  181. let client = Channel::new(
  182. connections.clone(),
  183. accept_addr.clone(),
  184. stored_addrs.clone(),
  185. );
  186. client
  187. .clone()
  188. .start_manual(remote_addr, executor.clone())
  189. .await;
  190. client_slots.push(client);
  191. }
  192. let rpc = RpcInterface::new();
  193. let http = listen(
  194. executor.clone(),
  195. rpc.clone(),
  196. Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?,
  197. None,
  198. );
  199. let http_task = executor.spawn(http);
  200. rpc.stop_recv.recv().await?;
  201. http_task.cancel().await;
  202. match server_task {
  203. None => {}
  204. Some(server_task) => {
  205. server_task.cancel().await;
  206. }
  207. }
  208. Ok(())
  209. }
  210. */
  211. struct ProgramOptions {
  212. network_settings: net::Settings,
  213. log_path: Box<std::path::PathBuf>,
  214. rpc_port: u16,
  215. }
  216. impl ProgramOptions {
  217. fn load() -> Result<ProgramOptions> {
  218. let app = clap_app!(dfi =>
  219. (version: "0.1.0")
  220. (author: "Amir Taaki <amir@dyne.org>")
  221. (about: "Dark node")
  222. (@arg ACCEPT: -a --accept +takes_value "Accept address")
  223. (@arg SEED_NODES: -s --seeds ... "Seed nodes")
  224. (@arg CONNECTS: -c --connect ... "Manual connections")
  225. (@arg CONNECT_SLOTS: --slots +takes_value "Connection slots")
  226. (@arg LOG_PATH: --log +takes_value "Logfile path")
  227. (@arg RPC_PORT: -r --rpc +takes_value "RPC port")
  228. )
  229. .get_matches();
  230. let accept_addr = if let Some(accept_addr) = app.value_of("ACCEPT") {
  231. Some(accept_addr.parse()?)
  232. } else {
  233. None
  234. };
  235. let mut seed_addrs: Vec<SocketAddr> = vec![];
  236. if let Some(seeds) = app.values_of("SEED_NODES") {
  237. for seed in seeds {
  238. seed_addrs.push(seed.parse()?);
  239. }
  240. }
  241. let mut manual_connects: Vec<SocketAddr> = vec![];
  242. if let Some(connections) = app.values_of("CONNECTS") {
  243. for connect in connections {
  244. manual_connects.push(connect.parse()?);
  245. }
  246. }
  247. let connection_slots = if let Some(connection_slots) = app.value_of("CONNECT_SLOTS") {
  248. connection_slots.parse()?
  249. } else {
  250. 0
  251. };
  252. let log_path = Box::new(
  253. if let Some(log_path) = app.value_of("LOG_PATH") {
  254. std::path::Path::new(log_path)
  255. } else {
  256. std::path::Path::new("/tmp/darkfid.log")
  257. }
  258. .to_path_buf(),
  259. );
  260. let rpc_port = if let Some(rpc_port) = app.value_of("RPC_PORT") {
  261. rpc_port.parse()?
  262. } else {
  263. 8000
  264. };
  265. Ok(ProgramOptions {
  266. network_settings: net::Settings {
  267. inbound: accept_addr,
  268. outbound_connections: connection_slots,
  269. external_addr: accept_addr,
  270. peers: manual_connects,
  271. seeds: seed_addrs,
  272. ..Default::default()
  273. },
  274. log_path,
  275. rpc_port,
  276. })
  277. }
  278. }
  279. fn main() -> Result<()> {
  280. use simplelog::*;
  281. let options = ProgramOptions::load()?;
  282. let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
  283. CombinedLogger::init(vec![
  284. TermLogger::new(LevelFilter::Debug, logger_config, TerminalMode::Mixed).unwrap(),
  285. WriteLogger::new(
  286. LevelFilter::Debug,
  287. Config::default(),
  288. std::fs::File::create(options.log_path.as_path()).unwrap(),
  289. ),
  290. ])
  291. .unwrap();
  292. let ex = Arc::new(Executor::new());
  293. let (signal, shutdown) = async_channel::unbounded::<()>();
  294. let ex2 = ex.clone();
  295. let (_, result) = Parallel::new()
  296. // Run four executor threads.
  297. .each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))
  298. // Run the main future on the current thread.
  299. .finish(|| {
  300. smol::future::block_on(async move {
  301. start(ex2, options).await?;
  302. drop(signal);
  303. Ok::<(), sapvi::Error>(())
  304. })
  305. });
  306. result
  307. }