rpc_transfer.rs 4.9 KB

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