rpc_swap.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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::encode_base10,
  22. zk::{proof::ProvingKey, vm::ZkCircuit, vm_stack::empty_witnesses, Proof},
  23. zkas::ZkBinary,
  24. };
  25. use darkfi_money_contract::{
  26. client::{build_half_swap_tx, EncryptedNote, Note},
  27. state::MoneyTransferParams,
  28. MoneyFunction, MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  29. };
  30. use darkfi_sdk::{
  31. crypto::{
  32. contract_id::MONEY_CONTRACT_ID,
  33. pedersen::{pedersen_commitment_base, pedersen_commitment_u64, ValueBlind},
  34. poseidon_hash, PublicKey, SecretKey, TokenId,
  35. },
  36. pasta::pallas,
  37. tx::ContractCall,
  38. };
  39. use darkfi_serial::{deserialize, Encodable, SerialDecodable, SerialEncodable};
  40. use rand::rngs::OsRng;
  41. use super::Drk;
  42. #[derive(SerialEncodable, SerialDecodable)]
  43. /// Half of the swap data, includes the coin that is supposed to be sent,
  44. /// and the coin that is supposed to be received.
  45. pub struct PartialSwapData {
  46. params: MoneyTransferParams,
  47. proofs: Vec<Proof>,
  48. value_pair: (u64, u64),
  49. token_pair: (TokenId, TokenId),
  50. value_blinds: Vec<ValueBlind>,
  51. token_blinds: Vec<ValueBlind>,
  52. }
  53. impl Drk {
  54. /// Initialize the first half of an atomic swap
  55. pub async fn init_swap(
  56. &self,
  57. value_send: u64,
  58. token_send: TokenId,
  59. value_recv: u64,
  60. token_recv: TokenId,
  61. ) -> Result<PartialSwapData> {
  62. // First we'll fetch all of our unspent coins from the wallet.
  63. let mut owncoins = self.wallet_coins(false).await?;
  64. // Then we see if we have one that we can send.
  65. owncoins.retain(|x| (x.0.note.value == value_send && x.0.note.token_id == token_send));
  66. if owncoins.is_empty() {
  67. return Err(anyhow!(
  68. "Did not find any unspent coins of value {} and token_id {}",
  69. value_send,
  70. token_send
  71. ))
  72. }
  73. // If there are any, we'll just spend the first one we see.
  74. let burn_coin = owncoins[0].0.clone();
  75. // Fetch our default address
  76. let address = self.wallet_address(0).await?;
  77. // We'll also need our Merkle tree
  78. let tree = self.wallet_tree().await?;
  79. let contract_id = *MONEY_CONTRACT_ID;
  80. // Now we need to do a lookup for the zkas proof bincodes, and create
  81. // the circuit objects and proving keys so we can build the transaction.
  82. // We also do this through the RPC.
  83. let zkas_bins = self.lookup_zkas(&contract_id).await?;
  84. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1) else {
  85. return Err(anyhow!("Mint circuit not found"))
  86. };
  87. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1) else {
  88. return Err(anyhow!("Burn circuit not found"))
  89. };
  90. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  91. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  92. let k = 13;
  93. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin), mint_zkbin.clone());
  94. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin), burn_zkbin.clone());
  95. eprintln!("Creating Mint circuit proving key");
  96. let mint_pk = ProvingKey::build(k, &mint_circuit);
  97. eprintln!("Creating Burn circuit proving key");
  98. let burn_pk = ProvingKey::build(k, &burn_circuit);
  99. // Now we should have everything we need to build the swap half
  100. eprintln!("Building first half of the swap transaction");
  101. let (half_params, half_proofs, _half_keys, _spent_coins, value_blinds, token_blinds) =
  102. build_half_swap_tx(
  103. &address,
  104. value_send,
  105. token_send,
  106. value_recv,
  107. token_recv,
  108. &[],
  109. &[],
  110. &[burn_coin],
  111. &tree,
  112. &mint_zkbin,
  113. &mint_pk,
  114. &burn_zkbin,
  115. &burn_pk,
  116. )?;
  117. // Now we have the half, so we can build `PartialSwapData` and return it.
  118. let ret = PartialSwapData {
  119. params: half_params,
  120. proofs: half_proofs,
  121. value_pair: (value_send, value_recv),
  122. token_pair: (token_send, token_recv),
  123. value_blinds,
  124. token_blinds,
  125. };
  126. Ok(ret)
  127. }
  128. /// Create a full transaction by inspecting and verifying given partial swap data,
  129. /// making the other half, and joining all this into a `Transaction` object.
  130. pub async fn join_swap(&self, partial: PartialSwapData) -> Result<Transaction> {
  131. // Our side of the tx in the pairs is the second half, so we try to find
  132. // an unspent coin like that in our wallet.
  133. let mut owncoins = self.wallet_coins(false).await?;
  134. owncoins.retain(|x| {
  135. x.0.note.value == partial.value_pair.1 && x.0.note.token_id == partial.token_pair.1
  136. });
  137. if owncoins.is_empty() {
  138. return Err(anyhow!(
  139. "Did not find any unspent coins of value {} and token_id {}",
  140. partial.value_pair.1,
  141. partial.token_pair.1
  142. ))
  143. }
  144. // If there are any, we'll just spend the first one we see.
  145. let burn_coin = owncoins[0].0.clone();
  146. // Fetch our default address
  147. let address = self.wallet_address(0).await?;
  148. // We'll also need our Merkle tree
  149. let tree = self.wallet_tree().await?;
  150. let contract_id = *MONEY_CONTRACT_ID;
  151. // Now we need to do a lookup for the zkas proof bincodes, and create
  152. // the circuit objects and proving keys so we can build the transaction.
  153. // We also do this through the RPC.
  154. let zkas_bins = self.lookup_zkas(&contract_id).await?;
  155. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1) else {
  156. return Err(anyhow!("Mint circuit not found"))
  157. };
  158. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1) else {
  159. return Err(anyhow!("Burn circuit not found"))
  160. };
  161. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  162. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  163. let k = 13;
  164. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin), mint_zkbin.clone());
  165. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin), burn_zkbin.clone());
  166. eprintln!("Creating Mint circuit proving key");
  167. let mint_pk = ProvingKey::build(k, &mint_circuit);
  168. eprintln!("Creating Burn circuit proving key");
  169. let burn_pk = ProvingKey::build(k, &burn_circuit);
  170. // TODO: Maybe some kind of verification at this point
  171. // Now we should have everything we need to build the swap half
  172. eprintln!("Building second half of the swap transaction");
  173. let (half_params, half_proofs, half_keys, _spent_coins, _value_blinds, _token_blinds) =
  174. build_half_swap_tx(
  175. &address,
  176. partial.value_pair.1,
  177. partial.token_pair.1,
  178. partial.value_pair.0,
  179. partial.token_pair.0,
  180. &partial.value_blinds,
  181. &partial.token_blinds,
  182. &[burn_coin],
  183. &tree,
  184. &mint_zkbin,
  185. &mint_pk,
  186. &burn_zkbin,
  187. &burn_pk,
  188. )?;
  189. let full_params = MoneyTransferParams {
  190. clear_inputs: vec![],
  191. inputs: vec![partial.params.inputs[0].clone(), half_params.inputs[0].clone()],
  192. outputs: vec![partial.params.outputs[0].clone(), half_params.outputs[0].clone()],
  193. };
  194. let full_proofs = vec![
  195. partial.proofs[0].clone(),
  196. half_proofs[0].clone(),
  197. partial.proofs[1].clone(),
  198. half_proofs[1].clone(),
  199. ];
  200. let mut data = vec![MoneyFunction::OtcSwap as u8];
  201. full_params.encode(&mut data)?;
  202. let mut tx = Transaction {
  203. calls: vec![ContractCall { contract_id, data }],
  204. proofs: vec![full_proofs],
  205. signatures: vec![],
  206. };
  207. eprintln!("Signing swap transaction");
  208. let sigs = tx.create_sigs(&mut OsRng, &half_keys)?;
  209. tx.signatures = vec![sigs];
  210. Ok(tx)
  211. }
  212. /// Inspect and verify a given swap (half or full) transaction
  213. pub async fn inspect_swap(&self, bytes: Vec<u8>) -> Result<()> {
  214. let mut full: Option<Transaction> = None;
  215. let mut _half: Option<PartialSwapData> = None;
  216. if let Ok(v) = deserialize(&bytes) {
  217. full = Some(v)
  218. };
  219. match deserialize(&bytes) {
  220. Ok(v) => _half = Some(v),
  221. Err(_) => {
  222. if full.is_none() {
  223. return Err(anyhow!("Failed to deserialize to Transaction or PartialSwapData"))
  224. }
  225. }
  226. }
  227. if let Some(tx) = full {
  228. // We're inspecting a full transaction
  229. if tx.calls.len() != 1 {
  230. eprintln!(
  231. "Found {} contract calls in the transaction, there should be 1",
  232. tx.calls.len()
  233. );
  234. return Err(anyhow!("Inspection failed"))
  235. }
  236. let params: MoneyTransferParams = deserialize(&tx.calls[0].data[1..])?;
  237. eprintln!("Parameters:\n{:#?}", params);
  238. if params.inputs.len() != 2 {
  239. eprintln!("Found {} inputs, there should be 2", params.inputs.len());
  240. return Err(anyhow!("Inspection failed"))
  241. }
  242. if params.outputs.len() != 2 {
  243. eprintln!("Found {} outputs, there should be 2", params.outputs.len());
  244. return Err(anyhow!("Inspection failed"))
  245. }
  246. // Try to decrypt one of the outputs.
  247. let secret_keys = self.wallet_secrets().await?;
  248. let mut skey: Option<SecretKey> = None;
  249. let mut note: Option<Note> = None;
  250. let mut output_idx = 0;
  251. for output in &params.outputs {
  252. let ciphertext = output.ciphertext.clone();
  253. let ephem_public = output.ephem_public;
  254. let e_note = EncryptedNote { ciphertext, ephem_public };
  255. eprintln!("Trying to decrypt note in output {}", output_idx);
  256. for secret in &secret_keys {
  257. if let Ok(d_note) = e_note.decrypt(secret) {
  258. let s: SecretKey = deserialize(&d_note.memo)?;
  259. skey = Some(s);
  260. note = Some(d_note);
  261. eprintln!("Successfully decrypted and found an ephemeral secret");
  262. break
  263. }
  264. }
  265. if note.is_some() {
  266. break
  267. }
  268. output_idx += 1;
  269. }
  270. let Some(note) = note else {
  271. eprintln!("Error: Could not decrypt notes of either output");
  272. return Err(anyhow!("Inspection failed"))
  273. };
  274. eprintln!(
  275. "Output[{}] value: {} ({})",
  276. output_idx,
  277. note.value,
  278. encode_base10(note.value, 8)
  279. );
  280. eprintln!("Output[{}] token ID: {}", output_idx, note.token_id);
  281. let skey = skey.unwrap();
  282. let (pub_x, pub_y) = PublicKey::from_secret(skey).xy();
  283. let coin = poseidon_hash([
  284. pub_x,
  285. pub_y,
  286. pallas::Base::from(note.value),
  287. note.token_id.inner(),
  288. note.serial,
  289. note.coin_blind,
  290. ]);
  291. if coin == params.outputs[output_idx].coin {
  292. eprintln!("Output[{}] coin matches decrypted note metadata", output_idx);
  293. } else {
  294. eprintln!("Error: Output[{}] coin does not match note metadata", output_idx);
  295. return Err(anyhow!("Inspection failed"))
  296. }
  297. let valcom = pedersen_commitment_u64(note.value, note.value_blind);
  298. let tokcom = pedersen_commitment_base(note.token_id.inner(), note.token_blind);
  299. if valcom != params.outputs[output_idx].value_commit {
  300. eprintln!(
  301. "Error: Output[{}] value commitment does not match note metadata",
  302. output_idx
  303. );
  304. return Err(anyhow!("Inspection failed"))
  305. }
  306. if tokcom != params.outputs[output_idx].token_commit {
  307. eprintln!(
  308. "Error: Output[{}] token commitment does not match note metadata",
  309. output_idx
  310. );
  311. return Err(anyhow!("Inspection failed"))
  312. }
  313. eprintln!("Value and token commitments match decrypted note metadata");
  314. // Verify that the output commitments match the other input commitments
  315. match output_idx {
  316. 0 => {
  317. if valcom != params.inputs[1].value_commit ||
  318. tokcom != params.inputs[1].token_commit
  319. {
  320. eprintln!("Error: Value/Token commits of output[0] do not match input[1]");
  321. return Err(anyhow!("Inspection failed"))
  322. }
  323. }
  324. 1 => {
  325. if valcom != params.inputs[0].value_commit ||
  326. tokcom != params.inputs[0].token_commit
  327. {
  328. eprintln!("Error: Value/Token commits of output[1] do not match input[0]");
  329. return Err(anyhow!("Inspection failed"))
  330. }
  331. }
  332. _ => unreachable!(),
  333. }
  334. eprintln!("Found matching pedersen commitments for outputs and inputs");
  335. // TODO: Verify signature
  336. // TODO: Verify ZK proofs
  337. return Ok(())
  338. }
  339. // TODO: Inspect PartialSwapData
  340. todo!("Inspect PartialSwapData");
  341. }
  342. /// Sign a given transaction by retrieving the secret key from the encrypted
  343. /// note and prepending it to the transaction's signatures.
  344. pub async fn sign_swap(&self, tx: &mut Transaction) -> Result<()> {
  345. // We need our secret keys to try and decrypt the note
  346. let secret_keys = self.wallet_secrets().await?;
  347. let params: MoneyTransferParams = deserialize(&tx.calls[0].data[1..])?;
  348. // Our output should be outputs[0] so we try to decrypt that.
  349. let ciphertext = params.outputs[0].ciphertext.clone();
  350. let ephem_public = params.outputs[0].ephem_public;
  351. let encrypted_note = EncryptedNote { ciphertext, ephem_public };
  352. eprintln!("Trying to decrypt note in outputs[0]");
  353. let mut skey = None;
  354. for secret in &secret_keys {
  355. if let Ok(note) = encrypted_note.decrypt(secret) {
  356. let s: SecretKey = deserialize(&note.memo)?;
  357. eprintln!("Successfully decrypted and found an ephemeral secret");
  358. skey = Some(s);
  359. break
  360. }
  361. }
  362. let Some(skey) = skey else {
  363. eprintln!("Error: Failed to decrypt note with any of our secret keys");
  364. return Err(anyhow!("Failed to decrypt note with any of our secret keys"))
  365. };
  366. eprintln!("Signing swap transaction");
  367. let sigs = tx.create_sigs(&mut OsRng, &[skey])?;
  368. tx.signatures[0].insert(0, sigs[0]);
  369. Ok(())
  370. }
  371. }