Skip to content

Commit

Permalink
Code refactoring
Browse files Browse the repository at this point in the history
Signed-off-by: artem.ivanov <[email protected]>
  • Loading branch information
Artemkaaas committed Dec 1, 2023
1 parent dd376e8 commit b71971b
Show file tree
Hide file tree
Showing 13 changed files with 215 additions and 192 deletions.
2 changes: 1 addition & 1 deletion src/data_types/w3c/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::data_types::w3c::uri::URI;

// Contexts
pub const W3C_CONTEXT: &str = "https://www.w3.org/2018/credentials/v1";
pub const W3C_ANONCREDS_CONTEXT: &str = "https://github.io/anoncreds-w3c/context.json"; // FIXME: Change address
pub const W3C_ANONCREDS_CONTEXT: &str = "https://raw.githubusercontent.com/hyperledger/anoncreds-spec/main/data/anoncreds-w3c-context.json";

// Types
pub const W3C_CREDENTIAL_TYPE: &str = "VerifiableCredential";
Expand Down
22 changes: 18 additions & 4 deletions src/data_types/w3c/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use std::string::ToString;
use zeroize::Zeroize;

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::credential_proof::{
CredentialProof, CredentialSignatureProof, NonAnonCredsDataIntegrityProof,
};
use crate::data_types::w3c::presentation_proof::{CredentialPresentationProof, PredicateAttribute};
use crate::data_types::{
cred_def::CredentialDefinitionId,
Expand Down Expand Up @@ -348,6 +350,18 @@ impl W3CCredential {
}
}

pub fn add_anoncreds_signature_proof(&mut self, proof: CredentialSignatureProof) {
self.add_proof(CredentialProof::AnonCredsSignatureProof(proof));
}

pub fn add_non_anoncreds_integrity_proof(&mut self, proof: NonAnonCredsDataIntegrityProof) {
self.add_proof(CredentialProof::NonAnonCredsDataIntegrityProof(proof));
}

pub fn set_anoncreds_presentation_proof(&mut self, proof: CredentialPresentationProof) {
self.proof = OneOrMany::One(CredentialProof::AnonCredsCredentialPresentationProof(proof));
}

