transfer.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 darkfi::{
  20. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  21. util::parse::{decode_base10, encode_base10},
  22. zk::{proof::ProvingKey, vm::ZkCircuit, vm_heap::empty_witnesses},
  23. zkas::ZkBinary,
  24. Error, Result,
  25. };
  26. use darkfi_money_contract::{
  27. client::{transfer_v1::make_transfer_call, OwnCoin},
  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, Keypair, PublicKey, TokenId},
  32. pasta::pallas,
  33. tx::ContractCall,
  34. };
  35. use darkfi_serial::Encodable;
  36. use crate::{money::BALANCE_BASE10_DECIMALS, Drk};
  37. impl Drk {
  38. /// Create a payment transaction. Returns the transaction object on success.
  39. pub async fn transfer(
  40. &self,
  41. amount: &str,
  42. token_id: TokenId,
  43. recipient: PublicKey,
  44. ) -> Result<Transaction> {
  45. // First get all unspent OwnCoins to see what our balance is.
  46. eprintln!("Fetching OwnCoins");
  47. let owncoins = self.get_coins(false).await?;
  48. let mut owncoins: Vec<OwnCoin> = owncoins.iter().map(|x| x.0.clone()).collect();
  49. // We're only interested in the ones for the token_id we're sending
  50. // And the ones not owned by some protocol (meaning spend-hook should be 0)
  51. owncoins.retain(|x| x.note.token_id == token_id);
  52. owncoins.retain(|x| x.note.spend_hook == pallas::Base::zero());
  53. if owncoins.is_empty() {
  54. return Err(Error::Custom(format!("Did not find any coins with token ID: {token_id}")))
  55. }
  56. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  57. let mut balance = 0;
  58. for coin in owncoins.iter() {
  59. balance += coin.note.value;
  60. }
  61. if balance < amount {
  62. return Err(Error::Custom(format!(
  63. "Not enough balance for token ID: {token_id}, found: {}",
  64. encode_base10(balance, BALANCE_BASE10_DECIMALS)
  65. )))
  66. }
  67. // We'll also need our Merkle tree
  68. let tree = self.get_money_tree().await?;
  69. let secret = self.default_secret().await?;
  70. let keypair = Keypair::new(secret);
  71. let contract_id = *MONEY_CONTRACT_ID;
  72. // Now we need to do a lookup for the zkas proof bincodes, and create
  73. // the circuit objects and proving keys so we can build the transaction.
  74. // We also do this through the RPC.
  75. let zkas_bins = self.lookup_zkas(&contract_id).await?;
  76. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  77. else {
  78. return Err(Error::Custom("Mint circuit not found".to_string()))
  79. };
  80. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  81. else {
  82. return Err(Error::Custom("Burn circuit not found".to_string()))
  83. };
  84. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  85. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  86. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  87. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  88. eprintln!("Creating Mint and Burn circuit 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. eprintln!("Building transaction parameters");
  92. let (params, secrets, spent_coins) = make_transfer_call(
  93. keypair, recipient, amount, token_id, owncoins, tree, mint_zkbin, mint_pk, burn_zkbin,
  94. burn_pk,
  95. )?;
  96. // Encode and sign the transaction
  97. let mut data = vec![MoneyFunction::TransferV1 as u8];
  98. params.encode(&mut data)?;
  99. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  100. let mut tx_builder =
  101. TransactionBuilder::new(ContractCallLeaf { call, proofs: secrets.proofs }, vec![])?;
  102. let mut tx = tx_builder.build()?;
  103. let sigs = tx.create_sigs(&mut OsRng, &secrets.signature_secrets)?;
  104. tx.signatures = vec![sigs];
  105. // We need to mark the coins we've spent in our wallet
  106. for spent_coin in spent_coins {
  107. if let Err(e) = self.mark_spent_coin(&spent_coin.coin).await {
  108. return Err(Error::Custom(format!("Mark spent coin {spent_coin:?} failed: {e:?}")))
  109. };
  110. }
  111. Ok(tx)
  112. }
  113. }