model.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. blockchain::expected_reward,
  46. crypto::{
  47. keypair::{Address, Keypair, Network, SecretKey},
  48. pasta_prelude::PrimeField,
  49. FuncId, MerkleTree, MONEY_CONTRACT_ID,
  50. },
  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 miner-claimable 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 reward = self.reward().await?;
  207. let expected = expected_reward(self.block.header.height);
  208. reward.checked_sub(expected).ok_or(Error::SubtractionUnderflow)
  209. }
  210. /// Return block reward excluding fees and fees values.
  211. pub async fn reward_excluding_fees_and_fees(&self) -> Result<(u64, u64)> {
  212. if self.block.txs.is_empty() {
  213. return Err(Error::BlockContainsNoTransactions(
  214. self.block.header.template_hash().as_string(),
  215. ))
  216. }
  217. let reward = self.reward().await?;
  218. let fees = reward
  219. .checked_sub(expected_reward(self.block.header.height))
  220. .ok_or(Error::SubtractionUnderflow)?;
  221. let reward = reward.checked_sub(fees).ok_or(Error::SubtractionUnderflow)?;
  222. Ok((reward, fees))
  223. }
  224. }
  225. /// Auxiliary structure representing a native miner client record.
  226. #[derive(Debug, Clone)]
  227. pub struct MinerClient {
  228. /// Miner wallet template key
  229. pub wallet: String,
  230. /// Miner recipient configuration
  231. pub config: MinerRewardsRecipientConfig,
  232. /// Current mining job
  233. pub job: String,
  234. /// Connection publisher to push new jobs
  235. pub publisher: JsonSubscriber,
  236. }
  237. impl MinerClient {
  238. pub fn new(wallet: &str, config: &MinerRewardsRecipientConfig, job: &str) -> (String, Self) {
  239. let mut hasher = blake3::Hasher::new();
  240. hasher.update(wallet.as_bytes());
  241. hasher.update(&NanoTimestamp::current_time().inner().to_le_bytes());
  242. let client_id = hex::encode(hasher.finalize().as_bytes()).to_string();
  243. let publisher = JsonSubscriber::new("job");
  244. (
  245. client_id,
  246. Self {
  247. wallet: String::from(wallet),
  248. config: config.clone(),
  249. job: job.to_owned(),
  250. publisher,
  251. },
  252. )
  253. }
  254. }
  255. /// ZK data used to generate the "coinbase" transaction in a block
  256. pub struct PowRewardV1Zk {
  257. pub zkbin: ZkBinary,
  258. pub provingkey: ProvingKey,
  259. }
  260. impl PowRewardV1Zk {
  261. pub async fn new(validator: &ValidatorPtr) -> Result<Self> {
  262. info!(
  263. target: "darkfid::registry::model::PowRewardV1Zk::new",
  264. "Generating PowRewardV1 ZkCircuit and ProvingKey...",
  265. );
  266. let validator = validator.read().await;
  267. let (zkbin, _) = validator
  268. .blockchain
  269. .contracts
  270. .get_zkas(&MONEY_CONTRACT_ID, MONEY_CONTRACT_ZKAS_MINT_NS_V1)?;
  271. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  272. let provingkey = ProvingKey::build(zkbin.k, &circuit);
  273. Ok(Self { zkbin, provingkey })
  274. }
  275. }
  276. /// Auxiliary function to generate next mining block template, in an
  277. /// atomic manner.
  278. pub async fn generate_next_block_template(
  279. extended_fork: &mut Fork,
  280. recipient_config: &MinerRewardsRecipientConfig,
  281. zkbin: &ZkBinary,
  282. pk: &ProvingKey,
  283. verify_fees: bool,
  284. ) -> Result<BlockTemplate> {
  285. // Grab forks' last block proposal(previous)
  286. let last_proposal = extended_fork.last_proposal()?;
  287. // Grab forks' next block height
  288. let next_block_height = last_proposal.block.header.height + 1;
  289. // Grab forks' RandomX keys for that height
  290. let randomx_keys = if next_block_height > RANDOMX_KEY_CHANGING_HEIGHT &&
  291. next_block_height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
  292. {
  293. (
  294. extended_fork
  295. .module
  296. .darkfi_rx_keys
  297. .1
  298. .ok_or_else(|| Error::ParseFailed("darkfi_rx_keys.1 unwrap() error"))?,
  299. None,
  300. )
  301. } else {
  302. extended_fork.module.darkfi_rx_keys
  303. };
  304. // Grab forks' next mine target and difficulty
  305. let (target, difficulty) = extended_fork.module.next_mine_target_and_difficulty()?;
  306. // The target should be compacted to 8 bytes. We'll send the MSB.
  307. let target_bytes = target.to_bytes_le();
  308. let mut padded = [0u8; 32];
  309. let len = target_bytes.len().min(32);
  310. padded[..len].copy_from_slice(&target_bytes[..len]);
  311. let target = padded[24..32].to_vec();
  312. // Cast difficulty to f64. This should always work.
  313. let difficulty = difficulty.to_string().parse()?;
  314. // Grab forks' unproposed transactions
  315. let (mut txs, _, fees) = extended_fork.unproposed_txs(next_block_height, verify_fees).await?;
  316. // Create an ephemeral block signing keypair. Its secret key will
  317. // be stored in the PowReward transaction's encrypted note for
  318. // later retrieval. It is encrypted towards the recipient's public
  319. // key.
  320. let block_signing_keypair = Keypair::random(&mut OsRng);
  321. // Generate reward transaction
  322. let tx = generate_transaction(
  323. next_block_height,
  324. fees,
  325. &block_signing_keypair,
  326. recipient_config,
  327. zkbin,
  328. pk,
  329. )?;
  330. // Apply producer transaction in the forks' overlay
  331. let _ = apply_producer_transaction(
  332. &extended_fork.overlay,
  333. next_block_height,
  334. extended_fork.module.target,
  335. &tx,
  336. &mut MerkleTree::new(1),
  337. )
  338. .await?;
  339. txs.push(tx);
  340. // Grab the updated contracts states root
  341. let diff =
  342. extended_fork.overlay.lock().unwrap().overlay.lock().unwrap().diff(&extended_fork.diffs)?;
  343. let state_root =
  344. extended_fork.overlay.lock().unwrap().contracts.update_state_monotree(&diff)?;
  345. // Generate the new header
  346. let mut header =
  347. Header::new(last_proposal.hash, next_block_height, 0, Timestamp::current_time());
  348. header.state_root = state_root;
  349. // Generate the block
  350. let mut next_block = BlockInfo::new_empty(header);
  351. // Add transactions to the block
  352. next_block.append_txs(txs);
  353. Ok(BlockTemplate::new(
  354. next_block,
  355. diff.new_trees(),
  356. randomx_keys,
  357. target,
  358. difficulty,
  359. block_signing_keypair.secret,
  360. ))
  361. }
  362. /// Auxiliary function to generate a Money::PoWReward transaction.
  363. fn generate_transaction(
  364. block_height: u32,
  365. fees: u64,
  366. block_signing_keypair: &Keypair,
  367. recipient_config: &MinerRewardsRecipientConfig,
  368. zkbin: &ZkBinary,
  369. pk: &ProvingKey,
  370. ) -> Result<Transaction> {
  371. // Build the transaction debris
  372. let debris = PoWRewardCallBuilder {
  373. signature_keypair: *block_signing_keypair,
  374. block_height,
  375. fees,
  376. recipient: Some(*recipient_config.recipient.public_key()),
  377. spend_hook: recipient_config.spend_hook,
  378. user_data: recipient_config.user_data,
  379. mint_zkbin: zkbin.clone(),
  380. mint_pk: pk.clone(),
  381. }
  382. .build()?;
  383. // Generate and sign the actual transaction
  384. let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
  385. debris.params.encode(&mut data)?;
  386. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  387. let mut tx_builder =
  388. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  389. let mut tx = tx_builder.build()?;
  390. let sigs = tx.create_sigs(&[block_signing_keypair.secret])?;
  391. tx.signatures = vec![sigs];
  392. Ok(tx)
  393. }