From c202b653d84ad57819353cf6c56f1616ffa35320 Mon Sep 17 00:00:00 2001 From: Bogdan Mircea Date: Tue, 26 Sep 2023 13:23:16 +0300 Subject: [PATCH 1/4] Removed obsolete rustfmt.toml files Signed-off-by: Bogdan Mircea --- did_doc/rustfmt.toml | 2 -- did_parser/rustfmt.toml | 2 -- did_resolver/rustfmt.toml | 2 -- did_resolver_registry/rustfmt.toml | 2 -- did_resolver_sov/rustfmt.toml | 2 -- libvdrtools/rustfmt.toml | 1 - 6 files changed, 11 deletions(-) delete mode 100644 did_doc/rustfmt.toml delete mode 100644 did_parser/rustfmt.toml delete mode 100644 did_resolver/rustfmt.toml delete mode 100644 did_resolver_registry/rustfmt.toml delete mode 100644 did_resolver_sov/rustfmt.toml delete mode 100644 libvdrtools/rustfmt.toml diff --git a/did_doc/rustfmt.toml b/did_doc/rustfmt.toml deleted file mode 100644 index b3a03b77b3..0000000000 --- a/did_doc/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -edition = "2021" -max_width=100 diff --git a/did_parser/rustfmt.toml b/did_parser/rustfmt.toml deleted file mode 100644 index b3a03b77b3..0000000000 --- a/did_parser/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -edition = "2021" -max_width=100 diff --git a/did_resolver/rustfmt.toml b/did_resolver/rustfmt.toml deleted file mode 100644 index b3a03b77b3..0000000000 --- a/did_resolver/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -edition = "2021" -max_width=100 diff --git a/did_resolver_registry/rustfmt.toml b/did_resolver_registry/rustfmt.toml deleted file mode 100644 index b3a03b77b3..0000000000 --- a/did_resolver_registry/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -edition = "2021" -max_width=100 diff --git a/did_resolver_sov/rustfmt.toml b/did_resolver_sov/rustfmt.toml deleted file mode 100644 index b3a03b77b3..0000000000 --- a/did_resolver_sov/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -edition = "2021" -max_width=100 diff --git a/libvdrtools/rustfmt.toml b/libvdrtools/rustfmt.toml deleted file mode 100644 index d9ba5fdb90..0000000000 --- a/libvdrtools/rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -imports_granularity = "Crate" \ No newline at end of file From fb63a58a07286f11be3aff7951d24ba018434ac6 Mon Sep 17 00:00:00 2001 From: Bogdan Mircea Date: Tue, 26 Sep 2023 13:34:52 +0300 Subject: [PATCH 2/4] Ran cargo fmt Signed-off-by: Bogdan Mircea --- did_doc/src/schema/did_doc.rs | 3 +- did_doc/src/schema/service.rs | 3 +- did_doc/src/schema/verification_method/mod.rs | 14 +- did_parser/src/did.rs | 11 +- did_parser/src/utils/parse.rs | 3 +- did_parser/tests/did_url/positive.rs | 3 +- .../dereferenceable/dereferencing_output.rs | 2 +- .../src/traits/dereferenceable/mod.rs | 2 +- did_resolver/src/traits/resolvable/mod.rs | 2 +- did_resolver_registry/src/lib.rs | 6 +- .../src/dereferencing/dereferencer.rs | 3 +- did_resolver_sov/src/dereferencing/utils.rs | 15 +- did_resolver_sov/src/resolution/resolver.rs | 3 +- did_resolver_sov/src/resolution/utils.rs | 3 +- did_resolver_sov/src/service.rs | 9 +- did_resolver_sov/tests/resolution.rs | 15 +- .../indy-api-types/src/domain/wallet/mod.rs | 3 +- libvdrtools/indy-api-types/src/errors.rs | 14 +- libvdrtools/indy-api-types/src/lib.rs | 7 +- .../crypto/chacha20poly1305_ietf/sodium.rs | 12 +- .../src/crypto/ed25519_box/sodium.rs | 3 +- .../src/crypto/ed25519_sign/sodium.rs | 1 - .../indy-utils/src/crypto/hash/openssl.rs | 6 +- .../src/crypto/pwhash_argon2i13/sodium.rs | 6 +- .../indy-utils/src/crypto/sealedbox/sodium.rs | 3 +- .../indy-utils/src/crypto/xsalsa20/sodium.rs | 3 +- libvdrtools/indy-utils/src/test.rs | 13 +- libvdrtools/indy-utils/src/wql.rs | 3 +- libvdrtools/indy-wallet/src/cache/lru.rs | 3 +- .../indy-wallet/src/cache/wallet_cache.rs | 20 +- libvdrtools/indy-wallet/src/encryption.rs | 21 +- libvdrtools/indy-wallet/src/export_import.rs | 14 +- libvdrtools/indy-wallet/src/lib.rs | 6 +- .../indy-wallet/src/query_encryption.rs | 2 +- .../indy-wallet/src/storage/default/mod.rs | 17 +- .../indy-wallet/src/storage/mysql/mod.rs | 9 +- libvdrtools/indy-wallet/src/wallet.rs | 7 +- .../src/controllers/anoncreds/issuer.rs | 265 ++++++++------- .../src/controllers/anoncreds/prover.rs | 309 +++++++++--------- .../src/controllers/anoncreds/tails.rs | 4 +- .../src/controllers/anoncreds/verifier.rs | 48 +-- libvdrtools/src/controllers/config.rs | 8 +- libvdrtools/src/controllers/crypto.rs | 40 +-- libvdrtools/src/controllers/did.rs | 49 +-- libvdrtools/src/controllers/mod.rs | 1 - libvdrtools/src/controllers/non_secrets.rs | 21 +- libvdrtools/src/controllers/pairwise.rs | 3 +- libvdrtools/src/controllers/wallet.rs | 164 +++++----- .../src/domain/anoncreds/credential.rs | 8 +- .../domain/anoncreds/credential_definition.rs | 25 +- .../src/domain/anoncreds/credential_offer.rs | 3 +- .../domain/anoncreds/credential_request.rs | 6 +- .../src/domain/anoncreds/indy_identifiers.rs | 34 +- .../src/domain/anoncreds/master_secret.rs | 3 +- libvdrtools/src/domain/anoncreds/proof.rs | 2 +- .../src/domain/anoncreds/proof_request.rs | 33 +- .../domain/anoncreds/requested_credential.rs | 5 +- .../domain/anoncreds/revocation_registry.rs | 3 +- .../revocation_registry_definition.rs | 37 ++- .../src/domain/anoncreds/revocation_state.rs | 2 +- libvdrtools/src/domain/anoncreds/schema.rs | 9 +- libvdrtools/src/domain/cache.rs | 3 +- libvdrtools/src/domain/crypto/did.rs | 17 +- libvdrtools/src/domain/ledger/auth_rule.rs | 3 +- libvdrtools/src/domain/ledger/node.rs | 10 +- libvdrtools/src/domain/ledger/pool.rs | 4 +- libvdrtools/src/domain/ledger/request.rs | 7 +- libvdrtools/src/domain/ledger/rev_reg.rs | 5 +- libvdrtools/src/domain/ledger/schema.rs | 4 +- libvdrtools/src/lib.rs | 30 +- libvdrtools/src/services/anoncreds/helpers.rs | 12 +- libvdrtools/src/services/anoncreds/issuer.rs | 12 +- libvdrtools/src/services/anoncreds/prover.rs | 35 +- .../src/services/anoncreds/verifier.rs | 73 ++++- .../services/blob_storage/default_reader.rs | 2 +- .../services/blob_storage/default_writer.rs | 4 +- libvdrtools/src/services/blob_storage/mod.rs | 1 - libvdrtools/src/services/crypto/ed25519.rs | 3 +- libvdrtools/src/services/crypto/mod.rs | 51 ++- libvdrtools/src/services/mod.rs | 1 - .../src/utils/crypto/signature_serializer.rs | 17 +- .../src/utils/crypto/verkey_builder.rs | 3 +- libvdrtools/src/utils/mod.rs | 1 - libvdrtools/src/utils/qualifier.rs | 5 +- 84 files changed, 891 insertions(+), 764 deletions(-) diff --git a/did_doc/src/schema/did_doc.rs b/did_doc/src/schema/did_doc.rs index 7601ed6dcb..72dd642a09 100644 --- a/did_doc/src/schema/did_doc.rs +++ b/did_doc/src/schema/did_doc.rs @@ -4,14 +4,13 @@ use did_parser::{Did, DidUrl}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::error::DidDocumentBuilderError; - use super::{ service::Service, types::uri::Uri, utils::OneOrList, verification_method::{VerificationMethod, VerificationMethodKind}, }; +use crate::error::DidDocumentBuilderError; pub type ControllerAlias = OneOrList; diff --git a/did_doc/src/schema/service.rs b/did_doc/src/schema/service.rs index d067882c08..5b0db23b7f 100644 --- a/did_doc/src/schema/service.rs +++ b/did_doc/src/schema/service.rs @@ -2,12 +2,11 @@ use std::collections::HashSet; use serde::{Deserialize, Serialize}; -use crate::error::DidDocumentBuilderError; - use super::{ types::{uri::Uri, url::Url}, utils::OneOrList, }; +use crate::error::DidDocumentBuilderError; pub type ServiceTypeAlias = OneOrList; diff --git a/did_doc/src/schema/verification_method/mod.rs b/did_doc/src/schema/verification_method/mod.rs index 3f2a00eda7..b4fcd62c16 100644 --- a/did_doc/src/schema/verification_method/mod.rs +++ b/did_doc/src/schema/verification_method/mod.rs @@ -2,15 +2,13 @@ mod public_key; mod verification_method_kind; mod verification_method_type; -pub use self::public_key::PublicKeyField; - use ::public_key::Key; -pub use verification_method_kind::VerificationMethodKind; -pub use verification_method_type::VerificationMethodType; - use did_parser::{Did, DidUrl}; use serde::{Deserialize, Serialize}; +pub use verification_method_kind::VerificationMethodKind; +pub use verification_method_type::VerificationMethodType; +pub use self::public_key::PublicKeyField; use crate::{error::DidDocumentBuilderError, schema::types::jsonwebkey::JsonWebKey}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] @@ -160,16 +158,18 @@ impl CompleteVerificationMethodBuilder { id: self.id, controller: self.controller, verification_method_type: self.verification_method_type, - public_key: self.public_key.unwrap(), // SAFETY: The builder will always set the public key + public_key: self.public_key.unwrap(), /* SAFETY: The builder will always set the + * public key */ } } } #[cfg(test)] mod tests { - use super::*; use serde_json::Value; + use super::*; + fn create_valid_did() -> Did { Did::parse("did:example:123456789abcdefghi".to_string()).unwrap() } diff --git a/did_parser/src/did.rs b/did_parser/src/did.rs index ac478e232b..5884bed718 100644 --- a/did_parser/src/did.rs +++ b/did_parser/src/did.rs @@ -1,11 +1,12 @@ -use std::convert::TryFrom; -use std::fmt::{Display, Formatter}; -use std::str::FromStr; +use std::{ + convert::TryFrom, + fmt::{Display, Formatter}, + str::FromStr, +}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::DidUrl; -use crate::{error::ParseError, utils::parse::parse_did_method_id, DidRange}; +use crate::{error::ParseError, utils::parse::parse_did_method_id, DidRange, DidUrl}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Did { diff --git a/did_parser/src/utils/parse.rs b/did_parser/src/utils/parse.rs index 2a21565ad1..00a45cbb26 100644 --- a/did_parser/src/utils/parse.rs +++ b/did_parser/src/utils/parse.rs @@ -1,5 +1,4 @@ -use crate::error::ParseError; -use crate::DidRange; +use crate::{error::ParseError, DidRange}; pub(crate) fn parse_key_value( did_url: &str, diff --git a/did_parser/tests/did_url/positive.rs b/did_parser/tests/did_url/positive.rs index 3802a06272..5fde90ec2a 100644 --- a/did_parser/tests/did_url/positive.rs +++ b/did_parser/tests/did_url/positive.rs @@ -1,6 +1,7 @@ -use did_parser::DidUrl; use std::collections::HashMap; +use did_parser::DidUrl; + macro_rules! test_cases_positive { ($($name:ident: $input:expr, $expected_did:expr, $expected_method:expr, $expected_id:expr, $expected_path:expr, $expected_fragment:expr, $expected_queries:expr, $expected_params:expr)*) => { $( diff --git a/did_resolver/src/traits/dereferenceable/dereferencing_output.rs b/did_resolver/src/traits/dereferenceable/dereferencing_output.rs index 1e75953c54..0be19e468d 100644 --- a/did_resolver/src/traits/dereferenceable/dereferencing_output.rs +++ b/did_resolver/src/traits/dereferenceable/dereferencing_output.rs @@ -1,7 +1,7 @@ -use crate::shared_types::did_document_metadata::DidDocumentMetadata; use std::io::Read; use super::dereferencing_metadata::DidDereferencingMetadata; +use crate::shared_types::did_document_metadata::DidDocumentMetadata; pub struct DidDereferencingOutput { dereferencing_metadata: DidDereferencingMetadata, diff --git a/did_resolver/src/traits/dereferenceable/mod.rs b/did_resolver/src/traits/dereferenceable/mod.rs index d9bb38f579..22b30580a0 100644 --- a/did_resolver/src/traits/dereferenceable/mod.rs +++ b/did_resolver/src/traits/dereferenceable/mod.rs @@ -5,13 +5,13 @@ pub mod dereferencing_output; use std::io::Read; -use crate::{error::GenericError, traits::resolvable::DidResolvable}; use async_trait::async_trait; use did_parser::DidUrl; use self::{ dereferencing_options::DidDereferencingOptions, dereferencing_output::DidDereferencingOutput, }; +use crate::{error::GenericError, traits::resolvable::DidResolvable}; #[async_trait] pub trait DidDereferenceable: DidResolvable { diff --git a/did_resolver/src/traits/resolvable/mod.rs b/did_resolver/src/traits/resolvable/mod.rs index 447c299c97..fce98a0676 100644 --- a/did_resolver/src/traits/resolvable/mod.rs +++ b/did_resolver/src/traits/resolvable/mod.rs @@ -3,11 +3,11 @@ pub mod resolution_metadata; pub mod resolution_options; pub mod resolution_output; -use crate::error::GenericError; use async_trait::async_trait; use did_parser::Did; use self::{resolution_options::DidResolutionOptions, resolution_output::DidResolutionOutput}; +use crate::error::GenericError; #[async_trait] pub trait DidResolvable { diff --git a/did_resolver_registry/src/lib.rs b/did_resolver_registry/src/lib.rs index c88b04ca12..8de6818b72 100644 --- a/did_resolver_registry/src/lib.rs +++ b/did_resolver_registry/src/lib.rs @@ -115,11 +115,13 @@ impl ResolverRegistry { #[cfg(test)] mod tests { - use super::*; + use std::{error::Error, pin::Pin}; + use async_trait::async_trait; use did_resolver::did_doc::schema::did_doc::DidDocumentBuilder; use mockall::{automock, predicate::eq}; - use std::{error::Error, pin::Pin}; + + use super::*; struct DummyDidResolver; diff --git a/did_resolver_sov/src/dereferencing/dereferencer.rs b/did_resolver_sov/src/dereferencing/dereferencer.rs index 284d240126..a2852d3142 100644 --- a/did_resolver_sov/src/dereferencing/dereferencer.rs +++ b/did_resolver_sov/src/dereferencing/dereferencer.rs @@ -13,9 +13,8 @@ use did_resolver::{ }, }; -use crate::resolution::DidSovResolver; - use super::utils::dereference_did_document; +use crate::resolution::DidSovResolver; #[async_trait] impl DidDereferenceable for DidSovResolver { diff --git a/did_resolver_sov/src/dereferencing/utils.rs b/did_resolver_sov/src/dereferencing/utils.rs index c41e8347e6..8a3194f1c4 100644 --- a/did_resolver_sov/src/dereferencing/utils.rs +++ b/did_resolver_sov/src/dereferencing/utils.rs @@ -91,14 +91,17 @@ pub(crate) fn dereference_did_document( #[cfg(test)] mod tests { - use super::*; - - use did_resolver::did_doc::schema::did_doc::DidDocumentBuilder; - use did_resolver::did_doc::schema::verification_method::VerificationMethodType; - use did_resolver::did_parser::DidUrl; - use did_resolver::traits::resolvable::resolution_output::DidResolutionOutput; + use did_resolver::{ + did_doc::schema::{ + did_doc::DidDocumentBuilder, verification_method::VerificationMethodType, + }, + did_parser::DidUrl, + traits::resolvable::resolution_output::DidResolutionOutput, + }; use serde_json::Value; + use super::*; + fn example_did_document_builder() -> DidDocumentBuilder<()> { let verification_method = VerificationMethod::builder( DidUrl::parse("did:example:123456789abcdefghi#keys-1".to_string()).unwrap(), diff --git a/did_resolver_sov/src/resolution/resolver.rs b/did_resolver_sov/src/resolution/resolver.rs index b220012fc0..4b32a9c488 100644 --- a/did_resolver_sov/src/resolution/resolver.rs +++ b/did_resolver_sov/src/resolution/resolver.rs @@ -13,13 +13,12 @@ use did_resolver::{ }; use serde_json::Value; +use super::utils::{is_valid_sovrin_did_id, ledger_response_to_ddo}; use crate::{ error::{parsing::ParsingErrorSource, DidSovError}, reader::AttrReader, }; -use super::utils::{is_valid_sovrin_did_id, ledger_response_to_ddo}; - pub struct DidSovResolver { ledger: Arc, } diff --git a/did_resolver_sov/src/resolution/utils.rs b/did_resolver_sov/src/resolution/utils.rs index 95c49b513d..0bc1ec212c 100644 --- a/did_resolver_sov/src/resolution/utils.rs +++ b/did_resolver_sov/src/resolution/utils.rs @@ -124,10 +124,11 @@ pub(super) async fn ledger_response_to_ddo( #[cfg(test)] mod tests { - use super::*; use chrono::TimeZone; use did_resolver::did_doc::schema::verification_method::PublicKeyField; + use super::*; + #[test] fn test_prepare_ids() { let did = "did:example:1234567890".to_string(); diff --git a/did_resolver_sov/src/service.rs b/did_resolver_sov/src/service.rs index 57a49abe1b..3242bd1c63 100644 --- a/did_resolver_sov/src/service.rs +++ b/did_resolver_sov/src/service.rs @@ -1,5 +1,4 @@ -use std::collections::HashSet; -use std::fmt::Display; +use std::{collections::HashSet, fmt::Display}; use serde::{Deserialize, Deserializer}; use url::Url; @@ -66,10 +65,12 @@ where #[cfg(test)] mod tests { - use super::*; - use serde_json::from_str; use std::iter::FromIterator; + use serde_json::from_str; + + use super::*; + #[test] fn test_deserialize_endpoint_did_sov() { let json = r#"{ diff --git a/did_resolver_sov/tests/resolution.rs b/did_resolver_sov/tests/resolution.rs index 76e3836869..ecc7264f16 100644 --- a/did_resolver_sov/tests/resolution.rs +++ b/did_resolver_sov/tests/resolution.rs @@ -1,19 +1,18 @@ -use std::sync::Arc; -use std::thread; -use std::time::Duration; +use std::{sync::Arc, thread, time::Duration}; -use aries_vcx::core::profile::profile::Profile; use aries_vcx::{ common::ledger::{ service_didsov::{DidSovServiceType, EndpointDidSov}, transactions::write_endpoint, }, + core::profile::profile::Profile, utils::devsetup::SetupProfile, }; -use did_resolver::did_parser::Did; -use did_resolver::traits::resolvable::{resolution_options::DidResolutionOptions, DidResolvable}; -use did_resolver_sov::reader::ConcreteAttrReader; -use did_resolver_sov::resolution::DidSovResolver; +use did_resolver::{ + did_parser::Did, + traits::resolvable::{resolution_options::DidResolutionOptions, DidResolvable}, +}; +use did_resolver_sov::{reader::ConcreteAttrReader, resolution::DidSovResolver}; async fn write_test_endpoint(profile: &Arc, did: &str) { let endpoint = EndpointDidSov::create() diff --git a/libvdrtools/indy-api-types/src/domain/wallet/mod.rs b/libvdrtools/indy-api-types/src/domain/wallet/mod.rs index fbfbb7e35f..4ccd271156 100644 --- a/libvdrtools/indy-api-types/src/domain/wallet/mod.rs +++ b/libvdrtools/indy-api-types/src/domain/wallet/mod.rs @@ -1,6 +1,7 @@ -use serde_json::value::Value; use std::collections::HashMap; +use serde_json::value::Value; + use crate::validation::Validatable; #[derive(Debug, Serialize, Deserialize, Clone, Default)] diff --git a/libvdrtools/indy-api-types/src/errors.rs b/libvdrtools/indy-api-types/src/errors.rs index a4f867aee2..f1a132e0dd 100644 --- a/libvdrtools/indy-api-types/src/errors.rs +++ b/libvdrtools/indy-api-types/src/errors.rs @@ -1,23 +1,20 @@ use std::{ cell, cell::RefCell, + error::Error, ffi::{CString, NulError}, fmt, io, ptr, sync::Arc, }; +use libc::c_char; use log; -use std::error::Error; -use thiserror::Error as ThisError; - #[cfg(feature = "casting_errors_wallet")] use sqlx; - +use thiserror::Error as ThisError; #[cfg(feature = "casting_errors_misc")] use ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; -use libc::c_char; - use crate::ErrorCode; pub mod prelude { @@ -616,8 +613,8 @@ pub fn set_current_error(err: &IndyError) { /// 1) synchronous - in the same application thread /// 2) asynchronous - inside of function callback /// -/// NOTE: Error is stored until the next one occurs in the same execution thread or until asynchronous callback finished. -/// Returning pointer has the same lifetime. +/// NOTE: Error is stored until the next one occurs in the same execution thread or until +/// asynchronous callback finished. Returning pointer has the same lifetime. /// /// #Params /// * `error_json_p` - Reference that will contain error details (if any error has occurred before) @@ -629,7 +626,6 @@ pub fn set_current_error(err: &IndyError) { /// 2) calling `indy_set_runtime_config` API function with `collect_backtrace: true` /// "message": str - human-readable error description /// } -/// pub fn get_current_error_c_json() -> *const c_char { let mut value = ptr::null(); diff --git a/libvdrtools/indy-api-types/src/lib.rs b/libvdrtools/indy-api-types/src/lib.rs index 079c5e2148..a81e656296 100644 --- a/libvdrtools/indy-api-types/src/lib.rs +++ b/libvdrtools/indy-api-types/src/lib.rs @@ -95,7 +95,8 @@ pub enum ErrorCode { // Invalid library state was detected in runtime. It signals library bug CommonInvalidState = 112, - // Object (json, config, key, credential and etc...) passed by library caller has invalid structure + // Object (json, config, key, credential and etc...) passed by library caller has invalid + // structure CommonInvalidStructure = 113, // IO Error @@ -217,8 +218,8 @@ pub enum ErrorCode { // Timeout for action PoolLedgerTimeout = 307, - // Attempt to open Pool for witch Genesis Transactions are not compatible with set Protocol version. - // Call pool.indy_set_protocol_version to set correct Protocol version. + // Attempt to open Pool for witch Genesis Transactions are not compatible with set Protocol + // version. Call pool.indy_set_protocol_version to set correct Protocol version. PoolIncompatibleProtocolVersion = 308, // Item not found on ledger. diff --git a/libvdrtools/indy-utils/src/crypto/chacha20poly1305_ietf/sodium.rs b/libvdrtools/indy-utils/src/crypto/chacha20poly1305_ietf/sodium.rs index 20c47b8158..5b913ec5da 100644 --- a/libvdrtools/indy-utils/src/crypto/chacha20poly1305_ietf/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/chacha20poly1305_ietf/sodium.rs @@ -1,13 +1,15 @@ extern crate sodiumoxide; -use self::sodiumoxide::{crypto::aead::chacha20poly1305_ietf, utils}; -use super::pwhash_argon2i13; -use indy_api_types::{domain::wallet::KeyDerivationMethod, errors::prelude::*}; use std::{ cmp, io, io::{Read, Write}, }; +use indy_api_types::{domain::wallet::KeyDerivationMethod, errors::prelude::*}; + +use self::sodiumoxide::{crypto::aead::chacha20poly1305_ietf, utils}; +use super::pwhash_argon2i13; + pub const KEYBYTES: usize = chacha20poly1305_ietf::KEYBYTES; pub const NONCEBYTES: usize = chacha20poly1305_ietf::NONCEBYTES; pub const TAGBYTES: usize = chacha20poly1305_ietf::TAGBYTES; @@ -303,8 +305,8 @@ mod tests { pub fn gen_nonce_and_encrypt_detached_decrypt_detached_works() { let data = randombytes(100); let key = gen_key(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = b"some protocol data input to the encryption"; let (c, nonce, tag) = gen_nonce_and_encrypt_detached(&data, aad, &key); diff --git a/libvdrtools/indy-utils/src/crypto/ed25519_box/sodium.rs b/libvdrtools/indy-utils/src/crypto/ed25519_box/sodium.rs index 4d6c1a0392..d51f75d92f 100644 --- a/libvdrtools/indy-utils/src/crypto/ed25519_box/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/ed25519_box/sodium.rs @@ -1,8 +1,9 @@ extern crate sodiumoxide; -use self::sodiumoxide::crypto::box_; use indy_api_types::errors::prelude::*; +use self::sodiumoxide::crypto::box_; + pub const NONCEBYTES: usize = box_::curve25519xsalsa20poly1305::NONCEBYTES; pub const PUBLICKEYBYTES: usize = box_::curve25519xsalsa20poly1305::PUBLICKEYBYTES; pub const SECRETKEYBYTES: usize = box_::curve25519xsalsa20poly1305::SECRETKEYBYTES; diff --git a/libvdrtools/indy-utils/src/crypto/ed25519_sign/sodium.rs b/libvdrtools/indy-utils/src/crypto/ed25519_sign/sodium.rs index 5f7ad758b1..c89f8abeab 100644 --- a/libvdrtools/indy-utils/src/crypto/ed25519_sign/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/ed25519_sign/sodium.rs @@ -1,5 +1,4 @@ use indy_api_types::errors::prelude::*; - use libc::c_int; use sodiumoxide::crypto::{box_, sign}; diff --git a/libvdrtools/indy-utils/src/crypto/hash/openssl.rs b/libvdrtools/indy-utils/src/crypto/hash/openssl.rs index 97c86bfc0a..237ac7e01f 100644 --- a/libvdrtools/indy-utils/src/crypto/hash/openssl.rs +++ b/libvdrtools/indy-utils/src/crypto/hash/openssl.rs @@ -1,11 +1,13 @@ extern crate openssl; -use self::openssl::hash::{Hasher, MessageDigest}; use indy_api_types::errors::prelude::*; +use self::openssl::hash::{Hasher, MessageDigest}; + pub const HASHBYTES: usize = 32; -// these bytes are the same as openssl_hash(MessageDigest::sha256(), &[]) so we do not have to actually call the hash function +// these bytes are the same as openssl_hash(MessageDigest::sha256(), &[]) so we do not have to +// actually call the hash function pub const EMPTY_HASH_BYTES: [u8; HASHBYTES] = [ 227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85, diff --git a/libvdrtools/indy-utils/src/crypto/pwhash_argon2i13/sodium.rs b/libvdrtools/indy-utils/src/crypto/pwhash_argon2i13/sodium.rs index 2989810302..b629c34c1f 100644 --- a/libvdrtools/indy-utils/src/crypto/pwhash_argon2i13/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/pwhash_argon2i13/sodium.rs @@ -1,10 +1,11 @@ extern crate serde; extern crate sodiumoxide; -use self::sodiumoxide::crypto::pwhash; use indy_api_types::{domain::wallet::KeyDerivationMethod, errors::prelude::*}; use libc::{c_int, c_ulonglong, size_t}; +use self::sodiumoxide::crypto::pwhash; + pub const SALTBYTES: usize = pwhash::SALTBYTES; sodium_type!(Salt, pwhash::Salt, SALTBYTES); @@ -84,9 +85,10 @@ extern "C" { #[cfg(test)] mod tests { - use super::*; use rmp_serde; + use super::*; + #[test] fn get_salt_works() { let salt = gen_salt(); diff --git a/libvdrtools/indy-utils/src/crypto/sealedbox/sodium.rs b/libvdrtools/indy-utils/src/crypto/sealedbox/sodium.rs index 0acc7abc4f..0f00f525fb 100644 --- a/libvdrtools/indy-utils/src/crypto/sealedbox/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/sealedbox/sodium.rs @@ -1,8 +1,9 @@ extern crate sodiumoxide; +use indy_api_types::errors::prelude::*; + use self::sodiumoxide::crypto::sealedbox; use super::ed25519_box; -use indy_api_types::errors::prelude::*; pub fn encrypt(pk: &ed25519_box::PublicKey, doc: &[u8]) -> Result, IndyError> { Ok(sealedbox::seal(doc, &pk.0)) diff --git a/libvdrtools/indy-utils/src/crypto/xsalsa20/sodium.rs b/libvdrtools/indy-utils/src/crypto/xsalsa20/sodium.rs index 913aba2456..64cb09cb6a 100644 --- a/libvdrtools/indy-utils/src/crypto/xsalsa20/sodium.rs +++ b/libvdrtools/indy-utils/src/crypto/xsalsa20/sodium.rs @@ -1,8 +1,9 @@ extern crate sodiumoxide; -use self::sodiumoxide::crypto::{secretbox, secretbox::xsalsa20poly1305}; use indy_api_types::errors::prelude::*; +use self::sodiumoxide::crypto::{secretbox, secretbox::xsalsa20poly1305}; + pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES; pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES; pub const MACBYTES: usize = xsalsa20poly1305::MACBYTES; diff --git a/libvdrtools/indy-utils/src/test.rs b/libvdrtools/indy-utils/src/test.rs index dbaf50da56..27147c4ec3 100644 --- a/libvdrtools/indy-utils/src/test.rs +++ b/libvdrtools/indy-utils/src/test.rs @@ -1,7 +1,7 @@ -use super::environment; - use std::{fs, fs::File, path::Path}; +use super::environment; + pub fn cleanup_files(dir: &Path, name: &str) { let mut path = dir.to_path_buf(); path.push(name); @@ -88,7 +88,14 @@ macro_rules! assert_match { _ => false, }) }; - ($pattern:pat, $var:expr, $val_in_pattern1:ident, $exp_value1:expr, $val_in_pattern2:ident, $exp_value2:expr) => { + ( + $pattern:pat, + $var:expr, + $val_in_pattern1:ident, + $exp_value1:expr, + $val_in_pattern2:ident, + $exp_value2:expr + ) => { assert!(match $var { $pattern => $val_in_pattern1 == $exp_value1 && $val_in_pattern2 == $exp_value2, _ => false, diff --git a/libvdrtools/indy-utils/src/wql.rs b/libvdrtools/indy-utils/src/wql.rs index 6af8897b5f..d9cabdd8d6 100644 --- a/libvdrtools/indy-utils/src/wql.rs +++ b/libvdrtools/indy-utils/src/wql.rs @@ -267,9 +267,10 @@ fn parse_single_operator( #[cfg(test)] mod tests { - use super::*; use rand::{distributions::Alphanumeric, thread_rng, Rng}; + use super::*; + fn _random_string(len: usize) -> String { thread_rng() .sample_iter(&Alphanumeric) diff --git a/libvdrtools/indy-wallet/src/cache/lru.rs b/libvdrtools/indy-wallet/src/cache/lru.rs index 8ce1b709b7..b72988547e 100644 --- a/libvdrtools/indy-wallet/src/cache/lru.rs +++ b/libvdrtools/indy-wallet/src/cache/lru.rs @@ -1,8 +1,9 @@ +use lru::LruCache as InnerCache; + use crate::cache::{ cache::Cache, wallet_cache::{WalletCacheKey, WalletCacheValue}, }; -use lru::LruCache as InnerCache; pub struct LruCache { inner: InnerCache, diff --git a/libvdrtools/indy-wallet/src/cache/wallet_cache.rs b/libvdrtools/indy-wallet/src/cache/wallet_cache.rs index 8d9bc01294..8276c8cfb3 100644 --- a/libvdrtools/indy-wallet/src/cache/wallet_cache.rs +++ b/libvdrtools/indy-wallet/src/cache/wallet_cache.rs @@ -1,3 +1,14 @@ +use std::{ + collections::{HashMap, HashSet}, + iter::FromIterator, + sync::{ + atomic::{AtomicUsize, Ordering}, + Mutex, RwLock, + }, +}; + +use indy_api_types::domain::wallet::{CacheConfig, CachingAlgorithm}; + use crate::{ cache::{cache::Cache, lru::LruCache}, storage::{ @@ -9,15 +20,6 @@ use crate::{ wallet::EncryptedValue, RecordOptions, }; -use indy_api_types::domain::wallet::{CacheConfig, CachingAlgorithm}; -use std::{ - collections::{HashMap, HashSet}, - iter::FromIterator, - sync::{ - atomic::{AtomicUsize, Ordering}, - Mutex, RwLock, - }, -}; #[derive(PartialEq, Eq, Hash)] pub struct WalletCacheKey { diff --git a/libvdrtools/indy-wallet/src/encryption.rs b/libvdrtools/indy-wallet/src/encryption.rs index 28c94a14fc..efe8d01406 100644 --- a/libvdrtools/indy-wallet/src/encryption.rs +++ b/libvdrtools/indy-wallet/src/encryption.rs @@ -426,7 +426,8 @@ pub(super) fn decrypt_storage_record( // #[test] // fn test_encrypt_decrypt_tags() { -// let tags = serde_json::from_str(r#"{"tag1":"value1", "tag2":"value2", "~tag3":"value3"}"#).unwrap(); +// let tags = serde_json::from_str(r#"{"tag1":"value1", "tag2":"value2", +// "~tag3":"value3"}"#).unwrap(); // let tag_name_key = chacha20poly1305_ietf::gen_key(); // let tag_value_key = chacha20poly1305_ietf::gen_key(); @@ -453,12 +454,13 @@ pub(super) fn decrypt_storage_record( // let value = "test_value"; // let encrypted_value = EncryptedValue::encrypt(value, &keys.value_key); // let type_ = "test_type"; -// let encrypted_name = encrypt_as_searchable(name.as_bytes(), &keys.name_key, &keys.item_hmac_key); -// let encrypted_type = encrypt_as_searchable(type_.as_bytes(), &keys.type_key, &keys.item_hmac_key); -// let mut tags = HashMap::new(); +// let encrypted_name = encrypt_as_searchable(name.as_bytes(), &keys.name_key, +// &keys.item_hmac_key); let encrypted_type = encrypt_as_searchable(type_.as_bytes(), +// &keys.type_key, &keys.item_hmac_key); let mut tags = HashMap::new(); // tags.insert("tag_name_1".to_string(), "tag_value_1".to_string()); // tags.insert("~tag_name_2".to_string(), "tag_value_2".to_string()); -// let encrypted_tags = encrypt_tags(&tags, &keys.tag_name_key, &keys.tag_value_key, &keys.tags_hmac_key); +// let encrypted_tags = encrypt_tags(&tags, &keys.tag_name_key, &keys.tag_value_key, +// &keys.tags_hmac_key); // let storage_record = StorageRecord { // id: encrypted_name, @@ -482,12 +484,13 @@ pub(super) fn decrypt_storage_record( // let value = "test_value"; // let encrypted_value = EncryptedValue::encrypt(value, &keys.value_key); // let type_ = "test_type"; -// let encrypted_name = encrypt_as_searchable(name.as_bytes(), &keys.name_key, &keys.item_hmac_key); -// let encrypted_type = encrypt_as_searchable(type_.as_bytes(), &keys.type_key, &keys.item_hmac_key); -// let mut tags = HashMap::new(); +// let encrypted_name = encrypt_as_searchable(name.as_bytes(), &keys.name_key, +// &keys.item_hmac_key); let encrypted_type = encrypt_as_searchable(type_.as_bytes(), +// &keys.type_key, &keys.item_hmac_key); let mut tags = HashMap::new(); // tags.insert("tag_name_1".to_string(), "tag_value_1".to_string()); // tags.insert("~tag_name_2".to_string(), "tag_value_2".to_string()); -// let encrypted_tags = encrypt_tags(&tags, &keys.tag_name_key, &keys.tag_value_key, &keys.tags_hmac_key); +// let encrypted_tags = encrypt_tags(&tags, &keys.tag_name_key, &keys.tag_value_key, +// &keys.tags_hmac_key); // let storage_record = StorageRecord { // id: encrypted_name, diff --git a/libvdrtools/indy-wallet/src/export_import.rs b/libvdrtools/indy-wallet/src/export_import.rs index 0aa1ab1e90..09651ec718 100644 --- a/libvdrtools/indy-wallet/src/export_import.rs +++ b/libvdrtools/indy-wallet/src/export_import.rs @@ -1,26 +1,23 @@ use std::{ io, io::{BufReader, BufWriter, Read, Write}, + sync::Arc, time::{SystemTime, UNIX_EPOCH}, }; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; - use indy_api_types::{ domain::wallet::{KeyDerivationMethod, Record}, errors::prelude::*, }; - use indy_utils::crypto::{ chacha20poly1305_ietf, hash::{hash, HASHBYTES}, pwhash_argon2i13, }; - use serde::{Deserialize, Serialize}; use crate::{encryption::KeyDerivationData, Wallet, WalletRecord}; -use std::sync::Arc; const CHUNK_SIZE: usize = 1024; @@ -30,7 +27,8 @@ pub enum EncryptionMethod { ChaCha20Poly1305IETF { // pwhash_argon2i13::Salt as bytes. Random salt used for deriving of key from passphrase salt: Vec, - // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each chunk to be sure in export file consistency + // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each + // chunk to be sure in export file consistency nonce: Vec, // size of encrypted chunk chunk_size: usize, @@ -39,14 +37,16 @@ pub enum EncryptionMethod { ChaCha20Poly1305IETFInteractive { // pwhash_argon2i13::Salt as bytes. Random salt used for deriving of key from passphrase salt: Vec, - // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each chunk to be sure in export file consistency + // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each + // chunk to be sure in export file consistency nonce: Vec, // size of encrypted chunk chunk_size: usize, }, // **ChaCha20-Poly1305-IETF raw key** cypher in blocks per chunk_size bytes ChaCha20Poly1305IETFRaw { - // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each chunk to be sure in export file consistency + // chacha20poly1305_ietf::Nonce as bytes. Random start nonce. We increment nonce for each + // chunk to be sure in export file consistency nonce: Vec, // size of encrypted chunk chunk_size: usize, diff --git a/libvdrtools/indy-wallet/src/lib.rs b/libvdrtools/indy-wallet/src/lib.rs index 01129372b2..8350cf8858 100644 --- a/libvdrtools/indy-wallet/src/lib.rs +++ b/libvdrtools/indy-wallet/src/lib.rs @@ -5,12 +5,12 @@ use std::{ fs, io::BufReader, path::PathBuf, - sync::Arc, + sync::{Arc, Mutex}, unimplemented, }; use indy_api_types::{ - domain::wallet::{Config, Credentials, ExportConfig, Record, Tags}, + domain::wallet::{CacheConfig, Config, Credentials, ExportConfig, Record, Tags}, errors::prelude::*, WalletHandle, }; @@ -21,7 +21,6 @@ use indy_utils::{ use log::{debug, trace}; use serde::{Deserialize, Serialize}; use serde_json::Value as SValue; -use std::sync::Mutex; pub use crate::encryption::KeyDerivationData; use crate::{ @@ -32,7 +31,6 @@ use crate::{ }, wallet::{Keys, Wallet}, }; -use indy_api_types::domain::wallet::CacheConfig; mod encryption; mod iterator; diff --git a/libvdrtools/indy-wallet/src/query_encryption.rs b/libvdrtools/indy-wallet/src/query_encryption.rs index e710e061ef..bf94a545c2 100644 --- a/libvdrtools/indy-wallet/src/query_encryption.rs +++ b/libvdrtools/indy-wallet/src/query_encryption.rs @@ -1,11 +1,11 @@ use indy_api_types::errors::prelude::*; +use indy_utils::wql::Query; use super::{ encryption::encrypt_as_searchable, language::{Operator, TagName, TargetValue}, wallet::Keys, }; -use indy_utils::wql::Query; // Performs encryption of WQL query // WQL query is provided as top-level Operator diff --git a/libvdrtools/indy-wallet/src/storage/default/mod.rs b/libvdrtools/indy-wallet/src/storage/default/mod.rs index cc5632c00d..d8e13aa897 100644 --- a/libvdrtools/indy-wallet/src/storage/default/mod.rs +++ b/libvdrtools/indy-wallet/src/storage/default/mod.rs @@ -3,17 +3,16 @@ use std::{ fs, }; +use async_trait::async_trait; use indy_api_types::errors::prelude::*; use indy_utils::environment; +use log::LevelFilter; use serde::Deserialize; use sqlx::{ sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}, ConnectOptions, SqlitePool, }; -use async_trait::async_trait; -use log::LevelFilter; - use crate::{ language, storage::{StorageIterator, StorageRecord, Tag, TagName, WalletStorage, WalletStorageType}, @@ -117,7 +116,6 @@ impl WalletStorage for SQLiteStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemNotFound` - Item is not found in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn get(&self, type_: &[u8], id: &[u8], options: &str) -> IndyResult { let options: RecordOptions = serde_json::from_str(options).to_indy( IndyErrorKind::InvalidStructure, @@ -206,7 +204,6 @@ impl WalletStorage for SQLiteStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemAlreadyExists` - Item is already present in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn add( &self, type_: &[u8], @@ -297,7 +294,8 @@ impl WalletStorage for SQLiteStorage { match *tag { Tag::Encrypted(ref tag_name, ref tag_data) => { sqlx::query( - "INSERT OR REPLACE INTO tags_encrypted (item_id, name, value) VALUES (?1, ?2, ?3)", + "INSERT OR REPLACE INTO tags_encrypted (item_id, name, value) VALUES (?1, \ + ?2, ?3)", ) .bind(item_id) .bind(tag_name) @@ -307,7 +305,8 @@ impl WalletStorage for SQLiteStorage { } Tag::PlainText(ref tag_name, ref tag_data) => { sqlx::query( - "INSERT OR REPLACE INTO tags_plaintext (item_id, name, value) VALUES (?1, ?2, ?3)", + "INSERT OR REPLACE INTO tags_plaintext (item_id, name, value) VALUES (?1, \ + ?2, ?3)", ) .bind(item_id) .bind(tag_name) @@ -430,7 +429,6 @@ impl WalletStorage for SQLiteStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemNotFound` - Item is not found in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn delete(&self, type_: &[u8], id: &[u8]) -> IndyResult<()> { let mut tx = self.pool.begin().await?; @@ -712,7 +710,6 @@ impl WalletStorageType for SQLiteStorageType { /// /// * `IndyError::NotFound` - File with the provided id not found /// * `IOError(..)` - Deletion of the file form the file-system failed - /// async fn delete_storage( &self, id: &str, @@ -764,7 +761,6 @@ impl WalletStorageType for SQLiteStorageType { /// * `IOError("Error occurred while creating wallet file:..)"` - Creation of schema failed /// * `IOError("Error occurred while inserting the keys...")` - Insertion of keys failed /// * `IOError(..)` - Deletion of the file form the file-system failed - /// async fn create_storage( &self, id: &str, @@ -906,7 +902,6 @@ impl WalletStorageType for SQLiteStorageType { /// /// * `IndyError::NotFound` - File with the provided id not found /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn open_storage( &self, id: &str, diff --git a/libvdrtools/indy-wallet/src/storage/mysql/mod.rs b/libvdrtools/indy-wallet/src/storage/mysql/mod.rs index 5b70cec054..68c73629d5 100644 --- a/libvdrtools/indy-wallet/src/storage/mysql/mod.rs +++ b/libvdrtools/indy-wallet/src/storage/mysql/mod.rs @@ -169,7 +169,6 @@ impl WalletStorage for MySqlStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemNotFound` - Item is not found in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn get(&self, type_: &[u8], id: &[u8], options: &str) -> IndyResult { let options: RecordOptions = serde_json::from_str(options).to_indy( IndyErrorKind::InvalidStructure, @@ -253,7 +252,6 @@ impl WalletStorage for MySqlStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemAlreadyExists` - Item is already present in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn add( &self, type_: &[u8], @@ -472,7 +470,6 @@ impl WalletStorage for MySqlStorage { /// * `IndyError::Closed` - Storage is closed /// * `IndyError::ItemNotFound` - Item is not found in database /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn delete(&self, type_: &[u8], id: &[u8]) -> IndyResult<()> { let mut tx = self.write_pool.begin().await?; @@ -713,7 +710,6 @@ impl WalletStorageType for MySqlStorageType { /// /// * `IndyError::NotFound` - File with the provided id not found /// * `IOError(..)` - Deletion of the file form the file-system failed - /// async fn delete_storage( &self, id: &str, @@ -802,7 +798,6 @@ impl WalletStorageType for MySqlStorageType { /// * `IOError("Error occurred while creating wallet file:..)"` - Creation of schema failed /// * `IOError("Error occurred while inserting the keys...")` - Insertion of keys failed /// * `IOError(..)` - Deletion of the file form the file-system failed - /// async fn create_storage( &self, id: &str, @@ -943,7 +938,6 @@ impl WalletStorageType for MySqlStorageType { /// /// * `IndyError::NotFound` - File with the provided id not found /// * `IOError("IO error during storage operation:...")` - Failed connection or SQL query - /// async fn open_storage( &self, id: &str, @@ -1013,9 +1007,10 @@ mod tests { #[async_std::test] #[cfg(feature = "benchmark")] async fn mysql_storage_sync_send() { - use futures::{channel::oneshot, executor::ThreadPool, future::join_all}; use std::{sync::Arc, time::SystemTime}; + use futures::{channel::oneshot, executor::ThreadPool, future::join_all}; + let count = 1000; let executor = ThreadPool::new().expect("Failed to new ThreadPool"); let storage_type = Arc::new(Box::new(MySqlStorageType::new())); diff --git a/libvdrtools/indy-wallet/src/wallet.rs b/libvdrtools/indy-wallet/src/wallet.rs index 1146245004..fa37c0a234 100644 --- a/libvdrtools/indy-wallet/src/wallet.rs +++ b/libvdrtools/indy-wallet/src/wallet.rs @@ -1,12 +1,11 @@ use std::{collections::HashMap, sync::Arc}; +use futures::future::join; use indy_api_types::errors::prelude::*; - use indy_utils::{ crypto::{chacha20poly1305_ietf, hmacsha256}, wql::Query, }; - use serde::{Deserialize, Serialize}; use zeroize::Zeroize; @@ -19,7 +18,6 @@ use crate::{ storage::StorageRecord, RecordOptions, WalletRecord, }; -use futures::future::join; #[derive(Serialize, Deserialize)] pub(super) struct Keys { @@ -121,7 +119,8 @@ impl EncryptedValue { #[allow(dead_code)] pub fn from_bytes(joined_data: &[u8]) -> IndyResult { - // value_key is stored as NONCE || CYPHERTEXT. Lenth of CYPHERTHEXT is length of DATA + length of TAG. + // value_key is stored as NONCE || CYPHERTEXT. Lenth of CYPHERTHEXT is length of DATA + + // length of TAG. if joined_data.len() < ENCRYPTED_KEY_LEN { return Err(err_msg( IndyErrorKind::InvalidStructure, diff --git a/libvdrtools/src/controllers/anoncreds/issuer.rs b/libvdrtools/src/controllers/anoncreds/issuer.rs index f0f9e104a5..a129fc19c5 100644 --- a/libvdrtools/src/controllers/anoncreds/issuer.rs +++ b/libvdrtools/src/controllers/anoncreds/issuer.rs @@ -6,12 +6,12 @@ use std::{ // use async_std::task::spawn_blocking; use indy_api_types::{domain::wallet::Tags, errors::prelude::*, WalletHandle}; use indy_wallet::{RecordOptions, WalletService}; - use ursa::cl::{ new_nonce, CredentialKeyCorrectnessProof, CredentialPrivateKey, RevocationRegistryDelta as CryptoRevocationRegistryDelta, Witness, }; +use super::tails::{store_tails_from_generator, SDKTailsAccessor}; pub use crate::{ domain::{ anoncreds::{ @@ -38,8 +38,6 @@ pub use crate::{ services::{AnoncredsHelpers, BlobStorageService, CryptoService, IssuerService}, }; -use super::tails::{store_tails_from_generator, SDKTailsAccessor}; - pub struct IssuerController { pub issuer_service: Arc, pub blob_storage_service: Arc, @@ -70,23 +68,24 @@ impl IssuerController { https://github.com/hyperledger/indy-hipe/blob/c761c583b1e01c1e9d3ceda2b03b35336fdc8cc1/text/anoncreds-protocol/README.md */ - /// Create credential schema entity that describes credential attributes list and allows credentials - /// interoperability. + /// Create credential schema entity that describes credential attributes list and allows + /// credentials interoperability. /// - /// Schema is public and intended to be shared with all anoncreds workflow actors usually by publishing SCHEMA transaction - /// to Indy distributed ledger. + /// Schema is public and intended to be shared with all anoncreds workflow actors usually by + /// publishing SCHEMA transaction to Indy distributed ledger. /// /// It is IMPORTANT for current version POST Schema in Ledger and after that GET it from Ledger /// with correct seq_no to save compatibility with Ledger. - /// After that can call indy_issuer_create_and_store_credential_def to build corresponding Credential Definition. + /// After that can call indy_issuer_create_and_store_credential_def to build corresponding + /// Credential Definition. /// /// #Params /// issuer_did: DID of schema issuer /// name: a name the schema /// version: a version of the schema - /// attrs: a list of schema attributes descriptions (the number of attributes should be less or equal than 125) - /// `["attr1", "attr2"]` + /// attrs: a list of schema attributes descriptions (the number of attributes should be less or + /// equal than 125) `["attr1", "attr2"]` /// /// #Returns /// schema_id: identifier of created schema @@ -137,17 +136,21 @@ impl IssuerController { res } - /// Create credential definition entity that encapsulates credentials issuer DID, credential schema, secrets used for signing credentials - /// and secrets used for credentials revocation. + /// Create credential definition entity that encapsulates credentials issuer DID, credential + /// schema, secrets used for signing credentials and secrets used for credentials + /// revocation. /// - /// Credential definition entity contains private and public parts. Private part will be stored in the wallet. Public part - /// will be returned as json intended to be shared with all anoncreds workflow actors usually by publishing CRED_DEF transaction - /// to Indy distributed ledger. + /// Credential definition entity contains private and public parts. Private part will be stored + /// in the wallet. Public part will be returned as json intended to be shared with all + /// anoncreds workflow actors usually by publishing CRED_DEF transaction to Indy distributed + /// ledger. /// - /// It is IMPORTANT for current version GET Schema from Ledger with correct seq_no to save compatibility with Ledger. + /// It is IMPORTANT for current version GET Schema from Ledger with correct seq_no to save + /// compatibility with Ledger. /// - /// Note: Use combination of `indy_issuer_rotate_credential_def_start` and `indy_issuer_rotate_credential_def_apply` functions - /// to generate new keys for an existing credential definition. + /// Note: Use combination of `indy_issuer_rotate_credential_def_start` and + /// `indy_issuer_rotate_credential_def_apply` functions to generate new keys for an existing + /// credential definition. /// /// #Params @@ -161,18 +164,15 @@ impl IssuerController { /// seqNo: (Optional) schema's sequence number on the ledger, /// ver: version of the Schema json /// } - /// tag: any string that allows to distinguish between credential definitions for the same issuer and schema - /// signature_type: credential definition type (optional, 'CL' by default) that defines credentials signature and revocation math. - /// Supported signature types: - /// - 'CL': Camenisch-Lysyanskaya credential signature type that is implemented according to the algorithm in this paper: - /// https://github.com/hyperledger/ursa/blob/master/libursa/docs/AnonCred.pdf - /// And is documented in this HIPE: - /// https://github.com/hyperledger/indy-hipe/blob/c761c583b1e01c1e9d3ceda2b03b35336fdc8cc1/text/anoncreds-protocol/README.md + /// tag: any string that allows to distinguish between credential definitions for the same + /// issuer and schema signature_type: credential definition type (optional, 'CL' by default) + /// that defines credentials signature and revocation math. Supported signature types: + /// - 'CL': Camenisch-Lysyanskaya credential signature type that is implemented according to the + /// algorithm in this paper: https://github.com/hyperledger/ursa/blob/master/libursa/docs/AnonCred.pdf + /// And is documented in this HIPE: https://github.com/hyperledger/indy-hipe/blob/c761c583b1e01c1e9d3ceda2b03b35336fdc8cc1/text/anoncreds-protocol/README.md /// config_json: (optional) type-specific configuration of credential definition as json: - /// - 'CL': - /// { - /// "support_revocation" - bool (optional, default false) whether to request non-revocation credential - /// } + /// - 'CL': { "support_revocation" - bool (optional, default false) whether to request + /// non-revocation credential } /// /// #Returns /// cred_def_id: identifier of created credential definition @@ -181,16 +181,17 @@ impl IssuerController { /// id: string - identifier of credential definition /// schemaId: string - identifier of stored in ledger schema /// type: string - type of the credential definition. CL is the only supported type now. - /// tag: string - allows to distinct between credential definitions for the same issuer and schema - /// value: Dictionary with Credential Definition's data is depended on the signature type: { - /// primary: primary credential public key, + /// tag: string - allows to distinct between credential definitions for the same issuer and + /// schema value: Dictionary with Credential Definition's data is depended on the + /// signature type: { primary: primary credential public key, /// Optional: revocation credential public key /// }, /// ver: Version of the CredDef json /// } /// - /// Note: `primary` and `revocation` fields of credential definition are complex opaque types that contain data structures internal to Ursa. - /// They should not be parsed and are likely to change in future versions. + /// Note: `primary` and `revocation` fields of credential definition are complex opaque types + /// that contain data structures internal to Ursa. They should not be parsed and are likely + /// to change in future versions. /// /// #Errors /// Common* @@ -206,9 +207,8 @@ impl IssuerController { config: Option, ) -> IndyResult<(String, String)> { trace!( - "create_and_store_credential_definition > wallet_handle {:?} \ - issuer_did {:?} schema {:?} tag {:?} \ - type_ {:?}, config {:?}", + "create_and_store_credential_definition > wallet_handle {:?} issuer_did {:?} schema \ + {:?} tag {:?} type_ {:?}, config {:?}", wallet_handle, issuer_did, schema, @@ -355,21 +355,22 @@ impl IssuerController { // Ok(res) } - /// Generate temporary credential definitional keys for an existing one (owned by the caller of the library). + /// Generate temporary credential definitional keys for an existing one (owned by the caller of + /// the library). /// - /// Use `indy_issuer_rotate_credential_def_apply` function to set generated temporary keys as the main. + /// Use `indy_issuer_rotate_credential_def_apply` function to set generated temporary keys as + /// the main. /// - /// WARNING: Rotating the credential definitional keys will result in making all credentials issued under the previous keys unverifiable. + /// WARNING: Rotating the credential definitional keys will result in making all credentials + /// issued under the previous keys unverifiable. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). /// cred_def_id: an identifier of created credential definition stored in the wallet /// config_json: (optional) type-specific configuration of credential definition as json: - /// - 'CL': - /// { - /// "support_revocation" - bool (optional, default false) whether to request non-revocation credential - /// } + /// - 'CL': { "support_revocation" - bool (optional, default false) whether to request + /// non-revocation credential } /// /// #Returns /// cred_def_json: public part of temporary created credential definition @@ -377,16 +378,17 @@ impl IssuerController { /// id: string - identifier of credential definition /// schemaId: string - identifier of stored in ledger schema /// type: string - type of the credential definition. CL is the only supported type now. - /// tag: string - allows to distinct between credential definitions for the same issuer and schema - /// value: Dictionary with Credential Definition's data is depended on the signature type: { - /// primary: primary credential public key, + /// tag: string - allows to distinct between credential definitions for the same issuer and + /// schema value: Dictionary with Credential Definition's data is depended on the + /// signature type: { primary: primary credential public key, /// Optional: revocation credential public key /// }, - only this field differs from the original credential definition /// ver: Version of the CredDef json /// } /// - /// Note: `primary` and `revocation` fields of credential definition are complex opaque types that contain data structures internal to Ursa. - /// They should not be parsed and are likely to change in future versions. + /// Note: `primary` and `revocation` fields of credential definition are complex opaque types + /// that contain data structures internal to Ursa. They should not be parsed and are likely + /// to change in future versions. /// /// #Errors /// Common* @@ -399,8 +401,8 @@ impl IssuerController { cred_def_config: Option, ) -> IndyResult { trace!( - "rotate_credential_definition_start > \ - wallet_handle {:?} cred_def_id {:?} cred_def_config {:?}", + "rotate_credential_definition_start > wallet_handle {:?} cred_def_id {:?} \ + cred_def_config {:?}", wallet_handle, cred_def_id, cred_def_config @@ -502,9 +504,11 @@ impl IssuerController { res } - /// Apply temporary keys as main for an existing Credential Definition (owned by the caller of the library). + /// Apply temporary keys as main for an existing Credential Definition (owned by the caller of + /// the library). /// - /// WARNING: Rotating the credential definitional keys will result in making all credentials issued under the previous keys unverifiable. + /// WARNING: Rotating the credential definitional keys will result in making all credentials + /// issued under the previous keys unverifiable. /// /// #Params @@ -567,67 +571,75 @@ impl IssuerController { } /// Create a new revocation registry for the given credential definition as tuple of entities - /// - Revocation registry definition that encapsulates credentials definition reference, revocation type specific configuration and - /// secrets used for credentials revocation - /// - Revocation registry state that stores the information about revoked entities in a non-disclosing way. The state can be - /// represented as ordered list of revocation registry entries were each entry represents the list of revocation or issuance operations. + /// - Revocation registry definition that encapsulates credentials definition reference, + /// revocation type specific configuration and secrets used for credentials revocation + /// - Revocation registry state that stores the information about revoked entities in a + /// non-disclosing way. The state can be represented as ordered list of revocation registry + /// entries were each entry represents the list of revocation or issuance operations. /// - /// Revocation registry definition entity contains private and public parts. Private part will be stored in the wallet. Public part - /// will be returned as json intended to be shared with all anoncreds workflow actors usually by publishing REVOC_REG_DEF transaction + /// Revocation registry definition entity contains private and public parts. Private part will + /// be stored in the wallet. Public part will be returned as json intended to be shared with + /// all anoncreds workflow actors usually by publishing REVOC_REG_DEF transaction /// to Indy distributed ledger. /// - /// Revocation registry state is stored on the wallet and also intended to be shared as the ordered list of REVOC_REG_ENTRY transactions. - /// This call initializes the state in the wallet and returns the initial entry. + /// Revocation registry state is stored on the wallet and also intended to be shared as the + /// ordered list of REVOC_REG_ENTRY transactions. This call initializes the state in the + /// wallet and returns the initial entry. /// - /// Some revocation registry types (for example, 'CL_ACCUM') can require generation of binary blob called tails used to hide information about revoked credentials in public - /// revocation registry and intended to be distributed out of leger (REVOC_REG_DEF transaction will still contain uri and hash of tails). - /// This call requires access to pre-configured blob storage writer instance handle that will allow to write generated tails. + /// Some revocation registry types (for example, 'CL_ACCUM') can require generation of binary + /// blob called tails used to hide information about revoked credentials in public + /// revocation registry and intended to be distributed out of leger (REVOC_REG_DEF transaction + /// will still contain uri and hash of tails). This call requires access to pre-configured + /// blob storage writer instance handle that will allow to write generated tails. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). /// issuer_did: a DID of the issuer - /// revoc_def_type: revocation registry type (optional, default value depends on credential definition type). Supported types are: + /// revoc_def_type: revocation registry type (optional, default value depends on credential + /// definition type). Supported types are: /// - 'CL_ACCUM': Type-3 pairing based accumulator implemented according to the algorithm in this paper: /// https://github.com/hyperledger/ursa/blob/master/libursa/docs/AnonCred.pdf /// This type is default for 'CL' credential definition type. - /// tag: any string that allows to distinct between revocation registries for the same issuer and credential definition - /// cred_def_id: id of stored in ledger credential definition + /// tag: any string that allows to distinct between revocation registries for the same issuer + /// and credential definition cred_def_id: id of stored in ledger credential definition /// config_json: type-specific configuration of revocation registry as json: - /// - 'CL_ACCUM': { - /// "issuance_type": (optional) type of issuance. Currently supported: - /// 1) ISSUANCE_BY_DEFAULT: all indices are assumed to be issued and initial accumulator is calculated over all indices; - /// Revocation Registry is updated only during revocation. - /// 2) ISSUANCE_ON_DEMAND: nothing is issued initially accumulator is 1 (used by default); - /// "max_cred_num": maximum number of credentials the new registry can process (optional, default 100000) + /// - 'CL_ACCUM': { "issuance_type": (optional) type of issuance. Currently supported: 1) + /// ISSUANCE_BY_DEFAULT: all indices are assumed to be issued and initial accumulator is + /// calculated over all indices; Revocation Registry is updated only during revocation. 2) + /// ISSUANCE_ON_DEMAND: nothing is issued initially accumulator is 1 (used by default); + /// "max_cred_num": maximum number of credentials the new registry can process (optional, + /// default 100000) /// } - /// tails_writer_handle: handle of blob storage to store tails (returned by `indy_open_blob_storage_writer`). + /// tails_writer_handle: handle of blob storage to store tails (returned by + /// `indy_open_blob_storage_writer`). /// /// NOTE: - /// Recursive creation of folder for Default Tails Writer (correspondent to `tails_writer_handle`) - /// in the system-wide temporary directory may fail in some setup due to permissions: `IO error: Permission denied`. - /// In this case use `TMPDIR` environment variable to define temporary directory specific for an application. + /// Recursive creation of folder for Default Tails Writer (correspondent to + /// `tails_writer_handle`) in the system-wide temporary directory may fail in some setup + /// due to permissions: `IO error: Permission denied`. In this case use `TMPDIR` + /// environment variable to define temporary directory specific for an application. /// /// #Returns /// revoc_reg_id: identifier of created revocation registry definition /// revoc_reg_def_json: public part of revocation registry definition /// { /// "id": string - ID of the Revocation Registry, - /// "revocDefType": string - Revocation Registry type (only CL_ACCUM is supported for now), - /// "tag": string - Unique descriptive ID of the Registry, + /// "revocDefType": string - Revocation Registry type (only CL_ACCUM is supported for + /// now), "tag": string - Unique descriptive ID of the Registry, /// "credDefId": string - ID of the corresponding CredentialDefinition, /// "value": Registry-specific data { - /// "issuanceType": string - Type of Issuance(ISSUANCE_BY_DEFAULT or ISSUANCE_ON_DEMAND), - /// "maxCredNum": number - Maximum number of credentials the Registry can serve. - /// "tailsHash": string - Hash of tails. + /// "issuanceType": string - Type of Issuance(ISSUANCE_BY_DEFAULT or + /// ISSUANCE_ON_DEMAND), "maxCredNum": number - Maximum number of credentials + /// the Registry can serve. "tailsHash": string - Hash of tails. /// "tailsLocation": string - Location of tails file. - /// "publicKeys": - Registry's public key (opaque type that contains data structures internal to Ursa. - /// It should not be parsed and are likely to change in future versions). - /// }, + /// "publicKeys": - Registry's public key (opaque type that contains + /// data structures internal to Ursa. + /// It should not be parsed and are likely to change in future versions). }, /// "ver": string - version of revocation registry definition json. /// } - /// revoc_reg_entry_json: revocation registry entry that defines initial state of revocation registry - /// { + /// revoc_reg_entry_json: revocation registry entry that defines initial state of revocation + /// registry { /// value: { /// prevAccum: string - previous accumulator value. /// accum: string - current accumulator value. @@ -652,9 +664,8 @@ impl IssuerController { tails_writer_handle: i32, ) -> IndyResult<(String, String, String)> { trace!( - "create_and_store_revocation_registry > wallet_handle {:?} \ - issuer_did {:?} type_ {:?} tag: {:?} cred_def_id {:?} \ - config: {:?} tails_handle {:?}", + "create_and_store_revocation_registry > wallet_handle {:?} issuer_did {:?} type_ {:?} \ + tag: {:?} cred_def_id {:?} config: {:?} tails_handle {:?}", wallet_handle, issuer_did, type_, @@ -826,10 +837,10 @@ impl IssuerController { /// "cred_def_id": string, - identifier of credential definition /// // Fields below can depend on Credential Definition type /// "nonce": string, - /// "key_correctness_proof" : key correctness proof for credential definition correspondent to cred_def_id - /// (opaque type that contains data structures internal to Ursa. - /// It should not be parsed and are likely to change in future versions). - /// } + /// "key_correctness_proof" : key correctness proof for credential definition + /// correspondent to cred_def_id (opaque type that + /// contains data structures internal to Ursa. It should + /// not be parsed and are likely to change in future versions). } /// /// #Errors /// Common* @@ -877,29 +888,31 @@ impl IssuerController { /// Check Cred Request for the given Cred Offer and issue Credential for the given Cred Request. /// - /// Cred Request must match Cred Offer. The credential definition and revocation registry definition - /// referenced in Cred Offer and Cred Request must be already created and stored into the wallet. + /// Cred Request must match Cred Offer. The credential definition and revocation registry + /// definition referenced in Cred Offer and Cred Request must be already created and stored + /// into the wallet. /// - /// Information for this credential revocation will be store in the wallet as part of revocation registry under - /// generated cred_revoc_id local for this wallet. + /// Information for this credential revocation will be store in the wallet as part of revocation + /// registry under generated cred_revoc_id local for this wallet. /// - /// This call returns revoc registry delta as json file intended to be shared as REVOC_REG_ENTRY transaction. - /// Note that it is possible to accumulate deltas to reduce ledger load. + /// This call returns revoc registry delta as json file intended to be shared as REVOC_REG_ENTRY + /// transaction. Note that it is possible to accumulate deltas to reduce ledger load. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). /// cred_offer_json: a cred offer created by indy_issuer_create_credential_offer /// cred_req_json: a credential request created by indy_prover_create_credential_req - /// cred_values_json: a credential containing attribute values for each of requested attribute names. - /// Example: + /// cred_values_json: a credential containing attribute values for each of requested attribute + /// names. Example: /// { /// "attr1" : {"raw": "value1", "encoded": "value1_as_int" }, /// "attr2" : {"raw": "value1", "encoded": "value1_as_int" } /// } - /// If you want to use empty value for some credential field, you should set "raw" to "" and "encoded" should not be empty - /// rev_reg_id: id of revocation registry stored in the wallet - /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to read revocation tails (returned by `indy_open_blob_storage_reader`) + /// If you want to use empty value for some credential field, you should set "raw" to "" and + /// "encoded" should not be empty rev_reg_id: id of revocation registry stored in the wallet + /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to + /// read revocation tails (returned by `indy_open_blob_storage_reader`) /// /// #Returns /// cred_json: Credential json containing signed credential values @@ -939,9 +952,8 @@ impl IssuerController { blob_storage_reader_handle: Option, ) -> IndyResult<(String, Option, Option)> { trace!( - "new_credential > wallet_handle {:?} cred_offer {:?} \ - cred_request {:?} cred_values {:?} rev_reg_id {:?} \ - blob_storage_reader_handle {:?}", + "new_credential > wallet_handle {:?} cred_offer {:?} cred_request {:?} cred_values \ + {:?} rev_reg_id {:?} blob_storage_reader_handle {:?}", wallet_handle, secret!(&cred_offer), secret!(&cred_request), @@ -1130,20 +1142,22 @@ impl IssuerController { res } - /// Revoke a credential identified by a cred_revoc_id (returned by indy_issuer_create_credential). + /// Revoke a credential identified by a cred_revoc_id (returned by + /// indy_issuer_create_credential). /// /// The corresponding credential definition and revocation registry must be already /// created an stored into the wallet. /// - /// This call returns revoc registry delta as json file intended to be shared as REVOC_REG_ENTRY transaction. - /// Note that it is possible to accumulate deltas to reduce ledger load. + /// This call returns revoc registry delta as json file intended to be shared as REVOC_REG_ENTRY + /// transaction. Note that it is possible to accumulate deltas to reduce ledger load. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). - /// blob_storage_reader_cfg_handle: configuration of blob storage reader handle that will allow to read revocation tails (returned by `indy_open_blob_storage_reader`). - /// rev_reg_id: id of revocation registry stored in wallet - /// cred_revoc_id: local id for revocation info related to issued credential + /// blob_storage_reader_cfg_handle: configuration of blob storage reader handle that will allow + /// to read revocation tails (returned by `indy_open_blob_storage_reader`). rev_reg_id: id + /// of revocation registry stored in wallet cred_revoc_id: local id for revocation info + /// related to issued credential /// /// #Returns /// revoc_reg_delta_json: Revocation registry delta json with a revoked credential @@ -1168,9 +1182,8 @@ impl IssuerController { cred_revoc_id: String, ) -> IndyResult { trace!( - "revoke_credential > wallet_handle {:?} \ - blob_storage_reader_handle {:?} \ - rev_reg_id {:?} cred_revoc_id {:?}", + "revoke_credential > wallet_handle {:?} blob_storage_reader_handle {:?} rev_reg_id \ + {:?} cred_revoc_id {:?}", wallet_handle, blob_storage_reader_handle, rev_reg_id, @@ -1273,8 +1286,14 @@ impl IssuerController { rev_reg_id: &RevocationRegistryId, cred_revoc_id: &str, ) -> IndyResult { - trace!("recovery_credential >>> wallet_handle: {:?}, blob_storage_reader_handle: {:?}, rev_reg_id: {:?}, cred_revoc_id: {:?}", - wallet_handle, blob_storage_reader_handle, rev_reg_id, secret!(cred_revoc_id)); + trace!( + "recovery_credential >>> wallet_handle: {:?}, blob_storage_reader_handle: {:?}, \ + rev_reg_id: {:?}, cred_revoc_id: {:?}", + wallet_handle, + blob_storage_reader_handle, + rev_reg_id, + secret!(cred_revoc_id) + ); let cred_revoc_id = AnoncredsHelpers::parse_cred_rev_id(cred_revoc_id)?; @@ -1365,8 +1384,9 @@ impl IssuerController { res } - /// Merge two revocation registry deltas (returned by indy_issuer_create_credential or indy_issuer_revoke_credential) to accumulate common delta. - /// Send common delta to ledger to reduce the load. + /// Merge two revocation registry deltas (returned by indy_issuer_create_credential or + /// indy_issuer_revoke_credential) to accumulate common delta. Send common delta to ledger + /// to reduce the load. /// /// #Params @@ -1381,7 +1401,8 @@ impl IssuerController { /// ver: string - version revocation registry delta json /// } /// - /// other_rev_reg_delta_json: revocation registry delta for which PrevAccum value is equal to value of accum field of rev_reg_delta_json parameter. + /// other_rev_reg_delta_json: revocation registry delta for which PrevAccum value is equal to + /// value of accum field of rev_reg_delta_json parameter. /// /// #Returns /// merged_rev_reg_delta: Merged revocation registry delta diff --git a/libvdrtools/src/controllers/anoncreds/prover.rs b/libvdrtools/src/controllers/anoncreds/prover.rs index 9c7537cc11..273fd394f2 100644 --- a/libvdrtools/src/controllers/anoncreds/prover.rs +++ b/libvdrtools/src/controllers/anoncreds/prover.rs @@ -12,6 +12,7 @@ use log::trace; use serde_json::Value; use ursa::cl::{new_nonce, RevocationRegistry, Witness}; +use super::tails::SDKTailsAccessor; use crate::{ domain::{ anoncreds::{ @@ -42,8 +43,6 @@ use crate::{ utils::wql::Query, }; -use super::tails::SDKTailsAccessor; - struct SearchForProofRequest { search: WalletSearch, interval: Option, @@ -152,16 +151,17 @@ impl ProverController { /// Creates a credential request for the given credential offer. /// - /// The method creates a blinded master secret for a master secret identified by a provided name. - /// The master secret identified by the name must be already stored in the secure wallet (see prover_create_master_secret) - /// The blinded master secret is a part of the credential request. + /// The method creates a blinded master secret for a master secret identified by a provided + /// name. The master secret identified by the name must be already stored in the secure + /// wallet (see prover_create_master_secret) The blinded master secret is a part of the + /// credential request. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet) /// prover_did: a DID of the prover - /// cred_offer_json: credential offer as a json containing information about the issuer and a credential - /// { + /// cred_offer_json: credential offer as a json containing information about the issuer and a + /// credential { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// ... @@ -185,9 +185,9 @@ impl ProverController { /// It should not be parsed and are likely to change in future versions). /// "nonce": string /// } - /// cred_req_metadata_json: Credential request metadata json for further processing of received form Issuer credential. - /// Credential request metadata contains data structures internal to Ursa. - /// Credential request metadata mustn't be shared with Issuer. + /// cred_req_metadata_json: Credential request metadata json for further processing of received + /// form Issuer credential. Credential request metadata contains data structures + /// internal to Ursa. Credential request metadata mustn't be shared with Issuer. /// /// #Errors /// Anoncreds* @@ -202,9 +202,8 @@ impl ProverController { master_secret_id: String, ) -> IndyResult<(String, String)> { trace!( - "create_credential_request > wallet_handle {:?} \ - prover_did {:?} cred_offer {:?} cred_def {:?} \ - master_secret_id: {:?}", + "create_credential_request > wallet_handle {:?} prover_did {:?} cred_offer {:?} \ + cred_def {:?} master_secret_id: {:?}", wallet_handle, prover_did, cred_offer, @@ -269,12 +268,12 @@ impl ProverController { /// "schema_version": , /// "issuer_did": , /// "cred_def_id": , - /// "rev_reg_id": , // "None" as string if not present - /// } + /// "rev_reg_id": , // "None" as string if not + /// present } /// - /// The policy sets the following tags for each attribute it marks taggable, written to subsequent - /// credentials and (optionally) all existing credentials on the credential definition: - /// { + /// The policy sets the following tags for each attribute it marks taggable, written to + /// subsequent credentials and (optionally) all existing credentials on the credential + /// definition: { /// "attr::::marker": "1", /// "attr::::value": , /// } @@ -284,7 +283,8 @@ impl ProverController { /// wallet_handle: wallet handle (created by open_wallet). /// cred_def_id: credential definition id /// tag_attrs_json: JSON array with names of attributes to tag by policy, or null for all - /// retroactive: boolean, whether to apply policy to existing credentials on credential definition identifier + /// retroactive: boolean, whether to apply policy to existing credentials on credential + /// definition identifier /// /// #Errors /// Anoncreds* @@ -298,8 +298,8 @@ impl ProverController { retroactive: bool, ) -> IndyResult<()> { trace!( - "set_credential_attr_tag_policy > wallet_handle {:?} \ - cred_def_id {:?} catpol {:?} retroactive {:?}", + "set_credential_attr_tag_policy > wallet_handle {:?} cred_def_id {:?} catpol {:?} \ + retroactive {:?}", wallet_handle, cred_def_id, catpol, @@ -328,7 +328,8 @@ impl ProverController { } }; - // Cascade whether we updated policy or not: could be a retroactive cred attr tags reset to existing policy + // Cascade whether we updated policy or not: could be a retroactive cred attr tags reset to + // existing policy if retroactive { let query_json = format!(r#"{{"cred_def_id": "{}"}}"#, cred_def_id.0); @@ -387,8 +388,7 @@ impl ProverController { cred_def_id: CredentialDefinitionId, ) -> IndyResult { trace!( - "get_credential_attr_tag_policy > wallet_handle {:?} \ - cred_def_id {:?}", + "get_credential_attr_tag_policy > wallet_handle {:?} cred_def_id {:?}", wallet_handle, cred_def_id ); @@ -405,26 +405,26 @@ impl ProverController { /// Check credential provided by Issuer for the given credential request, /// updates the credential by a master secret and stores in a secure wallet. /// - /// To support efficient and flexible search the following tags will be created for stored credential: - /// { + /// To support efficient and flexible search the following tags will be created for stored + /// credential: { /// "schema_id": , /// "schema_issuer_did": , /// "schema_name": , /// "schema_version": , /// "issuer_did": , /// "cred_def_id": , - /// "rev_reg_id": , // "None" as string if not present - /// // for every attribute in that credential attribute tagging policy marks taggable - /// "attr::::marker": "1", + /// "rev_reg_id": , // "None" as string if not + /// present // for every attribute in that credential attribute + /// tagging policy marks taggable "attr::::marker": "1", /// "attr::::value": , /// } /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). - /// cred_id: (optional, default is a random one) identifier by which credential will be stored in the wallet - /// cred_req_metadata_json: a credential request metadata created by indy_prover_create_credential_req - /// cred_json: credential json received from issuer + /// cred_id: (optional, default is a random one) identifier by which credential will be stored + /// in the wallet cred_req_metadata_json: a credential request metadata created by + /// indy_prover_create_credential_req cred_json: credential json received from issuer /// { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition @@ -439,7 +439,8 @@ impl ProverController { /// These fields should not be parsed and are likely to change in future versions. /// } /// cred_def_json: credential definition json related to in - /// rev_reg_def_json: revocation registry definition json related to in + /// rev_reg_def_json: revocation registry definition json related to in + /// /// /// #Returns /// out_cred_id: identifier by which credential is stored in the wallet @@ -458,10 +459,8 @@ impl ProverController { rev_reg_def: Option, ) -> IndyResult { trace!( - "store_credential > wallet_handle {:?} \ - cred_id {:?} cred_req_metadata {:?} \ - credential {:?} cred_def {:?} \ - rev_reg_def {:?}", + "store_credential > wallet_handle {:?} cred_id {:?} cred_req_metadata {:?} credential \ + {:?} cred_def {:?} rev_reg_def {:?}", wallet_handle, cred_id, cred_req_metadata, @@ -540,8 +539,8 @@ impl ProverController { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// "rev_reg_id": Optional, - identifier of revocation registry definition - /// "cred_rev_id": Optional - identifier of credential in the revocation registry definition - /// }] + /// "cred_rev_id": Optional - identifier of credential in the revocation + /// registry definition }] /// /// #Errors /// Anoncreds* @@ -600,8 +599,8 @@ impl ProverController { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// "rev_reg_id": Optional, - identifier of revocation registry definition - /// "cred_rev_id": Optional - identifier of credential in the revocation registry definition - /// } + /// "cred_rev_id": Optional - identifier of credential in the revocation + /// registry definition } /// /// #Errors /// Anoncreds* @@ -648,8 +647,8 @@ impl ProverController { /// where query: indy-sdk/docs/design/011-wallet-query-language/README.md /// /// #Returns - /// search_handle: Search handle that can be used later to fetch records by small batches (with indy_prover_fetch_credentials) - /// total_count: Total count of records + /// search_handle: Search handle that can be used later to fetch records by small batches (with + /// indy_prover_fetch_credentials) total_count: Total count of records /// /// #Errors /// Anoncreds* @@ -703,9 +702,10 @@ impl ProverController { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// "rev_reg_id": Optional, - identifier of revocation registry definition - /// "cred_rev_id": Optional - identifier of credential in the revocation registry definition - /// }] - /// NOTE: The list of length less than the requested count means credentials search iterator is completed. + /// "cred_rev_id": Optional - identifier of credential in the revocation + /// registry definition }] + /// NOTE: The list of length less than the requested count means credentials search iterator is + /// completed. /// /// #Errors /// Anoncreds* @@ -795,10 +795,10 @@ impl ProverController { /// { /// "name": string, /// "version": string, - /// "nonce": string, - a decimal number represented as a string (use `indy_generate_nonce` function to generate 80-bit number) - /// "requested_attributes": { // set of requested attributes - /// "": , // see below - /// ..., + /// "nonce": string, - a decimal number represented as a string (use + /// `indy_generate_nonce` function to generate 80-bit number) "requested_attributes" + /// : { // set of requested attributes "": , // see + /// below ..., /// }, /// "requested_predicates": { // set of requested predicates /// "": , // see below @@ -807,8 +807,8 @@ impl ProverController { /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation /// // for date in this interval for each attribute - /// // (applies to every attribute and predicate but can be overridden on attribute level), - /// "ver": Optional - proof request version: + /// // (applies to every attribute and predicate but can be overridden on + /// attribute level), "ver": Optional - proof request version: /// - omit or "1.0" to use unqualified identifiers for restrictions /// - "2.0" to use fully qualified identifiers for restrictions /// } @@ -818,9 +818,10 @@ impl ProverController { /// attr_info: Describes requested attribute /// { /// "name": Optional, // attribute name, (case insensitive and ignore spaces) - /// "names": Optional<[string, string]>, // attribute names, (case insensitive and ignore spaces) - /// // NOTE: should either be "name" or "names", not both and not none of them. - /// // Use "names" to specify several attributes that have to match a single credential. + /// "names": Optional<[string, string]>, // attribute names, (case insensitive and + /// ignore spaces) // NOTE: should either be + /// "name" or "names", not both and not none of them. + /// // Use "names" to specify several attributes that have to match a single credential. /// "restrictions": Optional, // see below /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation @@ -858,13 +859,14 @@ impl ProverController { /// credentials_json: json with credentials for the given proof request. /// { /// "attrs": { - /// "": [{ cred_info: , interval: Optional }], - /// ..., + /// "": [{ cred_info: , interval: + /// Optional }], ..., /// }, /// "predicates": { - /// "requested_predicates": [{ cred_info: , timestamp: Optional }, { cred_info: , timestamp: Optional }], - /// "requested_predicate_2_referent": [{ cred_info: , timestamp: Optional }] - /// } + /// "requested_predicates": [{ cred_info: , timestamp: + /// Optional }, { cred_info: , timestamp: Optional }], + /// "requested_predicate_2_referent": [{ cred_info: , timestamp: + /// Optional }] } /// }, where is /// { /// "referent": string, - id of credential in the wallet @@ -872,8 +874,8 @@ impl ProverController { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// "rev_reg_id": Optional, - identifier of revocation registry definition - /// "cred_rev_id": Optional - identifier of credential in the revocation registry definition - /// } + /// "cred_rev_id": Optional - identifier of credential in the revocation + /// registry definition } /// /// #Errors /// Anoncreds* @@ -977,10 +979,10 @@ impl ProverController { /// { /// "name": string, /// "version": string, - /// "nonce": string, - a decimal number represented as a string (use `indy_generate_nonce` function to generate 80-bit number) - /// "requested_attributes": { // set of requested attributes - /// "": , // see below - /// ..., + /// "nonce": string, - a decimal number represented as a string (use + /// `indy_generate_nonce` function to generate 80-bit number) "requested_attributes" + /// : { // set of requested attributes "": , // see + /// below ..., /// }, /// "requested_predicates": { // set of requested predicates /// "": , // see below @@ -989,8 +991,8 @@ impl ProverController { /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation /// // for date in this interval for each attribute - /// // (applies to every attribute and predicate but can be overridden on attribute level) - /// // (can be overridden on attribute level) + /// // (applies to every attribute and predicate but can be overridden on + /// attribute level) // (can be overridden on attribute level) /// "ver": Optional - proof request version: /// - omit or "1.0" to use unqualified identifiers for restrictions /// - "2.0" to use fully qualified identifiers for restrictions @@ -1000,9 +1002,10 @@ impl ProverController { /// attr_info: Describes requested attribute /// { /// "name": Optional, // attribute name, (case insensitive and ignore spaces) - /// "names": Optional<[string, string]>, // attribute names, (case insensitive and ignore spaces) - /// // NOTE: should either be "name" or "names", not both and not none of them. - /// // Use "names" to specify several attributes that have to match a single credential. + /// "names": Optional<[string, string]>, // attribute names, (case insensitive and + /// ignore spaces) // NOTE: should either be + /// "name" or "names", not both and not none of them. + /// // Use "names" to specify several attributes that have to match a single credential. /// "restrictions": Optional, // see below /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation @@ -1026,8 +1029,8 @@ impl ProverController { /// "from": Optional, // timestamp of interval beginning /// "to": Optional, // timestamp of interval ending /// } - /// extra_query_json:(Optional) List of extra queries that will be applied to correspondent attribute/predicate: - /// { + /// extra_query_json:(Optional) List of extra queries that will be applied to correspondent + /// attribute/predicate: { /// "": , /// "": , /// } @@ -1039,14 +1042,16 @@ impl ProverController { /// "schema_version": , /// "issuer_did": , /// "cred_def_id": , - /// "rev_reg_id": , // "None" as string if not present - /// // the following keys can be used for every `attribute name` in credential. - /// "attr::::marker": "1", - to filter based on existence of a specific attribute - /// "attr::::value": , - to filter based on value of a specific attribute + /// "rev_reg_id": , // "None" as string if not + /// present // the following keys can be used for every `attribute name` in + /// credential. "attr::::marker": "1", - to filter based on + /// existence of a specific attribute "attr::::value": , - to filter based on value of a specific attribute /// /// /// #Returns - /// search_handle: Search handle that can be used later to fetch records by small batches (with indy_prover_fetch_credentials_for_proof_req) + /// search_handle: Search handle that can be used later to fetch records by small batches (with + /// indy_prover_fetch_credentials_for_proof_req) /// /// #Errors /// Anoncreds* @@ -1059,8 +1064,8 @@ impl ProverController { extra_query: Option, ) -> IndyResult { trace!( - "search_credentials_for_proof_req > wallet_handle {:?} \ - proof_request {:?} extra_query {:?}", + "search_credentials_for_proof_req > wallet_handle {:?} proof_request {:?} extra_query \ + {:?}", wallet_handle, proof_request, extra_query @@ -1174,8 +1179,8 @@ impl ProverController { /// "schema_id": string, - identifier of schema /// "cred_def_id": string, - identifier of credential definition /// "rev_reg_id": Optional, - identifier of revocation registry definition - /// "cred_rev_id": Optional - identifier of credential in the revocation registry definition - /// } + /// "cred_rev_id": Optional - identifier of credential in the revocation + /// registry definition } /// non_revoc_interval: /// { /// "from": Optional, // timestamp of interval beginning @@ -1195,8 +1200,7 @@ impl ProverController { count: usize, ) -> IndyResult { trace!( - "fetch_credential_for_proof_request > search_handle {:?} \ - item_referent {:?} count {:?}", + "fetch_credential_for_proof_request > search_handle {:?} item_referent {:?} count {:?}", search_handle, item_referent, count @@ -1321,12 +1325,13 @@ impl ProverController { } /// Creates a proof according to the given proof request - /// Either a corresponding credential with optionally revealed attributes or self-attested attribute must be provided - /// for each requested attribute (see indy_prover_get_credentials_for_pool_req). - /// A proof request may request multiple credentials from different schemas and different issuers. - /// All required schemas, public keys and revocation registries must be provided. - /// The proof request also contains nonce. - /// The proof contains either proof or self-attested attribute value for each requested attribute. + /// Either a corresponding credential with optionally revealed attributes or self-attested + /// attribute must be provided for each requested attribute (see + /// indy_prover_get_credentials_for_pool_req). A proof request may request multiple + /// credentials from different schemas and different issuers. All required schemas, public + /// keys and revocation registries must be provided. The proof request also contains nonce. + /// The proof contains either proof or self-attested attribute value for each requested + /// attribute. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). @@ -1335,10 +1340,10 @@ impl ProverController { /// { /// "name": string, /// "version": string, - /// "nonce": string, - a decimal number represented as a string (use `indy_generate_nonce` function to generate 80-bit number) - /// "requested_attributes": { // set of requested attributes - /// "": , // see below - /// ..., + /// "nonce": string, - a decimal number represented as a string (use + /// `indy_generate_nonce` function to generate 80-bit number) "requested_attributes" + /// : { // set of requested attributes "": , // see + /// below ..., /// }, /// "requested_predicates": { // set of requested predicates /// "": , // see below @@ -1347,24 +1352,24 @@ impl ProverController { /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation /// // for date in this interval for each attribute - /// // (applies to every attribute and predicate but can be overridden on attribute level) - /// // (can be overridden on attribute level) + /// // (applies to every attribute and predicate but can be overridden on + /// attribute level) // (can be overridden on attribute level) /// "ver": Optional - proof request version: /// - omit or "1.0" to use unqualified identifiers for restrictions /// - "2.0" to use fully qualified identifiers for restrictions /// } - /// requested_credentials_json: either a credential or self-attested attribute for each requested attribute - /// { + /// requested_credentials_json: either a credential or self-attested attribute for each + /// requested attribute { /// "self_attested_attributes": { /// "self_attested_attribute_referent": string /// }, /// "requested_attributes": { - /// "requested_attribute_referent_1": {"cred_id": string, "timestamp": Optional, revealed: }}, - /// "requested_attribute_referent_2": {"cred_id": string, "timestamp": Optional, revealed: }} - /// }, + /// "requested_attribute_referent_1": {"cred_id": string, "timestamp": + /// Optional, revealed: }}, "requested_attribute_referent_2": + /// {"cred_id": string, "timestamp": Optional, revealed: }} }, /// "requested_predicates": { - /// "requested_predicates_referent_1": {"cred_id": string, "timestamp": Optional }}, - /// } + /// "requested_predicates_referent_1": {"cred_id": string, "timestamp": + /// Optional }}, } /// } /// master_secret_id: the id of the master secret stored in the wallet /// schemas_json: all schemas participating in the proof request @@ -1392,16 +1397,18 @@ impl ProverController { /// "timestamp4": /// }, /// } - /// Note: use credential_id instead rev_reg_id in case proving several credentials from the same revocation registry. + /// Note: use credential_id instead rev_reg_id in case proving several credentials from the same + /// revocation registry. /// /// where /// attr_referent: Proof-request local identifier of requested attribute /// attr_info: Describes requested attribute /// { /// "name": Optional, // attribute name, (case insensitive and ignore spaces) - /// "names": Optional<[string, string]>, // attribute names, (case insensitive and ignore spaces) - /// // NOTE: should either be "name" or "names", not both and not none of them. - /// // Use "names" to specify several attributes that have to match a single credential. + /// "names": Optional<[string, string]>, // attribute names, (case insensitive and + /// ignore spaces) // NOTE: should either be + /// "name" or "names", not both and not none of them. + /// // Use "names" to specify several attributes that have to match a single credential. /// "restrictions": Optional, // see below /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation @@ -1433,23 +1440,24 @@ impl ProverController { /// "schema_version": , /// "issuer_did": , /// "cred_def_id": , - /// "rev_reg_id": , // "None" as string if not present - /// // the following keys can be used for every `attribute name` in credential. - /// "attr::::marker": "1", - to filter based on existence of a specific attribute - /// "attr::::value": , - to filter based on value of a specific attribute + /// "rev_reg_id": , // "None" as string if not + /// present // the following keys can be used for every `attribute name` in + /// credential. "attr::::marker": "1", - to filter based on + /// existence of a specific attribute "attr::::value": , - to filter based on value of a specific attribute /// /// #Returns /// Proof json /// For each requested attribute either a proof (with optionally revealed attribute value) or /// self-attested attribute value is provided. - /// Each proof is associated with a credential and corresponding schema_id, cred_def_id, rev_reg_id and timestamp. - /// There is also aggregated proof part common for all credential proofs. - /// { + /// Each proof is associated with a credential and corresponding schema_id, cred_def_id, + /// rev_reg_id and timestamp. There is also aggregated proof part common for all credential + /// proofs. { /// "requested_proof": { /// "revealed_attrs": { - /// "requested_attr1_id": {sub_proof_index: number, raw: string, encoded: string}, - /// "requested_attr4_id": {sub_proof_index: number: string, encoded: string}, - /// }, + /// "requested_attr1_id": {sub_proof_index: number, raw: string, encoded: + /// string}, "requested_attr4_id": {sub_proof_index: number: string, + /// encoded: string}, }, /// "revealed_attr_groups": { /// "requested_attr5_id": { /// "sub_proof_index": number, @@ -1495,10 +1503,8 @@ impl ProverController { rev_states: RevocationStates, ) -> IndyResult { trace!( - "create_proof > wallet_handle {:?} \ - proof_req {:?} requested_credentials {:?} \ - master_secret_id {:?} schemas {:?} \ - cred_defs {:?} rev_states {:?}", + "create_proof > wallet_handle {:?} proof_req {:?} requested_credentials {:?} \ + master_secret_id {:?} schemas {:?} cred_defs {:?} rev_states {:?}", wallet_handle, proof_req, requested_credentials, @@ -1564,27 +1570,31 @@ impl ProverController { /// Create revocation state for a credential that corresponds to a particular time. /// /// Note that revocation delta must cover the whole registry existence time. - /// You can use `from`: `0` and `to`: `needed_time` as parameters for building request to get correct revocation delta. + /// You can use `from`: `0` and `to`: `needed_time` as parameters for building request to get + /// correct revocation delta. /// - /// The resulting revocation state and provided timestamp can be saved and reused later with applying a new - /// revocation delta with `indy_update_revocation_state` function. - /// This new delta should be received with parameters: `from`: `timestamp` and `to`: `needed_time`. + /// The resulting revocation state and provided timestamp can be saved and reused later with + /// applying a new revocation delta with `indy_update_revocation_state` function. + /// This new delta should be received with parameters: `from`: `timestamp` and `to`: + /// `needed_time`. /// /// #Params - /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to read revocation tails (returned by `indy_open_blob_storage_reader`) - /// rev_reg_def_json: revocation registry definition json related to `rev_reg_id` in a credential + /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to + /// read revocation tails (returned by `indy_open_blob_storage_reader`) rev_reg_def_json: + /// revocation registry definition json related to `rev_reg_id` in a credential /// rev_reg_delta_json: revocation registry delta which covers the whole registry existence time /// timestamp: time represented as a total number of seconds from Unix Epoch. - /// cred_rev_id: user credential revocation id in revocation registry (match to `cred_rev_id` in a credential) + /// cred_rev_id: user credential revocation id in revocation registry (match to `cred_rev_id` in + /// a credential) /// /// #Returns /// revocation state json: /// { /// "rev_reg": , /// "witness": , (opaque type that contains data structures internal to Ursa. - /// It should not be parsed and are likely to change in future versions). - /// "timestamp" : integer + /// It should not be parsed and are likely to change in future + /// versions). "timestamp" : integer /// } /// /// #Errors @@ -1600,9 +1610,8 @@ impl ProverController { cred_rev_id: String, ) -> IndyResult { trace!( - "create_revocation_state > blob_storage_reader_handle {:?} \ - revoc_reg_def {:?} rev_reg_delta {:?} timestamp {:?} \ - cred_rev_id {:?}", + "create_revocation_state > blob_storage_reader_handle {:?} revoc_reg_def {:?} \ + rev_reg_delta {:?} timestamp {:?} cred_rev_id {:?}", blob_storage_reader_handle, revoc_reg_def, rev_reg_delta, @@ -1647,29 +1656,33 @@ impl ProverController { } /// Create a new revocation state for a credential based on a revocation state created before. - /// Note that provided revocation delta must cover the registry gap from based state creation until the specified time - /// (this new delta should be received with parameters: `from`: `state_timestamp` and `to`: `needed_time`). + /// Note that provided revocation delta must cover the registry gap from based state creation + /// until the specified time (this new delta should be received with parameters: `from`: + /// `state_timestamp` and `to`: `needed_time`). /// /// This function reduces the calculation time. /// - /// The resulting revocation state and provided timestamp can be saved and reused later by applying a new revocation delta again. + /// The resulting revocation state and provided timestamp can be saved and reused later by + /// applying a new revocation delta again. /// /// #Params - /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to read revocation tails (returned by `indy_open_blob_storage_reader`) - /// rev_state_json: revocation registry state json - /// rev_reg_def_json: revocation registry definition json related to `rev_reg_id` in a credential - /// rev_reg_delta_json: revocation registry definition delta which covers the gap form original `rev_state_json` creation till the requested timestamp - /// timestamp: time represented as a total number of seconds from Unix Epoch - /// cred_rev_id: user credential revocation id in revocation registry (match to `cred_rev_id` in a credential) + /// blob_storage_reader_handle: configuration of blob storage reader handle that will allow to + /// read revocation tails (returned by `indy_open_blob_storage_reader`) rev_state_json: + /// revocation registry state json rev_reg_def_json: revocation registry definition json + /// related to `rev_reg_id` in a credential rev_reg_delta_json: revocation registry + /// definition delta which covers the gap form original `rev_state_json` creation till the + /// requested timestamp timestamp: time represented as a total number of seconds from Unix + /// Epoch cred_rev_id: user credential revocation id in revocation registry (match to + /// `cred_rev_id` in a credential) /// /// #Returns /// revocation state json: /// { /// "rev_reg": , /// "witness": , (opaque type that contains data structures internal to Ursa. - /// It should not be parsed and are likely to change in future versions). - /// "timestamp" : integer + /// It should not be parsed and are likely to change in future + /// versions). "timestamp" : integer /// } /// /// #Errors @@ -1686,9 +1699,8 @@ impl ProverController { cred_rev_id: String, ) -> IndyResult { trace!( - "update_revocation_state > blob_storage_reader_handle {:?} \ - rev_state {:?} rev_reg_def {:?} rev_reg_delta {:?} \ - timestamp {:?} cred_rev_id {:?}", + "update_revocation_state > blob_storage_reader_handle {:?} rev_state {:?} rev_reg_def \ + {:?} rev_reg_delta {:?} timestamp {:?} cred_rev_id {:?}", blob_storage_reader_handle, rev_state, rev_reg_def, @@ -1773,8 +1785,7 @@ impl ProverController { interval: &Option, ) -> IndyResult> { trace!( - "_query_requested_credentials > wallet_handle {:?} \ - query_json {:?} predicate_info {:?}", + "_query_requested_credentials > wallet_handle {:?} query_json {:?} predicate_info {:?}", wallet_handle, query_json, predicate_info diff --git a/libvdrtools/src/controllers/anoncreds/tails.rs b/libvdrtools/src/controllers/anoncreds/tails.rs index 7f29a1eb87..a6e0522c99 100644 --- a/libvdrtools/src/controllers/anoncreds/tails.rs +++ b/libvdrtools/src/controllers/anoncreds/tails.rs @@ -2,17 +2,15 @@ use std::sync::Arc; use indy_api_types::errors::prelude::*; use log::trace; - use ursa::{ cl::{RevocationTailsAccessor, RevocationTailsGenerator, Tail}, errors::prelude::{UrsaCryptoError, UrsaCryptoErrorKind}, }; -use crate::utils::crypto::base58::{FromBase58, ToBase58}; - use crate::{ domain::anoncreds::revocation_registry_definition::RevocationRegistryDefinitionV1, services::BlobStorageService, + utils::crypto::base58::{FromBase58, ToBase58}, }; const TAILS_BLOB_TAG_SZ: u8 = 2; diff --git a/libvdrtools/src/controllers/anoncreds/verifier.rs b/libvdrtools/src/controllers/anoncreds/verifier.rs index a3542ddec7..bfde54ccd1 100644 --- a/libvdrtools/src/controllers/anoncreds/verifier.rs +++ b/libvdrtools/src/controllers/anoncreds/verifier.rs @@ -29,8 +29,9 @@ impl VerifierController { /// Verifies a proof (of multiple credential). /// All required schemas, public keys and revocation registries must be provided. /// - /// IMPORTANT: You must use *_id's (`schema_id`, `cred_def_id`, `rev_reg_id`) listed in `proof[identifiers]` - /// as the keys for corresponding `schemas_json`, `credential_defs_json`, `rev_reg_defs_json`, `rev_regs_json` objects. + /// IMPORTANT: You must use *_id's (`schema_id`, `cred_def_id`, `rev_reg_id`) listed in + /// `proof[identifiers]` as the keys for corresponding `schemas_json`, + /// `credential_defs_json`, `rev_reg_defs_json`, `rev_regs_json` objects. /// /// #Params /// wallet_handle: wallet handle (created by open_wallet). @@ -39,10 +40,10 @@ impl VerifierController { /// { /// "name": string, /// "version": string, - /// "nonce": string, - a decimal number represented as a string (use `indy_generate_nonce` function to generate 80-bit number) - /// "requested_attributes": { // set of requested attributes - /// "": , // see below - /// ..., + /// "nonce": string, - a decimal number represented as a string (use + /// `indy_generate_nonce` function to generate 80-bit number) "requested_attributes" + /// : { // set of requested attributes "": , // see + /// below ..., /// }, /// "requested_predicates": { // set of requested predicates /// "": , // see below @@ -60,10 +61,11 @@ impl VerifierController { /// { /// "requested_proof": { /// "revealed_attrs": { - /// "requested_attr1_id": {sub_proof_index: number, raw: string, encoded: string}, // NOTE: check that `encoded` value match to `raw` value on application level - /// "requested_attr4_id": {sub_proof_index: number: string, encoded: string}, // NOTE: check that `encoded` value match to `raw` value on application level - /// }, - /// "revealed_attr_groups": { + /// "requested_attr1_id": {sub_proof_index: number, raw: string, encoded: + /// string}, // NOTE: check that `encoded` value match to `raw` value on application level + /// "requested_attr4_id": {sub_proof_index: number: string, encoded: string}, // + /// NOTE: check that `encoded` value match to `raw` value on application level + /// }, "revealed_attr_groups": { /// "requested_attr5_id": { /// "sub_proof_index": number, /// "values": { @@ -71,8 +73,8 @@ impl VerifierController { /// "raw": string, /// "encoded": string /// } - /// }, // NOTE: check that `encoded` value match to `raw` value on application level - /// } + /// }, // NOTE: check that `encoded` value match to `raw` value on + /// application level } /// }, /// "unrevealed_attrs": { /// "requested_attr3_id": {sub_proof_index: number} @@ -127,9 +129,10 @@ impl VerifierController { /// attr_info: Describes requested attribute /// { /// "name": Optional, // attribute name, (case insensitive and ignore spaces) - /// "names": Optional<[string, string]>, // attribute names, (case insensitive and ignore spaces) - /// // NOTE: should either be "name" or "names", not both and not none of them. - /// // Use "names" to specify several attributes that have to match a single credential. + /// "names": Optional<[string, string]>, // attribute names, (case insensitive and + /// ignore spaces) // NOTE: should either be + /// "name" or "names", not both and not none of them. + /// // Use "names" to specify several attributes that have to match a single credential. /// "restrictions": Optional, // see below /// "non_revoked": Optional<>, // see below, /// // If specified prover must proof non-revocation @@ -161,10 +164,11 @@ impl VerifierController { /// "schema_version": , /// "issuer_did": , /// "cred_def_id": , - /// "rev_reg_id": , // "None" as string if not present - /// // the following keys can be used for every `attribute name` in credential. - /// "attr::::marker": "1", - to filter based on existence of a specific attribute - /// "attr::::value": , - to filter based on value of a specific attribute + /// "rev_reg_id": , // "None" as string if not + /// present // the following keys can be used for every `attribute name` in + /// credential. "attr::::marker": "1", - to filter based on + /// existence of a specific attribute "attr::::value": , - to filter based on value of a specific attribute /// /// /// #Returns @@ -184,9 +188,8 @@ impl VerifierController { rev_regs: RevocationRegistries, ) -> IndyResult { trace!( - "verify_proof > proof_req {:?} \ - proof {:?} schemas {:?} cred_defs {:?} \ - rev_reg_defs {:?} rev_regs {:?}", + "verify_proof > proof_req {:?} proof {:?} schemas {:?} cred_defs {:?} rev_reg_defs \ + {:?} rev_regs {:?}", proof_req, proof, schemas, @@ -221,7 +224,6 @@ impl VerifierController { /// /// #Returns /// nonce: generated number as a string - /// pub fn generate_nonce(&self) -> IndyResult { trace!("generate_nonce >"); diff --git a/libvdrtools/src/controllers/config.rs b/libvdrtools/src/controllers/config.rs index 0112690172..5e903c80f2 100644 --- a/libvdrtools/src/controllers/config.rs +++ b/libvdrtools/src/controllers/config.rs @@ -13,10 +13,10 @@ impl ConfigController { /// /// #Params /// config: { - /// "crypto_thread_pool_size": Optional - size of thread pool for the most expensive crypto operations. (4 by default) - /// "collect_backtrace": Optional - whether errors backtrace should be collected. - /// Capturing of backtrace can affect library performance. - /// NOTE: must be set before invocation of any other API functions. + /// "crypto_thread_pool_size": Optional - size of thread pool for the most expensive + /// crypto operations. (4 by default) "collect_backtrace": Optional - whether + /// errors backtrace should be collected. Capturing of backtrace can affect library + /// performance. NOTE: must be set before invocation of any other API functions. /// } /// /// #Errors diff --git a/libvdrtools/src/controllers/crypto.rs b/libvdrtools/src/controllers/crypto.rs index 326b19c345..32e61a79e4 100644 --- a/libvdrtools/src/controllers/crypto.rs +++ b/libvdrtools/src/controllers/crypto.rs @@ -40,10 +40,10 @@ impl CryptoController { /// wallet_handle: Wallet handle (created by open_wallet). /// key_json: Key information as json. Example: /// { - /// "seed": string, (optional) Seed that allows deterministic key creation (if not set random one will be created). - /// Can be UTF-8, base64 or hex string. - /// "crypto_type": string, // Optional (if not set then ed25519 curve is used); Currently only 'ed25519' value is supported for this field. - /// } + /// "seed": string, (optional) Seed that allows deterministic key creation (if not set + /// random one will be created). Can be UTF-8, base64 or hex + /// string. "crypto_type": string, // Optional (if not set then ed25519 curve is used); + /// Currently only 'ed25519' value is supported for this field. } /// /// #Returns /// verkey: Ver key of generated key pair, also used as key identifier @@ -82,9 +82,9 @@ impl CryptoController { /// #Params /// wallet_handle: wallet handler (created by open_wallet). - /// signer_vk: id (verkey) of message signer. The key must be created by calling indy_create_key or indy_create_and_store_my_did - /// message_raw: a pointer to first byte of message to be signed - /// message_len: a message length + /// signer_vk: id (verkey) of message signer. The key must be created by calling indy_create_key + /// or indy_create_and_store_my_did message_raw: a pointer to first byte of message to be + /// signed message_len: a message length /// /// #Returns /// a signature string @@ -163,7 +163,8 @@ impl CryptoController { Ok(res) } - /// Packs a message by encrypting the message and serializes it in a JWE-like format (Experimental) + /// Packs a message by encrypting the message and serializes it in a JWE-like format + /// (Experimental) /// /// Note to use DID keys with this function you can call indy_key_for_did to get key id (verkey) /// for specific DID. @@ -173,11 +174,12 @@ impl CryptoController { /// wallet_handle: wallet handle (created by open_wallet). /// message: a pointer to the first byte of the message to be packed /// message_len: the length of the message - /// receivers: a string in the format of a json list which will contain the list of receiver's keys - /// the message is being encrypted for. + /// receivers: a string in the format of a json list which will contain the list of receiver's + /// keys the message is being encrypted for. /// Example: /// "[, ]" - /// sender: the sender's verkey as a string When null pointer is used in this parameter, anoncrypt is used + /// sender: the sender's verkey as a string When null pointer is used in this parameter, + /// anoncrypt is used /// /// #Returns /// a JWE using authcrypt alg is defined below: @@ -188,18 +190,18 @@ impl CryptoController { /// "alg": "Authcrypt", /// "recipients": [ /// { - /// "encrypted_key": base64URLencode(libsodium.crypto_box(my_key, their_vk, cek, cek_iv)) - /// "header": { + /// "encrypted_key": base64URLencode(libsodium.crypto_box(my_key, their_vk, cek, + /// cek_iv)) "header": { /// "kid": "base58encode(recipient_verkey)", - /// "sender" : base64URLencode(libsodium.crypto_box_seal(their_vk, base58encode(sender_vk)), - /// "iv" : base64URLencode(cek_iv) + /// "sender" : base64URLencode(libsodium.crypto_box_seal(their_vk, + /// base58encode(sender_vk)), "iv" : base64URLencode(cek_iv) /// } /// }, /// ], /// })", /// "iv": , - /// "ciphertext": b64URLencode(encrypt_detached({'@type'...}, protected_value_encoded, iv, cek), - /// "tag": + /// "ciphertext": b64URLencode(encrypt_detached({'@type'...}, protected_value_encoded, iv, + /// cek), "tag": /// } /// /// Alternative example in using anoncrypt alg is defined below: @@ -218,8 +220,8 @@ impl CryptoController { /// ], /// })", /// "iv": b64URLencode(iv), - /// "ciphertext": b64URLencode(encrypt_detached({'@type'...}, protected_value_encoded, iv, cek), - /// "tag": b64URLencode(tag) + /// "ciphertext": b64URLencode(encrypt_detached({'@type'...}, protected_value_encoded, iv, + /// cek), "tag": b64URLencode(tag) /// } /// /// diff --git a/libvdrtools/src/controllers/did.rs b/libvdrtools/src/controllers/did.rs index ebdbe7f4fb..284bbb394e 100644 --- a/libvdrtools/src/controllers/did.rs +++ b/libvdrtools/src/controllers/did.rs @@ -1,6 +1,5 @@ use std::{collections::HashMap, sync::Arc}; -use crate::utils::crypto::base58::{FromBase58, ToBase58}; use indy_api_types::{errors::prelude::*, WalletHandle}; use indy_wallet::{RecordOptions, SearchOptions, WalletService}; @@ -21,6 +20,7 @@ use crate::{ pairwise::Pairwise, }, services::CryptoService, + utils::crypto::base58::{FromBase58, ToBase58}, }; pub struct DidController { @@ -52,14 +52,14 @@ impl DidController { /// Example: /// { /// "did": string, (optional; - /// if not provided and cid param is false then the first 16 bit of the verkey will be used as a new DID; - /// if not provided and cid is true then the full verkey will be used as a new DID; - /// if provided, then keys will be replaced - key rotation use case) - /// "seed": string, (optional) Seed that allows deterministic did creation (if not set random one will be created). - /// Can be UTF-8, base64 or hex string. - /// "crypto_type": string, (optional; if not set then ed25519 curve is used; - /// currently only 'ed25519' value is supported for this field) - /// "cid": bool, (optional; if not set then false is used;) + /// if not provided and cid param is false then the first 16 bit of the verkey will + /// be used as a new DID; if not provided and cid is true then the full verkey + /// will be used as a new DID; if provided, then keys will be replaced - key + /// rotation use case) "seed": string, (optional) Seed that allows deterministic did + /// creation (if not set random one will be created). Can be + /// UTF-8, base64 or hex string. "crypto_type": string, (optional; if not set then + /// ed25519 curve is used; currently only 'ed25519' value is supported for + /// this field) "cid": bool, (optional; if not set then false is used;) /// "ledger_type": string, (optional) type of the ledger to create fully qualified did. /// "method_name": string, (optional) method name to create fully qualified did. /// } @@ -94,8 +94,8 @@ impl DidController { Err(err_msg( IndyErrorKind::DIDAlreadyExists, format!( - "DID \"{}\" already exists but with different Verkey. \ - You should specify Seed used for initial generation", + "DID \"{}\" already exists but with different Verkey. You should specify \ + Seed used for initial generation", did.did.0 ), ))?; @@ -126,9 +126,9 @@ impl DidController { /// did: target did to rotate keys. /// key_info: key information as json. Example: /// { - /// "seed": string, (optional) Seed that allows deterministic key creation (if not set random one will be created). - /// Can be UTF-8, base64 or hex string. - /// "crypto_type": string, (optional; if not set then ed25519 curve is used; + /// "seed": string, (optional) Seed that allows deterministic key creation (if not set + /// random one will be created). Can be UTF-8, base64 or hex + /// string. "crypto_type": string, (optional; if not set then ed25519 curve is used; /// currently only 'ed25519' value is supported for this field) /// } /// @@ -292,9 +292,9 @@ impl DidController { /// did_with_meta: { /// "did": string - DID stored in the wallet, /// "verkey": string - The DIDs transport key (ver key, key id), - /// "tempVerkey": string - Temporary DIDs transport key (ver key, key id), exist only during the rotation of the keys. - /// After rotation is done, it becomes a new verkey. - /// "metadata": string - The meta information stored with the DID + /// "tempVerkey": string - Temporary DIDs transport key (ver key, key id), exist only during + /// the rotation of the keys. After rotation is done, it becomes a + /// new verkey. "metadata": string - The meta information stored with the DID /// } /// /// #Errors @@ -525,8 +525,8 @@ impl DidController { /// wallet_handle: Wallet handle (created by open_wallet). /// did - The DID to resolve endpoint. - /// address - The DIDs endpoint address. indy-node and indy-plenum restrict this to ip_address:port - /// transport_key - The DIDs transport key (ver key, key id). + /// address - The DIDs endpoint address. indy-node and indy-plenum restrict this to + /// ip_address:port transport_key - The DIDs transport key (ver key, key id). /// /// #Returns /// @@ -610,7 +610,8 @@ impl DidController { /// did - The DID to retrieve metadata. /// /// #Returns - /// metadata - The meta information stored with the DID; Can be null if no metadata was saved for this DID. + /// metadata - The meta information stored with the DID; Can be null if no metadata was saved + /// for this DID. /// /// #Errors /// Common* @@ -799,8 +800,8 @@ impl DidController { get_nym_reply_result: IndyResult, ) -> IndyResult { trace!( - "get_nym_ack_process_and_store_their_did > \ - wallet_handle {:?} get_nym_reply_result {:?}", + "get_nym_ack_process_and_store_their_did > wallet_handle {:?} get_nym_reply_result \ + {:?}", wallet_handle, get_nym_reply_result ); @@ -881,8 +882,8 @@ impl DidController { get_attrib_reply_result: IndyResult, ) -> IndyResult { trace!( - "_get_attrib_ack_process_store_endpoint_to_wallet > \ - wallet_handle {:?} get_attrib_reply_result {:?}", + "_get_attrib_ack_process_store_endpoint_to_wallet > wallet_handle {:?} \ + get_attrib_reply_result {:?}", wallet_handle, get_attrib_reply_result ); diff --git a/libvdrtools/src/controllers/mod.rs b/libvdrtools/src/controllers/mod.rs index d9cb936566..2d6cc00516 100644 --- a/libvdrtools/src/controllers/mod.rs +++ b/libvdrtools/src/controllers/mod.rs @@ -11,7 +11,6 @@ mod wallet; pub use anoncreds::{ CredentialDefinitionId, IssuerController, ProverController, VerifierController, }; - pub(crate) use blob_storage::BlobStorageController; pub(crate) use config::ConfigController; pub(crate) use crypto::CryptoController; diff --git a/libvdrtools/src/controllers/non_secrets.rs b/libvdrtools/src/controllers/non_secrets.rs index 733b3d49db..3ae87a6a26 100644 --- a/libvdrtools/src/controllers/non_secrets.rs +++ b/libvdrtools/src/controllers/non_secrets.rs @@ -46,8 +46,7 @@ impl NonSecretsController { tags: Option, ) -> IndyResult<()> { trace!( - "add_record > wallet_handle {:?} type_ {:?} \ - id {:?} value {:?} tags {:?}", + "add_record > wallet_handle {:?} type_ {:?} id {:?} value {:?} tags {:?}", wallet_handle, type_, id, @@ -88,8 +87,7 @@ impl NonSecretsController { value: String, ) -> IndyResult<()> { trace!( - "update_record_value > wallet_handle {:?} type_ {:?} \ - id {:?} value {:?}", + "update_record_value > wallet_handle {:?} type_ {:?} id {:?} value {:?}", wallet_handle, type_, id, @@ -132,8 +130,7 @@ impl NonSecretsController { tags: Tags, ) -> IndyResult<()> { trace!( - "update_record_tags > wallet_handle {:?} type_ {:?} \ - id {:?} tags {:?}", + "update_record_tags > wallet_handle {:?} type_ {:?} id {:?} tags {:?}", wallet_handle, type_, id, @@ -178,8 +175,7 @@ impl NonSecretsController { tags: Tags, ) -> IndyResult<()> { trace!( - "add_record_tags > wallet_handle {:?} type_ {:?} \ - id {:?} tags {:?}", + "add_record_tags > wallet_handle {:?} type_ {:?} id {:?} tags {:?}", wallet_handle, type_, id, @@ -214,8 +210,7 @@ impl NonSecretsController { tag_names_json: String, ) -> IndyResult<()> { trace!( - "delete_record_tags > wallet_handle {:?} type_ {:?} \ - id {:?} tag_names_json {:?}", + "delete_record_tags > wallet_handle {:?} type_ {:?} id {:?} tag_names_json {:?}", wallet_handle, type_, id, @@ -298,8 +293,7 @@ impl NonSecretsController { options_json: String, ) -> IndyResult { trace!( - "get_record > wallet_handle {:?} type_ {:?} \ - id {:?} options_json {:?}", + "get_record > wallet_handle {:?} type_ {:?} id {:?} options_json {:?}", wallet_handle, type_, id, @@ -364,8 +358,7 @@ impl NonSecretsController { options_json: String, ) -> IndyResult { trace!( - "open_search > wallet_handle {:?} type_ {:?} \ - query_json {:?} options_json {:?}", + "open_search > wallet_handle {:?} type_ {:?} query_json {:?} options_json {:?}", wallet_handle, type_, query_json, diff --git a/libvdrtools/src/controllers/pairwise.rs b/libvdrtools/src/controllers/pairwise.rs index 11a05bb207..9d8833093b 100644 --- a/libvdrtools/src/controllers/pairwise.rs +++ b/libvdrtools/src/controllers/pairwise.rs @@ -75,8 +75,7 @@ impl PairwiseController { metadata: Option, ) -> IndyResult<()> { trace!( - "create_pairwise > wallet_handle {:?} \ - their_did {:?} my_did {:?} metadata {:?}", + "create_pairwise > wallet_handle {:?} their_did {:?} my_did {:?} metadata {:?}", wallet_handle, their_did, my_did, diff --git a/libvdrtools/src/controllers/wallet.rs b/libvdrtools/src/controllers/wallet.rs index a5e45dcea0..d3876c140b 100644 --- a/libvdrtools/src/controllers/wallet.rs +++ b/libvdrtools/src/controllers/wallet.rs @@ -1,21 +1,17 @@ use std::sync::Arc; // use async_std::task::spawn_blocking; - use indy_api_types::{ domain::wallet::{Config, Credentials, ExportConfig, KeyConfig, Record}, errors::prelude::*, WalletHandle, }; - use indy_utils::crypto::{ chacha20poly1305_ietf, chacha20poly1305_ietf::Key as MasterKey, randombytes, }; - -use crate::utils::crypto::base58::ToBase58; use indy_wallet::{KeyDerivationData, WalletService}; -use crate::services::CryptoService; +use crate::{services::CryptoService, utils::crypto::base58::ToBase58}; pub struct WalletController { wallet_service: Arc, @@ -42,10 +38,10 @@ impl WalletController { /// Configured storage uses this identifier to lookup exact wallet data placement. /// "storage_type": optional, Type of the wallet storage. Defaults to 'default'. /// 'Default' storage type allows to store wallet data in the local file. - /// Custom storage types can be registered with indy_register_wallet_storage call. - /// "storage_config": optional, Storage configuration json. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type configuration is: + /// Custom storage types can be registered with indy_register_wallet_storage + /// call. "storage_config": optional, Storage configuration json. Storage type + /// defines set of supported keys. Can be optional if storage supports + /// default configuration. For 'default' storage type configuration is: /// { /// "path": optional, Path to the directory with wallet files. /// Defaults to $HOME/.indy_client/wallet. @@ -55,16 +51,16 @@ impl WalletController { /// credentials: Wallet credentials json /// { /// "key": string, Key or passphrase used for wallet key derivation. - /// Look to key_derivation_method param for information about supported key derivation methods. - /// "storage_credentials": optional Credentials for wallet storage. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type should be empty. - /// "key_derivation_method": optional Algorithm to use for wallet key derivation: - /// ARGON2I_MOD - derive secured wallet master key (used by default) - /// ARGON2I_INT - derive secured wallet master key (less secured but faster) - /// RAW - raw wallet key master provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// } + /// Look to key_derivation_method param for information about supported key + /// derivation methods. "storage_credentials": optional Credentials for wallet + /// storage. Storage type defines set of supported keys. Can be + /// optional if storage supports default configuration. For + /// 'default' storage type should be empty. "key_derivation_method": optional + /// Algorithm to use for wallet key derivation: ARGON2I_MOD - + /// derive secured wallet master key (used by default) ARGON2I_INT + /// - derive secured wallet master key (less secured but faster) + /// RAW - raw wallet key master provided (skip derivation). + /// RAW keys can be generated with indy_generate_wallet_key call } /// /// #Returns /// err: Error code @@ -106,41 +102,42 @@ impl WalletController { /// Configured storage uses this identifier to lookup exact wallet data placement. /// "storage_type": optional, Type of the wallet storage. Defaults to 'default'. /// 'Default' storage type allows to store wallet data in the local file. - /// Custom storage types can be registered with indy_register_wallet_storage call. - /// "storage_config": optional, Storage configuration json. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type configuration is: - /// { + /// Custom storage types can be registered with + /// indy_register_wallet_storage call. "storage_config": optional, Storage + /// configuration json. Storage type defines set of supported keys. + /// Can be optional if storage supports default configuration. For + /// 'default' storage type configuration is: { /// "path": optional, Path to the directory with wallet files. /// Defaults to $HOME/.indy_client/wallet. /// Wallet will be stored in the file {path}/{id}/sqlite.db /// } - /// "cache": optional, Cache configuration json. If omitted the cache is disabled (default). - /// { + /// "cache": optional, Cache configuration json. If omitted the cache is disabled + /// (default). { /// "size": optional, Number of items in cache, - /// "entities": List, Types of items being cached. eg. ["vdrtools::Did", "vdrtools::Key"] - /// "algorithm" optional, cache algorithm, defaults to lru, which is the only one supported for now. - /// } + /// "entities": List, Types of items being cached. eg. ["vdrtools::Did", + /// "vdrtools::Key"] "algorithm" optional, cache algorithm, defaults to + /// lru, which is the only one supported for now. } /// } /// credentials: Wallet credentials json /// { /// "key": string, Key or passphrase used for wallet key derivation. - /// Look to key_derivation_method param for information about supported key derivation methods. - /// "rekey": optional, If present than wallet master key will be rotated to a new one. - /// "storage_credentials": optional Credentials for wallet storage. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type should be empty. - /// "key_derivation_method": optional Algorithm to use for wallet key derivation: - /// ARGON2I_MOD - derive secured wallet master key (used by default) - /// ARGON2I_INT - derive secured wallet master key (less secured but faster) - /// RAW - raw wallet key master provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// "rekey_derivation_method": optional Algorithm to use for wallet rekey derivation: - /// ARGON2I_MOD - derive secured wallet master rekey (used by default) - /// ARGON2I_INT - derive secured wallet master rekey (less secured but faster) - /// RAW - raw wallet rekey master provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// } + /// Look to key_derivation_method param for information about supported key + /// derivation methods. "rekey": optional, If present than wallet master key + /// will be rotated to a new one. "storage_credentials": optional Credentials + /// for wallet storage. Storage type defines set of supported keys. + /// Can be optional if storage supports default configuration. + /// For 'default' storage type should be empty. "key_derivation_method": + /// optional Algorithm to use for wallet key derivation: + /// ARGON2I_MOD - derive secured wallet master key (used by default) + /// ARGON2I_INT - derive secured wallet master key (less secured but faster) + /// RAW - raw wallet key master provided (skip derivation). + /// RAW keys can be generated with indy_generate_wallet_key call + /// "rekey_derivation_method": optional Algorithm to use for wallet rekey + /// derivation: ARGON2I_MOD - derive secured wallet master rekey + /// (used by default) ARGON2I_INT - derive secured wallet master + /// rekey (less secured but faster) RAW - raw wallet rekey master + /// provided (skip derivation). RAW keys can be generated + /// with indy_generate_wallet_key call } /// /// #Returns /// err: Error code @@ -209,10 +206,10 @@ impl WalletController { /// Configured storage uses this identifier to lookup exact wallet data placement. /// "storage_type": optional, Type of the wallet storage. Defaults to 'default'. /// 'Default' storage type allows to store wallet data in the local file. - /// Custom storage types can be registered with indy_register_wallet_storage call. - /// "storage_config": optional, Storage configuration json. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type configuration is: + /// Custom storage types can be registered with indy_register_wallet_storage + /// call. "storage_config": optional, Storage configuration json. Storage type + /// defines set of supported keys. Can be optional if storage supports + /// default configuration. For 'default' storage type configuration is: /// { /// "path": optional, Path to the directory with wallet files. /// Defaults to $HOME/.indy_client/wallet. @@ -222,16 +219,16 @@ impl WalletController { /// credentials: Wallet credentials json /// { /// "key": string, Key or passphrase used for wallet key derivation. - /// Look to key_derivation_method param for information about supported key derivation methods. - /// "storage_credentials": optional Credentials for wallet storage. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type should be empty. - /// "key_derivation_method": optional Algorithm to use for wallet key derivation: - /// ARGON2I_MOD - derive secured wallet master key (used by default) - /// ARGON2I_INT - derive secured wallet master key (less secured but faster) - /// RAW - raw wallet key master provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// } + /// Look to key_derivation_method param for information about supported key + /// derivation methods. "storage_credentials": optional Credentials for wallet + /// storage. Storage type defines set of supported keys. Can be + /// optional if storage supports default configuration. For + /// 'default' storage type should be empty. "key_derivation_method": optional + /// Algorithm to use for wallet key derivation: ARGON2I_MOD - + /// derive secured wallet master key (used by default) + /// ARGON2I_INT - derive secured wallet master key (less secured but faster) + /// RAW - raw wallet key master provided (skip derivation). + /// RAW keys can be generated with indy_generate_wallet_key call } /// /// #Returns /// Error code @@ -271,13 +268,13 @@ impl WalletController { /// { /// "path": , Path of the file that contains exported wallet content /// "key": , Key or passphrase used for wallet export key derivation. - /// Look to key_derivation_method param for information about supported key derivation methods. - /// "key_derivation_method": optional Algorithm to use for wallet export key derivation: - /// ARGON2I_MOD - derive secured export key (used by default) - /// ARGON2I_INT - derive secured export key (less secured but faster) - /// RAW - raw export key provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// } + /// Look to key_derivation_method param for information about supported key + /// derivation methods. "key_derivation_method": optional Algorithm to use for + /// wallet export key derivation: ARGON2I_MOD - derive secured + /// export key (used by default) ARGON2I_INT - derive secured + /// export key (less secured but faster) RAW - raw export key + /// provided (skip derivation). RAW keys can be generated + /// with indy_generate_wallet_key call } /// /// #Returns /// Error code @@ -323,10 +320,10 @@ impl WalletController { /// Configured storage uses this identifier to lookup exact wallet data placement. /// "storage_type": optional, Type of the wallet storage. Defaults to 'default'. /// 'Default' storage type allows to store wallet data in the local file. - /// Custom storage types can be registered with indy_register_wallet_storage call. - /// "storage_config": optional, Storage configuration json. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type configuration is: + /// Custom storage types can be registered with indy_register_wallet_storage + /// call. "storage_config": optional, Storage configuration json. Storage type + /// defines set of supported keys. Can be optional if storage supports + /// default configuration. For 'default' storage type configuration is: /// { /// "path": optional, Path to the directory with wallet files. /// Defaults to $HOME/.indy_client/wallet. @@ -336,16 +333,16 @@ impl WalletController { /// credentials: Wallet credentials json /// { /// "key": string, Key or passphrase used for wallet key derivation. - /// Look to key_derivation_method param for information about supported key derivation methods. - /// "storage_credentials": optional Credentials for wallet storage. Storage type defines set of supported keys. - /// Can be optional if storage supports default configuration. - /// For 'default' storage type should be empty. - /// "key_derivation_method": optional Algorithm to use for wallet key derivation: - /// ARGON2I_MOD - derive secured wallet master key (used by default) - /// ARGON2I_INT - derive secured wallet master key (less secured but faster) - /// RAW - raw wallet key master provided (skip derivation). - /// RAW keys can be generated with indy_generate_wallet_key call - /// } + /// Look to key_derivation_method param for information about supported key + /// derivation methods. "storage_credentials": optional Credentials for wallet + /// storage. Storage type defines set of supported keys. Can be + /// optional if storage supports default configuration. For + /// 'default' storage type should be empty. "key_derivation_method": optional + /// Algorithm to use for wallet key derivation: ARGON2I_MOD - + /// derive secured wallet master key (used by default) + /// ARGON2I_INT - derive secured wallet master key (less secured but faster) + /// RAW - raw wallet key master provided (skip derivation). + /// RAW keys can be generated with indy_generate_wallet_key call } /// import_config: Import settings json. /// { /// "path": , path of the file that contains exported wallet content @@ -406,13 +403,14 @@ impl WalletController { /// Generate wallet master key. /// Returned key is compatible with "RAW" key derivation method. - /// It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. + /// It allows to avoid expensive key derivation for use cases when wallet keys can be stored in + /// a secure enclave. /// /// #Params /// config: (optional) key configuration json. /// { - /// "seed": string, (optional) Seed that allows deterministic key creation (if not set random one will be created). - /// Can be UTF-8, base64 or hex string. + /// "seed": string, (optional) Seed that allows deterministic key creation (if not set random + /// one will be created). Can be UTF-8, base64 or hex string. /// } /// /// #Returns diff --git a/libvdrtools/src/domain/anoncreds/credential.rs b/libvdrtools/src/domain/anoncreds/credential.rs index dd0a07905a..3e7a51ebe6 100644 --- a/libvdrtools/src/domain/anoncreds/credential.rs +++ b/libvdrtools/src/domain/anoncreds/credential.rs @@ -1,8 +1,7 @@ use std::collections::HashMap; -use ursa::cl::{CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness}; - use indy_api_types::validation::Validatable; +use ursa::cl::{CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness}; use super::{ credential_definition::CredentialDefinitionId, @@ -76,7 +75,10 @@ impl Validatable for Credential { self.values.validate()?; if self.rev_reg_id.is_some() && (self.witness.is_none() || self.rev_reg.is_none()) { - return Err(String::from("Credential validation failed: `witness` and `rev_reg` must be passed for revocable Credential")); + return Err(String::from( + "Credential validation failed: `witness` and `rev_reg` must be passed for \ + revocable Credential", + )); } if self.values.0.is_empty() { diff --git a/libvdrtools/src/domain/anoncreds/credential_definition.rs b/libvdrtools/src/domain/anoncreds/credential_definition.rs index e3221a4e01..acf9766d4b 100644 --- a/libvdrtools/src/domain/anoncreds/credential_definition.rs +++ b/libvdrtools/src/domain/anoncreds/credential_definition.rs @@ -1,24 +1,24 @@ +use std::collections::HashMap; + use indy_api_types::{ errors::{IndyErrorKind, IndyResult}, + validation::Validatable, IndyError, }; -use std::collections::HashMap; - -use indy_api_types::validation::Validatable; - -use super::indy_identifiers; use ursa::cl::{ CredentialKeyCorrectnessProof, CredentialPrimaryPublicKey, CredentialPrivateKey, CredentialRevocationPublicKey, }; -use crate::utils::qualifier; - -use super::super::{ - anoncreds::{schema::SchemaId, DELIMITER}, - crypto::did::DidValue, - ledger::request::ProtocolVersion, +use super::{ + super::{ + anoncreds::{schema::SchemaId, DELIMITER}, + crypto::did::DidValue, + ledger::request::ProtocolVersion, + }, + indy_identifiers, }; +use crate::utils::qualifier; pub const CL_SIGNATURE_TYPE: &str = "CL"; @@ -260,7 +260,8 @@ impl CredentialDefinitionId { } if parts.len() == 16 { - // creddef:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag + // creddef:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov: + // NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag warn!("Deprecated format of FQ CredDef ID is used (creddef: suffix)"); let did = parts[2..5].join(DELIMITER); let signature_type = parts[6].to_string(); diff --git a/libvdrtools/src/domain/anoncreds/credential_offer.rs b/libvdrtools/src/domain/anoncreds/credential_offer.rs index a4ff5d3365..715fdf21ba 100644 --- a/libvdrtools/src/domain/anoncreds/credential_offer.rs +++ b/libvdrtools/src/domain/anoncreds/credential_offer.rs @@ -1,9 +1,8 @@ +use indy_api_types::validation::Validatable; use ursa::cl::{CredentialKeyCorrectnessProof, Nonce}; use super::{credential_definition::CredentialDefinitionId, schema::SchemaId}; -use indy_api_types::validation::Validatable; - #[derive(Debug, Deserialize, Serialize)] pub struct CredentialOffer { pub schema_id: SchemaId, diff --git a/libvdrtools/src/domain/anoncreds/credential_request.rs b/libvdrtools/src/domain/anoncreds/credential_request.rs index e410e62c61..ca804b8c88 100644 --- a/libvdrtools/src/domain/anoncreds/credential_request.rs +++ b/libvdrtools/src/domain/anoncreds/credential_request.rs @@ -1,12 +1,10 @@ -use super::super::crypto::did::DidValue; +use indy_api_types::validation::Validatable; use ursa::cl::{ BlindedCredentialSecrets, BlindedCredentialSecretsCorrectnessProof, CredentialSecretsBlindingFactors, Nonce, }; -use super::credential_definition::CredentialDefinitionId; - -use indy_api_types::validation::Validatable; +use super::{super::crypto::did::DidValue, credential_definition::CredentialDefinitionId}; #[derive(Debug, Serialize, Deserialize)] pub struct CredentialRequest { diff --git a/libvdrtools/src/domain/anoncreds/indy_identifiers.rs b/libvdrtools/src/domain/anoncreds/indy_identifiers.rs index 455d160e2b..9b5fcba751 100644 --- a/libvdrtools/src/domain/anoncreds/indy_identifiers.rs +++ b/libvdrtools/src/domain/anoncreds/indy_identifiers.rs @@ -1,9 +1,10 @@ +use lazy_static::lazy_static; +use regex::Regex; + use super::{ super::crypto::did::DidValue, credential_definition::CredentialDefinitionId, revocation_registry_definition::CL_ACCUM, schema::SchemaId, }; -use lazy_static::lazy_static; -use regex::Regex; const NAMESPACE_RE: &str = r"[a-z][a-z0-9_:-]*"; const DID_RE: &str = r"[1-9A-HJ-NP-Za-km-z]*"; //base58 @@ -68,8 +69,10 @@ pub fn try_parse_indy_rev_reg( let creddef_name_re = r"[^/]*"; let tag_re = r"[^/]*"; let schema_ref_re = &*SCHEMA_REF_RE; - let id_re = format!("^(did:indy(:{NAMESPACE_RE})?:{DID_RE})\ - /anoncreds/v0/REV_REG_DEF/{schema_ref_re}/({creddef_name_re})/({tag_re})$"); + let id_re = format!( + "^(did:indy(:{NAMESPACE_RE})?:{DID_RE})/anoncreds/v0/REV_REG_DEF/{schema_ref_re}/\ + ({creddef_name_re})/({tag_re})$" + ); let id_re = Regex::new(id_re.as_str()).unwrap(); if let Some(captures) = id_re.captures(id) { @@ -110,9 +113,11 @@ fn test_try_parse_valid_indy_creddefid_works() { assert_eq!(schema_seq_no, "1".to_owned()); assert_eq!(tag, "tag".to_owned()); - let (did, schema_ref, tag) = - try_parse_indy_creddef_id( - "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/tag").unwrap(); + let (did, schema_ref, tag) = try_parse_indy_creddef_id( + "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/\ + anoncreds/v0/SCHEMA/gvt/1.0/tag", + ) + .unwrap(); assert_eq!(did, "did:indy:NcYxiDXkpYi6ov5FcYDi1e".to_owned()); assert_eq!( schema_ref, @@ -134,10 +139,17 @@ fn test_try_parse_valid_indy_revreg_works() { ); assert_eq!(tag, "TAG1".to_owned()); - let (did, creddef, _, tag) = - try_parse_indy_rev_reg( - "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/creddef_name/TAG1").unwrap(); + let (did, creddef, _, tag) = try_parse_indy_rev_reg( + "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/\ + anoncreds/v0/SCHEMA/gvt/1.0/creddef_name/TAG1", + ) + .unwrap(); assert_eq!(did.0, "did:indy:NcYxiDXkpYi6ov5FcYDi1e".to_owned()); - assert_eq!(creddef.0, "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/creddef_name".to_owned()); + assert_eq!( + creddef.0, + "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/\ + anoncreds/v0/SCHEMA/gvt/1.0/creddef_name" + .to_owned() + ); assert_eq!(tag, "TAG1".to_owned()); } diff --git a/libvdrtools/src/domain/anoncreds/master_secret.rs b/libvdrtools/src/domain/anoncreds/master_secret.rs index 965290e216..72fb0f9293 100644 --- a/libvdrtools/src/domain/anoncreds/master_secret.rs +++ b/libvdrtools/src/domain/anoncreds/master_secret.rs @@ -1,6 +1,5 @@ -use ursa::cl::MasterSecret as CryptoMasterSecret; - use indy_api_types::validation::Validatable; +use ursa::cl::MasterSecret as CryptoMasterSecret; #[derive(Debug, Deserialize, Serialize)] pub struct MasterSecret { diff --git a/libvdrtools/src/domain/anoncreds/proof.rs b/libvdrtools/src/domain/anoncreds/proof.rs index 7879788641..6b9b3dbebe 100644 --- a/libvdrtools/src/domain/anoncreds/proof.rs +++ b/libvdrtools/src/domain/anoncreds/proof.rs @@ -1,12 +1,12 @@ use std::collections::HashMap; +use indy_api_types::validation::Validatable; use ursa::cl::Proof as CryptoProof; use super::{ credential_definition::CredentialDefinitionId, revocation_registry_definition::RevocationRegistryId, schema::SchemaId, }; -use indy_api_types::validation::Validatable; #[derive(Debug, Serialize, Deserialize)] pub struct Proof { diff --git a/libvdrtools/src/domain/anoncreds/proof_request.rs b/libvdrtools/src/domain/anoncreds/proof_request.rs index cad13d1a9e..0a67c1f417 100644 --- a/libvdrtools/src/domain/anoncreds/proof_request.rs +++ b/libvdrtools/src/domain/anoncreds/proof_request.rs @@ -1,18 +1,16 @@ use std::{collections::HashMap, fmt}; -use ursa::cl::Nonce; use indy_api_types::validation::Validatable; - -use crate::utils::wql::Query; use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; +use ursa::cl::Nonce; use super::{ super::crypto::did::DidValue, credential::Credential, credential_definition::CredentialDefinitionId, revocation_registry_definition::RevocationRegistryId, schema::SchemaId, }; -use crate::utils::qualifier; +use crate::utils::{qualifier, wql::Query}; #[derive(Debug, Deserialize, Serialize)] pub struct ProofRequestPayload { @@ -206,7 +204,10 @@ impl Validatable for ProofRequest { let version = self.version(); if value.requested_attributes.is_empty() && value.requested_predicates.is_empty() { - return Err(String::from("Proof Request validation failed: both `requested_attributes` and `requested_predicates` are empty")); + return Err(String::from( + "Proof Request validation failed: both `requested_attributes` and \ + `requested_predicates` are empty", + )); } for (_, requested_attribute) in value.requested_attributes.iter() { @@ -228,7 +229,11 @@ impl Validatable for ProofRequest { } if has_name && has_names { - return Err(format!("Proof request validation failed: there is a requested attribute with both name and names: {:?}", requested_attribute)); + return Err(format!( + "Proof request validation failed: there is a requested attribute with both \ + name and names: {:?}", + requested_attribute + )); } if let Some(ref restrictions) = requested_attribute.restrictions { @@ -372,8 +377,12 @@ fn _check_restriction( && Credential::QUALIFIABLE_TAGS.contains(&tag_name) && qualifier::is_fully_qualified(tag_value) { - return Err("Proof Request validation failed: fully qualified identifiers can not be used for Proof Request of the first version. \ - Please, set \"ver\":\"2.0\" to use fully qualified identifiers.".to_string()); + return Err( + "Proof Request validation failed: fully qualified identifiers can not be used for \ + Proof Request of the first version. Please, set \"ver\":\"2.0\" to use fully \ + qualified identifiers." + .to_string(), + ); } Ok(()) } @@ -431,8 +440,12 @@ mod tests { const CRED_DEF_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/1/tag"; const CRED_DEF_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:3:CL:1:tag"; - const REV_REG_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/tag/TAG_1"; - const REV_REG_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1"; + const REV_REG_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/\ + REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/\ + v0/SCHEMA/gvt/1.0/tag/TAG_1"; + const REV_REG_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:\ + CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:\ + TAG_1"; #[test] fn proof_request_to_unqualified() { diff --git a/libvdrtools/src/domain/anoncreds/requested_credential.rs b/libvdrtools/src/domain/anoncreds/requested_credential.rs index 103f88e6c1..b135386d68 100644 --- a/libvdrtools/src/domain/anoncreds/requested_credential.rs +++ b/libvdrtools/src/domain/anoncreds/requested_credential.rs @@ -28,7 +28,10 @@ impl Validatable for RequestedCredentials { && self.requested_attributes.is_empty() && self.requested_predicates.is_empty() { - return Err(String::from("Requested Credentials validation failed: `self_attested_attributes` and `requested_attributes` and `requested_predicates` are empty")); + return Err(String::from( + "Requested Credentials validation failed: `self_attested_attributes` and \ + `requested_attributes` and `requested_predicates` are empty", + )); } Ok(()) } diff --git a/libvdrtools/src/domain/anoncreds/revocation_registry.rs b/libvdrtools/src/domain/anoncreds/revocation_registry.rs index 549f81b988..330166061e 100644 --- a/libvdrtools/src/domain/anoncreds/revocation_registry.rs +++ b/libvdrtools/src/domain/anoncreds/revocation_registry.rs @@ -1,8 +1,7 @@ -use ursa::cl::RevocationRegistry as CryptoRevocationRegistry; - use std::collections::HashMap; use indy_api_types::validation::Validatable; +use ursa::cl::RevocationRegistry as CryptoRevocationRegistry; use super::revocation_registry_definition::RevocationRegistryId; diff --git a/libvdrtools/src/domain/anoncreds/revocation_registry_definition.rs b/libvdrtools/src/domain/anoncreds/revocation_registry_definition.rs index 7548cb00d6..dcd678739d 100644 --- a/libvdrtools/src/domain/anoncreds/revocation_registry_definition.rs +++ b/libvdrtools/src/domain/anoncreds/revocation_registry_definition.rs @@ -1,7 +1,9 @@ -use indy_api_types::errors::{err_msg, IndyErrorKind, IndyResult}; use std::collections::{HashMap, HashSet}; -use indy_api_types::validation::Validatable; +use indy_api_types::{ + errors::{err_msg, IndyErrorKind, IndyResult}, + validation::Validatable, +}; use lazy_static::lazy_static; use regex::Regex; use ursa::cl::{RevocationKeyPrivate, RevocationKeyPublic}; @@ -10,14 +12,17 @@ use super::{ super::crypto::did::DidValue, credential_definition::CredentialDefinitionId, indy_identifiers, DELIMITER, }; - use crate::utils::qualifier; pub const CL_ACCUM: &str = "CL_ACCUM"; pub const REV_REG_DEG_MARKER: &str = "4"; lazy_static! { - static ref QUALIFIED_REV_REG_ID: Regex = Regex::new("(^revreg:(?P[a-z0-9]+):)?(?P.+):4:(?P.+):(?P.+):(?P.+)$").unwrap(); + static ref QUALIFIED_REV_REG_ID: Regex = Regex::new( + "(^revreg:(?P[a-z0-9]+):)?(?P.+):4:(?P.+):(?P.+):\ + (?P.+)$" + ) + .unwrap(); } #[derive(Deserialize, Debug, Serialize)] @@ -231,7 +236,10 @@ impl Validatable for RevocationRegistryConfig { fn validate(&self) -> Result<(), String> { if let Some(num_) = self.max_cred_num { if num_ == 0 { - return Err(String::from("RevocationRegistryConfig validation failed: `max_cred_num` must be greater than 0")); + return Err(String::from( + "RevocationRegistryConfig validation failed: `max_cred_num` must be greater \ + than 0", + )); } } Ok(()) @@ -286,15 +294,28 @@ mod tests { } fn _cred_def_id_qualified() -> CredentialDefinitionId { - CredentialDefinitionId("creddef:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag".to_string()) + CredentialDefinitionId( + "creddef:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov:\ + NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag" + .to_string(), + ) } fn _rev_reg_id_unqualified() -> RevocationRegistryId { - RevocationRegistryId("NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1".to_string()) + RevocationRegistryId( + "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.\ + 0:tag:CL_ACCUM:TAG_1" + .to_string(), + ) } fn _rev_reg_id_qualified() -> RevocationRegistryId { - RevocationRegistryId("revreg:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:4:creddef:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1".to_string()) + RevocationRegistryId( + "revreg:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:4:creddef:sov:did:sov:\ + NcYxiDXkpYi6ov5FcYDi1e:3:CL:schema:sov:did:sov:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:\ + CL_ACCUM:TAG_1" + .to_string(), + ) } mod to_unqualified { diff --git a/libvdrtools/src/domain/anoncreds/revocation_state.rs b/libvdrtools/src/domain/anoncreds/revocation_state.rs index 3d159cec73..7fef93a481 100644 --- a/libvdrtools/src/domain/anoncreds/revocation_state.rs +++ b/libvdrtools/src/domain/anoncreds/revocation_state.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; -use ursa::cl::{RevocationRegistry, Witness}; use indy_api_types::validation::Validatable; +use ursa::cl::{RevocationRegistry, Witness}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RevocationState { diff --git a/libvdrtools/src/domain/anoncreds/schema.rs b/libvdrtools/src/domain/anoncreds/schema.rs index b5035cf677..deb73c130c 100644 --- a/libvdrtools/src/domain/anoncreds/schema.rs +++ b/libvdrtools/src/domain/anoncreds/schema.rs @@ -1,16 +1,13 @@ -use super::DELIMITER; - -use super::super::crypto::did::DidValue; +use std::collections::{HashMap, HashSet}; use indy_api_types::{ errors::{IndyErrorKind, IndyResult}, + validation::Validatable, IndyError, }; -use std::collections::{HashMap, HashSet}; -use super::indy_identifiers; +use super::{super::crypto::did::DidValue, indy_identifiers, DELIMITER}; use crate::utils::qualifier; -use indy_api_types::validation::Validatable; pub const MAX_ATTRIBUTES_COUNT: usize = 125; diff --git a/libvdrtools/src/domain/cache.rs b/libvdrtools/src/domain/cache.rs index cc26bf08a1..deea3c64be 100644 --- a/libvdrtools/src/domain/cache.rs +++ b/libvdrtools/src/domain/cache.rs @@ -10,5 +10,6 @@ pub struct GetCacheOptions { pub no_cache: Option, // Skip usage of cache, pub no_update: Option, // Use only cached data, do not try to update. pub no_store: Option, // Skip storing fresh data if updated - pub min_fresh: Option, // Return cached data if not older than this many seconds. -1 means do not check age. + pub min_fresh: Option, /* Return cached data if not older than this many seconds. -1 + * means do not check age. */ } diff --git a/libvdrtools/src/domain/crypto/did.rs b/libvdrtools/src/domain/crypto/did.rs index 2167acfb1a..3697df2990 100644 --- a/libvdrtools/src/domain/crypto/did.rs +++ b/libvdrtools/src/domain/crypto/did.rs @@ -1,4 +1,3 @@ -use crate::utils::qualifier; use indy_api_types::{ errors::{IndyError, IndyErrorKind, IndyResult}, validation::Validatable, @@ -6,6 +5,8 @@ use indy_api_types::{ use lazy_static::lazy_static; use regex::Regex; +use crate::utils::qualifier; + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct DidMethod(pub String); @@ -127,8 +128,11 @@ impl Validatable for DidValue { .map_err(|err| err.to_string())?; if did.len() != 16 && did.len() != 32 { - return Err(format!("Trying to use DID with unexpected length: {}. \ - The 16- or 32-byte number upon which a DID is based should be 22/23 or 44/45 bytes when encoded as base58.", did.len())); + return Err(format!( + "Trying to use DID with unexpected length: {}. The 16- or 32-byte number upon \ + which a DID is based should be 22/23 or 44/45 bytes when encoded as base58.", + did.len() + )); } } Ok(()) @@ -155,8 +159,11 @@ impl Validatable for ShortDidValue { .map_err(|err| err.to_string())?; if did.len() != 16 && did.len() != 32 { - return Err(format!("Trying to use DID with unexpected length: {}. \ - The 16- or 32-byte number upon which a DID is based should be 22/23 or 44/45 bytes when encoded as base58.", did.len())); + return Err(format!( + "Trying to use DID with unexpected length: {}. The 16- or 32-byte number upon \ + which a DID is based should be 22/23 or 44/45 bytes when encoded as base58.", + did.len() + )); } Ok(()) } diff --git a/libvdrtools/src/domain/ledger/auth_rule.rs b/libvdrtools/src/domain/ledger/auth_rule.rs index 64634e6223..69a6d044c2 100644 --- a/libvdrtools/src/domain/ledger/auth_rule.rs +++ b/libvdrtools/src/domain/ledger/auth_rule.rs @@ -1,6 +1,7 @@ -use serde_json::Value; use std::ops::Not; +use serde_json::Value; + use super::constants::{AUTH_RULE, AUTH_RULES, GET_AUTH_RULE}; #[allow(non_camel_case_types)] diff --git a/libvdrtools/src/domain/ledger/node.rs b/libvdrtools/src/domain/ledger/node.rs index c819019573..fb025f7c7c 100644 --- a/libvdrtools/src/domain/ledger/node.rs +++ b/libvdrtools/src/domain/ledger/node.rs @@ -1,8 +1,7 @@ -use super::constants::NODE; - -use super::super::crypto::did::ShortDidValue; use indy_api_types::validation::Validatable; +use super::{super::crypto::did::ShortDidValue, constants::NODE}; + #[derive(Serialize, PartialEq, Debug)] pub struct NodeOperation { #[serde(rename = "type")] @@ -68,7 +67,10 @@ impl Validatable for NodeOperationData { || self.client_ip.is_none() || self.client_port.is_none()) { - return Err(String::from("Invalid data json: Fields node_ip, node_port, client_ip, client_port must be specified together")); + return Err(String::from( + "Invalid data json: Fields node_ip, node_port, client_ip, client_port must be \ + specified together", + )); } Ok(()) diff --git a/libvdrtools/src/domain/ledger/pool.rs b/libvdrtools/src/domain/ledger/pool.rs index cf25932369..1e19bfb2cd 100644 --- a/libvdrtools/src/domain/ledger/pool.rs +++ b/libvdrtools/src/domain/ledger/pool.rs @@ -1,7 +1,7 @@ -use super::constants::{POOL_CONFIG, POOL_RESTART, POOL_UPGRADE}; - use std::collections::HashMap; +use super::constants::{POOL_CONFIG, POOL_RESTART, POOL_UPGRADE}; + #[derive(Serialize, PartialEq, Debug)] pub struct PoolConfigOperation { #[serde(rename = "type")] diff --git a/libvdrtools/src/domain/ledger/request.rs b/libvdrtools/src/domain/ledger/request.rs index 58b0c073c9..8da3574019 100644 --- a/libvdrtools/src/domain/ledger/request.rs +++ b/libvdrtools/src/domain/ledger/request.rs @@ -1,13 +1,12 @@ -use serde; -use serde_json; -use time; - use std::{ collections::HashMap, sync::atomic::{AtomicUsize, Ordering}, }; use lazy_static::lazy_static; +use serde; +use serde_json; +use time; use super::super::crypto::did::{DidValue, ShortDidValue}; diff --git a/libvdrtools/src/domain/ledger/rev_reg.rs b/libvdrtools/src/domain/ledger/rev_reg.rs index 14ebd679f5..18b01a5079 100644 --- a/libvdrtools/src/domain/ledger/rev_reg.rs +++ b/libvdrtools/src/domain/ledger/rev_reg.rs @@ -1,4 +1,4 @@ -use super::constants::{GET_REVOC_REG, GET_REVOC_REG_DELTA, REVOC_REG_ENTRY}; +use std::collections::HashSet; use ursa::cl::{RevocationRegistry, RevocationRegistryDelta}; @@ -8,11 +8,10 @@ use super::{ revocation_registry_definition::RevocationRegistryId, revocation_registry_delta::RevocationRegistryDeltaV1, }, + constants::{GET_REVOC_REG, GET_REVOC_REG_DELTA, REVOC_REG_ENTRY}, response::{GetReplyResultV1, ReplyType}, }; -use std::collections::HashSet; - #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct RevRegEntryOperation { diff --git a/libvdrtools/src/domain/ledger/schema.rs b/libvdrtools/src/domain/ledger/schema.rs index f2a286f583..73baf2e6b7 100644 --- a/libvdrtools/src/domain/ledger/schema.rs +++ b/libvdrtools/src/domain/ledger/schema.rs @@ -1,11 +1,11 @@ +use std::collections::HashSet; + use super::{ super::{anoncreds::schema::SchemaId, crypto::did::ShortDidValue}, constants::{GET_SCHEMA, SCHEMA}, response::{GetReplyResultV1, ReplyType}, }; -use std::collections::HashSet; - #[derive(Serialize, PartialEq, Debug)] pub struct SchemaOperation { #[serde(rename = "type")] diff --git a/libvdrtools/src/lib.rs b/libvdrtools/src/lib.rs index 2a181bbcc4..b2625ac609 100644 --- a/libvdrtools/src/lib.rs +++ b/libvdrtools/src/lib.rs @@ -28,22 +28,7 @@ mod services; use std::sync::Arc; -use lazy_static::lazy_static; - -use crate::{ - controllers::{ - BlobStorageController, ConfigController, CryptoController, DidController, IssuerController, - NonSecretsController, PairwiseController, ProverController, VerifierController, - WalletController, - }, - services::{ - BlobStorageService, CryptoService, IssuerService, ProverService, VerifierService, - WalletService, - }, -}; - pub use controllers::CredentialDefinitionId; - pub use domain::{ anoncreds::{ credential::{AttributeValues, Credential, CredentialValues}, @@ -71,15 +56,26 @@ pub use domain::{ pack::JWE, }, }; - pub use indy_api_types::{ CommandHandle, IndyError, SearchHandle, WalletHandle, INVALID_COMMAND_HANDLE, INVALID_SEARCH_HANDLE, INVALID_WALLET_HANDLE, }; - pub use indy_wallet::WalletRecord; +use lazy_static::lazy_static; pub use services::AnoncredsHelpers; +use crate::{ + controllers::{ + BlobStorageController, ConfigController, CryptoController, DidController, IssuerController, + NonSecretsController, PairwiseController, ProverController, VerifierController, + WalletController, + }, + services::{ + BlobStorageService, CryptoService, IssuerService, ProverService, VerifierService, + WalletService, + }, +}; + // Global (lazy inited) instance of Locator lazy_static! { static ref LOCATOR: Locator = Locator::new(); diff --git a/libvdrtools/src/services/anoncreds/helpers.rs b/libvdrtools/src/services/anoncreds/helpers.rs index 479826d4d2..1a3e981e35 100644 --- a/libvdrtools/src/services/anoncreds/helpers.rs +++ b/libvdrtools/src/services/anoncreds/helpers.rs @@ -1,7 +1,6 @@ use std::collections::{HashMap, HashSet}; use indy_api_types::errors::prelude::*; - use ursa::cl::{ issuer::Issuer as UrsaIssuer, verifier::Verifier as UrsaVerifier, CredentialSchema, CredentialValues, MasterSecret, NonCredentialSchema, SubProofRequest, @@ -109,8 +108,7 @@ impl AnoncredsHelpers { predicates_for_credential: &[PredicateInfo], ) -> IndyResult { trace!( - "build_sub_proof_request > attrs_for_credential {:?} \ - predicates_for_credential {:?}", + "build_sub_proof_request > attrs_for_credential {:?} predicates_for_credential {:?}", attrs_for_credential, predicates_for_credential ); @@ -254,8 +252,12 @@ mod tests { const CRED_DEF_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/1/tag"; const CRED_DEF_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:3:CL:1:tag"; - const REV_REG_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/tag/TAG_1"; - const REV_REG_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1"; + const REV_REG_ID_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/\ + REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/\ + v0/SCHEMA/gvt/1.0/tag/TAG_1"; + const REV_REG_ID_UNQUALIFIED: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:\ + CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:\ + TAG_1"; const SCHEMA_ID_WITH_SPACES_QUALIFIED: &str = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/Passport Schema/1.0"; const SCHEMA_ID_WITH_SPACES_UNQUALIFIED: &str = diff --git a/libvdrtools/src/services/anoncreds/issuer.rs b/libvdrtools/src/services/anoncreds/issuer.rs index 16348f7e48..14ef299eb9 100644 --- a/libvdrtools/src/services/anoncreds/issuer.rs +++ b/libvdrtools/src/services/anoncreds/issuer.rs @@ -1,5 +1,4 @@ use indy_api_types::errors::prelude::*; - use ursa::cl::{ issuer::Issuer as UrsaIssuer, CredentialKeyCorrectnessProof, CredentialPrivateKey, CredentialPublicKey, CredentialSignature, Nonce, RevocationKeyPrivate, RevocationRegistry, @@ -84,8 +83,8 @@ impl IssuerService { RevocationTailsGenerator, )> { trace!( - "new_revocation_registry > pub_key {:?} \ - max_cred_num {:?} issuance_by_default {:?} issuer_did {:?}", + "new_revocation_registry > pub_key {:?} max_cred_num {:?} issuance_by_default {:?} \ + issuer_did {:?}", cred_def, max_cred_num, issuance_by_default, @@ -140,10 +139,9 @@ impl IssuerService { RTA: RevocationTailsAccessor, { trace!( - "new_credential > cred_def {:?} cred_priv_key {:?} \ - cred_issuance_blinding_nonce {:?} cred_request {:?} \ - cred_values {:?} rev_idx {:?} rev_reg_def {:?} \ - rev_reg {:?} rev_key_priv {:?}", + "new_credential > cred_def {:?} cred_priv_key {:?} cred_issuance_blinding_nonce {:?} \ + cred_request {:?} cred_values {:?} rev_idx {:?} rev_reg_def {:?} rev_reg {:?} \ + rev_key_priv {:?}", cred_def, secret!(&cred_priv_key), secret!(&cred_issuance_blinding_nonce), diff --git a/libvdrtools/src/services/anoncreds/prover.rs b/libvdrtools/src/services/anoncreds/prover.rs index 0f1a3390f5..f000f7940f 100644 --- a/libvdrtools/src/services/anoncreds/prover.rs +++ b/libvdrtools/src/services/anoncreds/prover.rs @@ -1,7 +1,6 @@ use std::collections::{hash_map::Entry, HashMap}; use indy_api_types::errors::prelude::*; - use ursa::cl::{ issuer::Issuer as UrsaIssuer, prover::Prover as UrsaProver, verifier::Verifier as UrsaVerifier, BlindedCredentialSecrets, BlindedCredentialSecretsCorrectnessProof, CredentialPublicKey, @@ -103,8 +102,8 @@ impl ProverService { rev_reg_def: Option<&RevocationRegistryDefinitionV1>, ) -> IndyResult<()> { trace!( - "process_credential > credential {:?} cred_request_metadata {:?} \ - master_secret {:?} cred_def {:?} rev_reg_def {:?}", + "process_credential > credential {:?} cred_request_metadata {:?} master_secret {:?} \ + cred_def {:?} rev_reg_def {:?}", credential, cred_request_metadata, secret!(&master_secret), @@ -150,9 +149,8 @@ impl ProverService { rev_states: &HashMap>, ) -> IndyResult { trace!( - "create_proof > credentials {:?} proof_req {:?} \ - requested_credentials {:?} master_secret {:?} \ - schemas {:?} cred_defs {:?} rev_states {:?}", + "create_proof > credentials {:?} proof_req {:?} requested_credentials {:?} \ + master_secret {:?} schemas {:?} cred_defs {:?} rev_states {:?}", credentials, proof_req, requested_credentials, @@ -611,8 +609,8 @@ impl ProverService { ) -> IndyResult<()> { trace!( "_update_requested_proof > req_attrs_for_credential {:?} \ - req_predicates_for_credential {:?} proof_req {:?} credential {:?} \ - sub_proof_index {:?} requested_proof {:?}", + req_predicates_for_credential {:?} proof_req {:?} credential {:?} sub_proof_index \ + {:?} requested_proof {:?}", req_attrs_for_credential, req_predicates_for_credential, proof_req, @@ -702,7 +700,7 @@ impl ProverService { ) -> IndyResult { trace!( "_build_sub_proof_request > req_attrs_for_credential {:?} \ - req_predicates_for_credential {:?}", + req_predicates_for_credential {:?}", req_attrs_for_credential, req_predicates_for_credential ); @@ -752,9 +750,8 @@ impl ProverService { extra_query: &Option<&ProofRequestExtraQuery>, ) -> IndyResult { trace!( - "process_proof_request_restrictions > version {:?} \ - name {:?} names {:?} referent {:?} \ - restrictions {:?} extra_query {:?}", + "process_proof_request_restrictions > version {:?} name {:?} names {:?} referent {:?} \ + restrictions {:?} extra_query {:?}", version, name, names, @@ -935,7 +932,8 @@ mod tests { const SCHEMA_VERSION: &str = "1.0"; const ISSUER_DID: &str = "NcYxiDXkpYi6ov5FcYDi1e"; const CRED_DEF_ID: &str = "NcYxiDXkpYi6ov5FcYDi1e:3:CL:1:tag"; - const REV_REG_ID: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1"; + const REV_REG_ID: &str = "NcYxiDXkpYi6ov5FcYDi1e:4:NcYxiDXkpYi6ov5FcYDi1e:3:CL:\ + NcYxiDXkpYi6ov5FcYDi1e:2:gvt:1.0:tag:CL_ACCUM:TAG_1"; const NO_REV_REG_ID: &str = "None"; macro_rules! hashmap { @@ -955,8 +953,9 @@ mod tests { use crate::domain::anoncreds::revocation_registry_definition::RevocationRegistryId; fn _credential() -> Credential { - // note that encoding is not standardized by Indy except that 32-bit integers are encoded as themselves. IS-786 - // so Alex -> 12345 is an application choice while 25 -> 25 is not + // note that encoding is not standardized by Indy except that 32-bit integers are + // encoded as themselves. IS-786 so Alex -> 12345 is an application choice + // while 25 -> 25 is not let mut attr_values: HashMap = HashMap::new(); attr_values.insert( "name".to_string(), @@ -1064,7 +1063,8 @@ mod tests { let schema_id = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0"; let issuer_did = "did:indy:NcYxiDXkpYi6ov5FcYDi1e"; let cred_def_id = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/CLAIM_DEF/1/tag"; - let rev_reg_id = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/tag/TAG_1"; + let rev_reg_id = "did:indy:NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/REV_REG_DEF/did:indy:\ + NcYxiDXkpYi6ov5FcYDi1e/anoncreds/v0/SCHEMA/gvt/1.0/tag/TAG_1"; let mut credential = _credential(); credential.schema_id = SchemaId(schema_id.to_string()); @@ -1136,13 +1136,12 @@ mod tests { } mod prepare_credentials_for_proving { + use super::*; use crate::domain::anoncreds::{ proof_request::{AttributeInfo, PredicateInfo}, requested_credential::RequestedAttribute, }; - use super::*; - const CRED_ID: &str = "8591bcac-ee7d-4bef-ba7e-984696440b30"; const ATTRIBUTE_REFERENT: &str = "attribute_referent"; const PREDICATE_REFERENT: &str = "predicate_referent"; diff --git a/libvdrtools/src/services/anoncreds/verifier.rs b/libvdrtools/src/services/anoncreds/verifier.rs index 2c015fb1b0..d6937261b0 100644 --- a/libvdrtools/src/services/anoncreds/verifier.rs +++ b/libvdrtools/src/services/anoncreds/verifier.rs @@ -3,7 +3,6 @@ use std::collections::{HashMap, HashSet}; use indy_api_types::errors::prelude::*; use lazy_static::lazy_static; use regex::Regex; - use ursa::{ bn::BigNumber, cl::{new_nonce, verifier::Verifier as CryptoVerifier, CredentialPublicKey, Nonce}, @@ -54,8 +53,16 @@ impl VerifierService { rev_reg_defs: &HashMap, rev_regs: &HashMap>, ) -> IndyResult { - trace!("verify >>> full_proof: {:?}, proof_req: {:?}, schemas: {:?}, cred_defs: {:?}, rev_reg_defs: {:?} rev_regs: {:?}", - full_proof, proof_req, schemas, cred_defs, rev_reg_defs, rev_regs); + trace!( + "verify >>> full_proof: {:?}, proof_req: {:?}, schemas: {:?}, cred_defs: {:?}, \ + rev_reg_defs: {:?} rev_regs: {:?}", + full_proof, + proof_req, + schemas, + cred_defs, + rev_reg_defs, + rev_regs + ); let received_revealed_attrs: HashMap = VerifierService::_received_revealed_attrs(&full_proof)?; @@ -215,8 +222,13 @@ impl VerifierService { requested_proof: &RequestedProof, proof_req: &ProofRequestPayload, ) -> IndyResult> { - trace!("_get_revealed_attributes_for_credential >>> sub_proof_index: {:?}, requested_credentials: {:?}, proof_req: {:?}", - sub_proof_index, requested_proof, proof_req); + trace!( + "_get_revealed_attributes_for_credential >>> sub_proof_index: {:?}, \ + requested_credentials: {:?}, proof_req: {:?}", + sub_proof_index, + requested_proof, + proof_req + ); let mut revealed_attrs_for_credential = requested_proof .revealed_attrs @@ -253,8 +265,13 @@ impl VerifierService { requested_proof: &RequestedProof, proof_req: &ProofRequestPayload, ) -> IndyResult> { - trace!("_get_predicates_for_credential >>> sub_proof_index: {:?}, requested_credentials: {:?}, proof_req: {:?}", - sub_proof_index, requested_proof, proof_req); + trace!( + "_get_predicates_for_credential >>> sub_proof_index: {:?}, requested_credentials: \ + {:?}, proof_req: {:?}", + sub_proof_index, + requested_proof, + proof_req + ); let predicates_for_credential = requested_proof .predicates @@ -511,7 +528,11 @@ impl VerifierService { ), ))?; if attr_infos.values.len() != attr_names.len() { - error!("Proof Revealed Attr Group does not match Proof Request Attribute Group, proof request attrs: {:?}, referent: {:?}, attr_infos: {:?}", proof_req.requested_attributes, attr_referent, attr_infos); + error!( + "Proof Revealed Attr Group does not match Proof Request Attribute Group, \ + proof request attrs: {:?}, referent: {:?}, attr_infos: {:?}", + proof_req.requested_attributes, attr_referent, attr_infos + ); return Err(IndyError::from_msg( IndyErrorKind::InvalidStructure, "Proof Revealed Attr Group does not match Proof Request Attribute Group", @@ -569,8 +590,14 @@ impl VerifierService { if BigNumber::from_dec(reveal_attr_encoded)? != BigNumber::from_dec(&crypto_proof_encoded)? { - return Err(IndyError::from_msg(IndyErrorKind::ProofRejected, - format!("Encoded Values for \"{}\" are different in RequestedProof \"{}\" and CryptoProof \"{}\"", attr_name, reveal_attr_encoded, crypto_proof_encoded))); + return Err(IndyError::from_msg( + IndyErrorKind::ProofRejected, + format!( + "Encoded Values for \"{}\" are different in RequestedProof \"{}\" and \ + CryptoProof \"{}\"", + attr_name, reveal_attr_encoded, crypto_proof_encoded + ), + )); } Ok(()) @@ -657,7 +684,8 @@ impl VerifierService { let mut attr_value_map = HashMap::new(); attr_value_map.insert(info.name.to_string(), None); - // include any revealed attributes for the same credential (based on sub_proof_index) + // include any revealed attributes for the same credential (based on + // sub_proof_index) let pred_sub_proof_index = requested_proof .predicates .get(referent) @@ -698,7 +726,8 @@ impl VerifierService { // old style :-/ which fails for attribute restrictions on predicates //VerifierService::_process_operator(&info.name, &query, &filter, None) - // .map_err(|err| err.extend(format!("Requested restriction validation failed for \"{}\" predicate", &info.name)))?; + // .map_err(|err| err.extend(format!("Requested restriction validation failed for + // \"{}\" predicate", &info.name)))?; } } @@ -792,8 +821,14 @@ impl VerifierService { { Ok(()) } else { - Err(IndyError::from_msg(IndyErrorKind::ProofRejected, - format!("$neq operator validation failed for tag: \"{}\", value: \"{}\". Condition was passed.", tag_name, tag_value))) + Err(IndyError::from_msg( + IndyErrorKind::ProofRejected, + format!( + "$neq operator validation failed for tag: \"{}\", value: \"{}\". \ + Condition was passed.", + tag_name, tag_value + ), + )) } } Query::In(ref tag_name, ref tag_values) => { @@ -976,8 +1011,14 @@ impl VerifierService { )); } } else { - return Err(IndyError::from_msg(IndyErrorKind::ProofRejected, - format!("Revealed value hasn't been find by key: expected key: \"{}\", attr_value_map: \"{:?}\"", key, attr_value_map))); + return Err(IndyError::from_msg( + IndyErrorKind::ProofRejected, + format!( + "Revealed value hasn't been find by key: expected key: \"{}\", \ + attr_value_map: \"{:?}\"", + key, attr_value_map + ), + )); } Ok(()) } diff --git a/libvdrtools/src/services/blob_storage/default_reader.rs b/libvdrtools/src/services/blob_storage/default_reader.rs index 456d5ff091..901820246a 100644 --- a/libvdrtools/src/services/blob_storage/default_reader.rs +++ b/libvdrtools/src/services/blob_storage/default_reader.rs @@ -4,13 +4,13 @@ use std::{ path::PathBuf, }; -use crate::utils::crypto::base58::ToBase58; use async_trait::async_trait; use indy_api_types::errors::prelude::*; use indy_utils::crypto::hash::Hash; use serde_json; use super::{ReadableBlob, Reader, ReaderType}; +use crate::utils::crypto::base58::ToBase58; pub(crate) struct DefaultReader { file: SyncFile, diff --git a/libvdrtools/src/services/blob_storage/default_writer.rs b/libvdrtools/src/services/blob_storage/default_writer.rs index fafab7acf1..acc2b79596 100644 --- a/libvdrtools/src/services/blob_storage/default_writer.rs +++ b/libvdrtools/src/services/blob_storage/default_writer.rs @@ -1,14 +1,12 @@ use std::path::PathBuf; -use crate::utils::crypto::base58::ToBase58; use async_std::{fs, fs::File, prelude::*}; use async_trait::async_trait; use indy_api_types::errors::prelude::*; use serde_json; -use crate::utils::environment; - use super::{WritableBlob, Writer, WriterType}; +use crate::utils::{crypto::base58::ToBase58, environment}; #[allow(dead_code)] pub(crate) struct DefaultWriter { diff --git a/libvdrtools/src/services/blob_storage/mod.rs b/libvdrtools/src/services/blob_storage/mod.rs index 8009f7ccc2..b8cfe315a7 100644 --- a/libvdrtools/src/services/blob_storage/mod.rs +++ b/libvdrtools/src/services/blob_storage/mod.rs @@ -7,7 +7,6 @@ use async_trait::async_trait; use futures::lock::Mutex; use indy_api_types::errors::prelude::*; use indy_utils::sequence; - use sha2::{ digest::{FixedOutput, Update}, Sha256, diff --git a/libvdrtools/src/services/crypto/ed25519.rs b/libvdrtools/src/services/crypto/ed25519.rs index 98029ea06f..00c3ecbb96 100644 --- a/libvdrtools/src/services/crypto/ed25519.rs +++ b/libvdrtools/src/services/crypto/ed25519.rs @@ -1,7 +1,8 @@ -use super::CryptoType; use indy_api_types::errors::IndyError; use indy_utils::crypto::{ed25519_box, ed25519_sign, sealedbox}; +use super::CryptoType; + pub struct ED25519CryptoType {} impl ED25519CryptoType { diff --git a/libvdrtools/src/services/crypto/mod.rs b/libvdrtools/src/services/crypto/mod.rs index 94b2919765..ea6ce01afe 100644 --- a/libvdrtools/src/services/crypto/mod.rs +++ b/libvdrtools/src/services/crypto/mod.rs @@ -3,26 +3,25 @@ mod ed25519; use std::{collections::HashMap, str}; use async_std::sync::RwLock; +use ed25519::ED25519CryptoType; use hex::FromHex; use indy_api_types::errors::prelude::*; - use indy_utils::crypto::{ base64, chacha20poly1305_ietf, chacha20poly1305_ietf::gen_nonce_and_encrypt_detached, ed25519_box, ed25519_sign, }; -use crate::utils::crypto::base58::{FromBase58, ToBase58}; - use crate::{ domain::crypto::{ did::{Did, DidValue, MyDidInfo, TheirDid, TheirDidInfo}, key::{Key, KeyInfo}, }, - utils::crypto::verkey_builder::{build_full_verkey, split_verkey, verkey_get_cryptoname}, + utils::crypto::{ + base58::{FromBase58, ToBase58}, + verkey_builder::{build_full_verkey, split_verkey, verkey_get_cryptoname}, + }, }; -use ed25519::ED25519CryptoType; - const DEFAULT_CRYPTO_TYPE: &str = "ed25519"; //TODO fix this crypto trait so it matches the functions below @@ -463,8 +462,8 @@ impl CryptoService { return Err(err_msg( IndyErrorKind::InvalidStructure, format!( - "Trying to use invalid base64 encoded `seed`. \ - The number of bytes must be {} ", + "Trying to use invalid base64 encoded `seed`. The number of bytes must be \ + {} ", ed25519_sign::SEEDBYTES ), )); @@ -476,8 +475,8 @@ impl CryptoService { return Err(err_msg( IndyErrorKind::InvalidStructure, format!( - "Trying to use invalid `seed`. It can be either \ - {} bytes string or base64 string or {} bytes HEX string", + "Trying to use invalid `seed`. It can be either {} bytes string or base64 \ + string or {} bytes HEX string", ed25519_sign::SEEDBYTES, ed25519_sign::SEEDBYTES * 2 ), @@ -548,7 +547,7 @@ impl CryptoService { (ciphertext_encoded, iv_encoded, tag_encoded) } - /* ciphertext helper functions*/ + /* ciphertext helper functions */ pub(crate) fn decrypt_ciphertext( &self, ciphertext: &str, @@ -626,10 +625,10 @@ impl CryptoService { #[cfg(test)] mod tests { - use crate::domain::crypto::did::MyDidInfo; use indy_utils::crypto::chacha20poly1305_ietf::gen_key; use super::*; + use crate::domain::crypto::did::MyDidInfo; #[async_std::test] async fn create_my_did_with_works_for_empty_info() { @@ -1051,8 +1050,8 @@ mod tests { async fn test_encrypt_plaintext_and_decrypt_ciphertext_works() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); @@ -1070,8 +1069,8 @@ mod tests { async fn test_encrypt_plaintext_decrypt_ciphertext_empty_string_works() { let service: CryptoService = CryptoService::new(); let plaintext = "".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); @@ -1089,8 +1088,8 @@ mod tests { async fn test_encrypt_plaintext_decrypt_ciphertext_bad_iv_fails() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); @@ -1109,8 +1108,8 @@ mod tests { async fn test_encrypt_plaintext_decrypt_ciphertext_bad_ciphertext_fails() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); @@ -1128,8 +1127,8 @@ mod tests { async fn test_encrypt_plaintext_and_decrypt_ciphertext_wrong_cek_fails() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = chacha20poly1305_ietf::gen_key(); @@ -1148,8 +1147,8 @@ mod tests { async fn test_encrypt_plaintext_and_decrypt_ciphertext_bad_tag_fails() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); @@ -1166,8 +1165,8 @@ mod tests { async fn test_encrypt_plaintext_and_decrypt_ciphertext_bad_aad_fails() { let service: CryptoService = CryptoService::new(); let plaintext = "Hello World".as_bytes().to_vec(); - // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and alg - // Which the receiver MUST then check before decryption + // AAD allows the sender to tie extra (protocol) data to the encryption. Example JWE enc and + // alg Which the receiver MUST then check before decryption let aad = "some protocol data input to the encryption"; let cek = gen_key(); diff --git a/libvdrtools/src/services/mod.rs b/libvdrtools/src/services/mod.rs index 424cb4c373..72c6529083 100644 --- a/libvdrtools/src/services/mod.rs +++ b/libvdrtools/src/services/mod.rs @@ -4,7 +4,6 @@ mod crypto; mod wallet; pub use anoncreds::{AnoncredsHelpers, IssuerService, ProverService, VerifierService}; - pub use blob_storage::BlobStorageService; pub use crypto::CryptoService; pub(crate) use wallet::WalletService; diff --git a/libvdrtools/src/utils/crypto/signature_serializer.rs b/libvdrtools/src/utils/crypto/signature_serializer.rs index 2701d36c65..1360ab4ec9 100644 --- a/libvdrtools/src/utils/crypto/signature_serializer.rs +++ b/libvdrtools/src/utils/crypto/signature_serializer.rs @@ -1,8 +1,9 @@ -use crate::domain::ledger::constants::{ATTRIB, GET_ATTR}; use indy_api_types::errors::prelude::*; use indy_utils::crypto::hash::Hash; use serde_json::Value; +use crate::domain::ledger::constants::{ATTRIB, GET_ATTR}; + fn _serialize_signature( v: Value, is_top_level: bool, @@ -117,7 +118,10 @@ mod tests { }"#; let msg: Value = serde_json::from_str(data).unwrap(); - let result = "age:43|name:John Doe|operation:dest:54|hash:46aa0c92129b33ee72ee1478d2ae62fa6e756869dedc6c858af3214a6fcf1904|type:100|phones:1234567,2345678,age:1|rust:5,3"; + let result = "age:43|name:John \ + Doe|operation:dest:54|hash:\ + 46aa0c92129b33ee72ee1478d2ae62fa6e756869dedc6c858af3214a6fcf1904|type:\ + 100|phones:1234567,2345678,age:1|rust:5,3"; assert_eq!(serialize_signature(msg).unwrap(), result) } @@ -142,7 +146,11 @@ mod tests { }"#; let msg: Value = serde_json::from_str(data).unwrap(); - let result = "age:43|name:John Doe|operation:dest:54|hash:46aa0c92129b33ee72ee1478d2ae62fa6e756869dedc6c858af3214a6fcf1904|raw:1dcd0759ce38f57049344a6b3c5fc18144fca1724713090c2ceeffa788c02711|type:100|phones:1234567,2345678,age:1|rust:5,3"; + let result = "age:43|name:John \ + Doe|operation:dest:54|hash:\ + 46aa0c92129b33ee72ee1478d2ae62fa6e756869dedc6c858af3214a6fcf1904|raw:\ + 1dcd0759ce38f57049344a6b3c5fc18144fca1724713090c2ceeffa788c02711|type:\ + 100|phones:1234567,2345678,age:1|rust:5,3"; assert_eq!(serialize_signature(msg).unwrap(), result) } @@ -167,7 +175,8 @@ mod tests { }"#; let msg: Value = serde_json::from_str(data).unwrap(); - let result = "age:43|name:John Doe|operation:dest:54|hash:cool hash|raw:string for hash|type:101|phones:1234567,2345678,age:1|rust:5,3"; + let result = "age:43|name:John Doe|operation:dest:54|hash:cool hash|raw:string for \ + hash|type:101|phones:1234567,2345678,age:1|rust:5,3"; assert_eq!(serialize_signature(msg).unwrap(), result) } diff --git a/libvdrtools/src/utils/crypto/verkey_builder.rs b/libvdrtools/src/utils/crypto/verkey_builder.rs index 4acb3c98e6..465228077e 100644 --- a/libvdrtools/src/utils/crypto/verkey_builder.rs +++ b/libvdrtools/src/utils/crypto/verkey_builder.rs @@ -1,8 +1,9 @@ +use indy_api_types::errors::prelude::*; + use crate::{ services::CryptoService, utils::crypto::base58::{FromBase58, ToBase58}, }; -use indy_api_types::errors::prelude::*; pub fn build_full_verkey(dest: &str, verkey: Option<&str>) -> Result { if let Some(verkey) = verkey { diff --git a/libvdrtools/src/utils/mod.rs b/libvdrtools/src/utils/mod.rs index 5566ec33b8..330b6206ae 100755 --- a/libvdrtools/src/utils/mod.rs +++ b/libvdrtools/src/utils/mod.rs @@ -16,7 +16,6 @@ pub use indy_utils::test; pub mod try_utils; pub use indy_api_types::validation; - pub use indy_utils::wql; #[macro_use] diff --git a/libvdrtools/src/utils/qualifier.rs b/libvdrtools/src/utils/qualifier.rs index b2da56e8e7..1720f78f82 100644 --- a/libvdrtools/src/utils/qualifier.rs +++ b/libvdrtools/src/utils/qualifier.rs @@ -37,9 +37,8 @@ pub fn method(entity: &str) -> Option { (Some(type_), None) => Some(type_.as_str().to_owned()), _ => { warn!( - "Unrecognized FQ method for {}, parsed items are \ - (where 2nd is method type, and 3rd is sub-method (namespace, ledger, type, etc)\ - {:?}", + "Unrecognized FQ method for {}, parsed items are (where 2nd is method \ + type, and 3rd is sub-method (namespace, ledger, type, etc){:?}", entity, caps ); None From 1da02f47d56e322047167c678ed64773451aeceb Mon Sep 17 00:00:00 2001 From: Bogdan Mircea Date: Tue, 26 Sep 2023 16:41:13 +0300 Subject: [PATCH 3/4] Moved ci under .github dir Signed-off-by: Bogdan Mircea --- .github/actions/derive-cache-info/action.yml | 2 +- .github/actions/setup-codecov-rust/action.yml | 2 +- .github/actions/setup-testing-nodejs/action.yml | 2 +- {ci => .github/ci}/agency/docker-compose.yml | 0 {ci => .github/ci}/agency/localhost.env | 0 {ci => .github/ci}/util.sh | 0 {ci => .github/ci}/vdrproxy.dockerfile | 0 .github/workflows/main.yml | 6 +++--- 8 files changed, 6 insertions(+), 6 deletions(-) rename {ci => .github/ci}/agency/docker-compose.yml (100%) rename {ci => .github/ci}/agency/localhost.env (100%) rename {ci => .github/ci}/util.sh (100%) rename {ci => .github/ci}/vdrproxy.dockerfile (100%) diff --git a/.github/actions/derive-cache-info/action.yml b/.github/actions/derive-cache-info/action.yml index 7c56db06a7..606087e601 100644 --- a/.github/actions/derive-cache-info/action.yml +++ b/.github/actions/derive-cache-info/action.yml @@ -23,7 +23,7 @@ runs: - id: main shell: bash run: | - source ./ci/util.sh + source ./.github/ci/util.sh DOCKER_IMG=${{ inputs.docker-img }} CACHE_KEY=`as_docker_cache_key $DOCKER_IMG` CACHE_DIR="/tmp/cachedir-$CACHE_KEY" diff --git a/.github/actions/setup-codecov-rust/action.yml b/.github/actions/setup-codecov-rust/action.yml index fee5adaacb..1808bbec8b 100644 --- a/.github/actions/setup-codecov-rust/action.yml +++ b/.github/actions/setup-codecov-rust/action.yml @@ -29,4 +29,4 @@ runs: docker run --rm -d --name mysql --network host -e MYSQL_ROOT_PASSWORD=mysecretpassword mysql:5.7.35 docker run --rm -d --name indypool --network host ${{ env.DOCKER_IMAGE_POOL }} sleep 5 - docker-compose -f ./ci/agency/docker-compose.yml up -d \ No newline at end of file + docker-compose -f ./.github/ci/agency/docker-compose.yml up -d \ No newline at end of file diff --git a/.github/actions/setup-testing-nodejs/action.yml b/.github/actions/setup-testing-nodejs/action.yml index e924acc7c1..40a8512802 100644 --- a/.github/actions/setup-testing-nodejs/action.yml +++ b/.github/actions/setup-testing-nodejs/action.yml @@ -40,7 +40,7 @@ runs: docker run --rm -d --name mysql --network host -e MYSQL_ROOT_PASSWORD=mysecretpassword mysql:5.7.35 docker run --rm -d --name indypool --network host ${{ env.DOCKER_IMAGE_POOL }} sleep 5 - docker-compose -f ./ci/agency/docker-compose.yml up -d + docker-compose -f ./.github/ci/agency/docker-compose.yml up -d - name: "Build binding module" shell: bash run: (cd wrappers/vcx-napi-rs && npm install && npm run build:napi:debug) diff --git a/ci/agency/docker-compose.yml b/.github/ci/agency/docker-compose.yml similarity index 100% rename from ci/agency/docker-compose.yml rename to .github/ci/agency/docker-compose.yml diff --git a/ci/agency/localhost.env b/.github/ci/agency/localhost.env similarity index 100% rename from ci/agency/localhost.env rename to .github/ci/agency/localhost.env diff --git a/ci/util.sh b/.github/ci/util.sh similarity index 100% rename from ci/util.sh rename to .github/ci/util.sh diff --git a/ci/vdrproxy.dockerfile b/.github/ci/vdrproxy.dockerfile similarity index 100% rename from ci/vdrproxy.dockerfile rename to .github/ci/vdrproxy.dockerfile diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e11645955f..efd87a0bce 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -65,8 +65,8 @@ jobs: run: | set -x - HASH_DOCKERFILE_LIBVCX=${{ hashFiles('ci/libvcx.dockerfile') }} - HASH_DOCKERFILE_VDRPROXY=${{ hashFiles('ci/vdrproxy.dockerfile') }} + HASH_DOCKERFILE_LIBVCX=${{ hashFiles('.github/ci/libvcx.dockerfile') }} + HASH_DOCKERFILE_VDRPROXY=${{ hashFiles('.github/ci/vdrproxy.dockerfile') }} HASH_SRC_LIBVDRTOOLS=${{ hashFiles('libvdrtools') }} HASH_SRC_LIBVCX=${{ hashFiles('libvcx') }} HASH_SRC_ARIESVCX=${{ hashFiles('aries_vcx') }} @@ -233,7 +233,7 @@ jobs: uses: ./.github/actions/build-image with: docker-img: ${{ env.DOCKER_IMG_CACHED }} - dockerfile-path: "ci/vdrproxy.dockerfile" + dockerfile-path: ".github/ci/vdrproxy.dockerfile" build-arg: "ALPINE_CORE_IMAGE=$DOCKER_IMG_CACHED_ALPINE_CORE" branch-name: ${{ env.BRANCH_NAME }} branch-main: ${{ env.MAIN_BRANCH }} From b068a6de63eca5960e942f815ca5404a47d6427d Mon Sep 17 00:00:00 2001 From: Bogdan Mircea Date: Wed, 27 Sep 2023 12:16:59 +0300 Subject: [PATCH 4/4] Remove left-overs from other aries_vcx wrappers Signed-off-by: Bogdan Mircea --- .github/actions/publish-android/action.yml | 30 ---------------------- .github/workflows/main.yml | 1 - .gitignore | 4 --- 3 files changed, 35 deletions(-) delete mode 100644 .github/actions/publish-android/action.yml diff --git a/.github/actions/publish-android/action.yml b/.github/actions/publish-android/action.yml deleted file mode 100644 index 2efc8b0ac0..0000000000 --- a/.github/actions/publish-android/action.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: 'publish-android' -description: "Build andorid .aar and publish it to /tmp/artifacts" - -inputs: - abis: - description: 'A space separated list of ABIs to create a AAR for' - default: 'armv7 arm64 x86 x86_64' - docker-img-name: - description: 'Name of the android image' - required: true - full-version-name: - description: 'Name of the resulting .aar' - required: true - -runs: - using: "composite" - steps: - - name: Build, run android wrapper tests, and publish artifacts - run: | - set -x - sudo rm -rf "/usr/local/share/boost" "/usr/local/lib/android" "/usr/share/dotnet" - docker run --name publish-android-wrapper \ - -e ABIS="${{ inputs.abis }}" \ - -e FULL_VERSION_NAME="${{ inputs.full-version-name }}" \ - ${{ inputs.docker-img-name }} \ - bash -c '(cd /home/indy/aries-vcx && ./wrappers/java/ci/android.build.sh $ABIS)' - mkdir -p /tmp/artifacts/aar - docker cp publish-android-wrapper:/home/indy/artifacts/aar /tmp/artifacts - docker rm publish-android-wrapper > /dev/null - shell: bash diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index efd87a0bce..ff2c4ba172 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -74,7 +74,6 @@ jobs: HASH_SRC_AGENCYCLIENT=${{ hashFiles('agency_client') }} HASH_SRC_DIDDOC=${{ hashFiles('diddoc') }} HASH_SRC_MESSAGES=${{ hashFiles('messages') }} - HASH_SRC_WRAPPER_JAVA=${{ hashFiles('wrappers/java') }} SEED_HASH_ARIESVCX=${HASH_SRC_LIBVDRTOOLS:0:11}-${HASH_SRC_ARIESVCX_CORE:0:11}-${HASH_SRC_ARIESVCX:0:11}-${HASH_SRC_AGENCYCLIENT:0:11}-${HASH_SRC_DIDDOC:0:11}-${HASH_SRC_MESSAGES:0:11}} HASH_ARIESVCX=$(echo -n "$SEED_HASH_ARIESVCX" | sha256sum | awk '{print $1}') diff --git a/.gitignore b/.gitignore index 45b0f6b86f..45f9270f02 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,6 @@ **/node_modules **/*.node **/dist -wrappers/ios/vcx/vcx.framework/** -wrappers/ios/vcx/vcx.framework.dSYM/** -wrappers/ios_legacy/vcx/vcx.framework/** -wrappers/ios_legacy/vcx/vcx.framework.dSYM/** .vscode *.code-workspace **/tails.txt