rpc_transfer.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 anyhow::{anyhow, Result};
  19. use darkfi::{
  20. tx::Transaction,
  21. util::parse::{decode_base10, encode_base10},
  22. zk::{halo2::Field, proof::ProvingKey, vm::ZkCircuit, vm_stack::empty_witnesses},
  23. zkas::ZkBinary,
  24. };
  25. use darkfi_dao_contract::dao_model::DaoBulla;
  26. use darkfi_money_contract::{
  27. client::{build_transfer_tx, OwnCoin},
  28. MoneyFunction, MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  29. };
  30. use darkfi_sdk::{
  31. crypto::{
  32. contract_id::{DAO_CONTRACT_ID, MONEY_CONTRACT_ID},
  33. Keypair, PublicKey, TokenId,
  34. },
  35. pasta::pallas,
  36. tx::ContractCall,
  37. };
  38. use darkfi_serial::Encodable;
  39. use rand::rngs::OsRng;
  40. use super::Drk;
  41. impl Drk {
  42. /// Create a payment transaction. Returns the transaction object on success.
  43. pub async fn transfer(
  44. &self,
  45. amount: &str,
  46. token_id: TokenId,
  47. recipient: PublicKey,
  48. dao: bool,
  49. dao_bulla: Option<String>,
  50. ) -> Result<Transaction> {
  51. let dao_bulla: Option<DaoBulla> = if dao {
  52. let Some(dao_bulla) = dao_bulla else {
  53. return Err(anyhow!("Missing DAO bulla in parameters"))
  54. };
  55. Some(DaoBulla::try_from(dao_bulla.as_str())?)
  56. } else {
  57. None
  58. };
  59. let (spend_hook, user_data, user_data_blind) = if dao {
  60. (DAO_CONTRACT_ID.inner(), dao_bulla.unwrap().inner(), pallas::Base::random(&mut OsRng))
  61. } else {
  62. (pallas::Base::zero(), pallas::Base::zero(), pallas::Base::random(&mut OsRng))
  63. };
  64. // First get all unspent OwnCoins to see what our balance is.
  65. eprintln!("Fetching OwnCoins");
  66. let owncoins = self.get_coins(false).await?;
  67. let mut owncoins: Vec<OwnCoin> = owncoins.iter().map(|x| x.0.clone()).collect();
  68. // We're only interested in the ones for the token_id we're sending
  69. // And the ones not owned by some protocol (meaning spend-hook should be 0)
  70. owncoins.retain(|x| x.note.token_id == token_id);
  71. owncoins.retain(|x| x.note.spend_hook == pallas::Base::zero());
  72. if owncoins.is_empty() {
  73. return Err(anyhow!("Did not find any coins with token ID: {}", token_id))
  74. }
  75. // FIXME: Do not hardcode 8 decimals
  76. let amount = decode_base10(amount, 8, false)?;
  77. let mut balance = 0;
  78. for coin in owncoins.iter() {
  79. balance += coin.note.value;
  80. }
  81. if balance < amount {
  82. return Err(anyhow!(
  83. "Not enough balance for token ID: {}, found: {}",
  84. token_id,
  85. encode_base10(balance, 8)
  86. ))
  87. }
  88. // We'll also need our Merkle tree
  89. let tree = self.get_money_tree().await?;
  90. // TODO: Which keypair to actually use?
  91. let secrets = self.get_money_secrets().await?;
  92. let keypair = Keypair::new(secrets[0]);
  93. let contract_id = *MONEY_CONTRACT_ID;
  94. // Now we need to do a lookup for the zkas proof bincodes, and create
  95. // the circuit objects and proving keys so we can build the transaction.
  96. // We also do this through the RPC.
  97. let zkas_bins = self.lookup_zkas(&contract_id).await?;
  98. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1) else {
  99. return Err(anyhow!("Mint circuit not found"))
  100. };
  101. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1) else {
  102. return Err(anyhow!("Burn circuit not found"))
  103. };
  104. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  105. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  106. let k = 13;
  107. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin), mint_zkbin.clone());
  108. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin), burn_zkbin.clone());
  109. eprintln!("Creating Mint circuit proving key");
  110. let mint_pk = ProvingKey::build(k, &mint_circuit);
  111. eprintln!("Creating Burn circuit proving key");
  112. let burn_pk = ProvingKey::build(k, &burn_circuit);
  113. // Now we should have everything we need to build the transaction
  114. let (params, proofs, secrets, spent_coins) = build_transfer_tx(
  115. &keypair,
  116. &recipient,
  117. amount,
  118. token_id,
  119. spend_hook,
  120. user_data,
  121. user_data_blind,
  122. &owncoins,
  123. &tree,
  124. &mint_zkbin,
  125. &mint_pk,
  126. &burn_zkbin,
  127. &burn_pk,
  128. false,
  129. )?;
  130. // Encode and sign the transaction
  131. let mut data = vec![MoneyFunction::Transfer as u8];
  132. params.encode(&mut data)?;
  133. let calls = vec![ContractCall { contract_id, data }];
  134. let proofs = vec![proofs];
  135. let mut tx = Transaction { calls, proofs, signatures: vec![] };
  136. let sigs = tx.create_sigs(&mut OsRng, &secrets)?;
  137. tx.signatures = vec![sigs];
  138. // We need to mark the coins we've spent in our wallet
  139. for spent_coin in spent_coins {
  140. self.mark_spent_coin(&spent_coin.coin).await?;
  141. }
  142. Ok(tx)
  143. }
  144. }