lib.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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::{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. self.node.sender.send(()).await?;
  116. // Stop the JSON-RPC task
  117. info!(target: "minerd::Minerd::stop", "Stopping JSON-RPC server...");
  118. self.rpc_task.stop().await;
  119. // Consume channel item so its empty again
  120. if self.node.stop_signal.is_full() {
  121. self.node.stop_signal.recv().await?;
  122. }
  123. info!(target: "minerd::Minerd::stop", "Mining daemon terminated successfully!");
  124. Ok(())
  125. }
  126. }
  127. #[cfg(test)]
  128. use url::Url;
  129. #[test]
  130. /// Test the programmatic control of `Minerd`.
  131. ///
  132. /// First we initialize a daemon, start it and then perform
  133. /// couple of restarts to verify everything works as expected.
  134. fn minerd_programmatic_control() -> Result<()> {
  135. // Initialize logger
  136. let mut cfg = simplelog::ConfigBuilder::new();
  137. // We check this error so we can execute same file tests in parallel,
  138. // otherwise second one fails to init logger here.
  139. if simplelog::TermLogger::init(
  140. simplelog::LevelFilter::Info,
  141. //simplelog::LevelFilter::Debug,
  142. //simplelog::LevelFilter::Trace,
  143. cfg.build(),
  144. simplelog::TerminalMode::Mixed,
  145. simplelog::ColorChoice::Auto,
  146. )
  147. .is_err()
  148. {
  149. log::debug!(target: "minerd_programmatic_control", "Logger initialized");
  150. }
  151. // Daemon configuration
  152. let threads = 4;
  153. let rpc_settings =
  154. RpcSettings { listen: Url::parse("tcp://127.0.0.1:28467")?, ..RpcSettings::default() };
  155. // Create an executor and communication signals
  156. let ex = Arc::new(smol::Executor::new());
  157. let (signal, shutdown) = smol::channel::unbounded::<()>();
  158. // Generate a dummy mining job
  159. let target = darkfi::rpc::util::JsonValue::String(
  160. num_bigint::BigUint::from_bytes_be(&[0xFF; 32]).to_string(),
  161. );
  162. let block = darkfi::rpc::util::JsonValue::String(darkfi::util::encoding::base64::encode(
  163. &darkfi_serial::serialize(&darkfi::blockchain::BlockInfo::default()),
  164. ));
  165. let mining_job = darkfi::rpc::jsonrpc::JsonRequest::new(
  166. "mine",
  167. darkfi::rpc::util::JsonValue::Array(vec![target, block]),
  168. );
  169. easy_parallel::Parallel::new()
  170. .each(0..threads, |_| smol::block_on(ex.run(shutdown.recv())))
  171. .finish(|| {
  172. smol::block_on(async {
  173. // Initialize a daemon
  174. let daemon = Minerd::init(threads, 0);
  175. // Start it
  176. daemon.start(&ex, &rpc_settings);
  177. // Generate a JSON-RPC client to send mining jobs
  178. let mut rpc_client =
  179. darkfi::rpc::client::RpcClient::new(rpc_settings.listen.clone(), ex.clone())
  180. .await;
  181. while rpc_client.is_err() {
  182. rpc_client = darkfi::rpc::client::RpcClient::new(
  183. rpc_settings.listen.clone(),
  184. ex.clone(),
  185. )
  186. .await;
  187. }
  188. let rpc_client = rpc_client.unwrap();
  189. // Send a mining job but stop the daemon after it starts mining
  190. smol::future::or(
  191. async {
  192. rpc_client.request(mining_job).await.unwrap();
  193. },
  194. async {
  195. // Wait node to start mining
  196. darkfi::system::sleep(2).await;
  197. daemon.stop().await.unwrap();
  198. },
  199. )
  200. .await;
  201. rpc_client.stop().await;
  202. // Start it again
  203. daemon.start(&ex, &rpc_settings);
  204. // Stop it
  205. daemon.stop().await.unwrap();
  206. // Shutdown entirely
  207. drop(signal);
  208. })
  209. });
  210. Ok(())
  211. }