main.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. use async_executor::Executor;
  2. use async_std::sync::Arc;
  3. use futures_lite::future;
  4. use log::{error, info};
  5. use structopt_toml::StructOptToml;
  6. use url::Url;
  7. use darkfi::{
  8. async_daemonize, net,
  9. util::{
  10. cli::{get_log_config, get_log_level, spawn_config},
  11. path::get_config_path,
  12. },
  13. Result,
  14. };
  15. mod config;
  16. use config::{parse_configured_networks, Args, NetInfo};
  17. const CONFIG_FILE: &str = "lilith_config.toml";
  18. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  19. async fn spawn_network(
  20. name: &str,
  21. info: NetInfo,
  22. mut url: Url,
  23. ex: Arc<Executor<'_>>,
  24. ) -> Result<()> {
  25. url.set_port(Some(info.port))?;
  26. let network_settings = net::Settings {
  27. inbound: Some(url.clone()),
  28. seeds: info.seeds,
  29. peers: info.peers,
  30. outbound_connections: 0,
  31. ..Default::default()
  32. };
  33. let p2p = net::P2p::new(network_settings).await;
  34. info!("Starting seed network node for {} at: {}", name, url);
  35. p2p.clone().start(ex.clone()).await?;
  36. let _ex = ex.clone();
  37. ex.spawn(async move {
  38. if let Err(e) = p2p.run(_ex).await {
  39. error!("Failed starting P2P network seed: {}", e);
  40. }
  41. })
  42. .detach();
  43. Ok(())
  44. }
  45. async_daemonize!(realmain);
  46. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  47. // We use this handler to block this function after detaching all
  48. // tasks, and to catch a shutdown signal, where we can clean up and
  49. // exit gracefully.
  50. let (signal, shutdown) = async_channel::bounded::<()>(1);
  51. ctrlc_async::set_async_handler(async move {
  52. signal.send(()).await.unwrap();
  53. })
  54. .unwrap();
  55. // Pick up network settings from the TOML configuration
  56. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  57. let toml_contents = std::fs::read_to_string(cfg_path)?;
  58. let configured_nets = parse_configured_networks(&toml_contents)?;
  59. // Verify any daemon network is enabled
  60. if configured_nets.is_empty() {
  61. info!("No daemon network is enabled!");
  62. return Ok(())
  63. }
  64. // Spawn configured networks
  65. for (name, info) in &configured_nets {
  66. if let Err(e) = spawn_network(name, info.clone(), args.url.clone(), ex.clone()).await {
  67. error!("Failed starting {} P2P network seed: {}", name, e);
  68. }
  69. }
  70. // Wait for SIGINT
  71. shutdown.recv().await?;
  72. print!("\r");
  73. info!("Caught termination signal, cleaning up and exiting...");
  74. Ok(())
  75. }