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

Hashmap uniformization #232

Merged
merged 7 commits into from
Aug 25, 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 .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: 'Anoncreds'

env:
RUST_VERSION: '1.64.0'
RUST_VERSION: '1.65.0'
CROSS_VERSION: '0.2.4'

on:
Expand Down
15 changes: 15 additions & 0 deletions src/data_types/cred_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ impl CredentialDefinition {
.map_err(|e| e.to_string())?;
Ok(key)
}

pub fn try_clone(&self) -> Result<Self, crate::Error> {
let cred_data = CredentialDefinitionData {
primary: self.value.primary.try_clone()?,
revocation: self.value.revocation.clone(),
};

Ok(Self {
schema_id: self.schema_id.clone(),
signature_type: self.signature_type,
tag: self.tag.clone(),
value: cred_data,
issuer_id: self.issuer_id.clone(),
})
}
}

impl Validatable for CredentialDefinition {
Expand Down
35 changes: 28 additions & 7 deletions src/ffi/presentation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,18 @@ pub extern "C" fn anoncreds_create_presentation(
}

let schemas = AnoncredsObjectList::load(schemas.as_slice())?;
let schemas = schemas.refs_map::<SchemaId, Schema>(&schema_identifiers)?;
let schemas = schemas
.refs_map::<SchemaId, Schema>(&schema_identifiers)?
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();

let cred_defs = AnoncredsObjectList::load(cred_defs.as_slice())?;
let cred_defs = cred_defs
.refs_map::<CredentialDefinitionId, CredentialDefinition>(&cred_def_identifiers)?;
.refs_map::<CredentialDefinitionId, CredentialDefinition>(&cred_def_identifiers)?
.into_iter()
.map(|(k, v)| v.try_clone().map(|v| (k.clone(), v)))
.collect::<Result<_>>()?;

let presentation = create_presentation(
pres_req.load()?.cast_ref()?,
Expand Down Expand Up @@ -292,17 +299,27 @@ pub extern "C" fn anoncreds_verify_presentation(
}

let schemas = AnoncredsObjectList::load(schemas.as_slice())?;
let schemas = schemas.refs_map::<SchemaId, Schema>(&schema_identifiers)?;
let schemas = schemas
.refs_map::<SchemaId, Schema>(&schema_identifiers)?
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();

let cred_defs = AnoncredsObjectList::load(cred_defs.as_slice())?;
let cred_defs = cred_defs
.refs_map::<CredentialDefinitionId, CredentialDefinition>(&cred_def_identifiers)?;
.refs_map::<CredentialDefinitionId, CredentialDefinition>(&cred_def_identifiers)?
.into_iter()
.map(|(k, v)| v.try_clone().map(|v| (k.clone(), v)))
.collect::<Result<_>>()?;

let rev_reg_defs = AnoncredsObjectList::load(rev_reg_defs.as_slice())?;
let rev_reg_defs = rev_reg_defs
.refs_map::<RevocationRegistryDefinitionId, RevocationRegistryDefinition>(
&rev_reg_def_identifiers,
)?;
)?
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<HashMap<_, _>>();

let rev_reg_defs = if rev_reg_defs.is_empty() {
None
Expand All @@ -328,18 +345,22 @@ pub extern "C" fn anoncreds_verify_presentation(
let mut map_nonrevoked_interval_override = HashMap::new();
for (id, req_timestamp, override_timestamp) in &override_entries {
map_nonrevoked_interval_override
.entry(id)
.entry(id.clone())
.or_insert_with(HashMap::new)
.insert(*req_timestamp, *override_timestamp);
}

let rev_status_lists = rev_status_list
.as_ref()
.map(|v| v.iter().copied().cloned().collect());

let verify = verify_presentation(
presentation.load()?.cast_ref()?,
pres_req.load()?.cast_ref()?,
&schemas,
&cred_defs,
rev_reg_defs,
rev_status_list,
rev_status_lists,
Some(&map_nonrevoked_interval_override),
)?;
unsafe { *result_p = i8::from(verify) };
Expand Down
14 changes: 7 additions & 7 deletions src/services/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,11 @@ pub fn process_credential(
///
/// let mut schemas = HashMap::new();
/// let schema_id = SchemaId::new_unchecked("did:web:xyz/resource/schema");
/// schemas.insert(&schema_id, &schema);
/// schemas.insert(schema_id, schema);
///
/// let mut cred_defs = HashMap::new();
/// let cred_def_id = CredentialDefinitionId::new_unchecked("did:web:xyz/resource/cred-def");
/// cred_defs.insert(&cred_def_id, &cred_def);
/// cred_defs.insert(cred_def_id, cred_def);
///
/// let mut present = PresentCredentials::default();
/// let mut cred1 = present.add_credential(
Expand All @@ -403,8 +403,8 @@ pub fn create_presentation(
credentials: PresentCredentials,
self_attested: Option<HashMap<String, String>>,
link_secret: &LinkSecret,
schemas: &HashMap<&SchemaId, &Schema>,
cred_defs: &HashMap<&CredentialDefinitionId, &CredentialDefinition>,
schemas: &HashMap<SchemaId, Schema>,
cred_defs: &HashMap<CredentialDefinitionId, CredentialDefinition>,
) -> Result<Presentation> {
trace!("create_proof >>> credentials: {:?}, pres_req: {:?}, credentials: {:?}, self_attested: {:?}, link_secret: {:?}, schemas: {:?}, cred_defs: {:?}",
credentials, pres_req, credentials, &self_attested, secret!(&link_secret), schemas, cred_defs);
Expand Down Expand Up @@ -436,12 +436,12 @@ pub fn create_presentation(
}
let credential = present.cred;

let schema = *schemas
let schema = schemas
.get(&credential.schema_id)
.ok_or_else(|| err_msg!("Schema not provided for ID: {}", credential.schema_id))?;

let cred_def_id = CredentialDefinitionId::new(credential.cred_def_id.clone())?;
let cred_def = *cred_defs.get(&cred_def_id).ok_or_else(|| {
let cred_def = cred_defs.get(&cred_def_id).ok_or_else(|| {
err_msg!(
"Credential Definition not provided for ID: {}",
credential.cred_def_id
Expand Down Expand Up @@ -665,7 +665,7 @@ pub fn create_or_update_revocation_state(

let mut issued = HashSet::<u32>::new();
let mut revoked = HashSet::<u32>::new();
let tails_reader = TailsFileReader::new(tails_path);
let tails_reader = TailsFileReader::new(tails_path)?;
let witness = if let (Some(source_rev_state), Some(source_rev_list)) =
(rev_state, old_rev_status_list)
{
Expand Down
111 changes: 29 additions & 82 deletions src/services/tails.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::cell::RefCell;
use std::fmt::Debug;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use rand::random;
Expand All @@ -13,29 +13,42 @@ use crate::cl::{
};
use crate::error::Error;
use crate::utils::base58;
use crate::ErrorKind;

const TAILS_BLOB_TAG_SZ: u8 = 2;
const TAIL_SIZE: usize = Tail::BYTES_REPR_SIZE;

#[derive(Debug)]
pub struct TailsReader {
inner: Box<RefCell<dyn TailsReaderImpl>>,
pub struct TailsFileReader {
file: RefCell<BufReader<File>>,
}

impl TailsReader {
pub(crate) fn new<TR: TailsReaderImpl + 'static>(inner: TR) -> Self {
Self {
inner: Box::new(RefCell::new(inner)),
}
impl TailsFileReader {
pub fn new<P>(path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let file = RefCell::new(BufReader::new(File::open(path)?));
let reader = Self { file };
Ok(reader)
}
}

pub trait TailsReaderImpl: Debug + Send {
fn hash(&mut self) -> Result<Vec<u8>, Error>;
fn read(&mut self, size: usize, offset: usize) -> Result<Vec<u8>, Error>;
fn read(&self, size: usize, offset: usize) -> Result<Vec<u8>, Error> {
let mut buf = vec![0u8; size];

let mut file = self
.file
.try_borrow_mut()
.map_err(|err| Error::from(ErrorKind::IOError).with_cause(err))?;

file.seek(SeekFrom::Start(offset as u64))?;
file.read_exact(buf.as_mut_slice())?;

Ok(buf)
}
}

impl RevocationTailsAccessor for TailsReader {
impl RevocationTailsAccessor for TailsFileReader {
fn access_tail(
&self,
tail_id: u32,
Expand All @@ -44,8 +57,6 @@ impl RevocationTailsAccessor for TailsReader {
trace!("access_tail >>> tail_id: {:?}", tail_id);

let tail_bytes = self
.inner
.borrow_mut()
.read(
TAIL_SIZE,
TAIL_SIZE * tail_id as usize + TAILS_BLOB_TAG_SZ as usize,
Expand All @@ -63,70 +74,6 @@ impl RevocationTailsAccessor for TailsReader {
}
}

#[derive(Debug)]
pub struct TailsFileReader {
path: String,
file: Option<BufReader<File>>,
hash: Option<Vec<u8>>,
}

impl TailsFileReader {
pub fn new(path: &str) -> TailsReader {
TailsReader::new(Self {
path: path.to_owned(),
file: None,
hash: None,
})
}

pub fn open(&mut self) -> Result<&mut BufReader<File>, Error> {
if self.file.is_none() {
let file = File::open(self.path.clone())?;
self.file.replace(BufReader::new(file));
}
Ok(self.file.as_mut().unwrap())
}

pub fn close(&mut self) {
self.file.take();
}
}

impl TailsReaderImpl for TailsFileReader {
fn hash(&mut self) -> Result<Vec<u8>, Error> {
if let Some(hash) = self.hash.as_ref() {
return Ok(hash.clone());
}

let file = self.open()?;
file.seek(SeekFrom::Start(0))?;
let mut hasher = Sha256::default();

loop {
let buf = file.fill_buf()?;
let len = buf.len();
if len == 0 {
break;
}
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<Vec<u8>, Error> {
let mut buf = vec![0u8; size];

let file = self.open()?;
file.seek(SeekFrom::Start(offset as u64))?;
file.read_exact(buf.as_mut_slice())?;

Ok(buf)
}
}

pub trait TailsWriter: std::fmt::Debug {
fn write(
&mut self,
Expand Down Expand Up @@ -182,17 +129,17 @@ impl TailsWriter for TailsFileWriter {
let mut buf = BufWriter::new(file);
let mut hasher = Sha256::default();
let version = &[0u8, 2u8];
buf.write(version)?;
buf.write_all(version)?;
hasher.update(version);
while let Some(tail) = generator.try_next()? {
let tail_bytes = tail.to_bytes()?;
buf.write(&tail_bytes)?;
buf.write_all(&tail_bytes)?;
hasher.update(&tail_bytes);
}
let mut file = buf
.into_inner()
.map_err(|e| err_msg!("Error flushing output file: {e}"))?;
let tails_size = file.seek(SeekFrom::Current(0))?;
let tails_size = file.stream_position()?;
let hash = base58::encode(hasher.finalize());
let target_path = self.root_path.join(&hash);
drop(file);
Expand Down
23 changes: 11 additions & 12 deletions src/services/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ static INTERNAL_TAG_MATCHER: Lazy<Regex> =
pub fn verify_presentation(
presentation: &Presentation,
pres_req: &PresentationRequest,
schemas: &HashMap<&SchemaId, &Schema>,
cred_defs: &HashMap<&CredentialDefinitionId, &CredentialDefinition>,
rev_reg_defs: Option<&HashMap<&RevocationRegistryDefinitionId, &RevocationRegistryDefinition>>,
rev_status_lists: Option<Vec<&RevocationStatusList>>,
schemas: &HashMap<SchemaId, Schema>,
cred_defs: &HashMap<CredentialDefinitionId, CredentialDefinition>,
rev_reg_defs: Option<&HashMap<RevocationRegistryDefinitionId, RevocationRegistryDefinition>>,
rev_status_lists: Option<Vec<RevocationStatusList>>,
nonrevoke_interval_override: Option<
&HashMap<&RevocationRegistryDefinitionId, HashMap<u64, u64>>,
&HashMap<RevocationRegistryDefinitionId, HashMap<u64, u64>>,
>,
) -> Result<bool> {
trace!("verify >>> presentation: {:?}, pres_req: {:?}, schemas: {:?}, cred_defs: {:?}, rev_reg_defs: {:?} rev_status_lists: {:?}",
Expand Down Expand Up @@ -109,7 +109,7 @@ pub fn verify_presentation(
)
})?;

let rev_reg_map = if let Some(ref lists) = rev_status_lists {
let rev_reg_map = if let Some(lists) = rev_status_lists.clone() {
let mut map: HashMap<RevocationRegistryDefinitionId, HashMap<u64, RevocationRegistry>> =
HashMap::new();

Expand All @@ -122,7 +122,7 @@ pub fn verify_presentation(
.timestamp()
.ok_or_else(|| err_msg!(Unexpected, "RevStatusList missing timestamp"))?;

let rev_reg: Option<RevocationRegistry> = (*list).into();
let rev_reg: Option<RevocationRegistry> = (&list).into();
let rev_reg = rev_reg.ok_or_else(|| {
err_msg!(Unexpected, "Revocation status list missing accumulator")
})?;
Expand Down Expand Up @@ -217,7 +217,6 @@ pub fn verify_presentation(

let rev_reg_def = Some(
rev_reg_defs
.as_ref()
.ok_or_else(|| err_msg!("Could not load the Revocation Registry Definition"))?
.get(&rev_reg_def_id)
.ok_or_else(|| {
Expand Down Expand Up @@ -496,8 +495,8 @@ fn verify_revealed_attribute_value(
#[allow(clippy::too_many_arguments)]
fn verify_requested_restrictions(
pres_req: &PresentationRequestPayload,
schemas: &HashMap<&SchemaId, &Schema>,
cred_defs: &HashMap<&CredentialDefinitionId, &CredentialDefinition>,
schemas: &HashMap<SchemaId, Schema>,
cred_defs: &HashMap<CredentialDefinitionId, CredentialDefinition>,
requested_proof: &RequestedProof,
received_revealed_attrs: &HashMap<String, Identifier>,
received_unrevealed_attrs: &HashMap<String, Identifier>,
Expand Down Expand Up @@ -664,8 +663,8 @@ fn is_self_attested(
fn gather_filter_info(
referent: &str,
identifiers: &HashMap<String, Identifier>,
schemas: &HashMap<&SchemaId, &Schema>,
cred_defs: &HashMap<&CredentialDefinitionId, &CredentialDefinition>,
schemas: &HashMap<SchemaId, Schema>,
cred_defs: &HashMap<CredentialDefinitionId, CredentialDefinition>,
) -> Result<Filter> {
let identifier = identifiers.get(referent).ok_or_else(|| {
err_msg!(
Expand Down
Loading
Loading