rpc_transfer.rs 6.1 KB

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