diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 071fa8d..6ebfca7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,7 @@ on: push: branches: - - master + - main paths-ignore: - "**.md" - "!.github/workflows/*.yml" @@ -21,15 +21,14 @@ jobs: name: ubuntu-latest-pipeline steps: - uses: actions/checkout@v3 - - name: Install stable toolchain - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: nightly - override: true - components: rustfmt, clippy + + - name: Install active toolchain + run: rustup install + + - name: Install nightly toolchain for rustfmt + run: rustup install nightly --profile minimal --component rustfmt + - name: lint - ubuntu-latest - if: success() || failure() run: chmod 777 ./ci_scripts/lint-ubuntu.sh && ./ci_scripts/lint-ubuntu.sh - name: test ubuntu-latest if: success() || failure() diff --git a/ci_scripts/lint-ubuntu.sh b/ci_scripts/lint-ubuntu.sh index 16d46a2..dcfcfc6 100755 --- a/ci_scripts/lint-ubuntu.sh +++ b/ci_scripts/lint-ubuntu.sh @@ -1,8 +1,8 @@ set -e -cargo install taplo-cli --locked +cargo +nightly fmt -- --check -cargo fmt -- --check +cargo install taplo-cli --locked taplo fmt --check RISC0_SKIP_BUILD=1 cargo clippy --workspace --all-targets -- -D warnings diff --git a/common/src/block.rs b/common/src/block.rs index 456c879..baba1e4 100644 --- a/common/src/block.rs +++ b/common/src/block.rs @@ -6,7 +6,7 @@ use crate::transaction::EncodedTransaction; pub type HashType = [u8; 32]; #[derive(Debug, Clone)] -///Our own hasher. +/// Our own hasher. /// Currently it is SHA256 hasher wrapper. May change in a future. pub struct OwnHasher {} diff --git a/common/src/lib.rs b/common/src/lib.rs index 7976479..b64e6ef 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -4,8 +4,8 @@ pub mod rpc_primitives; pub mod sequencer_client; pub mod transaction; -//Module for tests utility functions -//TODO: Compile only for tests +// Module for tests utility functions +// TODO: Compile only for tests pub mod test_utils; pub type HashType = [u8; 32]; diff --git a/common/src/rpc_primitives/errors.rs b/common/src/rpc_primitives/errors.rs index fc52dd0..1f79981 100644 --- a/common/src/rpc_primitives/errors.rs +++ b/common/src/rpc_primitives/errors.rs @@ -1,6 +1,7 @@ -use serde_json::{Value, to_value}; use std::fmt; +use serde_json::{Value, to_value}; + #[derive(serde::Serialize)] pub struct RpcParseError(pub String); diff --git a/common/src/rpc_primitives/message.rs b/common/src/rpc_primitives/message.rs index e8e4186..8207267 100644 --- a/common/src/rpc_primitives/message.rs +++ b/common/src/rpc_primitives/message.rs @@ -9,11 +9,14 @@ //! //! The main entrypoint here is the [Message](enum.Message.html). The others are just building //! blocks and you should generally work with `Message` instead. -use serde::de::{Deserializer, Error, Unexpected, Visitor}; -use serde::ser::{SerializeStruct, Serializer}; -use serde_json::{Result as JsonResult, Value}; use std::fmt::{Formatter, Result as FmtResult}; +use serde::{ + de::{Deserializer, Error, Unexpected, Visitor}, + ser::{SerializeStruct, Serializer}, +}; +use serde_json::{Result as JsonResult, Value}; + use super::errors::RpcError; #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -69,6 +72,7 @@ impl Request { id: self.id.clone(), }) } + /// Answer the request with an error. pub fn error(&self, error: RpcError) -> Message { Message::Response(Response { @@ -207,6 +211,7 @@ impl Message { id, }) } + /// Create a top-level error (without an ID). pub fn error(error: RpcError) -> Self { Message::Response(Response { @@ -215,6 +220,7 @@ impl Message { id: Value::Null, }) } + /// A constructor for a notification. pub fn notification(method: String, params: Value) -> Self { Message::Notification(Notification { @@ -223,6 +229,7 @@ impl Message { params, }) } + /// A constructor for a response. pub fn response(id: Value, result: Result) -> Self { Message::Response(Response { @@ -231,6 +238,7 @@ impl Message { id, }) } + /// Returns id or Null if there is no id. pub fn id(&self) -> Value { match self { @@ -315,10 +323,7 @@ impl From for Vec { #[cfg(test)] mod tests { - use serde_json::Value; - use serde_json::de::from_slice; - use serde_json::json; - use serde_json::ser::to_vec; + use serde_json::{Value, de::from_slice, json, ser::to_vec}; use super::*; diff --git a/common/src/rpc_primitives/requests.rs b/common/src/rpc_primitives/requests.rs index cb570bc..7149472 100644 --- a/common/src/rpc_primitives/requests.rs +++ b/common/src/rpc_primitives/requests.rs @@ -1,14 +1,15 @@ 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; +use super::{ + errors::RpcParseError, + parser::{RpcRequest, parse_params}, +}; +use crate::parse_request; + #[derive(Serialize, Deserialize, Debug)] pub struct HelloRequest {} diff --git a/common/src/sequencer_client/json.rs b/common/src/sequencer_client/json.rs index 499a47c..d47aea4 100644 --- a/common/src/sequencer_client/json.rs +++ b/common/src/sequencer_client/json.rs @@ -1,13 +1,13 @@ use serde::{Deserialize, Serialize}; -//Requests +// Requests #[derive(Serialize, Deserialize, Debug)] pub struct SendTxRequest { pub transaction: Vec, } -//Responses +// Responses #[derive(Serialize, Deserialize, Debug)] pub struct SendTxResponse { @@ -15,7 +15,7 @@ pub struct SendTxResponse { pub tx_hash: String, } -//General +// General #[derive(Debug, Clone, Serialize)] pub struct SequencerRpcRequest { @@ -31,7 +31,7 @@ impl SequencerRpcRequest { jsonrpc: "2.0".to_string(), method, params: payload, - //ToDo: Correct checking of id + // ToDo: Correct checking of id id: 1, } } diff --git a/common/src/sequencer_client/mod.rs b/common/src/sequencer_client/mod.rs index 0c413d3..a31806e 100644 --- a/common/src/sequencer_client/mod.rs +++ b/common/src/sequencer_client/mod.rs @@ -1,24 +1,26 @@ 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::error::{SequencerClientError, SequencerRpcError}; -use crate::rpc_primitives::requests::{ - GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse, - GetLastBlockRequest, GetLastBlockResponse, GetProgramIdsRequest, GetProgramIdsResponse, - GetProofForCommitmentRequest, GetProofForCommitmentResponse, GetTransactionByHashRequest, - GetTransactionByHashResponse, +use super::rpc_primitives::requests::{ + GetAccountBalanceRequest, GetAccountBalanceResponse, GetBlockDataRequest, GetBlockDataResponse, + GetGenesisIdRequest, GetGenesisIdResponse, GetInitialTestnetAccountsRequest, +}; +use crate::{ + error::{SequencerClientError, SequencerRpcError}, + rpc_primitives::requests::{ + GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse, + GetLastBlockRequest, GetLastBlockResponse, GetProgramIdsRequest, GetProgramIdsResponse, + GetProofForCommitmentRequest, GetProofForCommitmentResponse, GetTransactionByHashRequest, + GetTransactionByHashResponse, + }, + sequencer_client::json::AccountInitialData, + transaction::{EncodedTransaction, NSSATransaction}, }; -use crate::sequencer_client::json::AccountInitialData; -use crate::transaction::{EncodedTransaction, NSSATransaction}; pub mod json; @@ -62,7 +64,7 @@ impl SequencerClient { } } - ///Get block data at `block_id` from sequencer + /// Get block data at `block_id` from sequencer pub async fn get_block( &self, block_id: u64, @@ -78,7 +80,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Get last known `blokc_id` from sequencer + /// Get last known `blokc_id` from sequencer pub async fn get_last_block(&self) -> Result { let block_req = GetLastBlockRequest {}; @@ -91,7 +93,8 @@ impl SequencerClient { Ok(resp_deser) } - ///Get account public balance for `account_id`. `account_id` must be a valid hex-string for 32 bytes. + /// Get account public balance for `account_id`. `account_id` must be a valid hex-string for 32 + /// bytes. pub async fn get_account_balance( &self, account_id: String, @@ -109,7 +112,8 @@ impl SequencerClient { Ok(resp_deser) } - ///Get accounts nonces for `account_ids`. `account_ids` must be a list of valid hex-strings for 32 bytes. + /// Get accounts nonces for `account_ids`. `account_ids` must be a list of valid hex-strings for + /// 32 bytes. pub async fn get_accounts_nonces( &self, account_ids: Vec, @@ -142,7 +146,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Get transaction details for `hash`. + /// Get transaction details for `hash`. pub async fn get_transaction_by_hash( &self, hash: String, @@ -160,7 +164,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Send transaction to sequencer + /// Send transaction to sequencer pub async fn send_tx_public( &self, transaction: nssa::PublicTransaction, @@ -180,7 +184,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Send transaction to sequencer + /// Send transaction to sequencer pub async fn send_tx_private( &self, transaction: nssa::PrivacyPreservingTransaction, @@ -200,7 +204,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Get genesis id from sequencer + /// Get genesis id from sequencer pub async fn get_genesis_id(&self) -> Result { let genesis_req = GetGenesisIdRequest {}; @@ -216,7 +220,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Get initial testnet accounts from sequencer + /// Get initial testnet accounts from sequencer pub async fn get_initial_testnet_accounts( &self, ) -> Result, SequencerClientError> { @@ -234,7 +238,7 @@ impl SequencerClient { Ok(resp_deser) } - ///Get proof for commitment + /// Get proof for commitment pub async fn get_proof_for_commitment( &self, commitment: nssa_core::Commitment, diff --git a/common/src/test_utils.rs b/common/src/test_utils.rs index 1225715..7e3c0ba 100644 --- a/common/src/test_utils.rs +++ b/common/src/test_utils.rs @@ -3,15 +3,15 @@ use crate::{ transaction::{EncodedTransaction, NSSATransaction}, }; -//Helpers +// Helpers pub fn sequencer_sign_key_for_testing() -> nssa::PrivateKey { nssa::PrivateKey::try_new([37; 32]).unwrap() } -//Dummy producers +// Dummy producers -///Produce dummy block with +/// Produce dummy block with /// /// `id` - block id, provide zero for genesis /// diff --git a/common/src/transaction.rs b/common/src/transaction.rs index 1bcf661..372bc95 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -1,7 +1,6 @@ use borsh::{BorshDeserialize, BorshSerialize}; use log::info; use serde::{Deserialize, Serialize}; - use sha2::{Digest, digest::FixedOutput}; pub type HashType = [u8; 32]; @@ -41,10 +40,10 @@ pub enum TxKind { } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] -///General transaction object +/// General transaction object pub struct EncodedTransaction { pub tx_kind: TxKind, - ///Encoded blobs of data + /// Encoded blobs of data pub encoded_transaction_data: Vec, } diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 72062d4..465f986 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -1,8 +1,8 @@ -use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use std::path::PathBuf; use actix_web::dev::ServerHandle; use anyhow::Result; +use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use clap::Parser; use common::{ sequencer_client::SequencerClient, @@ -96,13 +96,13 @@ pub async fn post_test(residual: (ServerHandle, JoinHandle>, TempDir) let wallet_home = wallet::helperfunctions::get_home().unwrap(); let persistent_data_home = wallet_home.join("storage.json"); - //Removing persistent accounts after run to not affect other executions - //Not necessary an error, if fails as there is tests for failure scenario + // Removing persistent accounts after run to not affect other executions + // Not necessary an error, if fails as there is tests for failure scenario let _ = std::fs::remove_file(persistent_data_home) .inspect_err(|err| warn!("Failed to remove persistent data with err {err:#?}")); - //At this point all of the references to sequencer_core must be lost. - //So they are dropped and tempdirs will be dropped too, + // At this point all of the references to sequencer_core must be lost. + // So they are dropped and tempdirs will be dropped too, } pub async fn main_tests_runner() -> Result<()> { diff --git a/integration_tests/src/main.rs b/integration_tests/src/main.rs index 5df600a..583df2a 100644 --- a/integration_tests/src/main.rs +++ b/integration_tests/src/main.rs @@ -1,5 +1,4 @@ use anyhow::Result; - use integration_tests::main_tests_runner; pub const NUM_THREADS: usize = 8; diff --git a/integration_tests/src/test_suite_map.rs b/integration_tests/src/test_suite_map.rs index 0cd4bcf..2fa8e1d 100644 --- a/integration_tests/src/test_suite_map.rs +++ b/integration_tests/src/test_suite_map.rs @@ -1,4 +1,3 @@ -use anyhow::Result; use std::{ collections::HashMap, path::PathBuf, @@ -7,6 +6,7 @@ use std::{ }; use actix_web::dev::ServerHandle; +use anyhow::Result; use common::{PINATA_BASE58, sequencer_client::SequencerClient}; use log::info; use nssa::{AccountId, ProgramDeploymentTransaction, program::Program}; @@ -31,10 +31,10 @@ use crate::{ ACC_RECEIVER, ACC_RECEIVER_PRIVATE, ACC_SENDER, ACC_SENDER_PRIVATE, NSSA_PROGRAM_FOR_TEST_DATA_CHANGER, TIME_TO_WAIT_FOR_BLOCK_SECONDS, fetch_privacy_preserving_tx, make_private_account_input_from_str, - make_public_account_input_from_str, replace_home_dir_with_temp_dir_in_configs, - tps_test_utils::TpsTestManager, + make_public_account_input_from_str, post_test, pre_test, + replace_home_dir_with_temp_dir_in_configs, tps_test_utils::TpsTestManager, + verify_commitment_is_in_state, }; -use crate::{post_test, pre_test, verify_commitment_is_in_state}; type TestFunction = fn(PathBuf) -> Pin>>; @@ -276,8 +276,8 @@ pub fn prepare_function_map() -> HashMap { assert_eq!(account.nonce, 0); } - /// This test creates a new token using the token program. After creating the token, the test executes a - /// token transfer to a new account. + /// This test creates a new token using the token program. After creating the token, the test + /// executes a token transfer to a new account. #[nssa_integration_test] pub async fn test_success_token_program() { info!("########## test_success_token_program ##########"); @@ -364,7 +364,8 @@ pub fn prepare_function_map() -> HashMap { ] ); - // Check the status of the token holding account with the total supply is the expected after the execution + // 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_account_id.to_string()) .await @@ -374,8 +375,8 @@ pub fn prepare_function_map() -> HashMap { // 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 + // [ 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 @@ -403,7 +404,8 @@ pub fn prepare_function_map() -> HashMap { 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_account_id` is the expected after the execution + // Check the status of the account at `supply_account_id` is the expected after the + // execution let supply_acc = seq_client .get_account(supply_account_id.to_string()) .await @@ -420,7 +422,8 @@ pub fn prepare_function_map() -> HashMap { 30 ); - // Check the status of the account at `recipient_account_id` is the expected after the execution + // Check the status of the account at `recipient_account_id` is the expected after the + // execution let recipient_acc = seq_client .get_account(recipient_account_id.to_string()) .await @@ -439,8 +442,9 @@ pub fn prepare_function_map() -> HashMap { ); } - /// 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 except definition. + /// 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 except + /// definition. #[nssa_integration_test] pub async fn test_success_token_program_private_owned() { info!("########## test_success_token_program_private_owned ##########"); @@ -559,7 +563,8 @@ pub fn prepare_function_map() -> HashMap { .unwrap(); assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); - // Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id` + // Transfer additional 7 tokens from `supply_acc` to the account at account_id + // `recipient_account_id` let subcommand = TokenProgramAgnosticSubcommand::Send { from: make_private_account_input_from_str(&supply_account_id.to_string()), to: Some(make_private_account_input_from_str( @@ -593,8 +598,8 @@ pub fn prepare_function_map() -> HashMap { 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. + /// 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. #[nssa_integration_test] pub async fn test_success_token_program_private_claiming_path() { info!("########## test_success_token_program_private_claiming_path ##########"); @@ -728,8 +733,9 @@ pub fn prepare_function_map() -> HashMap { 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. + /// 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. #[nssa_integration_test] pub async fn test_success_token_program_shielded_owned() { info!("########## test_success_token_program_shielded_owned ##########"); @@ -833,7 +839,8 @@ pub fn prepare_function_map() -> HashMap { .unwrap(); assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await); - // Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id` + // Transfer additional 7 tokens from `supply_acc` to the account at account_id + // `recipient_account_id` let subcommand = TokenProgramAgnosticSubcommand::Send { from: make_public_account_input_from_str(&supply_account_id.to_string()), to: Some(make_private_account_input_from_str( @@ -862,8 +869,9 @@ pub fn prepare_function_map() -> HashMap { 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. + /// 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. #[nssa_integration_test] pub async fn test_success_token_program_deshielded_owned() { info!("########## test_success_token_program_deshielded_owned ##########"); @@ -977,7 +985,8 @@ pub fn prepare_function_map() -> HashMap { .unwrap(); assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await); - // Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id` + // Transfer additional 7 tokens from `supply_acc` to the account at account_id + // `recipient_account_id` let subcommand = TokenProgramAgnosticSubcommand::Send { from: make_private_account_input_from_str(&supply_account_id.to_string()), to: Some(make_public_account_input_from_str( @@ -1157,75 +1166,75 @@ pub fn prepare_function_map() -> HashMap { info!("Success!"); } - #[nssa_integration_test] - pub async fn test_success_private_transfer_to_another_owned_account_cont_run_path() { - info!( - "########## test_success_private_transfer_to_another_owned_account_cont_run_path ##########" - ); - let continious_run_handle = tokio::spawn(wallet::execute_continious_run()); + // #[nssa_integration_test] + // pub async fn test_success_private_transfer_to_another_owned_account_cont_run_path() { + // info!( + // "########## test_success_private_transfer_to_another_owned_account_cont_run_path ##########" + // ); + // let continious_run_handle = tokio::spawn(wallet::execute_continious_run()); - let from: AccountId = ACC_SENDER_PRIVATE.parse().unwrap(); + // let from: AccountId = ACC_SENDER_PRIVATE.parse().unwrap(); - let command = Command::Account(AccountSubcommand::New(NewSubcommand::Private {})); + // let command = Command::Account(AccountSubcommand::New(NewSubcommand::Private {})); - let sub_ret = wallet::execute_subcommand(command).await.unwrap(); - let SubcommandReturnValue::RegisterAccount { - account_id: to_account_id, - } = sub_ret - else { - panic!("FAILED TO REGISTER ACCOUNT"); - }; + // let sub_ret = wallet::execute_subcommand(command).await.unwrap(); + // let SubcommandReturnValue::RegisterAccount { + // account_id: to_account_id, + // } = sub_ret + // else { + // panic!("FAILED TO REGISTER ACCOUNT"); + // }; - let wallet_config = fetch_config().await.unwrap(); - let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); - let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config.clone()) - .await - .unwrap(); + // let wallet_config = fetch_config().await.unwrap(); + // let seq_client = SequencerClient::new(wallet_config.sequencer_addr.clone()).unwrap(); + // let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config.clone()) + // .await + // .unwrap(); - let (to_keys, _) = wallet_storage - .storage - .user_data - .user_private_accounts - .get(&to_account_id) - .cloned() - .unwrap(); + // let (to_keys, _) = wallet_storage + // .storage + // .user_data + // .user_private_accounts + // .get(&to_account_id) + // .cloned() + // .unwrap(); - let command = Command::AuthTransfer(AuthTransferSubcommand::Send { - from: make_private_account_input_from_str(&from.to_string()), - to: None, - to_npk: Some(hex::encode(to_keys.nullifer_public_key.0)), - to_ipk: Some(hex::encode(to_keys.incoming_viewing_public_key.0)), - amount: 100, - }); + // let command = Command::AuthTransfer(AuthTransferSubcommand::Send { + // from: make_private_account_input_from_str(&from.to_string()), + // to: None, + // to_npk: Some(hex::encode(to_keys.nullifer_public_key.0)), + // to_ipk: Some(hex::encode(to_keys.incoming_viewing_public_key.0)), + // amount: 100, + // }); - let sub_ret = wallet::execute_subcommand(command).await.unwrap(); - let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = sub_ret else { - panic!("FAILED TO SEND TX"); - }; + // let sub_ret = wallet::execute_subcommand(command).await.unwrap(); + // let SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash } = sub_ret else { + // panic!("FAILED TO SEND TX"); + // }; - let tx = fetch_privacy_preserving_tx(&seq_client, tx_hash.clone()).await; + // let tx = fetch_privacy_preserving_tx(&seq_client, tx_hash.clone()).await; - println!("Waiting for next blocks to check if continoius run fetch account"); - tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + // println!("Waiting for next blocks to check if continoius run fetch account"); + // tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; + // tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await; - let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config) - .await - .unwrap(); + // let wallet_storage = WalletCore::start_from_config_update_chain(wallet_config) + // .await + // .unwrap(); - assert_eq!(tx.message.new_commitments.len(), 2); - for commitment in tx.message.new_commitments.into_iter() { - assert!(verify_commitment_is_in_state(commitment, &seq_client).await); - } + // assert_eq!(tx.message.new_commitments.len(), 2); + // for commitment in tx.message.new_commitments.into_iter() { + // assert!(verify_commitment_is_in_state(commitment, &seq_client).await); + // } - let to_res_acc = wallet_storage.get_account_private(&to_account_id).unwrap(); + // let to_res_acc = wallet_storage.get_account_private(&to_account_id).unwrap(); - assert_eq!(to_res_acc.balance, 100); + // assert_eq!(to_res_acc.balance, 100); - continious_run_handle.abort(); + // continious_run_handle.abort(); - info!("Success!"); - } + // info!("Success!"); + // } #[nssa_integration_test] pub async fn test_success_deshielded_transfer_to_another_account() { @@ -1425,7 +1434,8 @@ pub fn prepare_function_map() -> HashMap { // The program is the data changer and takes one account as input. // We pass an uninitialized account and we expect after execution to be owned by the data - // changer program (NSSA account claiming mechanism) with data equal to [0] (due to program logic) + // changer program (NSSA account claiming mechanism) with data equal to [0] (due to program + // logic) let data_changer = Program::new(bytecode).unwrap(); let account_id: AccountId = "11".repeat(16).parse().unwrap(); let message = nssa::public_transaction::Message::try_new( @@ -1617,7 +1627,7 @@ pub fn prepare_function_map() -> HashMap { let wallet_config = fetch_config().await.unwrap(); let old_seq_poll_retry_delay_millis = wallet_config.seq_poll_retry_delay_millis; - //Change config field + // Change config field let command = Command::Config(ConfigSubcommand::Set { key: "seq_poll_retry_delay_millis".to_string(), value: "1000".to_string(), @@ -1628,7 +1638,7 @@ pub fn prepare_function_map() -> HashMap { assert_eq!(wallet_config.seq_poll_retry_delay_millis, 1000); - //Return how it was at the beginning + // Return how it was at the beginning let command = Command::Config(ConfigSubcommand::Set { key: "seq_poll_retry_delay_millis".to_string(), value: old_seq_poll_retry_delay_millis.to_string(), diff --git a/integration_tests/src/tps_test_utils.rs b/integration_tests/src/tps_test_utils.rs index d625d17..d06a08f 100644 --- a/integration_tests/src/tps_test_utils.rs +++ b/integration_tests/src/tps_test_utils.rs @@ -19,8 +19,8 @@ pub(crate) struct TpsTestManager { } impl TpsTestManager { - /// Generates public account keypairs. These are used to populate the config and to generate valid - /// public transactions for the tps test. + /// Generates public account keypairs. These are used to populate the config and to generate + /// valid public transactions for the tps test. pub(crate) fn new(target_tps: u64, number_transactions: usize) -> Self { let public_keypairs = (1..(number_transactions + 2)) .map(|i| { @@ -43,7 +43,6 @@ impl TpsTestManager { Duration::from_secs_f64(number_transactions as f64 / self.target_tps as f64) } - /// /// Build a batch of public transactions to submit to the node. pub fn build_public_txs(&self) -> Vec { // Create valid public transactions @@ -70,8 +69,8 @@ impl TpsTestManager { } /// Generates a sequencer configuration with initial balance in a number of public accounts. - /// The transactions generated with the function `build_public_txs` will be valid in a node started - /// with the config from this method. + /// The transactions generated with the function `build_public_txs` will be valid in a node + /// started with the config from this method. pub(crate) fn generate_tps_test_config(&self) -> SequencerConfig { // Create public public keypairs let initial_public_accounts = self diff --git a/key_protocol/src/key_management/ephemeral_key_holder.rs b/key_protocol/src/key_management/ephemeral_key_holder.rs index 4d4fe9d..7a84ec5 100644 --- a/key_protocol/src/key_management/ephemeral_key_holder.rs +++ b/key_protocol/src/key_management/ephemeral_key_holder.rs @@ -6,7 +6,8 @@ use rand::{RngCore, rngs::OsRng}; use sha2::Digest; #[derive(Debug)] -///Ephemeral secret key holder. Non-clonable as intended for one-time use. Produces ephemeral public keys. Can produce shared secret for sender. +/// Ephemeral secret key holder. Non-clonable as intended for one-time use. Produces ephemeral +/// public keys. Can produce shared secret for sender. pub struct EphemeralKeyHolder { ephemeral_secret_key: EphemeralSecretKey, } diff --git a/key_protocol/src/key_management/mod.rs b/key_protocol/src/key_management/mod.rs index dd6908d..574f5f6 100644 --- a/key_protocol/src/key_management/mod.rs +++ b/key_protocol/src/key_management/mod.rs @@ -11,7 +11,7 @@ pub mod ephemeral_key_holder; pub mod secret_holders; #[derive(Serialize, Deserialize, Clone, Debug)] -///Entrypoint to key management +/// Entrypoint to key management pub struct KeyChain { secret_spending_key: SecretSpendingKey, pub private_key_holder: PrivateKeyHolder, @@ -21,8 +21,8 @@ pub struct KeyChain { impl KeyChain { pub fn new_os_random() -> Self { - //Currently dropping SeedHolder at the end of initialization. - //Now entirely sure if we need it in the future. + // Currently dropping SeedHolder at the end of initialization. + // Now entirely sure if we need it in the future. let seed_holder = SeedHolder::new_os_random(); let secret_spending_key = seed_holder.produce_top_secret_key_holder(); @@ -56,8 +56,7 @@ impl KeyChain { mod tests { use aes_gcm::aead::OsRng; use base58::ToBase58; - use k256::AffinePoint; - use k256::elliptic_curve::group::GroupEncoding; + use k256::{AffinePoint, elliptic_curve::group::GroupEncoding}; use rand::RngCore; use super::*; diff --git a/key_protocol/src/key_management/secret_holders.rs b/key_protocol/src/key_management/secret_holders.rs index 44016bb..4ac815d 100644 --- a/key_protocol/src/key_management/secret_holders.rs +++ b/key_protocol/src/key_management/secret_holders.rs @@ -9,22 +9,23 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, digest::FixedOutput}; #[derive(Debug)] -///Seed holder. Non-clonable to ensure that different holders use different seeds. +/// Seed holder. Non-clonable to ensure that different holders use different seeds. /// Produces `TopSecretKeyHolder` objects. pub struct SeedHolder { - //ToDo: Needs to be vec as serde derives is not implemented for [u8; 64] + // ToDo: Needs to be vec as serde derives is not implemented for [u8; 64] pub(crate) seed: Vec, } #[derive(Serialize, Deserialize, Debug, Clone)] -///Secret spending key object. Can produce `PrivateKeyHolder` objects. +/// Secret spending key object. Can produce `PrivateKeyHolder` objects. pub struct SecretSpendingKey(pub(crate) [u8; 32]); pub type IncomingViewingSecretKey = Scalar; pub type OutgoingViewingSecretKey = Scalar; #[derive(Serialize, Deserialize, Debug, Clone)] -///Private key holder. Produces public keys. Can produce account_id. Can produce shared secret for recepient. +/// Private key holder. Produces public keys. Can produce account_id. Can produce shared secret for +/// recepient. pub struct PrivateKeyHolder { pub nullifier_secret_key: NullifierSecretKey, pub(crate) incoming_viewing_secret_key: IncomingViewingSecretKey, @@ -51,7 +52,7 @@ impl SeedHolder { hash = hmac_sha512::HMAC::mac(hash, "NSSA_seed"); } - //Safe unwrap + // Safe unwrap *hash.first_chunk::<32>().unwrap() } diff --git a/key_protocol/src/key_protocol_core/mod.rs b/key_protocol/src/key_protocol_core/mod.rs index 031adbd..ad25545 100644 --- a/key_protocol/src/key_protocol_core/mod.rs +++ b/key_protocol/src/key_protocol_core/mod.rs @@ -10,9 +10,9 @@ pub type PublicKey = AffinePoint; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct NSSAUserData { - ///Map for all user public accounts + /// Map for all user public accounts pub pub_account_signing_keys: HashMap, - ///Map for all user private accounts + /// Map for all user private accounts pub user_private_accounts: HashMap, } @@ -124,7 +124,7 @@ impl NSSAUserData { impl Default for NSSAUserData { fn default() -> Self { - //Safe unwrap as maps are empty + // Safe unwrap as maps are empty Self::new_with_accounts(HashMap::default(), HashMap::default()).unwrap() } } diff --git a/mempool/src/lib.rs b/mempool/src/lib.rs index 8fb87dc..ff6163f 100644 --- a/mempool/src/lib.rs +++ b/mempool/src/lib.rs @@ -43,10 +43,10 @@ impl MemPoolHandle { #[cfg(test)] mod tests { - use super::*; - use tokio::test; + use super::*; + #[test] async fn test_mempool_new() { let (mut pool, _handle): (MemPool, _) = MemPool::new(10); diff --git a/nssa/core/src/account.rs b/nssa/core/src/account.rs index d6160fa..e767e1e 100644 --- a/nssa/core/src/account.rs +++ b/nssa/core/src/account.rs @@ -102,9 +102,8 @@ impl Display for AccountId { #[cfg(test)] mod tests { - use crate::program::DEFAULT_PROGRAM_ID; - use super::*; + use crate::program::DEFAULT_PROGRAM_ID; #[test] fn test_zero_balance_account_data_creation() { diff --git a/nssa/core/src/circuit_io.rs b/nssa/core/src/circuit_io.rs index 6370dc6..e1afe10 100644 --- a/nssa/core/src/circuit_io.rs +++ b/nssa/core/src/circuit_io.rs @@ -38,12 +38,13 @@ impl PrivacyPreservingCircuitOutput { #[cfg(feature = "host")] #[cfg(test)] mod tests { + use risc0_zkvm::serde::from_slice; + use super::*; use crate::{ Commitment, Nullifier, NullifierPublicKey, account::{Account, AccountId, AccountWithMetadata}, }; - use risc0_zkvm::serde::from_slice; #[test] fn test_privacy_preserving_circuit_output_to_bytes_is_compatible_with_from_slice() { diff --git a/nssa/core/src/encoding.rs b/nssa/core/src/encoding.rs index 59844d3..3a8a128 100644 --- a/nssa/core/src/encoding.rs +++ b/nssa/core/src/encoding.rs @@ -1,25 +1,20 @@ // TODO: Consider switching to deriving Borsh #[cfg(feature = "host")] use std::io::Cursor; - #[cfg(feature = "host")] use std::io::Read; -use crate::account::Account; - -use crate::account::AccountId; -#[cfg(feature = "host")] -use crate::encryption::shared_key_derivation::Secp256k1Point; - -use crate::encryption::Ciphertext; - -#[cfg(feature = "host")] -use crate::error::NssaCoreError; - -use crate::Commitment; #[cfg(feature = "host")] use crate::Nullifier; -use crate::NullifierPublicKey; +#[cfg(feature = "host")] +use crate::encryption::shared_key_derivation::Secp256k1Point; +#[cfg(feature = "host")] +use crate::error::NssaCoreError; +use crate::{ + Commitment, NullifierPublicKey, + account::{Account, AccountId}, + encryption::Ciphertext, +}; impl Account { pub fn to_bytes(&self) -> Vec { @@ -55,7 +50,7 @@ impl Account { cursor.read_exact(&mut u128_bytes)?; let nonce = u128::from_le_bytes(u128_bytes); - //data + // data cursor.read_exact(&mut u32_bytes)?; let data_length = u32::from_le_bytes(u32_bytes); let mut data = vec![0; data_length as usize]; diff --git a/nssa/core/src/encryption/shared_key_derivation.rs b/nssa/core/src/encryption/shared_key_derivation.rs index 2a05c85..7349d70 100644 --- a/nssa/core/src/encryption/shared_key_derivation.rs +++ b/nssa/core/src/encryption/shared_key_derivation.rs @@ -1,5 +1,4 @@ use borsh::{BorshDeserialize, BorshSerialize}; -use serde::{Deserialize, Serialize}; use k256::{ AffinePoint, EncodedPoint, FieldBytes, ProjectivePoint, @@ -8,6 +7,7 @@ use k256::{ sec1::{FromEncodedPoint, ToEncodedPoint}, }, }; +use serde::{Deserialize, Serialize}; use crate::{SharedSecretKey, encryption::Scalar}; diff --git a/nssa/core/src/program.rs b/nssa/core/src/program.rs index 3ecee30..66a957c 100644 --- a/nssa/core/src/program.rs +++ b/nssa/core/src/program.rs @@ -1,8 +1,8 @@ -use crate::account::{Account, AccountWithMetadata}; -use risc0_zkvm::serde::Deserializer; -use risc0_zkvm::{DeserializeOwned, guest::env}; +use risc0_zkvm::{DeserializeOwned, guest::env, serde::Deserializer}; use serde::{Deserialize, Serialize}; +use crate::account::{Account, AccountWithMetadata}; + pub type ProgramId = [u32; 8]; pub type InstructionData = Vec; pub const DEFAULT_PROGRAM_ID: ProgramId = [0; 8]; @@ -103,7 +103,8 @@ pub fn validate_execution( return false; } - // 6. If a post state has default program owner, the pre state must have been a default account + // 6. If a post state has default program owner, the pre state must have been a default + // account if post.program_owner == DEFAULT_PROGRAM_ID && pre.account != Account::default() { return false; } diff --git a/nssa/src/lib.rs b/nssa/src/lib.rs index 1907790..b698ae3 100644 --- a/nssa/src/lib.rs +++ b/nssa/src/lib.rs @@ -24,7 +24,5 @@ pub use privacy_preserving_transaction::{ pub use program_deployment_transaction::ProgramDeploymentTransaction; pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID; pub use public_transaction::PublicTransaction; -pub use signature::PrivateKey; -pub use signature::PublicKey; -pub use signature::Signature; +pub use signature::{PrivateKey, PublicKey, Signature}; pub use state::V02State; diff --git a/nssa/src/merkle_tree/mod.rs b/nssa/src/merkle_tree/mod.rs index 7b30d78..c4501cf 100644 --- a/nssa/src/merkle_tree/mod.rs +++ b/nssa/src/merkle_tree/mod.rs @@ -43,6 +43,7 @@ impl MerkleTree { (1 << (capacity_depth - tree_depth)) - 1 } } + /// Number of levels required to hold all nodes fn depth(&self) -> usize { self.length.next_power_of_two().trailing_zeros() as usize diff --git a/nssa/src/privacy_preserving_transaction/circuit.rs b/nssa/src/privacy_preserving_transaction/circuit.rs index 0962ee3..eeba692 100644 --- a/nssa/src/privacy_preserving_transaction/circuit.rs +++ b/nssa/src/privacy_preserving_transaction/circuit.rs @@ -7,9 +7,11 @@ use nssa_core::{ }; use risc0_zkvm::{ExecutorEnv, InnerReceipt, Receipt, default_prover}; -use crate::{error::NssaError, program::Program}; - -use crate::program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID}; +use crate::{ + error::NssaError, + program::Program, + program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID}, +}; /// Proof of the privacy preserving execution circuit #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] @@ -96,6 +98,7 @@ mod tests { account::{Account, AccountId, AccountWithMetadata}, }; + use super::*; use crate::{ privacy_preserving_transaction::circuit::execute_and_prove, program::Program, @@ -105,8 +108,6 @@ mod tests { }, }; - use super::*; - #[test] fn prove_privacy_preserving_execution_circuit_public_and_private_pre_accounts() { let recipient_keys = test_private_account_keys_1(); diff --git a/nssa/src/privacy_preserving_transaction/transaction.rs b/nssa/src/privacy_preserving_transaction/transaction.rs index 78484cc..2cb0889 100644 --- a/nssa/src/privacy_preserving_transaction/transaction.rs +++ b/nssa/src/privacy_preserving_transaction/transaction.rs @@ -6,13 +6,12 @@ use nssa_core::{ account::{Account, AccountWithMetadata}, }; -use crate::error::NssaError; -use crate::privacy_preserving_transaction::circuit::Proof; -use crate::privacy_preserving_transaction::message::EncryptedAccountData; -use crate::{AccountId, V02State}; - -use super::message::Message; -use super::witness_set::WitnessSet; +use super::{message::Message, witness_set::WitnessSet}; +use crate::{ + AccountId, V02State, + error::NssaError, + privacy_preserving_transaction::{circuit::Proof, message::EncryptedAccountData}, +}; #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] pub struct PrivacyPreservingTransaction { diff --git a/nssa/src/program.rs b/nssa/src/program.rs index 11eb413..d3f28b5 100644 --- a/nssa/src/program.rs +++ b/nssa/src/program.rs @@ -1,13 +1,14 @@ -use crate::program_methods::{AUTHENTICATED_TRANSFER_ELF, PINATA_ELF, TOKEN_ELF}; use nssa_core::{ account::AccountWithMetadata, program::{InstructionData, ProgramId, ProgramOutput}, }; - use risc0_zkvm::{ExecutorEnv, ExecutorEnvBuilder, default_executor, serde::to_vec}; use serde::Serialize; -use crate::error::NssaError; +use crate::{ + error::NssaError, + program_methods::{AUTHENTICATED_TRANSFER_ELF, PINATA_ELF, TOKEN_ELF}, +}; /// Maximum number of cycles for a public execution. /// TODO: Make this variable when fees are implemented @@ -107,13 +108,15 @@ impl Program { #[cfg(test)] mod tests { - use crate::program_methods::{ - AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, TOKEN_ELF, - TOKEN_ID, - }; use nssa_core::account::{Account, AccountId, AccountWithMetadata}; - use crate::program::Program; + use crate::{ + program::Program, + program_methods::{ + AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, + TOKEN_ELF, TOKEN_ID, + }, + }; impl Program { /// A program that changes the nonce of an account diff --git a/nssa/src/public_transaction/witness_set.rs b/nssa/src/public_transaction/witness_set.rs index 6a2a128..09a35a4 100644 --- a/nssa/src/public_transaction/witness_set.rs +++ b/nssa/src/public_transaction/witness_set.rs @@ -41,9 +41,8 @@ impl WitnessSet { #[cfg(test)] mod tests { - use crate::AccountId; - use super::*; + use crate::AccountId; #[test] fn test_for_message_constructor() { diff --git a/nssa/src/signature/mod.rs b/nssa/src/signature/mod.rs index 1081d9c..780ad63 100644 --- a/nssa/src/signature/mod.rs +++ b/nssa/src/signature/mod.rs @@ -4,7 +4,6 @@ mod public_key; use borsh::{BorshDeserialize, BorshSerialize}; pub use private_key::PrivateKey; pub use public_key::PublicKey; - use rand::{RngCore, rngs::OsRng}; #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] diff --git a/nssa/src/signature/public_key.rs b/nssa/src/signature/public_key.rs index c1246bb..4cf30fa 100644 --- a/nssa/src/signature/public_key.rs +++ b/nssa/src/signature/public_key.rs @@ -1,10 +1,9 @@ use borsh::{BorshDeserialize, BorshSerialize}; use nssa_core::account::AccountId; +use sha2::{Digest, Sha256}; use crate::{PrivateKey, error::NssaError}; -use sha2::{Digest, Sha256}; - #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize)] pub struct PublicKey([u8; 32]); diff --git a/nssa/src/state.rs b/nssa/src/state.rs index 4c7dad3..26e0e18 100644 --- a/nssa/src/state.rs +++ b/nssa/src/state.rs @@ -1,14 +1,17 @@ +use std::collections::{HashMap, HashSet}; + +use nssa_core::{ + Commitment, CommitmentSetDigest, DUMMY_COMMITMENT, MembershipProof, Nullifier, + account::{Account, AccountId}, + program::ProgramId, +}; + use crate::{ error::NssaError, merkle_tree::MerkleTree, privacy_preserving_transaction::PrivacyPreservingTransaction, program::Program, program_deployment_transaction::ProgramDeploymentTransaction, public_transaction::PublicTransaction, }; -use nssa_core::{ - Commitment, CommitmentSetDigest, DUMMY_COMMITMENT, MembershipProof, Nullifier, - account::Account, account::AccountId, program::ProgramId, -}; -use std::collections::{HashMap, HashSet}; pub(crate) struct CommitmentSet { merkle_tree: MerkleTree, @@ -241,6 +244,13 @@ pub mod tests { use std::collections::HashMap; + use nssa_core::{ + Commitment, Nullifier, NullifierPublicKey, NullifierSecretKey, SharedSecretKey, + account::{Account, AccountId, AccountWithMetadata, Nonce}, + encryption::{EphemeralPublicKey, IncomingViewingPublicKey, Scalar}, + program::ProgramId, + }; + use crate::{ PublicKey, PublicTransaction, V02State, error::NssaError, @@ -253,13 +263,6 @@ pub mod tests { signature::PrivateKey, }; - use nssa_core::{ - Commitment, Nullifier, NullifierPublicKey, NullifierSecretKey, SharedSecretKey, - account::{Account, AccountId, AccountWithMetadata, Nonce}, - encryption::{EphemeralPublicKey, IncomingViewingPublicKey, Scalar}, - program::ProgramId, - }; - fn transfer_transaction( from: AccountId, from_key: PrivateKey, @@ -577,7 +580,8 @@ pub mod tests { V02State::new_with_genesis_accounts(&initial_data, &[]).with_test_programs(); let account_id = AccountId::new([1; 32]); let account = state.get_account_by_id(&account_id); - // Assert the target account only differs from the default account in the program owner field + // Assert the target account only differs from the default account in the program owner + // field assert_ne!(account.program_owner, Account::default().program_owner); assert_eq!(account.balance, Account::default().balance); assert_eq!(account.nonce, Account::default().nonce); @@ -2103,7 +2107,7 @@ pub mod tests { let message = public_transaction::Message::try_new( program.id(), - vec![to, from], //The chain_caller program permutes the account order in the chain call + vec![to, from], // The chain_caller program permutes the account order in the call vec![0], instruction, ) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 5d56faf..3ec291c 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,3 @@ [toolchain] -channel = "nightly" +channel = "1.91.1" +profile = "default" diff --git a/rustfmt.toml b/rustfmt.toml index f216078..369ddfb 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1 +1,12 @@ edition = "2024" + +newline_style = "Unix" +use_field_init_shorthand = true +use_try_shorthand = true +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +normalize_comments = true +reorder_impl_items = true +wrap_comments = true +comment_width = 100 +format_code_in_doc_comments = true diff --git a/sequencer_core/src/block_store.rs b/sequencer_core/src/block_store.rs index 83a94b3..6753502 100644 --- a/sequencer_core/src/block_store.rs +++ b/sequencer_core/src/block_store.rs @@ -13,7 +13,7 @@ pub struct SequencerBlockStore { } impl SequencerBlockStore { - ///Starting database at the start of new chain. + /// Starting database at the start of new chain. /// Creates files if necessary. /// /// ATTENTION: Will overwrite genesis block. @@ -40,7 +40,7 @@ impl SequencerBlockStore { }) } - ///Reopening existing database + /// Reopening existing database pub fn open_db_restart(location: &Path, signing_key: nssa::PrivateKey) -> Result { SequencerBlockStore::open_db_with_genesis(location, None, signing_key) } @@ -94,11 +94,11 @@ pub(crate) fn block_to_transactions_map(block: &Block) -> HashMap #[cfg(test)] mod tests { - use super::*; - use common::{block::HashableBlockData, test_utils::sequencer_sign_key_for_testing}; use tempfile::tempdir; + use super::*; + #[test] fn test_get_transaction_by_hash() { let temp_dir = tempdir().unwrap(); diff --git a/sequencer_core/src/config.rs b/sequencer_core/src/config.rs index d719f4b..2f4ee3b 100644 --- a/sequencer_core/src/config.rs +++ b/sequencer_core/src/config.rs @@ -1,8 +1,9 @@ -use serde::{Deserialize, Serialize}; use std::path::PathBuf; +use serde::{Deserialize, Serialize}; + #[derive(Debug, Serialize, Deserialize, Clone)] -///Helperstruct for account serialization +/// Helperstruct for account serialization pub struct AccountInitialData { /// Hex encoded account id pub account_id: String, @@ -19,26 +20,26 @@ pub struct CommitmentsInitialData { // TODO: Provide default values #[derive(Clone, Serialize, Deserialize)] pub struct SequencerConfig { - ///Home dir of sequencer storage + /// Home dir of sequencer storage pub home: PathBuf, - ///Override rust log (env var logging level) + /// Override rust log (env var logging level) pub override_rust_log: Option, - ///Genesis id + /// Genesis id pub genesis_id: u64, - ///If `True`, then adds random sequence of bytes to genesis block + /// If `True`, then adds random sequence of bytes to genesis block pub is_genesis_random: bool, - ///Maximum number of transactions in block + /// Maximum number of transactions in block pub max_num_tx_in_block: usize, - ///Mempool maximum size + /// Mempool maximum size pub mempool_max_size: usize, - ///Interval in which blocks produced + /// Interval in which blocks produced pub block_create_timeout_millis: u64, - ///Port to listen + /// Port to listen pub port: u16, - ///List of initial accounts data + /// List of initial accounts data pub initial_accounts: Vec, - ///List of initial commitments + /// List of initial commitments pub initial_commitments: Vec, - ///Sequencer own signing key + /// Sequencer own signing key pub signing_key: [u8; 32], } diff --git a/sequencer_core/src/lib.rs b/sequencer_core/src/lib.rs index b792ecd..8e193ff 100644 --- a/sequencer_core/src/lib.rs +++ b/sequencer_core/src/lib.rs @@ -53,8 +53,8 @@ impl SequencerCore { let signing_key = nssa::PrivateKey::try_new(config.signing_key).unwrap(); let genesis_block = hashable_data.into_block(&signing_key); - //Sequencer should panic if unable to open db, - //as fixing this issue may require actions non-native to program scope + // Sequencer should panic if unable to open db, + // as fixing this issue may require actions non-native to program scope let block_store = SequencerBlockStore::open_db_with_genesis( &config.home.join("rocksdb"), Some(genesis_block), @@ -100,8 +100,9 @@ impl SequencerCore { (this, mempool_handle) } - /// If there are stored blocks ahead of the current height, this method will load and process all transaction - /// in them in the order they are stored. The NSSA state will be updated accordingly. + /// If there are stored blocks ahead of the current height, this method will load and process + /// all transaction in them in the order they are stored. The NSSA state will be updated + /// accordingly. fn sync_state_with_stored_blocks(&mut self) { let mut next_block_id = self.sequencer_config.genesis_id + 1; while let Ok(block) = self.block_store.get_block_at_id(next_block_id) { @@ -181,10 +182,15 @@ impl SequencerCore { self.chain_height = new_block_height; - // TODO: Consider switching to `tracing` crate to have more structured and consistent logs e.g. + // TODO: Consider switching to `tracing` crate to have more structured and consistent logs + // e.g. // // ``` - // info!(num_txs = num_txs_in_block, time = now.elapsed(), "Created block"); + // info!( + // num_txs = num_txs_in_block, + // time = now.elapsed(), + // "Created block" + // ); // ``` log::info!( "Created block with {} transactions in {} seconds", @@ -244,9 +250,8 @@ mod tests { use common::test_utils::sequencer_sign_key_for_testing; use nssa::PrivateKey; - use crate::config::AccountInitialData; - use super::*; + use crate::config::AccountInitialData; fn parse_unwrap_tx_body_into_nssa_tx(tx_body: EncodedTransaction) -> NSSATransaction { NSSATransaction::try_from(&tx_body) diff --git a/sequencer_rpc/src/lib.rs b/sequencer_rpc/src/lib.rs index 40d5b16..89b3e8c 100644 --- a/sequencer_rpc/src/lib.rs +++ b/sequencer_rpc/src/lib.rs @@ -9,16 +9,15 @@ use common::{ transaction::EncodedTransaction, }; use mempool::MemPoolHandle; +pub use net_utils::*; use sequencer_core::SequencerCore; use serde::Serialize; use serde_json::Value; - -pub use net_utils::*; use tokio::sync::Mutex; use self::types::err_rpc::RpcErr; -//ToDo: Add necessary fields +// ToDo: Add necessary fields pub struct JsonHandler { sequencer_state: Arc>, mempool_handle: MemPoolHandle, diff --git a/sequencer_rpc/src/net_utils.rs b/sequencer_rpc/src/net_utils.rs index 6ec4b70..33eacae 100644 --- a/sequencer_rpc/src/net_utils.rs +++ b/sequencer_rpc/src/net_utils.rs @@ -1,15 +1,13 @@ -use std::io; -use std::sync::Arc; +use std::{io, sync::Arc}; use actix_cors::Cors; use actix_web::{App, Error as HttpError, HttpResponse, HttpServer, http, middleware, web}; -use common::transaction::EncodedTransaction; -use futures::Future; -use futures::FutureExt; +use common::{ + rpc_primitives::{RpcConfig, message::Message}, + transaction::EncodedTransaction, +}; +use futures::{Future, FutureExt}; use log::info; - -use common::rpc_primitives::RpcConfig; -use common::rpc_primitives::message::Message; use mempool::MemPoolHandle; use sequencer_core::SequencerCore; use tokio::sync::Mutex; diff --git a/sequencer_rpc/src/process.rs b/sequencer_rpc/src/process.rs index 528554e..23d5edd 100644 --- a/sequencer_rpc/src/process.rs +++ b/sequencer_rpc/src/process.rs @@ -3,11 +3,6 @@ use std::collections::HashMap; use actix_web::Error as HttpError; use base58::FromBase58; use base64::{Engine, engine::general_purpose}; -use log::warn; -use nssa::{self, program::Program}; -use sequencer_core::{TransactionMalformationError, config::AccountInitialData}; -use serde_json::Value; - use common::{ HashType, block::HashableBlockData, @@ -18,19 +13,20 @@ use common::{ requests::{ GetAccountBalanceRequest, GetAccountBalanceResponse, GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse, - GetInitialTestnetAccountsRequest, GetProgramIdsRequest, GetProgramIdsResponse, - GetProofForCommitmentRequest, GetProofForCommitmentResponse, - GetTransactionByHashRequest, GetTransactionByHashResponse, + GetBlockDataRequest, GetBlockDataResponse, GetGenesisIdRequest, GetGenesisIdResponse, + GetInitialTestnetAccountsRequest, GetLastBlockRequest, GetLastBlockResponse, + GetProgramIdsRequest, GetProgramIdsResponse, GetProofForCommitmentRequest, + GetProofForCommitmentResponse, GetTransactionByHashRequest, + GetTransactionByHashResponse, HelloRequest, HelloResponse, SendTxRequest, + SendTxResponse, }, }, transaction::{EncodedTransaction, NSSATransaction}, }; - -use common::rpc_primitives::requests::{ - GetBlockDataRequest, GetBlockDataResponse, GetGenesisIdRequest, GetGenesisIdResponse, - GetLastBlockRequest, GetLastBlockResponse, HelloRequest, HelloResponse, SendTxRequest, - SendTxResponse, -}; +use log::warn; +use nssa::{self, program::Program}; +use sequencer_core::{TransactionMalformationError, config::AccountInitialData}; +use serde_json::Value; use super::{JsonHandler, respond, types::err_rpc::RpcErr}; @@ -91,7 +87,8 @@ impl JsonHandler { let authenticated_tx = sequencer_core::transaction_pre_check(transaction) .inspect_err(|err| warn!("Error at pre_check {err:#?}"))?; - // TODO: Do we need a timeout here? It will be usable if we have too many transactions to process + // TODO: Do we need a timeout here? It will be usable if we have too many transactions to + // process self.mempool_handle .push(authenticated_tx.into()) .await @@ -318,11 +315,9 @@ impl JsonHandler { mod tests { use std::sync::Arc; - use crate::{JsonHandler, rpc_handler}; use base58::ToBase58; use base64::{Engine, engine::general_purpose}; use common::{test_utils::sequencer_sign_key_for_testing, transaction::EncodedTransaction}; - use sequencer_core::{ SequencerCore, config::{AccountInitialData, SequencerConfig}, @@ -331,6 +326,8 @@ mod tests { use tempfile::tempdir; use tokio::sync::Mutex; + use crate::{JsonHandler, rpc_handler}; + fn sequencer_config_for_tests() -> SequencerConfig { let tempdir = tempdir().unwrap(); let home = tempdir.path().to_path_buf(); diff --git a/sequencer_rpc/src/types/err_rpc.rs b/sequencer_rpc/src/types/err_rpc.rs index d217571..14807d5 100644 --- a/sequencer_rpc/src/types/err_rpc.rs +++ b/sequencer_rpc/src/types/err_rpc.rs @@ -1,6 +1,5 @@ -use log::debug; - use common::rpc_primitives::errors::{RpcError, RpcParseError}; +use log::debug; use sequencer_core::TransactionMalformationError; pub struct RpcErr(pub RpcError); diff --git a/sequencer_runner/src/config.rs b/sequencer_runner/src/config.rs index 175903d..58f539b 100644 --- a/sequencer_runner/src/config.rs +++ b/sequencer_runner/src/config.rs @@ -1,11 +1,8 @@ -use std::path::PathBuf; +use std::{fs::File, io::BufReader, path::PathBuf}; use anyhow::Result; use sequencer_core::config::SequencerConfig; -use std::fs::File; -use std::io::BufReader; - pub fn from_file(config_home: PathBuf) -> Result { let file = File::open(config_home)?; let reader = BufReader::new(file); diff --git a/sequencer_runner/src/lib.rs b/sequencer_runner/src/lib.rs index 212066d..e9f4a84 100644 --- a/sequencer_runner/src/lib.rs +++ b/sequencer_runner/src/lib.rs @@ -80,7 +80,7 @@ pub async fn main_runner() -> Result<()> { } } - //ToDo: Add restart on failures + // ToDo: Add restart on failures let (_, main_loop_handle) = startup_sequencer(app_config).await?; main_loop_handle.await??; diff --git a/sequencer_runner/src/main.rs b/sequencer_runner/src/main.rs index 97f332d..3bf4ee2 100644 --- a/sequencer_runner/src/main.rs +++ b/sequencer_runner/src/main.rs @@ -1,5 +1,4 @@ use anyhow::Result; - use sequencer_runner::main_runner; pub const NUM_THREADS: usize = 4; diff --git a/storage/src/lib.rs b/storage/src/lib.rs index cbce767..87b7870 100644 --- a/storage/src/lib.rs +++ b/storage/src/lib.rs @@ -8,33 +8,33 @@ use rocksdb::{ pub mod error; -///Maximal size of stored blocks in base +/// Maximal size of stored blocks in base /// -///Used to control db size +/// Used to control db size /// -///Currently effectively unbounded. +/// Currently effectively unbounded. pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX; -///Size of stored blocks cache in memory +/// Size of stored blocks cache in memory /// -///Keeping small to not run out of memory +/// Keeping small to not run out of memory pub const CACHE_SIZE: usize = 1000; -///Key base for storing metainformation about id of first block in db +/// Key base for storing metainformation about id of first block in db pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db"; -///Key base for storing metainformation about id of last current block in db +/// Key base for storing metainformation about id of last current block in db pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db"; -///Key base for storing metainformation which describe if first block has been set +/// Key base for storing metainformation which describe if first block has been set pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set"; -///Key base for storing snapshot which describe block id +/// Key base for storing snapshot which describe block id pub const DB_SNAPSHOT_BLOCK_ID_KEY: &str = "block_id"; -///Name of block column family +/// Name of block column family pub const CF_BLOCK_NAME: &str = "cf_block"; -///Name of meta column family +/// Name of meta column family pub const CF_META_NAME: &str = "cf_meta"; -///Name of snapshot column family +/// Name of snapshot column family pub const CF_SNAPSHOT_NAME: &str = "cf_snapshot"; pub type DbResult = Result; @@ -47,7 +47,7 @@ impl RocksDBIO { pub fn open_or_create(path: &Path, start_block: Option) -> DbResult { let mut cf_opts = Options::default(); cf_opts.set_max_write_buffer_number(16); - //ToDo: Add more column families for different data + // ToDo: Add more column families for different data let cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone()); let cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone()); let cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone()); @@ -62,7 +62,7 @@ impl RocksDBIO { ); let dbio = Self { - //There is no point in handling this from runner code + // There is no point in handling this from runner code db: db.unwrap(), }; @@ -86,7 +86,7 @@ impl RocksDBIO { pub fn destroy(path: &Path) -> DbResult<()> { let mut cf_opts = Options::default(); cf_opts.set_max_write_buffer_number(16); - //ToDo: Add more column families for different data + // ToDo: Add more column families for different data let _cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone()); let _cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone()); let _cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone()); diff --git a/wallet/src/chain_storage/mod.rs b/wallet/src/chain_storage/mod.rs index bd38a38..d1143aa 100644 --- a/wallet/src/chain_storage/mod.rs +++ b/wallet/src/chain_storage/mod.rs @@ -72,9 +72,8 @@ impl WalletChainStore { #[cfg(test)] mod tests { - use crate::config::InitialAccountData; - use super::*; + use crate::config::InitialAccountData; fn create_initial_accounts() -> Vec { let initial_acc1 = serde_json::from_str( diff --git a/wallet/src/cli/account.rs b/wallet/src/cli/account.rs index 79484b0..79371c8 100644 --- a/wallet/src/cli/account.rs +++ b/wallet/src/cli/account.rs @@ -66,31 +66,31 @@ impl TokenHolding { } } -///Represents generic chain CLI subcommand +/// Represents generic chain CLI subcommand #[derive(Subcommand, Debug, Clone)] pub enum AccountSubcommand { - ///Get account data + /// Get account data Get { - ///Flag to get raw account data + /// Flag to get raw account data #[arg(short, long)] raw: bool, - ///Valid 32 byte base58 string with privacy prefix + /// Valid 32 byte base58 string with privacy prefix #[arg(short, long)] account_id: String, }, - ///Produce new public or private account + /// Produce new public or private account #[command(subcommand)] New(NewSubcommand), - ///Sync private accounts + /// Sync private accounts SyncPrivate {}, } -///Represents generic register CLI subcommand +/// Represents generic register CLI subcommand #[derive(Subcommand, Debug, Clone)] pub enum NewSubcommand { - ///Register new public account + /// Register new public account Public {}, - ///Register new private account + /// Register new private account Private {}, } diff --git a/wallet/src/cli/chain.rs b/wallet/src/cli/chain.rs index a6e7999..a606066 100644 --- a/wallet/src/cli/chain.rs +++ b/wallet/src/cli/chain.rs @@ -3,19 +3,19 @@ use clap::Subcommand; use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand}; -///Represents generic chain CLI subcommand +/// Represents generic chain CLI subcommand #[derive(Subcommand, Debug, Clone)] pub enum ChainSubcommand { - ///Get current block id from sequencer + /// Get current block id from sequencer CurrentBlockId {}, - ///Get block at id from sequencer + /// Get block at id from sequencer Block { #[arg(short, long)] id: u64, }, - ///Get transaction at hash from sequencer + /// Get transaction at hash from sequencer Transaction { - ///hash - valid 32 byte hex string + /// hash - valid 32 byte hex string #[arg(short, long)] hash: String, }, diff --git a/wallet/src/cli/config.rs b/wallet/src/cli/config.rs index 67fafcc..c41aa32 100644 --- a/wallet/src/cli/config.rs +++ b/wallet/src/cli/config.rs @@ -3,7 +3,7 @@ use clap::Subcommand; use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand}; -///Represents generic config CLI subcommand +/// Represents generic config CLI subcommand #[derive(Subcommand, Debug, Clone)] pub enum ConfigSubcommand { /// Command to explicitly setup config and storage diff --git a/wallet/src/cli/native_token_transfer_program.rs b/wallet/src/cli/native_token_transfer_program.rs index 6e4e880..f5fdb9a 100644 --- a/wallet/src/cli/native_token_transfer_program.rs +++ b/wallet/src/cli/native_token_transfer_program.rs @@ -9,34 +9,35 @@ use crate::{ helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix}, }; -///Represents generic CLI subcommand for a wallet working with native token transfer program +/// Represents generic CLI subcommand for a wallet working with native token transfer program #[derive(Subcommand, Debug, Clone)] pub enum AuthTransferSubcommand { - ///Initialize account under authenticated transfer program + /// Initialize account under authenticated transfer program Init { - ///account_id - valid 32 byte base58 string with privacy prefix + /// account_id - valid 32 byte base58 string with privacy prefix #[arg(long)] account_id: String, }, - ///Send native tokens from one account to another with variable privacy + /// Send native tokens from one account to another with variable privacy /// - ///If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive patterns. + /// If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive + /// patterns. /// - ///First is used for owned accounts, second otherwise. + /// First is used for owned accounts, second otherwise. Send { - ///from - valid 32 byte base58 string with privacy prefix + /// from - valid 32 byte base58 string with privacy prefix #[arg(long)] from: String, - ///to - valid 32 byte base58 string with privacy prefix + /// to - valid 32 byte base58 string with privacy prefix #[arg(long)] to: Option, - ///to_npk - valid 32 byte hex string + /// to_npk - valid 32 byte hex string #[arg(long)] to_npk: Option, - ///to_ipk - valid 33 byte hex string + /// to_ipk - valid 33 byte hex string #[arg(long)] to_ipk: Option, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, @@ -193,112 +194,114 @@ impl WalletSubcommand for AuthTransferSubcommand { } } -///Represents generic CLI subcommand for a wallet working with native token transfer program +/// Represents generic CLI subcommand for a wallet working with native token transfer program #[derive(Subcommand, Debug, Clone)] pub enum NativeTokenTransferProgramSubcommand { - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Public operation Public { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to - valid 32 byte hex string + /// to - valid 32 byte hex string #[arg(long)] to: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, - ///Private execution + /// Private execution #[command(subcommand)] Private(NativeTokenTransferProgramSubcommandPrivate), - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Deshielded operation Deshielded { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to - valid 32 byte hex string + /// to - valid 32 byte hex string #[arg(long)] to: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, - ///Shielded execution + /// Shielded execution #[command(subcommand)] Shielded(NativeTokenTransferProgramSubcommandShielded), } -///Represents generic shielded CLI subcommand for a wallet working with native token transfer program +/// Represents generic shielded CLI subcommand for a wallet working with native token transfer +/// program #[derive(Subcommand, Debug, Clone)] pub enum NativeTokenTransferProgramSubcommandShielded { - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Shielded operation ShieldedOwned { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to - valid 32 byte hex string + /// to - valid 32 byte hex string #[arg(long)] to: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Shielded operation ShieldedForeign { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to_npk - valid 32 byte hex string + /// to_npk - valid 32 byte hex string #[arg(long)] to_npk: String, - ///to_ipk - valid 33 byte hex string + /// to_ipk - valid 33 byte hex string #[arg(long)] to_ipk: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, } -///Represents generic private CLI subcommand for a wallet working with native token transfer program +/// Represents generic private CLI subcommand for a wallet working with native token transfer +/// program #[derive(Subcommand, Debug, Clone)] pub enum NativeTokenTransferProgramSubcommandPrivate { - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Private operation PrivateOwned { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to - valid 32 byte hex string + /// to - valid 32 byte hex string #[arg(long)] to: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, - ///Send native token transfer from `from` to `to` for `amount` + /// Send native token transfer from `from` to `to` for `amount` /// /// Private operation PrivateForeign { - ///from - valid 32 byte hex string + /// from - valid 32 byte hex string #[arg(long)] from: String, - ///to_npk - valid 32 byte hex string + /// to_npk - valid 32 byte hex string #[arg(long)] to_npk: String, - ///to_ipk - valid 33 byte hex string + /// to_ipk - valid 33 byte hex string #[arg(long)] to_ipk: String, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, diff --git a/wallet/src/cli/pinata_program.rs b/wallet/src/cli/pinata_program.rs index f69adbf..cc71a51 100644 --- a/wallet/src/cli/pinata_program.rs +++ b/wallet/src/cli/pinata_program.rs @@ -9,15 +9,15 @@ use crate::{ helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix}, }; -///Represents generic CLI subcommand for a wallet working with pinata program +/// Represents generic CLI subcommand for a wallet working with pinata program #[derive(Subcommand, Debug, Clone)] pub enum PinataProgramAgnosticSubcommand { - ///Claim pinata + /// Claim pinata Claim { - ///to_account_id - valid 32 byte base58 string with privacy prefix + /// to_account_id - valid 32 byte base58 string with privacy prefix #[arg(long)] to_account_id: String, - ///solution - solution to pinata challenge + /// solution - solution to pinata challenge #[arg(long)] solution: u128, }, @@ -59,48 +59,48 @@ impl WalletSubcommand for PinataProgramAgnosticSubcommand { } } -///Represents generic CLI subcommand for a wallet working with pinata program +/// Represents generic CLI subcommand for a wallet working with pinata program #[derive(Subcommand, Debug, Clone)] pub enum PinataProgramSubcommand { - ///Public execution + /// Public execution #[command(subcommand)] Public(PinataProgramSubcommandPublic), - ///Private execution + /// Private execution #[command(subcommand)] Private(PinataProgramSubcommandPrivate), } -///Represents generic public CLI subcommand for a wallet working with pinata program +/// Represents generic public CLI subcommand for a wallet working with pinata program #[derive(Subcommand, Debug, Clone)] pub enum PinataProgramSubcommandPublic { // TODO: Testnet only. Refactor to prevent compilation on mainnet. // Claim piñata prize Claim { - ///pinata_account_id - valid 32 byte hex string + /// pinata_account_id - valid 32 byte hex string #[arg(long)] pinata_account_id: String, - ///winner_account_id - valid 32 byte hex string + /// winner_account_id - valid 32 byte hex string #[arg(long)] winner_account_id: String, - ///solution - solution to pinata challenge + /// solution - solution to pinata challenge #[arg(long)] solution: u128, }, } -///Represents generic private CLI subcommand for a wallet working with pinata program +/// Represents generic private CLI subcommand for a wallet working with pinata program #[derive(Subcommand, Debug, Clone)] pub enum PinataProgramSubcommandPrivate { // TODO: Testnet only. Refactor to prevent compilation on mainnet. // Claim piñata prize ClaimPrivateOwned { - ///pinata_account_id - valid 32 byte hex string + /// pinata_account_id - valid 32 byte hex string #[arg(long)] pinata_account_id: String, - ///winner_account_id - valid 32 byte hex string + /// winner_account_id - valid 32 byte hex string #[arg(long)] winner_account_id: String, - ///solution - solution to pinata challenge + /// solution - solution to pinata challenge #[arg(long)] solution: u128, }, diff --git a/wallet/src/cli/token_program.rs b/wallet/src/cli/token_program.rs index b3af955..b412e2f 100644 --- a/wallet/src/cli/token_program.rs +++ b/wallet/src/cli/token_program.rs @@ -9,17 +9,17 @@ use crate::{ helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix}, }; -///Represents generic 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 TokenProgramAgnosticSubcommand { - ///Produce a new token + /// Produce a new token /// - ///Currently the only supported privacy options is for public definition + /// Currently the only supported privacy options is for public definition New { - ///definition_account_id - valid 32 byte base58 string with privacy prefix + /// definition_account_id - valid 32 byte base58 string with privacy prefix #[arg(long)] definition_account_id: String, - ///supply_account_id - valid 32 byte base58 string with privacy prefix + /// supply_account_id - valid 32 byte base58 string with privacy prefix #[arg(long)] supply_account_id: String, #[arg(short, long)] @@ -27,25 +27,26 @@ pub enum TokenProgramAgnosticSubcommand { #[arg(short, long)] total_supply: u128, }, - ///Send tokens from one account to another with variable privacy + /// Send tokens from one account to another with variable privacy /// - ///If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive patterns. + /// If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive + /// patterns. /// - ///First is used for owned accounts, second otherwise. + /// First is used for owned accounts, second otherwise. Send { - ///from - valid 32 byte base58 string with privacy prefix + /// from - valid 32 byte base58 string with privacy prefix #[arg(long)] from: String, - ///to - valid 32 byte base58 string with privacy prefix + /// to - valid 32 byte base58 string with privacy prefix #[arg(long)] to: Option, - ///to_npk - valid 32 byte hex string + /// to_npk - valid 32 byte hex string #[arg(long)] to_npk: Option, - ///to_ipk - valid 33 byte hex string + /// to_ipk - valid 33 byte hex string #[arg(long)] to_ipk: Option, - ///amount - amount of balance to move + /// amount - amount of balance to move #[arg(long)] amount: u128, }, @@ -90,11 +91,13 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { ) } (AccountPrivacyKind::Private, AccountPrivacyKind::Private) => { - //ToDo: maybe implement this one. It is not immediately clear why definition should be private. + // ToDo: maybe implement this one. It is not immediately clear why + // definition should be private. anyhow::bail!("Unavailable privacy pairing") } (AccountPrivacyKind::Private, AccountPrivacyKind::Public) => { - //ToDo: Probably valid. If definition is not public, but supply is it is very suspicious. + // ToDo: Probably valid. If definition is not public, but supply is it is + // very suspicious. anyhow::bail!("Unavailable privacy pairing") } }; @@ -195,27 +198,27 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { } } -///Represents generic 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 + /// Public execution #[command(subcommand)] Public(TokenProgramSubcommandPublic), - ///Private execution + /// Private execution #[command(subcommand)] Private(TokenProgramSubcommandPrivate), - ///Deshielded execution + /// Deshielded execution #[command(subcommand)] Deshielded(TokenProgramSubcommandDeshielded), - ///Shielded execution + /// Shielded execution #[command(subcommand)] Shielded(TokenProgramSubcommandShielded), } -///Represents generic public CLI subcommand for a wallet working with token_program +/// 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 + // Create a new token using the token program CreateNewToken { #[arg(short, long)] definition_account_id: String, @@ -226,7 +229,7 @@ pub enum TokenProgramSubcommandPublic { #[arg(short, long)] total_supply: u128, }, - //Transfer tokens using the token program + // Transfer tokens using the token program TransferToken { #[arg(short, long)] sender_account_id: String, @@ -237,10 +240,10 @@ pub enum TokenProgramSubcommandPublic { }, } -///Represents generic private 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 + // Create a new token using the token program CreateNewTokenPrivateOwned { #[arg(short, long)] definition_account_id: String, @@ -251,7 +254,7 @@ pub enum TokenProgramSubcommandPrivate { #[arg(short, long)] total_supply: u128, }, - //Transfer tokens using the token program + // Transfer tokens using the token program TransferTokenPrivateOwned { #[arg(short, long)] sender_account_id: String, @@ -260,14 +263,14 @@ pub enum TokenProgramSubcommandPrivate { #[arg(short, long)] balance_to_move: u128, }, - //Transfer tokens using the token program + // Transfer tokens using the token program TransferTokenPrivateForeign { #[arg(short, long)] sender_account_id: String, - ///recipient_npk - valid 32 byte hex string + /// recipient_npk - valid 32 byte hex string #[arg(long)] recipient_npk: String, - ///recipient_ipk - valid 33 byte hex string + /// recipient_ipk - valid 33 byte hex string #[arg(long)] recipient_ipk: String, #[arg(short, long)] @@ -275,10 +278,10 @@ pub enum TokenProgramSubcommandPrivate { }, } -///Represents deshielded public CLI subcommand for a wallet working with token_program +/// 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 + // Transfer tokens using the token program TransferTokenDeshielded { #[arg(short, long)] sender_account_id: String, @@ -289,10 +292,10 @@ pub enum TokenProgramSubcommandDeshielded { }, } -///Represents generic shielded CLI subcommand for a wallet working with token_program +/// 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 + // Transfer tokens using the token program TransferTokenShieldedOwned { #[arg(short, long)] sender_account_id: String, @@ -301,14 +304,14 @@ pub enum TokenProgramSubcommandShielded { #[arg(short, long)] balance_to_move: u128, }, - //Transfer tokens using the token program + // Transfer tokens using the token program TransferTokenShieldedForeign { #[arg(short, long)] sender_account_id: String, - ///recipient_npk - valid 32 byte hex string + /// recipient_npk - valid 32 byte hex string #[arg(long)] recipient_npk: String, - ///recipient_ipk - valid 33 byte hex string + /// recipient_ipk - valid 33 byte hex string #[arg(long)] recipient_ipk: String, #[arg(short, long)] diff --git a/wallet/src/config.rs b/wallet/src/config.rs index 982711c..dc84b0b 100644 --- a/wallet/src/config.rs +++ b/wallet/src/config.rs @@ -27,8 +27,9 @@ pub struct PersistentAccountDataPrivate { pub key_chain: KeyChain, } -//Big difference in enum variants sizes -//however it is improbable, that we will have that much accounts, that it will substantialy affect memory +// Big difference in enum variants sizes +// however it is improbable, that we will have that much accounts, that it will substantialy affect +// memory #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum InitialAccountData { @@ -36,8 +37,9 @@ pub enum InitialAccountData { Private(InitialAccountDataPrivate), } -//Big difference in enum variants sizes -//however it is improbable, that we will have that much accounts, that it will substantialy affect memory +// Big difference in enum variants sizes +// however it is improbable, that we will have that much accounts, that it will substantialy affect +// memory #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PersistentAccountData { @@ -113,19 +115,19 @@ pub struct GasConfig { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WalletConfig { - ///Override rust log (env var logging level) + /// Override rust log (env var logging level) pub override_rust_log: Option, - ///Sequencer URL + /// Sequencer URL pub sequencer_addr: String, - ///Sequencer polling duration for new blocks in milliseconds + /// Sequencer polling duration for new blocks in milliseconds pub seq_poll_timeout_millis: u64, - ///Sequencer polling max number of blocks + /// Sequencer polling max number of blocks pub seq_poll_max_blocks: usize, - ///Sequencer polling max number error retries + /// Sequencer polling max number error retries pub seq_poll_max_retries: u64, - ///Sequencer polling error retry delay in milliseconds + /// Sequencer polling error retry delay in milliseconds pub seq_poll_retry_delay_millis: u64, - ///Initial accounts for wallet + /// Initial accounts for wallet pub initial_accounts: Vec, } diff --git a/wallet/src/helperfunctions.rs b/wallet/src/helperfunctions.rs index a37a750..e274876 100644 --- a/wallet/src/helperfunctions.rs +++ b/wallet/src/helperfunctions.rs @@ -1,13 +1,13 @@ -use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; -use nssa_core::account::Nonce; -use rand::{RngCore, rngs::OsRng}; use std::{path::PathBuf, str::FromStr}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; use anyhow::Result; +use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; use key_protocol::key_protocol_core::NSSAUserData; use nssa::Account; +use nssa_core::account::Nonce; +use rand::{RngCore, rngs::OsRng}; use serde::Serialize; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::{ HOME_DIR_ENV_VAR, diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index 55c82c9..7a58224 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -1,22 +1,20 @@ use std::{path::PathBuf, sync::Arc}; +use anyhow::Result; use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; +use chain_storage::WalletChainStore; +use clap::{Parser, Subcommand}; use common::{ block::HashableBlockData, sequencer_client::SequencerClient, transaction::{EncodedTransaction, NSSATransaction}, }; - -use anyhow::Result; -use chain_storage::WalletChainStore; use config::WalletConfig; use log::info; use nssa::{ Account, AccountId, privacy_preserving_transaction::message::EncryptedAccountData, program::Program, }; - -use clap::{Parser, Subcommand}; use nssa_core::{Commitment, MembershipProof}; use tokio::io::AsyncWriteExt; @@ -28,10 +26,7 @@ use crate::{ token_program::TokenProgramAgnosticSubcommand, }, config::PersistentStorage, - helperfunctions::fetch_persistent_storage, -}; -use crate::{ - helperfunctions::{fetch_config, get_home, produce_data_for_storage}, + helperfunctions::{fetch_config, fetch_persistent_storage, get_home, produce_data_for_storage}, poller::TxPoller, }; @@ -77,7 +72,7 @@ impl WalletCore { }) } - ///Store persistent data at home + /// Store persistent data at home pub async fn store_persistent_data(&self) -> Result { let home = get_home()?; let storage_path = home.join("storage.json"); @@ -93,7 +88,7 @@ impl WalletCore { Ok(storage_path) } - ///Store persistent data at home + /// Store persistent data at home pub async fn store_config_changes(&self) -> Result { let home = get_home()?; let config_path = home.join("wallet_config.json"); @@ -119,7 +114,7 @@ impl WalletCore { .generate_new_privacy_preserving_transaction_key_chain() } - ///Get account balance + /// Get account balance pub async fn get_account_balance(&self, acc: AccountId) -> Result { Ok(self .sequencer_client @@ -128,7 +123,7 @@ impl WalletCore { .balance) } - ///Get accounts nonces + /// Get accounts nonces pub async fn get_accounts_nonces(&self, accs: Vec) -> Result> { Ok(self .sequencer_client @@ -137,7 +132,7 @@ impl WalletCore { .nonces) } - ///Get account + /// Get account pub async fn get_account_public(&self, account_id: AccountId) -> Result { let response = self .sequencer_client @@ -163,7 +158,7 @@ impl WalletCore { Some(Commitment::new(&keys.nullifer_public_key, account)) } - ///Poll transactions + /// Poll transactions pub async fn poll_native_token_transfer(&self, hash: String) -> Result { let transaction_encoded = self.poller.poll_tx(hash).await?; let tx_base64_decode = BASE64.decode(transaction_encoded)?; @@ -215,23 +210,23 @@ impl WalletCore { } } -///Represents CLI command for a wallet +/// Represents CLI command for a wallet #[derive(Subcommand, Debug, Clone)] #[clap(about)] pub enum Command { - ///Authenticated transfer subcommand + /// Authenticated transfer subcommand #[command(subcommand)] AuthTransfer(AuthTransferSubcommand), - ///Generic chain info subcommand + /// Generic chain info subcommand #[command(subcommand)] ChainInfo(ChainSubcommand), - ///Account view and sync subcommand + /// Account view and sync subcommand #[command(subcommand)] Account(AccountSubcommand), - ///Pinata program interaction subcommand + /// Pinata program interaction subcommand #[command(subcommand)] Pinata(PinataProgramAgnosticSubcommand), - ///Token program interaction subcommand + /// Token program interaction subcommand #[command(subcommand)] Token(TokenProgramAgnosticSubcommand), /// Check the wallet can connect to the node and builtin local programs @@ -242,7 +237,7 @@ pub enum Command { Config(ConfigSubcommand), } -///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config +/// To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config /// /// All account adresses must be valid 32 byte base58 strings. /// diff --git a/wallet/src/main.rs b/wallet/src/main.rs index 59f90fd..d38af75 100644 --- a/wallet/src/main.rs +++ b/wallet/src/main.rs @@ -6,9 +6,9 @@ use wallet::{Args, execute_continious_run, execute_subcommand}; pub const NUM_THREADS: usize = 2; // TODO #169: We have sample configs for sequencer, but not for wallet -// TODO #168: Why it requires config as a directory? Maybe better to deduce directory from config file path? -// TODO #172: Why it requires config as env var while sequencer_runner accepts as argument? -// TODO #171: Running pinata doesn't give output about transaction hash and etc. +// TODO #168: Why it requires config as a directory? Maybe better to deduce directory from config +// file path? TODO #172: Why it requires config as env var while sequencer_runner accepts as +// argument? TODO #171: Running pinata doesn't give output about transaction hash and etc. fn main() -> Result<()> { let runtime = Builder::new_multi_thread() .worker_threads(NUM_THREADS) diff --git a/wallet/src/poller.rs b/wallet/src/poller.rs index e6752ca..2b709e7 100644 --- a/wallet/src/poller.rs +++ b/wallet/src/poller.rs @@ -7,7 +7,7 @@ use log::{info, warn}; use crate::config::WalletConfig; #[derive(Clone)] -///Helperstruct to poll transactions +/// Helperstruct to poll transactions pub struct TxPoller { pub polling_max_blocks_to_query: usize, pub polling_max_error_attempts: u64, diff --git a/wallet/src/token_program_interactions.rs b/wallet/src/token_program_interactions.rs index e7a7c28..c441842 100644 --- a/wallet/src/token_program_interactions.rs +++ b/wallet/src/token_program_interactions.rs @@ -15,7 +15,8 @@ impl WalletCore { Program, impl FnOnce(&Account, &Account) -> Result<(), ExecutionFailureKind>, ) { - // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + // 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()); @@ -103,7 +104,8 @@ impl WalletCore { ) -> Result { let account_ids = vec![sender_account_id, recipient_account_id]; let program_id = nssa::program::Program::token().id(); - // Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00]. + // 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());