token.rs 18 KB

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