Skip to content

Commit

Permalink
Code clean up
Browse files Browse the repository at this point in the history
Signed-off-by: artem.ivanov <[email protected]>
  • Loading branch information
Artemkaaas committed Nov 20, 2023
1 parent 46d3dcc commit 498b28e
Show file tree
Hide file tree
Showing 14 changed files with 141 additions and 130 deletions.
2 changes: 1 addition & 1 deletion src/data_types/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ impl RawCredentialValues {
CredentialValuesEncoding::Auto => {
let mut cred_values = MakeCredentialValues::default();
for (attribute, raw_value) in self.0.iter() {
cred_values.add_raw(attribute, &raw_value.to_string())?;
cred_values.add_raw(attribute, raw_value)?;
}
Ok(cred_values.into())
}
Expand Down
81 changes: 12 additions & 69 deletions src/data_types/w3c/credential.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::string::ToString;
use zeroize::Zeroize;

use crate::data_types::pres_request::{PredicateInfo, PredicateTypes};
use crate::data_types::w3c::constants::{ANONCREDS_CONTEXTS, ANONCREDS_CREDENTIAL_TYPES};
use crate::data_types::w3c::credential_proof::{CredentialProof, CredentialSignatureProof};
use crate::data_types::w3c::presentation_proof::CredentialPresentationProof;
Expand Down Expand Up @@ -105,7 +104,7 @@ impl Validatable for CredentialAttributes {
"CredentialAttributes validation failed: {} value format is not supported",
attribute
)
.into())
.into());
}
}
}
Expand All @@ -129,29 +128,17 @@ impl From<&CredentialValues> for CredentialAttributes {
}

