token.rs 15 KB

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