rpc_swap.rs 17 KB

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