transfer.rs 6.1 KB

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