Skip to content
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

AnonCreds Credentials using the W3C Standard - proof value encoding #276

Merged
merged 19 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from 15 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
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ ffi = ["dep:ffi-support"]
zeroize = ["dep:zeroize"]
logger = ["dep:env_logger"]
vendored = ["anoncreds-clsignatures/openssl_vendored"]
w3c = ["base64", "chrono"]
w3c = ["base64", "chrono", "rmp-serde"]

[dependencies]
anoncreds-clsignatures = "0.3.0"
Expand All @@ -43,6 +43,7 @@ thiserror = "1.0.39"
zeroize = { version = "1.5.7", optional = true, features = ["zeroize_derive"] }
base64 = { version = "0.21.5", optional = true }
chrono = { version = "0.4.31", optional = true, features = ["serde"] }
rmp-serde = { version = "1.1.2", optional = true }

[dev-dependencies]
rstest = "0.18.2"
Expand Down
26 changes: 24 additions & 2 deletions src/data_types/nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use std::hash::{Hash, Hasher};

use crate::cl::{new_nonce, Nonce as CryptoNonce};
use crate::error::ConversionError;
use serde::de::{Error, SeqAccess};
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

pub struct Nonce {
strval: String,
Expand Down Expand Up @@ -52,6 +54,13 @@ impl Nonce {
Ok(Self { strval, native })
}

pub fn from_bytes(bytes: &[u8]) -> Result<Self, ConversionError> {
let native = CryptoNonce::from_bytes(bytes).map_err(|err| {
ConversionError::from_msg(format!("Error converting nonce from bytes: {err}"))
})?;
Self::from_native(native)
}

pub fn try_clone(&self) -> Result<Self, ConversionError> {
Self::from_dec(self.strval.clone())
}
Expand Down Expand Up @@ -157,7 +166,7 @@ impl<'a> Deserialize<'a> for Nonce {
type Value = Nonce;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("integer or string nonce")
formatter.write_str("integer or string nonce or bytes")
}

fn visit_i64<E>(self, value: i64) -> Result<Nonce, E>
Expand Down Expand Up @@ -187,9 +196,22 @@ impl<'a> Deserialize<'a> for Nonce {
{
Nonce::from_dec(value).map_err(E::custom)
}

fn visit_seq<E>(self, mut seq: E) -> Result<Self::Value, E::Error>
where
E: SeqAccess<'a>,
{
let mut vec = Vec::new();

while let Ok(Some(Value::Number(elem))) = seq.next_element() {
vec.push(elem.as_u64().unwrap() as u8);
Artemkaaas marked this conversation as resolved.
Show resolved Hide resolved
}

Nonce::from_bytes(&vec).map_err(E::Error::custom)
}
}

deserializer.deserialize_str(BigNumberVisitor)
deserializer.deserialize_any(BigNumberVisitor)
}
}

Expand Down
75 changes: 66 additions & 9 deletions src/data_types/w3c/proof.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::data_types::cred_def::CredentialDefinitionId;
use crate::data_types::rev_reg_def::RevocationRegistryDefinitionId;
use crate::data_types::schema::SchemaId;
use crate::utils::encoded_object::EncodedObject;
use crate::utils::base64;
use crate::utils::msg_pack;
use crate::Result;

