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