token.rs 16 KB

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