model.rs 13 KB

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