lib.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 smol::{
  20. channel::{Receiver, Sender},
  21. lock::Mutex,
  22. };
  23. use tracing::{error, info};
  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 {
  134. darkfi::util::logger::{setup_test_logger, Level},
  135. tracing::warn,
  136. url::Url,
  137. };
  138. #[test]
  139. /// Test the programmatic control of `Minerd`.
  140. ///
  141. /// First we initialize a daemon, start it and then perform
  142. /// couple of restarts to verify everything works as expected.
  143. fn minerd_programmatic_control() -> Result<()> {
  144. // We check this error so we can execute same file tests in parallel,
  145. // otherwise second one fails to init logger here.
  146. if setup_test_logger(
  147. &[],
  148. false,
  149. Level::Info,
  150. //Level::Verbose,
  151. //Level::Debug,
  152. //Level::Trace,
  153. )
  154. .is_err()
  155. {
  156. warn!(target: "minerd_programmatic_control", "Logger already initialized");
  157. }
  158. // Daemon configuration
  159. let threads = 4;
  160. let rpc_settings =
  161. RpcSettings { listen: Url::parse("tcp://127.0.0.1:28467")?, ..RpcSettings::default() };
  162. // Create an executor and communication signals
  163. let ex = Arc::new(smol::Executor::new());
  164. let (signal, shutdown) = smol::channel::unbounded::<()>();
  165. // Generate a dummy mining job
  166. let target = darkfi::rpc::util::JsonValue::String(
  167. num_bigint::BigUint::from_bytes_be(&[0xFF; 32]).to_string(),
  168. );
  169. let block = darkfi::rpc::util::JsonValue::String(darkfi::util::encoding::base64::encode(
  170. &darkfi_serial::serialize(&darkfi::blockchain::BlockInfo::default()),
  171. ));
  172. let mining_job = darkfi::rpc::jsonrpc::JsonRequest::new(
  173. "mine",
  174. darkfi::rpc::util::JsonValue::Array(vec![target, block]),
  175. );
  176. easy_parallel::Parallel::new()
  177. .each(0..threads, |_| smol::block_on(ex.run(shutdown.recv())))
  178. .finish(|| {
  179. smol::block_on(async {
  180. // Initialize a daemon
  181. let daemon = Minerd::init(threads, 0);
  182. // Start it
  183. daemon.start(&ex, &rpc_settings);
  184. // Generate a JSON-RPC client to send mining jobs
  185. let mut rpc_client =
  186. darkfi::rpc::client::RpcClient::new(rpc_settings.listen.clone(), ex.clone())
  187. .await;
  188. while rpc_client.is_err() {
  189. rpc_client = darkfi::rpc::client::RpcClient::new(
  190. rpc_settings.listen.clone(),
  191. ex.clone(),
  192. )
  193. .await;
  194. }
  195. let rpc_client = rpc_client.unwrap();
  196. // Send a mining job but stop the daemon after it starts mining
  197. smol::future::or(
  198. async {
  199. let _ = rpc_client.request(mining_job).await;
  200. },
  201. async {
  202. // Wait node to start mining
  203. darkfi::system::sleep(2).await;
  204. daemon.stop().await.unwrap();
  205. },
  206. )
  207. .await;
  208. rpc_client.stop().await;
  209. // Start it again
  210. daemon.start(&ex, &rpc_settings);
  211. // Stop it
  212. daemon.stop().await.unwrap();
  213. // Shutdown entirely
  214. drop(signal);
  215. })
  216. });
  217. Ok(())
  218. }