From 4c469dd27840ebc80e0c0f3ec44bf812a5a7105b Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Sun, 9 Jul 2023 12:43:13 -0700 Subject: [PATCH 1/6] initial updates to use anoncreds-clsignatures Signed-off-by: Andrew Whitehead --- indy-credx/Cargo.toml | 16 +- indy-credx/src/error.rs | 16 +- indy-credx/src/ffi/credential.rs | 10 - indy-credx/src/ffi/revocation.rs | 22 +- indy-credx/src/lib.rs | 2 +- indy-credx/src/services/helpers.rs | 98 ++++++-- indy-credx/src/services/issuer.rs | 215 ++++++------------ indy-credx/src/services/prover.rs | 20 +- indy-credx/src/services/tails.rs | 64 +++--- indy-credx/src/services/types.rs | 9 +- indy-credx/src/services/verifier.rs | 4 +- indy-credx/tests/anoncreds_demos.rs | 4 +- indy-data-types/Cargo.toml | 27 +-- indy-data-types/src/anoncreds/cred_def.rs | 13 +- indy-data-types/src/anoncreds/cred_offer.rs | 2 +- indy-data-types/src/anoncreds/cred_request.rs | 6 +- indy-data-types/src/anoncreds/credential.rs | 8 +- indy-data-types/src/anoncreds/macros.rs | 6 +- .../src/anoncreds/master_secret.rs | 6 +- indy-data-types/src/anoncreds/nonce.rs | 5 +- indy-data-types/src/anoncreds/presentation.rs | 2 +- indy-data-types/src/anoncreds/rev_reg.rs | 6 +- indy-data-types/src/anoncreds/rev_reg_def.rs | 4 +- indy-data-types/src/lib.rs | 2 +- indy-data-types/src/macros.rs | 1 + wrappers/python/demo/test.py | 5 +- wrappers/python/indy_credx/bindings.py | 15 +- wrappers/python/indy_credx/types.py | 13 +- wrappers/python/indy_credx/version.py | 2 +- 29 files changed, 280 insertions(+), 323 deletions(-) diff --git a/indy-credx/Cargo.toml b/indy-credx/Cargo.toml index af9df13..2576df3 100644 --- a/indy-credx/Cargo.toml +++ b/indy-credx/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "indy-credx" -version = "0.3.3" +version = "0.4.0" authors = ["Hyperledger Indy Contributors "] description = "Verifiable credential issuance and presentation for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org)." -edition = "2018" +edition = "2021" license = "Apache-2.0" readme = "../README.md" repository = "https://github.com/hyperledger/indy-shared-rs/" @@ -26,17 +26,17 @@ vendored = ["indy-data-types/vendored"] env_logger = { version = "0.10", optional = true } ffi-support = { version = "0.4.0", optional = true } log = "0.4" -once_cell = "1.9" -rand = "0.7" -regex = "1.2.1" +once_cell = "1" +rand = "0.8" +regex = "1" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -sha2 = "0.9" +sha2 = "0.10" thiserror = "1.0" -zeroize = { version = "1.3", optional = true } +zeroize = { version = "1", optional = true } [dependencies.indy-data-types] -version = "0.5.2" +version = "0.6" path = "../indy-data-types" features = ["cl_native"] diff --git a/indy-credx/src/error.rs b/indy-credx/src/error.rs index 0b6361d..25b976b 100644 --- a/indy-credx/src/error.rs +++ b/indy-credx/src/error.rs @@ -2,7 +2,7 @@ use std::error::Error as StdError; use std::fmt::{self, Display, Formatter}; use std::result::Result as StdResult; -use crate::ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; +use crate::anoncreds_clsignatures::{Error as ClError, ErrorKind as ClErrorKind}; pub type Result = std::result::Result; @@ -135,19 +135,13 @@ impl From for Error { } } -impl From for Error { - fn from(err: UrsaCryptoError) -> Self { +impl From for Error { + fn from(err: ClError) -> Self { // let message = format!("Ursa Crypto Error: {}", Fail::iter_causes(&err).map(|e| e.to_string()).collect::()); let message = err.to_string(); let kind = match err.kind() { - UrsaCryptoErrorKind::InvalidState => ErrorKind::InvalidState, - UrsaCryptoErrorKind::InvalidStructure => ErrorKind::Input, - UrsaCryptoErrorKind::IOError => ErrorKind::IOError, - UrsaCryptoErrorKind::InvalidRevocationAccumulatorIndex => ErrorKind::InvalidUserRevocId, - UrsaCryptoErrorKind::RevocationAccumulatorIsFull => ErrorKind::RevocationRegistryFull, - UrsaCryptoErrorKind::ProofRejected => ErrorKind::ProofRejected, - UrsaCryptoErrorKind::CredentialRevoked => ErrorKind::CredentialRevoked, - UrsaCryptoErrorKind::InvalidParam(_) => ErrorKind::Input, + ClErrorKind::InvalidState => ErrorKind::InvalidState, + ClErrorKind::ProofRejected => ErrorKind::ProofRejected, }; Error::from_msg(kind, message) } diff --git a/indy-credx/src/ffi/credential.rs b/indy-credx/src/ffi/credential.rs index ede0bf3..21770be 100644 --- a/indy-credx/src/ffi/credential.rs +++ b/indy-credx/src/ffi/credential.rs @@ -12,7 +12,6 @@ use crate::error::Result; use crate::services::{ issuer::create_credential, prover::process_credential, - tails::TailsFileReader, types::{Credential, CredentialRevocationConfig, MakeCredentialValues}, utils::encode_credential_attribute, }; @@ -25,7 +24,6 @@ pub struct FfiCredRevInfo<'a> { registry: ObjectHandle, reg_idx: i64, reg_used: FfiList<'a, i64>, - tails_path: FfiStr<'a>, } struct RevocationConfig { @@ -34,7 +32,6 @@ struct RevocationConfig { registry: IndyObject, reg_idx: u32, reg_used: HashSet, - tails_path: String, } impl RevocationConfig { @@ -45,7 +42,6 @@ impl RevocationConfig { registry: self.registry.cast_ref()?, registry_idx: self.reg_idx, registry_used: &self.reg_used, - tails_reader: TailsFileReader::new(self.tails_path.as_str()), }) } } @@ -104,11 +100,6 @@ pub extern "C" fn credx_create_credential( } let revocation_config = if !revocation.is_null() { let revocation = unsafe { &*revocation }; - let tails_path = revocation - .tails_path - .as_opt_str() - .ok_or_else(|| err_msg!("Missing tails file path"))? - .to_string(); let mut reg_used = HashSet::new(); for reg_idx in revocation.reg_used.as_slice() { reg_used.insert( @@ -126,7 +117,6 @@ pub extern "C" fn credx_create_credential( .try_into() .map_err(|_| err_msg!("Invalid revocation index"))?, reg_used, - tails_path, }) } else { None diff --git a/indy-credx/src/ffi/revocation.rs b/indy-credx/src/ffi/revocation.rs index d3836fb..8e710da 100644 --- a/indy-credx/src/ffi/revocation.rs +++ b/indy-credx/src/ffi/revocation.rs @@ -87,11 +87,12 @@ pub extern "C" fn credx_create_revocation_registry( #[no_mangle] pub extern "C" fn credx_update_revocation_registry( + cred_def: ObjectHandle, rev_reg_def: ObjectHandle, + rev_reg_def_priv: ObjectHandle, rev_reg: ObjectHandle, issued: FfiList, revoked: FfiList, - tails_path: FfiStr, rev_reg_p: *mut ObjectHandle, rev_reg_delta_p: *mut ObjectHandle, ) -> ErrorCode { @@ -100,17 +101,13 @@ pub extern "C" fn credx_update_revocation_registry( check_useful_c_ptr!(rev_reg_delta_p); let issued = registry_indices_to_set(issued.as_slice().into_iter().cloned())?; let revoked = registry_indices_to_set(revoked.as_slice().into_iter().cloned())?; - let tails_reader = TailsFileReader::new( - tails_path - .as_opt_str() - .ok_or_else(|| err_msg!("Missing tails file path"))?, - ); let (rev_reg, rev_reg_delta) = update_revocation_registry( + cred_def.load()?.cast_ref()?, rev_reg_def.load()?.cast_ref()?, + rev_reg_def_priv.load()?.cast_ref()?, rev_reg.load()?.cast_ref()?, issued, revoked, - &tails_reader, )?; let rev_reg = ObjectHandle::create(rev_reg)?; let rev_reg_delta = ObjectHandle::create(rev_reg_delta)?; @@ -124,28 +121,25 @@ pub extern "C" fn credx_update_revocation_registry( #[no_mangle] pub extern "C" fn credx_revoke_credential( + cred_def: ObjectHandle, rev_reg_def: ObjectHandle, + rev_reg_def_priv: ObjectHandle, rev_reg: ObjectHandle, cred_rev_idx: i64, - tails_path: FfiStr, rev_reg_p: *mut ObjectHandle, rev_reg_delta_p: *mut ObjectHandle, ) -> ErrorCode { catch_error(|| { check_useful_c_ptr!(rev_reg_p); check_useful_c_ptr!(rev_reg_delta_p); - let tails_reader = TailsFileReader::new( - tails_path - .as_opt_str() - .ok_or_else(|| err_msg!("Missing tails file path"))?, - ); let (rev_reg, rev_reg_delta) = revoke_credential( + cred_def.load()?.cast_ref()?, rev_reg_def.load()?.cast_ref()?, + rev_reg_def_priv.load()?.cast_ref()?, rev_reg.load()?.cast_ref()?, cred_rev_idx .try_into() .map_err(|_| err_msg!("Invalid registry index"))?, - &tails_reader, )?; let rev_reg = ObjectHandle::create(rev_reg)?; let rev_reg_delta = ObjectHandle::create(rev_reg_delta)?; diff --git a/indy-credx/src/lib.rs b/indy-credx/src/lib.rs index 47d4887..8ddeff2 100644 --- a/indy-credx/src/lib.rs +++ b/indy-credx/src/lib.rs @@ -8,7 +8,7 @@ extern crate log; extern crate serde; #[doc(hidden)] -pub use indy_data_types::ursa; +pub use indy_data_types::anoncreds_clsignatures; #[macro_use] mod error; diff --git a/indy-credx/src/services/helpers.rs b/indy-credx/src/services/helpers.rs index 661d21f..f1a9d90 100644 --- a/indy-credx/src/services/helpers.rs +++ b/indy-credx/src/services/helpers.rs @@ -5,16 +5,13 @@ use indy_data_types::anoncreds::{ nonce::Nonce, pres_request::{AttributeInfo, NonRevocedInterval, PredicateInfo}, }; -use indy_utils::hash::SHA256; -use crate::error::Result; -use crate::ursa::{ - bn::BigNumber, - cl::{ - issuer, verifier, CredentialSchema, CredentialValues as CryptoCredentialValues, - MasterSecret as CryptoMasterSecret, NonCredentialSchema, SubProofRequest, - }, +use crate::anoncreds_clsignatures::{ + hash_credential_attribute, CredentialSchema, CredentialValues as CryptoCredentialValues, + Issuer as ClIssuer, MasterSecret as CryptoMasterSecret, NonCredentialSchema, SubProofRequest, + Verifier as ClVerifier, }; +use crate::error::Result; pub fn attr_common_view(attr: &str) -> String { attr.replace(" ", "").to_lowercase() @@ -23,7 +20,7 @@ pub fn attr_common_view(attr: &str) -> String { pub fn build_credential_schema(attrs: &HashSet) -> Result { trace!("build_credential_schema >>> attrs: {:?}", attrs); - let mut credential_schema_builder = issuer::Issuer::new_credential_schema_builder()?; + let mut credential_schema_builder = ClIssuer::new_credential_schema_builder()?; for attr in attrs { credential_schema_builder.add_attr(&attr_common_view(attr))?; } @@ -38,7 +35,7 @@ pub fn build_credential_schema(attrs: &HashSet) -> Result Result { trace!("build_non_credential_schema"); - let mut non_credential_schema_builder = issuer::Issuer::new_non_credential_schema_builder()?; + let mut non_credential_schema_builder = ClIssuer::new_non_credential_schema_builder()?; non_credential_schema_builder.add_attr("master_secret")?; let res = non_credential_schema_builder.finalize()?; @@ -55,7 +52,7 @@ pub fn build_credential_values( credential_values ); - let mut credential_values_builder = issuer::Issuer::new_credential_values_builder()?; + let mut credential_values_builder = ClIssuer::new_credential_values_builder()?; for (attr, values) in credential_values { credential_values_builder.add_dec_known(&attr_common_view(attr), &values.encoded)?; } @@ -74,14 +71,7 @@ pub fn encode_credential_attribute(raw_value: &str) -> Result { if let Ok(val) = raw_value.parse::() { Ok(val.to_string()) } else { - let digest = SHA256::digest(raw_value.as_bytes()); - #[cfg(target_endian = "big")] - let digest = { - let mut d = digest; - d.reverse(); - d - }; - Ok(BigNumber::from_bytes(&digest)?.to_dec()?) + Ok(hash_credential_attribute(raw_value)?) } } @@ -95,7 +85,7 @@ pub fn build_sub_proof_request( predicates_for_credential ); - let mut sub_proof_request_builder = verifier::Verifier::new_sub_proof_request_builder()?; + let mut sub_proof_request_builder = ClVerifier::new_sub_proof_request_builder()?; for attr in attrs_for_credential { let names = if let Some(name) = &attr.name { @@ -168,6 +158,74 @@ mod tests { } } + #[test] + fn test_encode_attribute() { + assert_eq!( + encode_credential_attribute("101 Wilson Lane").unwrap(), + "68086943237164982734333428280784300550565381723532936263016368251445461241953" + ); + assert_eq!(encode_credential_attribute("87121").unwrap(), "87121"); + assert_eq!( + encode_credential_attribute("SLC").unwrap(), + "101327353979588246869873249766058188995681113722618593621043638294296500696424" + ); + assert_eq!( + encode_credential_attribute("101 Tela Lane").unwrap(), + "63690509275174663089934667471948380740244018358024875547775652380902762701972" + ); + assert_eq!( + encode_credential_attribute("UT").unwrap(), + "93856629670657830351991220989031130499313559332549427637940645777813964461231" + ); + assert_eq!( + encode_credential_attribute("").unwrap(), + "102987336249554097029535212322581322789799900648198034993379397001115665086549" + ); + assert_eq!( + encode_credential_attribute("None").unwrap(), + "99769404535520360775991420569103450442789945655240760487761322098828903685777" + ); + assert_eq!(encode_credential_attribute("0").unwrap(), "0"); + assert_eq!(encode_credential_attribute("1").unwrap(), "1"); + + // max i32 + assert_eq!( + encode_credential_attribute("2147483647").unwrap(), + "2147483647" + ); + assert_eq!( + encode_credential_attribute("2147483648").unwrap(), + "26221484005389514539852548961319751347124425277437769688639924217837557266135" + ); + + // min i32 + assert_eq!( + encode_credential_attribute("-2147483648").unwrap(), + "-2147483648" + ); + assert_eq!( + encode_credential_attribute("-2147483649").unwrap(), + "68956915425095939579909400566452872085353864667122112803508671228696852865689" + ); + + assert_eq!( + encode_credential_attribute("0.0").unwrap(), + "62838607218564353630028473473939957328943626306458686867332534889076311281879" + ); + assert_eq!( + encode_credential_attribute("\x00").unwrap(), + "49846369543417741186729467304575255505141344055555831574636310663216789168157" + ); + assert_eq!( + encode_credential_attribute("\x01").unwrap(), + "34356466678672179216206944866734405838331831190171667647615530531663699592602" + ); + assert_eq!( + encode_credential_attribute("\x02").unwrap(), + "99398763056634537812744552006896172984671876672520535998211840060697129507206" + ); + } + #[test] fn get_non_revoc_interval_for_global() { let res = get_non_revoc_interval(&Some(_interval()), &None).unwrap(); diff --git a/indy-credx/src/services/issuer.rs b/indy-credx/src/services/issuer.rs index 45b64f6..f9bc9b4 100644 --- a/indy-credx/src/services/issuer.rs +++ b/indy-credx/src/services/issuer.rs @@ -1,13 +1,9 @@ -use std::collections::{BTreeSet, HashSet}; -use std::iter::FromIterator; +use std::collections::BTreeSet; use super::types::*; +use crate::anoncreds_clsignatures::Issuer as ClIssuer; use crate::error::Result; use crate::services::helpers::*; -use crate::ursa::cl::{ - issuer::Issuer as CryptoIssuer, RevocationRegistryDelta as CryptoRevocationRegistryDelta, - Witness, -}; use indy_data_types::anoncreds::{ cred_def::{CredentialDefinitionData, CredentialDefinitionV1}, nonce::Nonce, @@ -20,7 +16,7 @@ use indy_data_types::anoncreds::{ }; use indy_utils::{Qualifiable, Validatable}; -use super::tails::{TailsFileReader, TailsReader, TailsWriter}; +use super::tails::TailsWriter; pub fn create_schema( origin_did: &DidValue, @@ -107,7 +103,7 @@ pub fn create_credential_definition( let non_credential_schema = build_non_credential_schema()?; let (credential_public_key, credential_private_key, correctness_proof) = - CryptoIssuer::new_credential_def( + ClIssuer::new_credential_def( &credential_schema, &non_credential_schema, config.support_revocation, @@ -119,8 +115,8 @@ pub fn create_credential_definition( signature_type, tag: tag.to_owned(), value: CredentialDefinitionData { - primary: credential_public_key.get_primary_key()?.try_clone()?, - revocation: credential_public_key.get_revocation_key()?.clone(), + primary: credential_public_key.get_primary_key().try_clone()?, + revocation: credential_public_key.get_revocation_key().cloned(), }, }); @@ -198,10 +194,12 @@ where "Error fetching public key from credential definition" ))?; - // NOTE: registry is created with issuance_by_default: false, then updated later - // this avoids generating the tails twice and is significantly faster let (revoc_key_pub, revoc_key_priv, revoc_registry, mut rev_tails_generator) = - CryptoIssuer::new_revocation_registry_def(&credential_pub_key, max_cred_num, false)?; + ClIssuer::new_revocation_registry_def( + &credential_pub_key, + max_cred_num, + matches!(issuance_type, IssuanceType::ISSUANCE_BY_DEFAULT), + )?; let rev_keys_pub = RevocationRegistryDefinitionValuePublicKeys { accum_key: revoc_key_pub, @@ -230,22 +228,7 @@ where let revoc_reg = RevocationRegistry::RevocationRegistryV1(RevocationRegistryV1 { value: revoc_registry, }); - - // now update registry to reflect issuance-by-default - let (revoc_reg, revoc_init_delta) = if issuance_type == IssuanceType::ISSUANCE_BY_DEFAULT { - let tails_reader = TailsFileReader::new(&tails_location); - let issued = BTreeSet::from_iter((1..=max_cred_num).into_iter()); - update_revocation_registry( - &revoc_reg_def, - &revoc_reg, - issued, - BTreeSet::new(), - &tails_reader, - )? - } else { - let delta = revoc_reg.initial_delta(); - (revoc_reg, delta) - }; + let revoc_init_delta = revoc_reg.initial_delta(); let revoc_def_priv = RevocationRegistryDefinitionPrivate { value: revoc_key_priv, @@ -262,12 +245,21 @@ where } pub fn update_revocation_registry( + cred_def: &CredentialDefinition, rev_reg_def: &RevocationRegistryDefinition, + rev_reg_priv: &RevocationRegistryDefinitionPrivate, rev_reg: &RevocationRegistry, issued: BTreeSet, revoked: BTreeSet, - tails_reader: &TailsReader, ) -> Result<(RevocationRegistry, RevocationRegistryDelta)> { + let cred_pub_key = match cred_def { + CredentialDefinition::CredentialDefinitionV1(v1) => { + v1.get_public_key().map_err(err_map!( + Unexpected, + "Error fetching public key from credential definition" + ))? + } + }; let rev_reg_def = match rev_reg_def { RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => v1, }; @@ -275,12 +267,13 @@ pub fn update_revocation_registry( RevocationRegistry::RevocationRegistryV1(v1) => v1.value.clone(), }; let max_cred_num = rev_reg_def.value.max_cred_num; - let delta = CryptoIssuer::update_revocation_registry( + let delta = ClIssuer::update_revocation_registry( &mut rev_reg, max_cred_num, issued, revoked, - tails_reader, + &cred_pub_key, + &rev_reg_priv.value, )?; Ok(( RevocationRegistry::RevocationRegistryV1(RevocationRegistryV1 { value: rev_reg }), @@ -335,13 +328,10 @@ pub fn create_credential( cred_def, secret!(&cred_def_private), &cred_offer.nonce, &cred_request, secret!(&cred_values), revocation_config, ); - let cred_public_key = match cred_def { - CredentialDefinition::CredentialDefinitionV1(cd) => { - cd.get_public_key().map_err(err_map!( - Unexpected, - "Error fetching public key from credential definition" - ))? - } + let cred_rev_pub_key = match cred_def { + CredentialDefinition::CredentialDefinitionV1(cd) => cd.get_public_key().map_err( + err_map!(Input, "Credential definition does not support revocation"), + )?, }; let credential_values = build_credential_values(&cred_values.0, None)?; @@ -362,45 +352,27 @@ pub fn create_credential( let mut rev_reg = match revocation.registry { RevocationRegistry::RevocationRegistryV1(v1) => v1.value.clone(), }; - let (credential_signature, signature_correctness_proof, delta) = - CryptoIssuer::sign_credential_with_revoc( + let (credential_signature, signature_correctness_proof, witness, delta) = + ClIssuer::sign_credential_with_revoc( &cred_request.prover_did.0, &cred_request.blinded_ms, &cred_request.blinded_ms_correctness_proof, cred_offer.nonce.as_native(), cred_request.nonce.as_native(), &credential_values, - &cred_public_key, + &cred_rev_pub_key, &cred_def_private.value, revocation.registry_idx, rev_reg_def.max_cred_num, rev_reg_def.issuance_type.to_bool(), &mut rev_reg, &revocation.reg_def_private.value, - &revocation.tails_reader, )?; 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()), }; - let witness = { - let empty = HashSet::new(); - let (by_default, issued, revoked) = match rev_reg_def.issuance_type { - IssuanceType::ISSUANCE_ON_DEMAND => (false, revocation.registry_used, &empty), - IssuanceType::ISSUANCE_BY_DEFAULT => (true, &empty, revocation.registry_used), - }; - - let rev_reg_delta = - CryptoRevocationRegistryDelta::from_parts(None, &rev_reg, issued, revoked); - Witness::new( - revocation.registry_idx, - rev_reg_def.max_cred_num, - by_default, - &rev_reg_delta, - &revocation.tails_reader, - )? - }; ( credential_signature, signature_correctness_proof, @@ -411,14 +383,14 @@ pub fn create_credential( ) } None => { - let (signature, correctness_proof) = CryptoIssuer::sign_credential( + let (signature, correctness_proof) = ClIssuer::sign_credential( &cred_request.prover_did.0, &cred_request.blinded_ms, &cred_request.blinded_ms_correctness_proof, cred_offer.nonce.as_native(), cred_request.nonce.as_native(), &credential_values, - &cred_public_key, + &cred_rev_pub_key, &cred_def_private.value, )?; (signature, correctness_proof, None, None, None, None) @@ -454,10 +426,11 @@ pub fn create_credential( } pub fn revoke_credential( + cred_def: &CredentialDefinition, rev_reg_def: &RevocationRegistryDefinition, + rev_reg_def_private: &RevocationRegistryDefinitionPrivate, rev_reg: &RevocationRegistry, cred_rev_idx: u32, - tails_reader: &TailsReader, ) -> Result<(RevocationRegistry, RevocationRegistryDelta)> { trace!( "revoke >>> rev_reg_def: {:?}, rev_reg: {:?}, cred_rev_idx: {:?}", @@ -466,14 +439,27 @@ pub fn revoke_credential( secret!(&cred_rev_idx) ); - let max_cred_num = match rev_reg_def { - RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => v1.value.max_cred_num, + let cred_pub_key = match cred_def { + CredentialDefinition::CredentialDefinitionV1(v1) => { + v1.get_public_key().map_err(err_map!( + Unexpected, + "Error fetching public key from credential definition" + ))? + } + }; + let rev_reg_def = match rev_reg_def { + RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => &v1.value, }; let mut rev_reg = match rev_reg { RevocationRegistry::RevocationRegistryV1(v1) => v1.value.clone(), }; - let rev_reg_delta = - CryptoIssuer::revoke_credential(&mut rev_reg, max_cred_num, cred_rev_idx, tails_reader)?; + let rev_reg_delta = ClIssuer::revoke_credential( + &mut rev_reg, + rev_reg_def.max_cred_num, + cred_rev_idx, + &cred_pub_key, + &rev_reg_def_private.value, + )?; let new_rev_reg = RevocationRegistry::RevocationRegistryV1(RevocationRegistryV1 { value: rev_reg }); @@ -486,11 +472,12 @@ pub fn revoke_credential( } #[allow(dead_code)] -pub fn recover_credential( +pub fn unrevoke_credential( + cred_def: &CredentialDefinition, rev_reg_def: &RevocationRegistryDefinition, + rev_reg_priv: &RevocationRegistryDefinitionPrivate, rev_reg: &RevocationRegistry, cred_rev_idx: u32, - tails_reader: &TailsReader, ) -> Result<(RevocationRegistry, RevocationRegistryDelta)> { trace!( "recover >>> rev_reg_def: {:?}, rev_reg: {:?}, cred_rev_idx: {:?}", @@ -499,14 +486,27 @@ pub fn recover_credential( secret!(&cred_rev_idx) ); + let cred_pub_key = match cred_def { + CredentialDefinition::CredentialDefinitionV1(v1) => { + v1.get_public_key().map_err(err_map!( + Unexpected, + "Error fetching public key from credential definition" + ))? + } + }; let max_cred_num = match rev_reg_def { RevocationRegistryDefinition::RevocationRegistryDefinitionV1(v1) => v1.value.max_cred_num, }; let mut rev_reg = match rev_reg { RevocationRegistry::RevocationRegistryV1(v1) => v1.value.clone(), }; - let rev_reg_delta = - CryptoIssuer::recovery_credential(&mut rev_reg, max_cred_num, cred_rev_idx, tails_reader)?; + let rev_reg_delta = ClIssuer::unrevoke_credential( + &mut rev_reg, + max_cred_num, + cred_rev_idx, + &cred_pub_key, + &rev_reg_priv.value, + )?; let new_rev_reg = RevocationRegistry::RevocationRegistryV1(RevocationRegistryV1 { value: rev_reg }); @@ -533,76 +533,3 @@ pub fn merge_revocation_registry_deltas( } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_encode_attribute() { - assert_eq!( - encode_credential_attribute("101 Wilson Lane").unwrap(), - "68086943237164982734333428280784300550565381723532936263016368251445461241953" - ); - assert_eq!(encode_credential_attribute("87121").unwrap(), "87121"); - assert_eq!( - encode_credential_attribute("SLC").unwrap(), - "101327353979588246869873249766058188995681113722618593621043638294296500696424" - ); - assert_eq!( - encode_credential_attribute("101 Tela Lane").unwrap(), - "63690509275174663089934667471948380740244018358024875547775652380902762701972" - ); - assert_eq!( - encode_credential_attribute("UT").unwrap(), - "93856629670657830351991220989031130499313559332549427637940645777813964461231" - ); - assert_eq!( - encode_credential_attribute("").unwrap(), - "102987336249554097029535212322581322789799900648198034993379397001115665086549" - ); - assert_eq!( - encode_credential_attribute("None").unwrap(), - "99769404535520360775991420569103450442789945655240760487761322098828903685777" - ); - assert_eq!(encode_credential_attribute("0").unwrap(), "0"); - assert_eq!(encode_credential_attribute("1").unwrap(), "1"); - - // max i32 - assert_eq!( - encode_credential_attribute("2147483647").unwrap(), - "2147483647" - ); - assert_eq!( - encode_credential_attribute("2147483648").unwrap(), - "26221484005389514539852548961319751347124425277437769688639924217837557266135" - ); - - // min i32 - assert_eq!( - encode_credential_attribute("-2147483648").unwrap(), - "-2147483648" - ); - assert_eq!( - encode_credential_attribute("-2147483649").unwrap(), - "68956915425095939579909400566452872085353864667122112803508671228696852865689" - ); - - assert_eq!( - encode_credential_attribute("0.0").unwrap(), - "62838607218564353630028473473939957328943626306458686867332534889076311281879" - ); - assert_eq!( - encode_credential_attribute("\x00").unwrap(), - "49846369543417741186729467304575255505141344055555831574636310663216789168157" - ); - assert_eq!( - encode_credential_attribute("\x01").unwrap(), - "34356466678672179216206944866734405838331831190171667647615530531663699592602" - ); - assert_eq!( - encode_credential_attribute("\x02").unwrap(), - "99398763056634537812744552006896172984671876672520535998211840060697129507206" - ); - } -} diff --git a/indy-credx/src/services/prover.rs b/indy-credx/src/services/prover.rs index 7eee5d9..37bba7f 100644 --- a/indy-credx/src/services/prover.rs +++ b/indy-credx/src/services/prover.rs @@ -1,13 +1,13 @@ use std::collections::{HashMap, HashSet}; use super::types::*; +use crate::anoncreds_clsignatures::{ + CredentialPublicKey, Issuer as ClIssuer, Prover as ClProver, + RevocationRegistry as CryptoRevocationRegistry, SubProofRequest, Verifier as ClVerifier, + Witness, +}; use crate::error::Result; use crate::services::helpers::*; -use crate::ursa::cl::{ - issuer::Issuer as CryptoIssuer, prover::Prover as CryptoProver, - verifier::Verifier as CryptoVerifier, CredentialPublicKey, - RevocationRegistry as CryptoRevocationRegistry, SubProofRequest, Witness, -}; use indy_data_types::anoncreds::{ credential::AttributeValues, pres_request::{PresentationRequestPayload, RequestedAttributeInfo, RequestedPredicateInfo}, @@ -45,7 +45,7 @@ pub fn create_credential_request( &cred_def.value.primary, cred_def.value.revocation.as_ref(), )?; - let mut credential_values_builder = CryptoIssuer::new_credential_values_builder()?; + let mut credential_values_builder = ClIssuer::new_credential_values_builder()?; credential_values_builder.add_value_hidden("master_secret", &master_secret.value.value()?)?; let cred_values = credential_values_builder.finalize()?; @@ -53,7 +53,7 @@ pub fn create_credential_request( let nonce_copy = nonce.try_clone().map_err(err_map!(Unexpected))?; let (blinded_ms, master_secret_blinding_data, blinded_ms_correctness_proof) = - CryptoProver::blind_credential_secrets( + ClProver::blind_credential_secrets( &credential_pub_key, &credential_offer.key_correctness_proof, &cred_values, @@ -109,7 +109,7 @@ pub fn process_credential( _ => None, }; - CryptoProver::process_credential_signature( + ClProver::process_credential_signature( &mut credential.signature, &credential_values, &credential.signature_correctness_proof, @@ -151,7 +151,7 @@ pub fn create_presentation( credentials.validate()?; let pres_req_val = pres_req.value(); - let mut proof_builder = CryptoProver::new_proof_builder()?; + let mut proof_builder = ClProver::new_proof_builder()?; proof_builder.add_common_attribute("master_secret")?; let mut requested_proof = RequestedProof::default(); @@ -469,7 +469,7 @@ fn build_sub_proof_request( trace!("_build_sub_proof_request <<< req_attrs_for_credential: {:?}, req_predicates_for_credential: {:?}", req_attrs_for_credential, req_predicates_for_credential); - let mut sub_proof_request_builder = CryptoVerifier::new_sub_proof_request_builder()?; + let mut sub_proof_request_builder = ClVerifier::new_sub_proof_request_builder()?; for attr in req_attrs_for_credential { if attr.revealed { diff --git a/indy-credx/src/services/tails.rs b/indy-credx/src/services/tails.rs index 3821d39..7421f5a 100644 --- a/indy-credx/src/services/tails.rs +++ b/indy-credx/src/services/tails.rs @@ -1,17 +1,18 @@ -use rand::random; use std::cell::RefCell; +use std::fmt::Debug; use std::fs::File; -use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write}; +use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use indy_utils::base58; +use rand::random; use sha2::{Digest, Sha256}; -use crate::error::Error; -use crate::ursa::{ - cl::{RevocationTailsAccessor, RevocationTailsGenerator, Tail}, - errors::{UrsaCryptoError, UrsaCryptoErrorKind}, +use crate::anoncreds_clsignatures::{ + Error as ClError, ErrorKind as ClErrorKind, RevocationTailsAccessor, RevocationTailsGenerator, + Tail, }; +use crate::error::Error; const TAILS_BLOB_TAG_SZ: u8 = 2; const TAIL_SIZE: usize = Tail::BYTES_REPR_SIZE; @@ -29,7 +30,7 @@ impl TailsReader { } } -pub trait TailsReaderImpl: std::fmt::Debug + Send { +pub trait TailsReaderImpl: Debug + Send { fn hash(&mut self) -> Result, Error>; fn read(&mut self, size: usize, offset: usize) -> Result, Error>; } @@ -39,7 +40,7 @@ impl RevocationTailsAccessor for TailsReader { &self, tail_id: u32, accessor: &mut dyn FnMut(&Tail), - ) -> std::result::Result<(), UrsaCryptoError> { + ) -> std::result::Result<(), ClError> { trace!("access_tail >>> tail_id: {:?}", tail_id); let tail_bytes = self @@ -49,12 +50,10 @@ impl RevocationTailsAccessor for TailsReader { TAIL_SIZE, TAIL_SIZE * tail_id as usize + TAILS_BLOB_TAG_SZ as usize, ) - .map_err(|_| { - UrsaCryptoError::from_msg( - UrsaCryptoErrorKind::InvalidState, - "Can't read tail bytes from file", - ) - })?; // FIXME: IO error should be returned + .map_err(|e| { + error!("IO error reading tails file: {e}"); + ClError::new(ClErrorKind::InvalidState, "Could not read from tails file") + })?; let tail = Tail::from_bytes(tail_bytes.as_slice())?; accessor(&tail); @@ -80,14 +79,12 @@ impl TailsFileReader { }) } - pub fn open(&mut self) -> Result<(), Error> { - if self.file.is_some() { - Ok(()) - } else { + pub fn open(&mut self) -> Result<&mut BufReader, Error> { + if self.file.is_none() { let file = File::open(self.path.clone())?; self.file.replace(BufReader::new(file)); - Ok(()) } + Ok(self.file.as_mut().unwrap()) } pub fn close(&mut self) { @@ -97,31 +94,32 @@ impl TailsFileReader { impl TailsReaderImpl for TailsFileReader { fn hash(&mut self) -> Result, Error> { - if self.hash.is_some() { - return Ok(self.hash.as_ref().unwrap().clone()); + if let Some(hash) = self.hash.as_ref() { + return Ok(hash.clone()); } - self.open()?; - let file = self.file.as_mut().unwrap(); + let file = self.open()?; file.seek(SeekFrom::Start(0))?; let mut hasher = Sha256::default(); - let mut buf = [0u8; 1024]; loop { - let sz = file.read(&mut buf)?; - if sz == 0 { - self.hash = Some(hasher.finalize().to_vec()); - return Ok(self.hash.as_ref().unwrap().clone()); + let buf = file.fill_buf()?; + let len = buf.len(); + if len == 0 { + break; } - hasher.update(&buf[0..sz]); + hasher.update(&buf); + file.consume(len); } + let hash = hasher.finalize().to_vec(); + self.hash.replace(hash.clone()); + Ok(hash) } fn read(&mut self, size: usize, offset: usize) -> Result, Error> { let mut buf = vec![0u8; size]; - self.open()?; - let file = self.file.as_mut().unwrap(); + let file = self.open()?; file.seek(SeekFrom::Start(offset as u64))?; file.read_exact(buf.as_mut_slice())?; @@ -188,8 +186,8 @@ impl TailsWriter for TailsFileWriter { hasher.update(version); while let Some(tail) = generator.try_next()? { let tail_bytes = tail.to_bytes()?; - buf.write(tail_bytes.as_slice())?; - hasher.update(tail_bytes); + buf.write(&tail_bytes)?; + hasher.update(&tail_bytes); } let mut file = buf .into_inner() diff --git a/indy-credx/src/services/types.rs b/indy-credx/src/services/types.rs index fe174a8..8fc4eee 100644 --- a/indy-credx/src/services/types.rs +++ b/indy-credx/src/services/types.rs @@ -1,6 +1,5 @@ use std::collections::HashSet; -use super::tails::TailsReader; pub use indy_data_types::{ anoncreds::{ cred_def::{ @@ -25,9 +24,9 @@ pub use indy_data_types::{ pub use indy_utils::did::DidValue; use indy_utils::{invalid, Validatable, ValidationError}; +use crate::anoncreds_clsignatures::{RevocationRegistry as CryptoRevocationRegistry, Witness}; use crate::error::Error; use crate::services::helpers::encode_credential_attribute; -use crate::ursa::cl::{RevocationRegistry as CryptoRevocationRegistry, Witness}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CredentialDefinitionConfig { @@ -196,7 +195,7 @@ pub(crate) struct ProvingCredentialKey { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CredentialRevocationState { - pub(crate) witness: Witness, + pub witness: Witness, pub(crate) rev_reg: CryptoRevocationRegistry, pub(crate) timestamp: u64, } @@ -218,19 +217,17 @@ pub struct CredentialRevocationConfig<'a> { pub registry: &'a RevocationRegistry, pub registry_idx: u32, pub registry_used: &'a HashSet, - pub tails_reader: TailsReader, } impl<'a> std::fmt::Debug for CredentialRevocationConfig<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, - "CredentialRevocationConfig {{ reg_def: {:?}, private: {:?}, registry: {:?}, idx: {}, reader: {:?} }}", + "CredentialRevocationConfig {{ reg_def: {:?}, private: {:?}, registry: {:?}, idx: {} }}", self.reg_def, secret!(self.reg_def_private), self.registry, secret!(self.registry_idx), - self.tails_reader, ) } } diff --git a/indy-credx/src/services/verifier.rs b/indy-credx/src/services/verifier.rs index 0d05235..df8aea1 100644 --- a/indy-credx/src/services/verifier.rs +++ b/indy-credx/src/services/verifier.rs @@ -5,8 +5,8 @@ use regex::Regex; use super::helpers::*; use super::types::*; +use crate::anoncreds_clsignatures::{CredentialPublicKey, Verifier as ClVerifier}; use crate::error::Result; -use crate::ursa::cl::{verifier::Verifier as CryptoVerifier, CredentialPublicKey}; use indy_data_types::anoncreds::{ nonce::Nonce, pres_request::{AttributeInfo, NonRevocedInterval, PredicateInfo, PresentationRequestPayload}, @@ -73,7 +73,7 @@ pub fn verify_presentation( &received_predicates, )?; - let mut proof_verifier = CryptoVerifier::new_proof_verifier()?; + let mut proof_verifier = ClVerifier::new_proof_verifier()?; let non_credential_schema = build_non_credential_schema()?; for sub_proof_index in 0..presentation.identifiers.len() { diff --git a/indy-credx/tests/anoncreds_demos.rs b/indy-credx/tests/anoncreds_demos.rs index 7b6f38e..e217157 100644 --- a/indy-credx/tests/anoncreds_demos.rs +++ b/indy-credx/tests/anoncreds_demos.rs @@ -216,7 +216,7 @@ fn anoncreds_works_for_single_issuer_single_prover() { } #[test] -fn anoncreds_works_for_twice_entry_of_credential_for_different_witness() { +fn anoncreds_works_for_single_issuer_single_prover_unrevoked() { // Create Issuer pseudo wallet let mut issuer_wallet = IssuerWallet::default(); @@ -287,7 +287,6 @@ fn anoncreds_works_for_twice_entry_of_credential_for_different_witness() { .expect("Error creating credential request"); // Issuer creates a credential - let tails_reader = TailsFileReader::new(&tails_path); let mut cred_values = MakeCredentialValues::default(); cred_values .add_raw("sex", "male") @@ -313,7 +312,6 @@ fn anoncreds_works_for_twice_entry_of_credential_for_different_witness() { registry: &rev_reg, registry_idx: 1, registry_used: &Default::default(), - tails_reader, }), ) .expect("Error creating credential"); diff --git a/indy-data-types/Cargo.toml b/indy-data-types/Cargo.toml index e1ea65f..b1d9a7e 100644 --- a/indy-data-types/Cargo.toml +++ b/indy-data-types/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "indy-data-types" -version = "0.5.2" +version = "0.6.0" authors = ["Hyperledger Indy Contributors "] description = "Common data types for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org)." -edition = "2018" +edition = "2021" license = "Apache-2.0" readme = "../README.md" repository = "https://github.com/hyperledger/indy-shared-rs/" @@ -16,24 +16,25 @@ path = "src/lib.rs" crate-type = ["rlib"] [features] -default = ["merkle_tree", "serde_support"] -cl = ["serde_support", "ursa", "ursa/cl", "ursa/serde"] -cl_native = ["serde_support", "ursa", "ursa/cl_native", "ursa/serde"] +default = ["serde_support", "cl_native"] +cl = ["serde_support"] +cl_native = ["serde_support", "anoncreds-clsignatures/openssl_bn"] merkle_tree = ["indy-utils/hash", "hex"] rich_schema = [] -serde_support = ["serde", "serde_json", "indy-utils/serde"] -vendored = ["openssl", "openssl/vendored", "openssl-src"] +serde_support = ["serde", "serde_json", "anoncreds-clsignatures?/serde", "indy-utils/serde"] +vendored = ["anoncreds-clsignatures?/openssl_vendored"] [dependencies] hex = { version = "0.4", optional = true } -openssl = { version = "0.10", optional = true } -openssl-src = { version = "=111.25.0", optional = true } # temp override -once_cell = "1.9" -regex = "1.3" +once_cell = "1" +regex = "1" serde = { version = "1.0", optional = true, features = ["derive"] } serde_json = { version = "1.0", optional = true, features = ["raw_value"] } -ursa = { version = "0.3", default-features = false, optional = true } -zeroize = { version = "1.1", features = ["zeroize_derive"] } +zeroize = { version = "1", features = ["zeroize_derive"] } + +[dependencies.anoncreds-clsignatures] +path = "../../anoncreds-clsignatures-rs" +optional = true [dependencies.indy-utils] version = "0.5" diff --git a/indy-data-types/src/anoncreds/cred_def.rs b/indy-data-types/src/anoncreds/cred_def.rs index 69d1ba4..34cc10a 100644 --- a/indy-data-types/src/anoncreds/cred_def.rs +++ b/indy-data-types/src/anoncreds/cred_def.rs @@ -1,3 +1,4 @@ +use crate::anoncreds_clsignatures::CredentialPublicKey; use crate::identifiers::cred_def::CredentialDefinitionId; use crate::identifiers::schema::SchemaId; use crate::utils::Qualifiable; @@ -29,9 +30,9 @@ impl SignatureType { #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CredentialDefinitionData { - pub primary: ursa_cl!(CredentialPrimaryPublicKey), + pub primary: cl_type!(CredentialPrimaryPublicKey), #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] - pub revocation: Option, + pub revocation: Option, } #[derive(Debug)] @@ -88,8 +89,8 @@ pub struct CredentialDefinitionV1 { #[cfg(any(feature = "cl", feature = "cl_native"))] impl CredentialDefinitionV1 { - pub fn get_public_key(&self) -> Result { - let key = crate::ursa::cl::CredentialPublicKey::build_from_parts( + pub fn get_public_key(&self) -> Result { + let key = CredentialPublicKey::build_from_parts( &self.value.primary, self.value.revocation.as_ref(), ) @@ -108,13 +109,13 @@ impl Validatable for CredentialDefinitionV1 { #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct CredentialDefinitionPrivate { - pub value: ursa_cl!(CredentialPrivateKey), + pub value: cl_type!(CredentialPrivateKey), } #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(transparent))] pub struct CredentialKeyCorrectnessProof { - pub value: ursa_cl!(CredentialKeyCorrectnessProof), + pub value: cl_type!(CredentialKeyCorrectnessProof), } impl CredentialKeyCorrectnessProof { diff --git a/indy-data-types/src/anoncreds/cred_offer.rs b/indy-data-types/src/anoncreds/cred_offer.rs index 9f0e435..c37400b 100644 --- a/indy-data-types/src/anoncreds/cred_offer.rs +++ b/indy-data-types/src/anoncreds/cred_offer.rs @@ -9,7 +9,7 @@ use crate::{Validatable, ValidationError}; pub struct CredentialOffer { pub schema_id: SchemaId, pub cred_def_id: CredentialDefinitionId, - pub key_correctness_proof: ursa_cl!(CredentialKeyCorrectnessProof), + pub key_correctness_proof: cl_type!(CredentialKeyCorrectnessProof), pub nonce: Nonce, #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] pub method_name: Option, diff --git a/indy-data-types/src/anoncreds/cred_request.rs b/indy-data-types/src/anoncreds/cred_request.rs index d6ac250..e99e1b5 100644 --- a/indy-data-types/src/anoncreds/cred_request.rs +++ b/indy-data-types/src/anoncreds/cred_request.rs @@ -9,8 +9,8 @@ use indy_utils::did::DidValue; pub struct CredentialRequest { pub prover_did: DidValue, pub cred_def_id: CredentialDefinitionId, - pub blinded_ms: ursa_cl!(BlindedCredentialSecrets), - pub blinded_ms_correctness_proof: ursa_cl!(BlindedCredentialSecretsCorrectnessProof), + pub blinded_ms: cl_type!(BlindedCredentialSecrets), + pub blinded_ms_correctness_proof: cl_type!(BlindedCredentialSecretsCorrectnessProof), pub nonce: Nonce, } @@ -38,7 +38,7 @@ impl Validatable for CredentialRequest { #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct CredentialRequestMetadata { - pub master_secret_blinding_data: ursa_cl!(CredentialSecretsBlindingFactors), + pub master_secret_blinding_data: cl_type!(CredentialSecretsBlindingFactors), pub nonce: Nonce, pub master_secret_name: String, } diff --git a/indy-data-types/src/anoncreds/credential.rs b/indy-data-types/src/anoncreds/credential.rs index b180f31..423ebe8 100644 --- a/indy-data-types/src/anoncreds/credential.rs +++ b/indy-data-types/src/anoncreds/credential.rs @@ -14,10 +14,10 @@ pub struct Credential { pub cred_def_id: CredentialDefinitionId, pub rev_reg_id: Option, pub values: CredentialValues, - pub signature: ursa_cl!(CredentialSignature), - pub signature_correctness_proof: ursa_cl!(SignatureCorrectnessProof), - pub rev_reg: Option, - pub witness: Option, + pub signature: cl_type!(CredentialSignature), + pub signature_correctness_proof: cl_type!(SignatureCorrectnessProof), + pub rev_reg: Option, + pub witness: Option, } #[cfg(any(feature = "cl", feature = "cl_native"))] diff --git a/indy-data-types/src/anoncreds/macros.rs b/indy-data-types/src/anoncreds/macros.rs index 258b5ec..c977910 100644 --- a/indy-data-types/src/anoncreds/macros.rs +++ b/indy-data-types/src/anoncreds/macros.rs @@ -1,12 +1,12 @@ #[cfg(any(feature = "cl", feature = "cl_native"))] -macro_rules! ursa_cl { +macro_rules! cl_type { ($ident:ident) => { - $crate::ursa::cl::$ident + $crate::anoncreds_clsignatures::$ident }; } #[cfg(not(any(feature = "cl", feature = "cl_native")))] -macro_rules! ursa_cl { +macro_rules! cl_type { ($ident:path) => { serde_json::Value }; diff --git a/indy-data-types/src/anoncreds/master_secret.rs b/indy-data-types/src/anoncreds/master_secret.rs index 1d5a648..82d4bd5 100644 --- a/indy-data-types/src/anoncreds/master_secret.rs +++ b/indy-data-types/src/anoncreds/master_secret.rs @@ -1,20 +1,20 @@ use std::fmt; -use crate::ursa::cl::{prover::Prover as UrsaProver, MasterSecret as UrsaMasterSecret}; use serde::{Deserialize, Serialize}; +use crate::anoncreds_clsignatures::{MasterSecret as ClMasterSecret, Prover as ClProver}; use crate::ConversionError; #[derive(Serialize, Deserialize)] pub struct MasterSecret { - pub value: UrsaMasterSecret, + pub value: ClMasterSecret, } impl MasterSecret { #[cfg(any(feature = "cl", feature = "cl_native"))] #[inline] pub fn new() -> Result { - let value = UrsaProver::new_master_secret().map_err(|err| { + let value = ClProver::new_master_secret().map_err(|err| { ConversionError::from_msg(format!("Error creating master secret: {}", err)) })?; Ok(Self { value }) diff --git a/indy-data-types/src/anoncreds/nonce.rs b/indy-data-types/src/anoncreds/nonce.rs index 6efc0df..f215605 100644 --- a/indy-data-types/src/anoncreds/nonce.rs +++ b/indy-data-types/src/anoncreds/nonce.rs @@ -2,11 +2,11 @@ use std::convert::TryFrom; use std::fmt; use std::hash::{Hash, Hasher}; -#[cfg(any(feature = "cl", feature = "cl_native"))] -use crate::ursa::cl::{new_nonce, Nonce as UrsaNonce}; #[cfg(feature = "serde")] use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; +#[cfg(any(feature = "cl", feature = "cl_native"))] +use crate::anoncreds_clsignatures::{new_nonce, Nonce as UrsaNonce}; use crate::ConversionError; pub struct Nonce { @@ -226,7 +226,6 @@ mod tests { "1a", ]; for v in invalid.iter() { - println!("try {}", v); assert!(Nonce::try_from(*v).is_err()) } } diff --git a/indy-data-types/src/anoncreds/presentation.rs b/indy-data-types/src/anoncreds/presentation.rs index 258e46c..064cb1f 100644 --- a/indy-data-types/src/anoncreds/presentation.rs +++ b/indy-data-types/src/anoncreds/presentation.rs @@ -8,7 +8,7 @@ use crate::Validatable; #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct Presentation { - pub proof: ursa_cl!(Proof), + pub proof: cl_type!(Proof), pub requested_proof: RequestedProof, pub identifiers: Vec, } diff --git a/indy-data-types/src/anoncreds/rev_reg.rs b/indy-data-types/src/anoncreds/rev_reg.rs index 452aa64..664cee5 100644 --- a/indy-data-types/src/anoncreds/rev_reg.rs +++ b/indy-data-types/src/anoncreds/rev_reg.rs @@ -19,7 +19,7 @@ impl RevocationRegistry { RevocationRegistryDelta::RevocationRegistryDeltaV1(RevocationRegistryDeltaV1 { value: { let empty = HashSet::new(); - crate::ursa::cl::RevocationRegistryDelta::from_parts( + crate::anoncreds_clsignatures::RevocationRegistryDelta::from_parts( None, &v1.value, &empty, &empty, ) }, @@ -32,7 +32,7 @@ impl RevocationRegistry { #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct RevocationRegistryV1 { - pub value: ursa_cl!(RevocationRegistry), + pub value: cl_type!(RevocationRegistry), } #[derive(Clone, Debug)] @@ -49,5 +49,5 @@ impl Validatable for RevocationRegistryDelta {} #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] pub struct RevocationRegistryDeltaV1 { - pub value: ursa_cl!(RevocationRegistryDelta), + pub value: cl_type!(RevocationRegistryDelta), } diff --git a/indy-data-types/src/anoncreds/rev_reg_def.rs b/indy-data-types/src/anoncreds/rev_reg_def.rs index 6d7e420..98cc04c 100644 --- a/indy-data-types/src/anoncreds/rev_reg_def.rs +++ b/indy-data-types/src/anoncreds/rev_reg_def.rs @@ -80,7 +80,7 @@ pub struct RevocationRegistryDefinitionValue { #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] pub struct RevocationRegistryDefinitionValuePublicKeys { - pub accum_key: ursa_cl!(RevocationKeyPublic), + pub accum_key: cl_type!(RevocationKeyPublic), } #[derive(Clone, Debug)] @@ -143,7 +143,7 @@ pub struct RevocationRegistryDefinitionV1 { #[derive(Debug)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct RevocationRegistryDefinitionPrivate { - pub value: ursa_cl!(RevocationKeyPrivate), + pub value: cl_type!(RevocationKeyPrivate), } #[derive(Deserialize, Debug, Serialize)] diff --git a/indy-data-types/src/lib.rs b/indy-data-types/src/lib.rs index f993780..d2faa73 100644 --- a/indy-data-types/src/lib.rs +++ b/indy-data-types/src/lib.rs @@ -19,7 +19,7 @@ pub use indy_utils::keys; pub use indy_utils::{invalid, ConversionError, Validatable, ValidationError}; #[cfg(any(feature = "cl", feature = "cl_native"))] -pub use ursa; +pub use anoncreds_clsignatures; /// Type definitions related Indy credential issuance and verification pub mod anoncreds; diff --git a/indy-data-types/src/macros.rs b/indy-data-types/src/macros.rs index dfcf4a5..0759b37 100644 --- a/indy-data-types/src/macros.rs +++ b/indy-data-types/src/macros.rs @@ -1,3 +1,4 @@ +#[cfg(feature = "merkle_tree")] macro_rules! unwrap_opt_or_return { ($opt:expr, $err:expr) => { match $opt { diff --git a/wrappers/python/demo/test.py b/wrappers/python/demo/test.py index b0d4aae..46da346 100644 --- a/wrappers/python/demo/test.py +++ b/wrappers/python/demo/test.py @@ -71,7 +71,6 @@ rev_reg, issuer_rev_index, (), - rev_reg_def.tails_location, ), ) # print("Issued credential:") @@ -130,10 +129,10 @@ # rev_delta_2 = rev_reg.revoke_credential( -# rev_reg_def, issuer_rev_index, rev_reg_def.tails_location +# cred_def, rev_reg_def, rev_reg_def_private, issuer_rev_index, # ) rev_delta_2 = rev_reg.update( - rev_reg_def, [], [issuer_rev_index], rev_reg_def.tails_location + cred_def, rev_reg_def, rev_reg_def_private, [], [issuer_rev_index], ) rev_state.update( diff --git a/wrappers/python/indy_credx/bindings.py b/wrappers/python/indy_credx/bindings.py index a4abb28..4ce9fd3 100644 --- a/wrappers/python/indy_credx/bindings.py +++ b/wrappers/python/indy_credx/bindings.py @@ -357,7 +357,6 @@ class RevocationConfig(Structure): ("rev_reg", ObjectHandle), ("rev_reg_index", c_int64), ("rev_reg_used", FfiIntList), - ("tails_path", c_char_p), ] @classmethod @@ -368,7 +367,6 @@ def create( rev_reg: IndyObject, rev_reg_index: int, rev_reg_used: Sequence[int], - tails_path: str, ) -> "RevocationConfig": config = RevocationConfig( rev_reg_def=rev_reg_def.handle, @@ -376,7 +374,6 @@ def create( rev_reg=rev_reg.handle, rev_reg_index=rev_reg_index, rev_reg_used=FfiIntList.create(rev_reg_used), - tails_path=encode_str(tails_path), ) keepalive(config, rev_reg_def, rev_reg_def_private, rev_reg) return config @@ -689,19 +686,21 @@ def process_credential( def revoke_credential( + cred_def: ObjectHandle, rev_reg_def: ObjectHandle, + rev_reg_def_private: ObjectHandle, rev_reg: ObjectHandle, cred_rev_idx: int, - tails_path: str, ) -> Tuple[ObjectHandle, ObjectHandle]: upd_rev_reg = ObjectHandle() rev_delta = ObjectHandle() do_call( "credx_revoke_credential", + cred_def, rev_reg_def, + rev_reg_def_private, rev_reg, c_int64(cred_rev_idx), - encode_str(tails_path), byref(upd_rev_reg), byref(rev_delta), ) @@ -840,21 +839,23 @@ def create_revocation_registry( def update_revocation_registry( + cred_def: ObjectHandle, rev_reg_def: ObjectHandle, + rev_reg_def_private: ObjectHandle, rev_reg: ObjectHandle, issued: Sequence[int], revoked: Sequence[int], - tails_path: str, ) -> Tuple[ObjectHandle, ObjectHandle]: upd_rev_reg = ObjectHandle() rev_delta = ObjectHandle() do_call( "credx_update_revocation_registry", + cred_def, rev_reg_def, + rev_reg_def_private, rev_reg, FfiIntList.create(issued), FfiIntList.create(revoked), - encode_str(tails_path), byref(upd_rev_reg), byref(rev_delta), ) diff --git a/wrappers/python/indy_credx/types.py b/wrappers/python/indy_credx/types.py index 397402b..1de1567 100644 --- a/wrappers/python/indy_credx/types.py +++ b/wrappers/python/indy_credx/types.py @@ -586,28 +586,30 @@ def load(cls, value: JsonType) -> "RevocationRegistry": def revoke_credential( self, + cred_def: Union[JsonType, CredentialDefinition], rev_reg_def: Union[JsonType, RevocationRegistryDefinition], + rev_reg_def_private: Union[JsonType, RevocationRegistryDefinitionPrivate], cred_rev_idx: int, - tails_path: str, ) -> "RevocationRegistryDelta": if not isinstance(rev_reg_def, bindings.IndyObject): rev_reg_def = RevocationRegistryDefinition.load(rev_reg_def) self.handle, rev_delta = bindings.revoke_credential( - rev_reg_def.handle, self.handle, cred_rev_idx, tails_path + cred_def.handle, rev_reg_def.handle, rev_reg_def_private.handle, self.handle, cred_rev_idx, ) return RevocationRegistryDelta(rev_delta) def update( self, + cred_def: Union[JsonType, CredentialDefinition], rev_reg_def: Union[JsonType, RevocationRegistryDefinition], + rev_reg_def_private: Union[JsonType, RevocationRegistryDefinitionPrivate], issued: Sequence[int], revoked: Sequence[int], - tails_path: str, ) -> "RevocationRegistryDelta": if not isinstance(rev_reg_def, bindings.IndyObject): rev_reg_def = RevocationRegistryDefinition.load(rev_reg_def) self.handle, rev_delta = bindings.update_revocation_registry( - rev_reg_def.handle, self.handle, issued, revoked, tails_path + cred_def.handle, rev_reg_def.handle, rev_reg_def_private.handle, self.handle, issued, revoked, ) return RevocationRegistryDelta(rev_delta) @@ -641,7 +643,6 @@ def __init__( rev_reg: Union[JsonType, "RevocationRegistry"] = None, rev_reg_index: int = None, rev_reg_used: Sequence[int] = None, - tails_path: str = None, ): if not isinstance(rev_reg_def, bindings.IndyObject): rev_reg_def = RevocationRegistryDefinition.load(rev_reg_def) @@ -656,7 +657,6 @@ def __init__( self.rev_reg = rev_reg self.rev_reg_index = rev_reg_index self.rev_reg_used = rev_reg_used - self.tails_path = tails_path @property def _native(self) -> bindings.RevocationConfig: @@ -666,7 +666,6 @@ def _native(self) -> bindings.RevocationConfig: self.rev_reg, self.rev_reg_index, self.rev_reg_used, - self.tails_path, ) diff --git a/wrappers/python/indy_credx/version.py b/wrappers/python/indy_credx/version.py index 9f9e286..634910f 100644 --- a/wrappers/python/indy_credx/version.py +++ b/wrappers/python/indy_credx/version.py @@ -1,3 +1,3 @@ """indy_credx library wrapper version.""" -__version__ = "0.3.3" +__version__ = "0.4.0" From 915d343daa38c7a8e0bd4c061ebbaa410a977cc7 Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Mon, 10 Jul 2023 12:15:19 -0700 Subject: [PATCH 2/6] support legacy verification flag Signed-off-by: Andrew Whitehead --- indy-credx/src/ffi/presentation.rs | 49 ++++++++++++++++++++++++-- indy-credx/src/services/verifier.rs | 41 +++++++++++++++++++++ wrappers/python/demo/test.py | 10 ++++++ wrappers/python/indy_credx/bindings.py | 3 +- wrappers/python/indy_credx/types.py | 2 ++ 5 files changed, 102 insertions(+), 3 deletions(-) diff --git a/indy-credx/src/ffi/presentation.rs b/indy-credx/src/ffi/presentation.rs index 4377ab4..81c91eb 100644 --- a/indy-credx/src/ffi/presentation.rs +++ b/indy-credx/src/ffi/presentation.rs @@ -10,7 +10,7 @@ use crate::error::Result; use crate::services::{ prover::create_presentation, types::{PresentCredentials, Presentation, RevocationRegistryDefinition}, - verifier::verify_presentation, + verifier::_verify_presentation, }; impl_indy_object!(Presentation, "Presentation"); @@ -193,6 +193,50 @@ pub extern "C" fn credx_verify_presentation( rev_reg_defs: FfiList, rev_reg_entries: FfiList, result_p: *mut i8, +) -> ErrorCode { + _credx_verify_presentation( + presentation, + pres_req, + schemas, + cred_defs, + rev_reg_defs, + rev_reg_entries, + false, + result_p, + ) +} + +#[no_mangle] +pub extern "C" fn credx_verify_presentation_legacy( + presentation: ObjectHandle, + pres_req: ObjectHandle, + schemas: FfiList, + cred_defs: FfiList, + rev_reg_defs: FfiList, + rev_reg_entries: FfiList, + result_p: *mut i8, +) -> ErrorCode { + _credx_verify_presentation( + presentation, + pres_req, + schemas, + cred_defs, + rev_reg_defs, + rev_reg_entries, + true, + result_p, + ) +} + +fn _credx_verify_presentation( + presentation: ObjectHandle, + pres_req: ObjectHandle, + schemas: FfiList, + cred_defs: FfiList, + rev_reg_defs: FfiList, + rev_reg_entries: FfiList, + accept_legacy_revocation: bool, + result_p: *mut i8, ) -> ErrorCode { catch_error(|| { let schemas = IndyObjectList::load(schemas.as_slice())?; @@ -221,13 +265,14 @@ pub extern "C" fn credx_verify_presentation( .or_insert_with(HashMap::new) .insert(*timestamp, entry.cast_ref()?); } - let verify = verify_presentation( + let verify = _verify_presentation( presentation.load()?.cast_ref()?, pres_req.load()?.cast_ref()?, &schemas.refs_map()?, &cred_defs.refs_map()?, Some(&rev_reg_defs.refs_map()?), Some(&rev_regs), + accept_legacy_revocation, )?; unsafe { *result_p = verify as i8 }; Ok(()) diff --git a/indy-credx/src/services/verifier.rs b/indy-credx/src/services/verifier.rs index df8aea1..36d311f 100644 --- a/indy-credx/src/services/verifier.rs +++ b/indy-credx/src/services/verifier.rs @@ -34,6 +34,46 @@ pub fn verify_presentation( cred_defs: &HashMap, rev_reg_defs: Option<&HashMap>, rev_regs: Option<&HashMap>>, +) -> Result { + _verify_presentation( + presentation, + pres_req, + schemas, + cred_defs, + rev_reg_defs, + rev_regs, + false, + ) +} + +/// Temporary method for verifying presentations with unlinked revocation proofs +pub fn verify_presentation_legacy( + presentation: &Presentation, + pres_req: &PresentationRequest, + schemas: &HashMap, + cred_defs: &HashMap, + rev_reg_defs: Option<&HashMap>, + rev_regs: Option<&HashMap>>, +) -> Result { + _verify_presentation( + presentation, + pres_req, + schemas, + cred_defs, + rev_reg_defs, + rev_regs, + true, + ) +} + +pub(crate) fn _verify_presentation( + presentation: &Presentation, + pres_req: &PresentationRequest, + schemas: &HashMap, + cred_defs: &HashMap, + rev_reg_defs: Option<&HashMap>, + rev_regs: Option<&HashMap>>, + accept_legacy_revocation: bool, ) -> Result { trace!("verify >>> presentation: {:?}, pres_req: {:?}, schemas: {:?}, cred_defs: {:?}, rev_reg_defs: {:?} rev_regs: {:?}", presentation, pres_req, schemas, cred_defs, rev_reg_defs, rev_regs); @@ -74,6 +114,7 @@ pub fn verify_presentation( )?; let mut proof_verifier = ClVerifier::new_proof_verifier()?; + proof_verifier.accept_legacy_revocation(accept_legacy_revocation); let non_credential_schema = build_non_credential_schema()?; for sub_proof_index in 0..presentation.identifiers.len() { diff --git a/wrappers/python/demo/test.py b/wrappers/python/demo/test.py index 46da346..a09e97e 100644 --- a/wrappers/python/demo/test.py +++ b/wrappers/python/demo/test.py @@ -127,6 +127,16 @@ ) assert verified +# check legacy revocation proof support +verified = presentation.verify( + pres_req, + [schema], + [cred_def], + [rev_reg_def], + {rev_reg_def.id: {timestamp: rev_reg}}, + accept_legacy_revocation=True, +) +assert verified # rev_delta_2 = rev_reg.revoke_credential( # cred_def, rev_reg_def, rev_reg_def_private, issuer_rev_index, diff --git a/wrappers/python/indy_credx/bindings.py b/wrappers/python/indy_credx/bindings.py index 4ce9fd3..e0d3890 100644 --- a/wrappers/python/indy_credx/bindings.py +++ b/wrappers/python/indy_credx/bindings.py @@ -789,6 +789,7 @@ def verify_presentation( cred_defs: Sequence[ObjectHandle], rev_reg_defs: Sequence[ObjectHandle], rev_regs: Sequence[RevocationEntry], + accept_legacy_revocation: bool = False, ) -> bool: verify = c_int8() entry_list = RevocationEntryList() @@ -796,7 +797,7 @@ def verify_presentation( entry_list.count = len(rev_regs) entry_list.data = (RevocationEntry * entry_list.count)(*rev_regs) do_call( - "credx_verify_presentation", + "credx_verify_presentation_legacy" if accept_legacy_revocation else "credx_verify_presentation", presentation, pres_req, FfiObjectHandleList.create(schemas), diff --git a/wrappers/python/indy_credx/types.py b/wrappers/python/indy_credx/types.py index 1de1567..ee22ba4 100644 --- a/wrappers/python/indy_credx/types.py +++ b/wrappers/python/indy_credx/types.py @@ -431,6 +431,7 @@ def verify( rev_reg_entries: Mapping[ str, Mapping[int, Union[JsonType, "RevocationRegistry"]] ] = None, + accept_legacy_revocation: bool = False, ) -> bool: if not isinstance(pres_req, bindings.IndyObject): pres_req = PresentationRequest.load(pres_req) @@ -470,6 +471,7 @@ def verify( cred_defs, reg_defs, reg_entries or None, + accept_legacy_revocation, ) From 42e843446258ce6920429b343d1d14244161f983 Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Mon, 10 Jul 2023 12:25:14 -0700 Subject: [PATCH 3/6] fix library_version method Signed-off-by: Andrew Whitehead --- wrappers/python/demo/test.py | 2 ++ wrappers/python/indy_credx/bindings.py | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/wrappers/python/demo/test.py b/wrappers/python/demo/test.py index a09e97e..1d066d0 100644 --- a/wrappers/python/demo/test.py +++ b/wrappers/python/demo/test.py @@ -2,6 +2,7 @@ from indy_credx import ( generate_nonce, + library_version, Credential, CredentialDefinition, CredentialOffer, @@ -16,6 +17,7 @@ Schema, ) +print("credx library version:", library_version()) test_did = "55GkHamhTU1ZbTbV2ab9DE" diff --git a/wrappers/python/indy_credx/bindings.py b/wrappers/python/indy_credx/bindings.py index e0d3890..08100c2 100644 --- a/wrappers/python/indy_credx/bindings.py +++ b/wrappers/python/indy_credx/bindings.py @@ -420,9 +420,9 @@ def get_library() -> CDLL: def library_version() -> str: """Get the version of the installed aries-askar library.""" - lib = get_library() - lib.credx_version.restype = c_void_p - return str(StrBuffer(lib.credx_version())) + lib_fn = getattr(get_library(), "credx_version") + lib_fn.restype = StrBuffer + return str(lib_fn()) def _load_library(lib_name: str) -> CDLL: From 8757c86c4aa06b101a68d1781682268a9cbf727e Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Tue, 11 Jul 2023 09:35:38 -0700 Subject: [PATCH 4/6] update to published crate Signed-off-by: Andrew Whitehead --- indy-data-types/Cargo.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/indy-data-types/Cargo.toml b/indy-data-types/Cargo.toml index b1d9a7e..f00048f 100644 --- a/indy-data-types/Cargo.toml +++ b/indy-data-types/Cargo.toml @@ -25,6 +25,7 @@ serde_support = ["serde", "serde_json", "anoncreds-clsignatures?/serde", "indy-u vendored = ["anoncreds-clsignatures?/openssl_vendored"] [dependencies] +anoncreds-clsignatures = { version = "0.1", optional = true } hex = { version = "0.4", optional = true } once_cell = "1" regex = "1" @@ -32,10 +33,6 @@ serde = { version = "1.0", optional = true, features = ["derive"] } serde_json = { version = "1.0", optional = true, features = ["raw_value"] } zeroize = { version = "1", features = ["zeroize_derive"] } -[dependencies.anoncreds-clsignatures] -path = "../../anoncreds-clsignatures-rs" -optional = true - [dependencies.indy-utils] version = "0.5" path = "../indy-utils" From 8abe4d30c5346a035f9ad7570e5c0c12580654fc Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Tue, 11 Jul 2023 09:40:14 -0700 Subject: [PATCH 5/6] update readme Signed-off-by: Andrew Whitehead --- README.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 7454c3f..ea5f3ab 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,13 @@ Shared Rust libraries for Hyperledger Indy. -- `indy-credx`: Indy verifiable credential issuance and presentation (aka Anoncreds) +- `indy-credx`: Indy verifiable credential issuance and presentation (aka Anoncreds). -- `indy-data-types`: Data type definitions for Schemas, Credential Definitions and other - types related to credential issuance and processing +- `indy-data-types`: Data type definitions for Schemas, Credential Definitions and other types related to credential issuance and processing. - `indy-test-utils`: Utilities for use in integration tests. -- `indy-utils`: Standard wrappers around binary data encodings and Ursa-provided - cryptography functions. Includes support for representing WQL (wallet query - language) expressions, normalizing transactions for signing, deriving DIDs and - verification keys, and packing and unpacking agent messages using the DIDComm - v1 envelope format. +- `indy-utils`: Standard wrappers around binary data encodings. Includes support for normalizing transactions for signing, deriving DIDs and verification keys. ## Credit From 0bed50a8cac8ab9d04f91e8cb12471a3440f2656 Mon Sep 17 00:00:00 2001 From: Andrew Whitehead Date: Tue, 11 Jul 2023 09:40:31 -0700 Subject: [PATCH 6/6] fix ursa references Signed-off-by: Andrew Whitehead --- indy-credx/src/error.rs | 1 - indy-data-types/src/anoncreds/nonce.rs | 16 ++++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/indy-credx/src/error.rs b/indy-credx/src/error.rs index 25b976b..059e2c9 100644 --- a/indy-credx/src/error.rs +++ b/indy-credx/src/error.rs @@ -137,7 +137,6 @@ impl From for Error { impl From for Error { fn from(err: ClError) -> Self { - // let message = format!("Ursa Crypto Error: {}", Fail::iter_causes(&err).map(|e| e.to_string()).collect::()); let message = err.to_string(); let kind = match err.kind() { ClErrorKind::InvalidState => ErrorKind::InvalidState, diff --git a/indy-data-types/src/anoncreds/nonce.rs b/indy-data-types/src/anoncreds/nonce.rs index f215605..fc3d3d1 100644 --- a/indy-data-types/src/anoncreds/nonce.rs +++ b/indy-data-types/src/anoncreds/nonce.rs @@ -6,13 +6,13 @@ use std::hash::{Hash, Hasher}; use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(any(feature = "cl", feature = "cl_native"))] -use crate::anoncreds_clsignatures::{new_nonce, Nonce as UrsaNonce}; +use crate::anoncreds_clsignatures::{new_nonce, Nonce as ClNonce}; use crate::ConversionError; pub struct Nonce { strval: String, #[cfg(any(feature = "cl", feature = "cl_native"))] - native: UrsaNonce, + native: ClNonce, } impl Nonce { @@ -26,20 +26,20 @@ impl Nonce { #[cfg(any(feature = "cl", feature = "cl_native"))] #[inline] - pub fn from_native(native: UrsaNonce) -> Result { + pub fn from_native(native: ClNonce) -> Result { let strval = native.to_dec().map_err(|e| e.to_string())?; Ok(Self { strval, native }) } #[cfg(any(feature = "cl", feature = "cl_native"))] #[inline] - pub fn as_native(&self) -> &UrsaNonce { + pub fn as_native(&self) -> &ClNonce { &self.native } #[cfg(any(feature = "cl", feature = "cl_native"))] #[inline] - pub fn into_native(self) -> UrsaNonce { + pub fn into_native(self) -> ClNonce { self.native } @@ -55,7 +55,7 @@ impl Nonce { } #[cfg(any(feature = "cl", feature = "cl_native"))] { - let native = UrsaNonce::from_dec(&strval).map_err(|e| e.to_string())?; + let native = ClNonce::from_dec(&strval).map_err(|e| e.to_string())?; Ok(Self { strval, native }) } #[cfg(not(any(feature = "cl", feature = "cl_native")))] @@ -243,11 +243,11 @@ mod tests { #[cfg(all(feature = "serde", any(feature = "cl", feature = "cl_native")))] #[test] fn nonce_convert() { - let nonce = UrsaNonce::new().expect("Error creating nonce"); + let nonce = ClNonce::new().expect("Error creating nonce"); let ser = serde_json::to_string(&nonce).unwrap(); let des = serde_json::from_str::(&ser).unwrap(); let ser2 = serde_json::to_string(&des).unwrap(); - let nonce_des = serde_json::from_str::(&ser2).unwrap(); + let nonce_des = serde_json::from_str::(&ser2).unwrap(); assert_eq!(nonce, nonce_des); let nonce = Nonce::new().unwrap();