transfer.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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 darkfi::{
  19. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  20. util::parse::{decode_base10, encode_base10},
  21. zk::{proof::ProvingKey, vm::ZkCircuit, vm_heap::empty_witnesses},
  22. zkas::ZkBinary,
  23. Error, Result,
  24. };
  25. use darkfi_money_contract::{
  26. client::transfer_v1::make_transfer_call, model::TokenId, MoneyFunction,
  27. MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_FEE_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  28. };
  29. use darkfi_sdk::{
  30. crypto::{contract_id::MONEY_CONTRACT_ID, FuncId, Keypair, PublicKey},
  31. pasta::pallas,
  32. tx::ContractCall,
  33. };
  34. use darkfi_serial::AsyncEncodable;
  35. use crate::{money::BALANCE_BASE10_DECIMALS, Drk};
  36. impl Drk {
  37. /// Create a payment transaction. Returns the transaction object on success.
  38. pub async fn transfer(
  39. &self,
  40. amount: &str,
  41. token_id: TokenId,
  42. recipient: PublicKey,
  43. spend_hook: Option<FuncId>,
  44. user_data: Option<pallas::Base>,
  45. half_split: bool,
  46. ) -> Result<Transaction> {
  47. // First get all unspent OwnCoins to see what our balance is
  48. let owncoins = self.get_token_coins(&token_id).await?;
  49. if owncoins.is_empty() {
  50. return Err(Error::Custom(format!(
  51. "Did not find any unspent coins with token ID: {token_id}"
  52. )))
  53. }
  54. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  55. let mut balance = 0;
  56. for coin in owncoins.iter() {
  57. balance += coin.note.value;
  58. }
  59. if balance < amount {
  60. return Err(Error::Custom(format!(
  61. "Not enough balance for token ID: {token_id}, found: {}",
  62. encode_base10(balance, BALANCE_BASE10_DECIMALS)
  63. )))
  64. }
  65. // Fetch our default secret
  66. let secret = self.default_secret().await?;
  67. let keypair = Keypair::new(secret);
  68. // We'll also need our Merkle tree
  69. let tree = self.get_money_tree().await?;
  70. // Now we need to do a lookup for the zkas proof bincodes, and create
  71. // the circuit objects and proving keys so we can build the transaction.
  72. // We also do this through the RPC.
  73. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  74. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  75. else {
  76. return Err(Error::Custom("Mint circuit not found".to_string()))
  77. };
  78. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  79. else {
  80. return Err(Error::Custom("Burn circuit not found".to_string()))
  81. };
  82. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  83. else {
  84. return Err(Error::Custom("Fee circuit not found".to_string()))
  85. };
  86. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  87. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  88. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  89. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  90. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  91. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  92. // Creating Mint, Burn and Fee circuits proving keys
  93. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  94. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  95. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  96. // Building transaction parameters
  97. let (params, secrets, spent_coins) = make_transfer_call(
  98. keypair,
  99. recipient,
  100. amount,
  101. token_id,
  102. owncoins,
  103. tree.clone(),
  104. spend_hook,
  105. user_data,
  106. mint_zkbin,
  107. mint_pk,
  108. burn_zkbin,
  109. burn_pk,
  110. half_split,
  111. )?;
  112. // Encode the call
  113. let mut data = vec![MoneyFunction::TransferV1 as u8];
  114. params.encode_async(&mut data).await?;
  115. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  116. // Create the TransactionBuilder containing the `Transfer` call
  117. let mut tx_builder =
  118. TransactionBuilder::new(ContractCallLeaf { call, proofs: secrets.proofs }, vec![])?;
  119. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  120. // it into the fee-creating function.
  121. // We also tell it about any spent coins so we don't accidentally reuse them in the
  122. // fee call.
  123. // TODO: We have to build a proper coin selection algorithm so that we can utilize
  124. // the Money::Transfer to merge any coins which would give us a coin with enough
  125. // value for paying the transaction fee.
  126. let mut tx = tx_builder.build()?;
  127. let sigs = tx.create_sigs(&secrets.signature_secrets)?;
  128. tx.signatures.push(sigs);
  129. let (fee_call, fee_proofs, fee_secrets) =
  130. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, Some(&spent_coins)).await?;
  131. // Append the fee call to the transaction
  132. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  133. // Now build the actual transaction and sign it with all necessary keys.
  134. let mut tx = tx_builder.build()?;
  135. let sigs = tx.create_sigs(&secrets.signature_secrets)?;
  136. tx.signatures.push(sigs);
  137. let sigs = tx.create_sigs(&fee_secrets)?;
  138. tx.signatures.push(sigs);
  139. Ok(tx)
  140. }
  141. }