From aa462b66eb58cfc52dafcd231a09d141573e5ab3 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 9 Mar 2026 18:27:56 +0300 Subject: [PATCH] feat: add nursery clippy lints --- Cargo.toml | 8 +++ common/src/config.rs | 2 +- common/src/error.rs | 2 +- common/src/lib.rs | 6 +- common/src/rpc_primitives/errors.rs | 34 +++++------ common/src/rpc_primitives/message.rs | 39 ++++++------ common/src/rpc_primitives/mod.rs | 6 +- common/src/rpc_primitives/parser.rs | 13 ++-- common/src/transaction.rs | 34 +++++------ .../guest/src/bin/tail_call_with_pda.rs | 1 - ...n_hello_world_through_tail_call_private.rs | 2 +- .../src/components/block_preview.rs | 2 +- .../src/components/transaction_preview.rs | 2 +- indexer/core/src/config.rs | 2 +- indexer/service/protocol/src/convert.rs | 40 ++++++------- indexer/service/protocol/src/lib.rs | 20 +++---- indexer/service/src/lib.rs | 4 +- indexer/service/src/service.rs | 2 +- integration_tests/src/config.rs | 4 +- integration_tests/src/lib.rs | 16 ++--- integration_tests/tests/tps.rs | 2 +- integration_tests/tests/wallet_ffi.rs | 7 +-- .../key_management/key_tree/chain_index.rs | 38 ++++++------ .../key_management/key_tree/keys_public.rs | 9 +-- key_protocol/src/key_protocol_core/mod.rs | 22 +++---- mempool/src/lib.rs | 2 +- nssa/core/src/account.rs | 8 +-- nssa/core/src/commitment.rs | 6 +- nssa/core/src/encoding.rs | 14 ++--- nssa/core/src/encryption/mod.rs | 2 +- .../src/encryption/shared_key_derivation.rs | 4 +- nssa/core/src/nullifier.rs | 14 ++++- nssa/core/src/program.rs | 15 ++--- nssa/src/merkle_tree/default_values.rs | 2 +- nssa/src/merkle_tree/mod.rs | 2 +- .../privacy_preserving_transaction/circuit.rs | 8 +-- .../privacy_preserving_transaction/message.rs | 12 ++-- .../transaction.rs | 6 +- .../witness_set.rs | 4 +- nssa/src/program.rs | 28 ++++----- .../program_deployment_transaction/message.rs | 2 +- .../transaction.rs | 4 +- nssa/src/public_transaction/message.rs | 2 +- nssa/src/public_transaction/transaction.rs | 6 +- nssa/src/public_transaction/witness_set.rs | 2 +- nssa/src/signature/private_key.rs | 2 +- nssa/src/signature/public_key.rs | 2 +- nssa/src/state.rs | 34 +++++------ .../src/bin/privacy_preserving_circuit.rs | 9 ++- programs/amm/core/src/lib.rs | 4 +- programs/amm/src/add.rs | 2 +- programs/amm/src/new_definition.rs | 4 +- programs/amm/src/remove.rs | 2 +- programs/amm/src/tests.rs | 16 ++--- programs/token/core/src/lib.rs | 34 +++++------ sequencer_core/src/block_store.rs | 8 +-- sequencer_core/src/config.rs | 4 +- sequencer_core/src/lib.rs | 27 ++++----- sequencer_rpc/src/lib.rs | 11 ++-- sequencer_runner/src/lib.rs | 2 +- storage/src/error.rs | 6 +- storage/src/indexer.rs | 31 +++++----- storage/src/sequencer.rs | 9 +-- .../bin/malicious_authorization_changer.rs | 2 +- wallet-ffi/src/error.rs | 2 +- wallet-ffi/src/types.rs | 18 +++--- wallet/src/chain_storage.rs | 2 +- wallet/src/cli/account.rs | 59 +++++++++---------- wallet/src/cli/chain.rs | 6 +- wallet/src/cli/config.rs | 6 +- wallet/src/cli/programs/amm.rs | 8 +-- .../src/cli/programs/native_token_transfer.rs | 20 +++---- wallet/src/cli/programs/pinata.rs | 10 ++-- wallet/src/cli/programs/token.rs | 58 +++++++++--------- wallet/src/config.rs | 8 +-- wallet/src/helperfunctions.rs | 8 +-- wallet/src/lib.rs | 10 ++-- wallet/src/poller.rs | 2 +- wallet/src/privacy_preserving_tx.rs | 4 +- 79 files changed, 431 insertions(+), 459 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8be7cb96..70a50f5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -248,3 +248,11 @@ clippy.let-underscore-untyped = "allow" # Reason: this lint is actually bad as it forces to use wildcard `..` instead of # field-by-field `_` which may lead to subtle bugs when new fields are added to the struct. clippy.unneeded-field-pattern = "allow" + +# Nursery +clippy.nursery = { level = "deny", priority = -1 } + +# Reason: this is okay if it compiles. +clippy.future-not-send = "allow" +# Reason: this is actually a good lint, but currently it gives a lot of false-positives. +clippy.significant-drop-tightening = "allow" diff --git a/common/src/config.rs b/common/src/config.rs index 94d00ff5..c076f699 100644 --- a/common/src/config.rs +++ b/common/src/config.rs @@ -50,6 +50,6 @@ impl FromStr for BasicAuth { impl From for BasicAuthCredentials { fn from(value: BasicAuth) -> Self { - BasicAuthCredentials::new(value.username, value.password) + Self::new(value.username, value.password) } } diff --git a/common/src/error.rs b/common/src/error.rs index bc037a60..1e348a32 100644 --- a/common/src/error.rs +++ b/common/src/error.rs @@ -22,7 +22,7 @@ pub enum SequencerClientError { impl From for SequencerClientError { fn from(value: SequencerRpcError) -> Self { - SequencerClientError::InternalError(value) + Self::InternalError(value) } } diff --git a/common/src/lib.rs b/common/src/lib.rs index 11c450f6..da07a602 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -48,7 +48,7 @@ impl FromStr for HashType { fn from_str(s: &str) -> Result { let mut bytes = [0_u8; 32]; hex::decode_to_slice(s, &mut bytes)?; - Ok(HashType(bytes)) + Ok(Self(bytes)) } } @@ -66,7 +66,7 @@ impl From for [u8; 32] { impl From<[u8; 32]> for HashType { fn from(bytes: [u8; 32]) -> Self { - HashType(bytes) + Self(bytes) } } @@ -74,7 +74,7 @@ impl TryFrom> for HashType { type Error = <[u8; 32] as TryFrom>>::Error; fn try_from(value: Vec) -> Result { - Ok(HashType(value.try_into()?)) + Ok(Self(value.try_into()?)) } } diff --git a/common/src/rpc_primitives/errors.rs b/common/src/rpc_primitives/errors.rs index 03f7fc16..ae791de8 100644 --- a/common/src/rpc_primitives/errors.rs +++ b/common/src/rpc_primitives/errors.rs @@ -9,7 +9,7 @@ pub struct RpcParseError(pub String); /// /// It is expected that that this struct has impls From<_> all other RPC errors /// like [`RpcBlockError`](crate::types::blocks::RpcBlockError). -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct RpcError { #[serde(flatten)] @@ -23,7 +23,7 @@ pub struct RpcError { pub data: Option, } -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] #[serde(tag = "name", content = "cause", rename_all = "SCREAMING_SNAKE_CASE")] pub enum RpcErrorKind { RequestValidationError(RpcRequestValidationErrorKind), @@ -31,7 +31,7 @@ pub enum RpcErrorKind { InternalError(Value), } -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] #[serde(tag = "name", content = "info", rename_all = "SCREAMING_SNAKE_CASE")] pub enum RpcRequestValidationErrorKind { MethodNotFound { method_name: String }, @@ -50,8 +50,8 @@ impl RpcError { /// /// Mostly for completeness, doesn't do anything but filling in the corresponding fields. #[must_use] - pub fn new(code: i64, message: String, data: Option) -> Self { - RpcError { + pub const fn new(code: i64, message: String, data: Option) -> Self { + Self { code, message, data, @@ -70,12 +70,12 @@ impl RpcError { ))); } }; - RpcError::new(-32_602, "Invalid params".to_owned(), Some(value)) + Self::new(-32_602, "Invalid params".to_owned(), Some(value)) } /// Create a server error. pub fn server_error(e: Option) -> Self { - RpcError::new( + Self::new( -32_000, "Server error".to_owned(), e.map(|v| to_value(v).expect("Must be representable in JSON")), @@ -85,7 +85,7 @@ impl RpcError { /// Create a parse error. #[must_use] pub fn parse_error(e: String) -> Self { - RpcError { + Self { code: -32_700, message: "Parse error".to_owned(), data: Some(Value::String(e.clone())), @@ -97,7 +97,7 @@ impl RpcError { #[must_use] pub fn serialization_error(e: &str) -> Self { - RpcError::new_internal_error(Some(Value::String(e.to_owned())), e) + Self::new_internal_error(Some(Value::String(e.to_owned())), e) } /// Helper method to define extract `INTERNAL_ERROR` in separate `RpcErrorKind` @@ -117,7 +117,7 @@ impl RpcError { #[must_use] pub fn new_internal_error(error_data: Option, info: &str) -> Self { - RpcError { + Self { code: -32_000, message: "Server error".to_owned(), data: error_data, @@ -129,7 +129,7 @@ impl RpcError { } fn new_handler_error(error_data: Option, error_struct: Value) -> Self { - RpcError { + Self { code: -32_000, message: "Server error".to_owned(), data: error_data, @@ -140,7 +140,7 @@ impl RpcError { /// Create a method not found error. #[must_use] pub fn method_not_found(method: String) -> Self { - RpcError { + Self { code: -32_601, message: "Method not found".to_owned(), data: Some(Value::String(method.clone())), @@ -175,20 +175,20 @@ impl From for RpcError { impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ServerError::Timeout => write!(f, "ServerError: Timeout"), - ServerError::Closed => write!(f, "ServerError: Closed"), + Self::Timeout => write!(f, "ServerError: Timeout"), + Self::Closed => write!(f, "ServerError: Closed"), } } } impl From for RpcError { - fn from(e: ServerError) -> RpcError { + fn from(e: ServerError) -> Self { let error_data = match to_value(&e) { Ok(value) => value, Err(_err) => { - return RpcError::new_internal_error(None, "Failed to serialize ServerError"); + return Self::new_internal_error(None, "Failed to serialize ServerError"); } }; - RpcError::new_internal_error(Some(error_data), e.to_string().as_str()) + Self::new_internal_error(Some(error_data), e.to_string().as_str()) } } diff --git a/common/src/rpc_primitives/message.rs b/common/src/rpc_primitives/message.rs index 80948149..70c62660 100644 --- a/common/src/rpc_primitives/message.rs +++ b/common/src/rpc_primitives/message.rs @@ -56,7 +56,7 @@ impl<'de> serde::Deserialize<'de> for Version { } /// An RPC request. -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] #[serde(deny_unknown_fields)] #[expect( clippy::partial_pub_fields, @@ -112,7 +112,7 @@ impl Request { clippy::partial_pub_fields, reason = "We don't want to allow access to the version, but the others are public for ease of use" )] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct Response { jsonrpc: Version, pub result: Result, @@ -160,7 +160,7 @@ impl<'de> serde::Deserialize<'de> for Response { return Err(err); } }; - Ok(Response { + Ok(Self { jsonrpc: Version, result, id: wr.id, @@ -173,7 +173,7 @@ impl<'de> serde::Deserialize<'de> for Response { clippy::partial_pub_fields, reason = "We don't want to allow access to the version, but the others are public for ease of use" )] -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct Notification { jsonrpc: Version, @@ -227,7 +227,7 @@ impl Message { #[must_use] pub fn request(method: String, params: Value) -> Self { let id = Value::from("dontcare"); - Message::Request(Request { + Self::Request(Request { jsonrpc: Version, method, params, @@ -237,8 +237,8 @@ impl Message { /// Create a top-level error (without an ID). #[must_use] - pub fn error(error: RpcError) -> Self { - Message::Response(Response { + pub const fn error(error: RpcError) -> Self { + Self::Response(Response { jsonrpc: Version, result: Err(error), id: Value::Null, @@ -247,8 +247,8 @@ impl Message { /// A constructor for a notification. #[must_use] - pub fn notification(method: String, params: Value) -> Self { - Message::Notification(Notification { + pub const fn notification(method: String, params: Value) -> Self { + Self::Notification(Notification { jsonrpc: Version, method, params, @@ -257,8 +257,8 @@ impl Message { /// A constructor for a response. #[must_use] - pub fn response(id: Value, result: Result) -> Self { - Message::Response(Response { + pub const fn response(id: Value, result: Result) -> Self { + Self::Response(Response { jsonrpc: Version, result, id, @@ -269,29 +269,30 @@ impl Message { #[must_use] pub fn id(&self) -> Value { match self { - Message::Request(req) => req.id.clone(), - Message::Response(response) => response.id.clone(), - Message::Notification(_) | Message::Batch(_) | Message::UnmatchedSub(_) => Value::Null, + Self::Request(req) => req.id.clone(), + Self::Response(response) => response.id.clone(), + Self::Notification(_) | Self::Batch(_) | Self::UnmatchedSub(_) => Value::Null, } } } impl From for String { fn from(val: Message) -> Self { - ::serde_json::ser::to_string(&val).unwrap() + ::serde_json::ser::to_string(&val).expect("message serialization to json should not fail") } } impl From for Vec { fn from(val: Message) -> Self { - ::serde_json::ser::to_vec(&val).unwrap() + ::serde_json::ser::to_vec(&val) + .expect("message serialization to json bytes should not fail") } } /// A broken message. /// /// Protocol-level errors. -#[derive(Debug, Clone, PartialEq, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] #[serde(untagged)] pub enum Broken { /// It was valid JSON, but doesn't match the form of a JSONRPC 2.0 message. @@ -309,10 +310,10 @@ impl Broken { #[must_use] pub fn reply(&self) -> Message { match self { - Broken::Unmatched(_) => Message::error(RpcError::parse_error( + Self::Unmatched(_) => Message::error(RpcError::parse_error( "JSON RPC Request format was expected".to_owned(), )), - Broken::SyntaxError(e) => Message::error(RpcError::parse_error(e.clone())), + Self::SyntaxError(e) => Message::error(RpcError::parse_error(e.clone())), } } } diff --git a/common/src/rpc_primitives/mod.rs b/common/src/rpc_primitives/mod.rs index 5cc74995..cd643712 100644 --- a/common/src/rpc_primitives/mod.rs +++ b/common/src/rpc_primitives/mod.rs @@ -30,7 +30,7 @@ pub struct RpcConfig { impl Default for RpcConfig { fn default() -> Self { - RpcConfig { + Self { addr: "0.0.0.0:3040".to_owned(), cors_allowed_origins: vec!["*".to_owned()], limits_config: RpcLimitsConfig::default(), @@ -41,7 +41,7 @@ impl Default for RpcConfig { impl RpcConfig { #[must_use] pub fn new(addr: &str) -> Self { - RpcConfig { + Self { addr: addr.to_owned(), ..Default::default() } @@ -49,7 +49,7 @@ impl RpcConfig { #[must_use] pub fn with_port(port: u16) -> Self { - RpcConfig { + Self { addr: format!("0.0.0.0:{port}"), ..Default::default() } diff --git a/common/src/rpc_primitives/parser.rs b/common/src/rpc_primitives/parser.rs index 933f8daf..0b918c94 100644 --- a/common/src/rpc_primitives/parser.rs +++ b/common/src/rpc_primitives/parser.rs @@ -19,10 +19,11 @@ pub trait RpcRequest: Sized { } pub fn parse_params(value: Option) -> Result { - if let Some(value) = value { - serde_json::from_value(value) - .map_err(|err| RpcParseError(format!("Failed parsing args: {err}"))) - } else { - Err(RpcParseError("Require at least one parameter".to_owned())) - } + value.map_or_else( + || Err(RpcParseError("Require at least one parameter".to_owned())), + |value| { + serde_json::from_value(value) + .map_err(|err| RpcParseError(format!("Failed parsing args: {err}"))) + }, + ) } diff --git a/common/src/transaction.rs b/common/src/transaction.rs index 74a41ca2..8fdc2074 100644 --- a/common/src/transaction.rs +++ b/common/src/transaction.rs @@ -16,18 +16,18 @@ impl NSSATransaction { #[must_use] pub fn hash(&self) -> HashType { HashType(match self { - NSSATransaction::Public(tx) => tx.hash(), - NSSATransaction::PrivacyPreserving(tx) => tx.hash(), - NSSATransaction::ProgramDeployment(tx) => tx.hash(), + Self::Public(tx) => tx.hash(), + Self::PrivacyPreserving(tx) => tx.hash(), + Self::ProgramDeployment(tx) => tx.hash(), }) } #[must_use] pub fn affected_public_account_ids(&self) -> Vec { match self { - NSSATransaction::ProgramDeployment(tx) => tx.affected_public_account_ids(), - NSSATransaction::Public(tx) => tx.affected_public_account_ids(), - NSSATransaction::PrivacyPreserving(tx) => tx.affected_public_account_ids(), + Self::ProgramDeployment(tx) => tx.affected_public_account_ids(), + Self::Public(tx) => tx.affected_public_account_ids(), + Self::PrivacyPreserving(tx) => tx.affected_public_account_ids(), } } @@ -35,21 +35,21 @@ impl NSSATransaction { pub fn transaction_stateless_check(self) -> Result { // Stateless checks here match self { - NSSATransaction::Public(tx) => { + Self::Public(tx) => { if tx.witness_set().is_valid_for(tx.message()) { - Ok(NSSATransaction::Public(tx)) + Ok(Self::Public(tx)) } else { Err(TransactionMalformationError::InvalidSignature) } } - NSSATransaction::PrivacyPreserving(tx) => { + Self::PrivacyPreserving(tx) => { if tx.witness_set().signatures_are_valid_for(tx.message()) { - Ok(NSSATransaction::PrivacyPreserving(tx)) + Ok(Self::PrivacyPreserving(tx)) } else { Err(TransactionMalformationError::InvalidSignature) } } - NSSATransaction::ProgramDeployment(tx) => Ok(NSSATransaction::ProgramDeployment(tx)), + Self::ProgramDeployment(tx) => Ok(Self::ProgramDeployment(tx)), } } @@ -58,13 +58,9 @@ impl NSSATransaction { state: &mut V02State, ) -> Result { match &self { - NSSATransaction::Public(tx) => state.transition_from_public_transaction(tx), - NSSATransaction::PrivacyPreserving(tx) => { - state.transition_from_privacy_preserving_transaction(tx) - } - NSSATransaction::ProgramDeployment(tx) => { - state.transition_from_program_deployment_transaction(tx) - } + Self::Public(tx) => state.transition_from_public_transaction(tx), + Self::PrivacyPreserving(tx) => state.transition_from_privacy_preserving_transaction(tx), + Self::ProgramDeployment(tx) => state.transition_from_program_deployment_transaction(tx), } .inspect_err(|err| warn!("Error at transition {err:#?}"))?; @@ -99,7 +95,7 @@ pub enum TxKind { ProgramDeployment, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)] pub enum TransactionMalformationError { #[error("Invalid signature(-s)")] InvalidSignature, diff --git a/examples/program_deployment/methods/guest/src/bin/tail_call_with_pda.rs b/examples/program_deployment/methods/guest/src/bin/tail_call_with_pda.rs index 679df3bf..3ebcabd2 100644 --- a/examples/program_deployment/methods/guest/src/bin/tail_call_with_pda.rs +++ b/examples/program_deployment/methods/guest/src/bin/tail_call_with_pda.rs @@ -41,7 +41,6 @@ fn main() { // Unpack the input account pre state let [pre_state] = pre_states - .clone() .try_into() .unwrap_or_else(|_| panic!("Input pre states should consist of a single account")); diff --git a/examples/program_deployment/src/bin/run_hello_world_through_tail_call_private.rs b/examples/program_deployment/src/bin/run_hello_world_through_tail_call_private.rs index 9b3619cb..4fac3eec 100644 --- a/examples/program_deployment/src/bin/run_hello_world_through_tail_call_private.rs +++ b/examples/program_deployment/src/bin/run_hello_world_through_tail_call_private.rs @@ -48,7 +48,7 @@ async fn main() { let hello_world_bytecode: Vec = std::fs::read(hello_world_path).unwrap(); let hello_world = Program::new(hello_world_bytecode).unwrap(); let dependencies: HashMap = - [(hello_world.id(), hello_world)].into_iter().collect(); + std::iter::once((hello_world.id(), hello_world)).collect(); let program_with_dependencies = ProgramWithDependencies::new(simple_tail_call, dependencies); let accounts = vec![PrivacyPreservingAccount::PrivateOwned(account_id)]; diff --git a/explorer_service/src/components/block_preview.rs b/explorer_service/src/components/block_preview.rs index e16ab831..04ba8555 100644 --- a/explorer_service/src/components/block_preview.rs +++ b/explorer_service/src/components/block_preview.rs @@ -5,7 +5,7 @@ use leptos_router::components::A; use crate::format_utils; /// Get CSS class for bedrock status -fn status_class(status: &BedrockStatus) -> &'static str { +const fn status_class(status: &BedrockStatus) -> &'static str { match status { BedrockStatus::Pending => "status-pending", BedrockStatus::Safe => "status-safe", diff --git a/explorer_service/src/components/transaction_preview.rs b/explorer_service/src/components/transaction_preview.rs index f4ff2bb4..0c82cf48 100644 --- a/explorer_service/src/components/transaction_preview.rs +++ b/explorer_service/src/components/transaction_preview.rs @@ -3,7 +3,7 @@ use leptos::prelude::*; use leptos_router::components::A; /// Get transaction type name and CSS class -fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) { +const fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) { match tx { Transaction::Public(_) => ("Public", "tx-type-public"), Transaction::PrivacyPreserving(_) => ("Privacy-Preserving", "tx-type-private"), diff --git a/indexer/core/src/config.rs b/indexer/core/src/config.rs index 326a79a3..7dec7fc9 100644 --- a/indexer/core/src/config.rs +++ b/indexer/core/src/config.rs @@ -42,7 +42,7 @@ pub struct IndexerConfig { } impl IndexerConfig { - pub fn from_path(config_path: &Path) -> Result { + pub fn from_path(config_path: &Path) -> Result { let file = File::open(config_path).with_context(|| { format!("Failed to open indexer config at {}", config_path.display()) })?; diff --git a/indexer/service/protocol/src/convert.rs b/indexer/service/protocol/src/convert.rs index 931c340c..9e31ef7a 100644 --- a/indexer/service/protocol/src/convert.rs +++ b/indexer/service/protocol/src/convert.rs @@ -35,7 +35,7 @@ impl From for AccountId { impl From for nssa_core::account::AccountId { fn from(value: AccountId) -> Self { let AccountId { value } = value; - nssa_core::account::AccountId::new(value) + Self::new(value) } } @@ -68,7 +68,7 @@ impl TryFrom for nssa_core::account::Account { nonce, } = value; - Ok(nssa_core::account::Account { + Ok(Self { program_owner: program_owner.into(), balance, data: data.try_into()?, @@ -87,7 +87,7 @@ impl TryFrom for nssa_core::account::Data { type Error = nssa_core::account::data::DataTooBigError; fn try_from(value: Data) -> Result { - nssa_core::account::Data::try_from(value.0) + Self::try_from(value.0) } } @@ -103,7 +103,7 @@ impl From for Commitment { impl From for nssa_core::Commitment { fn from(value: Commitment) -> Self { - nssa_core::Commitment::from_byte_array(value.0) + Self::from_byte_array(value.0) } } @@ -115,7 +115,7 @@ impl From for Nullifier { impl From for nssa_core::Nullifier { fn from(value: Nullifier) -> Self { - nssa_core::Nullifier::from_byte_array(value.0) + Self::from_byte_array(value.0) } } @@ -143,7 +143,7 @@ impl From for Ciphertext { impl From for nssa_core::encryption::Ciphertext { fn from(value: Ciphertext) -> Self { - nssa_core::encryption::Ciphertext::from_inner(value.0) + Self::from_inner(value.0) } } @@ -155,7 +155,7 @@ impl From for EphemeralPublicKey { impl From for nssa_core::encryption::EphemeralPublicKey { fn from(value: EphemeralPublicKey) -> Self { - nssa_core::encryption::shared_key_derivation::Secp256k1Point(value.0) + Self(value.0) } } @@ -173,7 +173,7 @@ impl From for Signature { impl From for nssa::Signature { fn from(value: Signature) -> Self { let Signature(sig_value) = value; - nssa::Signature { value: sig_value } + Self { value: sig_value } } } @@ -187,7 +187,7 @@ impl TryFrom for nssa::PublicKey { type Error = nssa::error::NssaError; fn try_from(value: PublicKey) -> Result { - nssa::PublicKey::try_new(value.0) + Self::try_new(value.0) } } @@ -203,7 +203,7 @@ impl From for Proof { impl From for nssa::privacy_preserving_transaction::circuit::Proof { fn from(value: Proof) -> Self { - nssa::privacy_preserving_transaction::circuit::Proof::from_inner(value.0) + Self::from_inner(value.0) } } @@ -505,12 +505,12 @@ impl From for nssa::ProgramDeploymentTransaction { impl From for Transaction { fn from(value: common::transaction::NSSATransaction) -> Self { match value { - common::transaction::NSSATransaction::Public(tx) => Transaction::Public(tx.into()), + common::transaction::NSSATransaction::Public(tx) => Self::Public(tx.into()), common::transaction::NSSATransaction::PrivacyPreserving(tx) => { - Transaction::PrivacyPreserving(tx.into()) + Self::PrivacyPreserving(tx.into()) } common::transaction::NSSATransaction::ProgramDeployment(tx) => { - Transaction::ProgramDeployment(tx.into()) + Self::ProgramDeployment(tx.into()) } } } @@ -521,15 +521,9 @@ impl TryFrom for common::transaction::NSSATransaction { fn try_from(value: Transaction) -> Result { match value { - Transaction::Public(tx) => { - Ok(common::transaction::NSSATransaction::Public(tx.try_into()?)) - } - Transaction::PrivacyPreserving(tx) => Ok( - common::transaction::NSSATransaction::PrivacyPreserving(tx.try_into()?), - ), - Transaction::ProgramDeployment(tx) => Ok( - common::transaction::NSSATransaction::ProgramDeployment(tx.into()), - ), + Transaction::Public(tx) => Ok(Self::Public(tx.try_into()?)), + Transaction::PrivacyPreserving(tx) => Ok(Self::PrivacyPreserving(tx.try_into()?)), + Transaction::ProgramDeployment(tx) => Ok(Self::ProgramDeployment(tx.into())), } } } @@ -683,6 +677,6 @@ impl From for HashType { impl From for common::HashType { fn from(value: HashType) -> Self { - common::HashType(value.0) + Self(value.0) } } diff --git a/indexer/service/protocol/src/lib.rs b/indexer/service/protocol/src/lib.rs index 42c513a2..6bd67d73 100644 --- a/indexer/service/protocol/src/lib.rs +++ b/indexer/service/protocol/src/lib.rs @@ -71,8 +71,8 @@ pub enum ProgramIdParseError { impl Display for ProgramIdParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ProgramIdParseError::InvalidBase58(err) => write!(f, "invalid base58: {err:?}"), - ProgramIdParseError::InvalidLength(len) => { + Self::InvalidBase58(err) => write!(f, "invalid base58: {err:?}"), + Self::InvalidLength(len) => { write!(f, "invalid length: expected 32 bytes, got {len}") } } @@ -93,7 +93,7 @@ impl FromStr for ProgramId { for (i, chunk) in bytes.chunks_exact(4).enumerate() { arr[i] = u32::from_le_bytes(chunk.try_into().unwrap()); } - Ok(ProgramId(arr)) + Ok(Self(arr)) } } @@ -125,7 +125,7 @@ impl FromStr for AccountId { } let mut value = [0_u8; 32]; value.copy_from_slice(&bytes); - Ok(AccountId { value }) + Ok(Self { value }) } } @@ -174,7 +174,7 @@ impl FromStr for Signature { fn from_str(s: &str) -> Result { let mut bytes = [0_u8; 64]; hex::decode_to_slice(s, &mut bytes)?; - Ok(Signature(bytes)) + Ok(Self(bytes)) } } @@ -194,11 +194,11 @@ impl Transaction { /// Get the hash of the transaction #[expect(clippy::same_name_method, reason = "This is handy")] #[must_use] - pub fn hash(&self) -> &self::HashType { + pub const fn hash(&self) -> &self::HashType { match self { - Transaction::Public(tx) => &tx.hash, - Transaction::PrivacyPreserving(tx) => &tx.hash, - Transaction::ProgramDeployment(tx) => &tx.hash, + Self::Public(tx) => &tx.hash, + Self::PrivacyPreserving(tx) => &tx.hash, + Self::ProgramDeployment(tx) => &tx.hash, } } } @@ -338,7 +338,7 @@ impl FromStr for HashType { fn from_str(s: &str) -> Result { let mut bytes = [0_u8; 32]; hex::decode_to_slice(s, &mut bytes)?; - Ok(HashType(bytes)) + Ok(Self(bytes)) } } diff --git a/indexer/service/src/lib.rs b/indexer/service/src/lib.rs index cfbe93a0..1f87e929 100644 --- a/indexer/service/src/lib.rs +++ b/indexer/service/src/lib.rs @@ -16,7 +16,7 @@ pub struct IndexerHandle { server_handle: Option, } impl IndexerHandle { - fn new(addr: SocketAddr, server_handle: jsonrpsee::server::ServerHandle) -> Self { + const fn new(addr: SocketAddr, server_handle: jsonrpsee::server::ServerHandle) -> Self { Self { addr, server_handle: Some(server_handle), @@ -24,7 +24,7 @@ impl IndexerHandle { } #[must_use] - pub fn addr(&self) -> SocketAddr { + pub const fn addr(&self) -> SocketAddr { self.addr } diff --git a/indexer/service/src/service.rs b/indexer/service/src/service.rs index 85d4f32f..2b2e3eca 100644 --- a/indexer/service/src/service.rs +++ b/indexer/service/src/service.rs @@ -252,7 +252,7 @@ struct Subscription { } impl Subscription { - fn new(sink: SubscriptionSink) -> Self { + const fn new(sink: SubscriptionSink) -> Self { Self { sink, _marker: std::marker::PhantomData, diff --git a/integration_tests/src/config.rs b/integration_tests/src/config.rs index e20179eb..0ce55177 100644 --- a/integration_tests/src/config.rs +++ b/integration_tests/src/config.rs @@ -158,8 +158,8 @@ pub enum UrlProtocol { impl std::fmt::Display for UrlProtocol { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - UrlProtocol::Http => write!(f, "http"), - UrlProtocol::Ws => write!(f, "ws"), + Self::Http => write!(f, "http"), + Self::Ws => write!(f, "ws"), } } } diff --git a/integration_tests/src/lib.rs b/integration_tests/src/lib.rs index 2492d939..4217b269 100644 --- a/integration_tests/src/lib.rs +++ b/integration_tests/src/lib.rs @@ -53,7 +53,7 @@ impl TestContext { } #[must_use] - pub fn builder() -> TestContextBuilder { + pub const fn builder() -> TestContextBuilder { TestContextBuilder::new() } @@ -271,7 +271,7 @@ impl TestContext { /// Get reference to the wallet. #[must_use] - pub fn wallet(&self) -> &WalletCore { + pub const fn wallet(&self) -> &WalletCore { &self.wallet } @@ -281,19 +281,19 @@ impl TestContext { } /// Get mutable reference to the wallet. - pub fn wallet_mut(&mut self) -> &mut WalletCore { + pub const fn wallet_mut(&mut self) -> &mut WalletCore { &mut self.wallet } /// Get reference to the sequencer client. #[must_use] - pub fn sequencer_client(&self) -> &SequencerClient { + pub const fn sequencer_client(&self) -> &SequencerClient { &self.sequencer_client } /// Get reference to the indexer client. #[must_use] - pub fn indexer_client(&self) -> &IndexerClient { + pub const fn indexer_client(&self) -> &IndexerClient { &self.indexer_client } @@ -384,7 +384,7 @@ impl BlockingTestContext { }) } - pub fn ctx(&self) -> &TestContext { + pub const fn ctx(&self) -> &TestContext { self.ctx.as_ref().expect("TestContext is set") } } @@ -395,7 +395,7 @@ pub struct TestContextBuilder { } impl TestContextBuilder { - fn new() -> Self { + const fn new() -> Self { Self { initial_data: None, sequencer_partial_config: None, @@ -409,7 +409,7 @@ impl TestContextBuilder { } #[must_use] - pub fn with_sequencer_partial_config( + pub const fn with_sequencer_partial_config( mut self, sequencer_partial_config: config::SequencerPartialConfig, ) -> Self { diff --git a/integration_tests/tests/tps.rs b/integration_tests/tests/tps.rs index a1e67fe5..c89ee761 100644 --- a/integration_tests/tests/tps.rs +++ b/integration_tests/tests/tps.rs @@ -118,7 +118,7 @@ impl TpsTestManager { } } - fn generate_sequencer_partial_config() -> SequencerPartialConfig { + const fn generate_sequencer_partial_config() -> SequencerPartialConfig { SequencerPartialConfig { max_num_tx_in_block: 300, max_block_size: ByteSize::mb(500), diff --git a/integration_tests/tests/wallet_ffi.rs b/integration_tests/tests/wallet_ffi.rs index 380f8b7b..2170734c 100644 --- a/integration_tests/tests/wallet_ffi.rs +++ b/integration_tests/tests/wallet_ffi.rs @@ -216,12 +216,7 @@ fn new_wallet_rust_with_default_config(password: &str) -> Result { let config_path = tempdir.path().join("wallet_config.json"); let storage_path = tempdir.path().join("storage.json"); - WalletCore::new_init_storage( - config_path.clone(), - storage_path.clone(), - None, - password.to_owned(), - ) + WalletCore::new_init_storage(config_path, storage_path, None, password.to_owned()) } fn load_existing_ffi_wallet(home: &Path) -> Result<*mut WalletHandle> { diff --git a/key_protocol/src/key_management/key_tree/chain_index.rs b/key_protocol/src/key_management/key_tree/chain_index.rs index e3700393..b22dc779 100644 --- a/key_protocol/src/key_management/key_tree/chain_index.rs +++ b/key_protocol/src/key_management/key_tree/chain_index.rs @@ -23,7 +23,7 @@ impl FromStr for ChainIndex { } if s == "/" { - return Ok(ChainIndex(vec![])); + return Ok(Self(vec![])); } let uprooted_substring = s.strip_prefix("/").unwrap(); @@ -55,14 +55,14 @@ impl Display for ChainIndex { impl Default for ChainIndex { fn default() -> Self { - ChainIndex::from_str("/").expect("Root parsing failure") + Self::from_str("/").expect("Root parsing failure") } } impl ChainIndex { #[must_use] pub fn root() -> Self { - ChainIndex::default() + Self::default() } #[must_use] @@ -76,42 +76,42 @@ impl ChainIndex { } #[must_use] - pub fn next_in_line(&self) -> Option { + pub fn next_in_line(&self) -> Option { let mut chain = self.0.clone(); // ToDo: Add overflow check if let Some(last_p) = chain.last_mut() { *last_p = last_p.checked_add(1)?; } - Some(ChainIndex(chain)) + Some(Self(chain)) } #[must_use] - pub fn previous_in_line(&self) -> Option { + pub fn previous_in_line(&self) -> Option { let mut chain = self.0.clone(); if let Some(last_p) = chain.last_mut() { *last_p = last_p.checked_sub(1)?; } - Some(ChainIndex(chain)) + Some(Self(chain)) } #[must_use] - pub fn parent(&self) -> Option { + pub fn parent(&self) -> Option { if self.0.is_empty() { None } else { let last = self.0.len().checked_sub(1)?; - Some(ChainIndex(self.0[..last].to_vec())) + Some(Self(self.0[..last].to_vec())) } } #[must_use] - pub fn nth_child(&self, child_id: u32) -> ChainIndex { + pub fn nth_child(&self, child_id: u32) -> Self { let mut chain = self.0.clone(); chain.push(child_id); - ChainIndex(chain) + Self(chain) } #[must_use] @@ -131,17 +131,17 @@ impl ChainIndex { Some(res) } - fn shuffle_iter(&self) -> impl Iterator { + fn shuffle_iter(&self) -> impl Iterator { self.0 .iter() .permutations(self.0.len()) .unique() - .map(|item| ChainIndex(item.into_iter().copied().collect())) + .map(|item| Self(item.into_iter().copied().collect())) } - pub fn chain_ids_at_depth(depth: usize) -> impl Iterator { - let mut stack = vec![ChainIndex(vec![0; depth])]; - let mut cumulative_stack = vec![ChainIndex(vec![0; depth])]; + pub fn chain_ids_at_depth(depth: usize) -> impl Iterator { + let mut stack = vec![Self(vec![0; depth])]; + let mut cumulative_stack = vec![Self(vec![0; depth])]; while let Some(top_id) = stack.pop() { if let Some(collapsed_id) = top_id.collapse_back() { @@ -155,9 +155,9 @@ impl ChainIndex { cumulative_stack.into_iter().unique() } - pub fn chain_ids_at_depth_rev(depth: usize) -> impl Iterator { - let mut stack = vec![ChainIndex(vec![0; depth])]; - let mut cumulative_stack = vec![ChainIndex(vec![0; depth])]; + pub fn chain_ids_at_depth_rev(depth: usize) -> impl Iterator { + let mut stack = vec![Self(vec![0; depth])]; + let mut cumulative_stack = vec![Self(vec![0; depth])]; while let Some(top_id) = stack.pop() { if let Some(collapsed_id) = top_id.collapse_back() { diff --git a/key_protocol/src/key_management/key_tree/keys_public.rs b/key_protocol/src/key_management/key_tree/keys_public.rs index 06c3de05..694c23c5 100644 --- a/key_protocol/src/key_management/key_tree/keys_public.rs +++ b/key_protocol/src/key_management/key_tree/keys_public.rs @@ -19,16 +19,13 @@ impl ChildKeysPublic { if 2_u32.pow(31) > cci { // Non-harden hash_input.extend_from_slice(self.cpk.value()); - hash_input.extend_from_slice(&cci.to_le_bytes()); - - hmac_sha512::HMAC::mac(hash_input, self.ccc) } else { // Harden hash_input.extend_from_slice(self.csk.value()); - hash_input.extend_from_slice(&(cci).to_le_bytes()); - - hmac_sha512::HMAC::mac(hash_input, self.ccc) } + hash_input.extend_from_slice(&cci.to_le_bytes()); + + hmac_sha512::HMAC::mac(hash_input, self.ccc) } } diff --git a/key_protocol/src/key_protocol_core/mod.rs b/key_protocol/src/key_protocol_core/mod.rs index d870b902..19ae45a3 100644 --- a/key_protocol/src/key_protocol_core/mod.rs +++ b/key_protocol/src/key_protocol_core/mod.rs @@ -104,17 +104,14 @@ impl NSSAUserData { } /// Returns the signing key for public transaction signatures + #[must_use] pub fn get_pub_account_signing_key( &self, account_id: nssa::AccountId, ) -> Option<&nssa::PrivateKey> { - // First seek in defaults - if let Some(key) = self.default_pub_account_signing_keys.get(&account_id) { - Some(key) - // Then seek in tree - } else { - self.public_key_tree.get_node(account_id).map(Into::into) - } + self.default_pub_account_signing_keys + .get(&account_id) + .or_else(|| self.public_key_tree.get_node(account_id).map(Into::into)) } /// Generated new private key for privacy preserving transactions @@ -137,17 +134,14 @@ impl NSSAUserData { } /// Returns the signing key for public transaction signatures + #[must_use] pub fn get_private_account( &self, account_id: nssa::AccountId, ) -> Option<&(KeyChain, nssa_core::account::Account)> { - // First seek in defaults - if let Some(key) = self.default_user_private_accounts.get(&account_id) { - Some(key) - // Then seek in tree - } else { - self.private_key_tree.get_node(account_id).map(Into::into) - } + self.default_user_private_accounts + .get(&account_id) + .or_else(|| self.private_key_tree.get_node(account_id).map(Into::into)) } /// Returns the signing key for public transaction signatures diff --git a/mempool/src/lib.rs b/mempool/src/lib.rs index fa844065..ff06da7d 100644 --- a/mempool/src/lib.rs +++ b/mempool/src/lib.rs @@ -49,7 +49,7 @@ pub struct MemPoolHandle { } impl MemPoolHandle { - fn new(sender: Sender) -> Self { + const fn new(sender: Sender) -> Self { Self { sender } } diff --git a/nssa/core/src/account.rs b/nssa/core/src/account.rs index 98799c9f..fa76dd08 100644 --- a/nssa/core/src/account.rs +++ b/nssa/core/src/account.rs @@ -88,17 +88,17 @@ impl std::fmt::Debug for AccountId { impl AccountId { #[must_use] - pub fn new(value: [u8; 32]) -> Self { + pub const fn new(value: [u8; 32]) -> Self { Self { value } } #[must_use] - pub fn value(&self) -> &[u8; 32] { + pub const fn value(&self) -> &[u8; 32] { &self.value } #[must_use] - pub fn into_value(self) -> [u8; 32] { + pub const fn into_value(self) -> [u8; 32] { self.value } } @@ -127,7 +127,7 @@ impl FromStr for AccountId { } let mut value = [0_u8; 32]; value.copy_from_slice(&bytes); - Ok(AccountId { value }) + Ok(Self { value }) } } diff --git a/nssa/core/src/commitment.rs b/nssa/core/src/commitment.rs index 87e1ac79..8cb4431b 100644 --- a/nssa/core/src/commitment.rs +++ b/nssa/core/src/commitment.rs @@ -91,18 +91,16 @@ pub fn compute_digest_for_path( .unwrap(); let mut level_index = proof.0; for node in &proof.1 { + let mut bytes = [0_u8; 64]; let is_left_child = level_index & 1 == 0; if is_left_child { - let mut bytes = [0_u8; 64]; bytes[..32].copy_from_slice(&result); bytes[32..].copy_from_slice(node); - result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap(); } else { - let mut bytes = [0_u8; 64]; bytes[..32].copy_from_slice(node); bytes[32..].copy_from_slice(&result); - result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap(); } + result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap(); level_index >>= 1; } result diff --git a/nssa/core/src/encoding.rs b/nssa/core/src/encoding.rs index 04e3ac88..6abd4c11 100644 --- a/nssa/core/src/encoding.rs +++ b/nssa/core/src/encoding.rs @@ -69,13 +69,13 @@ impl Account { impl Commitment { #[must_use] - pub fn to_byte_array(&self) -> [u8; 32] { + pub const fn to_byte_array(&self) -> [u8; 32] { self.0 } #[cfg(feature = "host")] #[must_use] - pub fn from_byte_array(bytes: [u8; 32]) -> Self { + pub const fn from_byte_array(bytes: [u8; 32]) -> Self { Self(bytes) } @@ -90,7 +90,7 @@ impl Commitment { impl NullifierPublicKey { #[must_use] - pub fn to_byte_array(&self) -> [u8; 32] { + pub const fn to_byte_array(&self) -> [u8; 32] { self.0 } } @@ -98,13 +98,13 @@ impl NullifierPublicKey { #[cfg(feature = "host")] impl Nullifier { #[must_use] - pub fn to_byte_array(&self) -> [u8; 32] { + pub const fn to_byte_array(&self) -> [u8; 32] { self.0 } #[cfg(feature = "host")] #[must_use] - pub fn from_byte_array(bytes: [u8; 32]) -> Self { + pub const fn from_byte_array(bytes: [u8; 32]) -> Self { Self(bytes) } @@ -137,7 +137,7 @@ impl Ciphertext { #[cfg(feature = "host")] #[must_use] - pub fn from_inner(inner: Vec) -> Self { + pub const fn from_inner(inner: Vec) -> Self { Self(inner) } @@ -175,7 +175,7 @@ impl Secp256k1Point { impl AccountId { #[must_use] - pub fn to_bytes(&self) -> [u8; 32] { + pub const fn to_bytes(&self) -> [u8; 32] { *self.value() } } diff --git a/nssa/core/src/encryption/mod.rs b/nssa/core/src/encryption/mod.rs index 1d722a5e..400fb331 100644 --- a/nssa/core/src/encryption/mod.rs +++ b/nssa/core/src/encryption/mod.rs @@ -44,7 +44,7 @@ impl EncryptionScheme { commitment: &Commitment, output_index: u32, ) -> Ciphertext { - let mut buffer = account.to_bytes().clone(); + let mut buffer = account.to_bytes(); Self::symmetric_transform(&mut buffer, shared_secret, commitment, output_index); Ciphertext(buffer) } diff --git a/nssa/core/src/encryption/shared_key_derivation.rs b/nssa/core/src/encryption/shared_key_derivation.rs index c5890f49..8169e8f9 100644 --- a/nssa/core/src/encryption/shared_key_derivation.rs +++ b/nssa/core/src/encryption/shared_key_derivation.rs @@ -32,7 +32,7 @@ impl std::fmt::Debug for Secp256k1Point { impl Secp256k1Point { #[must_use] - pub fn from_scalar(value: Scalar) -> Secp256k1Point { + pub fn from_scalar(value: Scalar) -> Self { let x_bytes: FieldBytes = value.into(); let x = k256::Scalar::from_repr(x_bytes).unwrap(); @@ -49,7 +49,7 @@ pub type EphemeralPublicKey = Secp256k1Point; pub type ViewingPublicKey = Secp256k1Point; impl From<&EphemeralSecretKey> for EphemeralPublicKey { fn from(value: &EphemeralSecretKey) -> Self { - Secp256k1Point::from_scalar(*value) + Self::from_scalar(*value) } } diff --git a/nssa/core/src/nullifier.rs b/nssa/core/src/nullifier.rs index 2ba9afc4..6ba59860 100644 --- a/nssa/core/src/nullifier.rs +++ b/nssa/core/src/nullifier.rs @@ -16,7 +16,12 @@ impl From<&NullifierPublicKey> for AccountId { let mut bytes = [0; 64]; bytes[0..32].copy_from_slice(PRIVATE_ACCOUNT_ID_PREFIX); bytes[32..].copy_from_slice(&value.0); - AccountId::new(Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap()) + Self::new( + Impl::hash_bytes(&bytes) + .as_bytes() + .try_into() + .expect("Conversion should not fail"), + ) } } @@ -36,7 +41,12 @@ impl From<&NullifierSecretKey> for NullifierPublicKey { bytes.extend_from_slice(value); bytes.extend_from_slice(SUFFIX_1); bytes.extend_from_slice(SUFFIX_2); - Self(Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap()) + Self( + Impl::hash_bytes(&bytes) + .as_bytes() + .try_into() + .expect("hash should be exactly 32 bytes long"), + ) } } diff --git a/nssa/core/src/program.rs b/nssa/core/src/program.rs index b541e5f0..bbb1e03b 100644 --- a/nssa/core/src/program.rs +++ b/nssa/core/src/program.rs @@ -42,7 +42,7 @@ impl From<(&ProgramId, &PdaSeed)> for AccountId { bytemuck::try_cast_slice(value.0).expect("ProgramId should be castable to &[u8]"); bytes[32..64].copy_from_slice(program_id_bytes); bytes[64..].copy_from_slice(&value.1.0); - AccountId::new( + Self::new( Impl::hash_bytes(&bytes) .as_bytes() .try_into() @@ -85,6 +85,7 @@ impl ChainedCall { } /// Represents the final state of an `Account` after a program execution. +/// /// A post state may optionally request that the executing program /// becomes the owner of the account (a “claim”). This is used to signal /// that the program intends to take ownership of the account. @@ -99,7 +100,7 @@ impl AccountPostState { /// Creates a post state without a claim request. /// The executing program is not requesting ownership of the account. #[must_use] - pub fn new(account: Account) -> Self { + pub const fn new(account: Account) -> Self { Self { account, claim: false, @@ -110,7 +111,7 @@ impl AccountPostState { /// This indicates that the executing program intends to claim the /// account as its own and is allowed to mutate it. #[must_use] - pub fn new_claimed(account: Account) -> Self { + pub const fn new_claimed(account: Account) -> Self { Self { account, claim: true, @@ -128,18 +129,18 @@ impl AccountPostState { /// Returns `true` if this post state requests that the account /// be claimed (owned) by the executing program. #[must_use] - pub fn requires_claim(&self) -> bool { + pub const fn requires_claim(&self) -> bool { self.claim } /// Returns the underlying account #[must_use] - pub fn account(&self) -> &Account { + pub const fn account(&self) -> &Account { &self.account } /// Returns the underlying account - pub fn account_mut(&mut self) -> &mut Account { + pub const fn account_mut(&mut self) -> &mut Account { &mut self.account } @@ -174,7 +175,7 @@ impl WrappedBalanceSum { /// Returns [`None`] if balance sum overflows `lo + hi * 2^128` representation, which is not /// expected in practical scenarios. fn from_balances(balances: impl Iterator) -> Option { - let mut wrapped = WrappedBalanceSum { lo: 0, hi: 0 }; + let mut wrapped = Self { lo: 0, hi: 0 }; for balance in balances { let (new_sum, did_overflow) = wrapped.lo.overflowing_add(balance); diff --git a/nssa/src/merkle_tree/default_values.rs b/nssa/src/merkle_tree/default_values.rs index 03166440..f4c8cbd1 100644 --- a/nssa/src/merkle_tree/default_values.rs +++ b/nssa/src/merkle_tree/default_values.rs @@ -1,4 +1,4 @@ -pub(crate) const DEFAULT_VALUES: [[u8; 32]; 32] = [ +pub const DEFAULT_VALUES: [[u8; 32]; 32] = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, diff --git a/nssa/src/merkle_tree/mod.rs b/nssa/src/merkle_tree/mod.rs index a2d97784..1126336c 100644 --- a/nssa/src/merkle_tree/mod.rs +++ b/nssa/src/merkle_tree/mod.rs @@ -156,7 +156,7 @@ fn hash_value(value: &Value) -> Node { hasher.finalize().into() } -fn prev_power_of_two(x: usize) -> usize { +const fn prev_power_of_two(x: usize) -> usize { if x == 0 { return 0; } diff --git a/nssa/src/privacy_preserving_transaction/circuit.rs b/nssa/src/privacy_preserving_transaction/circuit.rs index d1afe96d..4de1c2c4 100644 --- a/nssa/src/privacy_preserving_transaction/circuit.rs +++ b/nssa/src/privacy_preserving_transaction/circuit.rs @@ -27,7 +27,7 @@ impl Proof { } #[must_use] - pub fn from_inner(inner: Vec) -> Self { + pub const fn from_inner(inner: Vec) -> Self { Self(inner) } @@ -47,7 +47,7 @@ pub struct ProgramWithDependencies { impl ProgramWithDependencies { #[must_use] - pub fn new(program: Program, dependencies: HashMap) -> Self { + pub const fn new(program: Program, dependencies: HashMap) -> Self { Self { program, dependencies, @@ -57,7 +57,7 @@ impl ProgramWithDependencies { impl From for ProgramWithDependencies { fn from(program: Program) -> Self { - ProgramWithDependencies::new(program, HashMap::new()) + Self::new(program, HashMap::new()) } } @@ -328,7 +328,7 @@ mod tests { let shared_secret_2 = SharedSecretKey::new(&esk_2, &recipient_keys.vpk()); let (output, proof) = execute_and_prove( - vec![sender_pre.clone(), recipient], + vec![sender_pre, recipient], Program::serialize_instruction(balance_to_move).unwrap(), vec![1, 2], vec![0xdead_beef1, 0xdead_beef2], diff --git a/nssa/src/privacy_preserving_transaction/message.rs b/nssa/src/privacy_preserving_transaction/message.rs index fedd4438..34f5058f 100644 --- a/nssa/src/privacy_preserving_transaction/message.rs +++ b/nssa/src/privacy_preserving_transaction/message.rs @@ -155,12 +155,12 @@ pub mod tests { )]; Message { - public_account_ids: public_account_ids.clone(), - nonces: nonces.clone(), - public_post_states: public_post_states.clone(), - encrypted_private_post_states: encrypted_private_post_states.clone(), - new_commitments: new_commitments.clone(), - new_nullifiers: new_nullifiers.clone(), + public_account_ids, + nonces, + public_post_states, + encrypted_private_post_states, + new_commitments, + new_nullifiers, } } diff --git a/nssa/src/privacy_preserving_transaction/transaction.rs b/nssa/src/privacy_preserving_transaction/transaction.rs index 72119959..2b268c07 100644 --- a/nssa/src/privacy_preserving_transaction/transaction.rs +++ b/nssa/src/privacy_preserving_transaction/transaction.rs @@ -25,7 +25,7 @@ pub struct PrivacyPreservingTransaction { impl PrivacyPreservingTransaction { #[must_use] - pub fn new(message: Message, witness_set: WitnessSet) -> Self { + pub const fn new(message: Message, witness_set: WitnessSet) -> Self { Self { message, witness_set, @@ -129,12 +129,12 @@ impl PrivacyPreservingTransaction { } #[must_use] - pub fn message(&self) -> &Message { + pub const fn message(&self) -> &Message { &self.message } #[must_use] - pub fn witness_set(&self) -> &WitnessSet { + pub const fn witness_set(&self) -> &WitnessSet { &self.witness_set } diff --git a/nssa/src/privacy_preserving_transaction/witness_set.rs b/nssa/src/privacy_preserving_transaction/witness_set.rs index df80c420..373bbc9c 100644 --- a/nssa/src/privacy_preserving_transaction/witness_set.rs +++ b/nssa/src/privacy_preserving_transaction/witness_set.rs @@ -47,7 +47,7 @@ impl WitnessSet { } #[must_use] - pub fn proof(&self) -> &Proof { + pub const fn proof(&self) -> &Proof { &self.proof } @@ -57,7 +57,7 @@ impl WitnessSet { } #[must_use] - pub fn from_raw_parts( + pub const fn from_raw_parts( signatures_and_public_keys: Vec<(Signature, PublicKey)>, proof: Proof, ) -> Self { diff --git a/nssa/src/program.rs b/nssa/src/program.rs index 87b85749..90ca0244 100644 --- a/nssa/src/program.rs +++ b/nssa/src/program.rs @@ -33,7 +33,7 @@ impl Program { } #[must_use] - pub fn id(&self) -> ProgramId { + pub const fn id(&self) -> ProgramId { self.id } @@ -142,7 +142,7 @@ mod tests { pub fn nonce_changer_program() -> Self { use test_program_methods::{NONCE_CHANGER_ELF, NONCE_CHANGER_ID}; - Program { + Self { id: NONCE_CHANGER_ID, elf: NONCE_CHANGER_ELF.to_vec(), } @@ -153,7 +153,7 @@ mod tests { pub fn extra_output_program() -> Self { use test_program_methods::{EXTRA_OUTPUT_ELF, EXTRA_OUTPUT_ID}; - Program { + Self { id: EXTRA_OUTPUT_ID, elf: EXTRA_OUTPUT_ELF.to_vec(), } @@ -164,7 +164,7 @@ mod tests { pub fn missing_output_program() -> Self { use test_program_methods::{MISSING_OUTPUT_ELF, MISSING_OUTPUT_ID}; - Program { + Self { id: MISSING_OUTPUT_ID, elf: MISSING_OUTPUT_ELF.to_vec(), } @@ -175,7 +175,7 @@ mod tests { pub fn program_owner_changer() -> Self { use test_program_methods::{PROGRAM_OWNER_CHANGER_ELF, PROGRAM_OWNER_CHANGER_ID}; - Program { + Self { id: PROGRAM_OWNER_CHANGER_ID, elf: PROGRAM_OWNER_CHANGER_ELF.to_vec(), } @@ -186,7 +186,7 @@ mod tests { pub fn simple_balance_transfer() -> Self { use test_program_methods::{SIMPLE_BALANCE_TRANSFER_ELF, SIMPLE_BALANCE_TRANSFER_ID}; - Program { + Self { id: SIMPLE_BALANCE_TRANSFER_ID, elf: SIMPLE_BALANCE_TRANSFER_ELF.to_vec(), } @@ -197,7 +197,7 @@ mod tests { pub fn data_changer() -> Self { use test_program_methods::{DATA_CHANGER_ELF, DATA_CHANGER_ID}; - Program { + Self { id: DATA_CHANGER_ID, elf: DATA_CHANGER_ELF.to_vec(), } @@ -208,7 +208,7 @@ mod tests { pub fn minter() -> Self { use test_program_methods::{MINTER_ELF, MINTER_ID}; - Program { + Self { id: MINTER_ID, elf: MINTER_ELF.to_vec(), } @@ -219,7 +219,7 @@ mod tests { pub fn burner() -> Self { use test_program_methods::{BURNER_ELF, BURNER_ID}; - Program { + Self { id: BURNER_ID, elf: BURNER_ELF.to_vec(), } @@ -229,7 +229,7 @@ mod tests { pub fn chain_caller() -> Self { use test_program_methods::{CHAIN_CALLER_ELF, CHAIN_CALLER_ID}; - Program { + Self { id: CHAIN_CALLER_ID, elf: CHAIN_CALLER_ELF.to_vec(), } @@ -239,7 +239,7 @@ mod tests { pub fn claimer() -> Self { use test_program_methods::{CLAIMER_ELF, CLAIMER_ID}; - Program { + Self { id: CLAIMER_ID, elf: CLAIMER_ELF.to_vec(), } @@ -249,7 +249,7 @@ mod tests { pub fn changer_claimer() -> Self { use test_program_methods::{CHANGER_CLAIMER_ELF, CHANGER_CLAIMER_ID}; - Program { + Self { id: CHANGER_CLAIMER_ID, elf: CHANGER_CLAIMER_ELF.to_vec(), } @@ -259,7 +259,7 @@ mod tests { pub fn noop() -> Self { use test_program_methods::{NOOP_ELF, NOOP_ID}; - Program { + Self { id: NOOP_ID, elf: NOOP_ELF.to_vec(), } @@ -271,7 +271,7 @@ mod tests { MALICIOUS_AUTHORIZATION_CHANGER_ELF, MALICIOUS_AUTHORIZATION_CHANGER_ID, }; - Program { + Self { id: MALICIOUS_AUTHORIZATION_CHANGER_ID, elf: MALICIOUS_AUTHORIZATION_CHANGER_ELF.to_vec(), } diff --git a/nssa/src/program_deployment_transaction/message.rs b/nssa/src/program_deployment_transaction/message.rs index 1f8b7500..a51e4149 100644 --- a/nssa/src/program_deployment_transaction/message.rs +++ b/nssa/src/program_deployment_transaction/message.rs @@ -7,7 +7,7 @@ pub struct Message { impl Message { #[must_use] - pub fn new(bytecode: Vec) -> Self { + pub const fn new(bytecode: Vec) -> Self { Self { bytecode } } diff --git a/nssa/src/program_deployment_transaction/transaction.rs b/nssa/src/program_deployment_transaction/transaction.rs index 1cdb238a..1e53388d 100644 --- a/nssa/src/program_deployment_transaction/transaction.rs +++ b/nssa/src/program_deployment_transaction/transaction.rs @@ -13,7 +13,7 @@ pub struct ProgramDeploymentTransaction { impl ProgramDeploymentTransaction { #[must_use] - pub fn new(message: Message) -> Self { + pub const fn new(message: Message) -> Self { Self { message } } @@ -44,7 +44,7 @@ impl ProgramDeploymentTransaction { } #[must_use] - pub fn affected_public_account_ids(&self) -> Vec { + pub const fn affected_public_account_ids(&self) -> Vec { vec![] } } diff --git a/nssa/src/public_transaction/message.rs b/nssa/src/public_transaction/message.rs index 15eba285..d4838b87 100644 --- a/nssa/src/public_transaction/message.rs +++ b/nssa/src/public_transaction/message.rs @@ -50,7 +50,7 @@ impl Message { } #[must_use] - pub fn new_preserialized( + pub const fn new_preserialized( program_id: ProgramId, account_ids: Vec, nonces: Vec, diff --git a/nssa/src/public_transaction/transaction.rs b/nssa/src/public_transaction/transaction.rs index d19c12d4..4c4cd0b3 100644 --- a/nssa/src/public_transaction/transaction.rs +++ b/nssa/src/public_transaction/transaction.rs @@ -23,7 +23,7 @@ pub struct PublicTransaction { impl PublicTransaction { #[must_use] - pub fn new(message: Message, witness_set: WitnessSet) -> Self { + pub const fn new(message: Message, witness_set: WitnessSet) -> Self { Self { message, witness_set, @@ -31,12 +31,12 @@ impl PublicTransaction { } #[must_use] - pub fn message(&self) -> &Message { + pub const fn message(&self) -> &Message { &self.message } #[must_use] - pub fn witness_set(&self) -> &WitnessSet { + pub const fn witness_set(&self) -> &WitnessSet { &self.witness_set } diff --git a/nssa/src/public_transaction/witness_set.rs b/nssa/src/public_transaction/witness_set.rs index 59ef5c50..49c18b81 100644 --- a/nssa/src/public_transaction/witness_set.rs +++ b/nssa/src/public_transaction/witness_set.rs @@ -47,7 +47,7 @@ impl WitnessSet { } #[must_use] - pub fn from_raw_parts(signatures_and_public_keys: Vec<(Signature, PublicKey)>) -> Self { + pub const fn from_raw_parts(signatures_and_public_keys: Vec<(Signature, PublicKey)>) -> Self { Self { signatures_and_public_keys, } diff --git a/nssa/src/signature/private_key.rs b/nssa/src/signature/private_key.rs index f643406a..d8ece0e0 100644 --- a/nssa/src/signature/private_key.rs +++ b/nssa/src/signature/private_key.rs @@ -33,7 +33,7 @@ impl PrivateKey { } #[must_use] - pub fn value(&self) -> &[u8; 32] { + pub const fn value(&self) -> &[u8; 32] { &self.0 } } diff --git a/nssa/src/signature/public_key.rs b/nssa/src/signature/public_key.rs index 0522e114..9cdac761 100644 --- a/nssa/src/signature/public_key.rs +++ b/nssa/src/signature/public_key.rs @@ -44,7 +44,7 @@ impl PublicKey { } #[must_use] - pub fn value(&self) -> &[u8; 32] { + pub const fn value(&self) -> &[u8; 32] { &self.0 } } diff --git a/nssa/src/state.rs b/nssa/src/state.rs index 2210ae5c..6dbb2852 100644 --- a/nssa/src/state.rs +++ b/nssa/src/state.rs @@ -18,7 +18,7 @@ pub const MAX_NUMBER_CHAINED_CALLS: usize = 10; #[derive(Clone, BorshSerialize, BorshDeserialize)] #[cfg_attr(test, derive(Debug, PartialEq, Eq))] -pub(crate) struct CommitmentSet { +pub struct CommitmentSet { merkle_tree: MerkleTree, commitments: HashMap, root_history: HashSet, @@ -54,7 +54,7 @@ impl CommitmentSet { /// Initializes an empty `CommitmentSet` with a given capacity. /// If the capacity is not a `power_of_two`, then capacity is taken /// to be the next `power_of_two`. - pub(crate) fn with_capacity(capacity: usize) -> CommitmentSet { + pub(crate) fn with_capacity(capacity: usize) -> Self { Self { merkle_tree: MerkleTree::with_capacity(capacity), commitments: HashMap::new(), @@ -68,7 +68,7 @@ impl CommitmentSet { struct NullifierSet(BTreeSet); impl NullifierSet { - fn new() -> Self { + const fn new() -> Self { Self(BTreeSet::new()) } @@ -242,7 +242,7 @@ impl V02State { self.public_state .get(&account_id) .cloned() - .unwrap_or(Account::default()) + .unwrap_or_else(Account::default) } #[must_use] @@ -250,7 +250,7 @@ impl V02State { self.private_state.0.get_proof_for(commitment) } - pub(crate) fn programs(&self) -> &HashMap { + pub(crate) const fn programs(&self) -> &HashMap { &self.programs } @@ -631,8 +631,7 @@ pub mod tests { fn lp_supply_init() -> u128 { // isqrt(vault_a_balance_init * vault_b_balance_init) = isqrt(5_000 * 2_500) = 3535 - (BalanceForTests::vault_a_balance_init() * BalanceForTests::vault_b_balance_init()) - .isqrt() + (Self::vault_a_balance_init() * Self::vault_b_balance_init()).isqrt() } } @@ -642,16 +641,13 @@ pub mod tests { fn pool_definition_id() -> AccountId { amm_core::compute_pool_pda( Program::amm().id(), - IdForTests::token_a_definition_id(), - IdForTests::token_b_definition_id(), + Self::token_a_definition_id(), + Self::token_b_definition_id(), ) } fn token_lp_definition_id() -> AccountId { - amm_core::compute_liquidity_token_pda( - Program::amm().id(), - IdForTests::pool_definition_id(), - ) + amm_core::compute_liquidity_token_pda(Program::amm().id(), Self::pool_definition_id()) } fn token_a_definition_id() -> AccountId { @@ -683,16 +679,16 @@ pub mod tests { fn vault_a_id() -> AccountId { amm_core::compute_vault_pda( Program::amm().id(), - IdForTests::pool_definition_id(), - IdForTests::token_a_definition_id(), + Self::pool_definition_id(), + Self::token_a_definition_id(), ) } fn vault_b_id() -> AccountId { amm_core::compute_vault_pda( Program::amm().id(), - IdForTests::pool_definition_id(), - IdForTests::token_b_definition_id(), + Self::pool_definition_id(), + Self::token_b_definition_id(), ) } } @@ -2199,7 +2195,7 @@ pub mod tests { vec![], vec![], vec![], - &program.clone().into(), + &program.into(), ); assert!(matches!(result, Err(NssaError::ProgramProveFailed(_)))); @@ -4205,7 +4201,7 @@ pub mod tests { // Prepare new state of account let account_metadata = { - let mut acc = authorized_account.clone(); + let mut acc = authorized_account; acc.account.program_owner = Program::claimer().id(); acc }; diff --git a/program_methods/guest/src/bin/privacy_preserving_circuit.rs b/program_methods/guest/src/bin/privacy_preserving_circuit.rs index f4b3e6c9..b74b3e65 100644 --- a/program_methods/guest/src/bin/privacy_preserving_circuit.rs +++ b/program_methods/guest/src/bin/privacy_preserving_circuit.rs @@ -37,7 +37,7 @@ impl ExecutionState { }; let mut chained_calls = VecDeque::from_iter([(initial_call, None)]); - let mut execution_state = ExecutionState { + let mut execution_state = Self { pre_states: Vec::new(), post_states: HashMap::new(), }; @@ -324,10 +324,9 @@ fn compute_circuit_output( output.new_commitments.push(commitment_post); output.ciphertexts.push(encrypted_account); - output_index = match output_index.checked_add(1) { - Some(val) => val, - None => panic!("Too many private accounts, output index overflow"), - } + output_index = output_index + .checked_add(1) + .unwrap_or_else(|| panic!("Too many private accounts, output index overflow")); } _ => panic!("Invalid visibility mask value"), } diff --git a/programs/amm/core/src/lib.rs b/programs/amm/core/src/lib.rs index d499ae9f..05b0b870 100644 --- a/programs/amm/core/src/lib.rs +++ b/programs/amm/core/src/lib.rs @@ -97,7 +97,7 @@ impl TryFrom<&Data> for PoolDefinition { type Error = std::io::Error; fn try_from(data: &Data) -> Result { - PoolDefinition::try_from_slice(data.as_ref()) + Self::try_from_slice(data.as_ref()) } } @@ -109,7 +109,7 @@ impl From<&PoolDefinition> for Data { BorshSerialize::serialize(definition, &mut data) .expect("Serialization to Vec should not fail"); - Data::try_from(data).expect("Token definition encoded data should fit into Data") + Self::try_from(data).expect("Token definition encoded data should fit into Data") } } diff --git a/programs/amm/src/add.rs b/programs/amm/src/add.rs index 0a926b3b..d057507b 100644 --- a/programs/amm/src/add.rs +++ b/programs/amm/src/add.rs @@ -156,7 +156,7 @@ pub fn add_liquidity( pool_definition_lp_auth.is_authorized = true; let call_token_lp = ChainedCall::new( token_program_id, - vec![pool_definition_lp_auth.clone(), user_holding_lp.clone()], + vec![pool_definition_lp_auth, user_holding_lp.clone()], &token_core::Instruction::Mint { amount_to_mint: delta_lp, }, diff --git a/programs/amm/src/new_definition.rs b/programs/amm/src/new_definition.rs index 83b4a3ad..366eb747 100644 --- a/programs/amm/src/new_definition.rs +++ b/programs/amm/src/new_definition.rs @@ -134,7 +134,7 @@ pub fn new_definition( let call_token_lp = ChainedCall::new( token_program_id, - vec![pool_lp_auth.clone(), user_holding_lp.clone()], + vec![pool_lp_auth, user_holding_lp.clone()], &instruction, ) .with_pda_seeds(vec![compute_liquidity_token_pda_seed(pool.account_id)]); @@ -151,5 +151,5 @@ pub fn new_definition( AccountPostState::new(user_holding_lp.account), ]; - (post_states.clone(), chained_calls) + (post_states, chained_calls) } diff --git a/programs/amm/src/remove.rs b/programs/amm/src/remove.rs index d8c7ced5..7844f4bd 100644 --- a/programs/amm/src/remove.rs +++ b/programs/amm/src/remove.rs @@ -108,7 +108,7 @@ pub fn remove_liquidity( reserve_a: pool_def_data.reserve_a - withdraw_amount_a, reserve_b: pool_def_data.reserve_b - withdraw_amount_b, active, - ..pool_def_data.clone() + ..pool_def_data }; pool_post.data = Data::from(&pool_post_definition); diff --git a/programs/amm/src/tests.rs b/programs/amm/src/tests.rs index 6bb7cc1f..29456e03 100644 --- a/programs/amm/src/tests.rs +++ b/programs/amm/src/tests.rs @@ -107,7 +107,7 @@ impl BalanceForTests { fn lp_supply_init() -> u128 { // sqrt(vault_a_reserve_init * vault_b_reserve_init) = sqrt(1000 * 500) = 707 - (BalanceForTests::vault_a_reserve_init() * BalanceForTests::vault_b_reserve_init()).isqrt() + (Self::vault_a_reserve_init() * Self::vault_b_reserve_init()).isqrt() } fn vault_a_swap_test_1() -> u128 { @@ -365,7 +365,7 @@ impl IdForTests { } fn token_lp_definition_id() -> AccountId { - compute_liquidity_token_pda(AMM_PROGRAM_ID, IdForTests::pool_definition_id()) + compute_liquidity_token_pda(AMM_PROGRAM_ID, Self::pool_definition_id()) } fn user_token_a_id() -> AccountId { @@ -383,24 +383,24 @@ impl IdForTests { fn pool_definition_id() -> AccountId { compute_pool_pda( AMM_PROGRAM_ID, - IdForTests::token_a_definition_id(), - IdForTests::token_b_definition_id(), + Self::token_a_definition_id(), + Self::token_b_definition_id(), ) } fn vault_a_id() -> AccountId { compute_vault_pda( AMM_PROGRAM_ID, - IdForTests::pool_definition_id(), - IdForTests::token_a_definition_id(), + Self::pool_definition_id(), + Self::token_a_definition_id(), ) } fn vault_b_id() -> AccountId { compute_vault_pda( AMM_PROGRAM_ID, - IdForTests::pool_definition_id(), - IdForTests::token_b_definition_id(), + Self::pool_definition_id(), + Self::token_b_definition_id(), ) } } diff --git a/programs/token/core/src/lib.rs b/programs/token/core/src/lib.rs index f96e10e2..42c15860 100644 --- a/programs/token/core/src/lib.rs +++ b/programs/token/core/src/lib.rs @@ -92,7 +92,7 @@ impl TryFrom<&Data> for TokenDefinition { type Error = std::io::Error; fn try_from(data: &Data) -> Result { - TokenDefinition::try_from_slice(data.as_ref()) + Self::try_from_slice(data.as_ref()) } } @@ -104,7 +104,7 @@ impl From<&TokenDefinition> for Data { BorshSerialize::serialize(definition, &mut data) .expect("Serialization to Vec should not fail"); - Data::try_from(data).expect("Token definition encoded data should fit into Data") + Self::try_from(data).expect("Token definition encoded data should fit into Data") } } @@ -128,17 +128,17 @@ pub enum TokenHolding { impl TokenHolding { #[must_use] - pub fn zeroized_clone_from(other: &Self) -> Self { + pub const fn zeroized_clone_from(other: &Self) -> Self { match other { - TokenHolding::Fungible { definition_id, .. } => TokenHolding::Fungible { + Self::Fungible { definition_id, .. } => Self::Fungible { definition_id: *definition_id, balance: 0, }, - TokenHolding::NftMaster { definition_id, .. } => TokenHolding::NftMaster { + Self::NftMaster { definition_id, .. } => Self::NftMaster { definition_id: *definition_id, print_balance: 0, }, - TokenHolding::NftPrintedCopy { definition_id, .. } => TokenHolding::NftPrintedCopy { + Self::NftPrintedCopy { definition_id, .. } => Self::NftPrintedCopy { definition_id: *definition_id, owned: false, }, @@ -146,16 +146,16 @@ impl TokenHolding { } #[must_use] - pub fn zeroized_from_definition( + pub const fn zeroized_from_definition( definition_id: AccountId, definition: &TokenDefinition, ) -> Self { match definition { - TokenDefinition::Fungible { .. } => TokenHolding::Fungible { + TokenDefinition::Fungible { .. } => Self::Fungible { definition_id, balance: 0, }, - TokenDefinition::NonFungible { .. } => TokenHolding::NftPrintedCopy { + TokenDefinition::NonFungible { .. } => Self::NftPrintedCopy { definition_id, owned: false, }, @@ -163,11 +163,11 @@ impl TokenHolding { } #[must_use] - pub fn definition_id(&self) -> AccountId { + pub const fn definition_id(&self) -> AccountId { match self { - TokenHolding::Fungible { definition_id, .. } - | TokenHolding::NftMaster { definition_id, .. } - | TokenHolding::NftPrintedCopy { definition_id, .. } => *definition_id, + Self::Fungible { definition_id, .. } + | Self::NftMaster { definition_id, .. } + | Self::NftPrintedCopy { definition_id, .. } => *definition_id, } } } @@ -176,7 +176,7 @@ impl TryFrom<&Data> for TokenHolding { type Error = std::io::Error; fn try_from(data: &Data) -> Result { - TokenHolding::try_from_slice(data.as_ref()) + Self::try_from_slice(data.as_ref()) } } @@ -188,7 +188,7 @@ impl From<&TokenHolding> for Data { BorshSerialize::serialize(holding, &mut data) .expect("Serialization to Vec should not fail"); - Data::try_from(data).expect("Token holding encoded data should fit into Data") + Self::try_from(data).expect("Token holding encoded data should fit into Data") } } @@ -227,7 +227,7 @@ impl TryFrom<&Data> for TokenMetadata { type Error = std::io::Error; fn try_from(data: &Data) -> Result { - TokenMetadata::try_from_slice(data.as_ref()) + Self::try_from_slice(data.as_ref()) } } @@ -239,6 +239,6 @@ impl From<&TokenMetadata> for Data { BorshSerialize::serialize(metadata, &mut data) .expect("Serialization to Vec should not fail"); - Data::try_from(data).expect("Token metadata encoded data should fit into Data") + Self::try_from(data).expect("Token metadata encoded data should fit into Data") } } diff --git a/sequencer_core/src/block_store.rs b/sequencer_core/src/block_store.rs index 3cec3127..eb541188 100644 --- a/sequencer_core/src/block_store.rs +++ b/sequencer_core/src/block_store.rs @@ -72,11 +72,11 @@ impl SequencerStore { Ok(self.dbio.latest_block_meta()?) } - pub fn genesis_id(&self) -> u64 { + pub const fn genesis_id(&self) -> u64 { self.genesis_id } - pub fn signing_key(&self) -> &nssa::PrivateKey { + pub const fn signing_key(&self) -> &nssa::PrivateKey { &self.signing_key } @@ -201,7 +201,7 @@ mod tests { // Add a new block let tx = common::test_utils::produce_dummy_empty_transaction(); - let block = common::test_utils::produce_dummy_block(1, None, vec![tx.clone()]); + let block = common::test_utils::produce_dummy_block(1, None, vec![tx]); let block_hash = block.header.hash; let block_msg_id = [1; 32]; @@ -237,7 +237,7 @@ mod tests { // Add a new block with Pending status let tx = common::test_utils::produce_dummy_empty_transaction(); - let block = common::test_utils::produce_dummy_block(1, None, vec![tx.clone()]); + let block = common::test_utils::produce_dummy_block(1, None, vec![tx]); let block_id = block.header.block_id; let dummy_state = V02State::new_with_genesis_accounts(&[], &[]); diff --git a/sequencer_core/src/config.rs b/sequencer_core/src/config.rs index 003b82e8..72b8071a 100644 --- a/sequencer_core/src/config.rs +++ b/sequencer_core/src/config.rs @@ -69,7 +69,7 @@ pub struct BedrockConfig { } impl SequencerConfig { - pub fn from_path(config_home: &Path) -> Result { + pub fn from_path(config_home: &Path) -> Result { let file = File::open(config_home)?; let reader = BufReader::new(file); @@ -77,6 +77,6 @@ impl SequencerConfig { } } -fn default_max_block_size() -> ByteSize { +const fn default_max_block_size() -> ByteSize { ByteSize::mib(1) } diff --git a/sequencer_core/src/lib.rs b/sequencer_core/src/lib.rs index cd39dfc0..a7500da6 100644 --- a/sequencer_core/src/lib.rs +++ b/sequencer_core/src/lib.rs @@ -281,19 +281,19 @@ impl SequencerCore &nssa::V02State { + pub const fn state(&self) -> &nssa::V02State { &self.state } - pub fn block_store(&self) -> &SequencerStore { + pub const fn block_store(&self) -> &SequencerStore { &self.store } - pub fn chain_height(&self) -> u64 { + pub const fn chain_height(&self) -> u64 { self.chain_height } - pub fn sequencer_config(&self) -> &SequencerConfig { + pub const fn sequencer_config(&self) -> &SequencerConfig { &self.sequencer_config } @@ -302,20 +302,17 @@ impl SequencerCore Result<()> { - if let Some(first_pending_block_id) = self - .get_pending_blocks()? + self.get_pending_blocks()? .iter() .map(|block| block.header.block_id) .min() - { - info!("Clearing pending blocks up to id: {last_finalized_block_id}"); - // TODO: Delete blocks instead of marking them as finalized. - // Current approach is used because we still have `GetBlockDataRequest`. - (first_pending_block_id..=last_finalized_block_id) - .try_for_each(|id| self.store.mark_block_as_finalized(id)) - } else { - Ok(()) - } + .map_or(Ok(()), |first_pending_block_id| { + info!("Clearing pending blocks up to id: {last_finalized_block_id}"); + // TODO: Delete blocks instead of marking them as finalized. + // Current approach is used because we still have `GetBlockDataRequest`. + (first_pending_block_id..=last_finalized_block_id) + .try_for_each(|id| self.store.mark_block_as_finalized(id)) + }) } /// Returns the list of stored pending blocks. diff --git a/sequencer_rpc/src/lib.rs b/sequencer_rpc/src/lib.rs index b6049715..47e4fa75 100644 --- a/sequencer_rpc/src/lib.rs +++ b/sequencer_rpc/src/lib.rs @@ -42,13 +42,10 @@ fn respond(val: T) -> Result { #[must_use] pub fn rpc_error_responce_inverter(err: RpcError) -> RpcError { - let mut content: Option = None; - if err.error_struct.is_some() { - content = match err.error_struct.clone().unwrap() { - RpcErrorKind::HandlerError(val) | RpcErrorKind::InternalError(val) => Some(val), - RpcErrorKind::RequestValidationError(vall) => Some(serde_json::to_value(vall).unwrap()), - }; - } + let content = err.error_struct.map(|error| match error { + RpcErrorKind::HandlerError(val) | RpcErrorKind::InternalError(val) => val, + RpcErrorKind::RequestValidationError(vall) => serde_json::to_value(vall).unwrap(), + }); RpcError { error_struct: None, code: err.code, diff --git a/sequencer_runner/src/lib.rs b/sequencer_runner/src/lib.rs index 4e0c32ca..e2831191 100644 --- a/sequencer_runner/src/lib.rs +++ b/sequencer_runner/src/lib.rs @@ -80,7 +80,7 @@ impl SequencerHandle { } #[must_use] - pub fn addr(&self) -> SocketAddr { + pub const fn addr(&self) -> SocketAddr { self.addr } } diff --git a/storage/src/error.rs b/storage/src/error.rs index bcba2750..3056e09b 100644 --- a/storage/src/error.rs +++ b/storage/src/error.rs @@ -18,7 +18,7 @@ pub enum DbError { impl DbError { #[must_use] - pub fn rocksdb_cast_message(rerr: rocksdb::Error, message: Option) -> Self { + pub const fn rocksdb_cast_message(rerr: rocksdb::Error, message: Option) -> Self { Self::RocksDbError { error: rerr, additional_info: message, @@ -26,7 +26,7 @@ impl DbError { } #[must_use] - pub fn borsh_cast_message(berr: borsh::io::Error, message: Option) -> Self { + pub const fn borsh_cast_message(berr: borsh::io::Error, message: Option) -> Self { Self::SerializationError { error: berr, additional_info: message, @@ -34,7 +34,7 @@ impl DbError { } #[must_use] - pub fn db_interaction_error(message: String) -> Self { + pub const fn db_interaction_error(message: String) -> Self { Self::DbInteractionError { additional_info: message, } diff --git a/storage/src/indexer.rs b/storage/src/indexer.rs index ad17147d..6d03d320 100644 --- a/storage/src/indexer.rs +++ b/storage/src/indexer.rs @@ -92,10 +92,7 @@ impl RocksDBIO { let dbio = Self { db }; let is_start_set = dbio.get_meta_is_first_block_set()?; - - if is_start_set { - Ok(dbio) - } else { + if !is_start_set { let block_id = genesis_block.header.block_id; dbio.put_meta_last_block_in_db(block_id)?; dbio.put_meta_first_block_in_db(genesis_block)?; @@ -104,9 +101,9 @@ impl RocksDBIO { // First breakpoint setup dbio.put_breakpoint(0, initial_state)?; dbio.put_meta_last_breakpoint_id(0)?; - - Ok(dbio) } + + Ok(dbio) } pub fn destroy(path: &Path) -> DbResult<()> { @@ -494,7 +491,7 @@ impl RocksDBIO { acc_to_tx_map .entry(acc_id) .and_modify(|tx_hashes| tx_hashes.push(tx_hash.into())) - .or_insert(vec![tx_hash.into()]); + .or_insert_with(|| vec![tx_hash.into()]); } } @@ -932,10 +929,12 @@ impl RocksDBIO { .transactions .iter() .find(|tx| tx.hash().0 == tx_hash) - .ok_or(DbError::db_interaction_error(format!( - "Missing transaction in block {} with hash {:#?}", - block.header.block_id, tx_hash - )))?; + .ok_or_else(|| { + DbError::db_interaction_error(format!( + "Missing transaction in block {} with hash {:#?}", + block.header.block_id, tx_hash + )) + })?; tx_batch.push(transaction.clone()); } @@ -993,17 +992,15 @@ mod tests { fn transfer(amount: u128, nonce: u128, direction: bool) -> NSSATransaction { let from; let to; - let sign_key; - - if direction { + let sign_key = if direction { from = acc1(); to = acc2(); - sign_key = acc1_sign_key(); + acc1_sign_key() } else { from = acc2(); to = acc1(); - sign_key = acc2_sign_key(); - } + acc2_sign_key() + }; common::test_utils::create_transaction_native_token_transfer( from, nonce, to, amount, &sign_key, diff --git a/storage/src/sequencer.rs b/storage/src/sequencer.rs index 04ddc8e5..37ad419e 100644 --- a/storage/src/sequencer.rs +++ b/storage/src/sequencer.rs @@ -76,10 +76,7 @@ impl RocksDBIO { let dbio = Self { db }; let is_start_set = dbio.get_meta_is_first_block_set()?; - - if is_start_set { - Ok(dbio) - } else { + if !is_start_set { let block_id = genesis_block.header.block_id; dbio.put_meta_first_block_in_db(genesis_block, genesis_msg_id)?; dbio.put_meta_is_first_block_set()?; @@ -90,9 +87,9 @@ impl RocksDBIO { hash: genesis_block.header.hash, msg_id: genesis_msg_id, })?; - - Ok(dbio) } + + Ok(dbio) } pub fn destroy(path: &Path) -> DbResult<()> { diff --git a/test_program_methods/guest/src/bin/malicious_authorization_changer.rs b/test_program_methods/guest/src/bin/malicious_authorization_changer.rs index 46f06bf2..56ba7e72 100644 --- a/test_program_methods/guest/src/bin/malicious_authorization_changer.rs +++ b/test_program_methods/guest/src/bin/malicious_authorization_changer.rs @@ -36,7 +36,7 @@ fn main() { let chained_call = ChainedCall { program_id: transfer_program_id, instruction_data, - pre_states: vec![authorised_sender.clone(), receiver.clone()], + pre_states: vec![authorised_sender, receiver.clone()], pda_seeds: vec![], }; diff --git a/wallet-ffi/src/error.rs b/wallet-ffi/src/error.rs index b48eb31f..be3be56d 100644 --- a/wallet-ffi/src/error.rs +++ b/wallet-ffi/src/error.rs @@ -47,7 +47,7 @@ pub enum WalletFfiError { impl WalletFfiError { /// Check if it's [`WalletFfiError::Success`] or panic. pub fn unwrap(self) { - let WalletFfiError::Success = self else { + let Self::Success = self else { panic!("Called `unwrap()` on error value `{self:#?}`"); }; } diff --git a/wallet-ffi/src/types.rs b/wallet-ffi/src/types.rs index c689fe8e..a6a148c7 100644 --- a/wallet-ffi/src/types.rs +++ b/wallet-ffi/src/types.rs @@ -3,7 +3,7 @@ use core::slice; use std::{ffi::c_char, ptr}; -use nssa::{Account, Data}; +use nssa::Data; use nssa_core::encryption::shared_key_derivation::Secp256k1Point; use crate::error::WalletFfiError; @@ -143,20 +143,20 @@ impl Default for FfiTransferResult { impl FfiBytes32 { /// Create from a 32-byte array. #[must_use] - pub fn from_bytes(bytes: [u8; 32]) -> Self { + pub const fn from_bytes(bytes: [u8; 32]) -> Self { Self { data: bytes } } /// Create from an `AccountId`. #[must_use] - pub fn from_account_id(id: &nssa::AccountId) -> Self { + pub const fn from_account_id(id: &nssa::AccountId) -> Self { Self { data: *id.value() } } } impl FfiPrivateAccountKeys { #[must_use] - pub fn npk(&self) -> nssa_core::NullifierPublicKey { + pub const fn npk(&self) -> nssa_core::NullifierPublicKey { nssa_core::NullifierPublicKey(self.nullifier_public_key.data) } @@ -182,7 +182,7 @@ impl From for FfiU128 { impl From for u128 { fn from(value: FfiU128) -> Self { - u128::from_le_bytes(value.data) + Self::from_le_bytes(value.data) } } @@ -194,7 +194,7 @@ impl From<&nssa::AccountId> for FfiBytes32 { impl From for nssa::AccountId { fn from(bytes: FfiBytes32) -> Self { - nssa::AccountId::new(bytes.data) + Self::new(bytes.data) } } @@ -217,7 +217,7 @@ impl From for FfiAccount { let program_owner = FfiProgramId { data: value.program_owner, }; - FfiAccount { + Self { program_owner, balance: value.balance.into(), data, @@ -240,7 +240,7 @@ impl TryFrom<&FfiAccount> for nssa::Account { } else { Data::default() }; - Ok(Account { + Ok(Self { program_owner: value.program_owner.data, balance: value.balance.into(), data, @@ -261,7 +261,7 @@ impl TryFrom<&FfiPublicAccountKey> for nssa::PublicKey { type Error = WalletFfiError; fn try_from(value: &FfiPublicAccountKey) -> Result { - let public_key = nssa::PublicKey::try_new(value.public_key.data) + let public_key = Self::try_new(value.public_key.data) .map_err(|_err| WalletFfiError::InvalidTypeConversion)?; Ok(public_key) } diff --git a/wallet/src/chain_storage.rs b/wallet/src/chain_storage.rs index df703dc0..90325666 100644 --- a/wallet/src/chain_storage.rs +++ b/wallet/src/chain_storage.rs @@ -298,6 +298,6 @@ mod tests { let config = create_sample_wallet_config(); let accs = create_sample_persistent_accounts(); - let _ = WalletChainStore::new(config.clone(), accs, HashMap::new()).unwrap(); + let _ = WalletChainStore::new(config, accs, HashMap::new()).unwrap(); } } diff --git a/wallet/src/cli/account.rs b/wallet/src/cli/account.rs index bb9f9700..1c19252d 100644 --- a/wallet/src/cli/account.rs +++ b/wallet/src/cli/account.rs @@ -1,4 +1,4 @@ -use anyhow::Result; +use anyhow::{Context as _, Result}; use clap::Subcommand; use itertools::Itertools as _; use key_protocol::key_management::key_tree::chain_index::ChainIndex; @@ -79,7 +79,7 @@ impl WalletSubcommand for NewSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - NewSubcommand::Public { cci, label } => { + Self::Public { cci, label } => { if let Some(label) = &label && wallet_core .storage @@ -116,7 +116,7 @@ impl WalletSubcommand for NewSubcommand { Ok(SubcommandReturnValue::RegisterAccount { account_id }) } - NewSubcommand::Private { cci, label } => { + Self::Private { cci, label } => { if let Some(label) = &label && wallet_core .storage @@ -166,7 +166,7 @@ impl WalletSubcommand for AccountSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - AccountSubcommand::Get { + Self::Get { raw, keys, account_id, @@ -185,7 +185,7 @@ impl WalletSubcommand for AccountSubcommand { } AccountPrivacyKind::Private => wallet_core .get_account_private(account_id) - .ok_or(anyhow::anyhow!("Private account not found in storage"))?, + .context("Private account not found in storage")?, }; // Helper closure to display keys for the account @@ -196,7 +196,7 @@ impl WalletSubcommand for AccountSubcommand { .storage .user_data .get_pub_account_signing_key(account_id) - .ok_or(anyhow::anyhow!("Public account not found in storage"))?; + .context("Public account not found in storage")?; let public_key = PublicKey::new_from_private_key(private_key); println!("pk {}", hex::encode(public_key.value())); @@ -206,7 +206,7 @@ impl WalletSubcommand for AccountSubcommand { .storage .user_data .get_private_account(account_id) - .ok_or(anyhow::anyhow!("Private account not found in storage"))?; + .context("Private account not found in storage")?; println!("npk {}", hex::encode(key.nullifer_public_key.0)); println!("vpk {}", hex::encode(key.viewing_public_key.to_bytes())); @@ -226,7 +226,7 @@ impl WalletSubcommand for AccountSubcommand { } if raw { - let account_hr: HumanReadableAccount = account.clone().into(); + let account_hr: HumanReadableAccount = account.into(); println!("{}", serde_json::to_string(&account_hr).unwrap()); return Ok(SubcommandReturnValue::Empty); @@ -242,10 +242,8 @@ impl WalletSubcommand for AccountSubcommand { Ok(SubcommandReturnValue::Empty) } - AccountSubcommand::New(new_subcommand) => { - new_subcommand.handle_subcommand(wallet_core).await - } - AccountSubcommand::SyncPrivate => { + Self::New(new_subcommand) => new_subcommand.handle_subcommand(wallet_core).await, + Self::SyncPrivate => { let curr_last_block = wallet_core .sequencer_client .get_last_block() @@ -268,17 +266,15 @@ impl WalletSubcommand for AccountSubcommand { Ok(SubcommandReturnValue::SyncedToBlock(curr_last_block)) } - AccountSubcommand::List { long } => { + Self::List { long } => { let user_data = &wallet_core.storage.user_data; let labels = &wallet_core.storage.labels; let format_with_label = |prefix: &str, id: nssa::AccountId| { let id_str = id.to_string(); - if let Some(label) = labels.get(&id_str) { - format!("{prefix} [{label}]") - } else { - prefix.to_owned() - } + labels + .get(&id_str) + .map_or_else(|| prefix.to_owned(), |label| format!("{prefix} [{label}]")) }; if !long { @@ -378,7 +374,7 @@ impl WalletSubcommand for AccountSubcommand { Ok(SubcommandReturnValue::Empty) } - AccountSubcommand::Label { account_id, label } => { + Self::Label { account_id, label } => { let (account_id_str, _) = parse_addr_with_privacy_prefix(&account_id)?; // Check if label is already used by a different account @@ -422,29 +418,32 @@ fn format_account_details(account: &Account) -> (String, String) { o if *o == auth_tr_prog_id => { let account_hr: HumanReadableAccount = account.clone().into(); ( - "Account owned by authenticated transfer program".to_string(), + "Account owned by authenticated transfer program".to_owned(), serde_json::to_string(&account_hr).unwrap(), ) } - o if *o == token_prog_id => { - if let Ok(token_def) = TokenDefinition::try_from(&account.data) { + o if *o == token_prog_id => TokenDefinition::try_from(&account.data) + .map(|token_def| { ( "Definition account owned by token program".to_owned(), serde_json::to_string(&token_def).unwrap(), ) - } else if let Ok(token_hold) = TokenHolding::try_from(&account.data) { - ( - "Holding account owned by token program".to_string(), - serde_json::to_string(&token_hold).unwrap(), - ) - } else { + }) + .or_else(|_| { + TokenHolding::try_from(&account.data).map(|token_hold| { + ( + "Holding account owned by token program".to_owned(), + serde_json::to_string(&token_hold).unwrap(), + ) + }) + }) + .unwrap_or_else(|_| { let account_hr: HumanReadableAccount = account.clone().into(); ( "Unknown token program account".to_owned(), serde_json::to_string(&account_hr).unwrap(), ) - } - } + }), _ => { let account_hr: HumanReadableAccount = account.clone().into(); ( diff --git a/wallet/src/cli/chain.rs b/wallet/src/cli/chain.rs index 3979a84f..930c7fa8 100644 --- a/wallet/src/cli/chain.rs +++ b/wallet/src/cli/chain.rs @@ -31,17 +31,17 @@ impl WalletSubcommand for ChainSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - ChainSubcommand::CurrentBlockId => { + Self::CurrentBlockId => { let latest_block_res = wallet_core.sequencer_client.get_last_block().await?; println!("Last block id is {}", latest_block_res.last_block); } - ChainSubcommand::Block { id } => { + Self::Block { id } => { let block_res = wallet_core.sequencer_client.get_block(id).await?; println!("Last block id is {:#?}", block_res.block); } - ChainSubcommand::Transaction { hash } => { + Self::Transaction { hash } => { let tx_res = wallet_core .sequencer_client .get_transaction_by_hash(hash) diff --git a/wallet/src/cli/config.rs b/wallet/src/cli/config.rs index 99339132..ec5f1245 100644 --- a/wallet/src/cli/config.rs +++ b/wallet/src/cli/config.rs @@ -29,7 +29,7 @@ impl WalletSubcommand for ConfigSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - ConfigSubcommand::Get { all, key } => { + Self::Get { all, key } => { if all { let config_str = serde_json::to_string_pretty(&wallet_core.storage.wallet_config)?; @@ -86,7 +86,7 @@ impl WalletSubcommand for ConfigSubcommand { println!("Please provide a key or use --all flag"); } } - ConfigSubcommand::Set { key, value } => { + Self::Set { key, value } => { match key.as_str() { "override_rust_log" => { wallet_core.storage.wallet_config.override_rust_log = Some(value); @@ -122,7 +122,7 @@ impl WalletSubcommand for ConfigSubcommand { wallet_core.store_config_changes().await?; } - ConfigSubcommand::Description { key } => match key.as_str() { + Self::Description { key } => match key.as_str() { "override_rust_log" => { println!("Value of variable RUST_LOG to override, affects logging"); } diff --git a/wallet/src/cli/programs/amm.rs b/wallet/src/cli/programs/amm.rs index 5da445d6..1aa7cc1b 100644 --- a/wallet/src/cli/programs/amm.rs +++ b/wallet/src/cli/programs/amm.rs @@ -104,7 +104,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - AmmProgramAgnosticSubcommand::New { + Self::New { user_holding_a, user_holding_b, user_holding_lp, @@ -150,7 +150,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand { } } } - AmmProgramAgnosticSubcommand::Swap { + Self::Swap { user_holding_a, user_holding_b, amount_in, @@ -185,7 +185,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand { } } } - AmmProgramAgnosticSubcommand::AddLiquidity { + Self::AddLiquidity { user_holding_a, user_holding_b, user_holding_lp, @@ -233,7 +233,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand { } } } - AmmProgramAgnosticSubcommand::RemoveLiquidity { + Self::RemoveLiquidity { user_holding_a, user_holding_b, user_holding_lp, diff --git a/wallet/src/cli/programs/native_token_transfer.rs b/wallet/src/cli/programs/native_token_transfer.rs index b891976b..80e95641 100644 --- a/wallet/src/cli/programs/native_token_transfer.rs +++ b/wallet/src/cli/programs/native_token_transfer.rs @@ -51,7 +51,7 @@ impl WalletSubcommand for AuthTransferSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - AuthTransferSubcommand::Init { account_id } => { + Self::Init { account_id } => { let (account_id, addr_privacy) = parse_addr_with_privacy_prefix(&account_id)?; match addr_privacy { @@ -98,7 +98,7 @@ impl WalletSubcommand for AuthTransferSubcommand { Ok(SubcommandReturnValue::Empty) } - AuthTransferSubcommand::Send { + Self::Send { from, to, to_npk, @@ -307,7 +307,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandPrivate { wallet_core: &mut WalletCore, ) -> Result { match self { - NativeTokenTransferProgramSubcommandPrivate::PrivateOwned { from, to, amount } => { + Self::PrivateOwned { from, to, amount } => { let from: AccountId = from.parse().unwrap(); let to: AccountId = to.parse().unwrap(); @@ -333,7 +333,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandPrivate { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - NativeTokenTransferProgramSubcommandPrivate::PrivateForeign { + Self::PrivateForeign { from, to_npk, to_vpk, @@ -383,7 +383,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandShielded { wallet_core: &mut WalletCore, ) -> Result { match self { - NativeTokenTransferProgramSubcommandShielded::ShieldedOwned { from, to, amount } => { + Self::ShieldedOwned { from, to, amount } => { let from: AccountId = from.parse().unwrap(); let to: AccountId = to.parse().unwrap(); @@ -409,7 +409,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandShielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - NativeTokenTransferProgramSubcommandShielded::ShieldedForeign { + Self::ShieldedForeign { from, to_npk, to_vpk, @@ -450,13 +450,13 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - NativeTokenTransferProgramSubcommand::Private(private_subcommand) => { + Self::Private(private_subcommand) => { private_subcommand.handle_subcommand(wallet_core).await } - NativeTokenTransferProgramSubcommand::Shielded(shielded_subcommand) => { + Self::Shielded(shielded_subcommand) => { shielded_subcommand.handle_subcommand(wallet_core).await } - NativeTokenTransferProgramSubcommand::Deshielded { from, to, amount } => { + Self::Deshielded { from, to, amount } => { let from: AccountId = from.parse().unwrap(); let to: AccountId = to.parse().unwrap(); @@ -482,7 +482,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - NativeTokenTransferProgramSubcommand::Public { from, to, amount } => { + Self::Public { from, to, amount } => { let from: AccountId = from.parse().unwrap(); let to: AccountId = to.parse().unwrap(); diff --git a/wallet/src/cli/programs/pinata.rs b/wallet/src/cli/programs/pinata.rs index 0af61314..5bae0a65 100644 --- a/wallet/src/cli/programs/pinata.rs +++ b/wallet/src/cli/programs/pinata.rs @@ -28,7 +28,7 @@ impl WalletSubcommand for PinataProgramAgnosticSubcommand { wallet_core: &mut WalletCore, ) -> Result { let underlying_subcommand = match self { - PinataProgramAgnosticSubcommand::Claim { to } => { + Self::Claim { to } => { let (to, to_addr_privacy) = parse_addr_with_privacy_prefix(&to)?; match to_addr_privacy { @@ -99,7 +99,7 @@ impl WalletSubcommand for PinataProgramSubcommandPublic { wallet_core: &mut WalletCore, ) -> Result { match self { - PinataProgramSubcommandPublic::Claim { + Self::Claim { pinata_account_id, winner_account_id, } => { @@ -135,7 +135,7 @@ impl WalletSubcommand for PinataProgramSubcommandPrivate { wallet_core: &mut WalletCore, ) -> Result { match self { - PinataProgramSubcommandPrivate::ClaimPrivateOwned { + Self::ClaimPrivateOwned { pinata_account_id, winner_account_id, } => { @@ -182,10 +182,10 @@ impl WalletSubcommand for PinataProgramSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - PinataProgramSubcommand::Private(private_subcommand) => { + Self::Private(private_subcommand) => { private_subcommand.handle_subcommand(wallet_core).await } - PinataProgramSubcommand::Public(public_subcommand) => { + Self::Public(public_subcommand) => { public_subcommand.handle_subcommand(wallet_core).await } } diff --git a/wallet/src/cli/programs/token.rs b/wallet/src/cli/programs/token.rs index 343960ac..19fc3423 100644 --- a/wallet/src/cli/programs/token.rs +++ b/wallet/src/cli/programs/token.rs @@ -100,7 +100,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramAgnosticSubcommand::New { + Self::New { definition_account_id, supply_account_id, name, @@ -156,7 +156,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { underlying_subcommand.handle_subcommand(wallet_core).await } - TokenProgramAgnosticSubcommand::Send { + Self::Send { from, to, to_npk, @@ -246,7 +246,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { underlying_subcommand.handle_subcommand(wallet_core).await } - TokenProgramAgnosticSubcommand::Burn { + Self::Burn { definition, holder, amount, @@ -298,7 +298,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand { underlying_subcommand.handle_subcommand(wallet_core).await } - TokenProgramAgnosticSubcommand::Mint { + Self::Mint { definition, holder, holder_npk, @@ -653,7 +653,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommandPublic::TransferToken { + Self::TransferToken { sender_account_id, recipient_account_id, balance_to_move, @@ -667,7 +667,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic { .await?; Ok(SubcommandReturnValue::Empty) } - TokenProgramSubcommandPublic::BurnToken { + Self::BurnToken { definition_account_id, holder_account_id, amount, @@ -681,7 +681,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic { .await?; Ok(SubcommandReturnValue::Empty) } - TokenProgramSubcommandPublic::MintToken { + Self::MintToken { definition_account_id, holder_account_id, amount, @@ -705,7 +705,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommandPrivate::TransferTokenPrivateOwned { + Self::TransferTokenPrivateOwned { sender_account_id, recipient_account_id, balance_to_move, @@ -742,7 +742,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandPrivate::TransferTokenPrivateForeign { + Self::TransferTokenPrivateForeign { sender_account_id, recipient_npk, recipient_vpk, @@ -788,7 +788,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandPrivate::BurnTokenPrivateOwned { + Self::BurnTokenPrivateOwned { definition_account_id, holder_account_id, amount, @@ -825,7 +825,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandPrivate::MintTokenPrivateOwned { + Self::MintTokenPrivateOwned { definition_account_id, holder_account_id, amount, @@ -862,7 +862,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandPrivate::MintTokenPrivateForeign { + Self::MintTokenPrivateForeign { definition_account_id, holder_npk, holder_vpk, @@ -919,7 +919,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommandDeshielded::TransferTokenDeshielded { + Self::TransferTokenDeshielded { sender_account_id, recipient_account_id, balance_to_move, @@ -953,7 +953,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandDeshielded::BurnTokenDeshieldedOwned { + Self::BurnTokenDeshieldedOwned { definition_account_id, holder_account_id, amount, @@ -987,7 +987,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandDeshielded::MintTokenDeshielded { + Self::MintTokenDeshielded { definition_account_id, holder_account_id, amount, @@ -1031,7 +1031,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommandShielded::TransferTokenShieldedForeign { + Self::TransferTokenShieldedForeign { sender_account_id, recipient_npk, recipient_vpk, @@ -1072,7 +1072,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandShielded::TransferTokenShieldedOwned { + Self::TransferTokenShieldedOwned { sender_account_id, recipient_account_id, balance_to_move, @@ -1106,7 +1106,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandShielded::BurnTokenShielded { + Self::BurnTokenShielded { definition_account_id, holder_account_id, amount, @@ -1140,7 +1140,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandShielded::MintTokenShieldedOwned { + Self::MintTokenShieldedOwned { definition_account_id, holder_account_id, amount, @@ -1174,7 +1174,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - TokenProgramSubcommandShielded::MintTokenShieldedForeign { + Self::MintTokenShieldedForeign { definition_account_id, holder_npk, holder_vpk, @@ -1226,7 +1226,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - CreateNewTokenProgramSubcommand::NewPrivateDefPrivateSupp { + Self::NewPrivateDefPrivateSupp { definition_account_id, supply_account_id, name, @@ -1265,7 +1265,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - CreateNewTokenProgramSubcommand::NewPrivateDefPublicSupp { + Self::NewPrivateDefPublicSupp { definition_account_id, supply_account_id, name, @@ -1301,7 +1301,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - CreateNewTokenProgramSubcommand::NewPublicDefPrivateSupp { + Self::NewPublicDefPrivateSupp { definition_account_id, supply_account_id, name, @@ -1337,7 +1337,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand { Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash }) } - CreateNewTokenProgramSubcommand::NewPublicDefPublicSupp { + Self::NewPublicDefPublicSupp { definition_account_id, supply_account_id, name, @@ -1363,19 +1363,19 @@ impl WalletSubcommand for TokenProgramSubcommand { wallet_core: &mut WalletCore, ) -> Result { match self { - TokenProgramSubcommand::Create(creation_subcommand) => { + Self::Create(creation_subcommand) => { creation_subcommand.handle_subcommand(wallet_core).await } - TokenProgramSubcommand::Private(private_subcommand) => { + Self::Private(private_subcommand) => { private_subcommand.handle_subcommand(wallet_core).await } - TokenProgramSubcommand::Public(public_subcommand) => { + Self::Public(public_subcommand) => { public_subcommand.handle_subcommand(wallet_core).await } - TokenProgramSubcommand::Deshielded(deshielded_subcommand) => { + Self::Deshielded(deshielded_subcommand) => { deshielded_subcommand.handle_subcommand(wallet_core).await } - TokenProgramSubcommand::Shielded(shielded_subcommand) => { + Self::Shielded(shielded_subcommand) => { shielded_subcommand.handle_subcommand(wallet_core).await } } diff --git a/wallet/src/config.rs b/wallet/src/config.rs index ce1cf2ba..aa5fe9d7 100644 --- a/wallet/src/config.rs +++ b/wallet/src/config.rs @@ -70,7 +70,7 @@ pub struct Label(String); impl Label { #[must_use] - pub fn new(label: String) -> Self { + pub const fn new(label: String) -> Self { Self(label) } } @@ -507,7 +507,7 @@ impl Default for WalletConfig { } impl WalletConfig { - pub fn from_path_or_initialize_default(config_path: &Path) -> Result { + pub fn from_path_or_initialize_default(config_path: &Path) -> Result { match std::fs::File::open(config_path) { Ok(file) => { let reader = std::io::BufReader::new(file); @@ -532,7 +532,7 @@ impl WalletConfig { .truncate(true) .open(config_path)?; - let config = WalletConfig::default(); + let config = Self::default(); let default_config_serialized = serde_json::to_vec_pretty(&config).unwrap(); file.write_all(&default_config_serialized)?; @@ -545,7 +545,7 @@ impl WalletConfig { } pub fn apply_overrides(&mut self, overrides: WalletConfigOverrides) { - let WalletConfig { + let Self { override_rust_log, sequencer_addr, seq_poll_timeout, diff --git a/wallet/src/helperfunctions.rs b/wallet/src/helperfunctions.rs index fe4fdec3..d21d9cc7 100644 --- a/wallet/src/helperfunctions.rs +++ b/wallet/src/helperfunctions.rs @@ -58,16 +58,12 @@ fn get_home_nssa_var() -> Result { fn get_home_default_path() -> Result { std::env::home_dir() .map(|path| path.join(".nssa").join("wallet")) - .ok_or(anyhow::anyhow!("Failed to get HOME")) + .context("Failed to get HOME") } /// Get home dir for wallet. pub fn get_home() -> Result { - if let Ok(home) = get_home_nssa_var() { - Ok(home) - } else { - get_home_default_path() - } + get_home_nssa_var().or_else(|_| get_home_default_path()) } /// Fetch config path from default home diff --git a/wallet/src/lib.rs b/wallet/src/lib.rs index b81ff784..b25e749b 100644 --- a/wallet/src/lib.rs +++ b/wallet/src/lib.rs @@ -150,13 +150,13 @@ impl WalletCore { /// Get configuration with applied overrides #[must_use] - pub fn config(&self) -> &WalletConfig { + pub const fn config(&self) -> &WalletConfig { &self.storage.wallet_config } /// Get storage #[must_use] - pub fn storage(&self) -> &WalletChainStore { + pub const fn storage(&self) -> &WalletChainStore { &self.storage } @@ -505,17 +505,17 @@ impl WalletCore { } #[must_use] - pub fn config_path(&self) -> &PathBuf { + pub const fn config_path(&self) -> &PathBuf { &self.config_path } #[must_use] - pub fn storage_path(&self) -> &PathBuf { + pub const fn storage_path(&self) -> &PathBuf { &self.storage_path } #[must_use] - pub fn config_overrides(&self) -> &Option { + pub const fn config_overrides(&self) -> &Option { &self.config_overrides } } diff --git a/wallet/src/poller.rs b/wallet/src/poller.rs index 4ef77e04..3f93fc78 100644 --- a/wallet/src/poller.rs +++ b/wallet/src/poller.rs @@ -18,7 +18,7 @@ pub struct TxPoller { impl TxPoller { #[must_use] - pub fn new(config: &WalletConfig, client: Arc) -> Self { + pub const fn new(config: &WalletConfig, client: Arc) -> Self { Self { polling_delay: config.seq_poll_timeout, polling_max_blocks_to_query: config.seq_tx_poll_max_blocks, diff --git a/wallet/src/privacy_preserving_tx.rs b/wallet/src/privacy_preserving_tx.rs index 9cd23888..5418c58d 100644 --- a/wallet/src/privacy_preserving_tx.rs +++ b/wallet/src/privacy_preserving_tx.rs @@ -22,12 +22,12 @@ pub enum PrivacyPreservingAccount { impl PrivacyPreservingAccount { #[must_use] - pub fn is_public(&self) -> bool { + pub const fn is_public(&self) -> bool { matches!(&self, Self::Public(_)) } #[must_use] - pub fn is_private(&self) -> bool { + pub const fn is_private(&self) -> bool { matches!( &self, Self::PrivateOwned(_) | Self::PrivateForeign { npk: _, vpk: _ }