main.rs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashSet, sync::Arc};
  19. use log::{error, info};
  20. use smol::{
  21. channel::{Receiver, Sender},
  22. lock::Mutex,
  23. stream::StreamExt,
  24. Executor,
  25. };
  26. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  27. use url::Url;
  28. use darkfi::{
  29. async_daemonize, cli_desc,
  30. rpc::server::{listen_and_serve, RequestHandler},
  31. system::{StoppableTask, StoppableTaskPtr},
  32. Error, Result,
  33. };
  34. const CONFIG_FILE: &str = "minerd.toml";
  35. const CONFIG_FILE_CONTENTS: &str = include_str!("../minerd.toml");
  36. /// Daemon error codes
  37. mod error;
  38. /// JSON-RPC server methods
  39. mod rpc;
  40. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  41. #[serde(default)]
  42. #[structopt(name = "minerd", about = cli_desc!())]
  43. struct Args {
  44. #[structopt(short, long)]
  45. /// Configuration file to use
  46. config: Option<String>,
  47. #[structopt(short, long, default_value = "tcp://127.0.0.1:28467")]
  48. /// JSON-RPC listen URL
  49. rpc_listen: Url,
  50. #[structopt(short, long, default_value = "4")]
  51. /// PoW miner number of threads to use
  52. threads: usize,
  53. #[structopt(short, long)]
  54. /// Set log file to ouput into
  55. log: Option<String>,
  56. #[structopt(short, parse(from_occurrences))]
  57. /// Increase verbosity (-vvv supported)
  58. verbose: u8,
  59. }
  60. /// Daemon structure
  61. pub struct Minerd {
  62. /// PoW miner number of threads to use
  63. threads: usize,
  64. // Sender to stop miner threads
  65. sender: Sender<()>,
  66. // Receiver to stop miner threads
  67. stop_signal: Receiver<()>,
  68. /// JSON-RPC connection tracker
  69. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  70. }
  71. impl Minerd {
  72. pub fn new(threads: usize, sender: Sender<()>, stop_signal: Receiver<()>) -> Self {
  73. Self { threads, sender, stop_signal, rpc_connections: Mutex::new(HashSet::new()) }
  74. }
  75. }
  76. async_daemonize!(realmain);
  77. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  78. info!(target: "minerd", "Starting DarkFi Mining Daemon...");
  79. let (sender, recvr) = smol::channel::bounded(1);
  80. let minerd = Arc::new(Minerd::new(args.threads, sender.clone(), recvr));
  81. info!(target: "minerd", "Starting JSON-RPC server on {}", args.rpc_listen);
  82. let minerd_ = Arc::clone(&minerd);
  83. let rpc_task = StoppableTask::new();
  84. rpc_task.clone().start(
  85. listen_and_serve(args.rpc_listen, minerd.clone(), None, ex.clone()),
  86. |res| async move {
  87. match res {
  88. Ok(()) | Err(Error::RpcServerStopped) => minerd_.stop_connections().await,
  89. Err(e) => error!(target: "minerd", "Failed stopping JSON-RPC server: {}", e),
  90. }
  91. },
  92. Error::RpcServerStopped,
  93. ex.clone(),
  94. );
  95. // Signal handling for graceful termination.
  96. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  97. signals_handler.wait_termination(signals_task).await?;
  98. info!(target: "minerd", "Caught termination signal, cleaning up and exiting");
  99. info!(target: "minerd", "Stopping miner threads...");
  100. sender.send(()).await?;
  101. info!(target: "minerd", "Stopping JSON-RPC server...");
  102. rpc_task.stop().await;
  103. info!(target: "minerd", "Shut down successfully");
  104. Ok(())
  105. }