lib.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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::HashMap, sync::Arc};
  19. use smol::{
  20. channel::{Receiver, Sender},
  21. lock::RwLock,
  22. };
  23. use tracing::{debug, error, info};
  24. use url::Url;
  25. use darkfi::{
  26. rpc::util::JsonValue,
  27. system::{sleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  28. Error,
  29. };
  30. use darkfi_sdk::crypto::Keypair;
  31. /// darkfid JSON-RPC related methods
  32. mod rpc;
  33. use rpc::{polling_task, DarkfidRpcClient};
  34. /// Auxiliary structure representing miner node configuration.
  35. pub struct MinerNodeConfig {
  36. /// PoW miner number of threads to use
  37. threads: usize,
  38. /// Polling rate to ask darkfid for mining jobs
  39. polling_rate: u64,
  40. /// Stop mining at this height (0 mines forever)
  41. stop_at_height: u32,
  42. /// Wallet mining configuration to receive mining rewards
  43. wallet_config: HashMap<String, JsonValue>,
  44. }
  45. impl Default for MinerNodeConfig {
  46. fn default() -> Self {
  47. Self::new(
  48. 1,
  49. 5,
  50. 0,
  51. HashMap::from([(
  52. String::from("recipient"),
  53. JsonValue::String(Keypair::default().public.to_string()),
  54. )]),
  55. )
  56. }
  57. }
  58. impl MinerNodeConfig {
  59. pub fn new(
  60. threads: usize,
  61. polling_rate: u64,
  62. stop_at_height: u32,
  63. wallet_config: HashMap<String, JsonValue>,
  64. ) -> Self {
  65. Self { threads, polling_rate, stop_at_height, wallet_config }
  66. }
  67. }
  68. /// Atomic pointer to the DarkFi mining node
  69. pub type MinerNodePtr = Arc<MinerNode>;
  70. /// Structure representing a DarkFi mining node
  71. pub struct MinerNode {
  72. /// Node configuration
  73. config: MinerNodeConfig,
  74. /// Sender and receiver to stop mining threads
  75. mining_channel: (Sender<()>, Receiver<()>),
  76. /// Sender and receiver to stop background threads
  77. background_channel: (Sender<()>, Receiver<()>),
  78. /// JSON-RPC client to execute requests to darkfid daemon
  79. rpc_client: RwLock<DarkfidRpcClient>,
  80. }
  81. impl MinerNode {
  82. pub async fn new(config: MinerNodeConfig, endpoint: Url, ex: &ExecutorPtr) -> MinerNodePtr {
  83. // Initialize the smol channels to send signal between the threads
  84. let mining_channel = smol::channel::bounded(1);
  85. let background_channel = smol::channel::bounded(1);
  86. // Initialize JSON-RPC client
  87. let rpc_client = RwLock::new(DarkfidRpcClient::new(endpoint, ex.clone()).await);
  88. Arc::new(Self { config, mining_channel, background_channel, rpc_client })
  89. }
  90. /// Auxiliary function to abort all pending tasks.
  91. pub async fn abort(&self) {
  92. self.abort_mining().await;
  93. self.abort_background().await;
  94. }
  95. /// Auxiliary function to abort pending mining task.
  96. pub async fn abort_mining(&self) {
  97. Self::abort_task(&self.mining_channel.0, &self.mining_channel.1, "mining").await;
  98. }
  99. /// Auxiliary function to abort pending background Randomx VMs
  100. /// generation task.
  101. pub async fn abort_background(&self) {
  102. Self::abort_task(&self.background_channel.0, &self.background_channel.1, "VMs generation")
  103. .await;
  104. }
  105. /// Auxiliary function to abort pending task by signaling provided
  106. /// channels.
  107. async fn abort_task(sender: &Sender<()>, stop_signal: &Receiver<()>, task: &str) {
  108. // Check if a pending task is being processed
  109. debug!(target: "minerd::abort_task", "Checking if a pending {task} task is being processed...");
  110. if stop_signal.receiver_count() <= 1 {
  111. debug!(target: "minerd::abort_task", "No pending {task} task!");
  112. return
  113. }
  114. info!(target: "minerd::abort_task", "Pending {task} is in progress, sending stop signal...");
  115. // Send stop signal to worker
  116. if let Err(e) = sender.try_send(()) {
  117. error!(target: "minerd::abort_task", "Failed to stop pending {task} task: {e}");
  118. return
  119. }
  120. // Wait for worker to terminate
  121. info!(target: "minerd::abort_task", "Waiting for {task} task to terminate...");
  122. while stop_signal.receiver_count() > 1 {
  123. sleep(1).await;
  124. }
  125. info!(target: "minerd::abort_task", "Pending {task} task terminated!");
  126. // Consume channel item so its empty again
  127. if let Err(e) = stop_signal.try_recv() {
  128. error!(target: "minerd::abort_task", "Failed to cleanup stop signal channel: {e}");
  129. }
  130. }
  131. }
  132. /// Atomic pointer to the DarkFi mining daemon
  133. pub type MinerdPtr = Arc<Minerd>;
  134. /// Structure representing a DarkFi mining daemon
  135. pub struct Minerd {
  136. /// Miner node instance conducting the mining operations
  137. node: MinerNodePtr,
  138. /// Miner darkfid polling background task
  139. polling_task: StoppableTaskPtr,
  140. }
  141. impl Minerd {
  142. /// Initialize a DarkFi mining daemon.
  143. ///
  144. /// Generate a new `MinerNode` and a new task to handle the darkfid
  145. /// polling.
  146. pub async fn init(config: MinerNodeConfig, endpoint: Url, ex: &ExecutorPtr) -> MinerdPtr {
  147. info!(target: "minerd::Minerd::init", "Initializing a new mining daemon...");
  148. // Generate the node
  149. let node = MinerNode::new(config, endpoint, ex).await;
  150. // Generate the polling task
  151. let polling_task = StoppableTask::new();
  152. info!(target: "minerd::Minerd::init", "Mining daemon initialized successfully!");
  153. Arc::new(Self { node, polling_task })
  154. }
  155. /// Start the DarkFi mining daemon in the given executor.
  156. pub fn start(&self, ex: &ExecutorPtr) {
  157. info!(target: "minerd::Minerd::start", "Starting mining daemon...");
  158. // Start the polling task
  159. self.polling_task.clone().start(
  160. polling_task(self.node.clone(), ex.clone()),
  161. |res| async {
  162. match res {
  163. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  164. Err(e) => {
  165. error!(target: "minerd::Minerd::start", "Failed starting polling task: {e}")
  166. }
  167. }
  168. },
  169. Error::DetachedTaskStopped,
  170. ex.clone(),
  171. );
  172. info!(target: "minerd::Minerd::start", "Mining daemon started successfully!");
  173. }
  174. /// Stop the DarkFi mining daemon.
  175. pub async fn stop(&self) {
  176. info!(target: "minerd::Minerd::stop", "Terminating mining daemon...");
  177. // Stop the mining node
  178. info!(target: "minerd::Minerd::stop", "Stopping miner background tasks...");
  179. self.node.abort().await;
  180. // Stop the polling task
  181. info!(target: "minerd::Minerd::stop", "Stopping polling task...");
  182. self.polling_task.stop().await;
  183. // Close the JSON-RPC client
  184. info!(target: "minerd::Minerd::stop", "Stopping JSON-RPC client...");
  185. self.node.stop_rpc_client().await;
  186. info!(target: "minerd::Minerd::stop", "Mining daemon terminated successfully!");
  187. }
  188. }
  189. #[cfg(test)]
  190. use {
  191. darkfi::util::logger::{setup_test_logger, Level},
  192. tracing::warn,
  193. };
  194. #[test]
  195. /// Test the programmatic control of `Minerd`.
  196. ///
  197. /// First we initialize a daemon, start it and then perform
  198. /// couple of restarts to verify everything works as expected.
  199. fn minerd_programmatic_control() {
  200. // We check this error so we can execute same file tests in parallel,
  201. // otherwise second one fails to init logger here.
  202. if setup_test_logger(
  203. &[],
  204. false,
  205. Level::Info,
  206. //Level::Verbose,
  207. //Level::Debug,
  208. //Level::Trace,
  209. )
  210. .is_err()
  211. {
  212. warn!(target: "minerd_programmatic_control", "Logger already initialized");
  213. }
  214. // Create an executor and communication signals
  215. let ex = Arc::new(smol::Executor::new());
  216. let (signal, shutdown) = smol::channel::unbounded::<()>();
  217. easy_parallel::Parallel::new().each(0..1, |_| smol::block_on(ex.run(shutdown.recv()))).finish(
  218. || {
  219. smol::block_on(async {
  220. // Initialize a daemon
  221. let daemon = Minerd::init(
  222. MinerNodeConfig::default(),
  223. Url::parse("tcp://127.0.0.1:12345").unwrap(),
  224. &ex,
  225. )
  226. .await;
  227. // Start it
  228. daemon.start(&ex);
  229. // Stop it
  230. daemon.stop().await;
  231. // Start it again
  232. daemon.start(&ex);
  233. // Stop it
  234. daemon.stop().await;
  235. // Shutdown entirely
  236. drop(signal);
  237. })
  238. },
  239. );
  240. }