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

Switch usize to i64 in FFI #42

Merged
merged 3 commits into from
Sep 20, 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 indy-credx/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "indy-credx"
version = "1.0.2"
version = "1.0.3"
authors = ["Hyperledger Indy Contributors <[email protected]>"]
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 = "2021"
Expand Down
17 changes: 8 additions & 9 deletions indy-credx/src/ffi/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ pub extern "C" fn credx_create_credential(
"Mismatch between length of attribute names and raw values"
));
}
let enc_values = attr_enc_values.as_slice();
let enc_values = attr_enc_values.as_slice()?;
let mut cred_values = MakeCredentialValues::default();
let mut attr_idx = 0;
for (name, raw) in attr_names
.as_slice()
.into_iter()
.zip(attr_raw_values.as_slice())
for (attr_idx, (name, raw)) in attr_names
.as_slice()?
.iter()
.zip(attr_raw_values.as_slice()?)
.enumerate()
{
let name = name
.as_opt_str()
Expand All @@ -96,12 +96,11 @@ pub extern "C" fn credx_create_credential(
} else {
cred_values.add_raw(name, raw)?;
}
attr_idx += 1;
}
let revocation_config = if !revocation.is_null() {
let revocation = unsafe { &*revocation };
let mut reg_used = HashSet::new();
for reg_idx in revocation.reg_used.as_slice() {
for reg_idx in revocation.reg_used.as_slice()? {
reg_used.insert(
(*reg_idx)
.try_into()
Expand Down Expand Up @@ -157,7 +156,7 @@ pub extern "C" fn credx_encode_credential_attributes(
) -> ErrorCode {
catch_error(|| {
let mut result = String::new();
for raw_val in attr_raw_values.as_slice() {
for raw_val in attr_raw_values.as_slice()? {
let enc_val = encode_credential_attribute(
raw_val
.as_opt_str()
Expand Down
2 changes: 1 addition & 1 deletion indy-credx/src/ffi/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use once_cell::sync::Lazy;
static LAST_ERROR: Lazy<RwLock<Option<Error>>> = Lazy::new(|| RwLock::new(None));

#[derive(Debug, PartialEq, Copy, Clone, Serialize)]
#[repr(usize)]
#[repr(i64)]
pub enum ErrorCode {
Success = 0,
Input = 1,
Expand Down
2 changes: 1 addition & 1 deletion indy-credx/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ ffi_support::define_string_destructor!(credx_string_free);
#[no_mangle]
pub extern "C" fn credx_buffer_free(buffer: ByteBuffer) {
ffi_support::abort_on_panic::with_abort_on_panic(|| {
drop(buffer.destroy_into_vec().zeroize());
buffer.destroy_into_vec().zeroize();
})
}

Expand Down
41 changes: 11 additions & 30 deletions indy-credx/src/ffi/presentation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,26 +76,16 @@ pub extern "C" fn credx_create_presentation(
));
}

let entries = {
let credentials = credentials.as_slice();
credentials.into_iter().try_fold(
Vec::with_capacity(credentials.len()),
|mut r, ffi_entry| {
r.push(ffi_entry.load()?);
Result::Ok(r)
},
)?
};

let schemas = IndyObjectList::load(schemas.as_slice())?;
let cred_defs = IndyObjectList::load(cred_defs.as_slice())?;
let entries = credentials.try_collect(|entry| entry.load())?;
let schemas = IndyObjectList::load(schemas.as_slice()?)?;
let cred_defs = IndyObjectList::load(cred_defs.as_slice()?)?;

let self_attested = if !self_attest_names.is_empty() {
let mut self_attested = HashMap::new();
for (name, raw) in self_attest_names
.as_slice()
.into_iter()
.zip(self_attest_values.as_slice())
.as_slice()?
.iter()
.zip(self_attest_values.as_slice()?)
{
let name = name
.as_opt_str()
Expand Down Expand Up @@ -125,7 +115,7 @@ pub extern "C" fn credx_create_presentation(
.transpose()?,
);

for prove in credentials_prove.as_slice() {
for prove in credentials_prove.as_slice()? {
if prove.entry_idx < 0 {
return Err(err_msg!("Invalid credential index"));
}
Expand Down Expand Up @@ -239,19 +229,10 @@ fn _credx_verify_presentation(
result_p: *mut i8,
) -> ErrorCode {
catch_error(|| {
let schemas = IndyObjectList::load(schemas.as_slice())?;
let cred_defs = IndyObjectList::load(cred_defs.as_slice())?;
let rev_reg_defs = IndyObjectList::load(rev_reg_defs.as_slice())?;
let rev_reg_entries = {
let entries = rev_reg_entries.as_slice();
entries.into_iter().try_fold(
Vec::with_capacity(entries.len()),
|mut r, ffi_entry| {
r.push(ffi_entry.load()?);
Result::Ok(r)
},
)?
};
let schemas = IndyObjectList::load(schemas.as_slice()?)?;
let cred_defs = IndyObjectList::load(cred_defs.as_slice()?)?;
let rev_reg_defs = IndyObjectList::load(rev_reg_defs.as_slice()?)?;
let rev_reg_entries = rev_reg_entries.try_collect(|entry| entry.load())?;
let mut rev_regs = HashMap::new();
for (idx, entry, timestamp) in rev_reg_entries.iter() {
if *idx > rev_reg_defs.len() {
Expand Down
4 changes: 2 additions & 2 deletions indy-credx/src/ffi/revocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ pub extern "C" fn credx_update_revocation_registry(
catch_error(|| {
check_useful_c_ptr!(rev_reg_p);
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 issued = registry_indices_to_set(issued.as_slice()?.iter().cloned())?;
let revoked = registry_indices_to_set(revoked.as_slice()?.iter().cloned())?;
let (rev_reg, rev_reg_delta) = update_revocation_registry(
cred_def.load()?.cast_ref()?,
rev_reg_def.load()?.cast_ref()?,
Expand Down
23 changes: 10 additions & 13 deletions indy-credx/src/ffi/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,26 @@ use crate::error::Result;
#[derive(Debug)]
#[repr(C)]
pub struct FfiList<'a, T> {
count: usize,
count: i64,
data: *const T,
_pd: PhantomData<&'a ()>,
}

impl<'a, T> FfiList<'a, T> {
#[inline]
pub fn as_slice(&self) -> &[T] {
if self.data.is_null() {
&[]
pub fn as_slice(&self) -> Result<&[T]> {
if self.data.is_null() || self.count == 0 {
Ok(&[])
} else if self.count < 0 {
return Err(err_msg!(Input, "Invalid index for result set"));
} else {
unsafe { slice::from_raw_parts(self.data, self.count) }
Ok(unsafe { slice::from_raw_parts(self.data, self.count as usize) })
}
}

#[inline]
pub fn try_collect<R>(&self, mut f: impl FnMut(&T) -> Result<R>) -> Result<Vec<R>> {
self.as_slice()
.into_iter()
.try_fold(Vec::with_capacity(self.len()), |mut rs, v| {
rs.push(f(v)?);
Ok(rs)
})
pub fn try_collect<R>(&self, f: impl FnMut(&T) -> Result<R>) -> Result<Vec<R>> {
self.as_slice()?.iter().map(f).collect()
}

#[inline]
Expand All @@ -39,7 +36,7 @@ impl<'a, T> FfiList<'a, T> {
}

#[inline]
pub fn len(&self) -> usize {
pub fn len(&self) -> i64 {
if self.data.is_null() {
0
} else {
Expand Down
8 changes: 4 additions & 4 deletions indy-credx/src/services/tails.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::cell::{RefCell, RefMut};
use std::fmt::Debug;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::io::{self, BufReader, BufWriter, Read, Seek, Write};
use std::path::{Path, PathBuf};

use indy_utils::base58;
Expand Down Expand Up @@ -135,17 +135,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
2 changes: 1 addition & 1 deletion indy-credx/src/services/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,7 @@ fn verify_requested_restrictions(
if pred_sub_proof_index == attr_sub_proof_index {
for name in attr_info.values.keys() {
let raw_val = attr_info.values.get(name).unwrap().raw.as_str();
attr_value_map.insert(name.clone(), Some(raw_val.clone()));
attr_value_map.insert(name.clone(), Some(raw_val));
}
}
}
Expand Down
11 changes: 6 additions & 5 deletions wrappers/python/indy_credx/bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
c_char_p,
c_int8,
c_int64,
c_size_t,
c_ubyte,
pointer,
)
Expand Down Expand Up @@ -230,7 +229,7 @@ def _cleanup(cls, buffer: c_char_p):

class FfiObjectHandleList(Structure):
_fields_ = [
("count", c_size_t),
("count", c_int64),
("data", POINTER(ObjectHandle)),
]

Expand All @@ -246,7 +245,7 @@ def create(cls, values: Optional[Sequence[ObjectHandle]]) -> "FfiObjectHandleLis

class FfiIntList(Structure):
_fields_ = [
("count", c_size_t),
("count", c_int64),
("data", POINTER(c_int64)),
]

Expand All @@ -262,7 +261,7 @@ def create(cls, values: Optional[Sequence[str]]) -> "FfiIntList":

class FfiStrList(Structure):
_fields_ = [
("count", c_size_t),
("count", c_int64),
("data", POINTER(c_char_p)),
]

Expand Down Expand Up @@ -796,7 +795,9 @@ def verify_presentation(
entry_list.count = len(rev_regs)
entry_list.data = (RevocationEntry * entry_list.count)(*rev_regs)
do_call(
"credx_verify_presentation_legacy" if accept_legacy_revocation else "credx_verify_presentation",
"credx_verify_presentation_legacy"
if accept_legacy_revocation
else "credx_verify_presentation",
presentation,
pres_req,
FfiObjectHandleList.create(schemas),
Expand Down
2 changes: 1 addition & 1 deletion wrappers/python/indy_credx/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""indy_credx library wrapper version."""

__version__ = "1.0.2"
__version__ = "1.0.3"