transfer.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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, OwnCoin},
  27. model::TokenId,
  28. MoneyFunction, MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  29. };
  30. use darkfi_sdk::{
  31. crypto::{contract_id::MONEY_CONTRACT_ID, FuncId, Keypair, PublicKey},
  32. tx::ContractCall,
  33. };
  34. use darkfi_serial::Encodable;
  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. ) -> Result<Transaction> {
  44. // First get all unspent OwnCoins to see what our balance is.
  45. eprintln!("Fetching OwnCoins");
  46. let owncoins = self.get_coins(false).await?;
  47. let mut owncoins: Vec<OwnCoin> = owncoins.iter().map(|x| x.0.clone()).collect();
  48. // We're only interested in the ones for the token_id we're sending
  49. // And the ones not owned by some protocol (meaning spend-hook should be 0)
  50. owncoins.retain(|x| x.note.token_id == token_id);
  51. owncoins.retain(|x| x.note.spend_hook == FuncId::none());
  52. if owncoins.is_empty() {
  53. return Err(Error::Custom(format!("Did not find any coins with token ID: {token_id}")))
  54. }
  55. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  56. let mut balance = 0;
  57. for coin in owncoins.iter() {
  58. balance += coin.note.value;
  59. }
  60. if balance < amount {
  61. return Err(Error::Custom(format!(
  62. "Not enough balance for token ID: {token_id}, found: {}",
  63. encode_base10(balance, BALANCE_BASE10_DECIMALS)
  64. )))
  65. }
  66. // We'll also need our Merkle tree
  67. let tree = self.get_money_tree().await?;
  68. let secret = self.default_secret().await?;
  69. let keypair = Keypair::new(secret);
  70. let contract_id = *MONEY_CONTRACT_ID;
  71. // Now we need to do a lookup for the zkas proof bincodes, and create
  72. // the circuit objects and proving keys so we can build the transaction.
  73. // We also do this through the RPC.
  74. let zkas_bins = self.lookup_zkas(&contract_id).await?;
  75. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  76. else {
  77. return Err(Error::Custom("Mint circuit not found".to_string()))
  78. };
  79. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  80. else {
  81. return Err(Error::Custom("Burn circuit not found".to_string()))
  82. };
  83. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  84. let burn_zkbin = ZkBinary::decode(&burn_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. eprintln!("Creating Mint and Burn circuit proving keys");
  88. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  89. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  90. eprintln!("Building transaction parameters");
  91. let (params, secrets, spent_coins) = make_transfer_call(
  92. keypair, recipient, amount, token_id, owncoins, tree, mint_zkbin, mint_pk, burn_zkbin,
  93. burn_pk,
  94. )?;
  95. // Encode and sign the transaction
  96. let mut data = vec![MoneyFunction::TransferV1 as u8];
  97. params.encode(&mut data)?;
  98. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  99. let mut tx_builder =
  100. TransactionBuilder::new(ContractCallLeaf { call, proofs: secrets.proofs }, vec![])?;
  101. let mut tx = tx_builder.build()?;
  102. let sigs = tx.create_sigs(&secrets.signature_secrets)?;
  103. tx.signatures = vec![sigs];
  104. // We need to mark the coins we've spent in our wallet
  105. for spent_coin in spent_coins {
  106. if let Err(e) = self.mark_spent_coin(&spent_coin.coin).await {
  107. return Err(Error::Custom(format!("Mark spent coin {spent_coin:?} failed: {e:?}")))
  108. };
  109. }
  110. Ok(tx)
  111. }
  112. }