miner.rs 14 KB

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