use anoncreds_clsignatures::{
AggregatedProof, CredentialSignature as CLCredentialSignature, RevocationRegistry,
SignatureCorrectnessProof, SubProof, Witness,
Expand Down Expand Up @@ -42,29 +44,31 @@ impl DataIntegrityProof {
cryptosuite: CryptoSuite,
value: V,
challenge: Option<String>,
) -> Self {
DataIntegrityProof {
type_: DataIntegrityProofType::DataIntegrityProof,
) -> Result<Self> {
Ok(DataIntegrityProof {
cryptosuite,
proof_value: value.encode(),
proof_value: value.encode()?,
challenge,
}
type_: DataIntegrityProofType::DataIntegrityProof,
})
}

pub(crate) fn new_credential_proof(value: CredentialSignatureProof) -> DataIntegrityProof {
pub(crate) fn new_credential_proof(
value: CredentialSignatureProof,
) -> Result<DataIntegrityProof> {
DataIntegrityProof::new(CryptoSuite::AnonCredsVc2023, value, None)
}

pub(crate) fn new_credential_presentation_proof(
value: CredentialPresentationProofValue,
) -> DataIntegrityProof {
) -> Result<DataIntegrityProof> {
DataIntegrityProof::new(CryptoSuite::AnonCredsPresVc2023, value, None)
}

pub(crate) fn new_presentation_proof(
value: PresentationProofValue,
challenge: String,
) -> DataIntegrityProof {
) -> Result<DataIntegrityProof> {
DataIntegrityProof::new(CryptoSuite::AnonCredsPresVp2023, value, Some(challenge))
}

Expand Down Expand Up @@ -187,3 +191,56 @@ pub struct CredentialProofDetails {
pub rev_reg_index: Option<u32>,
pub timestamp: Option<u64>,
}

const BASE_HEADER: char = 'u';

pub trait EncodedObject {
fn encode(&self) -> Result<String>
where
Self: Serialize,
{
let bytes = msg_pack::encode(self)?;
let base64_encoded = base64::encode(bytes);
Ok(format!("{}{}", BASE_HEADER, base64_encoded))
}

fn decode(string: &str) -> Result<Self>
where
Self: DeserializeOwned,
{
match string.chars().next() {
Some(BASE_HEADER) => {
// ok
}
value => return Err(err_msg!("Unexpected multibase base header {:?}", value)),
}
let bytes = base64::decode(&string[1..])?;
let json = msg_pack::decode(&bytes)?;
Ok(json)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct TestObject {
type_: String,
value: i32,
}

impl EncodedObject for TestObject {}

#[test]
fn encoded_object_encode_decode_works() {
let obj = TestObject {
type_: "Test".to_string(),
value: 1,
};
let encoded = obj.encode().unwrap();
assert_eq!("ugqV0eXBlX6RUZXN0pXZhbHVlAQ", encoded);
let decoded = TestObject::decode(&encoded).unwrap();
assert_eq!(obj, decoded)
}
}
4 changes: 2 additions & 2 deletions src/services/w3c/credential_conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ pub fn credential_to_w3c(
rev_reg: credential.rev_reg,
witness: credential.witness,
};
let proof = DataIntegrityProof::new_credential_proof(signature);
let proof = DataIntegrityProof::new_credential_proof(signature)?;
let w3c_credential = W3CCredential::new(issuer, attributes, proof, version.as_ref());

trace!("credential_to_w3c <<< w3c_credential {:?}", w3c_credential);
Expand Down Expand Up @@ -347,7 +347,7 @@ pub(super) mod tests {
W3CCredential::new(
issuer_id(),
CredentialAttributes::from(&cred_values()),
DataIntegrityProof::new_credential_proof(_signature_data()),
DataIntegrityProof::new_credential_proof(_signature_data()).unwrap(),
None,
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/services/w3c/issuer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ pub fn create_credential(
witness,
};

let proof = DataIntegrityProof::new_credential_proof(signature);
let proof = DataIntegrityProof::new_credential_proof(signature)?;
let credential = W3CCredential::new(
cred_def.issuer_id.to_owned(),
raw_credential_values,
Expand Down
6 changes: 3 additions & 3 deletions src/services/w3c/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ pub fn process_credential(
credential_signature.witness.as_ref(),
)?;

*proof = DataIntegrityProof::new_credential_proof(credential_signature);
*proof = DataIntegrityProof::new_credential_proof(credential_signature)?;

trace!("process_w3c_credential <<< ");

Expand Down Expand Up @@ -192,7 +192,7 @@ pub fn create_presentation(
timestamp: present.timestamp,
sub_proof,
};
let proof = DataIntegrityProof::new_credential_presentation_proof(proof);
let proof = DataIntegrityProof::new_credential_presentation_proof(proof)?;
let credential = W3CCredential::derive(credential_attributes, proof, present.cred);
verifiable_credentials.push(credential);
}
Expand All @@ -203,7 +203,7 @@ pub fn create_presentation(
let proof = DataIntegrityProof::new_presentation_proof(
presentation_proof,
presentation_request.nonce.to_string(),
);
)?;
let presentation = W3CPresentation::new(verifiable_credentials, proof, version.as_ref());

trace!(
Expand Down
5 changes: 3 additions & 2 deletions src/services/w3c/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,15 +448,16 @@ mod tests {
timestamp: Some(PROOF_TIMESTAMP),
sub_proof: _credential_proof(),
},
);
)
.unwrap();
W3CCredential::new(issuer_id(), _credential_attributes(), proof, None)
}

fn _w3_presentation() -> W3CPresentation {
let proof = DataIntegrityProof {
type_: DataIntegrityProofType::DataIntegrityProof,
cryptosuite: CryptoSuite::AnonCredsPresVp2023,
proof_value: "proof".to_string(),
proof_value: "bla".to_string(),
challenge: Some("1".to_string()),
};
W3CPresentation::new(vec![_credential()], proof, None)
Expand Down
18 changes: 2 additions & 16 deletions src/utils/base64.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
use base64::{engine, Engine};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;

use crate::Error;

pub fn encode<T: AsRef<[u8]>>(val: T) -> String {
engine::general_purpose::URL_SAFE.encode(val)
}

pub fn encode_json<T: Serialize>(val: T) -> String {
let json = json!(val).to_string();
encode(json)
engine::general_purpose::URL_SAFE_NO_PAD.encode(val)
}

pub fn decode<T: AsRef<[u8]>>(val: T) -> Result<Vec<u8>, Error> {
engine::general_purpose::URL_SAFE
engine::general_purpose::URL_SAFE_NO_PAD
.decode(val)
.map_err(|_| err_msg!("invalid base64 string"))
}

pub fn decode_json<T: AsRef<[u8]>, V: DeserializeOwned>(val: T) -> Result<V, Error> {
let bytes = decode(val)?;
let json = serde_json::from_slice(&bytes)?;
Ok(json)
}
20 changes: 0 additions & 20 deletions src/utils/encoded_object.rs

This file was deleted.

5 changes: 2 additions & 3 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ pub mod base58;
#[cfg(feature = "w3c")]
pub mod base64;

#[cfg(feature = "w3c")]
pub mod encoded_object;

pub mod hash;

pub mod query;

pub mod msg_pack;

#[macro_use]
pub mod macros;
13 changes: 13 additions & 0 deletions src/utils/msg_pack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::Result;

pub fn encode<T: Serialize>(val: T) -> Result<Vec<u8>> {
rmp_serde::to_vec_named(&val)
.map_err(|_| err_msg!("unable to encode message using message pack"))
}

pub fn decode<T: DeserializeOwned>(val: &[u8]) -> Result<T> {
rmp_serde::from_slice(val).map_err(|_| err_msg!("unable to decode message using message pack"))
}