From e041b5780763aef5b69724f968b08bf115d458cb Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Tue, 7 Oct 2025 10:40:06 +0300 Subject: [PATCH 01/23] feat: private pinata claim method on wallet --- wallet/src/lib.rs | 85 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 3 deletions(-) diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 0e8b1cb..d507430 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -10,16 +10,17 @@ use common::{ use anyhow::Result; use chain_storage::WalletChainStore; use config::WalletConfig; +use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; use log::info; -use nssa::{Account, Address}; +use nssa::{Account, Address, privacy_preserving_transaction::circuit}; use clap::{Parser, Subcommand}; -use nssa_core::Commitment; +use nssa_core::{Commitment, SharedSecretKey, account::AccountWithMetadata}; use crate::{ helperfunctions::{ HumanReadableAccount, fetch_config, fetch_persistent_accounts, get_home, - produce_data_for_storage, + produce_data_for_storage, produce_random_nonces, }, poller::TxPoller, }; @@ -105,6 +106,84 @@ impl WalletCore { Ok(self.sequencer_client.send_tx_public(tx).await?) } + pub async fn claim_pinata_private_owned_account( + &self, + pinata_addr: Address, + winner_addr: Address, + solution: u128, + ) -> 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 winner_commitment = Commitment::new(&winner_npk, &winner_acc); + + let pinata_pre = AccountWithMetadata::new(pinata_acc, false, pinata_addr); + let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &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, 1], + &produce_random_nonces(1), + &[(winner_npk.clone(), shared_secret_winner.clone())], + &[( + winner_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(winner_commitment) + .await + .unwrap() + .unwrap(), + )], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![], + 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], + )) + } + pub async fn send_new_token_definition( &self, definition_address: Address, From 566df336f52be51d012ca5c20d474cee15a6403a Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Wed, 8 Oct 2025 16:01:35 +0300 Subject: [PATCH 02/23] feat: wallet method for private pinata claim --- ci_scripts/test-ubuntu.sh | 3 +- integration_tests/src/lib.rs | 64 +++++++++++++++++++++++++++++++++++- wallet/src/lib.rs | 58 ++++++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 2 deletions(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index 5c19b36..fd6d6a8 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -9,11 +9,12 @@ RISC0_DEV_MODE=1 cargo test --release cd integration_tests export NSSA_WALLET_HOME_DIR=$(pwd)/configs/debug/wallet/ export RUST_LOG=info -cargo run $(pwd)/configs/debug all echo "Try test valid proof at least once" cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account echo "Continuing in dev mode" RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all +echo "ToDo remove after Draft" +cargo run $(pwd)/configs/debug test_pinata_private_receiver cd .. cd nssa/program_methods/guest && cargo test --release diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 1690445..5149516 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -457,7 +457,7 @@ 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 { @@ -791,6 +791,65 @@ pub async fn test_pinata() { info!("Success!"); } +pub async fn test_pinata_private_receiver() { + info!("test_pinata_private_receiver"); + let pinata_addr = "cafe".repeat(16); + let pinata_prize = 150; + let solution = 989106; + + let command = Command::ClaimPinataPrivateReceiverOwned { + pinata_addr: pinata_addr.clone(), + winner_addr: ACC_SENDER_PRIVATE.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; + + let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = + wallet::execute_subcommand(command).await.unwrap() + else { + panic!("invalid subcommand return value"); + }; + + 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 command = Command::FetchPrivateAccount { + tx_hash: tx_hash.clone(), + acc_addr: ACC_SENDER_PRIVATE.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(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&ACC_SENDER_PRIVATE.parse().unwrap()) + .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(); @@ -871,6 +930,9 @@ pub async fn main_tests_runner() -> Result<()> { "test_pinata" => { test_cleanup_wrap!(home_dir, test_pinata); } + "test_pinata_private_receiver" => { + test_cleanup_wrap!(home_dir, test_pinata_private_receiver); + } "all" => { test_cleanup_wrap!(home_dir, test_success_move_to_another_account); test_cleanup_wrap!(home_dir, test_success); diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index d507430..4c7b726 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -456,6 +456,19 @@ pub enum Command { #[arg(long)] solution: u128, }, + // TODO: Testnet only. Refactor to prevent compilation on mainnet. + // Claim piñata prize + ClaimPinataPrivateReceiverOwned { + ///pinata_addr - valid 32 byte hex string + #[arg(long)] + pinata_addr: String, + ///winner_addr - valid 32 byte hex string + #[arg(long)] + winner_addr: String, + ///solution - solution to pinata challenge + #[arg(long)] + solution: u128, + }, } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -926,6 +939,51 @@ pub async fn execute_subcommand(command: Command) -> Result { + let pinata_addr = pinata_addr.parse().unwrap(); + let winner_addr = winner_addr.parse().unwrap(); + + let (res, [secret_winner]) = wallet_core + .claim_pinata_private_owned_account(pinata_addr, winner_addr, solution) + .await?; + info!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let winner_ead = tx.message.encrypted_private_post_states[0].clone(); + let winner_comm = tx.message.new_commitments[0].clone(); + + let res_acc_winner = nssa_core::EncryptionScheme::decrypt( + &winner_ead.ciphertext, + &secret_winner, + &winner_comm, + 0, + ) + .unwrap(); + + println!("Received new from acc {res_acc_winner:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(winner_addr, res_acc_winner); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } + } }; Ok(subcommand_ret) From e8f660c2c7588729e9e5bc290db06793284af566 Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Wed, 8 Oct 2025 20:27:09 -0300 Subject: [PATCH 03/23] wip --- nssa/Cargo.toml | 3 +++ nssa/build.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++ nssa/src/lib.rs | 4 +++ nssa/src/program.rs | 2 +- 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 nssa/build.rs diff --git a/nssa/Cargo.toml b/nssa/Cargo.toml index 93553a8..f1a055e 100644 --- a/nssa/Cargo.toml +++ b/nssa/Cargo.toml @@ -15,6 +15,9 @@ rand = "0.8" borsh = "1.5.7" hex = "0.4.3" +[build-dependencies] +risc0-build = "3.0.3" + [dev-dependencies] test-program-methods = { path = "test_program_methods" } hex-literal = "1.0.0" diff --git a/nssa/build.rs b/nssa/build.rs new file mode 100644 index 0000000..f04ba25 --- /dev/null +++ b/nssa/build.rs @@ -0,0 +1,66 @@ +use std::{env, fs, path::Path, process::Command}; +use risc0_build::a; + +fn main() { + // 1️⃣ Crate root and OUT_DIR + let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); + let out_dir = env::var("OUT_DIR").unwrap(); + + // 2️⃣ Directory to write generated module + let mod_dir = Path::new(&out_dir).join("nssa_programs"); + let mod_file = mod_dir.join("mod.rs"); + + println!("cargo:rerun-if-changed=program_methods/guest"); + + // 3️⃣ Build the Risc0 guest program + let guest_manifest = Path::new(&manifest_dir) + .join("program_methods/guest/Cargo.toml"); + + let status = Command::new("cargo") + .arg("risczero") + .arg("build") + .arg("--manifest-path") + .arg(&guest_manifest) + .status() + .expect("failed to run risczero build"); + assert!(status.success(), "Risc0 deterministic build failed"); + + // 4️⃣ Target directory where the Risc0 build produces .bin files + let target_dir = Path::new(&manifest_dir) + .join("program_methods/guest/target/riscv32im-risc0-zkvm-elf/docker/"); + + println!("cargo:warning=Looking for binaries in {}", target_dir.display()); + + // 5️⃣ Collect all .bin files + let bins = fs::read_dir(&target_dir) + .expect("failed to read external target dir") + .filter_map(Result::ok) + .filter(|e| e.path().extension().map(|ext| ext == "bin").unwrap_or(false)) + .collect::>(); + + if bins.is_empty() { + panic!("No .bin files found in {:?}", target_dir); + } + + println!("cargo:warning=Found {} binaries:", bins.len()); + for b in &bins { + println!("cargo:warning= - {}", b.path().display()); + } + + // 6️⃣ Generate Rust module + fs::create_dir_all(&mod_dir).unwrap(); + let mut src = String::new(); + for entry in bins { + let path = entry.path(); + let name = path.file_stem().unwrap().to_string_lossy(); + src.push_str(&format!( + "pub const {}_ELF: &[u8] = include_bytes!(r#\"{}\"#);\n", + name.to_uppercase(), + path.display() + )); + } + + fs::write(&mod_file, src).unwrap(); + println!("cargo:warning=Generated module at {}", mod_file.display()); +} + diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index 21defa9..cdf45a2 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -1,3 +1,7 @@ +pub mod programs { + include!(concat!(env!("OUT_DIR"), "/nssa_programs/mod.rs")); +} + pub mod encoding; pub mod error; mod merkle_tree; diff --git a/nssa/src/program.rs b/nssa/src/program.rs index 5abc153..fc13865 100644 --- a/nssa/src/program.rs +++ b/nssa/src/program.rs @@ -2,7 +2,7 @@ use nssa_core::{ account::{Account, AccountWithMetadata}, program::{InstructionData, ProgramId, ProgramOutput}, }; -use program_methods::{ +use crate::programs::{ AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, TOKEN_ELF, TOKEN_ID, }; From 359e545b69d3071fb0e841c74f913801763cb8fe Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Thu, 9 Oct 2025 09:44:13 +0300 Subject: [PATCH 04/23] fix: pinata test fix --- ci_scripts/test-ubuntu.sh | 2 -- integration_tests/src/lib.rs | 2 ++ wallet/src/lib.rs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index fd6d6a8..78761df 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -13,8 +13,6 @@ echo "Try test valid proof at least once" cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account echo "Continuing in dev mode" RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all -echo "ToDo remove after Draft" -cargo run $(pwd)/configs/debug test_pinata_private_receiver cd .. cd nssa/program_methods/guest && cargo test --release diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 5149516..65e8574 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -964,6 +964,7 @@ pub async fn main_tests_runner() -> Result<()> { test_success_private_transfer_to_another_owned_account_claiming_path ); test_cleanup_wrap!(home_dir, test_pinata); + test_cleanup_wrap!(home_dir, test_pinata_private_receiver); } "all_private" => { test_cleanup_wrap!( @@ -990,6 +991,7 @@ pub async fn main_tests_runner() -> Result<()> { home_dir, test_success_private_transfer_to_another_owned_account_claiming_path ); + test_cleanup_wrap!(home_dir, test_pinata_private_receiver); } _ => { anyhow::bail!("Unknown test name"); diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 4c7b726..b65fc8a 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -130,7 +130,7 @@ impl WalletCore { let winner_commitment = Commitment::new(&winner_npk, &winner_acc); - let pinata_pre = AccountWithMetadata::new(pinata_acc, false, pinata_addr); + let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &winner_npk); let eph_holder_winner = EphemeralKeyHolder::new(&winner_npk); @@ -156,7 +156,7 @@ impl WalletCore { let message = nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( - vec![], + vec![pinata_addr], vec![], vec![( winner_npk.clone(), From 0635bd201d5b0193aa3074ea0462756c7abde2cf Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Thu, 9 Oct 2025 14:40:06 +0300 Subject: [PATCH 05/23] feat: private token definitions --- wallet/src/lib.rs | 116 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index b65fc8a..dd396fd 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -208,6 +208,122 @@ impl WalletCore { Ok(self.sequencer_client.send_tx_public(tx).await?) } + pub async fn send_new_token_definition_private_owned( + &self, + definition_addr: Address, + supply_addr: Address, + name: [u8; 6], + total_supply: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { + let Some((definition_keys, definition_acc)) = self + .storage + .user_data + .get_private_account(&definition_addr) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some((supply_keys, supply_acc)) = self + .storage + .user_data + .get_private_account(&supply_addr) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let definition_npk = definition_keys.nullifer_public_key; + let definition_ipk = definition_keys.incoming_viewing_public_key; + let supply_npk = supply_keys.nullifer_public_key.clone(); + let supply_ipk = supply_keys.incoming_viewing_public_key.clone(); + + let program = nssa::program::Program::token(); + + let definition_commitment = Commitment::new(&definition_npk, &definition_acc); + let supply_commitment = Commitment::new(&supply_npk, &supply_acc); + + let definition_pre = + AccountWithMetadata::new(definition_acc.clone(), true, &definition_npk); + let supply_pre = AccountWithMetadata::new(supply_acc.clone(), true, &supply_npk); + + let eph_holder_definition = EphemeralKeyHolder::new(&definition_npk); + let shared_secret_definition = + eph_holder_definition.calculate_shared_secret_sender(&definition_ipk); + + let eph_holder_supply = EphemeralKeyHolder::new(&supply_npk); + let shared_secret_supply = eph_holder_supply.calculate_shared_secret_sender(&supply_ipk); + + // Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)] + let mut instruction = [0; 23]; + instruction[1..17].copy_from_slice(&total_supply.to_le_bytes()); + instruction[17..].copy_from_slice(&name); + + let (output, proof) = circuit::execute_and_prove( + &[definition_pre, supply_pre], + &nssa::program::Program::serialize_instruction(instruction).unwrap(), + &[1, 1], + &produce_random_nonces(2), + &[ + (definition_npk.clone(), shared_secret_definition.clone()), + (supply_npk.clone(), shared_secret_supply.clone()), + ], + &[ + ( + definition_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(definition_commitment) + .await + .unwrap() + .unwrap(), + ), + ( + supply_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(supply_commitment) + .await + .unwrap() + .unwrap(), + ), + ], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![], + vec![], + vec![ + ( + definition_npk.clone(), + definition_ipk.clone(), + eph_holder_definition.generate_ephemeral_public_key(), + ), + ( + supply_npk.clone(), + supply_ipk.clone(), + eph_holder_supply.generate_ephemeral_public_key(), + ), + ], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_definition, shared_secret_supply], + )) + } + pub async fn send_transfer_token_transaction( &self, sender_address: Address, From 7213da587cbef880722e2c8ac3cfeee4d087601a Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Fri, 10 Oct 2025 11:12:47 +0300 Subject: [PATCH 06/23] fix: token creation test --- integration_tests/src/lib.rs | 130 +++++++++++++++++++++++++++++++++++ wallet/src/lib.rs | 86 +++++++++++++++++++++++ 2 files changed, 216 insertions(+) diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 65e8574..5e0c738 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -447,6 +447,136 @@ pub async fn test_success_token_program() { ); } +/// This test creates a new private token using the token program. After creating the token, the test executes a +/// private token transfer to a new account. All accounts are owned. +pub async fn test_success_token_program_private_owned() { + let wallet_config = fetch_config().unwrap(); + + // Create new account for the token definition + let SubcommandReturnValue::RegisterAccount { + addr: definition_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for the token supply holder + let SubcommandReturnValue::RegisterAccount { addr: supply_addr } = + wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for receiving a token transaction + let SubcommandReturnValue::RegisterAccount { + addr: recipient_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + + // Create new token + let command = Command::CreateNewTokenPrivateOwned { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }; + 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 seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + + // Check the status of the token definition account is the expected after the execution + let definition_acc = seq_client + .get_account(definition_addr.to_string()) + .await + .unwrap() + .account; + + assert_eq!(definition_acc.program_owner, Program::token().id()); + // The data of a token definition account has the following layout: + // [ 0x00 || name (6 bytes) || total supply (little endian 16 bytes) ] + assert_eq!( + definition_acc.data, + vec![ + 0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] + ); + + // Check the status of the token holding account with the total supply is the expected after the execution + let supply_acc = seq_client + .get_account(supply_addr.to_string()) + .await + .unwrap() + .account; + + // The account must be owned by the token program + assert_eq!(supply_acc.program_owner, Program::token().id()); + // The data of a token definition account has the following layout: + // [ 0x01 || corresponding_token_definition_id (32 bytes) || balance (little endian 16 bytes) ] + // First byte of the data equal to 1 means it's a token holding account + assert_eq!(supply_acc.data[0], 1); + // Bytes from 1 to 33 represent the id of the token this account is associated with. + // In this example, this is a token account of the newly created token, so it is expected + // to be equal to the address of the token definition account. + assert_eq!(&supply_acc.data[1..33], definition_addr.to_bytes()); + assert_eq!( + u128::from_le_bytes(supply_acc.data[33..].try_into().unwrap()), + 37 + ); + + // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` + let command = Command::TransferToken { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }; + 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; + + // Check the status of the account at `supply_addr` is the expected after the execution + let supply_acc = seq_client + .get_account(supply_addr.to_string()) + .await + .unwrap() + .account; + // The account must be owned by the token program + assert_eq!(supply_acc.program_owner, Program::token().id()); + // First byte equal to 1 means it's a token holding account + assert_eq!(supply_acc.data[0], 1); + // Bytes from 1 to 33 represent the id of the token this account is associated with. + assert_eq!(&supply_acc.data[1..33], definition_addr.to_bytes()); + assert_eq!( + u128::from_le_bytes(supply_acc.data[33..].try_into().unwrap()), + 30 + ); + + // Check the status of the account at `recipient_addr` is the expected after the execution + let recipient_acc = seq_client + .get_account(recipient_addr.to_string()) + .await + .unwrap() + .account; + + // The account must be owned by the token program + assert_eq!(recipient_acc.program_owner, Program::token().id()); + // First byte equal to 1 means it's a token holding account + assert_eq!(recipient_acc.data[0], 1); + // Bytes from 1 to 33 represent the id of the token this account is associated with. + assert_eq!(&recipient_acc.data[1..33], definition_addr.to_bytes()); + assert_eq!( + u128::from_le_bytes(recipient_acc.data[33..].try_into().unwrap()), + 7 + ); +} + pub async fn test_success_private_transfer_to_another_owned_account() { info!("test_success_private_transfer_to_another_owned_account"); let from: Address = ACC_SENDER_PRIVATE.parse().unwrap(); diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index dd396fd..2837395 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -585,6 +585,17 @@ pub enum Command { #[arg(long)] solution: u128, }, + //Create a new token using the token program + CreateNewTokenPrivateOwned { + #[arg(short, long)] + definition_addr: String, + #[arg(short, long)] + supply_addr: String, + #[arg(short, long)] + name: String, + #[arg(short, long)] + total_supply: u128, + }, } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -1025,6 +1036,81 @@ pub async fn execute_subcommand(command: Command) -> Result { + let name = name.as_bytes(); + if name.len() > 6 { + // TODO: return error + panic!("Name length mismatch"); + } + let mut name_bytes = [0; 6]; + name_bytes[..name.len()].copy_from_slice(name); + + let definition_addr: Address = definition_addr.parse().unwrap(); + let supply_addr: Address = supply_addr.parse().unwrap(); + + let (res, [secret_definition, secret_supply]) = wallet_core + .send_new_token_definition_private_owned( + definition_addr, + supply_addr, + name_bytes, + total_supply, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let definition_ebc = tx.message.encrypted_private_post_states[0].clone(); + let definition_comm = tx.message.new_commitments[0].clone(); + + let supply_ebc = tx.message.encrypted_private_post_states[1].clone(); + let supply_comm = tx.message.new_commitments[1].clone(); + + let res_acc_definition = nssa_core::EncryptionScheme::decrypt( + &definition_ebc.ciphertext, + &secret_definition, + &definition_comm, + 0, + ) + .unwrap(); + + let res_acc_supply = nssa_core::EncryptionScheme::decrypt( + &supply_ebc.ciphertext, + &secret_supply, + &supply_comm, + 1, + ) + .unwrap(); + + println!("Received new from acc {res_acc_definition:#?}"); + println!("Received new to acc {res_acc_supply:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(definition_addr, res_acc_definition); + wallet_core + .storage + .insert_private_account_data(supply_addr, res_acc_supply); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } + } Command::TransferToken { sender_addr, recipient_addr, From 69b610269b6b708ee8739accae5c5d6a6584f2a4 Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Thu, 9 Oct 2025 21:27:43 -0300 Subject: [PATCH 07/23] use risc0 method for image_id computaiton --- ci_scripts/test-ubuntu.sh | 10 +-- nssa/Cargo.toml | 4 +- nssa/build.rs | 77 +++++++++---------- nssa/src/lib.rs | 8 +- .../privacy_preserving_transaction/circuit.rs | 2 +- nssa/src/program.rs | 2 +- 6 files changed, 53 insertions(+), 50 deletions(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index 5c19b36..b563e6b 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -4,16 +4,16 @@ curl -L https://risczero.com/install | bash /home/runner/.risc0/bin/rzup install source env.sh -RISC0_DEV_MODE=1 cargo test --release +RISC0_DEV_MODE=1 cargo test --release --features no_docker cd integration_tests export NSSA_WALLET_HOME_DIR=$(pwd)/configs/debug/wallet/ export RUST_LOG=info -cargo run $(pwd)/configs/debug all +cargo run $(pwd)/configs/debug all --features no_docker echo "Try test valid proof at least once" -cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account +cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account --features no_docker echo "Continuing in dev mode" -RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all +RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all --features no_docker cd .. -cd nssa/program_methods/guest && cargo test --release +cd nssa/program_methods/guest && cargo test --release --features no_docker diff --git a/nssa/Cargo.toml b/nssa/Cargo.toml index f1a055e..a86bd98 100644 --- a/nssa/Cargo.toml +++ b/nssa/Cargo.toml @@ -7,7 +7,7 @@ edition = "2024" thiserror = "2.0.12" risc0-zkvm = { version = "3.0.3", features = ['std'] } nssa-core = { path = "core", features = ["host"] } -program-methods = { path = "program_methods" } +program-methods = { path = "program_methods", optional = true } serde = "1.0.219" sha2 = "0.10.9" secp256k1 = "0.31.1" @@ -17,6 +17,7 @@ hex = "0.4.3" [build-dependencies] risc0-build = "3.0.3" +risc0-binfmt = "3.0.2" [dev-dependencies] test-program-methods = { path = "test_program_methods" } @@ -24,3 +25,4 @@ hex-literal = "1.0.0" [features] default = [] +no_docker = ["program-methods"] diff --git a/nssa/build.rs b/nssa/build.rs index f04ba25..cc4608e 100644 --- a/nssa/build.rs +++ b/nssa/build.rs @@ -1,66 +1,63 @@ -use std::{env, fs, path::Path, process::Command}; -use risc0_build::a; - fn main() { - // 1️⃣ Crate root and OUT_DIR - let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); - let out_dir = env::var("OUT_DIR").unwrap(); + if cfg!(feature = "no_docker") { + println!("cargo:warning=NO_DOCKER feature enabled – deterministic build skipped"); + return; + } - // 2️⃣ Directory to write generated module - let mod_dir = Path::new(&out_dir).join("nssa_programs"); + build_deterministic().expect("Deterministic build failed"); +} + +fn build_deterministic() -> Result<(), Box> { + use std::{env, fs, path::PathBuf, process::Command}; + + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); + let out_dir = PathBuf::from(env::var("OUT_DIR")?); + let mod_dir = out_dir.join("program_methods"); let mod_file = mod_dir.join("mod.rs"); - println!("cargo:rerun-if-changed=program_methods/guest"); + println!("cargo:rerun-if-changed=program_methods/guest/src"); + println!("cargo:rerun-if-changed=program_methods/guest/Cargo.toml"); - // 3️⃣ Build the Risc0 guest program - let guest_manifest = Path::new(&manifest_dir) - .join("program_methods/guest/Cargo.toml"); + let guest_manifest = manifest_dir.join("program_methods/guest/Cargo.toml"); let status = Command::new("cargo") - .arg("risczero") - .arg("build") - .arg("--manifest-path") + .args(["risczero", "build", "--manifest-path"]) .arg(&guest_manifest) - .status() - .expect("failed to run risczero build"); - assert!(status.success(), "Risc0 deterministic build failed"); + .status()?; + if !status.success() { + return Err("Risc0 deterministic build failed".into()); + } - // 4️⃣ Target directory where the Risc0 build produces .bin files - let target_dir = Path::new(&manifest_dir) - .join("program_methods/guest/target/riscv32im-risc0-zkvm-elf/docker/"); + let target_dir = + manifest_dir.join("program_methods/guest/target/riscv32im-risc0-zkvm-elf/docker/"); - println!("cargo:warning=Looking for binaries in {}", target_dir.display()); - - // 5️⃣ Collect all .bin files - let bins = fs::read_dir(&target_dir) - .expect("failed to read external target dir") + let bins = fs::read_dir(&target_dir)? .filter_map(Result::ok) - .filter(|e| e.path().extension().map(|ext| ext == "bin").unwrap_or(false)) + .filter(|e| e.path().extension().is_some_and(|ext| ext == "bin")) .collect::>(); if bins.is_empty() { - panic!("No .bin files found in {:?}", target_dir); + return Err(format!("No .bin files found in {:?}", target_dir).into()); } - println!("cargo:warning=Found {} binaries:", bins.len()); - for b in &bins { - println!("cargo:warning= - {}", b.path().display()); - } - - // 6️⃣ Generate Rust module - fs::create_dir_all(&mod_dir).unwrap(); + fs::create_dir_all(&mod_dir)?; let mut src = String::new(); for entry in bins { let path = entry.path(); let name = path.file_stem().unwrap().to_string_lossy(); + let bytecode = fs::read(&path)?; + let image_id: [u32; 8] = risc0_binfmt::compute_image_id(&bytecode)?.into(); src.push_str(&format!( - "pub const {}_ELF: &[u8] = include_bytes!(r#\"{}\"#);\n", + "pub const {}_ELF: &[u8] = include_bytes!(r#\"{}\"#);\n\ + pub const {}_ID: [u32; 8] = {:?};\n", name.to_uppercase(), - path.display() + path.display(), + name.to_uppercase(), + image_id )); } - - fs::write(&mod_file, src).unwrap(); + fs::write(&mod_file, src)?; println!("cargo:warning=Generated module at {}", mod_file.display()); -} + Ok(()) +} diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index cdf45a2..5227875 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -1,7 +1,11 @@ -pub mod programs { - include!(concat!(env!("OUT_DIR"), "/nssa_programs/mod.rs")); +#[cfg(not(feature = "no_docker"))] +pub mod program_methods { + include!(concat!(env!("OUT_DIR"), "/program_methods/mod.rs")); } +#[cfg(feature = "no_docker")] +use program_methods; + pub mod encoding; pub mod error; mod merkle_tree; diff --git a/nssa/src/privacy_preserving_transaction/circuit.rs b/nssa/src/privacy_preserving_transaction/circuit.rs index 3a98723..9ce0610 100644 --- a/nssa/src/privacy_preserving_transaction/circuit.rs +++ b/nssa/src/privacy_preserving_transaction/circuit.rs @@ -8,7 +8,7 @@ use risc0_zkvm::{ExecutorEnv, InnerReceipt, Receipt, default_prover}; use crate::{error::NssaError, program::Program}; -use program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID}; +use crate::program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID}; /// Proof of the privacy preserving execution circuit #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/nssa/src/program.rs b/nssa/src/program.rs index fc13865..b229241 100644 --- a/nssa/src/program.rs +++ b/nssa/src/program.rs @@ -2,7 +2,7 @@ use nssa_core::{ account::{Account, AccountWithMetadata}, program::{InstructionData, ProgramId, ProgramOutput}, }; -use crate::programs::{ +use crate::program_methods::{ AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, TOKEN_ELF, TOKEN_ID, }; From f200f39779d57c568804628d57295df322a36a8c Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Fri, 10 Oct 2025 16:48:12 -0300 Subject: [PATCH 08/23] minor fix --- ci_scripts/test-ubuntu.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index b563e6b..65d219e 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -9,11 +9,11 @@ RISC0_DEV_MODE=1 cargo test --release --features no_docker cd integration_tests export NSSA_WALLET_HOME_DIR=$(pwd)/configs/debug/wallet/ export RUST_LOG=info -cargo run $(pwd)/configs/debug all --features no_docker +cargo run --features no_docker $(pwd)/configs/debug all echo "Try test valid proof at least once" -cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account --features no_docker +cargo run --features no_docker $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account echo "Continuing in dev mode" -RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all --features no_docker +RISC0_DEV_MODE=1 cargo run --features no_docker $(pwd)/configs/debug all cd .. cd nssa/program_methods/guest && cargo test --release --features no_docker From 766d72bd754bf11201dbfec3daa85154b25694ca Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Fri, 10 Oct 2025 17:44:42 -0300 Subject: [PATCH 09/23] remove get programs --- common/src/rpc_primitives/requests.rs | 12 +++++++++++ common/src/sequencer_client/mod.rs | 27 ++++++++++++++++++++++-- nssa/src/lib.rs | 1 + sequencer_rpc/src/process.rs | 30 +++++++++++++++++++++++---- wallet/src/lib.rs | 30 ++++++++++++++++++++++++++- 5 files changed, 93 insertions(+), 7 deletions(-) diff --git a/common/src/rpc_primitives/requests.rs b/common/src/rpc_primitives/requests.rs index 94c2ddc..91596e6 100644 --- a/common/src/rpc_primitives/requests.rs +++ b/common/src/rpc_primitives/requests.rs @@ -1,8 +1,11 @@ +use std::collections::HashMap; + use crate::parse_request; use super::errors::RpcParseError; use super::parser::RpcRequest; use super::parser::parse_params; +use nssa_core::program::ProgramId; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -58,6 +61,9 @@ pub struct GetProofForCommitmentRequest { pub commitment: nssa_core::Commitment, } +#[derive(Serialize, Deserialize, Debug)] +pub struct GetProgramIdsRequest {} + parse_request!(HelloRequest); parse_request!(RegisterAccountRequest); parse_request!(SendTxRequest); @@ -70,6 +76,7 @@ parse_request!(GetTransactionByHashRequest); parse_request!(GetAccountsNoncesRequest); parse_request!(GetProofForCommitmentRequest); parse_request!(GetAccountRequest); +parse_request!(GetProgramIdsRequest); #[derive(Serialize, Deserialize, Debug)] pub struct HelloResponse { @@ -126,3 +133,8 @@ pub struct GetAccountResponse { pub struct GetProofForCommitmentResponse { pub membership_proof: Option, } + +#[derive(Serialize, Deserialize, Debug)] +pub struct GetProgramIdsResponse { + pub program_ids: HashMap, +} diff --git a/common/src/sequencer_client/mod.rs b/common/src/sequencer_client/mod.rs index 1aec903..2d1bc4c 100644 --- a/common/src/sequencer_client/mod.rs +++ b/common/src/sequencer_client/mod.rs @@ -1,16 +1,19 @@ +use std::collections::HashMap; + use super::rpc_primitives::requests::{ GetAccountBalanceRequest, GetAccountBalanceResponse, GetBlockDataRequest, GetBlockDataResponse, GetGenesisIdRequest, GetGenesisIdResponse, GetInitialTestnetAccountsRequest, }; use anyhow::Result; use json::{SendTxRequest, SendTxResponse, SequencerRpcRequest, SequencerRpcResponse}; +use nssa_core::program::ProgramId; use reqwest::Client; use serde_json::Value; use crate::rpc_primitives::requests::{ GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse, - GetProofForCommitmentRequest, GetProofForCommitmentResponse, GetTransactionByHashRequest, - GetTransactionByHashResponse, + GetProgramIdsRequest, GetProgramIdsResponse, GetProofForCommitmentRequest, + GetProofForCommitmentResponse, GetTransactionByHashRequest, GetTransactionByHashResponse, }; use crate::sequencer_client::json::AccountInitialData; use crate::transaction::{EncodedTransaction, NSSATransaction}; @@ -237,4 +240,24 @@ impl SequencerClient { Ok(resp_deser) } + + // Get Ids of the programs used by the node + pub async fn get_program_ids( + &self, + ) -> Result, SequencerClientError> { + let acc_req = GetProgramIdsRequest {}; + + let req = serde_json::to_value(acc_req).unwrap(); + + let resp = self + .call_method_with_payload("get_program_ids", req) + .await + .unwrap(); + + let resp_deser = serde_json::from_value::(resp) + .unwrap() + .program_ids; + + Ok(resp_deser) + } } diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index 21defa9..296cb2a 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -7,6 +7,7 @@ pub mod public_transaction; mod signature; mod state; +pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID; pub use nssa_core::account::{Account, AccountId}; pub use nssa_core::address::Address; pub use privacy_preserving_transaction::{ diff --git a/sequencer_rpc/src/process.rs b/sequencer_rpc/src/process.rs index f376f94..d8c3c01 100644 --- a/sequencer_rpc/src/process.rs +++ b/sequencer_rpc/src/process.rs @@ -1,6 +1,8 @@ +use std::collections::HashMap; + use actix_web::Error as HttpError; use base64::{Engine, engine::general_purpose}; -use nssa; +use nssa::{self, program::Program}; use sequencer_core::config::AccountInitialData; use serde_json::Value; @@ -14,9 +16,9 @@ use common::{ requests::{ GetAccountBalanceRequest, GetAccountBalanceResponse, GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse, - GetInitialTestnetAccountsRequest, GetProofForCommitmentRequest, - GetProofForCommitmentResponse, GetTransactionByHashRequest, - GetTransactionByHashResponse, + GetInitialTestnetAccountsRequest, GetProgramIdsRequest, GetProgramIdsResponse, + GetProofForCommitmentRequest, GetProofForCommitmentResponse, + GetTransactionByHashRequest, GetTransactionByHashResponse, }, }, transaction::EncodedTransaction, @@ -40,6 +42,7 @@ pub const GET_TRANSACTION_BY_HASH: &str = "get_transaction_by_hash"; pub const GET_ACCOUNTS_NONCES: &str = "get_accounts_nonces"; pub const GET_ACCOUNT: &str = "get_account"; pub const GET_PROOF_FOR_COMMITMENT: &str = "get_proof_for_commitment"; +pub const GET_PROGRAM_IDS: &str = "get_program_ids"; pub const HELLO_FROM_SEQUENCER: &str = "HELLO_FROM_SEQUENCER"; @@ -267,6 +270,24 @@ impl JsonHandler { respond(helperstruct) } + async fn process_get_program_ids(&self, request: Request) -> Result { + let _get_proof_req = GetProgramIdsRequest::parse(Some(request.params))?; + + let mut program_ids = HashMap::new(); + program_ids.insert( + "authenticated_transfer".to_string(), + Program::authenticated_transfer_program().id(), + ); + program_ids.insert("token".to_string(), Program::token().id()); + program_ids.insert("pinata".to_string(), Program::pinata().id()); + program_ids.insert( + "privacy_preserving_circuit".to_string(), + nssa::PRIVACY_PRESERVING_CIRCUIT_ID, + ); + let helperstruct = GetProgramIdsResponse { program_ids }; + respond(helperstruct) + } + pub async fn process_request_internal(&self, request: Request) -> Result { match request.method.as_ref() { HELLO => self.process_temp_hello(request).await, @@ -280,6 +301,7 @@ impl JsonHandler { GET_ACCOUNT => self.process_get_account(request).await, GET_TRANSACTION_BY_HASH => self.process_get_transaction_by_hash(request).await, GET_PROOF_FOR_COMMITMENT => self.process_get_proof_by_commitment(request).await, + GET_PROGRAM_IDS => self.process_get_program_ids(request).await, _ => Err(RpcErr(RpcError::method_not_found(request.method))), } } diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 0e8b1cb..12505ff 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -11,7 +11,7 @@ use anyhow::Result; use chain_storage::WalletChainStore; use config::WalletConfig; use log::info; -use nssa::{Account, Address}; +use nssa::{program::Program, Account, Address}; use clap::{Parser, Subcommand}; use nssa_core::Commitment; @@ -377,6 +377,9 @@ pub enum Command { #[arg(long)] solution: u128, }, + // Check the wallet can connect to the node and builtin local programs + // match the remote versions + CheckHealth { } } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -845,6 +848,31 @@ pub async fn execute_subcommand(command: Command) -> Result { + let remote_program_ids = wallet_core.sequencer_client.get_program_ids().await.expect("Error fetching program ids"); + let Some(authenticated_transfer_id) = remote_program_ids.get("authenticated_transfer") else { + panic!("Missing authenticated transfer ID from remote"); + }; + if authenticated_transfer_id != &Program::authenticated_transfer_program().id() { + panic!("Local ID for authenticated transfer program is different from remote"); + } + let Some(token_id) = remote_program_ids.get("token") else { + panic!("Missing token program ID from remote"); + }; + if token_id != &Program::token().id() { + panic!("Local ID for token program is different from remote"); + } + let Some(circuit_id) = remote_program_ids.get("privacy_preserving_circuit") else { + panic!("Missing privacy preserving circuit ID from remote"); + }; + if circuit_id != &nssa::PRIVACY_PRESERVING_CIRCUIT_ID { + panic!("Local ID for privacy preserving circuit is different from remote"); + } + + println!("✅All looks good!"); + SubcommandReturnValue::Empty } }; From d7240e073a961889b47702df671f5f97a0c36797 Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Fri, 10 Oct 2025 17:51:22 -0300 Subject: [PATCH 10/23] fix integration tests --- ci_scripts/test-ubuntu.sh | 8 ++++---- integration_tests/Cargo.toml | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index 65d219e..d62cbb3 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -9,11 +9,11 @@ RISC0_DEV_MODE=1 cargo test --release --features no_docker cd integration_tests export NSSA_WALLET_HOME_DIR=$(pwd)/configs/debug/wallet/ export RUST_LOG=info -cargo run --features no_docker $(pwd)/configs/debug all +cargo run $(pwd)/configs/debug all echo "Try test valid proof at least once" -cargo run --features no_docker $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account +cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account echo "Continuing in dev mode" -RISC0_DEV_MODE=1 cargo run --features no_docker $(pwd)/configs/debug all +RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all cd .. -cd nssa/program_methods/guest && cargo test --release --features no_docker +cd nssa/program_methods/guest && cargo test --release diff --git a/integration_tests/Cargo.toml b/integration_tests/Cargo.toml index db2dfeb..f7bd131 100644 --- a/integration_tests/Cargo.toml +++ b/integration_tests/Cargo.toml @@ -36,3 +36,4 @@ path = "../common" [dependencies.nssa] path = "../nssa" +features = ["no_docker"] From 35806f103615c3a1c493c3909d45f3455c546503 Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Fri, 10 Oct 2025 18:24:11 -0300 Subject: [PATCH 11/23] fmt --- nssa/src/lib.rs | 2 +- wallet/src/lib.rs | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index 296cb2a..0dd4ff2 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -7,12 +7,12 @@ pub mod public_transaction; mod signature; mod state; -pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID; pub use nssa_core::account::{Account, AccountId}; pub use nssa_core::address::Address; pub use privacy_preserving_transaction::{ PrivacyPreservingTransaction, circuit::execute_and_prove, }; +pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID; pub use public_transaction::PublicTransaction; pub use signature::PrivateKey; pub use signature::PublicKey; diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 12505ff..e56aea6 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -11,7 +11,7 @@ use anyhow::Result; use chain_storage::WalletChainStore; use config::WalletConfig; use log::info; -use nssa::{program::Program, Account, Address}; +use nssa::{Account, Address, program::Program}; use clap::{Parser, Subcommand}; use nssa_core::Commitment; @@ -379,7 +379,7 @@ pub enum Command { }, // Check the wallet can connect to the node and builtin local programs // match the remote versions - CheckHealth { } + CheckHealth {}, } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -850,9 +850,14 @@ pub async fn execute_subcommand(command: Command) -> Result { - let remote_program_ids = wallet_core.sequencer_client.get_program_ids().await.expect("Error fetching program ids"); - let Some(authenticated_transfer_id) = remote_program_ids.get("authenticated_transfer") else { + Command::CheckHealth {} => { + let remote_program_ids = wallet_core + .sequencer_client + .get_program_ids() + .await + .expect("Error fetching program ids"); + let Some(authenticated_transfer_id) = remote_program_ids.get("authenticated_transfer") + else { panic!("Missing authenticated transfer ID from remote"); }; if authenticated_transfer_id != &Program::authenticated_transfer_program().id() { From a205cc150562a3237ee928a8c98e1b4717a5127d Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Mon, 13 Oct 2025 13:29:32 +0300 Subject: [PATCH 12/23] feat: private token program transfers --- integration_tests/src/lib.rs | 220 +++++++--- wallet/src/lib.rs | 527 ++++++++++------------- wallet/src/pinata_interactions.rs | 104 +++++ wallet/src/token_program_interactions.rs | 455 +++++++++++++++++++ 4 files changed, 962 insertions(+), 344 deletions(-) create mode 100644 wallet/src/pinata_interactions.rs create mode 100644 wallet/src/token_program_interactions.rs diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 5e0c738..3aa45f1 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -448,20 +448,20 @@ pub async fn test_success_token_program() { } /// This test creates a new private token using the token program. After creating the token, the test executes a -/// private token transfer to a new account. All accounts are owned. +/// private token transfer to a new account. All accounts are owned except definition. pub async fn test_success_token_program_private_owned() { let wallet_config = fetch_config().unwrap(); - // Create new account for the token definition + // Create new account for the token definition (public) let SubcommandReturnValue::RegisterAccount { addr: definition_addr, - } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + } = wallet::execute_subcommand(Command::RegisterAccountPublic {}) .await .unwrap() else { panic!("invalid subcommand return value"); }; - // Create new account for the token supply holder + // Create new account for the token supply holder (private) let SubcommandReturnValue::RegisterAccount { addr: supply_addr } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) .await @@ -486,7 +486,9 @@ pub async fn test_success_token_program_private_owned() { name: "A NAME".to_string(), total_supply: 37, }; + 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; @@ -509,72 +511,180 @@ pub async fn test_success_token_program_private_owned() { ] ); - // Check the status of the token holding account with the total supply is the expected after the execution - let supply_acc = seq_client - .get_account(supply_addr.to_string()) - .await - .unwrap() - .account; + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); - // The account must be owned by the token program - assert_eq!(supply_acc.program_owner, Program::token().id()); - // The data of a token definition account has the following layout: - // [ 0x01 || corresponding_token_definition_id (32 bytes) || balance (little endian 16 bytes) ] - // First byte of the data equal to 1 means it's a token holding account - assert_eq!(supply_acc.data[0], 1); - // Bytes from 1 to 33 represent the id of the token this account is associated with. - // In this example, this is a token account of the newly created token, so it is expected - // to be equal to the address of the token definition account. - assert_eq!(&supply_acc.data[1..33], definition_addr.to_bytes()); - assert_eq!( - u128::from_le_bytes(supply_acc.data[33..].try_into().unwrap()), - 37 - ); + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let command = Command::TransferToken { + let command = Command::TransferTokenPrivateOwnedNotInitialized { sender_addr: supply_addr.to_string(), recipient_addr: recipient_addr.to_string(), balance_to_move: 7, }; + 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; - // Check the status of the account at `supply_addr` is the expected after the execution - let supply_acc = seq_client - .get_account(supply_addr.to_string()) + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + let new_commitment2 = wallet_storage + .get_private_account_commitment(&recipient_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); + + // Transfer additional 7 tokens from `supply_acc` to the account at address `recipient_addr` + let command = Command::TransferTokenPrivateOwnedAlreadyInitialized { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }; + + 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 wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + let new_commitment2 = wallet_storage + .get_private_account_commitment(&recipient_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); +} + +/// This test creates a new private token using the token program. After creating the token, the test executes a +/// private token transfer to a new account. +pub async fn test_success_token_program_private_claiming_path() { + let wallet_config = fetch_config().unwrap(); + + // Create new account for the token definition (public) + let SubcommandReturnValue::RegisterAccount { + addr: definition_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPublic {}) .await .unwrap() - .account; - // The account must be owned by the token program - assert_eq!(supply_acc.program_owner, Program::token().id()); - // First byte equal to 1 means it's a token holding account - assert_eq!(supply_acc.data[0], 1); - // Bytes from 1 to 33 represent the id of the token this account is associated with. - assert_eq!(&supply_acc.data[1..33], definition_addr.to_bytes()); - assert_eq!( - u128::from_le_bytes(supply_acc.data[33..].try_into().unwrap()), - 30 - ); + else { + panic!("invalid subcommand return value"); + }; + // Create new account for the token supply holder (private) + let SubcommandReturnValue::RegisterAccount { addr: supply_addr } = + wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for receiving a token transaction + let SubcommandReturnValue::RegisterAccount { + addr: recipient_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; - // Check the status of the account at `recipient_addr` is the expected after the execution - let recipient_acc = seq_client - .get_account(recipient_addr.to_string()) + // Create new token + let command = Command::CreateNewTokenPrivateOwned { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }; + + 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 seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + + // Check the status of the token definition account is the expected after the execution + let definition_acc = seq_client + .get_account(definition_addr.to_string()) .await .unwrap() .account; - // The account must be owned by the token program - assert_eq!(recipient_acc.program_owner, Program::token().id()); - // First byte equal to 1 means it's a token holding account - assert_eq!(recipient_acc.data[0], 1); - // Bytes from 1 to 33 represent the id of the token this account is associated with. - assert_eq!(&recipient_acc.data[1..33], definition_addr.to_bytes()); + assert_eq!(definition_acc.program_owner, Program::token().id()); + // The data of a token definition account has the following layout: + // [ 0x00 || name (6 bytes) || total supply (little endian 16 bytes) ] assert_eq!( - u128::from_le_bytes(recipient_acc.data[33..].try_into().unwrap()), - 7 + definition_acc.data, + vec![ + 0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] ); + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + let (recipient_keys, _) = wallet_storage + .storage + .user_data + .get_private_account(&recipient_addr) + .unwrap(); + + // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` + let command = Command::TransferTokenPrivateForeign { + sender_addr: supply_addr.to_string(), + recipient_npk: hex::encode(recipient_keys.nullifer_public_key.0), + recipient_ipk: hex::encode(recipient_keys.incoming_viewing_public_key.0.clone()), + balance_to_move: 7, + }; + + let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = + wallet::execute_subcommand(command).await.unwrap() + else { + panic!("invalid subcommand return value"); + }; + + 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: recipient_addr.to_string(), + output_id: 1, + }; + + 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 new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + let new_commitment2 = wallet_storage + .get_private_account_commitment(&recipient_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); } pub async fn test_success_private_transfer_to_another_owned_account() { @@ -1063,6 +1173,12 @@ pub async fn main_tests_runner() -> Result<()> { "test_pinata_private_receiver" => { test_cleanup_wrap!(home_dir, test_pinata_private_receiver); } + "test_success_token_program_private_owned" => { + test_cleanup_wrap!(home_dir, test_success_token_program_private_owned); + } + "test_success_token_program_private_claiming_path" => { + test_cleanup_wrap!(home_dir, test_success_token_program_private_claiming_path); + } "all" => { test_cleanup_wrap!(home_dir, test_success_move_to_another_account); test_cleanup_wrap!(home_dir, test_success); @@ -1095,6 +1211,8 @@ pub async fn main_tests_runner() -> Result<()> { ); test_cleanup_wrap!(home_dir, test_pinata); 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); } "all_private" => { test_cleanup_wrap!( @@ -1122,6 +1240,8 @@ pub async fn main_tests_runner() -> Result<()> { test_success_private_transfer_to_another_owned_account_claiming_path ); 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); } _ => { anyhow::bail!("Unknown test name"); diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 2837395..2aca9fa 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -2,25 +2,23 @@ use std::{fs::File, io::Write, path::PathBuf, str::FromStr, sync::Arc}; use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use common::{ - ExecutionFailureKind, - sequencer_client::{SequencerClient, json::SendTxResponse}, + sequencer_client::SequencerClient, transaction::{EncodedTransaction, NSSATransaction}, }; use anyhow::Result; use chain_storage::WalletChainStore; use config::WalletConfig; -use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; use log::info; -use nssa::{Account, Address, privacy_preserving_transaction::circuit}; +use nssa::{Account, Address}; use clap::{Parser, Subcommand}; -use nssa_core::{Commitment, SharedSecretKey, account::AccountWithMetadata}; +use nssa_core::Commitment; use crate::{ helperfunctions::{ HumanReadableAccount, fetch_config, fetch_persistent_accounts, get_home, - produce_data_for_storage, produce_random_nonces, + produce_data_for_storage, }, poller::TxPoller, }; @@ -32,7 +30,9 @@ pub const HOME_DIR_ENV_VAR: &str = "NSSA_WALLET_HOME_DIR"; pub mod chain_storage; pub mod config; pub mod helperfunctions; +pub mod pinata_interactions; pub mod poller; +pub mod token_program_interactions; pub mod token_transfers; pub struct WalletCore { @@ -88,275 +88,6 @@ impl WalletCore { .generate_new_privacy_preserving_transaction_key_chain() } - pub async fn claim_pinata( - &self, - pinata_addr: Address, - winner_addr: Address, - solution: u128, - ) -> Result { - let addresses = vec![pinata_addr, winner_addr]; - let program_id = nssa::program::Program::pinata().id(); - let message = - nssa::public_transaction::Message::try_new(program_id, addresses, vec![], solution) - .unwrap(); - - let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); - let tx = nssa::PublicTransaction::new(message, witness_set); - - Ok(self.sequencer_client.send_tx_public(tx).await?) - } - - pub async fn claim_pinata_private_owned_account( - &self, - pinata_addr: Address, - winner_addr: Address, - solution: u128, - ) -> 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 winner_commitment = Commitment::new(&winner_npk, &winner_acc); - - let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); - let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &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, 1], - &produce_random_nonces(1), - &[(winner_npk.clone(), shared_secret_winner.clone())], - &[( - winner_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(winner_commitment) - .await - .unwrap() - .unwrap(), - )], - &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], - )) - } - - pub async fn send_new_token_definition( - &self, - definition_address: Address, - supply_address: Address, - name: [u8; 6], - total_supply: u128, - ) -> Result { - let addresses = vec![definition_address, supply_address]; - let program_id = nssa::program::Program::token().id(); - // Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)] - let mut instruction = [0; 23]; - instruction[1..17].copy_from_slice(&total_supply.to_le_bytes()); - instruction[17..].copy_from_slice(&name); - let message = - nssa::public_transaction::Message::try_new(program_id, addresses, vec![], instruction) - .unwrap(); - - let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); - - let tx = nssa::PublicTransaction::new(message, witness_set); - - Ok(self.sequencer_client.send_tx_public(tx).await?) - } - - pub async fn send_new_token_definition_private_owned( - &self, - definition_addr: Address, - supply_addr: Address, - name: [u8; 6], - total_supply: u128, - ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { - let Some((definition_keys, definition_acc)) = self - .storage - .user_data - .get_private_account(&definition_addr) - .cloned() - else { - return Err(ExecutionFailureKind::KeyNotFoundError); - }; - - let Some((supply_keys, supply_acc)) = self - .storage - .user_data - .get_private_account(&supply_addr) - .cloned() - else { - return Err(ExecutionFailureKind::KeyNotFoundError); - }; - - let definition_npk = definition_keys.nullifer_public_key; - let definition_ipk = definition_keys.incoming_viewing_public_key; - let supply_npk = supply_keys.nullifer_public_key.clone(); - let supply_ipk = supply_keys.incoming_viewing_public_key.clone(); - - let program = nssa::program::Program::token(); - - let definition_commitment = Commitment::new(&definition_npk, &definition_acc); - let supply_commitment = Commitment::new(&supply_npk, &supply_acc); - - let definition_pre = - AccountWithMetadata::new(definition_acc.clone(), true, &definition_npk); - let supply_pre = AccountWithMetadata::new(supply_acc.clone(), true, &supply_npk); - - let eph_holder_definition = EphemeralKeyHolder::new(&definition_npk); - let shared_secret_definition = - eph_holder_definition.calculate_shared_secret_sender(&definition_ipk); - - let eph_holder_supply = EphemeralKeyHolder::new(&supply_npk); - let shared_secret_supply = eph_holder_supply.calculate_shared_secret_sender(&supply_ipk); - - // Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)] - let mut instruction = [0; 23]; - instruction[1..17].copy_from_slice(&total_supply.to_le_bytes()); - instruction[17..].copy_from_slice(&name); - - let (output, proof) = circuit::execute_and_prove( - &[definition_pre, supply_pre], - &nssa::program::Program::serialize_instruction(instruction).unwrap(), - &[1, 1], - &produce_random_nonces(2), - &[ - (definition_npk.clone(), shared_secret_definition.clone()), - (supply_npk.clone(), shared_secret_supply.clone()), - ], - &[ - ( - definition_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(definition_commitment) - .await - .unwrap() - .unwrap(), - ), - ( - supply_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(supply_commitment) - .await - .unwrap() - .unwrap(), - ), - ], - &program, - ) - .unwrap(); - - let message = - nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( - vec![], - vec![], - vec![ - ( - definition_npk.clone(), - definition_ipk.clone(), - eph_holder_definition.generate_ephemeral_public_key(), - ), - ( - supply_npk.clone(), - supply_ipk.clone(), - eph_holder_supply.generate_ephemeral_public_key(), - ), - ], - output, - ) - .unwrap(); - - let witness_set = - nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( - &message, - proof, - &[], - ); - let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); - - Ok(( - self.sequencer_client.send_tx_private(tx).await?, - [shared_secret_definition, shared_secret_supply], - )) - } - - pub async fn send_transfer_token_transaction( - &self, - sender_address: Address, - recipient_address: Address, - amount: u128, - ) -> Result { - let addresses = vec![sender_address, recipient_address]; - let program_id = nssa::program::Program::token().id(); - // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. - let mut instruction = [0; 23]; - instruction[0] = 0x01; - instruction[1..17].copy_from_slice(&amount.to_le_bytes()); - let Ok(nonces) = self.get_accounts_nonces(vec![sender_address]).await else { - return Err(ExecutionFailureKind::SequencerError); - }; - let message = - nssa::public_transaction::Message::try_new(program_id, addresses, nonces, instruction) - .unwrap(); - - let Some(signing_key) = self - .storage - .user_data - .get_pub_account_signing_key(&sender_address) - else { - return Err(ExecutionFailureKind::KeyNotFoundError); - }; - let witness_set = - nssa::public_transaction::WitnessSet::for_message(&message, &[signing_key]); - - let tx = nssa::PublicTransaction::new(message, witness_set); - - Ok(self.sequencer_client.send_tx_public(tx).await?) - } ///Get account balance pub async fn get_account_balance(&self, acc: Address) -> Result { Ok(self @@ -596,6 +327,37 @@ pub enum Command { #[arg(short, long)] total_supply: u128, }, + //Transfer tokens using the token program + TransferTokenPrivateOwnedAlreadyInitialized { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Transfer tokens using the token program + TransferTokenPrivateOwnedNotInitialized { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Transfer tokens using the token program + TransferTokenPrivateForeign { + #[arg(short, long)] + sender_addr: String, + ///recipient_npk - valid 32 byte hex string + #[arg(long)] + recipient_npk: String, + ///recipient_ipk - valid 33 byte hex string + #[arg(long)] + recipient_ipk: String, + #[arg(short, long)] + balance_to_move: u128, + }, } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -1053,7 +815,7 @@ pub async fn execute_subcommand(command: Command) -> Result Result Result { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let (res, [secret_sender, secret_recipient]) = wallet_core + .send_transfer_token_transaction_private_owned_account_already_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); + let recipient_comm = tx.message.new_commitments[1].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( + &recipient_ebc.ciphertext, + &secret_recipient, + &recipient_comm, + 1, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + println!("Received new recipient acc {res_acc_recipient:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + wallet_core + .storage + .insert_private_account_data(recipient_addr, res_acc_recipient); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } + } + Command::TransferTokenPrivateOwnedNotInitialized { + sender_addr, + recipient_addr, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let (res, [secret_sender, secret_recipient]) = wallet_core + .send_transfer_token_transaction_private_owned_account_not_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); + let recipient_comm = tx.message.new_commitments[1].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( + &recipient_ebc.ciphertext, + &secret_recipient, + &recipient_comm, + 1, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + println!("Received new recipient acc {res_acc_recipient:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + wallet_core + .storage + .insert_private_account_data(recipient_addr, res_acc_recipient); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } + } + Command::TransferTokenPrivateForeign { + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_npk_res = hex::decode(recipient_npk)?; + let mut recipient_npk = [0; 32]; + recipient_npk.copy_from_slice(&recipient_npk_res); + let recipient_npk = nssa_core::NullifierPublicKey(recipient_npk); + + let recipient_ipk_res = hex::decode(recipient_ipk)?; + let mut recipient_ipk = [0u8; 33]; + recipient_ipk.copy_from_slice(&recipient_ipk_res); + let recipient_ipk = nssa_core::encryption::shared_key_derivation::Secp256k1Point( + recipient_ipk.to_vec(), + ); + + let (res, [secret_sender, _]) = wallet_core + .send_transfer_token_transaction_private_foreign_account( + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } + } Command::ClaimPinata { pinata_addr, winner_addr, diff --git a/wallet/src/pinata_interactions.rs b/wallet/src/pinata_interactions.rs new file mode 100644 index 0000000..43f2bf8 --- /dev/null +++ b/wallet/src/pinata_interactions.rs @@ -0,0 +1,104 @@ +use common::{ExecutionFailureKind, sequencer_client::json::SendTxResponse}; +use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; +use nssa::{Address, privacy_preserving_transaction::circuit}; +use nssa_core::{Commitment, SharedSecretKey, account::AccountWithMetadata}; + +use crate::{WalletCore, helperfunctions::produce_random_nonces}; + +impl WalletCore { + pub async fn claim_pinata( + &self, + pinata_addr: Address, + winner_addr: Address, + solution: u128, + ) -> Result { + let addresses = vec![pinata_addr, winner_addr]; + let program_id = nssa::program::Program::pinata().id(); + let message = + nssa::public_transaction::Message::try_new(program_id, addresses, vec![], solution) + .unwrap(); + + let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); + let tx = nssa::PublicTransaction::new(message, witness_set); + + Ok(self.sequencer_client.send_tx_public(tx).await?) + } + + pub async fn claim_pinata_private_owned_account( + &self, + pinata_addr: Address, + winner_addr: Address, + solution: u128, + ) -> 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 winner_commitment = Commitment::new(&winner_npk, &winner_acc); + + let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); + let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &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, 1], + &produce_random_nonces(1), + &[(winner_npk.clone(), shared_secret_winner.clone())], + &[( + winner_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(winner_commitment) + .await + .unwrap() + .unwrap(), + )], + &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], + )) + } +} diff --git a/wallet/src/token_program_interactions.rs b/wallet/src/token_program_interactions.rs new file mode 100644 index 0000000..74c341e --- /dev/null +++ b/wallet/src/token_program_interactions.rs @@ -0,0 +1,455 @@ +use common::{ExecutionFailureKind, sequencer_client::json::SendTxResponse}; +use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; +use nssa::{Address, privacy_preserving_transaction::circuit, program::Program}; +use nssa_core::{ + Commitment, NullifierPublicKey, SharedSecretKey, account::AccountWithMetadata, + encryption::IncomingViewingPublicKey, +}; + +use crate::{WalletCore, helperfunctions::produce_random_nonces}; + +impl WalletCore { + pub async fn send_new_token_definition( + &self, + definition_address: Address, + supply_address: Address, + name: [u8; 6], + total_supply: u128, + ) -> Result { + let addresses = vec![definition_address, supply_address]; + let program_id = nssa::program::Program::token().id(); + // Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)] + let mut instruction = [0; 23]; + instruction[1..17].copy_from_slice(&total_supply.to_le_bytes()); + instruction[17..].copy_from_slice(&name); + let message = + nssa::public_transaction::Message::try_new(program_id, addresses, vec![], instruction) + .unwrap(); + + let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); + + let tx = nssa::PublicTransaction::new(message, witness_set); + + Ok(self.sequencer_client.send_tx_public(tx).await?) + } + + pub async fn send_new_token_definition_private_owned( + &self, + definition_addr: Address, + supply_addr: Address, + name: [u8; 6], + total_supply: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { + let Some((supply_keys, supply_acc)) = self + .storage + .user_data + .get_private_account(&supply_addr) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + //It makes more sence to have definition acc as public + let definition_acc = self.get_account_public(definition_addr).await.unwrap(); + + let supply_npk = supply_keys.nullifer_public_key; + let supply_ipk = supply_keys.incoming_viewing_public_key; + + let program = nssa::program::Program::token(); + + let definition_pre = + AccountWithMetadata::new(definition_acc.clone(), false, definition_addr); + let supply_pre = AccountWithMetadata::new(supply_acc.clone(), false, &supply_npk); + + let eph_holder_supply = EphemeralKeyHolder::new(&supply_npk); + let shared_secret_supply = eph_holder_supply.calculate_shared_secret_sender(&supply_ipk); + + // Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)] + let mut instruction = [0; 23]; + instruction[1..17].copy_from_slice(&total_supply.to_le_bytes()); + instruction[17..].copy_from_slice(&name); + + let (output, proof) = circuit::execute_and_prove( + &[definition_pre, supply_pre], + &nssa::program::Program::serialize_instruction(instruction).unwrap(), + &[0, 2], + &produce_random_nonces(1), + &[(supply_npk.clone(), shared_secret_supply.clone())], + &[], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![definition_addr], + vec![], + vec![( + supply_npk.clone(), + supply_ipk.clone(), + eph_holder_supply.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_supply], + )) + } + + pub async fn send_transfer_token_transaction( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + ) -> Result { + let addresses = vec![sender_address, recipient_address]; + let program_id = nssa::program::Program::token().id(); + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + let Ok(nonces) = self.get_accounts_nonces(vec![sender_address]).await else { + return Err(ExecutionFailureKind::SequencerError); + }; + let message = + nssa::public_transaction::Message::try_new(program_id, addresses, nonces, instruction) + .unwrap(); + + let Some(signing_key) = self + .storage + .user_data + .get_pub_account_signing_key(&sender_address) + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + let witness_set = + nssa::public_transaction::WitnessSet::for_message(&message, &[signing_key]); + + let tx = nssa::PublicTransaction::new(message, witness_set); + + Ok(self.sequencer_client.send_tx_public(tx).await?) + } + + pub async fn send_transfer_token_transaction_private_owned_account_already_initialized( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { + let Some((sender_keys, sender_acc)) = self + .storage + .user_data + .get_private_account(&sender_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some((recipient_keys, recipient_acc)) = self + .storage + .user_data + .get_private_account(&recipient_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let sender_npk = sender_keys.nullifer_public_key; + let sender_ipk = sender_keys.incoming_viewing_public_key; + let recipient_npk = recipient_keys.nullifer_public_key.clone(); + let recipient_ipk = recipient_keys.incoming_viewing_public_key.clone(); + + let program = Program::token(); + + let sender_commitment = Commitment::new(&sender_npk, &sender_acc); + let receiver_commitment = Commitment::new(&recipient_npk, &recipient_acc); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, &sender_npk); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), true, &recipient_npk); + + let eph_holder_sender = EphemeralKeyHolder::new(&sender_npk); + let shared_secret_sender = eph_holder_sender.calculate_shared_secret_sender(&sender_ipk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[1, 1], + &produce_random_nonces(2), + &[ + (sender_npk.clone(), shared_secret_sender.clone()), + (recipient_npk.clone(), shared_secret_recipient.clone()), + ], + &[ + ( + sender_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(sender_commitment) + .await + .unwrap() + .unwrap(), + ), + ( + recipient_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(receiver_commitment) + .await + .unwrap() + .unwrap(), + ), + ], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![], + vec![], + vec![ + ( + sender_npk.clone(), + sender_ipk.clone(), + eph_holder_sender.generate_ephemeral_public_key(), + ), + ( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + ), + ], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_sender, shared_secret_recipient], + )) + } + + pub async fn send_transfer_token_transaction_private_owned_account_not_initialized( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { + let Some((sender_keys, sender_acc)) = self + .storage + .user_data + .get_private_account(&sender_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some((recipient_keys, recipient_acc)) = self + .storage + .user_data + .get_private_account(&recipient_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let sender_npk = sender_keys.nullifer_public_key; + let sender_ipk = sender_keys.incoming_viewing_public_key; + let recipient_npk = recipient_keys.nullifer_public_key.clone(); + let recipient_ipk = recipient_keys.incoming_viewing_public_key.clone(); + + let program = Program::token(); + + let sender_commitment = Commitment::new(&sender_npk, &sender_acc); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, &sender_npk); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), false, &recipient_npk); + + let eph_holder_sender = EphemeralKeyHolder::new(&sender_npk); + let shared_secret_sender = eph_holder_sender.calculate_shared_secret_sender(&sender_ipk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[1, 2], + &produce_random_nonces(2), + &[ + (sender_npk.clone(), shared_secret_sender.clone()), + (recipient_npk.clone(), shared_secret_recipient.clone()), + ], + &[( + sender_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(sender_commitment) + .await + .unwrap() + .unwrap(), + )], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![], + vec![], + vec![ + ( + sender_npk.clone(), + sender_ipk.clone(), + eph_holder_sender.generate_ephemeral_public_key(), + ), + ( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + ), + ], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_sender, shared_secret_recipient], + )) + } + + pub async fn send_transfer_token_transaction_private_foreign_account( + &self, + sender_address: Address, + recipient_npk: NullifierPublicKey, + recipient_ipk: IncomingViewingPublicKey, + amount: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { + let Some((sender_keys, sender_acc)) = self + .storage + .user_data + .get_private_account(&sender_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let recipient_acc = nssa_core::account::Account::default(); + + let sender_npk = sender_keys.nullifer_public_key; + let sender_ipk = sender_keys.incoming_viewing_public_key; + + let program = Program::token(); + + let sender_commitment = Commitment::new(&sender_npk, &sender_acc); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, &sender_npk); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), false, &recipient_npk); + + let eph_holder_sender = EphemeralKeyHolder::new(&sender_npk); + let shared_secret_sender = eph_holder_sender.calculate_shared_secret_sender(&sender_ipk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[1, 2], + &produce_random_nonces(2), + &[ + (sender_npk.clone(), shared_secret_sender.clone()), + (recipient_npk.clone(), shared_secret_recipient.clone()), + ], + &[( + sender_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(sender_commitment) + .await + .unwrap() + .unwrap(), + )], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![], + vec![], + vec![ + ( + sender_npk.clone(), + sender_ipk.clone(), + eph_holder_sender.generate_ephemeral_public_key(), + ), + ( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + ), + ], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_sender, shared_secret_recipient], + )) + } +} From 577171bc5c77fee6edc98786690e41c558a87565 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Mon, 13 Oct 2025 16:12:43 +0300 Subject: [PATCH 13/23] fix: try generic array dep --- common/Cargo.toml | 4 ++++ common/src/transaction.rs | 6 ++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/common/Cargo.toml b/common/Cargo.toml index d235246..d0d145f 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -19,5 +19,9 @@ hex.workspace = true nssa-core = { path = "../nssa/core", features = ["host"] } borsh.workspace = true +[dependencies.generic-array] +version = "1.3.3" +features = ["zeroize"] + [dependencies.nssa] path = "../nssa" diff --git a/common/src/transaction.rs b/common/src/transaction.rs index 3a2bda1..baa57fe 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -1,14 +1,12 @@ use borsh::{BorshDeserialize, BorshSerialize}; +use generic_array::GenericArray; use k256::ecdsa::{Signature, SigningKey, VerifyingKey}; use log::info; use serde::{Deserialize, Serialize}; use sha2::{Digest, digest::FixedOutput}; -use elliptic_curve::{ - consts::{B0, B1}, - generic_array::GenericArray, -}; +use sha2::digest::typenum::{B0, B1}; use sha2::digest::typenum::{UInt, UTerm}; #[derive(Debug, Clone, PartialEq, Eq)] From 898c5e9bcfc9a45d0235d0665e1a6459373697c6 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Mon, 13 Oct 2025 17:25:36 +0300 Subject: [PATCH 14/23] fix: structured subcommand approach --- integration_tests/src/lib.rs | 43 ++-- wallet/src/cli/mod.rs | 10 + wallet/src/cli/token_program.rs | 372 ++++++++++++++++++++++++++++++++ wallet/src/lib.rs | 360 +------------------------------ 4 files changed, 420 insertions(+), 365 deletions(-) create mode 100644 wallet/src/cli/mod.rs create mode 100644 wallet/src/cli/token_program.rs diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 3aa45f1..bcb877b 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -19,6 +19,7 @@ use tempfile::TempDir; use tokio::task::JoinHandle; use wallet::{ Command, SubcommandReturnValue, WalletCore, + cli::token_program::TokenProgramSubcommand, config::PersistentAccountData, helperfunctions::{fetch_config, fetch_persistent_accounts}, }; @@ -350,13 +351,15 @@ pub async fn test_success_token_program() { .expect("Failed to produce new account, not present in persistent accounts"); // Create new token - let command = Command::CreateNewToken { + let subcommand = TokenProgramSubcommand::CreateNewToken { definition_addr: definition_addr.to_string(), supply_addr: supply_addr.to_string(), name: "A NAME".to_string(), total_supply: 37, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -402,12 +405,14 @@ pub async fn test_success_token_program() { ); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let command = Command::TransferToken { + let subcommand = TokenProgramSubcommand::TransferToken { sender_addr: supply_addr.to_string(), recipient_addr: recipient_addr.to_string(), balance_to_move: 7, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -480,14 +485,16 @@ pub async fn test_success_token_program_private_owned() { }; // Create new token - let command = Command::CreateNewTokenPrivateOwned { + let subcommand = TokenProgramSubcommand::CreateNewTokenPrivateOwned { definition_addr: definition_addr.to_string(), supply_addr: supply_addr.to_string(), name: "A NAME".to_string(), total_supply: 37, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -520,13 +527,15 @@ pub async fn test_success_token_program_private_owned() { assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let command = Command::TransferTokenPrivateOwnedNotInitialized { + let subcommand = TokenProgramSubcommand::TransferTokenPrivateOwnedNotInitialized { sender_addr: supply_addr.to_string(), recipient_addr: recipient_addr.to_string(), balance_to_move: 7, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -545,13 +554,15 @@ pub async fn test_success_token_program_private_owned() { assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); // Transfer additional 7 tokens from `supply_acc` to the account at address `recipient_addr` - let command = Command::TransferTokenPrivateOwnedAlreadyInitialized { + let subcommand = TokenProgramSubcommand::TransferTokenPrivateOwnedAlreadyInitialized { sender_addr: supply_addr.to_string(), recipient_addr: recipient_addr.to_string(), balance_to_move: 7, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -603,14 +614,16 @@ pub async fn test_success_token_program_private_claiming_path() { }; // Create new token - let command = Command::CreateNewTokenPrivateOwned { + let subcommand = TokenProgramSubcommand::CreateNewTokenPrivateOwned { definition_addr: definition_addr.to_string(), supply_addr: supply_addr.to_string(), name: "A NAME".to_string(), total_supply: 37, }; - wallet::execute_subcommand(command).await.unwrap(); + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); info!("Waiting for next block creation"); tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; @@ -649,7 +662,7 @@ pub async fn test_success_token_program_private_claiming_path() { .unwrap(); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let command = Command::TransferTokenPrivateForeign { + let subcommand = TokenProgramSubcommand::TransferTokenPrivateForeign { sender_addr: supply_addr.to_string(), recipient_npk: hex::encode(recipient_keys.nullifer_public_key.0), recipient_ipk: hex::encode(recipient_keys.incoming_viewing_public_key.0.clone()), @@ -657,7 +670,9 @@ pub async fn test_success_token_program_private_claiming_path() { }; let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = - wallet::execute_subcommand(command).await.unwrap() + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap() else { panic!("invalid subcommand return value"); }; diff --git a/wallet/src/cli/mod.rs b/wallet/src/cli/mod.rs new file mode 100644 index 0000000..5b277e0 --- /dev/null +++ b/wallet/src/cli/mod.rs @@ -0,0 +1,10 @@ +use anyhow::Result; + +use crate::{SubcommandReturnValue, WalletCore}; + +pub mod token_program; + +pub(crate) trait WalletSubcommand { + async fn handle_subcommand(self, wallet_core: &mut WalletCore) + -> Result; +} diff --git a/wallet/src/cli/token_program.rs b/wallet/src/cli/token_program.rs new file mode 100644 index 0000000..d3b42ea --- /dev/null +++ b/wallet/src/cli/token_program.rs @@ -0,0 +1,372 @@ +use anyhow::Result; +use clap::Subcommand; +use common::transaction::NSSATransaction; +use nssa::Address; + +use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand}; + +///Represents CLI subcommand for a wallet working with token_program +#[derive(Subcommand, Debug, Clone)] +pub enum TokenProgramSubcommand { + //Create a new token using the token program + CreateNewToken { + #[arg(short, long)] + definition_addr: String, + #[arg(short, long)] + supply_addr: String, + #[arg(short, long)] + name: String, + #[arg(short, long)] + total_supply: u128, + }, + //Transfer tokens using the token program + TransferToken { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Create a new token using the token program + CreateNewTokenPrivateOwned { + #[arg(short, long)] + definition_addr: String, + #[arg(short, long)] + supply_addr: String, + #[arg(short, long)] + name: String, + #[arg(short, long)] + total_supply: u128, + }, + //Transfer tokens using the token program + TransferTokenPrivateOwnedAlreadyInitialized { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Transfer tokens using the token program + TransferTokenPrivateOwnedNotInitialized { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Transfer tokens using the token program + TransferTokenPrivateForeign { + #[arg(short, long)] + sender_addr: String, + ///recipient_npk - valid 32 byte hex string + #[arg(long)] + recipient_npk: String, + ///recipient_ipk - valid 33 byte hex string + #[arg(long)] + recipient_ipk: String, + #[arg(short, long)] + balance_to_move: u128, + }, +} + +impl WalletSubcommand for TokenProgramSubcommand { + async fn handle_subcommand( + self, + wallet_core: &mut WalletCore, + ) -> Result { + match self { + TokenProgramSubcommand::CreateNewToken { + definition_addr, + supply_addr, + name, + total_supply, + } => { + let name = name.as_bytes(); + if name.len() > 6 { + // TODO: return error + panic!(); + } + let mut name_bytes = [0; 6]; + name_bytes[..name.len()].copy_from_slice(name); + wallet_core + .send_new_token_definition( + definition_addr.parse().unwrap(), + supply_addr.parse().unwrap(), + name_bytes, + total_supply, + ) + .await?; + Ok(SubcommandReturnValue::Empty) + } + TokenProgramSubcommand::CreateNewTokenPrivateOwned { + definition_addr, + supply_addr, + name, + total_supply, + } => { + let name = name.as_bytes(); + if name.len() > 6 { + // TODO: return error + panic!("Name length mismatch"); + } + let mut name_bytes = [0; 6]; + name_bytes[..name.len()].copy_from_slice(name); + + let definition_addr: Address = definition_addr.parse().unwrap(); + let supply_addr: Address = supply_addr.parse().unwrap(); + + let (res, [secret_supply]) = wallet_core + .send_new_token_definition_private_owned( + definition_addr, + supply_addr, + name_bytes, + total_supply, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let supply_ebc = tx.message.encrypted_private_post_states[0].clone(); + let supply_comm = tx.message.new_commitments[0].clone(); + + let res_acc_supply = nssa_core::EncryptionScheme::decrypt( + &supply_ebc.ciphertext, + &secret_supply, + &supply_comm, + 0, + ) + .unwrap(); + + println!("Received new to acc {res_acc_supply:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(supply_addr, res_acc_supply); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + TokenProgramSubcommand::TransferToken { + sender_addr, + recipient_addr, + balance_to_move, + } => { + wallet_core + .send_transfer_token_transaction( + sender_addr.parse().unwrap(), + recipient_addr.parse().unwrap(), + balance_to_move, + ) + .await?; + Ok(SubcommandReturnValue::Empty) + } + TokenProgramSubcommand::TransferTokenPrivateOwnedAlreadyInitialized { + sender_addr, + recipient_addr, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let (res, [secret_sender, secret_recipient]) = wallet_core + .send_transfer_token_transaction_private_owned_account_already_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); + let recipient_comm = tx.message.new_commitments[1].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( + &recipient_ebc.ciphertext, + &secret_recipient, + &recipient_comm, + 1, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + println!("Received new recipient acc {res_acc_recipient:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + wallet_core + .storage + .insert_private_account_data(recipient_addr, res_acc_recipient); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + TokenProgramSubcommand::TransferTokenPrivateOwnedNotInitialized { + sender_addr, + recipient_addr, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let (res, [secret_sender, secret_recipient]) = wallet_core + .send_transfer_token_transaction_private_owned_account_not_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); + let recipient_comm = tx.message.new_commitments[1].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( + &recipient_ebc.ciphertext, + &secret_recipient, + &recipient_comm, + 1, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + println!("Received new recipient acc {res_acc_recipient:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + wallet_core + .storage + .insert_private_account_data(recipient_addr, res_acc_recipient); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + TokenProgramSubcommand::TransferTokenPrivateForeign { + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_npk_res = hex::decode(recipient_npk)?; + let mut recipient_npk = [0; 32]; + recipient_npk.copy_from_slice(&recipient_npk_res); + let recipient_npk = nssa_core::NullifierPublicKey(recipient_npk); + + let recipient_ipk_res = hex::decode(recipient_ipk)?; + let mut recipient_ipk = [0u8; 33]; + recipient_ipk.copy_from_slice(&recipient_ipk_res); + let recipient_ipk = nssa_core::encryption::shared_key_derivation::Secp256k1Point( + recipient_ipk.to_vec(), + ); + + let (res, [secret_sender, _]) = wallet_core + .send_transfer_token_transaction_private_foreign_account( + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); + let sender_comm = tx.message.new_commitments[0].clone(); + + let res_acc_sender = nssa_core::EncryptionScheme::decrypt( + &sender_ebc.ciphertext, + &secret_sender, + &sender_comm, + 0, + ) + .unwrap(); + + println!("Received new sender acc {res_acc_sender:#?}"); + + println!("Transaction data is {:?}", tx.message); + + wallet_core + .storage + .insert_private_account_data(sender_addr, res_acc_sender); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + } + } +} diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 2aca9fa..cdd98e6 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -15,7 +15,9 @@ use nssa::{Account, Address}; use clap::{Parser, Subcommand}; use nssa_core::Commitment; +use crate::cli::WalletSubcommand; use crate::{ + cli::token_program::TokenProgramSubcommand, helperfunctions::{ HumanReadableAccount, fetch_config, fetch_persistent_accounts, get_home, produce_data_for_storage, @@ -28,6 +30,7 @@ use crate::{ pub const HOME_DIR_ENV_VAR: &str = "NSSA_WALLET_HOME_DIR"; pub mod chain_storage; +pub mod cli; pub mod config; pub mod helperfunctions; pub mod pinata_interactions; @@ -270,26 +273,6 @@ pub enum Command { #[arg(short, long)] addr: String, }, - //Create a new token using the token program - CreateNewToken { - #[arg(short, long)] - definition_addr: String, - #[arg(short, long)] - supply_addr: String, - #[arg(short, long)] - name: String, - #[arg(short, long)] - total_supply: u128, - }, - //Transfer tokens using the token program - TransferToken { - #[arg(short, long)] - sender_addr: String, - #[arg(short, long)] - recipient_addr: String, - #[arg(short, long)] - balance_to_move: u128, - }, // TODO: Testnet only. Refactor to prevent compilation on mainnet. // Claim piñata prize ClaimPinata { @@ -316,48 +299,9 @@ pub enum Command { #[arg(long)] solution: u128, }, - //Create a new token using the token program - CreateNewTokenPrivateOwned { - #[arg(short, long)] - definition_addr: String, - #[arg(short, long)] - supply_addr: String, - #[arg(short, long)] - name: String, - #[arg(short, long)] - total_supply: u128, - }, - //Transfer tokens using the token program - TransferTokenPrivateOwnedAlreadyInitialized { - #[arg(short, long)] - sender_addr: String, - #[arg(short, long)] - recipient_addr: String, - #[arg(short, long)] - balance_to_move: u128, - }, - //Transfer tokens using the token program - TransferTokenPrivateOwnedNotInitialized { - #[arg(short, long)] - sender_addr: String, - #[arg(short, long)] - recipient_addr: String, - #[arg(short, long)] - balance_to_move: u128, - }, - //Transfer tokens using the token program - TransferTokenPrivateForeign { - #[arg(short, long)] - sender_addr: String, - ///recipient_npk - valid 32 byte hex string - #[arg(long)] - recipient_npk: String, - ///recipient_ipk - valid 33 byte hex string - #[arg(long)] - recipient_ipk: String, - #[arg(short, long)] - balance_to_move: u128, - }, + ///Test command + #[command(subcommand)] + TokenProgram(TokenProgramSubcommand), } ///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config @@ -775,295 +719,6 @@ pub async fn execute_subcommand(command: Command) -> Result { - let name = name.as_bytes(); - if name.len() > 6 { - // TODO: return error - panic!(); - } - let mut name_bytes = [0; 6]; - name_bytes[..name.len()].copy_from_slice(name); - wallet_core - .send_new_token_definition( - definition_addr.parse().unwrap(), - supply_addr.parse().unwrap(), - name_bytes, - total_supply, - ) - .await?; - SubcommandReturnValue::Empty - } - Command::CreateNewTokenPrivateOwned { - definition_addr, - supply_addr, - name, - total_supply, - } => { - let name = name.as_bytes(); - if name.len() > 6 { - // TODO: return error - panic!("Name length mismatch"); - } - let mut name_bytes = [0; 6]; - name_bytes[..name.len()].copy_from_slice(name); - - let definition_addr: Address = definition_addr.parse().unwrap(); - let supply_addr: Address = supply_addr.parse().unwrap(); - - let (res, [secret_supply]) = wallet_core - .send_new_token_definition_private_owned( - definition_addr, - supply_addr, - name_bytes, - total_supply, - ) - .await?; - - println!("Results of tx send is {res:#?}"); - - let tx_hash = res.tx_hash; - let transfer_tx = wallet_core - .poll_native_token_transfer(tx_hash.clone()) - .await?; - - if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let supply_ebc = tx.message.encrypted_private_post_states[0].clone(); - let supply_comm = tx.message.new_commitments[0].clone(); - - let res_acc_supply = nssa_core::EncryptionScheme::decrypt( - &supply_ebc.ciphertext, - &secret_supply, - &supply_comm, - 0, - ) - .unwrap(); - - println!("Received new to acc {res_acc_supply:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(supply_addr, res_acc_supply); - } - - let path = wallet_core.store_persistent_accounts()?; - - println!("Stored persistent accounts at {path:#?}"); - - SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } - } - Command::TransferToken { - sender_addr, - recipient_addr, - balance_to_move, - } => { - wallet_core - .send_transfer_token_transaction( - sender_addr.parse().unwrap(), - recipient_addr.parse().unwrap(), - balance_to_move, - ) - .await?; - SubcommandReturnValue::Empty - } - Command::TransferTokenPrivateOwnedAlreadyInitialized { - sender_addr, - recipient_addr, - balance_to_move, - } => { - let sender_addr: Address = sender_addr.parse().unwrap(); - let recipient_addr: Address = recipient_addr.parse().unwrap(); - - let (res, [secret_sender, secret_recipient]) = wallet_core - .send_transfer_token_transaction_private_owned_account_already_initialized( - sender_addr, - recipient_addr, - balance_to_move, - ) - .await?; - - println!("Results of tx send is {res:#?}"); - - let tx_hash = res.tx_hash; - let transfer_tx = wallet_core - .poll_native_token_transfer(tx_hash.clone()) - .await?; - - if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); - - let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); - let recipient_comm = tx.message.new_commitments[1].clone(); - - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( - &recipient_ebc.ciphertext, - &secret_recipient, - &recipient_comm, - 1, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - println!("Received new recipient acc {res_acc_recipient:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); - wallet_core - .storage - .insert_private_account_data(recipient_addr, res_acc_recipient); - } - - let path = wallet_core.store_persistent_accounts()?; - - println!("Stored persistent accounts at {path:#?}"); - - SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } - } - Command::TransferTokenPrivateOwnedNotInitialized { - sender_addr, - recipient_addr, - balance_to_move, - } => { - let sender_addr: Address = sender_addr.parse().unwrap(); - let recipient_addr: Address = recipient_addr.parse().unwrap(); - - let (res, [secret_sender, secret_recipient]) = wallet_core - .send_transfer_token_transaction_private_owned_account_not_initialized( - sender_addr, - recipient_addr, - balance_to_move, - ) - .await?; - - println!("Results of tx send is {res:#?}"); - - let tx_hash = res.tx_hash; - let transfer_tx = wallet_core - .poll_native_token_transfer(tx_hash.clone()) - .await?; - - if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); - - let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); - let recipient_comm = tx.message.new_commitments[1].clone(); - - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( - &recipient_ebc.ciphertext, - &secret_recipient, - &recipient_comm, - 1, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - println!("Received new recipient acc {res_acc_recipient:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); - wallet_core - .storage - .insert_private_account_data(recipient_addr, res_acc_recipient); - } - - let path = wallet_core.store_persistent_accounts()?; - - println!("Stored persistent accounts at {path:#?}"); - - SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } - } - Command::TransferTokenPrivateForeign { - sender_addr, - recipient_npk, - recipient_ipk, - balance_to_move, - } => { - let sender_addr: Address = sender_addr.parse().unwrap(); - let recipient_npk_res = hex::decode(recipient_npk)?; - let mut recipient_npk = [0; 32]; - recipient_npk.copy_from_slice(&recipient_npk_res); - let recipient_npk = nssa_core::NullifierPublicKey(recipient_npk); - - let recipient_ipk_res = hex::decode(recipient_ipk)?; - let mut recipient_ipk = [0u8; 33]; - recipient_ipk.copy_from_slice(&recipient_ipk_res); - let recipient_ipk = nssa_core::encryption::shared_key_derivation::Secp256k1Point( - recipient_ipk.to_vec(), - ); - - let (res, [secret_sender, _]) = wallet_core - .send_transfer_token_transaction_private_foreign_account( - sender_addr, - recipient_npk, - recipient_ipk, - balance_to_move, - ) - .await?; - - println!("Results of tx send is {res:#?}"); - - let tx_hash = res.tx_hash; - let transfer_tx = wallet_core - .poll_native_token_transfer(tx_hash.clone()) - .await?; - - if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); - - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); - } - - let path = wallet_core.store_persistent_accounts()?; - - println!("Stored persistent accounts at {path:#?}"); - - SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } - } Command::ClaimPinata { pinata_addr, winner_addr, @@ -1125,6 +780,9 @@ pub async fn execute_subcommand(command: Command) -> Result { + token_subcommand.handle_subcommand(&mut wallet_core).await? + } }; Ok(subcommand_ret) From ba35fafad4c2c65cdc0819f618336dee586b447c Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Mon, 13 Oct 2025 15:09:50 -0300 Subject: [PATCH 15/23] fmt --- nssa/src/lib.rs | 1 + nssa/src/program.rs | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index 5227875..a635c0f 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -4,6 +4,7 @@ pub mod program_methods { } #[cfg(feature = "no_docker")] +#[allow(clippy::single_component_path_imports)] use program_methods; pub mod encoding; diff --git a/nssa/src/program.rs b/nssa/src/program.rs index b229241..f6df8fe 100644 --- a/nssa/src/program.rs +++ b/nssa/src/program.rs @@ -1,11 +1,11 @@ -use nssa_core::{ - account::{Account, AccountWithMetadata}, - program::{InstructionData, ProgramId, ProgramOutput}, -}; use crate::program_methods::{ AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, TOKEN_ELF, TOKEN_ID, }; +use nssa_core::{ + account::{Account, AccountWithMetadata}, + program::{InstructionData, ProgramId, ProgramOutput}, +}; use risc0_zkvm::{ExecutorEnv, ExecutorEnvBuilder, default_executor, serde::to_vec}; use serde::Serialize; From cf9d296d085bcd6bf02f06f6707185c909f5200c Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Mon, 13 Oct 2025 15:26:14 -0300 Subject: [PATCH 16/23] remove redundant test in ci --- ci_scripts/test-ubuntu.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/ci_scripts/test-ubuntu.sh b/ci_scripts/test-ubuntu.sh index d62cbb3..2aeba86 100755 --- a/ci_scripts/test-ubuntu.sh +++ b/ci_scripts/test-ubuntu.sh @@ -9,7 +9,6 @@ RISC0_DEV_MODE=1 cargo test --release --features no_docker cd integration_tests export NSSA_WALLET_HOME_DIR=$(pwd)/configs/debug/wallet/ export RUST_LOG=info -cargo run $(pwd)/configs/debug all echo "Try test valid proof at least once" cargo run $(pwd)/configs/debug test_success_private_transfer_to_another_owned_account echo "Continuing in dev mode" From 6274addad92a75511fd99a47b0db658274c151d0 Mon Sep 17 00:00:00 2001 From: Sergio Chouhy Date: Mon, 13 Oct 2025 16:25:59 -0300 Subject: [PATCH 17/23] Remove unused Nonce alias --- common/src/transaction.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/common/src/transaction.rs b/common/src/transaction.rs index 3a2bda1..5332e5c 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -5,12 +5,6 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, digest::FixedOutput}; -use elliptic_curve::{ - consts::{B0, B1}, - generic_array::GenericArray, -}; -use sha2::digest::typenum::{UInt, UTerm}; - #[derive(Debug, Clone, PartialEq, Eq)] pub enum NSSATransaction { Public(nssa::PublicTransaction), @@ -32,7 +26,6 @@ impl From for NSSATransaction { use crate::TreeHashType; pub type CipherText = Vec; -pub type Nonce = GenericArray, B1>, B0>, B0>>; pub type Tag = u8; #[derive( From d4a8cbd8d82b09f4ef3d318a56625cbd64f886b4 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Tue, 14 Oct 2025 08:33:20 +0300 Subject: [PATCH 18/23] fix: suggestions 1 --- integration_tests/src/lib.rs | 116 +++++++----- wallet/src/lib.rs | 303 ++++++++---------------------- wallet/src/pinata_interactions.rs | 173 +++++++++++++++++ 3 files changed, 320 insertions(+), 272 deletions(-) create mode 100644 wallet/src/pinata_interactions.rs diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 65e8574..78b7a6b 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -457,30 +457,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(); @@ -519,13 +501,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(); @@ -624,21 +599,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(); @@ -671,21 +636,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(); @@ -850,6 +806,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(); @@ -933,6 +946,9 @@ pub async fn main_tests_runner() -> Result<()> { "test_pinata_private_receiver" => { test_cleanup_wrap!(home_dir, test_pinata_private_receiver); } + "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); @@ -965,6 +981,7 @@ pub async fn main_tests_runner() -> Result<()> { ); test_cleanup_wrap!(home_dir, test_pinata); test_cleanup_wrap!(home_dir, test_pinata_private_receiver); + test_cleanup_wrap!(home_dir, test_pinata_private_receiver_new_account); } "all_private" => { test_cleanup_wrap!( @@ -992,6 +1009,7 @@ pub async fn main_tests_runner() -> Result<()> { test_success_private_transfer_to_another_owned_account_claiming_path ); test_cleanup_wrap!(home_dir, test_pinata_private_receiver); + 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 b65fc8a..8e3086d 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -10,28 +10,26 @@ use common::{ use anyhow::Result; use chain_storage::WalletChainStore; use config::WalletConfig; -use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; use log::info; -use nssa::{Account, Address, privacy_preserving_transaction::circuit}; +use nssa::{Account, Address}; use clap::{Parser, Subcommand}; -use nssa_core::{Commitment, SharedSecretKey, account::AccountWithMetadata}; +use nssa_core::Commitment; use crate::{ helperfunctions::{ HumanReadableAccount, fetch_config, fetch_persistent_accounts, get_home, - produce_data_for_storage, produce_random_nonces, + produce_data_for_storage, }, poller::TxPoller, }; -// - pub const HOME_DIR_ENV_VAR: &str = "NSSA_WALLET_HOME_DIR"; pub mod chain_storage; pub mod config; pub mod helperfunctions; +pub mod pinata_interactions; pub mod poller; pub mod token_transfers; @@ -88,102 +86,6 @@ impl WalletCore { .generate_new_privacy_preserving_transaction_key_chain() } - pub async fn claim_pinata( - &self, - pinata_addr: Address, - winner_addr: Address, - solution: u128, - ) -> Result { - let addresses = vec![pinata_addr, winner_addr]; - let program_id = nssa::program::Program::pinata().id(); - let message = - nssa::public_transaction::Message::try_new(program_id, addresses, vec![], solution) - .unwrap(); - - let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); - let tx = nssa::PublicTransaction::new(message, witness_set); - - Ok(self.sequencer_client.send_tx_public(tx).await?) - } - - pub async fn claim_pinata_private_owned_account( - &self, - pinata_addr: Address, - winner_addr: Address, - solution: u128, - ) -> 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 winner_commitment = Commitment::new(&winner_npk, &winner_acc); - - let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); - let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &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, 1], - &produce_random_nonces(1), - &[(winner_npk.clone(), shared_secret_winner.clone())], - &[( - winner_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(winner_commitment) - .await - .unwrap() - .unwrap(), - )], - &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], - )) - } - pub async fn send_new_token_definition( &self, definition_address: Address, @@ -286,6 +188,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 @@ -529,39 +472,10 @@ pub async fn execute_subcommand(command: Command) -> Result Result Result Result Result Result Result Result Result { + let addresses = vec![pinata_addr, winner_addr]; + let program_id = nssa::program::Program::pinata().id(); + let message = + nssa::public_transaction::Message::try_new(program_id, addresses, vec![], solution) + .unwrap(); + + let witness_set = nssa::public_transaction::WitnessSet::for_message(&message, &[]); + let tx = nssa::PublicTransaction::new(message, witness_set); + + Ok(self.sequencer_client.send_tx_public(tx).await?) + } + + pub async fn claim_pinata_private_owned_account_already_initialized( + &self, + pinata_addr: Address, + winner_addr: Address, + solution: u128, + ) -> 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 winner_commitment = Commitment::new(&winner_npk, &winner_acc); + + let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); + let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &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, 1], + &produce_random_nonces(1), + &[(winner_npk.clone(), shared_secret_winner.clone())], + &[( + winner_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(winner_commitment) + .await + .unwrap() + .unwrap(), + )], + &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], + )) + } + + pub async fn claim_pinata_private_owned_account_not_initialized( + &self, + pinata_addr: Address, + winner_addr: Address, + solution: u128, + ) -> 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], + )) + } +} From d556c9b699148e04d3750f1d42848c948191a061 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Tue, 14 Oct 2025 09:36:21 +0300 Subject: [PATCH 19/23] fix: lint build fix 1 --- common/Cargo.toml | 4 ++++ common/src/transaction.rs | 9 +++------ wallet/src/lib.rs | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/common/Cargo.toml b/common/Cargo.toml index d235246..d0d145f 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -19,5 +19,9 @@ hex.workspace = true nssa-core = { path = "../nssa/core", features = ["host"] } borsh.workspace = true +[dependencies.generic-array] +version = "1.3.3" +features = ["zeroize"] + [dependencies.nssa] path = "../nssa" diff --git a/common/src/transaction.rs b/common/src/transaction.rs index 3a2bda1..7790ea0 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -3,13 +3,10 @@ use k256::ecdsa::{Signature, SigningKey, VerifyingKey}; use log::info; use serde::{Deserialize, Serialize}; -use sha2::{Digest, digest::FixedOutput}; - -use elliptic_curve::{ - consts::{B0, B1}, - generic_array::GenericArray, -}; +use generic_array::GenericArray; +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/wallet/src/lib.rs b/wallet/src/lib.rs index 8e3086d..b874ff9 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -213,7 +213,7 @@ impl WalletCore { let res_acc = nssa_core::EncryptionScheme::decrypt( &acc_ead.ciphertext, - &secret, + secret, &acc_comm, output_index as u32, ) From 4b7319afe92f2d33a2fe2f80f443f41055ea24e9 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Tue, 14 Oct 2025 10:18:54 +0300 Subject: [PATCH 20/23] fix: merge updates --- integration_tests/src/lib.rs | 76 +++++---- wallet/src/cli/token_program.rs | 270 ++++++++++++-------------------- wallet/src/lib.rs | 2 +- 3 files changed, 146 insertions(+), 202 deletions(-) diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 0eaae0d..abe1c76 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -19,7 +19,9 @@ use tempfile::TempDir; use tokio::task::JoinHandle; use wallet::{ Command, SubcommandReturnValue, WalletCore, - cli::token_program::TokenProgramSubcommand, + cli::token_program::{ + TokenProgramSubcommand, TokenProgramSubcommandPrivate, TokenProgramSubcommandPublic, + }, config::PersistentAccountData, helperfunctions::{fetch_config, fetch_persistent_accounts}, }; @@ -351,12 +353,12 @@ pub async fn test_success_token_program() { .expect("Failed to produce new account, not present in persistent accounts"); // Create new token - let subcommand = TokenProgramSubcommand::CreateNewToken { + let subcommand = TokenProgramSubcommand::Public(TokenProgramSubcommandPublic::CreateNewToken { definition_addr: definition_addr.to_string(), supply_addr: supply_addr.to_string(), name: "A NAME".to_string(), total_supply: 37, - }; + }); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await .unwrap(); @@ -405,11 +407,11 @@ pub async fn test_success_token_program() { ); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let subcommand = TokenProgramSubcommand::TransferToken { + let subcommand = TokenProgramSubcommand::Public(TokenProgramSubcommandPublic::TransferToken { sender_addr: supply_addr.to_string(), recipient_addr: recipient_addr.to_string(), balance_to_move: 7, - }; + }); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await .unwrap(); @@ -485,12 +487,14 @@ pub async fn test_success_token_program_private_owned() { }; // Create new token - let subcommand = TokenProgramSubcommand::CreateNewTokenPrivateOwned { - definition_addr: definition_addr.to_string(), - supply_addr: supply_addr.to_string(), - name: "A NAME".to_string(), - total_supply: 37, - }; + let subcommand = TokenProgramSubcommand::Private( + TokenProgramSubcommandPrivate::CreateNewTokenPrivateOwned { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }, + ); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await @@ -527,11 +531,12 @@ pub async fn test_success_token_program_private_owned() { assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let subcommand = TokenProgramSubcommand::TransferTokenPrivateOwnedNotInitialized { - sender_addr: supply_addr.to_string(), - recipient_addr: recipient_addr.to_string(), - balance_to_move: 7, - }; + let subcommand = + TokenProgramSubcommand::Private(TokenProgramSubcommandPrivate::TransferTokenPrivateOwned { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await @@ -554,11 +559,12 @@ pub async fn test_success_token_program_private_owned() { assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); // Transfer additional 7 tokens from `supply_acc` to the account at address `recipient_addr` - let subcommand = TokenProgramSubcommand::TransferTokenPrivateOwnedAlreadyInitialized { - sender_addr: supply_addr.to_string(), - recipient_addr: recipient_addr.to_string(), - balance_to_move: 7, - }; + let subcommand = + TokenProgramSubcommand::Private(TokenProgramSubcommandPrivate::TransferTokenPrivateOwned { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await @@ -614,12 +620,14 @@ pub async fn test_success_token_program_private_claiming_path() { }; // Create new token - let subcommand = TokenProgramSubcommand::CreateNewTokenPrivateOwned { - definition_addr: definition_addr.to_string(), - supply_addr: supply_addr.to_string(), - name: "A NAME".to_string(), - total_supply: 37, - }; + let subcommand = TokenProgramSubcommand::Private( + TokenProgramSubcommandPrivate::CreateNewTokenPrivateOwned { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }, + ); wallet::execute_subcommand(Command::TokenProgram(subcommand)) .await @@ -662,12 +670,14 @@ pub async fn test_success_token_program_private_claiming_path() { .unwrap(); // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` - let subcommand = TokenProgramSubcommand::TransferTokenPrivateForeign { - sender_addr: supply_addr.to_string(), - recipient_npk: hex::encode(recipient_keys.nullifer_public_key.0), - recipient_ipk: hex::encode(recipient_keys.incoming_viewing_public_key.0.clone()), - balance_to_move: 7, - }; + let subcommand = TokenProgramSubcommand::Private( + TokenProgramSubcommandPrivate::TransferTokenPrivateForeign { + sender_addr: supply_addr.to_string(), + recipient_npk: hex::encode(recipient_keys.nullifer_public_key.0), + recipient_ipk: hex::encode(recipient_keys.incoming_viewing_public_key.0.clone()), + balance_to_move: 7, + }, + ); let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = wallet::execute_subcommand(Command::TokenProgram(subcommand)) diff --git a/wallet/src/cli/token_program.rs b/wallet/src/cli/token_program.rs index d3b42ea..02c9b53 100644 --- a/wallet/src/cli/token_program.rs +++ b/wallet/src/cli/token_program.rs @@ -5,9 +5,20 @@ use nssa::Address; use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand}; -///Represents CLI subcommand for a wallet working with token_program +///Represents generic CLI subcommand for a wallet working with token_program #[derive(Subcommand, Debug, Clone)] pub enum TokenProgramSubcommand { + ///Public execution + #[command(subcommand)] + Public(TokenProgramSubcommandPublic), + ///Private execution + #[command(subcommand)] + Private(TokenProgramSubcommandPrivate), +} + +///Represents generic public CLI subcommand for a wallet working with token_program +#[derive(Subcommand, Debug, Clone)] +pub enum TokenProgramSubcommandPublic { //Create a new token using the token program CreateNewToken { #[arg(short, long)] @@ -28,6 +39,11 @@ pub enum TokenProgramSubcommand { #[arg(short, long)] balance_to_move: u128, }, +} + +///Represents generic public CLI subcommand for a wallet working with token_program +#[derive(Subcommand, Debug, Clone)] +pub enum TokenProgramSubcommandPrivate { //Create a new token using the token program CreateNewTokenPrivateOwned { #[arg(short, long)] @@ -40,16 +56,7 @@ pub enum TokenProgramSubcommand { total_supply: u128, }, //Transfer tokens using the token program - TransferTokenPrivateOwnedAlreadyInitialized { - #[arg(short, long)] - sender_addr: String, - #[arg(short, long)] - recipient_addr: String, - #[arg(short, long)] - balance_to_move: u128, - }, - //Transfer tokens using the token program - TransferTokenPrivateOwnedNotInitialized { + TransferTokenPrivateOwned { #[arg(short, long)] sender_addr: String, #[arg(short, long)] @@ -72,13 +79,13 @@ pub enum TokenProgramSubcommand { }, } -impl WalletSubcommand for TokenProgramSubcommand { +impl WalletSubcommand for TokenProgramSubcommandPublic { async fn handle_subcommand( self, wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommand::CreateNewToken { + TokenProgramSubcommandPublic::CreateNewToken { definition_addr, supply_addr, name, @@ -101,7 +108,31 @@ impl WalletSubcommand for TokenProgramSubcommand { .await?; Ok(SubcommandReturnValue::Empty) } - TokenProgramSubcommand::CreateNewTokenPrivateOwned { + TokenProgramSubcommandPublic::TransferToken { + sender_addr, + recipient_addr, + balance_to_move, + } => { + wallet_core + .send_transfer_token_transaction( + sender_addr.parse().unwrap(), + recipient_addr.parse().unwrap(), + balance_to_move, + ) + .await?; + Ok(SubcommandReturnValue::Empty) + } + } + } +} + +impl WalletSubcommand for TokenProgramSubcommandPrivate { + async fn handle_subcommand( + self, + wallet_core: &mut WalletCore, + ) -> Result { + match self { + TokenProgramSubcommandPrivate::CreateNewTokenPrivateOwned { definition_addr, supply_addr, name, @@ -135,24 +166,12 @@ impl WalletSubcommand for TokenProgramSubcommand { .await?; if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let supply_ebc = tx.message.encrypted_private_post_states[0].clone(); - let supply_comm = tx.message.new_commitments[0].clone(); + let acc_decode_data = vec![(secret_supply, supply_addr)]; - let res_acc_supply = nssa_core::EncryptionScheme::decrypt( - &supply_ebc.ciphertext, - &secret_supply, - &supply_comm, - 0, - ) - .unwrap(); - - println!("Received new to acc {res_acc_supply:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(supply_addr, res_acc_supply); + wallet_core.decode_insert_privacy_preserving_transaction_results( + tx, + &acc_decode_data, + )?; } let path = wallet_core.store_persistent_accounts()?; @@ -161,21 +180,7 @@ impl WalletSubcommand for TokenProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommand::TransferToken { - sender_addr, - recipient_addr, - balance_to_move, - } => { - wallet_core - .send_transfer_token_transaction( - sender_addr.parse().unwrap(), - recipient_addr.parse().unwrap(), - balance_to_move, - ) - .await?; - Ok(SubcommandReturnValue::Empty) - } - TokenProgramSubcommand::TransferTokenPrivateOwnedAlreadyInitialized { + TokenProgramSubcommandPrivate::TransferTokenPrivateOwned { sender_addr, recipient_addr, balance_to_move, @@ -183,13 +188,27 @@ impl WalletSubcommand for TokenProgramSubcommand { let sender_addr: Address = sender_addr.parse().unwrap(); let recipient_addr: Address = recipient_addr.parse().unwrap(); - let (res, [secret_sender, secret_recipient]) = wallet_core - .send_transfer_token_transaction_private_owned_account_already_initialized( - sender_addr, - recipient_addr, - balance_to_move, - ) - .await?; + let recipient_initialized = wallet_core + .check_private_account_initialized(&recipient_addr) + .await; + + let (res, [secret_sender, secret_recipient]) = if recipient_initialized { + wallet_core + .send_transfer_token_transaction_private_owned_account_already_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await? + } else { + wallet_core + .send_transfer_token_transaction_private_owned_account_not_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await? + }; println!("Results of tx send is {res:#?}"); @@ -199,39 +218,15 @@ impl WalletSubcommand for TokenProgramSubcommand { .await?; if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); + let acc_decode_data = vec![ + (secret_sender, sender_addr), + (secret_recipient, recipient_addr), + ]; - let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); - let recipient_comm = tx.message.new_commitments[1].clone(); - - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( - &recipient_ebc.ciphertext, - &secret_recipient, - &recipient_comm, - 1, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - println!("Received new recipient acc {res_acc_recipient:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); - wallet_core - .storage - .insert_private_account_data(recipient_addr, res_acc_recipient); + wallet_core.decode_insert_privacy_preserving_transaction_results( + tx, + &acc_decode_data, + )?; } let path = wallet_core.store_persistent_accounts()?; @@ -240,72 +235,7 @@ impl WalletSubcommand for TokenProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommand::TransferTokenPrivateOwnedNotInitialized { - sender_addr, - recipient_addr, - balance_to_move, - } => { - let sender_addr: Address = sender_addr.parse().unwrap(); - let recipient_addr: Address = recipient_addr.parse().unwrap(); - - let (res, [secret_sender, secret_recipient]) = wallet_core - .send_transfer_token_transaction_private_owned_account_not_initialized( - sender_addr, - recipient_addr, - balance_to_move, - ) - .await?; - - println!("Results of tx send is {res:#?}"); - - let tx_hash = res.tx_hash; - let transfer_tx = wallet_core - .poll_native_token_transfer(tx_hash.clone()) - .await?; - - if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); - - let recipient_ebc = tx.message.encrypted_private_post_states[1].clone(); - let recipient_comm = tx.message.new_commitments[1].clone(); - - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - let res_acc_recipient = nssa_core::EncryptionScheme::decrypt( - &recipient_ebc.ciphertext, - &secret_recipient, - &recipient_comm, - 1, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - println!("Received new recipient acc {res_acc_recipient:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); - wallet_core - .storage - .insert_private_account_data(recipient_addr, res_acc_recipient); - } - - let path = wallet_core.store_persistent_accounts()?; - - println!("Stored persistent accounts at {path:#?}"); - - Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) - } - TokenProgramSubcommand::TransferTokenPrivateForeign { + TokenProgramSubcommandPrivate::TransferTokenPrivateForeign { sender_addr, recipient_npk, recipient_ipk, @@ -341,24 +271,12 @@ impl WalletSubcommand for TokenProgramSubcommand { .await?; if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { - let sender_ebc = tx.message.encrypted_private_post_states[0].clone(); - let sender_comm = tx.message.new_commitments[0].clone(); + let acc_decode_data = vec![(secret_sender, sender_addr)]; - let res_acc_sender = nssa_core::EncryptionScheme::decrypt( - &sender_ebc.ciphertext, - &secret_sender, - &sender_comm, - 0, - ) - .unwrap(); - - println!("Received new sender acc {res_acc_sender:#?}"); - - println!("Transaction data is {:?}", tx.message); - - wallet_core - .storage - .insert_private_account_data(sender_addr, res_acc_sender); + wallet_core.decode_insert_privacy_preserving_transaction_results( + tx, + &acc_decode_data, + )?; } let path = wallet_core.store_persistent_accounts()?; @@ -370,3 +288,19 @@ impl WalletSubcommand for TokenProgramSubcommand { } } } + +impl WalletSubcommand for TokenProgramSubcommand { + async fn handle_subcommand( + self, + wallet_core: &mut WalletCore, + ) -> Result { + match self { + TokenProgramSubcommand::Private(private_subcommand) => { + private_subcommand.handle_subcommand(wallet_core).await + } + TokenProgramSubcommand::Public(public_subcommand) => { + public_subcommand.handle_subcommand(wallet_core).await + } + } + } +} diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index aacdfcd..ac4cf6d 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -338,7 +338,7 @@ pub enum Command { #[arg(long)] solution: u128, }, - ///Test command + ///Token command #[command(subcommand)] TokenProgram(TokenProgramSubcommand), } From 1428dc4a908d307a65c5ed8e5b45bcb5ab7e217f Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Wed, 15 Oct 2025 15:25:36 +0300 Subject: [PATCH 21/23] fix: suggestion fix 2 --- wallet/src/lib.rs | 26 ++++++++++++++------------ wallet/src/pinata_interactions.rs | 11 +++-------- 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index b874ff9..3706b8c 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -14,7 +14,7 @@ use log::info; use nssa::{Account, Address}; use clap::{Parser, Subcommand}; -use nssa_core::Commitment; +use nssa_core::{Commitment, MembershipProof}; use crate::{ helperfunctions::{ @@ -189,16 +189,17 @@ impl WalletCore { Ok(NSSATransaction::try_from(&pub_tx)?) } - pub async fn check_private_account_initialized(&self, addr: &Address) -> bool { + pub async fn check_private_account_initialized( + &self, + addr: &Address, + ) -> Result> { if let Some(acc_comm) = self.get_private_account_commitment(addr) { - matches!( - self.sequencer_client - .get_proof_for_commitment(acc_comm) - .await, - Ok(Some(_)) - ) + self.sequencer_client + .get_proof_for_commitment(acc_comm) + .await + .map_err(anyhow::Error::from) } else { - false + Ok(None) } } @@ -799,16 +800,17 @@ pub async fn execute_subcommand(command: Command) -> Result Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { let Some((winner_keys, winner_acc)) = self .storage @@ -46,8 +47,6 @@ impl WalletCore { let program = nssa::program::Program::pinata(); - let winner_commitment = Commitment::new(&winner_npk, &winner_acc); - let pinata_pre = AccountWithMetadata::new(pinata_acc.clone(), false, pinata_addr); let winner_pre = AccountWithMetadata::new(winner_acc.clone(), true, &winner_npk); @@ -62,11 +61,7 @@ impl WalletCore { &[(winner_npk.clone(), shared_secret_winner.clone())], &[( winner_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(winner_commitment) - .await - .unwrap() - .unwrap(), + winner_proof, )], &program, ) From 5010c6c37020e4ad1f8e9c4b75d18851d4df3037 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Wed, 15 Oct 2025 15:29:28 +0300 Subject: [PATCH 22/23] fix: merge update --- wallet/src/cli/token_program.rs | 28 +++++++++++++----------- wallet/src/token_program_interactions.rs | 10 +++------ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/wallet/src/cli/token_program.rs b/wallet/src/cli/token_program.rs index 02c9b53..7a17730 100644 --- a/wallet/src/cli/token_program.rs +++ b/wallet/src/cli/token_program.rs @@ -188,27 +188,29 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { let sender_addr: Address = sender_addr.parse().unwrap(); let recipient_addr: Address = recipient_addr.parse().unwrap(); - let recipient_initialized = wallet_core + let recipient_initialization = wallet_core .check_private_account_initialized(&recipient_addr) - .await; + .await?; - let (res, [secret_sender, secret_recipient]) = if recipient_initialized { - wallet_core + let (res, [secret_sender, secret_recipient]) = + if let Some(recipient_proof) = recipient_initialization { + wallet_core .send_transfer_token_transaction_private_owned_account_already_initialized( sender_addr, recipient_addr, balance_to_move, + recipient_proof, ) .await? - } else { - wallet_core - .send_transfer_token_transaction_private_owned_account_not_initialized( - sender_addr, - recipient_addr, - balance_to_move, - ) - .await? - }; + } else { + wallet_core + .send_transfer_token_transaction_private_owned_account_not_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await? + }; println!("Results of tx send is {res:#?}"); diff --git a/wallet/src/token_program_interactions.rs b/wallet/src/token_program_interactions.rs index 74c341e..76bd36b 100644 --- a/wallet/src/token_program_interactions.rs +++ b/wallet/src/token_program_interactions.rs @@ -2,7 +2,7 @@ use common::{ExecutionFailureKind, sequencer_client::json::SendTxResponse}; use key_protocol::key_management::ephemeral_key_holder::EphemeralKeyHolder; use nssa::{Address, privacy_preserving_transaction::circuit, program::Program}; use nssa_core::{ - Commitment, NullifierPublicKey, SharedSecretKey, account::AccountWithMetadata, + Commitment, MembershipProof, NullifierPublicKey, SharedSecretKey, account::AccountWithMetadata, encryption::IncomingViewingPublicKey, }; @@ -146,6 +146,7 @@ impl WalletCore { sender_address: Address, recipient_address: Address, amount: u128, + recipient_proof: MembershipProof, ) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> { let Some((sender_keys, sender_acc)) = self .storage @@ -173,7 +174,6 @@ impl WalletCore { let program = Program::token(); let sender_commitment = Commitment::new(&sender_npk, &sender_acc); - let receiver_commitment = Commitment::new(&recipient_npk, &recipient_acc); let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, &sender_npk); let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), true, &recipient_npk); @@ -210,11 +210,7 @@ impl WalletCore { ), ( recipient_keys.private_key_holder.nullifier_secret_key, - self.sequencer_client - .get_proof_for_commitment(receiver_commitment) - .await - .unwrap() - .unwrap(), + recipient_proof, ), ], &program, From e5a6acf28dff1fd2fc425ac53a9318051067f6c7 Mon Sep 17 00:00:00 2001 From: Oleksandr Pravdyvyi Date: Mon, 20 Oct 2025 09:10:54 +0300 Subject: [PATCH 23/23] fix; shielded and deshielded transfers --- integration_tests/src/lib.rs | 249 +++++++++++++++++- wallet/src/cli/token_program.rs | 212 ++++++++++++++- wallet/src/token_program_interactions.rs | 321 +++++++++++++++++++++++ 3 files changed, 780 insertions(+), 2 deletions(-) diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index abe1c76..9b13f01 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -20,7 +20,8 @@ use tokio::task::JoinHandle; use wallet::{ Command, SubcommandReturnValue, WalletCore, cli::token_program::{ - TokenProgramSubcommand, TokenProgramSubcommandPrivate, TokenProgramSubcommandPublic, + TokenProgramSubcommand, TokenProgramSubcommandDeshielded, TokenProgramSubcommandPrivate, + TokenProgramSubcommandPublic, TokenProgramSubcommandShielded, }, config::PersistentAccountData, helperfunctions::{fetch_config, fetch_persistent_accounts}, @@ -712,6 +713,246 @@ pub async fn test_success_token_program_private_claiming_path() { assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); } +/// This test creates a new public token using the token program. After creating the token, the test executes a +/// shielded token transfer to a new account. All accounts are owned except definition. +pub async fn test_success_token_program_shielded_owned() { + let wallet_config = fetch_config().unwrap(); + + // Create new account for the token definition (public) + let SubcommandReturnValue::RegisterAccount { + addr: definition_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPublic {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for the token supply holder (private) + let SubcommandReturnValue::RegisterAccount { addr: supply_addr } = + wallet::execute_subcommand(Command::RegisterAccountPublic {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for receiving a token transaction + let SubcommandReturnValue::RegisterAccount { + addr: recipient_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + + // Create new token + let subcommand = TokenProgramSubcommand::Public(TokenProgramSubcommandPublic::CreateNewToken { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + + // Check the status of the token definition account is the expected after the execution + let definition_acc = seq_client + .get_account(definition_addr.to_string()) + .await + .unwrap() + .account; + + assert_eq!(definition_acc.program_owner, Program::token().id()); + // The data of a token definition account has the following layout: + // [ 0x00 || name (6 bytes) || total supply (little endian 16 bytes) ] + assert_eq!( + definition_acc.data, + vec![ + 0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] + ); + + // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` + let subcommand = TokenProgramSubcommand::Shielded( + TokenProgramSubcommandShielded::TransferTokenShieldedOwned { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }, + ); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment2 = wallet_storage + .get_private_account_commitment(&recipient_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); + + // Transfer additional 7 tokens from `supply_acc` to the account at address `recipient_addr` + let subcommand = TokenProgramSubcommand::Shielded( + TokenProgramSubcommandShielded::TransferTokenShieldedOwned { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }, + ); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment2 = wallet_storage + .get_private_account_commitment(&recipient_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); +} + +/// This test creates a new private token using the token program. After creating the token, the test executes a +/// deshielded token transfer to a new account. All accounts are owned except definition. +pub async fn test_success_token_program_deshielded_owned() { + let wallet_config = fetch_config().unwrap(); + + // Create new account for the token definition (public) + let SubcommandReturnValue::RegisterAccount { + addr: definition_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPublic {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for the token supply holder (private) + let SubcommandReturnValue::RegisterAccount { addr: supply_addr } = + wallet::execute_subcommand(Command::RegisterAccountPrivate {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + // Create new account for receiving a token transaction + let SubcommandReturnValue::RegisterAccount { + addr: recipient_addr, + } = wallet::execute_subcommand(Command::RegisterAccountPublic {}) + .await + .unwrap() + else { + panic!("invalid subcommand return value"); + }; + + // Create new token + let subcommand = TokenProgramSubcommand::Private( + TokenProgramSubcommandPrivate::CreateNewTokenPrivateOwned { + definition_addr: definition_addr.to_string(), + supply_addr: supply_addr.to_string(), + name: "A NAME".to_string(), + total_supply: 37, + }, + ); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + + // Check the status of the token definition account is the expected after the execution + let definition_acc = seq_client + .get_account(definition_addr.to_string()) + .await + .unwrap() + .account; + + assert_eq!(definition_acc.program_owner, Program::token().id()); + // The data of a token definition account has the following layout: + // [ 0x00 || name (6 bytes) || total supply (little endian 16 bytes) ] + assert_eq!( + definition_acc.data, + vec![ + 0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] + ); + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + // Transfer 7 tokens from `supply_acc` to the account at address `recipient_addr` + let subcommand = TokenProgramSubcommand::Deshielded( + TokenProgramSubcommandDeshielded::TransferTokenDeshielded { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }, + ); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); + + // Transfer additional 7 tokens from `supply_acc` to the account at address `recipient_addr` + let subcommand = TokenProgramSubcommand::Deshielded( + TokenProgramSubcommandDeshielded::TransferTokenDeshielded { + sender_addr: supply_addr.to_string(), + recipient_addr: recipient_addr.to_string(), + balance_to_move: 7, + }, + ); + + wallet::execute_subcommand(Command::TokenProgram(subcommand)) + .await + .unwrap(); + + info!("Waiting for next block creation"); + tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + + let wallet_config = fetch_config().unwrap(); + let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config).unwrap(); + + let new_commitment1 = wallet_storage + .get_private_account_commitment(&supply_addr) + .unwrap(); + assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); +} + pub async fn test_success_private_transfer_to_another_owned_account() { info!("test_success_private_transfer_to_another_owned_account"); let from: Address = ACC_SENDER_PRIVATE.parse().unwrap(); @@ -1220,6 +1461,12 @@ pub async fn main_tests_runner() -> Result<()> { "test_pinata_private_receiver_new_account" => { test_cleanup_wrap!(home_dir, test_pinata_private_receiver_new_account); } + "test_success_token_program_shielded_owned" => { + test_cleanup_wrap!(home_dir, test_success_token_program_shielded_owned); + } + "test_success_token_program_deshielded_owned" => { + test_cleanup_wrap!(home_dir, test_success_token_program_deshielded_owned); + } "all" => { test_cleanup_wrap!(home_dir, test_success_move_to_another_account); test_cleanup_wrap!(home_dir, test_success); diff --git a/wallet/src/cli/token_program.rs b/wallet/src/cli/token_program.rs index 7a17730..02b25b1 100644 --- a/wallet/src/cli/token_program.rs +++ b/wallet/src/cli/token_program.rs @@ -14,6 +14,12 @@ pub enum TokenProgramSubcommand { ///Private execution #[command(subcommand)] Private(TokenProgramSubcommandPrivate), + ///Deshielded execution + #[command(subcommand)] + Deshielded(TokenProgramSubcommandDeshielded), + ///Shielded execution + #[command(subcommand)] + Shielded(TokenProgramSubcommandShielded), } ///Represents generic public CLI subcommand for a wallet working with token_program @@ -41,7 +47,7 @@ pub enum TokenProgramSubcommandPublic { }, } -///Represents generic public CLI subcommand for a wallet working with token_program +///Represents generic private CLI subcommand for a wallet working with token_program #[derive(Subcommand, Debug, Clone)] pub enum TokenProgramSubcommandPrivate { //Create a new token using the token program @@ -79,6 +85,47 @@ pub enum TokenProgramSubcommandPrivate { }, } +///Represents deshielded public CLI subcommand for a wallet working with token_program +#[derive(Subcommand, Debug, Clone)] +pub enum TokenProgramSubcommandDeshielded { + //Transfer tokens using the token program + TransferTokenDeshielded { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, +} + +///Represents generic shielded CLI subcommand for a wallet working with token_program +#[derive(Subcommand, Debug, Clone)] +pub enum TokenProgramSubcommandShielded { + //Transfer tokens using the token program + TransferTokenShieldedOwned { + #[arg(short, long)] + sender_addr: String, + #[arg(short, long)] + recipient_addr: String, + #[arg(short, long)] + balance_to_move: u128, + }, + //Transfer tokens using the token program + TransferTokenShieldedForeign { + #[arg(short, long)] + sender_addr: String, + ///recipient_npk - valid 32 byte hex string + #[arg(long)] + recipient_npk: String, + ///recipient_ipk - valid 33 byte hex string + #[arg(long)] + recipient_ipk: String, + #[arg(short, long)] + balance_to_move: u128, + }, +} + impl WalletSubcommand for TokenProgramSubcommandPublic { async fn handle_subcommand( self, @@ -291,6 +338,163 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { } } +impl WalletSubcommand for TokenProgramSubcommandDeshielded { + async fn handle_subcommand( + self, + wallet_core: &mut WalletCore, + ) -> Result { + match self { + TokenProgramSubcommandDeshielded::TransferTokenDeshielded { + sender_addr, + recipient_addr, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let (res, [secret_sender]) = wallet_core + .send_transfer_token_transaction_deshielded( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let acc_decode_data = vec![(secret_sender, sender_addr)]; + + wallet_core.decode_insert_privacy_preserving_transaction_results( + tx, + &acc_decode_data, + )?; + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + } + } +} + +impl WalletSubcommand for TokenProgramSubcommandShielded { + async fn handle_subcommand( + self, + wallet_core: &mut WalletCore, + ) -> Result { + match self { + TokenProgramSubcommandShielded::TransferTokenShieldedForeign { + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_npk_res = hex::decode(recipient_npk)?; + let mut recipient_npk = [0; 32]; + recipient_npk.copy_from_slice(&recipient_npk_res); + let recipient_npk = nssa_core::NullifierPublicKey(recipient_npk); + + let recipient_ipk_res = hex::decode(recipient_ipk)?; + let mut recipient_ipk = [0u8; 33]; + recipient_ipk.copy_from_slice(&recipient_ipk_res); + let recipient_ipk = nssa_core::encryption::shared_key_derivation::Secp256k1Point( + recipient_ipk.to_vec(), + ); + + let res = wallet_core + .send_transfer_token_transaction_shielded_foreign_account( + sender_addr, + recipient_npk, + recipient_ipk, + balance_to_move, + ) + .await?; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + println!("Transaction data is {:?}", tx.message); + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + TokenProgramSubcommandShielded::TransferTokenShieldedOwned { + sender_addr, + recipient_addr, + balance_to_move, + } => { + let sender_addr: Address = sender_addr.parse().unwrap(); + let recipient_addr: Address = recipient_addr.parse().unwrap(); + + let recipient_initialization = wallet_core + .check_private_account_initialized(&recipient_addr) + .await?; + + let (res, [secret_recipient]) = + if let Some(recipient_proof) = recipient_initialization { + wallet_core + .send_transfer_token_transaction_shielded_owned_account_already_initialized( + sender_addr, + recipient_addr, + balance_to_move, + recipient_proof, + ) + .await? + } else { + wallet_core + .send_transfer_token_transaction_shielded_owned_account_not_initialized( + sender_addr, + recipient_addr, + balance_to_move, + ) + .await? + }; + + println!("Results of tx send is {res:#?}"); + + let tx_hash = res.tx_hash; + let transfer_tx = wallet_core + .poll_native_token_transfer(tx_hash.clone()) + .await?; + + if let NSSATransaction::PrivacyPreserving(tx) = transfer_tx { + let acc_decode_data = vec![(secret_recipient, recipient_addr)]; + + wallet_core.decode_insert_privacy_preserving_transaction_results( + tx, + &acc_decode_data, + )?; + } + + let path = wallet_core.store_persistent_accounts()?; + + println!("Stored persistent accounts at {path:#?}"); + + Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) + } + } + } +} + impl WalletSubcommand for TokenProgramSubcommand { async fn handle_subcommand( self, @@ -303,6 +507,12 @@ impl WalletSubcommand for TokenProgramSubcommand { TokenProgramSubcommand::Public(public_subcommand) => { public_subcommand.handle_subcommand(wallet_core).await } + TokenProgramSubcommand::Deshielded(deshielded_subcommand) => { + deshielded_subcommand.handle_subcommand(wallet_core).await + } + TokenProgramSubcommand::Shielded(shielded_subcommand) => { + shielded_subcommand.handle_subcommand(wallet_core).await + } } } } diff --git a/wallet/src/token_program_interactions.rs b/wallet/src/token_program_interactions.rs index 76bd36b..a77a512 100644 --- a/wallet/src/token_program_interactions.rs +++ b/wallet/src/token_program_interactions.rs @@ -448,4 +448,325 @@ impl WalletCore { [shared_secret_sender, shared_secret_recipient], )) } + + pub async fn send_transfer_token_transaction_deshielded( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { + let Some((sender_keys, sender_acc)) = self + .storage + .user_data + .get_private_account(&sender_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Ok(recipient_acc) = self.get_account_public(recipient_address).await else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let sender_npk = sender_keys.nullifer_public_key; + let sender_ipk = sender_keys.incoming_viewing_public_key; + + let program = Program::token(); + + let sender_commitment = Commitment::new(&sender_npk, &sender_acc); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, &sender_npk); + let recipient_pre = + AccountWithMetadata::new(recipient_acc.clone(), false, recipient_address); + + let eph_holder_sender = EphemeralKeyHolder::new(&sender_npk); + let shared_secret_sender = eph_holder_sender.calculate_shared_secret_sender(&sender_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[1, 0], + &produce_random_nonces(1), + &[(sender_npk.clone(), shared_secret_sender.clone())], + &[( + sender_keys.private_key_holder.nullifier_secret_key, + self.sequencer_client + .get_proof_for_commitment(sender_commitment) + .await + .unwrap() + .unwrap(), + )], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![recipient_address], + vec![], + vec![( + sender_npk.clone(), + sender_ipk.clone(), + eph_holder_sender.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_sender], + )) + } + + pub async fn send_transfer_token_transaction_shielded_owned_account_already_initialized( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + recipient_proof: MembershipProof, + ) -> Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { + let Ok(sender_acc) = self.get_account_public(sender_address).await else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some(sender_priv_key) = self + .storage + .user_data + .get_pub_account_signing_key(&sender_address) + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some((recipient_keys, recipient_acc)) = self + .storage + .user_data + .get_private_account(&recipient_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let recipient_npk = recipient_keys.nullifer_public_key.clone(); + let recipient_ipk = recipient_keys.incoming_viewing_public_key.clone(); + + let program = Program::token(); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, sender_address); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), true, &recipient_npk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[0, 1], + &produce_random_nonces(1), + &[(recipient_npk.clone(), shared_secret_recipient.clone())], + &[( + recipient_keys.private_key_holder.nullifier_secret_key, + recipient_proof, + )], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![sender_address], + vec![sender_acc.nonce], + vec![( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[sender_priv_key], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_recipient], + )) + } + + pub async fn send_transfer_token_transaction_shielded_owned_account_not_initialized( + &self, + sender_address: Address, + recipient_address: Address, + amount: u128, + ) -> Result<(SendTxResponse, [SharedSecretKey; 1]), ExecutionFailureKind> { + let Ok(sender_acc) = self.get_account_public(sender_address).await else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some(sender_priv_key) = self + .storage + .user_data + .get_pub_account_signing_key(&sender_address) + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some((recipient_keys, recipient_acc)) = self + .storage + .user_data + .get_private_account(&recipient_address) + .cloned() + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let recipient_npk = recipient_keys.nullifer_public_key.clone(); + let recipient_ipk = recipient_keys.incoming_viewing_public_key.clone(); + + let program = Program::token(); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, sender_address); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), false, &recipient_npk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[0, 2], + &produce_random_nonces(1), + &[(recipient_npk.clone(), shared_secret_recipient.clone())], + &[], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![sender_address], + vec![sender_acc.nonce], + vec![( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[sender_priv_key], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(( + self.sequencer_client.send_tx_private(tx).await?, + [shared_secret_recipient], + )) + } + + pub async fn send_transfer_token_transaction_shielded_foreign_account( + &self, + sender_address: Address, + recipient_npk: NullifierPublicKey, + recipient_ipk: IncomingViewingPublicKey, + amount: u128, + ) -> Result { + let Ok(sender_acc) = self.get_account_public(sender_address).await else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let Some(sender_priv_key) = self + .storage + .user_data + .get_pub_account_signing_key(&sender_address) + else { + return Err(ExecutionFailureKind::KeyNotFoundError); + }; + + let recipient_acc = nssa_core::account::Account::default(); + + let program = Program::token(); + + let sender_pre = AccountWithMetadata::new(sender_acc.clone(), true, sender_address); + let recipient_pre = AccountWithMetadata::new(recipient_acc.clone(), false, &recipient_npk); + + let eph_holder_recipient = EphemeralKeyHolder::new(&recipient_npk); + let shared_secret_recipient = + eph_holder_recipient.calculate_shared_secret_sender(&recipient_ipk); + + // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + let mut instruction = [0; 23]; + instruction[0] = 0x01; + instruction[1..17].copy_from_slice(&amount.to_le_bytes()); + + let (output, proof) = circuit::execute_and_prove( + &[sender_pre, recipient_pre], + &Program::serialize_instruction(instruction).unwrap(), + &[0, 2], + &produce_random_nonces(1), + &[(recipient_npk.clone(), shared_secret_recipient.clone())], + &[], + &program, + ) + .unwrap(); + + let message = + nssa::privacy_preserving_transaction::message::Message::try_from_circuit_output( + vec![sender_address], + vec![sender_acc.nonce], + vec![( + recipient_npk.clone(), + recipient_ipk.clone(), + eph_holder_recipient.generate_ephemeral_public_key(), + )], + output, + ) + .unwrap(); + + let witness_set = + nssa::privacy_preserving_transaction::witness_set::WitnessSet::for_message( + &message, + proof, + &[sender_priv_key], + ); + let tx = nssa::PrivacyPreservingTransaction::new(message, witness_set); + + Ok(self.sequencer_client.send_tx_private(tx).await?) + } }