token.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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::{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_TOKEN_FRZ_NS_V1,
  34. MONEY_CONTRACT_ZKAS_TOKEN_MINT_NS_V1,
  35. };
  36. use darkfi_sdk::{
  37. crypto::{
  38. contract_id::MONEY_CONTRACT_ID, Blind, FuncId, FuncRef, Keypair, PublicKey, SecretKey,
  39. },
  40. dark_tree::DarkLeaf,
  41. pasta::pallas,
  42. tx::ContractCall,
  43. };
  44. use darkfi_serial::{deserialize, serialize, Encodable};
  45. use crate::{
  46. error::WalletDbResult,
  47. money::{
  48. BALANCE_BASE10_DECIMALS, MONEY_TOKENS_COL_IS_FROZEN, MONEY_TOKENS_COL_MINT_AUTHORITY,
  49. MONEY_TOKENS_COL_TOKEN_ID, MONEY_TOKENS_TABLE,
  50. },
  51. Drk,
  52. };
  53. impl Drk {
  54. /// Import a token mint authority into the wallet
  55. pub async fn import_mint_authority(&self, mint_authority: SecretKey) -> WalletDbResult<()> {
  56. let token_id = TokenId::derive(mint_authority);
  57. let is_frozen = 0;
  58. let query = format!(
  59. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  60. *MONEY_TOKENS_TABLE,
  61. MONEY_TOKENS_COL_MINT_AUTHORITY,
  62. MONEY_TOKENS_COL_TOKEN_ID,
  63. MONEY_TOKENS_COL_IS_FROZEN,
  64. );
  65. self.wallet
  66. .exec_sql(
  67. &query,
  68. rusqlite::params![serialize(&mint_authority), serialize(&token_id), is_frozen,],
  69. )
  70. .await
  71. }
  72. pub async fn list_tokens(&self) -> Result<Vec<(TokenId, SecretKey, bool)>> {
  73. let rows = match self.wallet.query_multiple(&MONEY_TOKENS_TABLE, &[], &[]).await {
  74. Ok(r) => r,
  75. Err(e) => {
  76. return Err(Error::RusqliteError(format!(
  77. "[list_tokens] Tokens retrieval failed: {e:?}"
  78. )))
  79. }
  80. };
  81. let mut ret = Vec::with_capacity(rows.len());
  82. for row in rows {
  83. let Value::Blob(ref auth_bytes) = row[0] else {
  84. return Err(Error::ParseFailed("[list_tokens] Mint authority bytes parsing failed"))
  85. };
  86. let mint_authority = deserialize(auth_bytes)?;
  87. let Value::Blob(ref token_bytes) = row[1] else {
  88. return Err(Error::ParseFailed("[list_tokens] Token ID bytes parsing failed"))
  89. };
  90. let token_id = deserialize(token_bytes)?;
  91. let Value::Integer(frozen) = row[2] else {
  92. return Err(Error::ParseFailed("[list_tokens] Is frozen parsing failed"))
  93. };
  94. let Ok(frozen) = i32::try_from(frozen) else {
  95. return Err(Error::ParseFailed("[list_tokens] Is frozen parsing failed"))
  96. };
  97. ret.push((token_id, mint_authority, frozen != 0));
  98. }
  99. Ok(ret)
  100. }
  101. /// Create a token mint transaction. Returns the transaction object on success.
  102. pub async fn mint_token(
  103. &self,
  104. amount: &str,
  105. recipient: PublicKey,
  106. token_attrs: TokenAttributes,
  107. ) -> Result<Transaction> {
  108. // TODO: Mint directly into DAO treasury
  109. let spend_hook = FuncId::none();
  110. let user_data = pallas::Base::zero();
  111. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  112. let token_id = token_attrs.to_token_id();
  113. let mut tokens = self.list_tokens().await?;
  114. tokens.retain(|x| x.0 == token_id);
  115. if tokens.is_empty() {
  116. return Err(Error::Custom(format!(
  117. "Did not find mint authority for token ID {token_id}"
  118. )))
  119. }
  120. assert!(tokens.len() == 1);
  121. let mint_authority = Keypair::new(tokens[0].1);
  122. if tokens[0].2 {
  123. return Err(Error::Custom(
  124. "This token mint is marked as frozen in the wallet".to_string(),
  125. ))
  126. }
  127. // Now we need to do a lookup for the zkas proof bincodes, and create
  128. // the circuit objects and proving keys so we can build the transaction.
  129. // We also do this through the RPC.
  130. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  131. let (mint_zkbin, mint_pk) = {
  132. let mint_zkas_ns = MONEY_CONTRACT_ZKAS_TOKEN_MINT_NS_V1;
  133. let Some(token_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == mint_zkas_ns) else {
  134. return Err(Error::Custom("Token mint circuit not found".to_string()))
  135. };
  136. let mint_zkbin = ZkBinary::decode(&token_mint_zkbin.1)?;
  137. let token_mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  138. eprintln!("Creating token mint circuit proving keys");
  139. let mint_pk = ProvingKey::build(mint_zkbin.k, &token_mint_circuit);
  140. (mint_zkbin, mint_pk)
  141. };
  142. let (auth_mint_zkbin, auth_mint_pk) = {
  143. let auth_zkas_ns = MONEY_CONTRACT_ZKAS_AUTH_TOKEN_MINT_NS_V1;
  144. let Some(token_auth_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == auth_zkas_ns) else {
  145. return Err(Error::Custom("Token mint circuit not found".to_string()))
  146. };
  147. let auth_mint_zkbin = ZkBinary::decode(&token_auth_mint_zkbin.1)?;
  148. let token_auth_mint_circuit =
  149. ZkCircuit::new(empty_witnesses(&auth_mint_zkbin)?, &auth_mint_zkbin);
  150. eprintln!("Creating token mint circuit proving keys");
  151. let auth_mint_pk = ProvingKey::build(auth_mint_zkbin.k, &token_auth_mint_circuit);
  152. (auth_mint_zkbin, auth_mint_pk)
  153. };
  154. /*
  155. let mint_builder = TokenMintCallBuilder {
  156. mint_keypair: mint_authority,
  157. recipient,
  158. amount,
  159. spend_hook,
  160. user_data,
  161. token_mint_zkbin,
  162. token_mint_pk,
  163. };
  164. eprintln!("Building transaction parameters");
  165. let debris = mint_builder.build()?;
  166. // Encode and sign the transaction
  167. let mut data = vec![MoneyFunction::TokenMintV1 as u8];
  168. debris.params.encode(&mut data)?;
  169. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  170. let mut tx_builder =
  171. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  172. let mut tx = tx_builder.build()?;
  173. let sigs = tx.create_sigs(&mut OsRng, &[mint_authority.secret])?;
  174. tx.signatures = vec![sigs];
  175. */
  176. let _auth_func_id = FuncRef {
  177. contract_id: *MONEY_CONTRACT_ID,
  178. func_code: MoneyFunction::AuthTokenMintV1 as u8,
  179. }
  180. .to_func_id();
  181. //let token_attrs = TokenAttributes {
  182. // auth_parent: auth_func_id,
  183. // user_data: poseidon_hash([mint_authority.public.x(), mint_authority.public.y()]),
  184. // blind: token_blind,
  185. //};
  186. //let token_id = token_attrs.to_token_id();
  187. let coin_attrs = CoinAttributes {
  188. public_key: recipient,
  189. value: amount,
  190. token_id,
  191. spend_hook,
  192. user_data,
  193. blind: Blind::random(&mut OsRng),
  194. };
  195. let builder = TokenMintCallBuilder {
  196. coin_attrs: coin_attrs.clone(),
  197. token_attrs: token_attrs.clone(),
  198. mint_zkbin,
  199. mint_pk,
  200. };
  201. let mint_debris = builder.build()?;
  202. let mut data = vec![MoneyFunction::TokenMintV1 as u8];
  203. mint_debris.params.encode(&mut data)?;
  204. let mint_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  205. let builder = AuthTokenMintCallBuilder {
  206. coin_attrs,
  207. token_attrs,
  208. mint_keypair: mint_authority,
  209. auth_mint_zkbin,
  210. auth_mint_pk,
  211. };
  212. let auth_debris = builder.build()?;
  213. let mut data = vec![MoneyFunction::AuthTokenMintV1 as u8];
  214. auth_debris.params.encode(&mut data)?;
  215. let auth_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  216. let mut tx = Transaction {
  217. calls: vec![
  218. DarkLeaf { data: mint_call, parent_index: Some(1), children_indexes: vec![] },
  219. DarkLeaf { data: auth_call, parent_index: None, children_indexes: vec![0] },
  220. ],
  221. proofs: vec![mint_debris.proofs, auth_debris.proofs],
  222. signatures: vec![],
  223. };
  224. let mint_sigs = tx.create_sigs(&mut OsRng, &[])?;
  225. let auth_sigs = tx.create_sigs(&mut OsRng, &[mint_authority.secret])?;
  226. tx.signatures = vec![mint_sigs, auth_sigs];
  227. Ok(tx)
  228. }
  229. /// Create a token freeze transaction. Returns the transaction object on success.
  230. pub async fn freeze_token(&self, token_attrs: TokenAttributes) -> Result<Transaction> {
  231. let token_id = token_attrs.to_token_id();
  232. let mut tokens = self.list_tokens().await?;
  233. tokens.retain(|x| x.0 == token_id);
  234. if tokens.is_empty() {
  235. return Err(Error::Custom(format!(
  236. "Did not find mint authority for token ID {token_id}"
  237. )))
  238. }
  239. assert!(tokens.len() == 1);
  240. let mint_authority = Keypair::new(tokens[0].1);
  241. if tokens[0].2 {
  242. return Err(Error::Custom(
  243. "This token is already marked as frozen in the wallet".to_string(),
  244. ))
  245. }
  246. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  247. let zkas_ns = MONEY_CONTRACT_ZKAS_TOKEN_FRZ_NS_V1;
  248. let Some(token_freeze_zkbin) = zkas_bins.iter().find(|x| x.0 == zkas_ns) else {
  249. return Err(Error::Custom("Token freeze circuit not found".to_string()))
  250. };
  251. let freeze_zkbin = ZkBinary::decode(&token_freeze_zkbin.1)?;
  252. let token_freeze_circuit = ZkCircuit::new(empty_witnesses(&freeze_zkbin)?, &freeze_zkbin);
  253. eprintln!("Creating token freeze circuit proving keys");
  254. let freeze_pk = ProvingKey::build(freeze_zkbin.k, &token_freeze_circuit);
  255. let freeze_builder = TokenFreezeCallBuilder {
  256. mint_keypair: mint_authority,
  257. token_attrs,
  258. freeze_zkbin,
  259. freeze_pk,
  260. };
  261. eprintln!("Building transaction parameters");
  262. let debris = freeze_builder.build()?;
  263. // Encode and sign the transaction
  264. let mut data = vec![MoneyFunction::TokenFreezeV1 as u8];
  265. debris.params.encode(&mut data)?;
  266. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  267. let mut tx_builder =
  268. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  269. let mut tx = tx_builder.build()?;
  270. let sigs = tx.create_sigs(&mut OsRng, &[mint_authority.secret])?;
  271. tx.signatures = vec![sigs];
  272. Ok(tx)
  273. }
  274. }