rpc_transfer.rs 4.9 KB

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