model.rs 12 KB

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