token.rs 18 KB

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