miner.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 darkfi::{
  19. blockchain::{BlockInfo, Header, HeaderHash},
  20. rpc::{jsonrpc::JsonNotification, util::JsonValue},
  21. system::{ExecutorPtr, StoppableTask, Subscription},
  22. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  23. util::{encoding::base64, time::Timestamp},
  24. validator::{
  25. consensus::{Fork, Proposal},
  26. utils::best_fork_index,
  27. verification::apply_producer_transaction,
  28. },
  29. zk::{empty_witnesses, ProvingKey, ZkCircuit},
  30. zkas::ZkBinary,
  31. Error, Result,
  32. };
  33. use darkfi_money_contract::{
  34. client::pow_reward_v1::PoWRewardCallBuilder, MoneyFunction, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  35. };
  36. use darkfi_sdk::{
  37. crypto::{poseidon_hash, FuncId, MerkleTree, PublicKey, SecretKey, MONEY_CONTRACT_ID},
  38. pasta::pallas,
  39. ContractCall,
  40. };
  41. use darkfi_serial::{serialize_async, Encodable};
  42. use log::{error, info};
  43. use num_bigint::BigUint;
  44. use rand::rngs::OsRng;
  45. use smol::channel::{Receiver, Sender};
  46. use crate::{proto::ProposalMessage, task::garbage_collect_task, DarkfiNodePtr};
  47. /// Auxiliary structure representing node miner rewards recipient configuration
  48. pub struct MinerRewardsRecipientConfig {
  49. pub recipient: PublicKey,
  50. pub spend_hook: Option<FuncId>,
  51. pub user_data: Option<pallas::Base>,
  52. }
  53. /// Async task used for participating in the PoW block production.
  54. ///
  55. /// Miner initializes their setup and waits for next confirmation,
  56. /// by listenning for new proposals from the network, for optimal
  57. /// conditions. After confirmation occurs, they start the actual
  58. /// miner loop, where they first grab the best ranking fork to extend,
  59. /// and start mining procedure for its next block. Additionally, they
  60. /// listen to the network for new proposals, and check if these
  61. /// proposals produce a new best ranking fork. If they do, the stop
  62. /// mining. These two tasks run in parallel, and after one of them
  63. /// finishes, node triggers confirmation check.
  64. pub async fn miner_task(
  65. node: &DarkfiNodePtr,
  66. recipient_config: &MinerRewardsRecipientConfig,
  67. skip_sync: bool,
  68. ex: &ExecutorPtr,
  69. ) -> Result<()> {
  70. // Initialize miner configuration
  71. info!(target: "darkfid::task::miner_task", "Starting miner task...");
  72. // Grab zkas proving keys and bin for PoWReward transaction
  73. info!(target: "darkfid::task::miner_task", "Generating zkas bin and proving keys...");
  74. let (zkbin, _) = node.validator.blockchain.contracts.get_zkas(
  75. &node.validator.blockchain.sled_db,
  76. &MONEY_CONTRACT_ID,
  77. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  78. )?;
  79. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  80. let pk = ProvingKey::build(zkbin.k, &circuit);
  81. // Generate a random master secret key, to derive all signing keys from.
  82. // This enables us to deanonimize proposals from reward recipient(miner).
  83. // TODO: maybe miner wants to keep this master secret so they can
  84. // verify their signature in the future?
  85. info!(target: "darkfid::task::miner_task", "Generating signing key...");
  86. let mut secret = SecretKey::random(&mut OsRng);
  87. // Grab blocks subscriber
  88. let block_sub = node.subscribers.get("blocks").unwrap();
  89. // Grab proposals subscriber and subscribe to it
  90. let proposals_sub = node.subscribers.get("proposals").unwrap();
  91. let subscription = proposals_sub.publisher.clone().subscribe().await;
  92. // Listen for blocks until next confirmation, for optimal conditions
  93. if !skip_sync {
  94. info!(target: "darkfid::task::miner_task", "Waiting for next confirmation...");
  95. loop {
  96. subscription.receive().await;
  97. // Check if we can confirmation anything and broadcast them
  98. let confirmed = node.validator.confirmation().await?;
  99. if confirmed.is_empty() {
  100. continue
  101. }
  102. let mut notif_blocks = Vec::with_capacity(confirmed.len());
  103. for block in confirmed {
  104. notif_blocks
  105. .push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
  106. }
  107. block_sub.notify(JsonValue::Array(notif_blocks)).await;
  108. break;
  109. }
  110. }
  111. // Create channels so threads can signal each other
  112. let (sender, stop_signal) = smol::channel::bounded(1);
  113. // Create the garbage collection task using a dummy task
  114. let gc_task = StoppableTask::new();
  115. gc_task.clone().start(
  116. async { Ok(()) },
  117. |_| async { /* Do nothing */ },
  118. Error::GarbageCollectionTaskStopped,
  119. ex.clone(),
  120. );
  121. info!(target: "darkfid::task::miner_task", "Miner initialized successfully!");
  122. // Start miner loop
  123. loop {
  124. // Grab best current fork
  125. let forks = node.validator.consensus.forks.read().await;
  126. let index = match best_fork_index(&forks) {
  127. Ok(i) => i,
  128. Err(e) => {
  129. error!(
  130. target: "darkfid::task::miner_task",
  131. "Finding best fork index failed: {e}"
  132. );
  133. continue
  134. }
  135. };
  136. let extended_fork = match forks[index].full_clone() {
  137. Ok(f) => f,
  138. Err(e) => {
  139. error!(
  140. target: "darkfid::task::miner_task",
  141. "Fork full clone creation failed: {e}"
  142. );
  143. continue
  144. }
  145. };
  146. drop(forks);
  147. // Grab extended fork last proposal hash
  148. let last_proposal_hash = extended_fork.last_proposal()?.hash;
  149. // Start listenning for network proposals and mining next block for best fork.
  150. match smol::future::or(
  151. listen_to_network(node, last_proposal_hash, &subscription, &sender),
  152. mine(
  153. node,
  154. extended_fork,
  155. &mut secret,
  156. recipient_config,
  157. &zkbin,
  158. &pk,
  159. &stop_signal,
  160. skip_sync,
  161. ),
  162. )
  163. .await
  164. {
  165. Ok(_) => { /* Do nothing */ }
  166. Err(Error::NetworkNotConnected) => {
  167. error!(target: "darkfid::task::miner_task", "Node disconnected from the network");
  168. subscription.unsubscribe().await;
  169. return Err(Error::NetworkNotConnected)
  170. }
  171. Err(e) => {
  172. error!(
  173. target: "darkfid::task::miner_task",
  174. "Error during listen_to_network() or mine(): {e}"
  175. );
  176. continue
  177. }
  178. }
  179. // Check if we can confirm anything and broadcast them
  180. let confirmed = match node.validator.confirmation().await {
  181. Ok(f) => f,
  182. Err(e) => {
  183. error!(
  184. target: "darkfid::task::miner_task",
  185. "Confirmation failed: {e}"
  186. );
  187. continue
  188. }
  189. };
  190. if confirmed.is_empty() {
  191. continue
  192. }
  193. let mut notif_blocks = Vec::with_capacity(confirmed.len());
  194. for block in confirmed {
  195. notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
  196. }
  197. block_sub.notify(JsonValue::Array(notif_blocks)).await;
  198. // Invoke the detached garbage collection task
  199. gc_task.clone().stop().await;
  200. gc_task.clone().start(
  201. garbage_collect_task(node.clone()),
  202. |res| async {
  203. match res {
  204. Ok(()) | Err(Error::GarbageCollectionTaskStopped) => { /* Do nothing */ }
  205. Err(e) => {
  206. error!(target: "darkfid", "Failed starting garbage collection task: {}", e)
  207. }
  208. }
  209. },
  210. Error::GarbageCollectionTaskStopped,
  211. ex.clone(),
  212. );
  213. }
  214. }
  215. /// Async task to listen for incoming proposals and check if the best fork has changed.
  216. async fn listen_to_network(
  217. node: &DarkfiNodePtr,
  218. last_proposal_hash: HeaderHash,
  219. subscription: &Subscription<JsonNotification>,
  220. sender: &Sender<()>,
  221. ) -> Result<()> {
  222. loop {
  223. // Wait until a new proposal has been received
  224. subscription.receive().await;
  225. // Grab a lock over node forks
  226. let forks = node.validator.consensus.forks.read().await;
  227. // Grab best current fork index
  228. let index = best_fork_index(&forks)?;
  229. // Verify if proposals sequence has changed
  230. if forks[index].last_proposal()?.hash != last_proposal_hash {
  231. drop(forks);
  232. break
  233. }
  234. drop(forks);
  235. }
  236. // Signal miner to abort mining
  237. sender.send(()).await?;
  238. if let Err(e) = node.miner_daemon_request("abort", &JsonValue::Array(vec![])).await {
  239. error!(target: "darkfid::task::miner::listen_to_network", "Failed to execute miner daemon abort request: {}", e);
  240. }
  241. Ok(())
  242. }
  243. /// Async task to generate and mine provided fork index next block,
  244. /// while listening for a stop signal.
  245. #[allow(clippy::too_many_arguments)]
  246. async fn mine(
  247. node: &DarkfiNodePtr,
  248. extended_fork: Fork,
  249. secret: &mut SecretKey,
  250. recipient_config: &MinerRewardsRecipientConfig,
  251. zkbin: &ZkBinary,
  252. pk: &ProvingKey,
  253. stop_signal: &Receiver<()>,
  254. skip_sync: bool,
  255. ) -> Result<()> {
  256. smol::future::or(
  257. wait_stop_signal(stop_signal),
  258. mine_next_block(node, extended_fork, secret, recipient_config, zkbin, pk, skip_sync),
  259. )
  260. .await
  261. }
  262. /// Async task to wait for listener's stop signal.
  263. pub async fn wait_stop_signal(stop_signal: &Receiver<()>) -> Result<()> {
  264. // Clean stop signal channel
  265. if stop_signal.is_full() {
  266. stop_signal.recv().await?;
  267. }
  268. // Wait for listener signal
  269. stop_signal.recv().await?;
  270. Ok(())
  271. }
  272. /// Async task to generate and mine provided fork index next block.
  273. async fn mine_next_block(
  274. node: &DarkfiNodePtr,
  275. mut extended_fork: Fork,
  276. secret: &mut SecretKey,
  277. recipient_config: &MinerRewardsRecipientConfig,
  278. zkbin: &ZkBinary,
  279. pk: &ProvingKey,
  280. skip_sync: bool,
  281. ) -> Result<()> {
  282. // Grab next target and block
  283. let (next_target, mut next_block) = generate_next_block(
  284. &mut extended_fork,
  285. secret,
  286. recipient_config,
  287. zkbin,
  288. pk,
  289. node.validator.consensus.module.read().await.target,
  290. node.validator.verify_fees,
  291. )
  292. .await?;
  293. // Execute request to minerd and parse response
  294. let target = JsonValue::String(next_target.to_string());
  295. let block = JsonValue::String(base64::encode(&serialize_async(&next_block).await));
  296. let response =
  297. node.miner_daemon_request_with_retry("mine", &JsonValue::Array(vec![target, block])).await;
  298. next_block.header.nonce = *response.get::<f64>().unwrap() as u64;
  299. // Sign the mined block
  300. next_block.sign(secret);
  301. // Verify it
  302. extended_fork.module.verify_current_block(&next_block)?;
  303. // Check if we are connected to the network
  304. if !skip_sync && !node.p2p_handler.p2p.is_connected() {
  305. return Err(Error::NetworkNotConnected)
  306. }
  307. // Append the mined block as a proposal
  308. let proposal = Proposal::new(next_block);
  309. node.validator.append_proposal(&proposal).await?;
  310. // Broadcast proposal to the network
  311. let message = ProposalMessage(proposal);
  312. node.p2p_handler.p2p.broadcast(&message).await;
  313. Ok(())
  314. }
  315. /// Auxiliary function to generate next block in an atomic manner.
  316. async fn generate_next_block(
  317. extended_fork: &mut Fork,
  318. secret: &mut SecretKey,
  319. recipient_config: &MinerRewardsRecipientConfig,
  320. zkbin: &ZkBinary,
  321. pk: &ProvingKey,
  322. block_target: u32,
  323. verify_fees: bool,
  324. ) -> Result<(BigUint, BlockInfo)> {
  325. // Grab forks' last block proposal(previous)
  326. let last_proposal = extended_fork.last_proposal()?;
  327. // Grab forks' next block height
  328. let next_block_height = last_proposal.block.header.height + 1;
  329. // Grab forks' unproposed transactions
  330. let (mut txs, _, fees, overlay) = extended_fork
  331. .unproposed_txs(&extended_fork.blockchain, next_block_height, block_target, verify_fees)
  332. .await?;
  333. // We are deriving the next secret key for optimization.
  334. // Next secret is the poseidon hash of:
  335. // [prefix, current(previous) secret, signing(block) height].
  336. let prefix = pallas::Base::from_raw([4, 0, 0, 0]);
  337. let next_secret = poseidon_hash([prefix, secret.inner(), (next_block_height as u64).into()]);
  338. *secret = SecretKey::from(next_secret);
  339. // Generate reward transaction
  340. let tx = generate_transaction(next_block_height, fees, secret, recipient_config, zkbin, pk)?;
  341. // Apply producer transaction in the overlay
  342. let _ = apply_producer_transaction(
  343. &overlay,
  344. next_block_height,
  345. block_target,
  346. &tx,
  347. &mut MerkleTree::new(1),
  348. )
  349. .await?;
  350. txs.push(tx);
  351. // Grab the updated contracts states root
  352. overlay.lock().unwrap().contracts.update_state_monotree(&mut extended_fork.state_monotree)?;
  353. let Some(state_root) = extended_fork.state_monotree.get_headroot()? else {
  354. return Err(Error::ContractsStatesRootNotFoundError);
  355. };
  356. // Drop new trees opened by the unproposed transactions overlay
  357. overlay.lock().unwrap().overlay.lock().unwrap().purge_new_trees()?;
  358. // Generate the new header
  359. let mut header =
  360. Header::new(last_proposal.hash, next_block_height, Timestamp::current_time(), 0);
  361. header.state_root = state_root;
  362. // Generate the block
  363. let mut next_block = BlockInfo::new_empty(header);
  364. // Add transactions to the block
  365. next_block.append_txs(txs);
  366. // Grab the next mine target
  367. let target = extended_fork.module.next_mine_target()?;
  368. Ok((target, next_block))
  369. }
  370. /// Auxiliary function to generate a Money::PoWReward transaction.
  371. fn generate_transaction(
  372. block_height: u32,
  373. fees: u64,
  374. secret: &SecretKey,
  375. recipient_config: &MinerRewardsRecipientConfig,
  376. zkbin: &ZkBinary,
  377. pk: &ProvingKey,
  378. ) -> Result<Transaction> {
  379. // Build the transaction debris
  380. let debris = PoWRewardCallBuilder {
  381. signature_public: PublicKey::from_secret(*secret),
  382. block_height,
  383. fees,
  384. recipient: Some(recipient_config.recipient),
  385. spend_hook: recipient_config.spend_hook,
  386. user_data: recipient_config.user_data,
  387. mint_zkbin: zkbin.clone(),
  388. mint_pk: pk.clone(),
  389. }
  390. .build()?;
  391. // Generate and sign the actual transaction
  392. let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
  393. debris.params.encode(&mut data)?;
  394. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  395. let mut tx_builder =
  396. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  397. let mut tx = tx_builder.build()?;
  398. let sigs = tx.create_sigs(&[*secret])?;
  399. tx.signatures = vec![sigs];
  400. Ok(tx)
  401. }