transfer.rs 6.0 KB

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