model.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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, str::FromStr};
  19. use rand::rngs::OsRng;
  20. use tinyjson::JsonValue;
  21. use tracing::info;
  22. use darkfi::{
  23. blockchain::{BlockInfo, Header, HeaderHash},
  24. rpc::jsonrpc::JsonSubscriber,
  25. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  26. util::{
  27. encoding::base64,
  28. time::{NanoTimestamp, Timestamp},
  29. },
  30. validator::{
  31. consensus::Fork,
  32. pow::{RANDOMX_KEY_CHANGE_DELAY, RANDOMX_KEY_CHANGING_HEIGHT},
  33. verification::apply_producer_transaction,
  34. ValidatorPtr,
  35. },
  36. zk::{empty_witnesses, ProvingKey, ZkCircuit},
  37. zkas::ZkBinary,
  38. Error, Result,
  39. };
  40. use darkfi_money_contract::{
  41. client::pow_reward_v1::PoWRewardCallBuilder, model::MoneyPoWRewardParamsV1, MoneyFunction,
  42. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  43. };
  44. use darkfi_sdk::{
  45. crypto::{
  46. keypair::{Address, Keypair, Network, SecretKey},
  47. pasta_prelude::PrimeField,
  48. FuncId, MerkleTree, MONEY_CONTRACT_ID,
  49. },
  50. fee::accumulate_fee,
  51. pasta::pallas,
  52. ContractCall,
  53. };
  54. use darkfi_serial::{deserialize_async, Encodable};
  55. use crate::error::RpcError;
  56. /// Auxiliary structure representing node miner rewards recipient configuration.
  57. #[derive(Debug, Clone)]
  58. pub struct MinerRewardsRecipientConfig {
  59. /// Wallet mining address to receive mining rewards
  60. pub recipient: Address,
  61. /// Optional contract spend hook to use in the mining reward
  62. pub spend_hook: Option<FuncId>,
  63. /// Optional contract user data to use in the mining reward.
  64. /// This is not arbitrary data.
  65. pub user_data: Option<pallas::Base>,
  66. }
  67. impl MinerRewardsRecipientConfig {
  68. pub fn new(
  69. recipient: Address,
  70. spend_hook: Option<FuncId>,
  71. user_data: Option<pallas::Base>,
  72. ) -> Self {
  73. Self { recipient, spend_hook, user_data }
  74. }
  75. /// Auxiliary function to convert provided string to its
  76. /// `MinerRewardsRecipientConfig`. Supports parsing both a normal
  77. /// `Address` and a `base64` encoded mining configuration. Also
  78. /// verifies it corresponds to the provided `Network`.
  79. pub async fn from_str(network: &Network, address: &str) -> std::result::Result<Self, RpcError> {
  80. // Try to parse the string as an `Address`
  81. if let Ok(recipient) = Address::from_str(address) {
  82. if recipient.network() != *network {
  83. return Err(RpcError::MinerInvalidRecipientPrefix)
  84. }
  85. return Ok(Self { recipient, spend_hook: None, user_data: None })
  86. }
  87. // Try to parse the string as a `base64` encoded mining
  88. // configuration
  89. let Some(address_bytes) = base64::decode(address) else {
  90. return Err(RpcError::MinerInvalidWalletConfig)
  91. };
  92. let Ok((recipient, spend_hook, user_data)) =
  93. deserialize_async::<(String, Option<String>, Option<String>)>(&address_bytes).await
  94. else {
  95. return Err(RpcError::MinerInvalidWalletConfig)
  96. };
  97. let Ok(recipient) = Address::from_str(&recipient) else {
  98. return Err(RpcError::MinerInvalidRecipient)
  99. };
  100. if recipient.network() != *network {
  101. return Err(RpcError::MinerInvalidRecipientPrefix)
  102. }
  103. let spend_hook = match spend_hook {
  104. Some(s) => match FuncId::from_str(&s) {
  105. Ok(s) => Some(s),
  106. Err(_) => return Err(RpcError::MinerInvalidSpendHook),
  107. },
  108. None => None,
  109. };
  110. let user_data: Option<pallas::Base> = match user_data {
  111. Some(u) => {
  112. let Ok(bytes) = bs58::decode(&u).into_vec() else {
  113. return Err(RpcError::MinerInvalidUserData)
  114. };
  115. let bytes: [u8; 32] = match bytes.try_into() {
  116. Ok(b) => b,
  117. Err(_) => return Err(RpcError::MinerInvalidUserData),
  118. };
  119. match pallas::Base::from_repr(bytes).into() {
  120. Some(v) => Some(v),
  121. None => return Err(RpcError::MinerInvalidUserData),
  122. }
  123. }
  124. None => None,
  125. };
  126. Ok(Self { recipient, spend_hook, user_data })
  127. }
  128. }
  129. /// Auxiliary structure representing a block template for mining.
  130. #[derive(Debug, Clone)]
  131. pub struct BlockTemplate {
  132. /// Block that is being mined
  133. pub block: BlockInfo,
  134. /// New kvdb trees opened the overlay this block was generated
  135. pub new_trees: Vec<String>,
  136. /// RandomX current and next keys pair
  137. pub randomx_keys: (HeaderHash, Option<HeaderHash>),
  138. /// Compacted block mining target
  139. pub target: Vec<u8>,
  140. /// Block difficulty
  141. pub difficulty: f64,
  142. /// Ephemeral signing secret for this blocktemplate
  143. pub secret: SecretKey,
  144. /// Flag indicating if this template has been submitted
  145. pub submitted: bool,
  146. }
  147. impl BlockTemplate {
  148. fn new(
  149. block: BlockInfo,
  150. new_trees: Vec<String>,
  151. randomx_keys: (HeaderHash, Option<HeaderHash>),
  152. target: Vec<u8>,
  153. difficulty: f64,
  154. secret: SecretKey,
  155. ) -> Self {
  156. Self { block, new_trees, randomx_keys, target, difficulty, secret, submitted: false }
  157. }
  158. pub fn job_notification(&self) -> (String, JsonValue) {
  159. let block_hash = hex::encode(self.block.header.hash().inner()).to_string();
  160. let mut job = HashMap::from([
  161. (
  162. "blob".to_string(),
  163. JsonValue::from(hex::encode(self.block.header.to_block_hashing_blob()).to_string()),
  164. ),
  165. ("job_id".to_string(), JsonValue::from(block_hash.clone())),
  166. ("height".to_string(), JsonValue::from(self.block.header.height as f64)),
  167. ("target".to_string(), JsonValue::from(hex::encode(&self.target))),
  168. ("algo".to_string(), JsonValue::from(String::from("rx/0"))),
  169. (
  170. "seed_hash".to_string(),
  171. JsonValue::from(hex::encode(self.randomx_keys.0.inner()).to_string()),
  172. ),
  173. ]);
  174. if let Some(next_randomx_key) = self.randomx_keys.1 {
  175. job.insert(
  176. "next_seed_hash".to_string(),
  177. JsonValue::from(hex::encode(next_randomx_key.inner()).to_string()),
  178. );
  179. }
  180. (block_hash, JsonValue::from(job))
  181. }
  182. /// Return block full reward.
  183. ///
  184. /// Note: always check if block contains transactions before
  185. /// calling this function.
  186. pub async fn reward(&self) -> Result<u64> {
  187. let Some(producer_tx) = self.block.txs.last() else {
  188. return Err(Error::BlockContainsNoTransactions(
  189. self.block.header.template_hash().as_string(),
  190. ))
  191. };
  192. let Some(call) = producer_tx.calls.first() else {
  193. return Err(Error::ParseFailed("producer transaction contains no calls"))
  194. };
  195. if !call.data.is_money_pow_reward() {
  196. return Err(Error::ParseFailed("producer transaction is not Money::PoWRewardV1"))
  197. }
  198. let params: MoneyPoWRewardParamsV1 = deserialize_async(&call.data.data[1..]).await?;
  199. Ok(params.input.value)
  200. }
  201. /// Return block fees.
  202. ///
  203. /// Note: always check if block contains transactions before
  204. /// calling this function.
  205. pub async fn fees(&self) -> Result<u64> {
  206. let mut fees = 0;
  207. 'outer: for tx in &self.block.txs[..self.block.txs.len() - 1] {
  208. for call in &tx.calls {
  209. if !call.data.is_money_fee() {
  210. continue
  211. }
  212. fees = accumulate_fee(fees, call.data.money_fee_value()?)?;
  213. continue 'outer
  214. }
  215. }
  216. Ok(fees)
  217. }
  218. /// Return block reward excluding fees and fees values.
  219. pub async fn reward_excluding_fees_and_fees(&self) -> Result<(u64, u64)> {
  220. if self.block.txs.is_empty() {
  221. return Err(Error::BlockContainsNoTransactions(
  222. self.block.header.template_hash().as_string(),
  223. ))
  224. }
  225. let fees = self.fees().await?;
  226. let reward = self.reward().await?.checked_sub(fees).ok_or(Error::SubtractionUnderflow)?;
  227. Ok((reward, fees))
  228. }
  229. }
  230. /// Auxiliary structure representing a native miner client record.
  231. #[derive(Debug, Clone)]
  232. pub struct MinerClient {
  233. /// Miner wallet template key
  234. pub wallet: String,
  235. /// Miner recipient configuration
  236. pub config: MinerRewardsRecipientConfig,
  237. /// Current mining job
  238. pub job: String,
  239. /// Connection publisher to push new jobs
  240. pub publisher: JsonSubscriber,
  241. }
  242. impl MinerClient {
  243. pub fn new(wallet: &str, config: &MinerRewardsRecipientConfig, job: &str) -> (String, Self) {
  244. let mut hasher = blake3::Hasher::new();
  245. hasher.update(wallet.as_bytes());
  246. hasher.update(&NanoTimestamp::current_time().inner().to_le_bytes());
  247. let client_id = hex::encode(hasher.finalize().as_bytes()).to_string();
  248. let publisher = JsonSubscriber::new("job");
  249. (
  250. client_id,
  251. Self {
  252. wallet: String::from(wallet),
  253. config: config.clone(),
  254. job: job.to_owned(),
  255. publisher,
  256. },
  257. )
  258. }
  259. }
  260. /// ZK data used to generate the "coinbase" transaction in a block
  261. pub struct PowRewardV1Zk {
  262. pub zkbin: ZkBinary,
  263. pub provingkey: ProvingKey,
  264. }
  265. impl PowRewardV1Zk {
  266. pub async fn new(validator: &ValidatorPtr) -> Result<Self> {
  267. info!(
  268. target: "darkfid::registry::model::PowRewardV1Zk::new",
  269. "Generating PowRewardV1 ZkCircuit and ProvingKey...",
  270. );
  271. let validator = validator.read().await;
  272. let (zkbin, _) = validator
  273. .blockchain
  274. .contracts
  275. .get_zkas(&MONEY_CONTRACT_ID, MONEY_CONTRACT_ZKAS_MINT_NS_V1)?;
  276. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  277. let provingkey = ProvingKey::build(zkbin.k, &circuit);
  278. Ok(Self { zkbin, provingkey })
  279. }
  280. }
  281. /// Auxiliary function to generate next mining block template, in an
  282. /// atomic manner.
  283. pub async fn generate_next_block_template(
  284. extended_fork: &mut Fork,
  285. recipient_config: &MinerRewardsRecipientConfig,
  286. zkbin: &ZkBinary,
  287. pk: &ProvingKey,
  288. verify_fees: bool,
  289. ) -> Result<BlockTemplate> {
  290. // Grab forks' last block proposal(previous)
  291. let last_proposal = extended_fork.last_proposal()?;
  292. // Grab forks' next block height
  293. let next_block_height = last_proposal.block.header.height + 1;
  294. // Grab forks' RandomX keys for that height
  295. let randomx_keys = if next_block_height > RANDOMX_KEY_CHANGING_HEIGHT &&
  296. next_block_height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
  297. {
  298. (
  299. extended_fork
  300. .module
  301. .darkfi_rx_keys
  302. .1
  303. .ok_or_else(|| Error::ParseFailed("darkfi_rx_keys.1 unwrap() error"))?,
  304. None,
  305. )
  306. } else {
  307. extended_fork.module.darkfi_rx_keys
  308. };
  309. // Grab forks' next mine target and difficulty
  310. let (target, difficulty) = extended_fork.module.next_mine_target_and_difficulty()?;
  311. // The target should be compacted to 8 bytes. We'll send the MSB.
  312. let target_bytes = target.to_bytes_le();
  313. let mut padded = [0u8; 32];
  314. let len = target_bytes.len().min(32);
  315. padded[..len].copy_from_slice(&target_bytes[..len]);
  316. let target = padded[24..32].to_vec();
  317. // Cast difficulty to f64. This should always work.
  318. let difficulty = difficulty.to_string().parse()?;
  319. // Grab forks' unproposed transactions
  320. let (mut txs, _, fees) = extended_fork.unproposed_txs(next_block_height, verify_fees).await?;
  321. // Create an ephemeral block signing keypair. Its secret key will
  322. // be stored in the PowReward transaction's encrypted note for
  323. // later retrieval. It is encrypted towards the recipient's public
  324. // key.
  325. let block_signing_keypair = Keypair::random(&mut OsRng);
  326. // Generate reward transaction
  327. let tx = generate_transaction(
  328. next_block_height,
  329. fees,
  330. &block_signing_keypair,
  331. recipient_config,
  332. zkbin,
  333. pk,
  334. )?;
  335. // Apply producer transaction in the forks' overlay
  336. let _ = apply_producer_transaction(
  337. &extended_fork.overlay,
  338. next_block_height,
  339. extended_fork.module.target,
  340. &tx,
  341. &mut MerkleTree::new(1),
  342. )
  343. .await?;
  344. txs.push(tx);
  345. // Grab the updated contracts states root
  346. let diff =
  347. extended_fork.overlay.lock().unwrap().overlay.lock().unwrap().diff(&extended_fork.diffs)?;
  348. let state_root =
  349. extended_fork.overlay.lock().unwrap().contracts.update_state_monotree(&diff)?;
  350. // Generate the new header
  351. let mut header =
  352. Header::new(last_proposal.hash, next_block_height, 0, Timestamp::current_time());
  353. header.state_root = state_root;
  354. // Generate the block
  355. let mut next_block = BlockInfo::new_empty(header);
  356. // Add transactions to the block
  357. next_block.append_txs(txs);
  358. Ok(BlockTemplate::new(
  359. next_block,
  360. diff.new_trees(),
  361. randomx_keys,
  362. target,
  363. difficulty,
  364. block_signing_keypair.secret,
  365. ))
  366. }
  367. /// Auxiliary function to generate a Money::PoWReward transaction.
  368. fn generate_transaction(
  369. block_height: u32,
  370. fees: u64,
  371. block_signing_keypair: &Keypair,
  372. recipient_config: &MinerRewardsRecipientConfig,
  373. zkbin: &ZkBinary,
  374. pk: &ProvingKey,
  375. ) -> Result<Transaction> {
  376. // Build the transaction debris
  377. let debris = PoWRewardCallBuilder {
  378. signature_keypair: *block_signing_keypair,
  379. block_height,
  380. fees,
  381. recipient: Some(*recipient_config.recipient.public_key()),
  382. spend_hook: recipient_config.spend_hook,
  383. user_data: recipient_config.user_data,
  384. mint_zkbin: zkbin.clone(),
  385. mint_pk: pk.clone(),
  386. }
  387. .build()?;
  388. // Generate and sign the actual transaction
  389. let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
  390. debris.params.encode(&mut data)?;
  391. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  392. let mut tx_builder =
  393. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  394. let mut tx = tx_builder.build()?;
  395. let sigs = tx.create_sigs(&[block_signing_keypair.secret])?;
  396. tx.signatures = vec![sigs];
  397. Ok(tx)
  398. }