impl CredentialAttributes {
pub fn add_attribute(&mut self, attribute: String, value: Value) {
pub(crate) fn add(&mut self, attribute: String, value: Value) {
self.0.insert(attribute, value);
}

pub fn add_predicate(&mut self, attribute: String, value: PredicateAttribute) {
self.0.insert(attribute, json!(value));
}

pub fn get_attribute(&self, attribute: &str) -> Result<&Value> {
self.0
.get(attribute)
.ok_or_else(|| err_msg!("Credential attribute {} not found", attribute))
}

pub fn encode(&self, encoding: &CredentialValuesEncoding) -> Result<CredentialValues> {
pub(crate) fn encode(&self, encoding: &CredentialValuesEncoding) -> Result<CredentialValues> {
match encoding {
CredentialValuesEncoding::Auto => {
let mut cred_values = MakeCredentialValues::default();
for (attribute, raw_value) in self.0.iter() {
match raw_value {
Value::String(raw_value) => {
cred_values.add_raw(attribute, &raw_value.to_string())?
}
Value::String(raw_value) => cred_values.add_raw(attribute, raw_value)?,
value => {
return Err(err_msg!(
"Encoding is not supported for credential value {:?}",
Expand All @@ -170,36 +157,6 @@ impl CredentialAttributes {
}
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PredicateAttribute {
#[serde(rename = "type")]
pub type_: PredicateAttributeType,
pub p_type: PredicateTypes,
pub p_value: i32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PredicateAttributeType {
#[serde(rename = "AnonCredsPredicate")]
AnonCredsPredicate,
}

impl Default for PredicateAttributeType {
fn default() -> Self {
PredicateAttributeType::AnonCredsPredicate
}
}

impl From<PredicateInfo> for PredicateAttribute {
fn from(info: PredicateInfo) -> Self {
PredicateAttribute {
type_: PredicateAttributeType::AnonCredsPredicate,
p_type: info.p_type,
p_value: info.p_value,
}
}
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CredentialStatus {
pub id: URI,
Expand Down Expand Up @@ -298,35 +255,21 @@ impl W3CCredential {
}

pub fn get_credential_signature_proof(&self) -> Result<&CredentialSignatureProof> {
match &self.proof {
OneOrMany::One(ref proof) => proof.get_credential_signature_proof(),
OneOrMany::Many(ref proofs) => proofs
.iter()
.find_map(|proof| proof.get_credential_signature_proof().ok())
.ok_or_else(|| err_msg!("credential does not contain AnonCredsSignatureProof")),
}
self.proof
.get_value(&|proof: &CredentialProof| proof.get_credential_signature_proof())
}

pub(crate) fn get_mut_credential_signature_proof(
&mut self,
) -> Result<&mut CredentialSignatureProof> {
match self.proof {
OneOrMany::One(ref mut proof) => proof.get_mut_credential_signature_proof(),
OneOrMany::Many(ref mut proofs) => proofs
.iter_mut()
.find_map(|proof| proof.get_mut_credential_signature_proof().ok())
.ok_or_else(|| err_msg!("credential does not contain AnonCredsSignatureProof")),
}
self.proof.get_mut_value(&|proof: &mut CredentialProof| {
proof.get_mut_credential_signature_proof()
})
}

pub fn get_presentation_proof(&self) -> Result<&CredentialPresentationProof> {
match &self.proof {
OneOrMany::One(ref proof) => proof.get_presentation_proof(),
OneOrMany::Many(ref proofs) => proofs
.iter()
.find_map(|proof| proof.get_presentation_proof().ok())
.ok_or_else(|| err_msg!("credential does not contain PresentationProof")),
}
self.proof
.get_value(&|proof: &CredentialProof| proof.get_presentation_proof())
}

pub fn validate(&self) -> Result<()> {
Expand Down
27 changes: 27 additions & 0 deletions src/data_types/w3c/one_or_many.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::error::Result;

/// Helper structure to handle the case when value is either single object or list of objects
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
Expand All @@ -11,3 +13,28 @@ impl<T> Default for OneOrMany<T> {
OneOrMany::Many(Vec::new())
}
}

impl<T> OneOrMany<T> {
pub fn get_value<F>(&self, closure: &dyn Fn(&T) -> Result<&F>) -> Result<&F> {
match &self {
OneOrMany::One(value) => closure(value),
OneOrMany::Many(values) => values
.iter()
.find_map(|value| closure(value).ok())
.ok_or_else(|| err_msg!("Object does not contain required value")),
}
}

pub(crate) fn get_mut_value<F>(
&mut self,
closure: &dyn Fn(&mut T) -> Result<&mut F>,
) -> Result<&mut F> {
match self {
OneOrMany::One(value) => closure(value),
OneOrMany::Many(values) => values
.iter_mut()
.find_map(|value| closure(value).ok())
.ok_or_else(|| err_msg!("Object does not contain required value")),
}
}
}
31 changes: 31 additions & 0 deletions src/data_types/w3c/presentation_proof.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::data_types::pres_request::{PredicateInfo, PredicateTypes};
use crate::utils::base64;
use anoncreds_clsignatures::{AggregatedProof, SubProof};
use std::collections::HashSet;
Expand Down Expand Up @@ -131,3 +132,33 @@ pub struct CredentialAttributesMapping {
#[serde(default)]
pub predicates: HashSet<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PredicateAttribute {
#[serde(rename = "type")]
pub type_: PredicateAttributeType,
pub p_type: PredicateTypes,
pub p_value: i32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PredicateAttributeType {
#[serde(rename = "AnonCredsPredicate")]
AnonCredsPredicate,
}

impl Default for PredicateAttributeType {
fn default() -> Self {
PredicateAttributeType::AnonCredsPredicate
}
}

impl From<PredicateInfo> for PredicateAttribute {
fn from(info: PredicateInfo) -> Self {
PredicateAttribute {
type_: PredicateAttributeType::AnonCredsPredicate,
p_type: info.p_type,
p_value: info.p_value,
}
}
}
6 changes: 3 additions & 3 deletions src/data_types/w3c/uri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ impl<'de> Deserialize<'de> for URI {

let id: String = Deserialize::deserialize(v).map_err(de::Error::custom)?;

URI_IDENTIFIER.captures(&id).ok_or_else(|| {
de::Error::custom("CredentialWC3 `id` validation failed: not URI id is passed")
})?;
URI_IDENTIFIER
.captures(&id)
.ok_or_else(|| de::Error::custom("Invalid URI passed"))?;

Ok(URI(id))
}
Expand Down
32 changes: 21 additions & 11 deletions src/ffi/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ffi_support::{rust_string_to_c, FfiStr};
use super::error::{catch_error, ErrorCode};
use super::object::{AnoncredsObject, ObjectHandle};
use super::util::FfiStrList;
use crate::conversion::{credential_from_w3c, credential_to_w3c};
use crate::credential_conversion::{credential_from_w3c, credential_to_w3c};
use crate::data_types::credential::CredentialValuesEncoding;
use crate::data_types::w3c::credential::CredentialAttributes;
use crate::data_types::w3c::credential_proof::{CredentialProof, NonAnonCredsDataIntegrityProof};
Expand Down Expand Up @@ -299,6 +299,7 @@ pub extern "C" fn anoncreds_process_w3c_credential(
///
/// # Params
/// cred: object handle pointing to credential in legacy form to convert
/// cred_def: object handle pointing to the credential definition
/// cred_p: reference that will contain converted credential (in W3C form) instance pointer
///
/// # Returns
Expand Down Expand Up @@ -353,8 +354,8 @@ pub extern "C" fn anoncreds_credential_from_w3c(
/// Add Non-Anoncreds Data Integrity proof signature to W3C AnonCreds credential
///
/// # Params
/// cred - object handle pointing to W3C AnonCreds credential
/// proof - data integrity proof as JSON string
/// cred: object handle pointing to W3C AnonCreds credential
/// proof: data integrity proof as JSON string
/// cred_p: reference that will contain update credential
///
/// # Returns
Expand Down Expand Up @@ -388,8 +389,8 @@ pub extern "C" fn anoncreds_w3c_credential_add_non_anoncreds_integrity_proof(
/// Set id to W3C AnonCreds credential
///
/// # Params
/// cred - object handle pointing to W3C AnonCreds credential
/// id - id to add into credential
/// cred: object handle pointing to W3C AnonCreds credential
/// id: id to add into credential
/// cred_p: reference that will contain update credential
///
/// # Returns
Expand Down Expand Up @@ -419,8 +420,8 @@ pub extern "C" fn anoncreds_w3c_set_credential_id(
/// Set subject id to W3C AnonCreds credential
///
/// # Params
/// cred - object handle pointing to W3C AnonCreds credential
/// id - subject id to add into credential
/// cred: object handle pointing to W3C AnonCreds credential
/// id: subject id to add into credential
/// cred_p: reference that will contain update credential
///
/// # Returns
Expand Down Expand Up @@ -450,8 +451,8 @@ pub extern "C" fn anoncreds_credential_w3c_subject_id(
/// Add context to W3C AnonCreds credential
///
/// # Params
/// cred - object handle pointing to W3C AnonCreds credential
/// context - context to add into credential
/// cred: object handle pointing to W3C AnonCreds credential
/// context: context to add into credential
/// cred_p: reference that will contain update credential
///
/// # Returns
Expand Down Expand Up @@ -483,8 +484,8 @@ pub extern "C" fn anoncreds_w3c_credential_add_context(
/// Add type to W3C AnonCreds credential
///
/// # Params
/// cred - object handle pointing to W3C AnonCreds credential
/// type - type to add into credential
/// cred: object handle pointing to W3C AnonCreds credential
/// type: type to add into credential
/// cred_p: reference that will contain update credential
///
/// # Returns
Expand All @@ -511,6 +512,15 @@ pub extern "C" fn anoncreds_w3c_credential_add_type(
})
}

/// Get value of requested credential attribute as string
///
/// # Params
/// handle: object handle pointing to the credential (in W3 form)
/// name: name of attribute to retrieve
/// result_p: reference that will contain value of request credential attribute
///
/// # Returns
/// Error code
#[no_mangle]
pub extern "C" fn anoncreds_w3c_credential_get_attribute(
handle: ObjectHandle,
Expand Down
10 changes: 0 additions & 10 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
#[cfg(test)]
macro_rules! assert_kind {
($kind:ident, $var:expr) => {
match $var {
Err(e) => assert_eq!($crate::error::ErrorKind::$kind, e.kind()),
_ => assert!(false, "Result expected to be error"),
}
};
}

#[cfg(debug_assertions)]
macro_rules! secret {
($val:expr) => {{
Expand Down
Loading

0 comments on commit 498b28e

Please sign in to comment.