lib.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. };
  24. use darkfi::{
  25. rpc::{
  26. server::{listen_and_serve, RequestHandler},
  27. settings::RpcSettings,
  28. },
  29. system::{sleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  30. Error, Result,
  31. };
  32. /// Daemon error codes
  33. mod error;
  34. /// JSON-RPC server methods
  35. mod rpc;
  36. /// Atomic pointer to the DarkFi mining node
  37. pub type MinerNodePtr = Arc<MinerNode>;
  38. /// Structure representing a DarkFi mining node
  39. pub struct MinerNode {
  40. /// PoW miner number of threads to use
  41. threads: usize,
  42. /// Stop mining at this height
  43. stop_at_height: u32,
  44. /// Sender to stop miner threads
  45. sender: Sender<()>,
  46. /// Receiver to stop miner threads
  47. stop_signal: Receiver<()>,
  48. /// JSON-RPC connection tracker
  49. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  50. }
  51. impl MinerNode {
  52. pub fn new(
  53. threads: usize,
  54. stop_at_height: u32,
  55. sender: Sender<()>,
  56. stop_signal: Receiver<()>,
  57. ) -> MinerNodePtr {
  58. Arc::new(Self {
  59. threads,
  60. stop_at_height,
  61. sender,
  62. stop_signal,
  63. rpc_connections: Mutex::new(HashSet::new()),
  64. })
  65. }
  66. }
  67. /// Atomic pointer to the DarkFi mining daemon
  68. pub type MinerdPtr = Arc<Minerd>;
  69. /// Structure representing a DarkFi mining daemon
  70. pub struct Minerd {
  71. /// Miner node instance conducting the mining operations
  72. node: MinerNodePtr,
  73. /// JSON-RPC background task
  74. rpc_task: StoppableTaskPtr,
  75. }
  76. impl Minerd {
  77. /// Initialize a DarkFi mining daemon.
  78. ///
  79. /// Corresponding communication channels are setup to generate a new `MinerNode`,
  80. /// and a new task is generated to handle the JSON-RPC API.
  81. pub fn init(threads: usize, stop_at_height: u32) -> MinerdPtr {
  82. info!(target: "minerd::Minerd::init", "Initializing a new mining daemon...");
  83. // Initialize the smol channels to send signal between the threads
  84. let (sender, stop_signal) = smol::channel::bounded(1);
  85. // Generate the node
  86. let node = MinerNode::new(threads, stop_at_height, sender, stop_signal);
  87. // Generate the JSON-RPC task
  88. let rpc_task = StoppableTask::new();
  89. info!(target: "minerd::Minerd::init", "Mining daemon initialized successfully!");
  90. Arc::new(Self { node, rpc_task })
  91. }
  92. /// Start the DarkFi mining daemon in the given executor, using the provided JSON-RPC listen url.
  93. pub fn start(&self, executor: &ExecutorPtr, rpc_settings: &RpcSettings) {
  94. info!(target: "minerd::Minerd::start", "Starting mining daemon...");
  95. // Start the JSON-RPC task
  96. let node_ = self.node.clone();
  97. self.rpc_task.clone().start(
  98. listen_and_serve(rpc_settings.clone(), self.node.clone(), None, executor.clone()),
  99. |res| async move {
  100. match res {
  101. Ok(()) | Err(Error::RpcServerStopped) => node_.stop_connections().await,
  102. Err(e) => error!(target: "minerd::Minerd::start", "Failed starting JSON-RPC server: {e}"),
  103. }
  104. },
  105. Error::RpcServerStopped,
  106. executor.clone(),
  107. );
  108. info!(target: "minerd::Minerd::start", "Mining daemon started successfully!");
  109. }
  110. /// Stop the DarkFi mining daemon.
  111. pub async fn stop(&self) -> Result<()> {
  112. info!(target: "minerd::Minerd::stop", "Terminating mining daemon...");
  113. // Stop the mining node
  114. info!(target: "minerd::Minerd::stop", "Stopping miner threads...");
  115. if self.node.stop_signal.is_empty() {
  116. self.node.sender.send(()).await?;
  117. }
  118. while self.node.stop_signal.receiver_count() > 1 {
  119. sleep(1).await;
  120. }
  121. // Stop the JSON-RPC task
  122. info!(target: "minerd::Minerd::stop", "Stopping JSON-RPC server...");
  123. self.rpc_task.stop().await;
  124. // Consume channel item so its empty again
  125. if self.node.stop_signal.is_full() {
  126. self.node.stop_signal.recv().await?;
  127. }
  128. info!(target: "minerd::Minerd::stop", "Mining daemon terminated successfully!");
  129. Ok(())
  130. }
  131. }
  132. #[cfg(test)]
  133. use url::Url;
  134. #[test]
  135. /// Test the programmatic control of `Minerd`.
  136. ///
  137. /// First we initialize a daemon, start it and then perform
  138. /// couple of restarts to verify everything works as expected.
  139. fn minerd_programmatic_control() -> Result<()> {
  140. // Initialize logger
  141. let mut cfg = simplelog::ConfigBuilder::new();
  142. // We check this error so we can execute same file tests in parallel,
  143. // otherwise second one fails to init logger here.
  144. if simplelog::TermLogger::init(
  145. simplelog::LevelFilter::Info,
  146. //simplelog::LevelFilter::Debug,
  147. //simplelog::LevelFilter::Trace,
  148. cfg.build(),
  149. simplelog::TerminalMode::Mixed,
  150. simplelog::ColorChoice::Auto,
  151. )
  152. .is_err()
  153. {
  154. log::debug!(target: "minerd_programmatic_control", "Logger initialized");
  155. }
  156. // Daemon configuration
  157. let threads = 4;
  158. let rpc_settings =
  159. RpcSettings { listen: Url::parse("tcp://127.0.0.1:28467")?, ..RpcSettings::default() };
  160. // Create an executor and communication signals
  161. let ex = Arc::new(smol::Executor::new());
  162. let (signal, shutdown) = smol::channel::unbounded::<()>();
  163. // Generate a dummy mining job
  164. let target = darkfi::rpc::util::JsonValue::String(
  165. num_bigint::BigUint::from_bytes_be(&[0xFF; 32]).to_string(),
  166. );
  167. let block = darkfi::rpc::util::JsonValue::String(darkfi::util::encoding::base64::encode(
  168. &darkfi_serial::serialize(&darkfi::blockchain::BlockInfo::default()),
  169. ));
  170. let mining_job = darkfi::rpc::jsonrpc::JsonRequest::new(
  171. "mine",
  172. darkfi::rpc::util::JsonValue::Array(vec![target, block]),
  173. );
  174. easy_parallel::Parallel::new()
  175. .each(0..threads, |_| smol::block_on(ex.run(shutdown.recv())))
  176. .finish(|| {
  177. smol::block_on(async {
  178. // Initialize a daemon
  179. let daemon = Minerd::init(threads, 0);
  180. // Start it
  181. daemon.start(&ex, &rpc_settings);
  182. // Generate a JSON-RPC client to send mining jobs
  183. let mut rpc_client =
  184. darkfi::rpc::client::RpcClient::new(rpc_settings.listen.clone(), ex.clone())
  185. .await;
  186. while rpc_client.is_err() {
  187. rpc_client = darkfi::rpc::client::RpcClient::new(
  188. rpc_settings.listen.clone(),
  189. ex.clone(),
  190. )
  191. .await;
  192. }
  193. let rpc_client = rpc_client.unwrap();
  194. // Send a mining job but stop the daemon after it starts mining
  195. smol::future::or(
  196. async {
  197. let _ = rpc_client.request(mining_job).await;
  198. },
  199. async {
  200. // Wait node to start mining
  201. darkfi::system::sleep(2).await;
  202. daemon.stop().await.unwrap();
  203. },
  204. )
  205. .await;
  206. rpc_client.stop().await;
  207. // Start it again
  208. daemon.start(&ex, &rpc_settings);
  209. // Stop it
  210. daemon.stop().await.unwrap();
  211. // Shutdown entirely
  212. drop(signal);
  213. })
  214. });
  215. Ok(())
  216. }