From ee4b2fb4ca0effcd592d63693fd721c0168c1b39 Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Thu, 14 Sep 2023 15:24:02 -0700 Subject: [PATCH] clean up clippy warnings Signed-off-by: Andrew Whitehead --- indy-credx/src/ffi/cred_def.rs | 1 + indy-credx/src/ffi/object.rs | 15 ++-- indy-credx/src/ffi/presentation.rs | 1 + indy-credx/src/ffi/revocation.rs | 1 + indy-credx/src/services/helpers.rs | 2 +- indy-credx/src/services/issuer.rs | 38 ++++----- indy-credx/src/services/prover.rs | 38 +++------ indy-credx/src/services/types.rs | 16 +--- indy-credx/src/services/verifier.rs | 72 +++++++--------- indy-credx/tests/anoncreds_demos.rs | 28 +++---- indy-credx/tests/utils/anoncreds.rs | 4 +- indy-data-types/src/anoncreds/cred_def.rs | 20 +++-- indy-data-types/src/anoncreds/nonce.rs | 10 +-- indy-data-types/src/anoncreds/pres_request.rs | 14 ++-- indy-data-types/src/anoncreds/presentation.rs | 14 +--- indy-data-types/src/anoncreds/rev_reg_def.rs | 48 ++++++----- indy-data-types/src/anoncreds/rich_schema.rs | 4 +- indy-data-types/src/anoncreds/schema.rs | 8 +- indy-data-types/src/anoncreds/wql.rs | 20 ++--- indy-data-types/src/did.rs | 6 +- indy-data-types/src/error.rs | 6 +- indy-data-types/src/identifiers/cred_def.rs | 2 +- indy-data-types/src/identifiers/mod.rs | 2 +- indy-data-types/src/identifiers/rev_reg.rs | 9 +- .../src/identifiers/rich_schema.rs | 6 +- indy-data-types/src/keys/mod.rs | 54 ++++++------ indy-data-types/src/keys/types.rs | 83 ++++++++++--------- indy-data-types/src/merkle_tree/hash.rs | 7 +- indy-data-types/src/merkle_tree/mod.rs | 36 ++++---- indy-data-types/src/merkle_tree/proof.rs | 43 +++++----- indy-data-types/src/qualifiable.rs | 6 +- 31 files changed, 287 insertions(+), 327 deletions(-) diff --git a/indy-credx/src/ffi/cred_def.rs b/indy-credx/src/ffi/cred_def.rs index 6b6a4e0..021c62e 100644 --- a/indy-credx/src/ffi/cred_def.rs +++ b/indy-credx/src/ffi/cred_def.rs @@ -1,4 +1,5 @@ use std::os::raw::c_char; +use std::str::FromStr; use ffi_support::{rust_string_to_c, FfiStr}; use indy_data_types::Qualifiable; diff --git a/indy-credx/src/ffi/object.rs b/indy-credx/src/ffi/object.rs index f67abf0..ab7d570 100644 --- a/indy-credx/src/ffi/object.rs +++ b/indy-credx/src/ffi/object.rs @@ -19,7 +19,7 @@ pub(crate) static FFI_OBJECTS: Lazy>> = static FFI_OBJECT_COUNTER: AtomicUsize = AtomicUsize::new(0); -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] #[repr(transparent)] pub struct ObjectHandle(pub usize); @@ -71,12 +71,6 @@ impl ObjectHandle { } } -impl Default for ObjectHandle { - fn default() -> Self { - Self(0) - } -} - impl std::fmt::Display for ObjectHandle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}({})", stringify!($newtype), self.0) @@ -112,6 +106,7 @@ pub(crate) struct IndyObject(Arc); impl IndyObject { pub fn new(value: O) -> Self { + assert!(std::mem::size_of::() != 0); Self(Arc::new(value)) } @@ -135,6 +130,10 @@ impl IndyObject { impl PartialEq for IndyObject { fn eq(&self, other: &IndyObject) -> bool { + #[allow(clippy::vtable_address_comparisons)] + // this is allowed only because we create all such objects + // in one place (the `new` method) and ensure they are not + // zero-sized. Arc::ptr_eq(&self.0, &other.0) } } @@ -252,7 +251,7 @@ pub(crate) struct IndyObjectList(Vec); impl IndyObjectList { pub fn load(handles: &[ObjectHandle]) -> Result { let loaded = handles - .into_iter() + .iter() .map(ObjectHandle::load) .collect::>()?; Ok(Self(loaded)) diff --git a/indy-credx/src/ffi/presentation.rs b/indy-credx/src/ffi/presentation.rs index a2e5c5f..9763f9d 100644 --- a/indy-credx/src/ffi/presentation.rs +++ b/indy-credx/src/ffi/presentation.rs @@ -218,6 +218,7 @@ pub extern "C" fn credx_verify_presentation_legacy( ) } +#[allow(clippy::too_many_arguments)] fn _credx_verify_presentation( presentation: ObjectHandle, pres_req: ObjectHandle, diff --git a/indy-credx/src/ffi/revocation.rs b/indy-credx/src/ffi/revocation.rs index 886fb4b..e17daf3 100644 --- a/indy-credx/src/ffi/revocation.rs +++ b/indy-credx/src/ffi/revocation.rs @@ -1,6 +1,7 @@ use std::collections::BTreeSet; use std::convert::TryInto; use std::os::raw::c_char; +use std::str::FromStr; use ffi_support::{rust_string_to_c, FfiStr}; use indy_data_types::Qualifiable; diff --git a/indy-credx/src/services/helpers.rs b/indy-credx/src/services/helpers.rs index 8d28c25..c808d10 100644 --- a/indy-credx/src/services/helpers.rs +++ b/indy-credx/src/services/helpers.rs @@ -14,7 +14,7 @@ use crate::anoncreds_clsignatures::{ use crate::error::Result; pub fn attr_common_view(attr: &str) -> String { - attr.replace(" ", "").to_lowercase() + attr.replace(' ', "").to_lowercase() } pub fn build_credential_schema(attrs: &HashSet) -> Result { diff --git a/indy-credx/src/services/issuer.rs b/indy-credx/src/services/issuer.rs index 82f7bc0..5c65d16 100644 --- a/indy-credx/src/services/issuer.rs +++ b/indy-credx/src/services/issuer.rs @@ -29,7 +29,7 @@ pub fn create_schema( origin_did, schema_name, schema_version, attr_names); origin_did.validate()?; - let schema_id = SchemaId::new(&origin_did, schema_name, schema_version); + let schema_id = SchemaId::new(origin_did, schema_name, schema_version); let schema = SchemaV1 { id: schema_id, name: schema_name.to_string(), @@ -57,12 +57,12 @@ pub fn make_credential_definition_id( }; let schema_infix_id = schema_seq_no .map(|n| SchemaId(n.to_string())) - .unwrap_or(schema_id.clone()); + .unwrap_or(schema_id); Ok(CredentialDefinitionId::new( origin_did, &schema_infix_id, - &signature_type.to_str(), + signature_type.to_str(), tag, )) } @@ -84,9 +84,7 @@ pub fn create_credential_definition( config ); - let schema = match schema { - Schema::SchemaV1(s) => s, - }; + let Schema::SchemaV1(schema) = schema; let cred_def_id = make_credential_definition_id(origin_did, &schema.id, schema.seq_no, tag, signature_type)?; @@ -142,9 +140,7 @@ pub fn make_revocation_registry_id( tag: &str, rev_reg_type: RegistryType, ) -> Result { - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(c) => c, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let origin_did = match (origin_did.get_method(), cred_def.id.get_method()) { (None, Some(_)) => { @@ -157,9 +153,9 @@ pub fn make_revocation_registry_id( }; Ok(RevocationRegistryId::new( - &origin_did, + origin_did, &cred_def.id, - &rev_reg_type.to_str(), + rev_reg_type.to_str(), tag, )) } @@ -186,9 +182,7 @@ where let rev_reg_id = make_revocation_registry_id(origin_did, cred_def, tag, rev_reg_type)?; - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(c) => c, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let credential_pub_key = cred_def.get_public_key().map_err(err_map!( Unexpected, "Error fetching public key from credential definition" @@ -211,13 +205,13 @@ where max_cred_num, issuance_type, public_keys: rev_keys_pub, - tails_location: tails_location.clone(), + tails_location, tails_hash, }; let revoc_reg_def = RevocationRegistryDefinition::RevocationRegistryDefinitionV1( RevocationRegistryDefinitionV1 { - id: rev_reg_id.clone(), + id: rev_reg_id, revoc_def_type: rev_reg_type, tag: tag.to_string(), cred_def_id: cred_def.id.clone(), @@ -260,9 +254,7 @@ pub fn update_revocation_registry( ))? } }; - let rev_reg_def = match rev_reg_def { - RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => v1, - }; + let RevocationRegistryDefinition::RevocationRegistryDefinitionV1(rev_reg_def) = rev_reg_def; let mut rev_reg = match rev_reg { RevocationRegistry::RevocationRegistryV1(v1) => v1.value.clone(), }; @@ -292,9 +284,7 @@ pub fn create_credential_offer( let nonce = Nonce::new().map_err(err_map!(Unexpected, "Error creating nonce"))?; - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(c) => c, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let key_correctness_proof = correctness_proof .try_clone() @@ -370,8 +360,8 @@ pub fn create_credential( )?; let cred_rev_reg_id = match cred_offer.method_name.as_ref() { - Some(ref _method_name) => Some(reg_reg_id.to_unqualified()), - _ => Some(reg_reg_id.clone()), + Some(_method_name) => Some(reg_reg_id.to_unqualified()), + _ => Some(reg_reg_id), }; ( credential_signature, diff --git a/indy-credx/src/services/prover.rs b/indy-credx/src/services/prover.rs index 252998d..c3e6c05 100644 --- a/indy-credx/src/services/prover.rs +++ b/indy-credx/src/services/prover.rs @@ -38,9 +38,7 @@ pub fn create_credential_request( credential_offer ); - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(cd) => cd, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let credential_pub_key = CredentialPublicKey::build_from_parts( &cred_def.value.primary, cred_def.value.revocation.as_ref(), @@ -93,9 +91,7 @@ pub fn process_credential( trace!("process_credential >>> credential: {:?}, cred_request_metadata: {:?}, link_secret: {:?}, cred_def: {:?}, rev_reg_def: {:?}", credential, cred_request_metadata, secret!(&link_secret), cred_def, rev_reg_def); - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(cd) => cd, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let credential_pub_key = CredentialPublicKey::build_from_parts( &cred_def.value.primary, cred_def.value.revocation.as_ref(), @@ -154,9 +150,10 @@ pub fn create_presentation( let mut proof_builder = ClProver::new_proof_builder()?; proof_builder.add_common_attribute("master_secret")?; - let mut requested_proof = RequestedProof::default(); - - requested_proof.self_attested_attrs = self_attested.unwrap_or_default(); + let mut requested_proof = RequestedProof { + self_attested_attrs: self_attested.unwrap_or_default(), + ..Default::default() + }; let mut sub_proof_index = 0; let non_credential_schema = build_non_credential_schema()?; @@ -168,12 +165,9 @@ pub fn create_presentation( } let credential = present.cred; - let schema = *schemas + let Schema::SchemaV1(schema) = *schemas .get(&credential.schema_id) .ok_or_else(|| err_msg!("Schema not provided for ID: {}", credential.schema_id))?; - let schema = match schema { - Schema::SchemaV1(schema) => schema, - }; let cred_def = *cred_defs.get(&credential.cred_def_id).ok_or_else(|| { err_msg!( @@ -181,9 +175,7 @@ pub fn create_presentation( credential.cred_def_id ) })?; - let cred_def = match cred_def { - CredentialDefinition::CredentialDefinitionV1(cd) => cd, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = cred_def; let credential_pub_key = CredentialPublicKey::build_from_parts( &cred_def.value.primary, @@ -272,12 +264,8 @@ rev_reg_delta: {:?}, rev_reg_idx: {}, timestamp: {:?}, rev_state: {:?}", rev_state ); - let revoc_reg_def = match revoc_reg_def { - RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => v1, - }; - let rev_reg_delta = match rev_reg_delta { - RevocationRegistryDelta::RevocationRegistryDeltaV1(v1) => v1, - }; + let RevocationRegistryDefinition::RevocationRegistryDefinitionV1(revoc_reg_def) = revoc_reg_def; + let RevocationRegistryDelta::RevocationRegistryDeltaV1(rev_reg_delta) = rev_reg_delta; let witness = match rev_state { None => Witness::new( @@ -377,7 +365,7 @@ fn get_credential_values_for_attribute( let res = credential_attrs .iter() - .find(|&(ref key, _)| attr_common_view(key) == attr_common_view(&requested_attr)) + .find(|(key, _)| attr_common_view(key) == attr_common_view(requested_attr)) .map(|(_, values)| values.clone()); trace!( @@ -406,7 +394,7 @@ fn update_requested_proof( if let Some(name) = &attribute.name { let attribute_values = - get_credential_values_for_attribute(&credential.values.0, &name).ok_or_else( + get_credential_values_for_attribute(&credential.values.0, name).ok_or_else( || err_msg!("Credential value not found for attribute {:?}", name), )?; @@ -422,7 +410,7 @@ fn update_requested_proof( let mut value_map: HashMap = HashMap::new(); for name in names { let attr_value = - get_credential_values_for_attribute(&credential.values.0, &name) + get_credential_values_for_attribute(&credential.values.0, name) .ok_or_else(|| { err_msg!("Credential value not found for attribute {:?}", name) })?; diff --git a/indy-credx/src/services/types.rs b/indy-credx/src/services/types.rs index d15d9eb..be5d2eb 100644 --- a/indy-credx/src/services/types.rs +++ b/indy-credx/src/services/types.rs @@ -27,7 +27,7 @@ use crate::anoncreds_clsignatures::{RevocationRegistry as CryptoRevocationRegist use crate::error::Error; use crate::services::helpers::encode_credential_attribute; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CredentialDefinitionConfig { pub support_revocation: bool, } @@ -38,14 +38,6 @@ impl CredentialDefinitionConfig { } } -impl Default for CredentialDefinitionConfig { - fn default() -> Self { - Self { - support_revocation: false, - } - } -} - impl Validatable for CredentialDefinitionConfig {} #[derive(Debug, Default)] @@ -81,9 +73,9 @@ impl MakeCredentialValues { } } -impl Into for MakeCredentialValues { - fn into(self) -> CredentialValues { - self.0 +impl From for CredentialValues { + fn from(val: MakeCredentialValues) -> CredentialValues { + val.0 } } diff --git a/indy-credx/src/services/verifier.rs b/indy-credx/src/services/verifier.rs index 12b8526..17bc76f 100644 --- a/indy-credx/src/services/verifier.rs +++ b/indy-credx/src/services/verifier.rs @@ -80,11 +80,11 @@ pub(crate) fn _verify_presentation( let pres_req = pres_req.value(); let received_revealed_attrs: HashMap = - received_revealed_attrs(&presentation)?; + received_revealed_attrs(presentation)?; let received_unrevealed_attrs: HashMap = - received_unrevealed_attrs(&presentation)?; - let received_predicates: HashMap = received_predicates(&presentation)?; - let received_self_attested_attrs: HashSet = received_self_attested_attrs(&presentation); + received_unrevealed_attrs(presentation)?; + let received_predicates: HashMap = received_predicates(presentation)?; + let received_self_attested_attrs: HashSet = received_self_attested_attrs(presentation); compare_attr_from_proof_and_request( pres_req, @@ -94,10 +94,10 @@ pub(crate) fn _verify_presentation( &received_predicates, )?; - verify_revealed_attribute_values(&pres_req, &presentation)?; + verify_revealed_attribute_values(pres_req, presentation)?; verify_requested_restrictions( - &pres_req, + pres_req, &presentation.requested_proof, &received_revealed_attrs, &received_unrevealed_attrs, @@ -120,21 +120,17 @@ pub(crate) fn _verify_presentation( for sub_proof_index in 0..presentation.identifiers.len() { let identifier = presentation.identifiers[sub_proof_index].clone(); - let schema = match schemas + let Schema::SchemaV1(schema) = schemas .get(&identifier.schema_id) - .ok_or_else(|| err_msg!("Schema not provided for ID: {:?}", identifier.schema_id))? - { - Schema::SchemaV1(schema) => schema, - }; + .ok_or_else(|| err_msg!("Schema not provided for ID: {:?}", identifier.schema_id))?; - let cred_def = match cred_defs.get(&identifier.cred_def_id).ok_or_else(|| { - err_msg!( - "Credential Definition not provided for ID: {:?}", - identifier.cred_def_id - ) - })? { - CredentialDefinition::CredentialDefinitionV1(cred_def) => cred_def, - }; + let CredentialDefinition::CredentialDefinitionV1(cred_def) = + cred_defs.get(&identifier.cred_def_id).ok_or_else(|| { + err_msg!( + "Credential Definition not provided for ID: {:?}", + identifier.cred_def_id + ) + })?; let (rev_reg_def, rev_reg) = if let Some(timestamp) = identifier.timestamp { let rev_reg_id = identifier.rev_reg_id.clone().ok_or_else(|| { @@ -241,7 +237,7 @@ fn get_revealed_attributes_for_credential( let mut revealed_attrs_for_credential = requested_proof .revealed_attrs .iter() - .filter(|&(attr_referent, ref revealed_attr_info)| { + .filter(|&(attr_referent, revealed_attr_info)| { sub_proof_index == revealed_attr_info.sub_proof_index as usize && pres_req.requested_attributes.contains_key(attr_referent) }) @@ -252,7 +248,7 @@ fn get_revealed_attributes_for_credential( &mut requested_proof .revealed_attr_groups .iter() - .filter(|&(attr_referent, ref revealed_attr_info)| { + .filter(|&(attr_referent, revealed_attr_info)| { sub_proof_index == revealed_attr_info.sub_proof_index as usize && pres_req.requested_attributes.contains_key(attr_referent) }) @@ -310,7 +306,7 @@ fn compare_attr_from_proof_and_request( .chain(received_unrevealed_attrs) .map(|(r, _)| r.to_string()) .collect::>() - .union(&received_self_attested_attrs) + .union(received_self_attested_attrs) .cloned() .collect(); @@ -349,14 +345,14 @@ fn compare_timestamps_from_proof_and_request( .iter() .map(|(referent, info)| { validate_timestamp( - &received_revealed_attrs, + received_revealed_attrs, referent, &pres_req.non_revoked, &info.non_revoked, ) .or_else(|_| { validate_timestamp( - &received_unrevealed_attrs, + received_unrevealed_attrs, referent, &pres_req.non_revoked, &info.non_revoked, @@ -489,7 +485,7 @@ fn verify_revealed_attribute_values( attr_referent, ) })?; - verify_revealed_attribute_value(attr_name.as_str(), proof, &attr_info)?; + verify_revealed_attribute_value(attr_name.as_str(), proof, attr_info)?; } for (attr_referent, attr_infos) in proof.requested_proof.revealed_attr_groups.iter() { @@ -542,11 +538,7 @@ fn verify_revealed_attribute_value( proof: &Presentation, attr_info: &RevealedAttributeInfo, ) -> Result<()> { - let reveal_attr_encoded = attr_info.encoded.to_string(); - let reveal_attr_encoded = Regex::new("^0*") - .unwrap() - .replace_all(&reveal_attr_encoded, "") - .to_owned(); + let reveal_attr_encoded = attr_info.encoded.trim_start_matches('0'); let sub_proof_index = attr_info.sub_proof_index as usize; let crypto_proof_encoded = proof @@ -562,7 +554,7 @@ fn verify_revealed_attribute_value( })? .revealed_attrs()? .iter() - .find(|(key, _)| attr_common_view(attr_name) == attr_common_view(&key)) + .find(|(key, _)| attr_common_view(attr_name) == attr_common_view(key)) .map(|(_, val)| val.to_string()) .ok_or_else(|| { err_msg!( @@ -597,13 +589,13 @@ fn verify_requested_restrictions( let requested_attrs: HashMap = pres_req .requested_attributes .iter() - .filter(|&(referent, info)| !is_self_attested(&referent, &info, self_attested_attrs)) + .filter(|&(referent, info)| !is_self_attested(referent, info, self_attested_attrs)) .map(|(referent, info)| (referent.to_string(), info.clone())) .collect(); for (referent, info) in requested_attrs.iter() { if let Some(ref query) = info.restrictions { - let filter = gather_filter_info(&referent, &proof_attr_identifiers)?; + let filter = gather_filter_info(referent, &proof_attr_identifiers)?; let attr_value_map: HashMap> = if let Some(name) = info.name.as_ref() @@ -638,7 +630,7 @@ fn verify_requested_restrictions( )); }; - process_operator(&attr_value_map, &query, &filter).map_err(err_map!( + process_operator(&attr_value_map, query, &filter).map_err(err_map!( "Requested restriction validation failed for \"{:?}\" attributes", &attr_value_map ))?; @@ -647,7 +639,7 @@ fn verify_requested_restrictions( for (referent, info) in pres_req.requested_predicates.iter() { if let Some(ref query) = info.restrictions { - let filter = gather_filter_info(&referent, received_predicates)?; + let filter = gather_filter_info(referent, received_predicates)?; // start with the predicate requested attribute, which is un-revealed let mut attr_value_map = HashMap::new(); @@ -683,7 +675,7 @@ fn verify_requested_restrictions( } } - process_operator(&attr_value_map, &query, &filter).map_err(err_map!( + process_operator(&attr_value_map, query, &filter).map_err(err_map!( "Requested restriction validation failed for \"{}\" predicate", &info.name ))?; @@ -748,14 +740,14 @@ fn process_operator( ) -> Result<()> { match restriction_op { Query::Eq(ref tag_name, ref tag_value) => { - process_filter(attr_value_map, &tag_name, &tag_value, filter).map_err(err_map!( + process_filter(attr_value_map, tag_name, tag_value, filter).map_err(err_map!( "$eq operator validation failed for tag: \"{}\", value: \"{}\"", tag_name, tag_value )) } Query::Neq(ref tag_name, ref tag_value) => { - if process_filter(attr_value_map, &tag_name, &tag_value, filter).is_err() { + if process_filter(attr_value_map, tag_name, tag_value, filter).is_err() { Ok(()) } else { Err(err_msg!(ProofRejected, @@ -765,7 +757,7 @@ fn process_operator( Query::In(ref tag_name, ref tag_values) => { let res = tag_values .iter() - .any(|val| process_filter(attr_value_map, &tag_name, &val, filter).is_ok()); + .any(|val| process_filter(attr_value_map, tag_name, val, filter).is_ok()); if res { Ok(()) } else { @@ -797,7 +789,7 @@ fn process_operator( } } Query::Not(ref operator) => { - if process_operator(attr_value_map, &*operator, filter).is_err() { + if process_operator(attr_value_map, operator, filter).is_err() { Ok(()) } else { Err(err_msg!( diff --git a/indy-credx/tests/anoncreds_demos.rs b/indy-credx/tests/anoncreds_demos.rs index e41f395..a539731 100644 --- a/indy-credx/tests/anoncreds_demos.rs +++ b/indy-credx/tests/anoncreds_demos.rs @@ -16,8 +16,8 @@ use self::utils::anoncreds::{IssuerWallet, ProverWallet}; mod utils; -pub static GVT_SCHEMA_NAME: &'static str = "gvt"; -pub static GVT_SCHEMA_ATTRIBUTES: &[&'static str; 4] = &["name", "age", "sex", "height"]; +pub static GVT_SCHEMA_NAME: &str = "gvt"; +pub static GVT_SCHEMA_ATTRIBUTES: &[&str; 4] = &["name", "age", "sex", "height"]; #[test] fn anoncreds_works_for_single_issuer_single_prover() { @@ -56,7 +56,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { // Issuer creates a Credential Offer let cred_offer = issuer::create_credential_offer( gvt_schema.id(), - &gvt_cred_def, + gvt_cred_def, &issuer_wallet.cred_defs[0].key_proof, ) .expect("Error creating credential offer"); @@ -64,7 +64,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { // Prover creates a Credential Request let (cred_request, cred_request_metadata) = prover::create_credential_request( &prover_wallet.did, - &*gvt_cred_def, + gvt_cred_def, &prover_wallet.link_secret, "default", &cred_offer, @@ -86,7 +86,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { .add_raw("age", "28") .expect("Error encoding attribute"); let (issue_cred, _, _) = issuer::create_credential( - &*gvt_cred_def, + gvt_cred_def, &issuer_wallet.cred_defs[0].private, &cred_offer, &cred_request, @@ -101,7 +101,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { &mut recv_cred, &cred_request_metadata, &prover_wallet.link_secret, - &*gvt_cred_def, + gvt_cred_def, None, ) .expect("Error processing credential"); @@ -154,7 +154,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { schemas.insert(gvt_schema.id().clone(), &gvt_schema); let mut cred_defs = HashMap::new(); - cred_defs.insert(gvt_cred_def.id().clone(), &*gvt_cred_def); + cred_defs.insert(gvt_cred_def.id().clone(), gvt_cred_def); let presentation = prover::create_presentation( &pres_request, @@ -254,7 +254,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { let (rev_reg_def, rev_reg_def_private, rev_reg, rev_reg_delta) = issuer::create_revocation_registry( &issuer_wallet.did, - &gvt_cred_def, + gvt_cred_def, "tag", RegistryType::CL_ACCUM, IssuanceType::ISSUANCE_BY_DEFAULT, @@ -271,7 +271,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { // Issuer creates a Credential Offer let cred_offer = issuer::create_credential_offer( gvt_schema.id(), - &gvt_cred_def, + gvt_cred_def, &issuer_wallet.cred_defs[0].key_proof, ) .expect("Error creating credential offer"); @@ -279,7 +279,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { // Prover creates a Credential Request let (cred_request, cred_request_metadata) = prover::create_credential_request( &prover_wallet.did, - &gvt_cred_def, + gvt_cred_def, &prover_wallet.link_secret, "default", &cred_offer, @@ -301,7 +301,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { .add_raw("age", "28") .expect("Error encoding attribute"); let (issue_cred, _rev_reg, _delta) = issuer::create_credential( - &*gvt_cred_def, + gvt_cred_def, &issuer_wallet.cred_defs[0].private, &cred_offer, &cred_request, @@ -322,7 +322,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { &mut recv_cred, &cred_request_metadata, &prover_wallet.link_secret, - &*gvt_cred_def, + gvt_cred_def, Some(&rev_reg_def), ) .expect("Error processing credential"); @@ -354,7 +354,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { .expect("Error creating proof request"); // Prover creates revocation state - let tails_reader = TailsFileReader::new(&tails_path); + let tails_reader = TailsFileReader::new(tails_path); let rev_state = prover::create_or_update_revocation_state( tails_reader, &rev_reg_def, @@ -387,7 +387,7 @@ fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { schemas.insert(gvt_schema.id().clone(), &gvt_schema); let mut cred_defs = HashMap::new(); - cred_defs.insert(gvt_cred_def.id().clone(), &*gvt_cred_def); + cred_defs.insert(gvt_cred_def.id().clone(), gvt_cred_def); let presentation = prover::create_presentation( &pres_request, diff --git a/indy-credx/tests/utils/anoncreds.rs b/indy-credx/tests/utils/anoncreds.rs index 139a5f9..de702aa 100644 --- a/indy-credx/tests/utils/anoncreds.rs +++ b/indy-credx/tests/utils/anoncreds.rs @@ -5,8 +5,8 @@ use indy_data_types::anoncreds::credential::Credential; use indy_data_types::anoncreds::link_secret::LinkSecret; use indy_data_types::did::DidValue; -pub const ISSUER_DID: &'static str = "NcYxiDXkpYi6ov5FcYDi1e"; -pub const PROVER_DID: &'static str = "VsKV7grR1BUE29mG2Fm2kX"; +pub const ISSUER_DID: &str = "NcYxiDXkpYi6ov5FcYDi1e"; +pub const PROVER_DID: &str = "VsKV7grR1BUE29mG2Fm2kX"; pub struct StoredCredDef { pub public: CredentialDefinition, diff --git a/indy-data-types/src/anoncreds/cred_def.rs b/indy-data-types/src/anoncreds/cred_def.rs index 1de6ea2..3d06eb9 100644 --- a/indy-data-types/src/anoncreds/cred_def.rs +++ b/indy-data-types/src/anoncreds/cred_def.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + #[cfg(any(feature = "cl", feature = "cl_native"))] use crate::anoncreds_clsignatures::CredentialPublicKey; use crate::identifiers::cred_def::CredentialDefinitionId; @@ -13,13 +15,6 @@ pub enum SignatureType { } impl SignatureType { - pub fn from_str(value: &str) -> Result { - match value { - CL_SIGNATURE_TYPE => Ok(Self::CL), - _ => Err(ConversionError::from_msg("Invalid signature type")), - } - } - pub fn to_str(&self) -> &'static str { match *self { SignatureType::CL => CL_SIGNATURE_TYPE, @@ -27,6 +22,17 @@ impl SignatureType { } } +impl FromStr for SignatureType { + type Err = ConversionError; + + fn from_str(value: &str) -> Result { + match value { + CL_SIGNATURE_TYPE => Ok(Self::CL), + _ => Err(ConversionError::from_msg("Invalid signature type")), + } + } +} + #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CredentialDefinitionData { diff --git a/indy-data-types/src/anoncreds/nonce.rs b/indy-data-types/src/anoncreds/nonce.rs index fc3d3d1..123feaa 100644 --- a/indy-data-types/src/anoncreds/nonce.rs +++ b/indy-data-types/src/anoncreds/nonce.rs @@ -49,7 +49,7 @@ impl Nonce { return Err("Invalid bignum: empty value".into()); } for c in strval.chars() { - if c < '0' || c > '9' { + if !c.is_ascii_digit() { return Err("Invalid bignum value".into()); } } @@ -176,28 +176,28 @@ impl<'a> Deserialize<'a> for Nonce { where E: serde::de::Error, { - Ok(Nonce::try_from(value).map_err(E::custom)?) + Nonce::try_from(value).map_err(E::custom) } fn visit_u64(self, value: u64) -> Result where E: serde::de::Error, { - Ok(Nonce::try_from(value).map_err(E::custom)?) + Nonce::try_from(value).map_err(E::custom) } fn visit_u128(self, value: u128) -> Result where E: serde::de::Error, { - Ok(Nonce::try_from(value).map_err(E::custom)?) + Nonce::try_from(value).map_err(E::custom) } fn visit_str(self, value: &str) -> Result where E: serde::de::Error, { - Ok(Nonce::from_dec(value).map_err(E::custom)?) + Nonce::from_dec(value).map_err(E::custom) } } diff --git a/indy-data-types/src/anoncreds/pres_request.rs b/indy-data-types/src/anoncreds/pres_request.rs index 89baf5b..c1adc66 100644 --- a/indy-data-types/src/anoncreds/pres_request.rs +++ b/indy-data-types/src/anoncreds/pres_request.rs @@ -42,7 +42,7 @@ pub enum PresentationRequestVersion { } impl PresentationRequest { - pub fn value<'a>(&'a self) -> &'a PresentationRequestPayload { + pub fn value(&self) -> &PresentationRequestPayload { match self { PresentationRequest::PresentationRequestV1(req) => req, PresentationRequest::PresentationRequestV2(req) => req, @@ -227,7 +227,7 @@ impl Validatable for PresentationRequest { } if let Some(ref restrictions) = requested_attribute.restrictions { - _process_operator(&restrictions, &version)?; + _process_operator(restrictions, &version)?; } } @@ -239,7 +239,7 @@ impl Validatable for PresentationRequest { )); } if let Some(ref restrictions) = requested_predicate.restrictions { - _process_operator(&restrictions, &version)?; + _process_operator(restrictions, &version)?; } } @@ -255,13 +255,13 @@ impl PresentationRequest { requested_attribute.restrictions = requested_attribute .restrictions .as_mut() - .map(|ref mut restrictions| _convert_query_to_unqualified(&restrictions)); + .map(|ref mut restrictions| _convert_query_to_unqualified(restrictions)); } for (_, requested_predicate) in request.requested_predicates.iter_mut() { requested_predicate.restrictions = requested_predicate .restrictions .as_mut() - .map(|ref mut restrictions| _convert_query_to_unqualified(&restrictions)); + .map(|ref mut restrictions| _convert_query_to_unqualified(restrictions)); } }; @@ -298,13 +298,13 @@ fn _convert_query_to_unqualified(query: &Query) -> Query { Query::And(ref queries) => Query::And( queries .iter() - .map(|query| _convert_query_to_unqualified(query)) + .map(_convert_query_to_unqualified) .collect::>(), ), Query::Or(ref queries) => Query::Or( queries .iter() - .map(|query| _convert_query_to_unqualified(query)) + .map(_convert_query_to_unqualified) .collect::>(), ), Query::Not(ref query) => _convert_query_to_unqualified(query), diff --git a/indy-data-types/src/anoncreds/presentation.rs b/indy-data-types/src/anoncreds/presentation.rs index 064cb1f..4a64a76 100644 --- a/indy-data-types/src/anoncreds/presentation.rs +++ b/indy-data-types/src/anoncreds/presentation.rs @@ -13,7 +13,7 @@ pub struct Presentation { pub identifiers: Vec, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct RequestedProof { pub revealed_attrs: HashMap, @@ -28,18 +28,6 @@ pub struct RequestedProof { pub predicates: HashMap, } -impl Default for RequestedProof { - fn default() -> Self { - RequestedProof { - revealed_attrs: HashMap::new(), - revealed_attr_groups: HashMap::new(), - self_attested_attrs: HashMap::new(), - unrevealed_attrs: HashMap::new(), - predicates: HashMap::new(), - } - } -} - #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct SubProofReferent { diff --git a/indy-data-types/src/anoncreds/rev_reg_def.rs b/indy-data-types/src/anoncreds/rev_reg_def.rs index 158514d..b41b975 100644 --- a/indy-data-types/src/anoncreds/rev_reg_def.rs +++ b/indy-data-types/src/anoncreds/rev_reg_def.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use crate::identifiers::cred_def::CredentialDefinitionId; use crate::identifiers::rev_reg::RevocationRegistryId; use crate::{invalid, ConversionError, Qualifiable, Validatable, ValidationError}; @@ -8,24 +10,17 @@ pub const ISSUANCE_BY_DEFAULT: &str = "ISSUANCE_BY_DEFAULT"; pub const ISSUANCE_ON_DEMAND: &str = "ISSUANCE_ON_DEMAND"; #[allow(non_camel_case_types)] -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum IssuanceType { + #[default] ISSUANCE_BY_DEFAULT, ISSUANCE_ON_DEMAND, } impl IssuanceType { - pub fn from_str(value: &str) -> Result { - match value { - ISSUANCE_BY_DEFAULT => Ok(Self::ISSUANCE_BY_DEFAULT), - ISSUANCE_ON_DEMAND => Ok(Self::ISSUANCE_ON_DEMAND), - _ => Err(ConversionError::from_msg("Invalid issuance type")), - } - } - pub fn to_bool(&self) -> bool { - self.clone() == IssuanceType::ISSUANCE_BY_DEFAULT + matches!(self, IssuanceType::ISSUANCE_BY_DEFAULT) } pub fn to_str(&self) -> &'static str { @@ -36,27 +31,27 @@ impl IssuanceType { } } -impl Default for IssuanceType { - fn default() -> Self { - Self::ISSUANCE_BY_DEFAULT +impl FromStr for IssuanceType { + type Err = ConversionError; + + fn from_str(value: &str) -> Result { + match value { + ISSUANCE_BY_DEFAULT => Ok(Self::ISSUANCE_BY_DEFAULT), + ISSUANCE_ON_DEMAND => Ok(Self::ISSUANCE_ON_DEMAND), + _ => Err(ConversionError::from_msg("Invalid issuance type")), + } } } #[allow(non_camel_case_types)] -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum RegistryType { + #[default] CL_ACCUM, } impl RegistryType { - pub fn from_str(value: &str) -> Result { - match value { - CL_ACCUM => Ok(Self::CL_ACCUM), - _ => Err(ConversionError::from_msg("Invalid registry type")), - } - } - pub fn to_str(&self) -> &'static str { match *self { Self::CL_ACCUM => CL_ACCUM, @@ -64,6 +59,17 @@ impl RegistryType { } } +impl FromStr for RegistryType { + type Err = ConversionError; + + fn from_str(value: &str) -> Result { + match value { + CL_ACCUM => Ok(Self::CL_ACCUM), + _ => Err(ConversionError::from_msg("Invalid registry type")), + } + } +} + #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] diff --git a/indy-data-types/src/anoncreds/rich_schema.rs b/indy-data-types/src/anoncreds/rich_schema.rs index fa268f8..88abc57 100644 --- a/indy-data-types/src/anoncreds/rich_schema.rs +++ b/indy-data-types/src/anoncreds/rich_schema.rs @@ -20,7 +20,7 @@ pub struct RSContent(pub String); impl Validatable for RSContent { fn validate(&self) -> Result<(), ValidationError> { // ToDo: Add JSON-LD validation if needed - return Ok(()); + Ok(()) } } @@ -59,7 +59,7 @@ impl Validatable for RichSchema { let _rs_type: RSType = serde_json::from_value(serde_json::value::Value::String(self.rs_type.clone())) .map_err(|_err| _err.to_string())?; - return self.id.validate(); + self.id.validate() } } diff --git a/indy-data-types/src/anoncreds/schema.rs b/indy-data-types/src/anoncreds/schema.rs index 7ba0d42..6a4c817 100644 --- a/indy-data-types/src/anoncreds/schema.rs +++ b/indy-data-types/src/anoncreds/schema.rs @@ -54,7 +54,7 @@ pub struct SchemaV1 { pub seq_no: Option, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct AttributeNames(pub HashSet); @@ -86,9 +86,9 @@ impl From> for AttributeNames { } } -impl Into> for AttributeNames { - fn into(self) -> HashSet { - self.0 +impl From for HashSet { + fn from(val: AttributeNames) -> HashSet { + val.0 } } diff --git a/indy-data-types/src/anoncreds/wql.rs b/indy-data-types/src/anoncreds/wql.rs index f49e37a..20a10a2 100644 --- a/indy-data-types/src/anoncreds/wql.rs +++ b/indy-data-types/src/anoncreds/wql.rs @@ -198,9 +198,7 @@ mod serde_support { let v = JsonValue::deserialize(deserializer)?; match v { - JsonValue::Object(map) => { - parse_query(map).map_err(|err| de::Error::missing_field(err)) - } + JsonValue::Object(map) => parse_query(map).map_err(de::Error::missing_field), JsonValue::Array(array) => { // cast old restrictions format to wql let mut res: Vec = Vec::new(); @@ -210,7 +208,7 @@ mod serde_support { .ok_or_else(|| de::Error::custom("Restriction is invalid"))? .clone() .into_iter() - .filter(|&(_, ref v)| !v.is_null()) + .filter(|(_, v)| !v.is_null()) .collect(); if !sub_query.is_empty() { @@ -221,7 +219,7 @@ mod serde_support { let mut map = serde_json::Map::new(); map.insert("$or".to_string(), JsonValue::Array(res)); - parse_query(map).map_err(|err| de::Error::custom(err)) + parse_query(map).map_err(de::Error::custom) } _ => Err(de::Error::missing_field( "Restriction must be either object or array", @@ -341,7 +339,7 @@ mod serde_support { (_, JsonValue::Object(map)) => { if map.len() == 1 { let (operator_name, value) = map.into_iter().next().unwrap(); - parse_single_operator(operator_name, key, value).map(|operator| Some(operator)) + parse_single_operator(operator_name, key, value).map(Some) } else { Err("value must be JSON object of length 1") } @@ -2852,9 +2850,9 @@ mod tests { #[test] fn test_old_format_empty() { - let json = format!(r#"[]"#); + let json = r#"[]"#; - let query: Query = ::serde_json::from_str(&json).unwrap(); + let query: Query = ::serde_json::from_str(json).unwrap(); let expected = Query::And(vec![]); @@ -2868,8 +2866,8 @@ mod tests { let value1 = _random_string(10); let json = json!(vec![ - json ! ({name1.clone(): value1.clone()}), - json!({ name2.clone(): ::serde_json::Value::Null }) + json!({ name1.clone(): value1 }), + json!({ name2: ::serde_json::Value::Null }) ]) .to_string(); @@ -2893,7 +2891,7 @@ mod tests { fn test_optimise_or() { let json = r#"[]"#; - let query: Query = ::serde_json::from_str(&json).unwrap(); + let query: Query = ::serde_json::from_str(json).unwrap(); assert_eq!(query.optimise(), None); } diff --git a/indy-data-types/src/did.rs b/indy-data-types/src/did.rs index 3396a49..31139e2 100644 --- a/indy-data-types/src/did.rs +++ b/indy-data-types/src/did.rs @@ -33,7 +33,7 @@ pub fn generate_did( Some(1) | None => Ok(base58::encode(&pk.as_ref()[..16])), Some(2) => { let mut hasher = Sha256::new(); - Digest::update(&mut hasher, &pk.as_ref()); + Digest::update(&mut hasher, pk.as_ref()); let hash = hasher.finalize(); Ok(base58::encode(&hash[..16])) } @@ -80,7 +80,7 @@ impl DidValue { pub fn is_abbreviatable(&self) -> bool { match self.get_method() { - Some(ref method) if method.starts_with("sov") => true, + Some(method) if method.starts_with("sov") => true, Some(_) => false, None => true, } @@ -125,7 +125,7 @@ impl std::ops::Deref for ShortDidValue { impl ShortDidValue { /// Convert a short DID value to a qualified DID pub fn qualify(&self, method: Option) -> DidValue { - DidValue::combine(method.as_ref().map(String::as_str), &self) + DidValue::combine(method.as_deref(), self) } } diff --git a/indy-data-types/src/error.rs b/indy-data-types/src/error.rs index 22dfc82..5e2a01d 100644 --- a/indy-data-types/src/error.rs +++ b/indy-data-types/src/error.rs @@ -78,9 +78,9 @@ macro_rules! define_error { } } - impl Into for $name { - fn into(self) -> String { - self.to_string() + impl From<$name> for String { + fn from(val: $name) -> String { + val.to_string() } } diff --git a/indy-data-types/src/identifiers/cred_def.rs b/indy-data-types/src/identifiers/cred_def.rs index c205db7..78928b1 100644 --- a/indy-data-types/src/identifiers/cred_def.rs +++ b/indy-data-types/src/identifiers/cred_def.rs @@ -18,7 +18,7 @@ impl CredentialDefinitionId { tag: &str, ) -> CredentialDefinitionId { let tag = if tag.is_empty() { - format!("") + String::new() } else { format!("{}{}", DELIMITER, tag) }; diff --git a/indy-data-types/src/identifiers/mod.rs b/indy-data-types/src/identifiers/mod.rs index e6a7467..2a5fc0c 100644 --- a/indy-data-types/src/identifiers/mod.rs +++ b/indy-data-types/src/identifiers/mod.rs @@ -10,4 +10,4 @@ pub mod schema; pub mod rich_schema; /// The standard delimiter used in identifier strings -pub const DELIMITER: &'static str = ":"; +pub const DELIMITER: &str = ":"; diff --git a/indy-data-types/src/identifiers/rev_reg.rs b/indy-data-types/src/identifiers/rev_reg.rs index edf0e8c..93c6b96 100644 --- a/indy-data-types/src/identifiers/rev_reg.rs +++ b/indy-data-types/src/identifiers/rev_reg.rs @@ -44,15 +44,14 @@ impl RevocationRegistryId { } pub fn parts(&self) -> Option<(DidValue, CredentialDefinitionId, String, String)> { - match QUALIFIED_REV_REG_ID.captures(&self.0) { - Some(caps) => Some(( + QUALIFIED_REV_REG_ID.captures(&self.0).map(|caps| { + ( DidValue(caps["did"].to_string()), CredentialDefinitionId(caps["cred_def_id"].to_string()), caps["rev_reg_type"].to_string(), caps["tag"].to_string(), - )), - None => None, - } + ) + }) } } diff --git a/indy-data-types/src/identifiers/rich_schema.rs b/indy-data-types/src/identifiers/rich_schema.rs index 596b466..3e11012 100644 --- a/indy-data-types/src/identifiers/rich_schema.rs +++ b/indy-data-types/src/identifiers/rich_schema.rs @@ -7,14 +7,14 @@ impl RichSchemaId { pub const PREFIX: &'static str = "rich_schema"; pub fn new(did_string: String) -> RichSchemaId { // ToDo: add RichSchema specific id forming if needed - return RichSchemaId(did_string); + RichSchemaId(did_string) } } impl Validatable for RichSchemaId { fn validate(&self) -> Result<(), ValidationError> { // ToDO: add RichSchema ID specific validation - return Ok(()); + Ok(()) } } @@ -38,7 +38,7 @@ mod tests { #[test] fn _validate_qualified_rs_id() { - assert_eq!(_rs_id_qualified().validate().unwrap(), ()) + _rs_id_qualified().validate().unwrap(); } // #[test] diff --git a/indy-data-types/src/keys/mod.rs b/indy-data-types/src/keys/mod.rs index 69a30d1..8ebd410 100644 --- a/indy-data-types/src/keys/mod.rs +++ b/indy-data-types/src/keys/mod.rs @@ -1,3 +1,7 @@ +#[cfg(feature = "ed25519")] +use std::convert::TryFrom; +use std::str::FromStr; + #[cfg(feature = "ed25519")] use curve25519_dalek::edwards::CompressedEdwardsY; #[cfg(feature = "ed25519")] @@ -6,10 +10,6 @@ use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use rand::{thread_rng, RngCore}; #[cfg(feature = "ed25519")] use sha2::digest::Digest; - -#[cfg(feature = "ed25519")] -use std::convert::TryFrom; - use zeroize::Zeroize; use crate::utils::base58; @@ -79,7 +79,7 @@ impl PrivateKey { let x_sk = x25519_dalek::StaticSecret::from(<[u8; 32]>::try_from(&hash[..32]).unwrap()); hash.zeroize(); - Ok(Self::new(&x_sk.to_bytes(), Some(KeyType::X25519))) + Ok(Self::new(x_sk.to_bytes(), Some(KeyType::X25519))) } _ => Err("Unsupported key format for key exchange".into()), } @@ -176,7 +176,7 @@ impl VerKey { let vky = CompressedEdwardsY::from_slice(&self.key).unwrap(); if let Some(x_vk) = vky.decompress() { Ok(Self::new( - x_vk.to_montgomery().as_bytes().to_vec(), + x_vk.to_montgomery().as_bytes(), Some(KeyType::X25519), )) } else { @@ -270,8 +270,8 @@ impl EncodedVerKey { } pub fn from_did_and_verkey(did: &str, key: &str) -> Result { - if key.chars().next() == Some('~') { - let mut vk_bytes = base58::decode(&key[1..])?; + if let Some(key) = key.strip_prefix('~') { + let mut vk_bytes = base58::decode(key)?; if vk_bytes.len() != 16 { return Err("Expected 16-byte abbreviated verkey".into()); } @@ -281,7 +281,7 @@ impl EncodedVerKey { } did_bytes.append(&mut vk_bytes); Ok(Self::new( - &base58::encode(did_bytes), + base58::encode(did_bytes), Some(KeyType::ED25519), Some(KeyEncoding::BASE58), )) @@ -324,10 +324,6 @@ impl EncodedVerKey { Self::from_str_qualified(key, None, None, None) } - pub fn from_str(key: &str) -> Result { - Self::from_str_qualified(key, None, None, None) - } - pub fn from_str_qualified( key: &str, dest: Option<&str>, @@ -345,12 +341,12 @@ impl EncodedVerKey { (key, alg) }; - if key.starts_with('~') { - let dest = dest.ok_or_else(|| "Destination required for short verkey")?; + if let Some(key) = key.strip_prefix('~') { + let dest = dest.ok_or("Destination required for short verkey")?; let mut result = base58::decode(dest)?; - let mut end = base58::decode(&key[1..])?; + let mut end = base58::decode(key)?; result.append(&mut end); - Ok(Self::new(&base58::encode(result), alg, enc)) + Ok(Self::new(base58::encode(result), alg, enc)) } else { Ok(Self::new(key, alg, enc)) } @@ -422,6 +418,14 @@ impl std::fmt::Display for EncodedVerKey { } } +impl FromStr for EncodedVerKey { + type Err = ConversionError; + + fn from_str(key: &str) -> Result { + Self::from_str_qualified(key, None, None, None) + } +} + impl Validatable for EncodedVerKey { fn validate(&self) -> Result<(), ValidationError> { let verkey = self.decode()?; @@ -505,7 +509,7 @@ mod tests { const SEED: &[u8; 32] = b"aaaabbbbccccddddeeeeffffgggghhhh"; let sk = PrivateKey::from_seed(&SEED[..]).unwrap(); assert_eq!( - &sk.as_ref()[..], + sk.as_ref(), &[ 97, 97, 97, 97, 98, 98, 98, 98, 99, 99, 99, 99, 100, 100, 100, 100, 101, 101, 101, 101, 102, 102, 102, 102, 103, 103, 103, 103, 104, 104, 104, 104, 113, 22, 13, 44, @@ -515,7 +519,7 @@ mod tests { ); let xk = sk.key_exchange().unwrap(); assert_eq!( - &xk.as_ref(), + xk.as_ref(), &[ 208, 235, 232, 147, 241, 214, 250, 182, 45, 157, 20, 202, 31, 184, 226, 115, 149, 82, 210, 89, 50, 100, 22, 67, 21, 8, 124, 198, 100, 252, 237, 107 @@ -528,11 +532,11 @@ mod tests { fn sign_and_verify() { let message = b"hello there"; let sk = PrivateKey::generate(None).unwrap(); - let sig = sk.sign(&message).unwrap(); + let sig = sk.sign(message).unwrap(); let vk = sk.public_key().unwrap(); - assert!(vk.verify_signature(&message, &sig).unwrap()); - assert!(vk.verify_signature(&message, &[]).is_err()); - assert!(!vk.verify_signature(&"goodbye", &sig).unwrap()); + assert!(vk.verify_signature(message, &sig).unwrap()); + assert!(vk.verify_signature(message, b"").is_err()); + assert!(!vk.verify_signature("goodbye", &sig).unwrap()); } #[cfg(feature = "ed25519")] @@ -544,8 +548,8 @@ mod tests { vk.validate().unwrap(); let sk = PrivateKey::new(b"bad key", Some(KeyType::ED25519)); - assert_eq!(sk.validate().is_ok(), false); + assert!(sk.validate().is_err()); let vk = VerKey::new(b"bad key", Some(KeyType::ED25519)); - assert_eq!(vk.validate().is_ok(), false); + assert!(vk.validate().is_err()); } } diff --git a/indy-data-types/src/keys/types.rs b/indy-data-types/src/keys/types.rs index 2bd0dd2..0551fda 100644 --- a/indy-data-types/src/keys/types.rs +++ b/indy-data-types/src/keys/types.rs @@ -1,30 +1,26 @@ -pub const KEY_ENC_BASE58: &'static str = "base58"; +use std::fmt::{self, Display, Formatter}; +use std::ops::Deref; +use std::str::FromStr; -pub const KEY_TYPE_ED25519: &'static str = "ed25519"; -pub const KEY_TYPE_X25519: &'static str = "x25519"; +use crate::ConversionError; + +pub const KEY_ENC_BASE58: &str = "base58"; + +pub const KEY_TYPE_ED25519: &str = "ed25519"; +pub const KEY_TYPE_X25519: &str = "x25519"; /// Enum of known and unknown key types -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum KeyType { + #[default] ED25519, X25519, Other(String), } impl KeyType { - pub fn from_str(keytype: &str) -> KeyType { - match keytype.to_ascii_lowercase().as_str() { - KEY_TYPE_ED25519 => KeyType::ED25519, - KEY_TYPE_X25519 => KeyType::X25519, - _ => KeyType::Other(keytype.to_owned()), - } - } - pub fn is_known(&self) -> bool { - match self { - Self::Other(_) => false, - _ => true, - } + !matches!(self, Self::Other(_)) } pub fn as_str(&self) -> &str { @@ -36,15 +32,21 @@ impl KeyType { } } -impl std::string::ToString for KeyType { - fn to_string(&self) -> String { - self.as_str().to_owned() +impl FromStr for KeyType { + type Err = ConversionError; + + fn from_str(keytype: &str) -> Result { + Ok(match keytype.to_ascii_lowercase().as_str() { + KEY_TYPE_ED25519 => KeyType::ED25519, + KEY_TYPE_X25519 => KeyType::X25519, + _ => KeyType::Other(keytype.to_owned()), + }) } } -impl Default for KeyType { - fn default() -> Self { - KeyType::ED25519 +impl Display for KeyType { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) } } @@ -57,31 +59,25 @@ impl std::ops::Deref for KeyType { impl From<&str> for KeyType { fn from(value: &str) -> Self { - Self::from_str(value) + Self::from_str(value).unwrap() } } impl From for KeyType { fn from(value: String) -> Self { - Self::from_str(&value) + Self::from_str(&value).unwrap() } } /// Enum of known and unknown key encodings -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum KeyEncoding { + #[default] BASE58, Other(String), } impl KeyEncoding { - pub fn from_str(keyenc: &str) -> KeyEncoding { - match keyenc.to_ascii_lowercase().as_str() { - KEY_ENC_BASE58 => KeyEncoding::BASE58, - _ => KeyEncoding::Other(keyenc.to_owned()), - } - } - pub fn as_str(&self) -> &str { match self { Self::BASE58 => KEY_ENC_BASE58, @@ -90,19 +86,24 @@ impl KeyEncoding { } } -impl std::string::ToString for KeyEncoding { - fn to_string(&self) -> String { - self.as_str().to_owned() +impl FromStr for KeyEncoding { + type Err = ConversionError; + + fn from_str(keyenc: &str) -> Result { + Ok(match keyenc.to_ascii_lowercase().as_str() { + KEY_ENC_BASE58 => KeyEncoding::BASE58, + _ => KeyEncoding::Other(keyenc.to_owned()), + }) } } -impl Default for KeyEncoding { - fn default() -> Self { - KeyEncoding::BASE58 +impl Display for KeyEncoding { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) } } -impl std::ops::Deref for KeyEncoding { +impl Deref for KeyEncoding { type Target = str; fn deref(&self) -> &str { self.as_str() @@ -111,12 +112,12 @@ impl std::ops::Deref for KeyEncoding { impl From<&str> for KeyEncoding { fn from(value: &str) -> Self { - Self::from_str(value) + Self::from_str(value).unwrap() } } impl From for KeyEncoding { fn from(value: String) -> Self { - Self::from_str(&value) + Self::from_str(&value).unwrap() } } diff --git a/indy-data-types/src/merkle_tree/hash.rs b/indy-data-types/src/merkle_tree/hash.rs index 3e18e8c..75816c4 100644 --- a/indy-data-types/src/merkle_tree/hash.rs +++ b/indy-data-types/src/merkle_tree/hash.rs @@ -49,7 +49,7 @@ impl TreeHash for H { T: Hashable, { let mut ctx = Self::new(); - ctx.update(&[0x00]); + ctx.update([0x00]); leaf.update_context(&mut ctx)?; Ok(ctx.finalize().to_vec()) } @@ -59,7 +59,7 @@ impl TreeHash for H { T: Hashable, { let mut ctx = Self::new(); - ctx.update(&[0x01]); + ctx.update([0x01]); left.update_context(&mut ctx)?; right.update_context(&mut ctx)?; Ok(ctx.finalize().to_vec()) @@ -95,7 +95,8 @@ pub trait Hashable { impl> Hashable for T { fn update_context(&self, context: &mut D) -> Result<(), ValidationError> { - Ok(context.update(self.as_ref())) + context.update(self.as_ref()); + Ok(()) } } diff --git a/indy-data-types/src/merkle_tree/mod.rs b/indy-data-types/src/merkle_tree/mod.rs index 8fcfe7c..2a5138b 100644 --- a/indy-data-types/src/merkle_tree/mod.rs +++ b/indy-data-types/src/merkle_tree/mod.rs @@ -32,10 +32,7 @@ impl MerkleTree { pub fn find_hash<'a>(from: &'a Tree, required_hash: &Vec) -> Option<&'a Tree> { match *from { - Tree::Empty { .. } => { - assert!(false); - None - } + Tree::Empty { .. } => None, Tree::Node { ref left, ref right, @@ -72,7 +69,7 @@ impl MerkleTree { &self, new_root_hash: &Vec, new_size: usize, - proof: &Vec>, + proof: &[Vec], ) -> Result { if self.count == 0 { // empty old tree @@ -84,7 +81,6 @@ impl MerkleTree { } if self.count > new_size { // old tree is bigger! - assert!(false); return Ok(false); } @@ -171,7 +167,7 @@ impl MerkleTree { self.nodes_count += 1; } _ => { - assert!(false); + unreachable!(); } } } else { @@ -202,7 +198,7 @@ impl MerkleTree { self.nodes_count += 1; } _ => { - assert!(false); + unreachable!(); } } self.height += 1; @@ -321,9 +317,9 @@ mod tests { assert!(mt .consistency_proof( &vec![ - 0x77 as u8, 0xf1, 0x5a, 0x58, 0x07, 0xfd, 0xaa, 0x56, 0x51, 0x28, 0xc5, 0x8f, - 0x59, 0x1f, 0x4f, 0x03, 0x25, 0x81, 0xfe, 0xe7, 0xd8, 0x61, 0x99, 0xae, 0xf8, - 0xae, 0xac, 0x7b, 0x05, 0x80, 0xbe, 0x0a + 0x77u8, 0xf1, 0x5a, 0x58, 0x07, 0xfd, 0xaa, 0x56, 0x51, 0x28, 0xc5, 0x8f, 0x59, + 0x1f, 0x4f, 0x03, 0x25, 0x81, 0xfe, 0xe7, 0xd8, 0x61, 0x99, 0xae, 0xf8, 0xae, + 0xac, 0x7b, 0x05, 0x80, 0xbe, 0x0a ], 4, &proofs @@ -344,11 +340,9 @@ mod tests { let proofs: Vec> = vec![]; - assert_eq!( - false, - mt.consistency_proof(&vec![0x77 as u8, 0xf1, 0x5a], 4, &proofs) - .unwrap() - ); + assert!(!mt + .consistency_proof(&vec![0x77u8, 0xf1, 0x5a], 4, &proofs) + .unwrap()); } #[test] @@ -364,7 +358,7 @@ mod tests { for value in values { let proof = tree.gen_proof(value).unwrap(); let is_valid = proof - .map(|p| p.validate(&root_hash).unwrap()) + .map(|p| p.validate(root_hash).unwrap()) .unwrap_or(false); assert!(is_valid); @@ -428,7 +422,7 @@ mod tests { //add 5th node mt.append(all_values[5 - 1].clone()).unwrap(); assert!(mt - .consistency_proof(&full_root_hash, 8, &proofs_for_5) + .consistency_proof(full_root_hash, 8, &proofs_for_5) .unwrap()); //try to add 6th node @@ -444,7 +438,7 @@ mod tests { //add 6th node mt.append(all_values[6 - 1].clone()).unwrap(); assert!(mt - .consistency_proof(&full_root_hash, 8, &proofs_for_6) + .consistency_proof(full_root_hash, 8, &proofs_for_6) .unwrap()); //try to add 7th node @@ -461,7 +455,7 @@ mod tests { //add 7th node mt.append(all_values[7 - 1].clone()).unwrap(); assert!(mt - .consistency_proof(&full_root_hash, 8, &proofs_for_7) + .consistency_proof(full_root_hash, 8, &proofs_for_7) .unwrap()); //try to add 8th node, empty proof @@ -469,7 +463,7 @@ mod tests { //add 7th node mt.append(all_values[8 - 1].clone()).unwrap(); assert!(mt - .consistency_proof(&full_root_hash, 8, &proofs_for_8) + .consistency_proof(full_root_hash, 8, &proofs_for_8) .unwrap()); } diff --git a/indy-data-types/src/merkle_tree/proof.rs b/indy-data-types/src/merkle_tree/proof.rs index f2c38a5..aeda1b7 100644 --- a/indy-data-types/src/merkle_tree/proof.rs +++ b/indy-data-types/src/merkle_tree/proof.rs @@ -32,30 +32,29 @@ impl Proof { if self.root_hash != root_hash || self.lemma.node_hash != root_hash { return Ok(false); } - - Ok(self.validate_lemma(&self.lemma)?) + _validate_lemma(&self.lemma) } +} - fn validate_lemma(&self, lemma: &Lemma) -> Result { - match lemma.sub_lemma { - None => Ok(lemma.sibling_hash.is_none()), - - Some(ref sub) => match lemma.sibling_hash { - None => Ok(false), - - Some(Positioned::Left(ref hash)) => { - let combined = Hash::hash_nodes(hash, &sub.node_hash)?; - let hashes_match = combined == lemma.node_hash; - Ok(hashes_match && self.validate_lemma(sub)?) - } - - Some(Positioned::Right(ref hash)) => { - let combined = Hash::hash_nodes(&sub.node_hash, hash)?; - let hashes_match = combined == lemma.node_hash; - Ok(hashes_match && self.validate_lemma(sub)?) - } - }, - } +fn _validate_lemma(lemma: &Lemma) -> Result { + match lemma.sub_lemma { + None => Ok(lemma.sibling_hash.is_none()), + + Some(ref sub) => match lemma.sibling_hash { + None => Ok(false), + + Some(Positioned::Left(ref hash)) => { + let combined = Hash::hash_nodes(hash, &sub.node_hash)?; + let hashes_match = combined == lemma.node_hash; + Ok(hashes_match && _validate_lemma(sub)?) + } + + Some(Positioned::Right(ref hash)) => { + let combined = Hash::hash_nodes(&sub.node_hash, hash)?; + let hashes_match = combined == lemma.node_hash; + Ok(hashes_match && _validate_lemma(sub)?) + } + }, } } diff --git a/indy-data-types/src/qualifiable.rs b/indy-data-types/src/qualifiable.rs index 91f2787..b8b3536 100644 --- a/indy-data-types/src/qualifiable.rs +++ b/indy-data-types/src/qualifiable.rs @@ -17,7 +17,7 @@ pub fn combine(prefix: &str, method: Option<&str>, entity: &str) -> String { /// Split a qualifiable identifier into its method and value components pub fn split<'a>(prefix: &str, val: &'a str) -> (Option<&'a str>, &'a str) { - match REGEX.captures(&val) { + match REGEX.captures(val) { None => (None, val), Some(caps) => { if caps.get(1).map(|m| m.as_str()) == Some(prefix) { @@ -45,11 +45,11 @@ pub trait Qualifiable: From + std::ops::Deref + Validatabl Self::from(combine(Self::prefix(), method, entity)) } - fn split<'a>(&'a self) -> (Option<&'a str>, &'a str) { + fn split(&self) -> (Option<&str>, &str) { split(Self::prefix(), self.deref()) } - fn get_method<'a>(&'a self) -> Option<&'a str> { + fn get_method(&self) -> Option<&str> { let (method, _rest) = self.split(); method }