rpc_swap.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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, pedersen::pedersen_commitment_u64, poseidon_hash,
  34. 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(Debug, Clone, 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: MoneyTransferParamsV1,
  47. proofs: Vec<Proof>,
  48. value_pair: (u64, u64),
  49. token_pair: (TokenId, TokenId),
  50. value_blinds: Vec<pallas::Scalar>,
  51. token_blinds: Vec<pallas::Base>,
  52. }
  53. impl fmt::Display for PartialSwapData {
  54. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  55. let s =
  56. format!(
  57. "{:#?}\nValue pair: {}:{}\nToken pair: {}:{}\nValue blinds: {:?}\nToken blinds: {:?}\n",
  58. self.params, self.value_pair.0, self.value_pair.1, self.token_pair.0, self.token_pair.1,
  59. self.value_blinds, self.token_blinds,
  60. );
  61. write!(f, "{}", s)
  62. }
  63. }
  64. impl Drk {
  65. /// Initialize the first half of an atomic swap
  66. pub async fn init_swap(
  67. &self,
  68. value_send: u64,
  69. token_send: TokenId,
  70. value_recv: u64,
  71. token_recv: TokenId,
  72. ) -> Result<PartialSwapData> {
  73. // First we'll fetch all of our unspent coins from the wallet.
  74. let mut owncoins = self.get_coins(false).await?;
  75. // Then we see if we have one that we can send.
  76. owncoins.retain(|x| {
  77. x.0.note.value == value_send &&
  78. x.0.note.token_id == token_send &&
  79. x.0.note.spend_hook == pallas::Base::zero()
  80. });
  81. if owncoins.is_empty() {
  82. return Err(anyhow!(
  83. "Did not find any unspent coins of value {} and token_id {}",
  84. value_send,
  85. token_send
  86. ))
  87. }
  88. // If there are any, we'll just spend the first one we see.
  89. let burn_coin = owncoins[0].0.clone();
  90. // Fetch our default address
  91. let address = self.wallet_address(1).await?;
  92. // We'll also need our Merkle tree
  93. let tree = self.get_money_tree().await?;
  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)
  100. else {
  101. return Err(anyhow!("Mint circuit not found"))
  102. };
  103. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  104. else {
  105. return Err(anyhow!("Burn circuit not found"))
  106. };
  107. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  108. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  109. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  110. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  111. // Since we're creating the first half, we generate the blinds.
  112. let value_blinds = [pallas::Scalar::random(&mut OsRng), pallas::Scalar::random(&mut OsRng)];
  113. let token_blinds = [pallas::Base::random(&mut OsRng), pallas::Base::random(&mut OsRng)];
  114. // Now we should have everything we need to build the swap half
  115. eprintln!("Creating Mint and Burn circuit proving keys");
  116. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  117. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  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,
  133. burn_zkbin,
  134. burn_pk,
  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 mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  187. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  188. // TODO: Maybe some kind of verification at this point
  189. // Now we should have everything we need to build the swap half
  190. eprintln!("Creating Mint and Burn circuit proving keys");
  191. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  192. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  193. let builder = SwapCallBuilder {
  194. pubkey: address,
  195. value_send: partial.value_pair.1,
  196. token_id_send: partial.token_pair.1,
  197. value_recv: partial.value_pair.0,
  198. token_id_recv: partial.token_pair.0,
  199. user_data_blind_send: pallas::Base::random(&mut OsRng), // <-- FIXME: Perhaps should be passed in
  200. spend_hook_recv: pallas::Base::zero(), // <-- FIXME: Should be passed in
  201. user_data_recv: pallas::Base::zero(), // <-- FIXME: Should be passed in
  202. value_blinds: [partial.value_blinds[1], partial.value_blinds[0]],
  203. token_blinds: [partial.token_blinds[1], partial.token_blinds[0]],
  204. coin: burn_coin,
  205. tree,
  206. mint_zkbin,
  207. mint_pk,
  208. burn_zkbin,
  209. burn_pk,
  210. };
  211. eprintln!("Building second half of the swap transaction");
  212. let debris = builder.build()?;
  213. let full_params = MoneyTransferParamsV1 {
  214. clear_inputs: vec![],
  215. inputs: vec![partial.params.inputs[0].clone(), debris.params.inputs[0].clone()],
  216. outputs: vec![partial.params.outputs[0].clone(), debris.params.outputs[0].clone()],
  217. };
  218. let full_proofs = vec![
  219. partial.proofs[0].clone(),
  220. debris.proofs[0].clone(),
  221. partial.proofs[1].clone(),
  222. debris.proofs[1].clone(),
  223. ];
  224. let mut data = vec![MoneyFunction::OtcSwapV1 as u8];
  225. full_params.encode(&mut data)?;
  226. let mut tx = Transaction {
  227. calls: vec![ContractCall { contract_id, data }],
  228. proofs: vec![full_proofs],
  229. signatures: vec![],
  230. };
  231. eprintln!("Signing swap transaction");
  232. let sigs = tx.create_sigs(&mut OsRng, &[debris.signature_secret])?;
  233. tx.signatures = vec![sigs];
  234. Ok(tx)
  235. }
  236. /// Inspect and verify a given swap (half or full) transaction
  237. pub async fn inspect_swap(&self, bytes: Vec<u8>) -> Result<()> {
  238. let mut full: Option<Transaction> = None;
  239. let mut half: Option<PartialSwapData> = None;
  240. if let Ok(v) = deserialize(&bytes) {
  241. full = Some(v)
  242. };
  243. match deserialize(&bytes) {
  244. Ok(v) => half = Some(v),
  245. Err(_) => {
  246. if full.is_none() {
  247. return Err(anyhow!("Failed to deserialize to Transaction or PartialSwapData"))
  248. }
  249. }
  250. }
  251. if let Some(tx) = full {
  252. // We're inspecting a full transaction
  253. if tx.calls.len() != 1 {
  254. eprintln!(
  255. "Found {} contract calls in the transaction, there should be 1",
  256. tx.calls.len()
  257. );
  258. return Err(anyhow!("Inspection failed"))
  259. }
  260. let params: MoneyTransferParamsV1 = deserialize(&tx.calls[0].data[1..])?;
  261. eprintln!("Parameters:\n{:#?}", params);
  262. if params.inputs.len() != 2 {
  263. eprintln!("Found {} inputs, there should be 2", params.inputs.len());
  264. return Err(anyhow!("Inspection failed"))
  265. }
  266. if params.outputs.len() != 2 {
  267. eprintln!("Found {} outputs, there should be 2", params.outputs.len());
  268. return Err(anyhow!("Inspection failed"))
  269. }
  270. // Try to decrypt one of the outputs.
  271. let secret_keys = self.get_money_secrets().await?;
  272. let mut skey: Option<SecretKey> = None;
  273. let mut note: Option<MoneyNote> = None;
  274. let mut output_idx = 0;
  275. for output in &params.outputs {
  276. eprintln!("Trying to decrypt note in output {}", output_idx);
  277. for secret in &secret_keys {
  278. if let Ok(d_note) = output.note.decrypt::<MoneyNote>(secret) {
  279. let s: SecretKey = deserialize(&d_note.memo)?;
  280. skey = Some(s);
  281. note = Some(d_note);
  282. eprintln!("Successfully decrypted and found an ephemeral secret");
  283. break
  284. }
  285. }
  286. if note.is_some() {
  287. break
  288. }
  289. output_idx += 1;
  290. }
  291. let Some(note) = note else {
  292. eprintln!("Error: Could not decrypt notes of either output");
  293. return Err(anyhow!("Inspection failed"))
  294. };
  295. eprintln!(
  296. "Output[{}] value: {} ({})",
  297. output_idx,
  298. note.value,
  299. encode_base10(note.value, 8)
  300. );
  301. eprintln!("Output[{}] token ID: {}", output_idx, note.token_id);
  302. let skey = skey.unwrap();
  303. let (pub_x, pub_y) = PublicKey::from_secret(skey).xy();
  304. let coin = Coin::from(poseidon_hash([
  305. pub_x,
  306. pub_y,
  307. pallas::Base::from(note.value),
  308. note.token_id.inner(),
  309. note.serial,
  310. ]));
  311. if coin == params.outputs[output_idx].coin {
  312. eprintln!("Output[{}] coin matches decrypted note metadata", output_idx);
  313. } else {
  314. eprintln!("Error: Output[{}] coin does not match note metadata", output_idx);
  315. return Err(anyhow!("Inspection failed"))
  316. }
  317. let valcom = pedersen_commitment_u64(note.value, note.value_blind);
  318. let tokcom = poseidon_hash([note.token_id.inner(), note.token_blind]);
  319. if valcom != params.outputs[output_idx].value_commit {
  320. eprintln!(
  321. "Error: Output[{}] value commitment does not match note metadata",
  322. output_idx
  323. );
  324. return Err(anyhow!("Inspection failed"))
  325. }
  326. if tokcom != params.outputs[output_idx].token_commit {
  327. eprintln!(
  328. "Error: Output[{}] token commitment does not match note metadata",
  329. output_idx
  330. );
  331. return Err(anyhow!("Inspection failed"))
  332. }
  333. eprintln!("Value and token commitments match decrypted note metadata");
  334. // Verify that the output commitments match the other input commitments
  335. match output_idx {
  336. 0 => {
  337. if valcom != params.inputs[1].value_commit ||
  338. tokcom != params.inputs[1].token_commit
  339. {
  340. eprintln!("Error: Value/Token commits of output[0] do not match input[1]");
  341. return Err(anyhow!("Inspection failed"))
  342. }
  343. }
  344. 1 => {
  345. if valcom != params.inputs[0].value_commit ||
  346. tokcom != params.inputs[0].token_commit
  347. {
  348. eprintln!("Error: Value/Token commits of output[1] do not match input[0]");
  349. return Err(anyhow!("Inspection failed"))
  350. }
  351. }
  352. _ => unreachable!(),
  353. }
  354. eprintln!("Found matching pedersen commitments for outputs and inputs");
  355. // TODO: Verify signature
  356. // TODO: Verify ZK proofs
  357. return Ok(())
  358. }
  359. // Inspect PartialSwapData
  360. let partial = half.unwrap();
  361. eprintln!("{}", partial);
  362. Ok(())
  363. }
  364. /// Sign a given transaction by retrieving the secret key from the encrypted
  365. /// note and prepending it to the transaction's signatures.
  366. pub async fn sign_swap(&self, tx: &mut Transaction) -> Result<()> {
  367. // We need our secret keys to try and decrypt the note
  368. let secret_keys = self.get_money_secrets().await?;
  369. let params: MoneyTransferParamsV1 = deserialize(&tx.calls[0].data[1..])?;
  370. // Our output should be outputs[0] so we try to decrypt that.
  371. let encrypted_note = &params.outputs[0].note;
  372. eprintln!("Trying to decrypt note in outputs[0]");
  373. let mut skey = None;
  374. for secret in &secret_keys {
  375. if let Ok(note) = encrypted_note.decrypt::<MoneyNote>(secret) {
  376. let s: SecretKey = deserialize(&note.memo)?;
  377. eprintln!("Successfully decrypted and found an ephemeral secret");
  378. skey = Some(s);
  379. break
  380. }
  381. }
  382. let Some(skey) = skey else {
  383. eprintln!("Error: Failed to decrypt note with any of our secret keys");
  384. return Err(anyhow!("Failed to decrypt note with any of our secret keys"))
  385. };
  386. eprintln!("Signing swap transaction");
  387. let sigs = tx.create_sigs(&mut OsRng, &[skey])?;
  388. tx.signatures[0].insert(0, sigs[0]);
  389. Ok(())
  390. }
  391. }