pub fn get_credential_signature_proof(&self) -> Result<&CredentialSignatureProof> {
self.proof
.get_value(&|proof: &CredentialProof| proof.get_credential_signature_proof())
Expand Down Expand Up @@ -390,15 +404,15 @@ impl W3CCredential {
Ok(())
}

pub fn schema_id(&self) -> &SchemaId {
pub fn get_schema_id(&self) -> &SchemaId {
&self.credential_schema.schema
}

pub fn cred_def_id(&self) -> &CredentialDefinitionId {
pub fn get_cred_def_id(&self) -> &CredentialDefinitionId {
&self.credential_schema.definition
}

pub fn rev_reg_id(&self) -> Option<&RevocationRegistryDefinitionId> {
pub fn get_rev_reg_id(&self) -> Option<&RevocationRegistryDefinitionId> {
if let Some(credential_status) = self.credential_status.as_ref() {
match credential_status.type_ {
CredentialStatusType::AnonCredsCredentialStatusList2023 => {
Expand Down
11 changes: 6 additions & 5 deletions src/data_types/w3c/credential_proof.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::data_types::w3c::presentation_proof::CredentialPresentationProof;
use crate::utils::encoded_object::EncodedObject;
use crate::Result;
use anoncreds_clsignatures::{
CredentialSignature as CLCredentialSignature, RevocationRegistry, SignatureCorrectnessProof,
Witness,
Expand All @@ -14,7 +15,7 @@ pub enum CredentialProof {
NonAnonCredsDataIntegrityProof(NonAnonCredsDataIntegrityProof),
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialSignatureProof {
#[serde(rename = "type")]
pub type_: CredentialSignatureType,
Expand All @@ -29,7 +30,7 @@ impl CredentialSignatureProof {
}
}

pub fn get_credential_signature(&self) -> crate::Result<CredentialSignature> {
pub fn get_credential_signature(&self) -> Result<CredentialSignature> {
match self.type_ {
CredentialSignatureType::AnonCredsProof2023 => {
CredentialSignature::decode(&self.signature)
Expand All @@ -53,7 +54,7 @@ impl Default for CredentialSignatureType {
}

impl CredentialProof {
pub fn get_credential_signature_proof(&self) -> crate::Result<&CredentialSignatureProof> {
pub fn get_credential_signature_proof(&self) -> Result<&CredentialSignatureProof> {
match self {
CredentialProof::AnonCredsSignatureProof(ref signature) => Ok(signature),
_ => Err(err_msg!(
Expand All @@ -64,7 +65,7 @@ impl CredentialProof {

pub(crate) fn get_mut_credential_signature_proof(
&mut self,
) -> crate::Result<&mut CredentialSignatureProof> {
) -> Result<&mut CredentialSignatureProof> {
match self {
CredentialProof::AnonCredsSignatureProof(ref mut signature) => Ok(signature),
_ => Err(err_msg!(
Expand All @@ -73,7 +74,7 @@ impl CredentialProof {
}
}

pub fn get_presentation_proof(&self) -> crate::Result<&CredentialPresentationProof> {
pub fn get_presentation_proof(&self) -> Result<&CredentialPresentationProof> {
match self {
CredentialProof::AnonCredsCredentialPresentationProof(ref proof) => Ok(proof),
_ => Err(err_msg!(
Expand Down
5 changes: 3 additions & 2 deletions src/data_types/w3c/presentation_proof.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::data_types::pres_request::{PredicateInfo, PredicateTypes};
use crate::utils::encoded_object::EncodedObject;
use crate::Result;
use anoncreds_clsignatures::{AggregatedProof, SubProof};
use std::collections::HashSet;

Expand Down Expand Up @@ -46,7 +47,7 @@ impl CredentialPresentationProof {
}
}

pub fn get_proof_value(&self) -> crate::Result<CredentialPresentationProofValue> {
pub fn get_proof_value(&self) -> Result<CredentialPresentationProofValue> {
match self.type_ {
PresentationProofType::AnonCredsPresentationProof2023 => {
CredentialPresentationProofValue::decode(&self.proof_value)
Expand Down Expand Up @@ -78,7 +79,7 @@ impl PresentationProof {
}
}

pub fn get_proof_value(&self) -> crate::Result<PresentationProofValue> {
pub fn get_proof_value(&self) -> Result<PresentationProofValue> {
match self.type_ {
PresentationProofType::AnonCredsPresentationProof2023 => {
PresentationProofValue::decode(&self.proof_value)
Expand Down
10 changes: 5 additions & 5 deletions src/ffi/w3c/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 crate::data_types::credential::CredentialValuesEncoding;
use crate::data_types::w3c::credential::CredentialAttributes;
use crate::data_types::w3c::credential::W3CCredential;
use crate::data_types::w3c::credential_proof::{CredentialProof, NonAnonCredsDataIntegrityProof};
use crate::data_types::w3c::credential_proof::NonAnonCredsDataIntegrityProof;
use crate::data_types::w3c::uri::URI;
use crate::error::Result;
use crate::ffi::credential::{FfiCredRevInfo, _link_secret, _revocation_config};
Expand Down Expand Up @@ -202,7 +202,7 @@ pub extern "C" fn anoncreds_w3c_credential_add_non_anoncreds_integrity_proof(

let mut cred = cred.load()?.cast_ref::<W3CCredential>()?.clone();

cred.add_proof(CredentialProof::NonAnonCredsDataIntegrityProof(proof));
cred.add_non_anoncreds_integrity_proof(proof);

let cred = ObjectHandle::create(cred)?;
unsafe { *cred_p = cred };
Expand Down Expand Up @@ -357,10 +357,10 @@ pub extern "C" fn anoncreds_w3c_credential_get_attribute(
let cred = handle.load()?;
let cred = cred.cast_ref::<W3CCredential>()?;
let val = match name.as_opt_str().unwrap_or_default() {
"schema_id" => rust_string_to_c(cred.schema_id().clone()),
"cred_def_id" => rust_string_to_c(cred.cred_def_id().to_string()),
"schema_id" => rust_string_to_c(cred.get_schema_id().clone()),
"cred_def_id" => rust_string_to_c(cred.get_cred_def_id().to_string()),
"rev_reg_id" => cred
.rev_reg_id()
.get_rev_reg_id()
.map_or(ptr::null_mut(), |s| rust_string_to_c(s.to_string())),
"rev_reg_index" => cred
.get_credential_signature_proof()?
Expand Down
172 changes: 92 additions & 80 deletions src/services/issuer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,9 +714,7 @@ pub fn create_credential(
);

let (credential_signature, signature_correctness_proof, rev_reg_id, rev_reg, witness) =
_create_credential(
cred_def,
cred_def_private,
CLCredentialIssuer::init(cred_def, cred_def_private)?.create_credential(
cred_offer,
cred_request,
&cred_values,
Expand All @@ -742,99 +740,113 @@ pub fn create_credential(
Ok(credential)
}

#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
pub(crate) fn _create_credential(
cred_def: &CredentialDefinition,
cred_def_private: &CredentialDefinitionPrivate,
cred_offer: &CredentialOffer,
cred_request: &CredentialRequest,
cred_values: &CredentialValues,
revocation_config: Option<CredentialRevocationConfig>,
) -> Result<(
anoncreds_clsignatures::CredentialSignature,
SignatureCorrectnessProof,
Option<RevocationRegistryDefinitionId>,
Option<CryptoRevocationRegistry>,
Option<Witness>,
)> {
let cred_public_key: anoncreds_clsignatures::CredentialPublicKey =
cred_def.get_public_key().map_err(err_map!(
pub(crate) struct CLCredentialIssuer<'a> {
cred_def: &'a CredentialDefinition,
cred_def_private: &'a CredentialDefinitionPrivate,
}

impl<'a> CLCredentialIssuer<'a> {
pub(crate) fn init(
cred_def: &'a CredentialDefinition,
cred_def_private: &'a CredentialDefinitionPrivate,
) -> Result<CLCredentialIssuer<'a>> {
Ok(CLCredentialIssuer {
cred_def,
cred_def_private,
})
}

#[allow(clippy::type_complexity)]
pub(crate) fn create_credential(
&self,
cred_offer: &CredentialOffer,
cred_request: &CredentialRequest,
cred_values: &CredentialValues,
revocation_config: Option<CredentialRevocationConfig>,
) -> Result<(
anoncreds_clsignatures::CredentialSignature,
SignatureCorrectnessProof,
Option<RevocationRegistryDefinitionId>,
Option<CryptoRevocationRegistry>,
Option<Witness>,
)> {
let cred_public_key = self.cred_def.get_public_key().map_err(err_map!(
Unexpected,
"Error fetching public key from credential definition"
))?;

let cred_values = build_credential_values(cred_values, None)?;

if let Some(rev_config) = revocation_config {
let rev_reg_def: &RevocationRegistryDefinitionValue = &rev_config.reg_def.value;
let rev_reg: Option<CryptoRevocationRegistry> = rev_config.status_list.into();
let mut rev_reg = rev_reg.ok_or_else(|| {
err_msg!(
Unexpected,
"RevocationStatusList should have accumulator value"
)
})?;

let status = rev_config
.status_list
.get(rev_config.registry_idx as usize)
.ok_or_else(|| {
let cred_values = build_credential_values(cred_values, None)?;

if let Some(rev_config) = revocation_config {
let rev_reg_def: &RevocationRegistryDefinitionValue = &rev_config.reg_def.value;
let rev_reg: Option<CryptoRevocationRegistry> = rev_config.status_list.into();
let mut rev_reg = rev_reg.ok_or_else(|| {
err_msg!(
"Revocation status list does not have the index {}",
rev_config.registry_idx
Unexpected,
"RevocationStatusList should have accumulator value"
)
})?;

// This will be a temporary solution for the `issuance_on_demand` vs
// `issuance_by_default` state. Right now, we pass in the revcation status list and
// we check in this list whether the provided idx (revocation_config.registry_idx)
// is inside the revocation status list. If it is not in there we hit an edge case,
// which should not be possible within the happy flow.
//
// If the index is inside the revocation status list we check whether it is set to
// `true` or `false` within the bitvec.
// When it is set to `true`, or 1, we invert the value. This means that we use
// `issuance_on_demand`.
// When it is set to `false`, or 0, we invert the value. This means that we use
// `issuance_by_default`.
let issuance_by_default = !status;

let (credential_signature, signature_correctness_proof, witness, _opt_delta) =
Issuer::sign_credential_with_revoc(
let status = rev_config
.status_list
.get(rev_config.registry_idx as usize)
.ok_or_else(|| {
err_msg!(
"Revocation status list does not have the index {}",
rev_config.registry_idx
)
})?;

// This will be a temporary solution for the `issuance_on_demand` vs
// `issuance_by_default` state. Right now, we pass in the revcation status list and
// we check in this list whether the provided idx (revocation_config.registry_idx)
// is inside the revocation status list. If it is not in there we hit an edge case,
// which should not be possible within the happy flow.
//
// If the index is inside the revocation status list we check whether it is set to
// `true` or `false` within the bitvec.
// When it is set to `true`, or 1, we invert the value. This means that we use
// `issuance_on_demand`.
// When it is set to `false`, or 0, we invert the value. This means that we use
// `issuance_by_default`.
let issuance_by_default = !status;

let (credential_signature, signature_correctness_proof, witness, _opt_delta) =
Issuer::sign_credential_with_revoc(
&cred_request.entropy()?,
&cred_request.blinded_ms,
&cred_request.blinded_ms_correctness_proof,
cred_offer.nonce.as_native(),
cred_request.nonce.as_native(),
&cred_values,
&cred_public_key,
&self.cred_def_private.value,
rev_config.registry_idx,
rev_reg_def.max_cred_num,
issuance_by_default,
&mut rev_reg,
&rev_config.reg_def_private.value,
)?;
Ok((
credential_signature,
signature_correctness_proof,
rev_config.status_list.id(),
Some(rev_reg),
Some(witness),
))
} else {
let (signature, correctness_proof) = Issuer::sign_credential(
&cred_request.entropy()?,
&cred_request.blinded_ms,
&cred_request.blinded_ms_correctness_proof,
cred_offer.nonce.as_native(),
cred_request.nonce.as_native(),
&cred_values,
&cred_public_key,
&cred_def_private.value,
rev_config.registry_idx,
rev_reg_def.max_cred_num,
issuance_by_default,
&mut rev_reg,
&rev_config.reg_def_private.value,
&self.cred_def_private.value,
)?;
Ok((
credential_signature,
signature_correctness_proof,
rev_config.status_list.id(),
Some(rev_reg),
Some(witness),
))
} else {
let (signature, correctness_proof) = Issuer::sign_credential(
&cred_request.entropy()?,
&cred_request.blinded_ms,
&cred_request.blinded_ms_correctness_proof,
cred_offer.nonce.as_native(),
cred_request.nonce.as_native(),
&cred_values,
&cred_public_key,
&cred_def_private.value,
)?;
Ok((signature, correctness_proof, None, None, None))
Ok((signature, correctness_proof, None, None, None))
}
}
}

Expand Down
Loading

0 comments on commit b71971b

Please sign in to comment.