diff --git a/common/src/transaction.rs b/common/src/transaction.rs index baa57fe..fd38138 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -4,10 +4,9 @@ use k256::ecdsa::{Signature, SigningKey, VerifyingKey}; use log::info; use serde::{Deserialize, Serialize}; -use sha2::{Digest, digest::FixedOutput}; - use sha2::digest::typenum::{B0, B1}; use sha2::digest::typenum::{UInt, UTerm}; +use sha2::{Digest, digest::FixedOutput}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum NSSATransaction { diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index bcb877b..0eaae0d 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -712,30 +712,12 @@ pub async fn test_success_private_transfer_to_another_owned_account() { to: to.to_string(), amount: 100, }; - // - let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = - wallet::execute_subcommand(command).await.unwrap() - else { - panic!("invalid subcommand return value"); - }; + + wallet::execute_subcommand(command).await.unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - let command = Command::FetchPrivateAccount { - tx_hash: tx_hash.clone(), - acc_addr: from.to_string(), - output_id: 0, - }; - wallet::execute_subcommand(command).await.unwrap(); - - let command = Command::FetchPrivateAccount { - tx_hash, - acc_addr: to.to_string(), - output_id: 1, - }; - wallet::execute_subcommand(command).await.unwrap(); - let wallet_config = fetch_config().unwrap(); let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); @@ -774,13 +756,6 @@ pub async fn test_success_private_transfer_to_another_foreign_account() { info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - let command = Command::FetchPrivateAccount { - tx_hash: tx_hash.clone(), - acc_addr: from.to_string(), - output_id: 0, - }; - wallet::execute_subcommand(command).await.unwrap(); - let wallet_config = fetch_config().unwrap(); let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); @@ -879,21 +854,11 @@ pub async fn test_success_deshielded_transfer_to_another_account() { let from_acc = wallet_storage.get_account_private(&from).unwrap(); assert_eq!(from_acc.balance, 10000); - let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = - wallet::execute_subcommand(command).await.unwrap() - else { - panic!("invalid subcommand return value"); - }; + wallet::execute_subcommand(command).await.unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - let command = Command::FetchPrivateAccount { - tx_hash, - acc_addr: from.to_string(), - output_id: 0, - }; - wallet::execute_subcommand(command).await.unwrap(); let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); let from_acc = wallet_storage.get_account_private(&from).unwrap(); @@ -926,21 +891,12 @@ pub async fn test_success_shielded_transfer_to_another_owned_account() { let wallet_config = fetch_config().unwrap(); let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); - let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = - wallet::execute_subcommand(command).await.unwrap() - else { - panic!("invalid subcommand return value"); - }; + wallet::execute_subcommand(command).await.unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - let command = Command::FetchPrivateAccount { - tx_hash, - acc_addr: to.to_string(), - output_id: 0, - }; - wallet::execute_subcommand(command).await.unwrap(); + let wallet_config = fetch_config().unwrap(); let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); let acc_to = wallet_storage.get_account_private(&to).unwrap(); @@ -1105,6 +1061,63 @@ pub async fn test_pinata_private_receiver() { info!("Success!"); } +pub async fn test_pinata_private_receiver_new_account() { + info!("test_pinata_private_receiver"); + let pinata_addr = "cafe".repeat(16); + let pinata_prize = 150; + let solution = 989106; + + // Create new account for the token supply holder (private) + let SubcommandReturnValue::RegisterAccount { addr: winner_addr } = + wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + + let command = Command::ClaimPinataPrivateReceiverOwned { + pinata_addr: pinata_addr.clone(), + winner_addr: winner_addr.to_string(), + solution, + }; + + let wallet_config = fetch_config().unwrap(); + + let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + + let pinata_balance_pre = seq_client + .get_account_balance(pinata_addr.clone()) + .await + .unwrap() + .balance; + + wallet::execute_subcommand(command).await.unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + info!("Checking correct balance move"); + let pinata_balance_post = seq_client + .get_account_balance(pinata_addr.clone()) + .await + .unwrap() + .balance; + + let wallet_config = fetch_config().unwrap(); + let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&winner_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + assert_eq!(pinata_balance_post, pinata_balance_pre - pinata_prize); + + info!("Success!"); +} + macro_rules! test_cleanup_wrap { ($home_dir:ident, $test_func:ident) => {{ let res = pre_test($home_dir.clone()).await.unwrap(); @@ -1194,6 +1207,9 @@ pub async fn main_tests_runner() -> Result<()> { "test_success_token_program_private_claiming_path" => { test_cleanup_wrap!(home_dir, test_success_token_program_private_claiming_path); } + "test_pinata_private_receiver_new_account" => { + test_cleanup_wrap!(home_dir, test_pinata_private_receiver_new_account); + } "all" => { test_cleanup_wrap!(home_dir, test_success_move_to_another_account); test_cleanup_wrap!(home_dir, test_success); @@ -1228,6 +1244,7 @@ pub async fn main_tests_runner() -> Result<()> { test_cleanup_wrap!(home_dir, test_pinata_private_receiver); test_cleanup_wrap!(home_dir, test_success_token_program_private_owned); test_cleanup_wrap!(home_dir, test_success_token_program_private_claiming_path); + test_cleanup_wrap!(home_dir, test_pinata_private_receiver_new_account); } "all_private" => { test_cleanup_wrap!( @@ -1257,6 +1274,7 @@ pub async fn main_tests_runner() -> Result<()> { test_cleanup_wrap!(home_dir, test_pinata_private_receiver); test_cleanup_wrap!(home_dir, test_success_token_program_private_owned); test_cleanup_wrap!(home_dir, test_success_token_program_private_claiming_path); + test_cleanup_wrap!(home_dir, test_pinata_private_receiver_new_account); } _ => { anyhow::bail!("Unknown test name"); diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index cdd98e6..aacdfcd 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -25,8 +25,6 @@ use crate::{ poller::TxPoller, }; -// - pub const HOME_DIR_ENV_VAR: &str = "NSSA_WALLET_HOME_DIR"; pub mod chain_storage; @@ -136,6 +134,47 @@ impl WalletCore { Ok(NSSATransaction::try_from(&pub_tx)?) } + + pub async fn check_private_account_initialized(&self, addr: &Address) -> bool { + if let Some(acc_comm) = self.get_private_account_commitment(addr) { + matches!( + self.sequencer_client + .get_proof_for_commitment(acc_comm) + .await, + Ok(Some(_)) + ) + } else { + false + } + } + + pub fn decode_insert_privacy_preserving_transaction_results( + &mut self, + tx: nssa::privacy_preserving_transaction::PrivacyPreservingTransaction, + acc_decode_data: &[(nssa_core::SharedSecretKey, Address)], + ) -> Result<()> { + for (output_index, (secret, acc_address)) in acc_decode_data.iter().enumerate() { + let acc_ead = tx.message.encrypted_private_post_states[output_index].clone(); + let acc_comm = tx.message.new_commitments[output_index].clone(); + + let res_acc = nssa_core::EncryptionScheme::decrypt( + &acc_ead.ciphertext, + secret, + &acc_comm, + output_index as u32, + ) + .unwrap(); + + println!("Received new acc {res_acc:#?}"); + + self.storage + .insert_private_account_data(*acc_address, res_acc); + } + + println!("Transaction data is {:?}", tx.message); + + Ok(()) + } } ///Represents CLI command for a wallet @@ -362,39 +401,10 @@ pub async fn execute_subcommand(command: Command) -> Result Result Result Result Result Result Result Result Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { + let Some((winner_keys, winner_acc)) = self + .storage + .user_data + .get_private_account(&winner_addr) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let pinata_acc = self.get_account_public(pinata_addr).await.unwrap(); + + let winner_npk = winner_keys.nullifer_public_key; + let winner_ipk = winner_keys.incoming_viewing_public_key; + + let program = nssa::program::Program::pinata(); + + let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); + let winner_pre = AccountWithMetadata::new(winner_acc.clone(), false, &winner_npk); + + let eph_holder_winner = EphemeralKeyHolder::new(&winner_npk); + let shared_secret_winner = eph_holder_winner.calculate_shared_secret_sender(&winner_ipk); + + let (output, proof) = circuit::execute_and_prove( + &[pinata_pre, winner_pre], + &nssa::program::Program::serialize_instruction(solution).unwrap(), + &[0, 2], + &produce_random_nonces(1), + &[(winner_npk.clone(), shared_secret_winner.clone())], + &[], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![pinata_addr], + vec![], + vec![( + winner_npk.clone(), + winner_ipk.clone(), + eph_holder_winner.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::privacy_preserving_transaction::PrivacyPreservingTransaction::new( + message, + witness_set, + ); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_winner], + )) + } }