token.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 rand::rngs::OsRng;
  19. use rusqlite::types::Value;
  20. use darkfi::{
  21. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  22. util::parse::decode_base10,
  23. zk::{halo2::Field, proof::ProvingKey, vm::ZkCircuit, vm_heap::empty_witnesses},
  24. zkas::ZkBinary,
  25. Error, Result,
  26. };
  27. use darkfi_money_contract::{
  28. client::{
  29. auth_token_freeze_v1::AuthTokenFreezeCallBuilder,
  30. auth_token_mint_v1::AuthTokenMintCallBuilder, token_mint_v1::TokenMintCallBuilder,
  31. },
  32. model::{CoinAttributes, TokenAttributes, TokenId},
  33. MoneyFunction, MONEY_CONTRACT_ZKAS_AUTH_TOKEN_MINT_NS_V1, MONEY_CONTRACT_ZKAS_FEE_NS_V1,
  34. MONEY_CONTRACT_ZKAS_TOKEN_MINT_NS_V1,
  35. };
  36. use darkfi_sdk::{
  37. crypto::{
  38. contract_id::MONEY_CONTRACT_ID, poseidon_hash, BaseBlind, Blind, FuncId, FuncRef, Keypair,
  39. PublicKey, SecretKey,
  40. },
  41. dark_tree::DarkTree,
  42. pasta::pallas,
  43. tx::ContractCall,
  44. };
  45. use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
  46. use crate::{
  47. convert_named_params,
  48. error::WalletDbResult,
  49. money::{
  50. BALANCE_BASE10_DECIMALS, MONEY_TOKENS_COL_FREEZE_HEIGHT, MONEY_TOKENS_COL_IS_FROZEN,
  51. MONEY_TOKENS_COL_MINT_AUTHORITY, MONEY_TOKENS_COL_TOKEN_BLIND, MONEY_TOKENS_COL_TOKEN_ID,
  52. MONEY_TOKENS_TABLE,
  53. },
  54. Drk,
  55. };
  56. impl Drk {
  57. /// Auxiliary function to derive `TokenAttributes` for provided secret key and token blind.
  58. fn derive_token_attributes(
  59. &self,
  60. mint_authority: SecretKey,
  61. token_blind: BaseBlind,
  62. ) -> TokenAttributes {
  63. // Create the Auth FuncID
  64. let auth_func_id = FuncRef {
  65. contract_id: *MONEY_CONTRACT_ID,
  66. func_code: MoneyFunction::AuthTokenMintV1 as u8,
  67. }
  68. .to_func_id();
  69. // Grab the mint authority key public coordinates
  70. let (mint_auth_x, mint_auth_y) = PublicKey::from_secret(mint_authority).xy();
  71. // Generate the token attributes
  72. TokenAttributes {
  73. auth_parent: auth_func_id,
  74. user_data: poseidon_hash([mint_auth_x, mint_auth_y]),
  75. blind: token_blind,
  76. }
  77. }
  78. /// Import a token mint authority into the wallet.
  79. pub async fn import_mint_authority(
  80. &self,
  81. mint_authority: SecretKey,
  82. token_blind: BaseBlind,
  83. ) -> Result<TokenId> {
  84. let token_id = self.derive_token_attributes(mint_authority, token_blind).to_token_id();
  85. let is_frozen = 0;
  86. let freeze_height: Option<u32> = None;
  87. let query = format!(
  88. "INSERT INTO {} ({}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5);",
  89. *MONEY_TOKENS_TABLE,
  90. MONEY_TOKENS_COL_TOKEN_ID,
  91. MONEY_TOKENS_COL_MINT_AUTHORITY,
  92. MONEY_TOKENS_COL_TOKEN_BLIND,
  93. MONEY_TOKENS_COL_IS_FROZEN,
  94. MONEY_TOKENS_COL_FREEZE_HEIGHT,
  95. );
  96. if let Err(e) = self.wallet.exec_sql(
  97. &query,
  98. rusqlite::params![
  99. serialize_async(&token_id).await,
  100. serialize_async(&mint_authority).await,
  101. serialize_async(&token_blind).await,
  102. is_frozen,
  103. freeze_height,
  104. ],
  105. ) {
  106. return Err(Error::DatabaseError(format!(
  107. "[import_mint_authority] Inserting mint authority failed: {e}"
  108. )))
  109. };
  110. Ok(token_id)
  111. }
  112. /// Auxiliary function to parse a `MONEY_TOKENS_TABLE` records.
  113. /// The boolean in the returned tuples notes if the token mint authority is frozen.
  114. async fn parse_mint_authority_record(
  115. &self,
  116. row: &[Value],
  117. ) -> Result<(TokenId, SecretKey, BaseBlind, bool, Option<u32>)> {
  118. let Value::Blob(ref token_bytes) = row[0] else {
  119. return Err(Error::ParseFailed(
  120. "[parse_mint_authority_record] Token ID bytes parsing failed",
  121. ))
  122. };
  123. let token_id = deserialize_async(token_bytes).await?;
  124. let Value::Blob(ref auth_bytes) = row[1] else {
  125. return Err(Error::ParseFailed(
  126. "[parse_mint_authority_record] Mint authority bytes parsing failed",
  127. ))
  128. };
  129. let mint_authority = deserialize_async(auth_bytes).await?;
  130. let Value::Blob(ref token_blind_bytes) = row[2] else {
  131. return Err(Error::ParseFailed(
  132. "[parse_mint_authority_record] Token blind bytes parsing failed",
  133. ))
  134. };
  135. let token_blind: BaseBlind = deserialize_async(token_blind_bytes).await?;
  136. let Value::Integer(frozen) = row[3] else {
  137. return Err(Error::ParseFailed("[parse_mint_authority_record] Is frozen parsing failed"))
  138. };
  139. let Ok(frozen) = i32::try_from(frozen) else {
  140. return Err(Error::ParseFailed("[parse_mint_authority_record] Is frozen parsing failed"))
  141. };
  142. let freeze_height = match row[4] {
  143. Value::Integer(freeze_height) => {
  144. let Ok(freeze_height) = u32::try_from(freeze_height) else {
  145. return Err(Error::ParseFailed(
  146. "[parse_mint_authority_record] Freeze height parsing failed",
  147. ))
  148. };
  149. Some(freeze_height)
  150. }
  151. Value::Null => None,
  152. _ => {
  153. return Err(Error::ParseFailed(
  154. "[parse_mint_authority_record] Freeze height parsing failed",
  155. ))
  156. }
  157. };
  158. Ok((token_id, mint_authority, token_blind, frozen != 0, freeze_height))
  159. }
  160. /// Reset all token mint authorities frozen status in the wallet.
  161. pub fn reset_mint_authorities(&self, output: &mut Vec<String>) -> WalletDbResult<()> {
  162. output.push(String::from("Resetting mint authorities frozen status"));
  163. let query = format!(
  164. "UPDATE {} SET {} = 0, {} = NULL;",
  165. *MONEY_TOKENS_TABLE, MONEY_TOKENS_COL_IS_FROZEN, MONEY_TOKENS_COL_FREEZE_HEIGHT
  166. );
  167. self.wallet.exec_sql(&query, &[])?;
  168. output.push(String::from("Successfully reset mint authorities frozen status"));
  169. Ok(())
  170. }
  171. /// Remove token mint authorities frozen status in the wallet that
  172. /// where frozen after provided height.
  173. pub fn unfreeze_mint_authorities_after(
  174. &self,
  175. height: &u32,
  176. output: &mut Vec<String>,
  177. ) -> WalletDbResult<()> {
  178. output.push(format!("Resetting mint authorities frozen status after: {height}"));
  179. let query = format!(
  180. "UPDATE {} SET {} = 0, {} = NULL WHERE {} > ?1;",
  181. *MONEY_TOKENS_TABLE,
  182. MONEY_TOKENS_COL_IS_FROZEN,
  183. MONEY_TOKENS_COL_FREEZE_HEIGHT,
  184. MONEY_TOKENS_COL_FREEZE_HEIGHT
  185. );
  186. self.wallet.exec_sql(&query, rusqlite::params![Some(*height)])?;
  187. output.push(String::from("Successfully reset mint authorities frozen status"));
  188. Ok(())
  189. }
  190. /// Fetch all token mint authorities from the wallet.
  191. pub async fn get_mint_authorities(
  192. &self,
  193. ) -> Result<Vec<(TokenId, SecretKey, BaseBlind, bool, Option<u32>)>> {
  194. let rows = match self.wallet.query_multiple(&MONEY_TOKENS_TABLE, &[], &[]) {
  195. Ok(r) => r,
  196. Err(e) => {
  197. return Err(Error::DatabaseError(format!(
  198. "[get_mint_authorities] Tokens mint autorities retrieval failed: {e}"
  199. )))
  200. }
  201. };
  202. let mut ret = Vec::with_capacity(rows.len());
  203. for row in rows {
  204. ret.push(self.parse_mint_authority_record(&row).await?);
  205. }
  206. Ok(ret)
  207. }
  208. /// Fetch provided token unfrozen mint authority from the wallet.
  209. async fn get_token_mint_authority(
  210. &self,
  211. token_id: &TokenId,
  212. ) -> Result<(TokenId, SecretKey, BaseBlind, bool, Option<u32>)> {
  213. let row = match self.wallet.query_single(
  214. &MONEY_TOKENS_TABLE,
  215. &[],
  216. convert_named_params! {(MONEY_TOKENS_COL_TOKEN_ID, serialize_async(token_id).await)},
  217. ) {
  218. Ok(r) => r,
  219. Err(e) => {
  220. return Err(Error::DatabaseError(format!(
  221. "[get_token_mint_authority] Token mint authority retrieval failed: {e}"
  222. )))
  223. }
  224. };
  225. let token = self.parse_mint_authority_record(&row).await?;
  226. if token.3 {
  227. return Err(Error::Custom(
  228. "This token mint is marked as frozen in the wallet".to_string(),
  229. ))
  230. }
  231. Ok(token)
  232. }
  233. /// Create a token mint transaction. Returns the transaction object on success.
  234. pub async fn mint_token(
  235. &self,
  236. amount: &str,
  237. recipient: PublicKey,
  238. token_id: TokenId,
  239. spend_hook: Option<FuncId>,
  240. user_data: Option<pallas::Base>,
  241. ) -> Result<Transaction> {
  242. // Decode provided amount
  243. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  244. // Grab token ID mint authority and attributes
  245. let token_mint_authority = self.get_token_mint_authority(&token_id).await?;
  246. let token_attrs =
  247. self.derive_token_attributes(token_mint_authority.1, token_mint_authority.2);
  248. let mint_authority = Keypair::new(token_mint_authority.1);
  249. // Sanity check
  250. assert_eq!(token_id, token_attrs.to_token_id());
  251. // Now we need to do a lookup for the zkas proof bincodes, and create
  252. // the circuit objects and proving keys so we can build the transaction.
  253. // We also do this through the RPC.
  254. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  255. let Some(mint_zkbin) =
  256. zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_TOKEN_MINT_NS_V1)
  257. else {
  258. return Err(Error::Custom("Token mint circuit not found".to_string()))
  259. };
  260. let Some(auth_mint_zkbin) =
  261. zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_AUTH_TOKEN_MINT_NS_V1)
  262. else {
  263. return Err(Error::Custom("Auth token mint circuit not found".to_string()))
  264. };
  265. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  266. else {
  267. return Err(Error::Custom("Fee circuit not found".to_string()))
  268. };
  269. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  270. let auth_mint_zkbin = ZkBinary::decode(&auth_mint_zkbin.1)?;
  271. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  272. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  273. let auth_mint_circuit =
  274. ZkCircuit::new(empty_witnesses(&auth_mint_zkbin)?, &auth_mint_zkbin);
  275. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  276. // Creating TokenMint, AuthTokenMint and Fee circuits proving keys
  277. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  278. let auth_mint_pk = ProvingKey::build(auth_mint_zkbin.k, &auth_mint_circuit);
  279. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  280. // Build the coin attributes
  281. let coin_attrs = CoinAttributes {
  282. public_key: recipient,
  283. value: amount,
  284. token_id,
  285. spend_hook: spend_hook.unwrap_or(FuncId::none()),
  286. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  287. blind: Blind::random(&mut OsRng),
  288. };
  289. // Create the auth call
  290. let builder = AuthTokenMintCallBuilder {
  291. coin_attrs: coin_attrs.clone(),
  292. token_attrs: token_attrs.clone(),
  293. mint_keypair: mint_authority,
  294. auth_mint_zkbin,
  295. auth_mint_pk,
  296. };
  297. let auth_debris = builder.build()?;
  298. let mut data = vec![MoneyFunction::AuthTokenMintV1 as u8];
  299. auth_debris.params.encode_async(&mut data).await?;
  300. let auth_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  301. // Create the minting call
  302. let builder = TokenMintCallBuilder { coin_attrs, token_attrs, mint_zkbin, mint_pk };
  303. let mint_debris = builder.build()?;
  304. let mut data = vec![MoneyFunction::TokenMintV1 as u8];
  305. mint_debris.params.encode_async(&mut data).await?;
  306. let mint_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  307. // Create the TransactionBuilder containing above calls
  308. let mut tx_builder = TransactionBuilder::new(
  309. ContractCallLeaf { call: mint_call, proofs: mint_debris.proofs },
  310. vec![DarkTree::new(
  311. ContractCallLeaf { call: auth_call, proofs: auth_debris.proofs },
  312. vec![],
  313. None,
  314. None,
  315. )],
  316. )?;
  317. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  318. // it into the fee-creating function.
  319. let mut tx = tx_builder.build()?;
  320. let auth_sigs = tx.create_sigs(&[mint_authority.secret])?;
  321. let mint_sigs = tx.create_sigs(&[])?;
  322. tx.signatures = vec![auth_sigs, mint_sigs];
  323. let tree = self.get_money_tree().await?;
  324. let (fee_call, fee_proofs, fee_secrets) =
  325. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  326. // Append the fee call to the transaction
  327. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  328. // Now build the actual transaction and sign it with all necessary keys.
  329. let mut tx = tx_builder.build()?;
  330. let sigs = tx.create_sigs(&[mint_authority.secret])?;
  331. tx.signatures.push(sigs);
  332. let sigs = tx.create_sigs(&[])?;
  333. tx.signatures.push(sigs);
  334. let sigs = tx.create_sigs(&fee_secrets)?;
  335. tx.signatures.push(sigs);
  336. Ok(tx)
  337. }
  338. /// Create a token freeze transaction. Returns the transaction object on success.
  339. pub async fn freeze_token(&self, token_id: TokenId) -> Result<Transaction> {
  340. // Grab token ID mint authority and attributes
  341. let token_mint_authority = self.get_token_mint_authority(&token_id).await?;
  342. let token_attrs =
  343. self.derive_token_attributes(token_mint_authority.1, token_mint_authority.2);
  344. let mint_authority = Keypair::new(token_mint_authority.1);
  345. // Sanity check
  346. assert_eq!(token_id, token_attrs.to_token_id());
  347. // Now we need to do a lookup for the zkas proof bincodes, and create
  348. // the circuit objects and proving keys so we can build the transaction.
  349. // We also do this through the RPC.
  350. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  351. let Some(auth_mint_zkbin) =
  352. zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_AUTH_TOKEN_MINT_NS_V1)
  353. else {
  354. return Err(Error::Custom("Auth token mint circuit not found".to_string()))
  355. };
  356. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  357. else {
  358. return Err(Error::Custom("Fee circuit not found".to_string()))
  359. };
  360. let auth_mint_zkbin = ZkBinary::decode(&auth_mint_zkbin.1)?;
  361. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  362. let auth_mint_circuit =
  363. ZkCircuit::new(empty_witnesses(&auth_mint_zkbin)?, &auth_mint_zkbin);
  364. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  365. // Creating AuthTokenMint and Fee circuits proving keys
  366. let auth_mint_pk = ProvingKey::build(auth_mint_zkbin.k, &auth_mint_circuit);
  367. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  368. // Create the freeze call
  369. let builder = AuthTokenFreezeCallBuilder {
  370. mint_keypair: mint_authority,
  371. token_attrs,
  372. auth_mint_zkbin,
  373. auth_mint_pk,
  374. };
  375. let freeze_debris = builder.build()?;
  376. let mut data = vec![MoneyFunction::AuthTokenFreezeV1 as u8];
  377. freeze_debris.params.encode_async(&mut data).await?;
  378. let freeze_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  379. // Create the TransactionBuilder containing above call
  380. let mut tx_builder = TransactionBuilder::new(
  381. ContractCallLeaf { call: freeze_call, proofs: freeze_debris.proofs },
  382. vec![],
  383. )?;
  384. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  385. // it into the fee-creating function.
  386. let mut tx = tx_builder.build()?;
  387. let sigs = tx.create_sigs(&[mint_authority.secret])?;
  388. tx.signatures.push(sigs);
  389. let tree = self.get_money_tree().await?;
  390. let (fee_call, fee_proofs, fee_secrets) =
  391. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  392. // Append the fee call to the transaction
  393. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  394. // Now build the actual transaction and sign it with all necessary keys.
  395. let mut tx = tx_builder.build()?;
  396. let sigs = tx.create_sigs(&[mint_authority.secret])?;
  397. tx.signatures.push(sigs);
  398. let sigs = tx.create_sigs(&fee_secrets)?;
  399. tx.signatures.push(sigs);
  400. Ok(tx)
  401. }
  402. }