token.rs 15 KB

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