Skip to content

Update to idiomatic rust #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion anoncreds/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "anoncreds"
version = "0.3.1"
authors = ["Hyperledger AnonCreds Contributors <[email protected]>"]
description = "Verifiable credential issuance and presentation for Hyperledger AnonCreds (https://www.hyperledger.org/projects), which provides a foundation for self-sovereign identity."
edition = "2018"
edition = "2021"
license = "Apache-2.0"
readme = "../README.md"
repository = "https://github.com/hyperledger/anoncreds-rs/"
Expand Down
15 changes: 6 additions & 9 deletions anoncreds/src/data_types/anoncreds/cred_def.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use indy_utils::{Validatable, ValidationError};
use std::str::FromStr;

use crate::{data_types::ConversionError, impl_anoncreds_object_identifier};

Expand All @@ -13,19 +14,15 @@ pub enum SignatureType {
CL,
}

impl SignatureType {
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
match value {
impl FromStr for SignatureType {
type Err = ConversionError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
CL_SIGNATURE_TYPE => Ok(Self::CL),
_ => Err(ConversionError::from_msg("Invalid signature type")),
}
}

pub fn to_str(&self) -> &'static str {
match *self {
SignatureType::CL => CL_SIGNATURE_TYPE,
}
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down
30 changes: 16 additions & 14 deletions anoncreds/src/data_types/anoncreds/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ macro_rules! impl_anoncreds_object_identifier {
Self(s.into())
}

pub fn new(s: impl Into<String>) -> Result<Self, crate::data_types::ValidationError> {
pub fn new(s: impl Into<String>) -> Result<Self, $crate::data_types::ValidationError> {
let s = Self(s.into());
s.validate()?;
Ok(s)
}
}

impl crate::data_types::Validatable for $i {
fn validate(&self) -> Result<(), crate::data_types::ValidationError> {
impl $crate::data_types::Validatable for $i {
fn validate(&self) -> Result<(), $crate::data_types::ValidationError> {
// TODO: stricten the URI regex.
// Right now everything after the first colon is allowed, we might want to restrict
// this
Expand All @@ -35,23 +35,25 @@ macro_rules! impl_anoncreds_object_identifier {
}
}

impl Into<String> for $i {
fn into(self) -> String {
self.0
impl From<$i> for String {
fn from(i: $i) -> Self {
i.0
}
}

// TODO: replace these with TryInto
impl From<String> for $i {
fn from(value: String) -> Self {
$i::new_unchecked(value)
impl TryFrom<String> for $i {
type Error = indy_utils::ValidationError;

fn try_from(value: String) -> Result<Self, Self::Error> {
$i::new(value)
}
}

// TODO: replace these with TryInto
impl From<&str> for $i {
fn from(value: &str) -> Self {
$i::new_unchecked(value.to_owned())
impl TryFrom<&str> for $i {
type Error = indy_utils::ValidationError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
$i::new(value.to_owned())
}
}

Expand Down
2 changes: 1 addition & 1 deletion anoncreds/src/data_types/anoncreds/master_secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl MasterSecret {
#[inline]
pub fn new() -> Result<Self, ConversionError> {
let value = UrsaProver::new_master_secret().map_err(|err| {
ConversionError::from_msg(format!("Error creating master secret: {}", err))
ConversionError::from_msg(format!("Error creating master secret: {err}"))
})?;
Ok(Self { value })
}
Expand Down
12 changes: 6 additions & 6 deletions anoncreds/src/data_types/anoncreds/nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Nonce {
#[inline]
pub fn new() -> Result<Self, ConversionError> {
let native = new_nonce()
.map_err(|err| ConversionError::from_msg(format!("Error creating nonce: {}", err)))?;
.map_err(|err| ConversionError::from_msg(format!("Error creating nonce: {err}")))?;
Self::from_native(native)
}

Expand All @@ -42,7 +42,7 @@ impl Nonce {
return Err("Invalid bignum: empty value".into());
}
for c in strval.chars() {
if c < '0' || c > '9' {
if !matches!(c, '0'..='9') {
return Err("Invalid bignum value".into());
}
}
Expand Down Expand Up @@ -163,28 +163,28 @@ impl<'a> Deserialize<'a> for Nonce {
where
E: serde::de::Error,
{
Ok(Nonce::try_from(value).map_err(E::custom)?)
Nonce::try_from(value).map_err(E::custom)
}

fn visit_u64<E>(self, value: u64) -> Result<Nonce, E>
where
E: serde::de::Error,
{
Ok(Nonce::try_from(value).map_err(E::custom)?)
Nonce::try_from(value).map_err(E::custom)
}

fn visit_u128<E>(self, value: u128) -> Result<Nonce, E>
where
E: serde::de::Error,
{
Ok(Nonce::try_from(value).map_err(E::custom)?)
Nonce::try_from(value).map_err(E::custom)
}

fn visit_str<E>(self, value: &str) -> Result<Nonce, E>
where
E: serde::de::Error,
{
Ok(Nonce::from_dec(value).map_err(E::custom)?)
Nonce::from_dec(value).map_err(E::custom)
}
}

Expand Down
6 changes: 3 additions & 3 deletions anoncreds/src/data_types/anoncreds/pres_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub enum PresentationRequestVersion {
}

impl PresentationRequest {
pub fn value<'a>(&'a self) -> &'a PresentationRequestPayload {
pub fn value(&self) -> &PresentationRequestPayload {
match self {
PresentationRequest::PresentationRequestV1(req) => req,
PresentationRequest::PresentationRequestV2(req) => req,
Expand Down Expand Up @@ -213,7 +213,7 @@ impl Validatable for PresentationRequest {
}

if let Some(ref restrictions) = requested_attribute.restrictions {
_process_operator(&restrictions, &version)?;
_process_operator(restrictions, &version)?;
}
}

Expand All @@ -225,7 +225,7 @@ impl Validatable for PresentationRequest {
));
}
if let Some(ref restrictions) = requested_predicate.restrictions {
_process_operator(&restrictions, &version)?;
_process_operator(restrictions, &version)?;
}
}

Expand Down
31 changes: 17 additions & 14 deletions anoncreds/src/data_types/anoncreds/presentation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::collections::HashMap;

use indy_utils::ValidationError;

use crate::data_types::Validatable;

use super::{cred_def::CredentialDefinitionId, rev_reg::RevocationRegistryId, schema::SchemaId};
Expand All @@ -11,7 +13,7 @@ pub struct Presentation {
pub identifiers: Vec<Identifier>,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
pub struct RequestedProof {
pub revealed_attrs: HashMap<String, RevealedAttributeInfo>,
#[serde(skip_serializing_if = "HashMap::is_empty")]
Expand All @@ -25,18 +27,6 @@ pub struct RequestedProof {
pub predicates: HashMap<String, SubProofReferent>,
}

impl Default for RequestedProof {
fn default() -> Self {
RequestedProof {
revealed_attrs: HashMap::new(),
revealed_attr_groups: HashMap::new(),
self_attested_attrs: HashMap::new(),
unrevealed_attrs: HashMap::new(),
predicates: HashMap::new(),
}
}
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct SubProofReferent {
pub sub_proof_index: u32,
Expand Down Expand Up @@ -69,7 +59,20 @@ pub struct Identifier {
pub timestamp: Option<u64>,
}

impl Validatable for Presentation {}
impl Validatable for Presentation {
fn validate(&self) -> Result<(), ValidationError> {
for identifier in self.identifiers.iter() {
identifier.schema_id.validate()?;
identifier.cred_def_id.validate()?;
identifier
.rev_reg_id
.as_ref()
.map(|rri| rri.validate())
.transpose()?;
}
Ok(())
}
}

#[cfg(test)]
mod tests {
Expand Down
44 changes: 17 additions & 27 deletions anoncreds/src/data_types/anoncreds/rev_reg_def.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::str::FromStr;

use crate::{
data_types::{invalid, ConversionError, Validatable, ValidationError},
impl_anoncreds_object_identifier,
Expand All @@ -13,36 +15,28 @@ pub const ISSUANCE_ON_DEMAND: &str = "ISSUANCE_ON_DEMAND";
impl_anoncreds_object_identifier!(RevocationRegistryDefinitionId);

#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
pub enum IssuanceType {
#[default]
ISSUANCE_BY_DEFAULT,
ISSUANCE_ON_DEMAND,
}

impl IssuanceType {
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
match value {
impl FromStr for IssuanceType {
type Err = ConversionError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
ISSUANCE_BY_DEFAULT => Ok(Self::ISSUANCE_BY_DEFAULT),
ISSUANCE_ON_DEMAND => Ok(Self::ISSUANCE_ON_DEMAND),
_ => Err(ConversionError::from_msg("Invalid issuance type")),
}
}

pub fn to_bool(&self) -> bool {
self.clone() == IssuanceType::ISSUANCE_BY_DEFAULT
}

pub fn to_str(&self) -> &'static str {
match *self {
Self::ISSUANCE_BY_DEFAULT => ISSUANCE_BY_DEFAULT,
Self::ISSUANCE_ON_DEMAND => ISSUANCE_ON_DEMAND,
}
}
}

impl Default for IssuanceType {
fn default() -> Self {
Self::ISSUANCE_BY_DEFAULT
impl IssuanceType {
pub fn to_bool(&self) -> bool {
*self == IssuanceType::ISSUANCE_BY_DEFAULT
}
}

Expand All @@ -52,19 +46,15 @@ pub enum RegistryType {
CL_ACCUM,
}

impl RegistryType {
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
match value {
impl FromStr for RegistryType {
type Err = ConversionError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
CL_ACCUM => Ok(Self::CL_ACCUM),
_ => Err(ConversionError::from_msg("Invalid registry type")),
}
}

pub fn to_str(&self) -> &'static str {
match *self {
Self::CL_ACCUM => CL_ACCUM,
}
}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
Expand Down
14 changes: 4 additions & 10 deletions anoncreds/src/data_types/anoncreds/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,9 @@ pub struct SchemaV1 {
pub seq_no: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AttributeNames(pub HashSet<String>);

impl AttributeNames {
pub fn new() -> Self {
AttributeNames(HashSet::new())
}
}

impl From<&[&str]> for AttributeNames {
fn from(attrs: &[&str]) -> Self {
let mut attrset = HashSet::new();
Expand All @@ -56,9 +50,9 @@ impl From<HashSet<String>> for AttributeNames {
}
}

impl Into<HashSet<String>> for AttributeNames {
fn into(self) -> HashSet<String> {
self.0
impl From<AttributeNames> for HashSet<String> {
fn from(a: AttributeNames) -> Self {
a.0
}
}

Expand Down
6 changes: 3 additions & 3 deletions anoncreds/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ impl fmt::Display for Error {
match (self.kind, &self.message) {
(ErrorKind::Input, None) => write!(f, "{}", self.kind),
(ErrorKind::Input, Some(msg)) => f.write_str(msg),
(kind, None) => write!(f, "{}", kind),
(kind, Some(msg)) => write!(f, "{}: {}", kind, msg),
(kind, None) => write!(f, "{kind}"),
(kind, Some(msg)) => write!(f, "{kind}: {msg}"),
}?;
if let Some(ref source) = self.cause {
write!(f, " [{}]", source)?;
write!(f, " [{source}]")?;
}
Ok(())
}
Expand Down
Loading