From e04ba1ac9d738aa9527cd9899677d27b43d120de Mon Sep 17 00:00:00 2001 From: Bogdan Mircea <98585737+bobozaur@users.noreply.github.com> Date: Thu, 28 Sep 2023 09:52:53 +0300 Subject: [PATCH 1/4] Move CI dir (#1001) * Removed obsolete rustfmt.toml files * Ran cargo fmt * Moved ci under .github dir * Remove left-overs from other aries_vcx wrappers Signed-off-by: Bogdan Mircea --- .github/actions/derive-cache-info/action.yml | 2 +- .github/actions/publish-android/action.yml | 30 -- .github/actions/setup-codecov-rust/action.yml | 2 +- .../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 | 7 +- .gitignore | 4 - did_doc/rustfmt.toml | 2 - 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/rustfmt.toml | 2 - did_parser/src/did.rs | 11 +- did_parser/src/utils/parse.rs | 3 +- did_parser/tests/did_url/positive.rs | 3 +- did_resolver/rustfmt.toml | 2 - .../dereferenceable/dereferencing_output.rs | 2 +- .../src/traits/dereferenceable/mod.rs | 2 +- did_resolver/src/traits/resolvable/mod.rs | 2 +- did_resolver_registry/rustfmt.toml | 2 - did_resolver_registry/src/lib.rs | 6 +- did_resolver_sov/rustfmt.toml | 2 - .../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 +- libvdrtools/rustfmt.toml | 1 - .../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 +- 100 files changed, 897 insertions(+), 816 deletions(-) delete mode 100644 .github/actions/publish-android/action.yml 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%) 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/.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/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/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..ff2c4ba172 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') }} @@ -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}') @@ -233,7 +232,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 }} 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 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_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/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_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/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/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/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_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/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/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/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 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 d8e760249264c13f9392d0a64736adb4c7ece500 Mon Sep 17 00:00:00 2001 From: nain-F49FF806 <126972030+nain-F49FF806@users.noreply.github.com> Date: Thu, 28 Sep 2023 08:54:03 +0200 Subject: [PATCH 2/4] Use standard UnpackMessage struct until needing to transform. (#1002) Signed-off-by: Naian <126972030+nain-F49FF806@users.noreply.github.com> --- aries_vcx/src/common/signing.rs | 23 +------------------- libvcx_core/src/api_vcx/api_global/wallet.rs | 6 ++--- wrappers/vcx-napi-rs/src/api/wallet.rs | 5 +++-- 3 files changed, 7 insertions(+), 27 deletions(-) diff --git a/aries_vcx/src/common/signing.rs b/aries_vcx/src/common/signing.rs index 8e1b5112b4..d9ae7f3088 100644 --- a/aries_vcx/src/common/signing.rs +++ b/aries_vcx/src/common/signing.rs @@ -8,7 +8,7 @@ use messages::msg_fields::protocols::connection::{ }; use time; -use crate::{errors::error::prelude::*, global::settings}; +use crate::errors::error::prelude::*; async fn get_signature_data( wallet: &Arc, @@ -90,27 +90,6 @@ pub async fn decode_signed_connection_response( Ok(connection) } -pub async fn unpack_message_to_string( - wallet: &Arc, - msg: &[u8], -) -> VcxResult { - if settings::indy_mocks_enabled() { - return Ok(String::new()); - } - let unpack_msg = wallet.unpack_message(msg).await.map_err(|_| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidMessagePack, - "Failed to unpack message", - ) - })?; - serde_json::to_string(&unpack_msg).map_err(|_| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidMessageFormat, - "Failed to convert message to utf8 string", - ) - }) -} - // #[cfg(test)] // pub mod unit_tests { // use crate::common::test_utils::{create_trustee_key, indy_handles_to_profile}; diff --git a/libvcx_core/src/api_vcx/api_global/wallet.rs b/libvcx_core/src/api_vcx/api_global/wallet.rs index e26d5d1e90..4aace7a7c9 100644 --- a/libvcx_core/src/api_vcx/api_global/wallet.rs +++ b/libvcx_core/src/api_vcx/api_global/wallet.rs @@ -18,10 +18,10 @@ use aries_vcx::{ wallet::{close_wallet, create_and_open_wallet, delete_wallet, import}, IndySdkWallet, IssuerConfig, RestoreWalletConfigs, WalletConfig, }, + structs_io::UnpackMessageOutput, }, SearchHandle, WalletHandle, }, - common::signing::unpack_message_to_string, global::settings::DEFAULT_LINK_SECRET_ALIAS, protocols::mediated_connection::pairwise_info::PairwiseInfo, }; @@ -167,9 +167,9 @@ pub async fn rotate_verkey_apply(did: &str, temp_vk: &str) -> LibvcxResult<()> { ) } -pub async fn wallet_unpack_message_to_string(payload: &[u8]) -> LibvcxResult { +pub async fn wallet_unpack_message(payload: &[u8]) -> LibvcxResult { let wallet = get_main_wallet()?; - map_ariesvcx_result(unpack_message_to_string(&wallet, payload).await) + map_ariesvcx_core_result(wallet.unpack_message(payload).await) } pub async fn wallet_create_and_store_did(seed: Option<&str>) -> LibvcxResult { diff --git a/wrappers/vcx-napi-rs/src/api/wallet.rs b/wrappers/vcx-napi-rs/src/api/wallet.rs index e72990aaa2..e06a612893 100644 --- a/wrappers/vcx-napi-rs/src/api/wallet.rs +++ b/wrappers/vcx-napi-rs/src/api/wallet.rs @@ -72,9 +72,10 @@ pub async fn configure_issuer_wallet(enterprise_seed: String) -> napi::Result napi::Result { let data = data.as_ref(); - wallet::wallet_unpack_message_to_string(data) + let unpacked = wallet::wallet_unpack_message(data) .await - .map_err(to_napi_err) + .map_err(to_napi_err)?; + serde_json::to_string(&unpacked).map_err(|err| napi::Error::from_reason(err.to_string())) } #[napi] From ed39a5286da603c9a52bdd19162e6178239dd3c9 Mon Sep 17 00:00:00 2001 From: gmulhearn-anonyome <90162009+gmulhearn-anonyome@users.noreply.github.com> Date: Thu, 28 Sep 2023 18:52:54 +1000 Subject: [PATCH 3/4] Issue Credential V2.0 message structures (#990) Issue Credential V2.0 message structures (#990) Signed-off-by: George Mulhearn --- .../aries-vcx-agent/src/services/holder.rs | 12 +- .../aries-vcx-agent/src/services/issuer.rs | 14 +- aries_vcx/src/handlers/issuance/holder.rs | 43 ++-- aries_vcx/src/handlers/issuance/issuer.rs | 55 +++-- .../src/handlers/issuance/mediated_holder.rs | 17 +- .../src/handlers/issuance/mediated_issuer.rs | 22 +- .../src/handlers/out_of_band/receiver.rs | 23 +- aries_vcx/src/handlers/out_of_band/sender.rs | 8 +- aries_vcx/src/handlers/util.rs | 56 ++++- .../issuance/holder/state_machine.rs | 49 ++-- .../issuance/holder/states/finished.rs | 4 +- .../issuance/holder/states/offer_received.rs | 6 +- .../issuance/holder/states/proposal_set.rs | 6 +- .../issuance/holder/states/request_set.rs | 10 +- .../issuance/issuer/state_machine.rs | 75 +++--- .../issuance/issuer/states/credential_set.rs | 4 +- .../issuance/issuer/states/offer_set.rs | 10 +- .../issuer/states/proposal_received.rs | 6 +- .../issuer/states/requested_received.rs | 8 +- aries_vcx/src/utils/filters.rs | 28 ++- .../utils/scenarios/credential_issuance.rs | 24 +- aries_vcx/tests/utils/scenarios/data.rs | 15 +- .../src/api_vcx/api_handle/credential.rs | 50 ++-- messages/src/lib.rs | 29 ++- .../protocols/cred_issuance/common/mod.rs | 15 ++ .../msg_fields/protocols/cred_issuance/mod.rs | 219 +---------------- .../protocols/cred_issuance/{ => v1}/ack.rs | 14 +- .../{ => v1}/issue_credential.rs | 14 +- .../protocols/cred_issuance/v1/mod.rs | 225 +++++++++++++++++ .../{ => v1}/offer_credential.rs | 24 +- .../cred_issuance/{ => v1}/problem_report.rs | 16 +- .../{ => v1}/propose_credential.rs | 24 +- .../{ => v1}/request_credential.rs | 14 +- .../protocols/cred_issuance/v2/ack.rs | 90 +++++++ .../cred_issuance/v2/issue_credential.rs | 137 +++++++++++ .../protocols/cred_issuance/v2/mod.rs | 232 ++++++++++++++++++ .../cred_issuance/v2/offer_credential.rs | 149 +++++++++++ .../cred_issuance/v2/problem_report.rs | 135 ++++++++++ .../cred_issuance/v2/propose_credential.rs | 137 +++++++++++ .../cred_issuance/v2/request_credential.rs | 123 ++++++++++ .../msg_fields/protocols/notification/mod.rs | 5 +- .../msg_fields/protocols/present_proof/mod.rs | 15 +- .../src/msg_types/protocols/cred_issuance.rs | 118 ++++++++- messages/src/msg_types/registry.rs | 17 +- 44 files changed, 1783 insertions(+), 514 deletions(-) create mode 100644 messages/src/msg_fields/protocols/cred_issuance/common/mod.rs rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/ack.rs (81%) rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/issue_credential.rs (87%) create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v1/mod.rs rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/offer_credential.rs (81%) rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/problem_report.rs (88%) rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/propose_credential.rs (80%) rename messages/src/msg_fields/protocols/cred_issuance/{ => v1}/request_credential.rs (84%) create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/ack.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/problem_report.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs create mode 100644 messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs diff --git a/agents/rust/aries-vcx-agent/src/services/holder.rs b/agents/rust/aries-vcx-agent/src/services/holder.rs index 157d361203..85f7e9eb7d 100644 --- a/agents/rust/aries-vcx-agent/src/services/holder.rs +++ b/agents/rust/aries-vcx-agent/src/services/holder.rs @@ -4,9 +4,9 @@ use aries_vcx::{ core::profile::profile::Profile, handlers::issuance::holder::Holder, messages::{ - msg_fields::protocols::cred_issuance::{ - issue_credential::IssueCredential, offer_credential::OfferCredential, - propose_credential::ProposeCredential, + msg_fields::protocols::cred_issuance::v1::{ + issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1, + propose_credential::ProposeCredentialV1, }, AriesMessage, }, @@ -63,7 +63,7 @@ impl ServiceCredentialsHolder { pub async fn send_credential_proposal( &self, connection_id: &str, - propose_credential: ProposeCredential, + propose_credential: ProposeCredentialV1, ) -> AgentResult { let connection = self.service_connections.get_by_id(connection_id)?; let wallet = self.profile.inject_wallet(); @@ -83,7 +83,7 @@ impl ServiceCredentialsHolder { pub fn create_from_offer( &self, connection_id: &str, - offer: OfferCredential, + offer: OfferCredentialV1, ) -> AgentResult { self.service_connections.get_by_id(connection_id)?; let holder = Holder::create_from_offer("", offer)?; @@ -128,7 +128,7 @@ impl ServiceCredentialsHolder { pub async fn process_credential( &self, thread_id: &str, - msg_issue_credential: IssueCredential, + msg_issue_credential: IssueCredentialV1, ) -> AgentResult { let mut holder = self.get_holder(thread_id)?; let connection_id = self.get_connection_id(thread_id)?; diff --git a/agents/rust/aries-vcx-agent/src/services/issuer.rs b/agents/rust/aries-vcx-agent/src/services/issuer.rs index dd94371e83..0449917cf1 100644 --- a/agents/rust/aries-vcx-agent/src/services/issuer.rs +++ b/agents/rust/aries-vcx-agent/src/services/issuer.rs @@ -4,9 +4,9 @@ use aries_vcx::{ core::profile::profile::Profile, handlers::{issuance::issuer::Issuer, util::OfferInfo}, messages::{ - msg_fields::protocols::cred_issuance::{ - ack::AckCredential, propose_credential::ProposeCredential, - request_credential::RequestCredential, + msg_fields::protocols::cred_issuance::v1::{ + ack::AckCredentialV1, propose_credential::ProposeCredentialV1, + request_credential::RequestCredentialV1, }, AriesMessage, }, @@ -63,7 +63,7 @@ impl ServiceCredentialsIssuer { pub async fn accept_proposal( &self, connection_id: &str, - proposal: &ProposeCredential, + proposal: &ProposeCredentialV1, ) -> AgentResult { let issuer = Issuer::create_from_proposal("", proposal)?; self.creds_issuer.insert( @@ -106,7 +106,7 @@ impl ServiceCredentialsIssuer { pub fn process_credential_request( &self, thread_id: &str, - request: RequestCredential, + request: RequestCredentialV1, ) -> AgentResult<()> { let IssuerWrapper { mut issuer, @@ -120,7 +120,7 @@ impl ServiceCredentialsIssuer { Ok(()) } - pub fn process_credential_ack(&self, thread_id: &str, ack: AckCredential) -> AgentResult<()> { + pub fn process_credential_ack(&self, thread_id: &str, ack: AckCredentialV1) -> AgentResult<()> { let IssuerWrapper { mut issuer, connection_id, @@ -180,7 +180,7 @@ impl ServiceCredentialsIssuer { issuer.get_rev_id().map_err(|err| err.into()) } - pub fn get_proposal(&self, thread_id: &str) -> AgentResult { + pub fn get_proposal(&self, thread_id: &str) -> AgentResult { let issuer = self.get_issuer(thread_id)?; issuer.get_proposal().map_err(|err| err.into()) } diff --git a/aries_vcx/src/handlers/issuance/holder.rs b/aries_vcx/src/handlers/issuance/holder.rs index 5e0b3f045d..8d9ff70b0a 100644 --- a/aries_vcx/src/handlers/issuance/holder.rs +++ b/aries_vcx/src/handlers/issuance/holder.rs @@ -9,11 +9,14 @@ use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ - ack::{AckCredential, AckCredentialContent}, - issue_credential::IssueCredential, - offer_credential::OfferCredential, - propose_credential::ProposeCredential, - request_credential::RequestCredential, + v1::{ + ack::{AckCredentialV1, AckCredentialV1Content}, + issue_credential::IssueCredentialV1, + offer_credential::OfferCredentialV1, + propose_credential::ProposeCredentialV1, + request_credential::RequestCredentialV1, + CredentialIssuanceV1, + }, CredentialIssuance, }, notification::ack::{AckContent, AckDecorators, AckStatus}, @@ -34,8 +37,8 @@ use crate::{ protocols::issuance::holder::state_machine::{HolderFullState, HolderSM, HolderState}, }; -fn build_credential_ack(thread_id: &str) -> AckCredential { - let content = AckCredentialContent::builder() +fn build_credential_ack(thread_id: &str) -> AckCredentialV1 { + let content = AckCredentialV1Content::builder() .inner(AckContent::builder().status(AckStatus::Ok).build()) .build(); let decorators = AckDecorators::builder() @@ -43,7 +46,7 @@ fn build_credential_ack(thread_id: &str) -> AckCredential { .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - AckCredential::builder() + AckCredentialV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) @@ -64,7 +67,7 @@ impl Holder { pub fn create_with_proposal( source_id: &str, - propose_credential: ProposeCredential, + propose_credential: ProposeCredentialV1, ) -> VcxResult { trace!( "Holder::create_with_proposal >>> source_id: {:?}, propose_credential: {:?}", @@ -77,7 +80,7 @@ impl Holder { pub fn create_from_offer( source_id: &str, - credential_offer: OfferCredential, + credential_offer: OfferCredentialV1, ) -> VcxResult { trace!( "Holder::create_from_offer >>> source_id: {:?}, credential_offer: {:?}", @@ -88,7 +91,7 @@ impl Holder { Ok(Holder { holder_sm }) } - pub fn set_proposal(&mut self, credential_proposal: ProposeCredential) -> VcxResult<()> { + pub fn set_proposal(&mut self, credential_proposal: ProposeCredentialV1) -> VcxResult<()> { self.holder_sm = self.holder_sm.clone().set_proposal(credential_proposal)?; Ok(()) } @@ -115,10 +118,10 @@ impl Holder { } } - pub fn get_msg_credential_request(&self) -> VcxResult { + pub fn get_msg_credential_request(&self) -> VcxResult { match self.holder_sm.state { HolderFullState::RequestSet(ref state) => { - let mut msg: RequestCredential = state.msg_credential_request.clone(); + let mut msg: RequestCredentialV1 = state.msg_credential_request.clone(); let timing = Timing::builder().out_time(Utc::now()).build(); msg.decorators.timing = Some(timing); Ok(msg) @@ -142,7 +145,7 @@ impl Holder { &mut self, ledger: &Arc, anoncreds: &Arc, - credential: IssueCredential, + credential: IssueCredentialV1, ) -> VcxResult<()> { self.holder_sm = self .holder_sm @@ -176,7 +179,7 @@ impl Holder { self.holder_sm.get_attachment() } - pub fn get_offer(&self) -> VcxResult { + pub fn get_offer(&self) -> VcxResult { self.holder_sm.get_offer() } @@ -261,10 +264,12 @@ impl Holder { message: AriesMessage, ) -> VcxResult<()> { let holder_sm = match message { - AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(offer)) => { - self.holder_sm.clone().receive_offer(offer)? - } - AriesMessage::CredentialIssuance(CredentialIssuance::IssueCredential(credential)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(offer), + )) => self.holder_sm.clone().receive_offer(offer)?, + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::IssueCredential(credential), + )) => { self.holder_sm .clone() .receive_credential(ledger, anoncreds, credential) diff --git a/aries_vcx/src/handlers/issuance/issuer.rs b/aries_vcx/src/handlers/issuance/issuer.rs index 3b7eb78208..fa73b0a9c2 100644 --- a/aries_vcx/src/handlers/issuance/issuer.rs +++ b/aries_vcx/src/handlers/issuance/issuer.rs @@ -7,10 +7,13 @@ use messages::{ misc::MimeType, msg_fields::protocols::{ cred_issuance::{ - ack::AckCredential, issue_credential::IssueCredential, - offer_credential::OfferCredential, propose_credential::ProposeCredential, - request_credential::RequestCredential, CredentialAttr, CredentialIssuance, - CredentialPreview, + common::CredentialAttr, + v1::{ + ack::AckCredentialV1, issue_credential::IssueCredentialV1, + offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, + request_credential::RequestCredentialV1, CredentialIssuanceV1, CredentialPreviewV1, + }, + CredentialIssuance, }, notification::Notification, report_problem::ProblemReport, @@ -36,7 +39,7 @@ pub struct IssuerConfig { pub tails_file: Option, } -fn _build_credential_preview(credential_json: &str) -> VcxResult { +fn _build_credential_preview(credential_json: &str) -> VcxResult { trace!( "Issuer::_build_credential_preview >>> credential_json: {:?}", secret!(credential_json) @@ -115,7 +118,7 @@ fn _build_credential_preview(credential_json: &str) -> VcxResult {} }; - Ok(CredentialPreview::new(attributes)) + Ok(CredentialPreviewV1::new(attributes)) } impl Issuer { @@ -127,7 +130,7 @@ impl Issuer { pub fn create_from_proposal( source_id: &str, - credential_proposal: &ProposeCredential, + credential_proposal: &ProposeCredentialV1, ) -> VcxResult { trace!( "Issuer::create_from_proposal >>> source_id: {:?}, credential_proposal: {:?}", @@ -159,7 +162,7 @@ impl Issuer { Ok(()) } - pub fn get_credential_offer(&self) -> VcxResult { + pub fn get_credential_offer(&self) -> VcxResult { self.issuer_sm.get_credential_offer_msg() } @@ -168,12 +171,12 @@ impl Issuer { Ok(offer.into()) } - pub fn process_credential_request(&mut self, request: RequestCredential) -> VcxResult<()> { + pub fn process_credential_request(&mut self, request: RequestCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_request(request)?; Ok(()) } - pub fn process_credential_ack(&mut self, ack: AckCredential) -> VcxResult<()> { + pub fn process_credential_ack(&mut self, ack: AckCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_ack(ack)?; Ok(()) } @@ -183,7 +186,7 @@ impl Issuer { Ok(()) } - pub fn get_msg_issue_credential(&mut self) -> VcxResult { + pub fn get_msg_issue_credential(&mut self) -> VcxResult { self.issuer_sm.clone().get_msg_issue_credential() } @@ -253,7 +256,7 @@ impl Issuer { self.issuer_sm.thread_id() } - pub fn get_proposal(&self) -> VcxResult { + pub fn get_proposal(&self) -> VcxResult { self.issuer_sm.get_proposal() } @@ -269,17 +272,17 @@ impl Issuer { self.issuer_sm.is_revoked(ledger).await } - pub async fn receive_proposal(&mut self, proposal: ProposeCredential) -> VcxResult<()> { + pub async fn receive_proposal(&mut self, proposal: ProposeCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_proposal(proposal)?; Ok(()) } - pub async fn receive_request(&mut self, request: RequestCredential) -> VcxResult<()> { + pub async fn receive_request(&mut self, request: RequestCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_request(request)?; Ok(()) } - pub async fn receive_ack(&mut self, ack: AckCredential) -> VcxResult<()> { + pub async fn receive_ack(&mut self, ack: AckCredentialV1) -> VcxResult<()> { self.issuer_sm = self.issuer_sm.clone().receive_ack(ack)?; Ok(()) } @@ -299,15 +302,15 @@ impl Issuer { // todo: will ultimately end up in generic SM layer pub async fn process_aries_msg(&mut self, msg: AriesMessage) -> VcxResult<()> { let issuer_sm = match msg { - AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential(proposal)) => { - self.issuer_sm.clone().receive_proposal(proposal)? - } - AriesMessage::CredentialIssuance(CredentialIssuance::RequestCredential(request)) => { - self.issuer_sm.clone().receive_request(request)? - } - AriesMessage::CredentialIssuance(CredentialIssuance::Ack(ack)) => { - self.issuer_sm.clone().receive_ack(ack)? - } + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(proposal), + )) => self.issuer_sm.clone().receive_proposal(proposal)?, + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::RequestCredential(request), + )) => self.issuer_sm.clone().receive_request(request)?, + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::Ack(ack), + )) => self.issuer_sm.clone().receive_ack(ack)?, AriesMessage::ReportProblem(report) => { self.issuer_sm.clone().receive_problem_report(report)? } @@ -315,7 +318,9 @@ impl Issuer { .issuer_sm .clone() .receive_problem_report(report.into())?, - AriesMessage::CredentialIssuance(CredentialIssuance::ProblemReport(report)) => self + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProblemReport(report), + )) => self .issuer_sm .clone() .receive_problem_report(report.into())?, diff --git a/aries_vcx/src/handlers/issuance/mediated_holder.rs b/aries_vcx/src/handlers/issuance/mediated_holder.rs index c1cc8cd025..0b27b296b7 100644 --- a/aries_vcx/src/handlers/issuance/mediated_holder.rs +++ b/aries_vcx/src/handlers/issuance/mediated_holder.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; use messages::{ - msg_fields::protocols::{cred_issuance::CredentialIssuance, notification::Notification}, + msg_fields::protocols::{ + cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance}, + notification::Notification, + }, AriesMessage, }; @@ -22,8 +25,8 @@ pub fn holder_find_message_to_handle( for (uid, message) in messages { match sm.get_state() { HolderState::ProposalSet => { - if let AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential( - offer, + if let AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(offer), )) = &message { if matches_opt_thread_id!(offer, sm.get_thread_id().unwrap().as_str()) { @@ -32,15 +35,15 @@ pub fn holder_find_message_to_handle( } } HolderState::RequestSet => match &message { - AriesMessage::CredentialIssuance(CredentialIssuance::IssueCredential( - credential, + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::IssueCredential(credential), )) => { if matches_thread_id!(credential, sm.get_thread_id().unwrap().as_str()) { return Some((uid, message)); } } - AriesMessage::CredentialIssuance(CredentialIssuance::ProblemReport( - problem_report, + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProblemReport(problem_report), )) => { if matches_opt_thread_id!(problem_report, sm.get_thread_id().unwrap().as_str()) { diff --git a/aries_vcx/src/handlers/issuance/mediated_issuer.rs b/aries_vcx/src/handlers/issuance/mediated_issuer.rs index 29c66c8ad0..1b47fa3f59 100644 --- a/aries_vcx/src/handlers/issuance/mediated_issuer.rs +++ b/aries_vcx/src/handlers/issuance/mediated_issuer.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; use messages::{ - msg_fields::protocols::{cred_issuance::CredentialIssuance, notification::Notification}, + msg_fields::protocols::{ + cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance}, + notification::Notification, + }, AriesMessage, }; @@ -27,8 +30,9 @@ pub fn issuer_find_message_to_handle( for (uid, message) in messages { match sm.get_state() { IssuerState::Initial => { - if let AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential(_)) = - &message + if let AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(_), + )) = &message { info!( "In state IssuerState::OfferSet, found matching message ProposeCredential" @@ -37,7 +41,9 @@ pub fn issuer_find_message_to_handle( } } IssuerState::OfferSet => match &message { - AriesMessage::CredentialIssuance(CredentialIssuance::RequestCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::RequestCredential(msg), + )) => { info!( "In state IssuerState::OfferSet, found potentially matching message \ RequestCredential" @@ -48,7 +54,9 @@ pub fn issuer_find_message_to_handle( return Some((uid, message)); } } - AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(msg), + )) => { info!( "In state IssuerState::OfferSet, found potentially matching message \ ProposeCredential" @@ -66,7 +74,9 @@ pub fn issuer_find_message_to_handle( _ => {} }, IssuerState::CredentialSet => match &message { - AriesMessage::CredentialIssuance(CredentialIssuance::Ack(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::Ack(msg), + )) => { info!( "In state IssuerState::CredentialSet, found matching message \ CredentialIssuance::Ack" diff --git a/aries_vcx/src/handlers/out_of_band/receiver.rs b/aries_vcx/src/handlers/out_of_band/receiver.rs index e8205a1c26..2593cec6c5 100644 --- a/aries_vcx/src/handlers/out_of_band/receiver.rs +++ b/aries_vcx/src/handlers/out_of_band/receiver.rs @@ -7,8 +7,11 @@ use messages::{ decorators::{attachment::AttachmentType, thread::Thread}, msg_fields::protocols::{ cred_issuance::{ - issue_credential::IssueCredential, offer_credential::OfferCredential, - request_credential::RequestCredential, CredentialIssuance, + v1::{ + issue_credential::IssueCredentialV1, offer_credential::OfferCredentialV1, + request_credential::RequestCredentialV1, CredentialIssuanceV1, + }, + CredentialIssuance, }, out_of_band::{ invitation::{Invitation, OobService}, @@ -194,7 +197,7 @@ impl OutOfBandReceiver { Some(id) => match id { AttachmentId::CredentialOffer => { let mut offer = - OfferCredential::deserialize(&attach_json).map_err(|_| { + OfferCredentialV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), @@ -212,12 +215,12 @@ impl OutOfBandReceiver { } return Ok(Some(AriesMessage::CredentialIssuance( - CredentialIssuance::OfferCredential(offer), + CredentialIssuance::V1(CredentialIssuanceV1::OfferCredential(offer)), ))); } AttachmentId::CredentialRequest => { let mut request = - RequestCredential::deserialize(&attach_json).map_err(|_| { + RequestCredentialV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), @@ -235,12 +238,14 @@ impl OutOfBandReceiver { } return Ok(Some(AriesMessage::CredentialIssuance( - CredentialIssuance::RequestCredential(request), + CredentialIssuance::V1(CredentialIssuanceV1::RequestCredential( + request, + )), ))); } AttachmentId::Credential => { let mut credential = - IssueCredential::deserialize(&attach_json).map_err(|_| { + IssueCredentialV1::deserialize(&attach_json).map_err(|_| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, format!("Failed to deserialize attachment: {attach_json:?}"), @@ -250,7 +255,9 @@ impl OutOfBandReceiver { credential.decorators.thread.pthid = Some(self.oob.id.clone()); return Ok(Some(AriesMessage::CredentialIssuance( - CredentialIssuance::IssueCredential(credential), + CredentialIssuance::V1(CredentialIssuanceV1::IssueCredential( + credential, + )), ))); } AttachmentId::PresentationRequest => { diff --git a/aries_vcx/src/handlers/out_of_band/sender.rs b/aries_vcx/src/handlers/out_of_band/sender.rs index c48e3fb519..d49fbf0ce3 100644 --- a/aries_vcx/src/handlers/out_of_band/sender.rs +++ b/aries_vcx/src/handlers/out_of_band/sender.rs @@ -1,6 +1,6 @@ use messages::{ msg_fields::protocols::{ - cred_issuance::CredentialIssuance, + cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance}, out_of_band::{ invitation::{Invitation, InvitationContent, InvitationDecorators, OobService}, OobGoalCode, @@ -94,9 +94,9 @@ impl OutOfBandSender { AttachmentId::PresentationRequest, json!(&a2a_msg).to_string(), ), - a2a_msg @ AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(_)) => { - (AttachmentId::CredentialOffer, json!(&a2a_msg).to_string()) - } + a2a_msg @ AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(_), + )) => (AttachmentId::CredentialOffer, json!(&a2a_msg).to_string()), _ => { error!("Appended message type {:?} is not allowed.", msg); return Err(AriesVcxError::from_msg( diff --git a/aries_vcx/src/handlers/util.rs b/aries_vcx/src/handlers/util.rs index e6009e4605..56d0d5b621 100644 --- a/aries_vcx/src/handlers/util.rs +++ b/aries_vcx/src/handlers/util.rs @@ -1,7 +1,7 @@ use messages::{ msg_fields::protocols::{ connection::{invitation::Invitation, Connection}, - cred_issuance::CredentialIssuance, + cred_issuance::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance}, discover_features::DiscoverFeatures, notification::Notification, out_of_band::{invitation::Invitation as OobInvitation, OutOfBand}, @@ -92,22 +92,64 @@ pub fn verify_thread_id(thread_id: &str, message: &AriesMessage) -> VcxResult<() matches_opt_thread_id!(msg, thread_id) } AriesMessage::Connection(Connection::Response(msg)) => matches_thread_id!(msg, thread_id), - AriesMessage::CredentialIssuance(CredentialIssuance::Ack(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1(CredentialIssuanceV1::Ack( + msg, + ))) => { matches_thread_id!(msg, thread_id) } - AriesMessage::CredentialIssuance(CredentialIssuance::IssueCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::IssueCredential(msg), + )) => { matches_thread_id!(msg, thread_id) } - AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(msg), + )) => { matches_opt_thread_id!(msg, thread_id) } - AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(msg), + )) => { matches_opt_thread_id!(msg, thread_id) } - AriesMessage::CredentialIssuance(CredentialIssuance::RequestCredential(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::RequestCredential(msg), + )) => { matches_opt_thread_id!(msg, thread_id) } - AriesMessage::CredentialIssuance(CredentialIssuance::ProblemReport(msg)) => { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProblemReport(msg), + )) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2(CredentialIssuanceV2::Ack( + msg, + ))) => { + matches_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2( + CredentialIssuanceV2::IssueCredential(msg), + )) => { + matches_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2( + CredentialIssuanceV2::OfferCredential(msg), + )) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2( + CredentialIssuanceV2::ProposeCredential(msg), + )) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2( + CredentialIssuanceV2::RequestCredential(msg), + )) => { + matches_opt_thread_id!(msg, thread_id) + } + AriesMessage::CredentialIssuance(CredentialIssuance::V2( + CredentialIssuanceV2::ProblemReport(msg), + )) => { matches_opt_thread_id!(msg, thread_id) } AriesMessage::DiscoverFeatures(DiscoverFeatures::Query(msg)) => msg.id == thread_id, diff --git a/aries_vcx/src/protocols/issuance/holder/state_machine.rs b/aries_vcx/src/protocols/issuance/holder/state_machine.rs index 5f665e29e1..ca43201503 100644 --- a/aries_vcx/src/protocols/issuance/holder/state_machine.rs +++ b/aries_vcx/src/protocols/issuance/holder/state_machine.rs @@ -8,11 +8,14 @@ use messages::{ decorators::{thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ - issue_credential::IssueCredential, - offer_credential::OfferCredential, - propose_credential::ProposeCredential, - request_credential::{ - RequestCredential, RequestCredentialContent, RequestCredentialDecorators, + v1::{ + issue_credential::IssueCredentialV1, + offer_credential::OfferCredentialV1, + propose_credential::ProposeCredentialV1, + request_credential::{ + RequestCredentialV1, RequestCredentialV1Content, RequestCredentialV1Decorators, + }, + CredentialIssuanceV1, }, CredentialIssuance, }, @@ -80,20 +83,20 @@ impl fmt::Display for HolderFullState { fn _build_credential_request_msg( credential_request_attach: String, thread_id: &str, -) -> RequestCredential { - let content = RequestCredentialContent::builder() +) -> RequestCredentialV1 { + let content = RequestCredentialV1Content::builder() .requests_attach(vec![make_attach_from_str!( &credential_request_attach, AttachmentId::CredentialRequest.as_ref().to_string() )]) .build(); - let decorators = RequestCredentialDecorators::builder() + let decorators = RequestCredentialV1Decorators::builder() .thread(Thread::builder().thid(thread_id.to_owned()).build()) .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - RequestCredential::builder() + RequestCredentialV1::builder() .id(Uuid::new_v4().to_string()) .content(content) .decorators(decorators) @@ -109,7 +112,7 @@ impl HolderSM { } } - pub fn from_offer(offer: OfferCredential, source_id: String) -> Self { + pub fn from_offer(offer: OfferCredentialV1, source_id: String) -> Self { HolderSM { thread_id: offer.id.clone(), state: HolderFullState::OfferReceived(OfferReceivedState::new(offer)), @@ -117,7 +120,7 @@ impl HolderSM { } } - pub fn with_proposal(propose_credential: ProposeCredential, source_id: String) -> Self { + pub fn with_proposal(propose_credential: ProposeCredentialV1, source_id: String) -> Self { HolderSM { thread_id: propose_credential.id.clone(), state: HolderFullState::ProposalSet(ProposalSetState::new(propose_credential)), @@ -143,7 +146,7 @@ impl HolderSM { } #[allow(dead_code)] - pub fn get_proposal(&self) -> VcxResult { + pub fn get_proposal(&self) -> VcxResult { match &self.state { HolderFullState::ProposalSet(state) => Ok(state.credential_proposal.clone()), _ => Err(AriesVcxError::from_msg( @@ -153,12 +156,12 @@ impl HolderSM { } } - pub fn set_proposal(self, proposal: ProposeCredential) -> VcxResult { + pub fn set_proposal(self, proposal: ProposeCredentialV1) -> VcxResult { trace!("HolderSM::set_proposal >>"); verify_thread_id( &self.thread_id, - &AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential( - proposal.clone(), + &AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(proposal.clone()), )), )?; let state = match self.state { @@ -180,11 +183,13 @@ impl HolderSM { Ok(Self { state, ..self }) } - pub fn receive_offer(self, offer: OfferCredential) -> VcxResult { + pub fn receive_offer(self, offer: OfferCredentialV1) -> VcxResult { trace!("HolderSM::receive_offer >>"); verify_thread_id( &self.thread_id, - &AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(offer.clone())), + &AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(offer.clone()), + )), )?; let state = match self.state { HolderFullState::ProposalSet(_) => { @@ -261,7 +266,7 @@ impl HolderSM { self, ledger: &'a Arc, anoncreds: &'a Arc, - credential: IssueCredential, + credential: IssueCredentialV1, ) -> VcxResult { trace!("HolderSM::receive_credential >>"); let state = match self.state { @@ -403,7 +408,7 @@ impl HolderSM { } } - pub fn get_offer(&self) -> VcxResult { + pub fn get_offer(&self) -> VcxResult { match self.state { HolderFullState::OfferReceived(ref state) => Ok(state.offer.clone()), _ => Err(AriesVcxError::from_msg( @@ -529,7 +534,7 @@ fn _parse_rev_reg_id_from_credential(credential: &str) -> VcxResult, anoncreds: &Arc, - credential: &IssueCredential, + credential: &IssueCredentialV1, req_meta: &str, cred_def_json: &str, ) -> VcxResult<(String, Option)> { @@ -585,8 +590,8 @@ async fn build_credential_request_msg( anoncreds: &Arc, thread_id: String, my_pw_did: String, - offer: &OfferCredential, -) -> VcxResult<(RequestCredential, String, String)> { + offer: &OfferCredentialV1, +) -> VcxResult<(RequestCredentialV1, String, String)> { trace!( "Holder::_make_credential_request >>> my_pw_did: {:?}, offer: {:?}", my_pw_did, diff --git a/aries_vcx/src/protocols/issuance/holder/states/finished.rs b/aries_vcx/src/protocols/issuance/holder/states/finished.rs index f93e3e6dfc..55145a94c1 100644 --- a/aries_vcx/src/protocols/issuance/holder/states/finished.rs +++ b/aries_vcx/src/protocols/issuance/holder/states/finished.rs @@ -1,5 +1,5 @@ use messages::msg_fields::protocols::{ - cred_issuance::issue_credential::IssueCredential, report_problem::ProblemReport, + cred_issuance::v1::issue_credential::IssueCredentialV1, report_problem::ProblemReport, }; use crate::{ @@ -10,7 +10,7 @@ use crate::{ #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FinishedHolderState { pub cred_id: Option, - pub credential: Option, + pub credential: Option, pub status: Status, pub rev_reg_def_json: Option, pub ack_requested: Option, diff --git a/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs b/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs index 27a5f9b2de..3adf7af235 100644 --- a/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs +++ b/aries_vcx/src/protocols/issuance/holder/states/offer_received.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use aries_vcx_core::ledger::base_ledger::AnoncredsLedgerRead; -use messages::msg_fields::protocols::cred_issuance::offer_credential::OfferCredential; +use messages::msg_fields::protocols::cred_issuance::v1::offer_credential::OfferCredentialV1; use crate::{ errors::error::prelude::*, @@ -13,11 +13,11 @@ use crate::{ #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OfferReceivedState { - pub offer: OfferCredential, + pub offer: OfferCredentialV1, } impl OfferReceivedState { - pub fn new(offer: OfferCredential) -> Self { + pub fn new(offer: OfferCredentialV1) -> Self { OfferReceivedState { offer } } diff --git a/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs b/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs index 7f9ac0489a..f5352bad3b 100644 --- a/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs +++ b/aries_vcx/src/protocols/issuance/holder/states/proposal_set.rs @@ -1,17 +1,17 @@ use std::sync::Arc; use aries_vcx_core::ledger::base_ledger::AnoncredsLedgerRead; -use messages::msg_fields::protocols::cred_issuance::propose_credential::ProposeCredential; +use messages::msg_fields::protocols::cred_issuance::v1::propose_credential::ProposeCredentialV1; use crate::{errors::error::prelude::*, protocols::issuance::is_cred_def_revokable}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ProposalSetState { - pub credential_proposal: ProposeCredential, + pub credential_proposal: ProposeCredentialV1, } impl ProposalSetState { - pub fn new(credential_proposal: ProposeCredential) -> Self { + pub fn new(credential_proposal: ProposeCredentialV1) -> Self { Self { credential_proposal, } diff --git a/aries_vcx/src/protocols/issuance/holder/states/request_set.rs b/aries_vcx/src/protocols/issuance/holder/states/request_set.rs index 40b6c92cf6..e348378872 100644 --- a/aries_vcx/src/protocols/issuance/holder/states/request_set.rs +++ b/aries_vcx/src/protocols/issuance/holder/states/request_set.rs @@ -1,5 +1,5 @@ -use messages::msg_fields::protocols::cred_issuance::{ - issue_credential::IssueCredential, request_credential::RequestCredential, +use messages::msg_fields::protocols::cred_issuance::v1::{ + issue_credential::IssueCredentialV1, request_credential::RequestCredentialV1, }; use crate::{ @@ -11,15 +11,15 @@ use crate::{ pub struct RequestSetState { pub req_meta: String, pub cred_def_json: String, - pub msg_credential_request: RequestCredential, + pub msg_credential_request: RequestCredentialV1, } -impl From<(RequestSetState, String, IssueCredential, Option)> for FinishedHolderState { +impl From<(RequestSetState, String, IssueCredentialV1, Option)> for FinishedHolderState { fn from( (_, cred_id, credential, rev_reg_def_json): ( RequestSetState, String, - IssueCredential, + IssueCredentialV1, Option, ), ) -> Self { diff --git a/aries_vcx/src/protocols/issuance/issuer/state_machine.rs b/aries_vcx/src/protocols/issuance/issuer/state_machine.rs index 4f984f9024..a2b897203f 100644 --- a/aries_vcx/src/protocols/issuance/issuer/state_machine.rs +++ b/aries_vcx/src/protocols/issuance/issuer/state_machine.rs @@ -8,16 +8,19 @@ use messages::{ decorators::{please_ack::PleaseAck, thread::Thread, timing::Timing}, msg_fields::protocols::{ cred_issuance::{ - ack::AckCredential, - issue_credential::{ - IssueCredential, IssueCredentialContent, IssueCredentialDecorators, + v1::{ + ack::AckCredentialV1, + issue_credential::{ + IssueCredentialV1, IssueCredentialV1Content, IssueCredentialV1Decorators, + }, + offer_credential::{ + OfferCredentialV1, OfferCredentialV1Content, OfferCredentialV1Decorators, + }, + propose_credential::ProposeCredentialV1, + request_credential::RequestCredentialV1, + CredentialIssuanceV1, CredentialPreviewV1, }, - offer_credential::{ - OfferCredential, OfferCredentialContent, OfferCredentialDecorators, - }, - propose_credential::ProposeCredential, - request_credential::RequestCredential, - CredentialIssuance, CredentialPreview, + CredentialIssuance, }, report_problem::ProblemReport, }, @@ -97,22 +100,22 @@ pub struct IssuerSM { pub(crate) state: IssuerFullState, } -fn build_credential_message(libindy_credential: String, thread_id: String) -> IssueCredential { +fn build_credential_message(libindy_credential: String, thread_id: String) -> IssueCredentialV1 { let id = Uuid::new_v4().to_string(); - let content = IssueCredentialContent::builder() + let content = IssueCredentialV1Content::builder() .credentials_attach(vec![make_attach_from_str!( &libindy_credential, AttachmentId::Credential.as_ref().to_string() )]) .build(); - let decorators = IssueCredentialDecorators::builder() + let decorators = IssueCredentialV1Decorators::builder() .thread(Thread::builder().thid(thread_id).build()) .please_ack(PleaseAck::builder().on(vec![]).build()) .build(); - IssueCredential::builder() + IssueCredentialV1::builder() .id(id) .content(content) .decorators(decorators) @@ -122,12 +125,12 @@ fn build_credential_message(libindy_credential: String, thread_id: String) -> Is fn build_credential_offer( thread_id: &str, credential_offer: &str, - credential_preview: CredentialPreview, + credential_preview: CredentialPreviewV1, comment: Option, -) -> VcxResult { +) -> VcxResult { let id = thread_id.to_owned(); - let content = OfferCredentialContent::builder() + let content = OfferCredentialV1Content::builder() .credential_preview(credential_preview) .offers_attach(vec![make_attach_from_str!( &credential_offer, @@ -140,11 +143,11 @@ fn build_credential_offer( content.build() }; - let decorators = OfferCredentialDecorators::builder() + let decorators = OfferCredentialV1Decorators::builder() .timing(Timing::builder().out_time(Utc::now()).build()) .build(); - Ok(OfferCredential::builder() + Ok(OfferCredentialV1::builder() .id(id) .content(content) .decorators(decorators) @@ -160,7 +163,7 @@ impl IssuerSM { } } - pub fn from_proposal(source_id: &str, credential_proposal: &ProposeCredential) -> Self { + pub fn from_proposal(source_id: &str, credential_proposal: &ProposeCredentialV1) -> Self { Self { thread_id: credential_proposal.id.clone(), source_id: source_id.to_string(), @@ -299,7 +302,7 @@ impl IssuerSM { } } - pub fn get_proposal(&self) -> VcxResult { + pub fn get_proposal(&self) -> VcxResult { match &self.state { IssuerFullState::ProposalReceived(state) => Ok(state.credential_proposal.clone()), _ => Err(AriesVcxError::from_msg( @@ -312,7 +315,7 @@ impl IssuerSM { pub fn build_credential_offer_msg( self, credential_offer: &str, - credential_preview: CredentialPreview, + credential_preview: CredentialPreviewV1, comment: Option, offer_info: &OfferInfo, ) -> VcxResult { @@ -350,7 +353,7 @@ impl IssuerSM { Ok(Self::step(source_id, thread_id, state)) } - pub fn get_credential_offer_msg(&self) -> VcxResult { + pub fn get_credential_offer_msg(&self) -> VcxResult { match &self.state { IssuerFullState::OfferSet(state) => Ok(state.offer.clone()), _ => Err(AriesVcxError::from_msg( @@ -363,11 +366,11 @@ impl IssuerSM { } } - pub fn receive_proposal(self, proposal: ProposeCredential) -> VcxResult { + pub fn receive_proposal(self, proposal: ProposeCredentialV1) -> VcxResult { verify_thread_id( &self.thread_id, - &AriesMessage::CredentialIssuance(CredentialIssuance::ProposeCredential( - proposal.clone(), + &AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::ProposeCredential(proposal.clone()), )), )?; let (state, thread_id) = match self.state { @@ -394,11 +397,11 @@ impl IssuerSM { }) } - pub fn receive_request(self, request: RequestCredential) -> VcxResult { + pub fn receive_request(self, request: RequestCredentialV1) -> VcxResult { verify_thread_id( &self.thread_id, - &AriesMessage::CredentialIssuance(CredentialIssuance::RequestCredential( - request.clone(), + &AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::RequestCredential(request.clone()), )), )?; let state = match self.state { @@ -465,10 +468,10 @@ impl IssuerSM { Ok(Self { state, ..self }) } - pub fn get_msg_issue_credential(self) -> VcxResult { + pub fn get_msg_issue_credential(self) -> VcxResult { match self.state { IssuerFullState::CredentialSet(ref state_data) => { - let mut msg_issue_credential: IssueCredential = + let mut msg_issue_credential: IssueCredentialV1 = state_data.msg_issue_credential.clone(); let timing = Timing::builder().out_time(Utc::now()).build(); @@ -482,10 +485,12 @@ impl IssuerSM { } } - pub fn receive_ack(self, ack: AckCredential) -> VcxResult { + pub fn receive_ack(self, ack: AckCredentialV1) -> VcxResult { verify_thread_id( &self.thread_id, - &AriesMessage::CredentialIssuance(CredentialIssuance::Ack(ack.clone())), + &AriesMessage::CredentialIssuance(CredentialIssuance::V1(CredentialIssuanceV1::Ack( + ack.clone(), + ))), )?; let state = match self.state { IssuerFullState::CredentialSet(state_data) => { @@ -556,13 +561,13 @@ impl IssuerSM { async fn create_credential( anoncreds: &Arc, - request: &RequestCredential, + request: &RequestCredentialV1, rev_reg_id: &Option, tails_file: &Option, - offer: &OfferCredential, + offer: &OfferCredentialV1, cred_data: &str, thread_id: String, -) -> VcxResult<(IssueCredential, Option)> { +) -> VcxResult<(IssueCredentialV1, Option)> { let offer = get_attach_as_string!(&offer.content.offers_attach); trace!( diff --git a/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs b/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs index c927935090..343d6dea82 100644 --- a/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs +++ b/aries_vcx/src/protocols/issuance/issuer/states/credential_set.rs @@ -1,4 +1,4 @@ -use messages::msg_fields::protocols::cred_issuance::issue_credential::IssueCredential; +use messages::msg_fields::protocols::cred_issuance::v1::issue_credential::IssueCredentialV1; use crate::{ handlers::util::Status, @@ -10,7 +10,7 @@ use crate::{ #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CredentialSetState { pub revocation_info_v1: Option, - pub msg_issue_credential: IssueCredential, + pub msg_issue_credential: IssueCredentialV1, } impl FinishedState { diff --git a/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs b/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs index cc3179638e..7339d1771e 100644 --- a/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs +++ b/aries_vcx/src/protocols/issuance/issuer/states/offer_set.rs @@ -1,5 +1,7 @@ use messages::msg_fields::protocols::{ - cred_issuance::{offer_credential::OfferCredential, request_credential::RequestCredential}, + cred_issuance::v1::{ + offer_credential::OfferCredentialV1, request_credential::RequestCredentialV1, + }, report_problem::ProblemReport, }; @@ -13,7 +15,7 @@ use crate::{ #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OfferSetState { - pub offer: OfferCredential, + pub offer: OfferCredentialV1, pub credential_json: String, pub cred_def_id: String, pub rev_reg_id: Option, @@ -22,7 +24,7 @@ pub struct OfferSetState { impl OfferSetState { pub fn new( - cred_offer_msg: OfferCredential, + cred_offer_msg: OfferCredentialV1, credential_json: &str, cred_def_id: &str, rev_reg_id: Option, @@ -39,7 +41,7 @@ impl OfferSetState { } impl RequestReceivedState { - pub fn from_offer_set_and_request(state: OfferSetState, request: RequestCredential) -> Self { + pub fn from_offer_set_and_request(state: OfferSetState, request: RequestCredentialV1) -> Self { trace!("SM is now in Request Received state"); RequestReceivedState { offer: state.offer, diff --git a/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs b/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs index 2ab4ca834b..7e13f75881 100644 --- a/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs +++ b/aries_vcx/src/protocols/issuance/issuer/states/proposal_received.rs @@ -1,15 +1,15 @@ -use messages::msg_fields::protocols::cred_issuance::propose_credential::ProposeCredential; +use messages::msg_fields::protocols::cred_issuance::v1::propose_credential::ProposeCredentialV1; use crate::handlers::util::OfferInfo; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ProposalReceivedState { - pub credential_proposal: ProposeCredential, + pub credential_proposal: ProposeCredentialV1, pub offer_info: Option, } impl ProposalReceivedState { - pub fn new(credential_proposal: ProposeCredential, offer_info: Option) -> Self { + pub fn new(credential_proposal: ProposeCredentialV1, offer_info: Option) -> Self { Self { credential_proposal, offer_info, diff --git a/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs b/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs index 1925f4bac5..2c0718fb53 100644 --- a/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs +++ b/aries_vcx/src/protocols/issuance/issuer/states/requested_received.rs @@ -1,5 +1,7 @@ use messages::msg_fields::protocols::{ - cred_issuance::{offer_credential::OfferCredential, request_credential::RequestCredential}, + cred_issuance::v1::{ + offer_credential::OfferCredentialV1, request_credential::RequestCredentialV1, + }, report_problem::ProblemReport, }; @@ -13,11 +15,11 @@ use crate::{ // TODO: Use OfferInfo instead of ind. fields #[derive(Serialize, Deserialize, Debug, Clone)] pub struct RequestReceivedState { - pub offer: OfferCredential, + pub offer: OfferCredentialV1, pub cred_data: String, pub rev_reg_id: Option, pub tails_file: Option, - pub request: RequestCredential, + pub request: RequestCredentialV1, } impl FinishedState { diff --git a/aries_vcx/src/utils/filters.rs b/aries_vcx/src/utils/filters.rs index 6015b6119f..293ce6f7d1 100644 --- a/aries_vcx/src/utils/filters.rs +++ b/aries_vcx/src/utils/filters.rs @@ -1,7 +1,7 @@ use messages::{ decorators::attachment::Attachment, msg_fields::protocols::{ - cred_issuance::offer_credential::OfferCredential, + cred_issuance::v1::offer_credential::OfferCredentialV1, present_proof::request::RequestPresentation, }, }; @@ -52,16 +52,20 @@ fn _filter_proof_requests_by_name( Ok(filtered) } -fn _filter_offers_by_comment(offers: &str, match_comment: &str) -> VcxResult> { - let credential_offers: Vec = serde_json::from_str(offers).map_err(|err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidJson, - format!( - "Failed to deserialize Vec: {}\nObtained error: {:?}", - offers, err - ), - ) - })?; +fn _filter_offers_by_comment( + offers: &str, + match_comment: &str, +) -> VcxResult> { + let credential_offers: Vec = + serde_json::from_str(offers).map_err(|err| { + AriesVcxError::from_msg( + AriesVcxErrorKind::InvalidJson, + format!( + "Failed to deserialize Vec: {}\nObtained error: {:?}", + offers, err + ), + ) + })?; let filtered = credential_offers .into_iter() .filter_map(|credential_offer| match &credential_offer.content.comment { @@ -90,7 +94,7 @@ pub fn filter_proof_requests_by_name(requests: &str, name: &str) -> VcxResult VcxResult { - let credential_offers: Vec = _filter_offers_by_comment(offers, comment)?; + let credential_offers: Vec = _filter_offers_by_comment(offers, comment)?; let filtered: String = serde_json::to_string(&credential_offers).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, diff --git a/aries_vcx/tests/utils/scenarios/credential_issuance.rs b/aries_vcx/tests/utils/scenarios/credential_issuance.rs index 06f6a8c031..403ea141a0 100644 --- a/aries_vcx/tests/utils/scenarios/credential_issuance.rs +++ b/aries_vcx/tests/utils/scenarios/credential_issuance.rs @@ -23,9 +23,9 @@ use aries_vcx::{ utils::constants::TEST_TAILS_URL, }; use messages::msg_fields::protocols::{ - cred_issuance::{ - offer_credential::OfferCredential, propose_credential::ProposeCredential, - request_credential::RequestCredential, + cred_issuance::v1::{ + offer_credential::OfferCredentialV1, propose_credential::ProposeCredentialV1, + request_credential::RequestCredentialV1, }, report_problem::ProblemReport, }; @@ -70,13 +70,13 @@ pub async fn create_address_schema_creddef_revreg( (schema, cred_def, rev_reg) } -pub fn create_holder_from_proposal(proposal: ProposeCredential) -> Holder { +pub fn create_holder_from_proposal(proposal: ProposeCredentialV1) -> Holder { let holder = Holder::create_with_proposal("TEST_CREDENTIAL", proposal).unwrap(); assert_eq!(HolderState::ProposalSet, holder.get_state()); holder } -pub fn create_issuer_from_proposal(proposal: ProposeCredential) -> Issuer { +pub fn create_issuer_from_proposal(proposal: ProposeCredentialV1) -> Issuer { let issuer = Issuer::create_from_proposal("TEST_CREDENTIAL", &proposal).unwrap(); assert_eq!(IssuerState::ProposalReceived, issuer.get_state()); assert_eq!(proposal.clone(), issuer.get_proposal().unwrap()); @@ -86,10 +86,10 @@ pub fn create_issuer_from_proposal(proposal: ProposeCredential) -> Issuer { pub async fn accept_credential_proposal( faber: &mut TestAgent, issuer: &mut Issuer, - cred_proposal: ProposeCredential, + cred_proposal: ProposeCredentialV1, rev_reg_id: Option, tails_dir: Option, -) -> OfferCredential { +) -> OfferCredentialV1 { let offer_info = OfferInfo { credential_json: json!(cred_proposal.content.credential_proposal.attributes).to_string(), cred_def_id: cred_proposal.content.cred_def_id.clone(), @@ -109,9 +109,9 @@ pub async fn accept_credential_proposal( pub async fn accept_offer( alice: &mut TestAgent, - cred_offer: OfferCredential, + cred_offer: OfferCredentialV1, holder: &mut Holder, -) -> RequestCredential { +) -> RequestCredentialV1 { // TODO: Replace with message-specific handler holder .process_aries_msg( @@ -140,7 +140,7 @@ pub async fn accept_offer( pub async fn decline_offer( alice: &mut TestAgent, - cred_offer: OfferCredential, + cred_offer: OfferCredentialV1, holder: &mut Holder, ) -> ProblemReport { // TODO: Replace with message-specific handler @@ -163,7 +163,7 @@ pub async fn send_credential( faber: &mut TestAgent, issuer_credential: &mut Issuer, holder_credential: &mut Holder, - cred_request: RequestCredential, + cred_request: RequestCredentialV1, revokable: bool, ) { let thread_id = issuer_credential.get_thread_id().unwrap(); @@ -329,7 +329,7 @@ async fn create_credential_offer( issuer } -async fn create_credential_request(alice: &mut TestAgent, cred_offer: OfferCredential) -> Holder { +async fn create_credential_request(alice: &mut TestAgent, cred_offer: OfferCredentialV1) -> Holder { let mut holder = Holder::create_from_offer("TEST_CREDENTIAL", cred_offer).unwrap(); assert_eq!(HolderState::OfferReceived, holder.get_state()); holder diff --git a/aries_vcx/tests/utils/scenarios/data.rs b/aries_vcx/tests/utils/scenarios/data.rs index f3740bddf1..4dbd7a049c 100644 --- a/aries_vcx/tests/utils/scenarios/data.rs +++ b/aries_vcx/tests/utils/scenarios/data.rs @@ -2,8 +2,11 @@ use messages::{ misc::MimeType, msg_fields::protocols::{ cred_issuance::{ - propose_credential::{ProposeCredential, ProposeCredentialContent}, - CredentialAttr, CredentialPreview, + common::CredentialAttr, + v1::{ + propose_credential::{ProposeCredentialV1, ProposeCredentialV1Content}, + CredentialPreviewV1, + }, }, present_proof::propose::PresentationAttr, }, @@ -66,7 +69,7 @@ pub fn create_credential_proposal( schema_id: &str, cred_def_id: &str, comment: &str, -) -> ProposeCredential { +) -> ProposeCredentialV1 { let attrs = credential_data_address_1() .as_object() .unwrap() @@ -79,13 +82,13 @@ pub fn create_credential_proposal( .build() }) .collect(); - let content = ProposeCredentialContent::builder() - .credential_proposal(CredentialPreview::new(attrs)) + let content = ProposeCredentialV1Content::builder() + .credential_proposal(CredentialPreviewV1::new(attrs)) .schema_id(schema_id.to_owned()) .cred_def_id(cred_def_id.to_owned()) .comment(comment.to_owned()) .build(); - ProposeCredential::builder() + ProposeCredentialV1::builder() .id("test".to_owned()) .content(content) .build() diff --git a/libvcx_core/src/api_vcx/api_handle/credential.rs b/libvcx_core/src/api_vcx/api_handle/credential.rs index d4530a098c..fca70c9cb8 100644 --- a/libvcx_core/src/api_vcx/api_handle/credential.rs +++ b/libvcx_core/src/api_vcx/api_handle/credential.rs @@ -4,7 +4,8 @@ use aries_vcx::{ handlers::issuance::{holder::Holder, mediated_holder::holder_find_message_to_handle}, messages::{ msg_fields::protocols::cred_issuance::{ - offer_credential::OfferCredential, CredentialIssuance, + v1::{offer_credential::OfferCredentialV1, CredentialIssuanceV1}, + CredentialIssuance, }, AriesMessage, }, @@ -62,7 +63,7 @@ fn create_credential(source_id: &str, offer: &str) -> LibvcxResult offer, }; - if let Ok(cred_offer) = serde_json::from_value::(offer_message) { + if let Ok(cred_offer) = serde_json::from_value::(offer_message) { return Ok(Some(Holder::create_from_offer(source_id, cred_offer)?)); } @@ -77,7 +78,7 @@ pub fn credential_create_with_offer(source_id: &str, offer: &str) -> LibvcxResul secret!(&offer) ); - let cred_offer: OfferCredential = serde_json::from_str(offer).map_err(|err| { + let cred_offer: OfferCredentialV1 = serde_json::from_str(offer).map_err(|err| { LibvcxError::from_msg( LibvcxErrorKind::InvalidJson, format!( @@ -285,20 +286,21 @@ async fn get_credential_offer_msg(connection_handle: u32, msg_id: &str) -> Libvc AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); AgencyMockDecrypted::set_next_decrypted_message(ARIES_CREDENTIAL_OFFER); } - let credential_offer = match mediated_connection::get_message_by_id(connection_handle, msg_id) - .await - { - Ok(message) => match message { - AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(_)) => Ok(message), - msg => { - return Err(LibvcxError::from_msg( - LibvcxErrorKind::InvalidMessages, - format!("Message of different type was received: {:?}", msg), - )); - } - }, - Err(err) => Err(err), - }?; + let credential_offer = + match mediated_connection::get_message_by_id(connection_handle, msg_id).await { + Ok(message) => match message { + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(_), + )) => Ok(message), + msg => { + return Err(LibvcxError::from_msg( + LibvcxErrorKind::InvalidMessages, + format!("Message of different type was received: {:?}", msg), + )); + } + }, + Err(err) => Err(err), + }?; serde_json::to_string(&credential_offer).map_err(|err| { LibvcxError::from_msg( @@ -323,9 +325,9 @@ pub async fn get_credential_offer_messages_with_conn_handle( .await? .into_iter() .filter_map(|(_, a2a_message)| match a2a_message { - AriesMessage::CredentialIssuance(CredentialIssuance::OfferCredential(_)) => { - Some(a2a_message) - } + AriesMessage::CredentialIssuance(CredentialIssuance::V1( + CredentialIssuanceV1::OfferCredential(_), + )) => Some(a2a_message), _ => None, }) .collect(); @@ -413,7 +415,7 @@ pub mod tests_utils { #[allow(clippy::unwrap_used)] pub mod tests { use aries_vcx::{ - messages::msg_fields::protocols::cred_issuance::issue_credential::IssueCredential, + messages::msg_fields::protocols::cred_issuance::v1::issue_credential::IssueCredentialV1, protocols::issuance::holder::state_machine::HolderState, utils::{ devsetup::{SetupDefaults, SetupMocks}, @@ -574,7 +576,7 @@ pub mod tests { "full_credential_test:: going to deserialize credential: {:?}", msg_value ); - let _credential_struct: IssueCredential = + let _credential_struct: IssueCredentialV1 = serde_json::from_str(msg_value.to_string().as_str()).unwrap(); info!("full_credential_test:: going get offered attributes from final state"); @@ -619,7 +621,7 @@ pub mod tests { .unwrap(); let o: serde_json::Value = serde_json::from_str(&offer).unwrap(); debug!("Serialized credential offer: {:?}", &o[0]); - let _credential_offer: OfferCredential = serde_json::from_str(&o[0].to_string()).unwrap(); + let _credential_offer: OfferCredentialV1 = serde_json::from_str(&o[0].to_string()).unwrap(); } #[tokio::test] @@ -629,7 +631,7 @@ pub mod tests { let handle = from_string(CREDENTIAL_SM_FINISHED).unwrap(); let cred_string: String = get_credential(handle).unwrap(); let cred_value: serde_json::Value = serde_json::from_str(&cred_string).unwrap(); - let _credential_struct: IssueCredential = + let _credential_struct: IssueCredentialV1 = serde_json::from_str(cred_value.to_string().as_str()).unwrap(); } } diff --git a/messages/src/lib.rs b/messages/src/lib.rs index 828cafa2de..6ac2d5d9f9 100644 --- a/messages/src/lib.rs +++ b/messages/src/lib.rs @@ -15,13 +15,19 @@ pub mod msg_types; use derive_more::From; use misc::utils; -use msg_types::{report_problem::ReportProblemTypeV1_0, routing::RoutingTypeV1_0, MsgWithType}; +use msg_fields::protocols::cred_issuance::{ + v1::CredentialIssuanceV1, v2::CredentialIssuanceV2, CredentialIssuance, +}; +use msg_types::{ + cred_issuance::CredentialIssuanceType, report_problem::ReportProblemTypeV1_0, + routing::RoutingTypeV1_0, MsgWithType, +}; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; use crate::{ msg_fields::{ protocols::{ - basic_message::BasicMessage, connection::Connection, cred_issuance::CredentialIssuance, + basic_message::BasicMessage, connection::Connection, discover_features::DiscoverFeatures, notification::Notification, out_of_band::OutOfBand, present_proof::PresentProof, report_problem::ProblemReport, revocation::Revocation, routing::Forward, trust_ping::TrustPing, @@ -100,9 +106,19 @@ impl DelayedSerde for AriesMessage { Protocol::RevocationType(msg_type) => { Revocation::delayed_deserialize((msg_type, kind_str), deserializer).map(From::from) } - Protocol::CredentialIssuanceType(msg_type) => { - CredentialIssuance::delayed_deserialize((msg_type, kind_str), deserializer) - .map(From::from) + Protocol::CredentialIssuanceType(CredentialIssuanceType::V1(msg_type)) => { + CredentialIssuanceV1::delayed_deserialize( + (CredentialIssuanceType::V1(msg_type), kind_str), + deserializer, + ) + .map(|x| AriesMessage::from(CredentialIssuance::V1(x))) + } + Protocol::CredentialIssuanceType(CredentialIssuanceType::V2(msg_type)) => { + CredentialIssuanceV2::delayed_deserialize( + (CredentialIssuanceType::V2(msg_type), kind_str), + deserializer, + ) + .map(|x| AriesMessage::from(CredentialIssuance::V2(x))) } Protocol::ReportProblemType(msg_type) => { let kind = match msg_type { @@ -159,7 +175,8 @@ impl DelayedSerde for AriesMessage { Self::Routing(v) => MsgWithType::from(v).serialize(serializer), Self::Connection(v) => v.delayed_serialize(serializer), Self::Revocation(v) => v.delayed_serialize(serializer), - Self::CredentialIssuance(v) => v.delayed_serialize(serializer), + Self::CredentialIssuance(CredentialIssuance::V1(v)) => v.delayed_serialize(serializer), + Self::CredentialIssuance(CredentialIssuance::V2(v)) => v.delayed_serialize(serializer), Self::ReportProblem(v) => MsgWithType::from(v).serialize(serializer), Self::PresentProof(v) => v.delayed_serialize(serializer), Self::TrustPing(v) => v.delayed_serialize(serializer), diff --git a/messages/src/msg_fields/protocols/cred_issuance/common/mod.rs b/messages/src/msg_fields/protocols/cred_issuance/common/mod.rs new file mode 100644 index 0000000000..d2feabd431 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/common/mod.rs @@ -0,0 +1,15 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::misc::MimeType; + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] +#[serde(rename_all = "kebab-case")] +pub struct CredentialAttr { + pub name: String, + pub value: String, + #[builder(default, setter(strip_option))] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "mime-type")] + pub mime_type: Option, +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/mod.rs b/messages/src/msg_fields/protocols/cred_issuance/mod.rs index 9e1bf997c6..1ff283a530 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/mod.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/mod.rs @@ -1,218 +1,13 @@ -//! Module containing the `issue credential` protocol messages, as defined in the [RFC](). - -pub mod ack; -pub mod issue_credential; -pub mod offer_credential; -pub mod problem_report; -pub mod propose_credential; -pub mod request_credential; - -use std::str::FromStr; - use derive_more::From; -use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; -use shared_vcx::misc::utils::CowStr; -use typed_builder::TypedBuilder; -use self::{ - ack::{AckCredential, AckCredentialContent}, - issue_credential::{IssueCredential, IssueCredentialContent, IssueCredentialDecorators}, - offer_credential::{OfferCredential, OfferCredentialContent, OfferCredentialDecorators}, - problem_report::{CredIssuanceProblemReport, CredIssuanceProblemReportContent}, - propose_credential::{ - ProposeCredential, ProposeCredentialContent, ProposeCredentialDecorators, - }, - request_credential::{ - RequestCredential, RequestCredentialContent, RequestCredentialDecorators, - }, -}; -use super::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}; -use crate::{ - misc::{ - utils::{self, into_msg_with_type, transit_to_aries_msg}, - MimeType, - }, - msg_fields::traits::DelayedSerde, - msg_types::{ - protocols::cred_issuance::{ - CredentialIssuanceType as CredentialIssuanceKind, CredentialIssuanceTypeV1, - CredentialIssuanceTypeV1_0, - }, - traits::MessageKind, - MessageType, MsgWithType, Protocol, - }, -}; +use self::{v1::CredentialIssuanceV1, v2::CredentialIssuanceV2}; + +pub mod common; +pub mod v1; +pub mod v2; #[derive(Clone, Debug, From, PartialEq)] pub enum CredentialIssuance { - OfferCredential(OfferCredential), - ProposeCredential(ProposeCredential), - RequestCredential(RequestCredential), - IssueCredential(IssueCredential), - Ack(AckCredential), - ProblemReport(CredIssuanceProblemReport), -} - -impl DelayedSerde for CredentialIssuance { - type MsgType<'a> = (CredentialIssuanceKind, &'a str); - - fn delayed_deserialize<'de, D>( - msg_type: Self::MsgType<'de>, - deserializer: D, - ) -> Result - where - D: Deserializer<'de>, - { - let (protocol, kind_str) = msg_type; - let kind = match protocol { - CredentialIssuanceKind::V1(CredentialIssuanceTypeV1::V1_0(kind)) => { - kind.kind_from_str(kind_str) - } - }; - - match kind.map_err(D::Error::custom)? { - CredentialIssuanceTypeV1_0::OfferCredential => { - OfferCredential::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::ProposeCredential => { - ProposeCredential::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::RequestCredential => { - RequestCredential::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::IssueCredential => { - IssueCredential::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::Ack => { - AckCredential::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::ProblemReport => { - CredIssuanceProblemReport::deserialize(deserializer).map(From::from) - } - CredentialIssuanceTypeV1_0::CredentialPreview => { - Err(utils::not_standalone_msg::(kind_str)) - } - } - } - - fn delayed_serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - match self { - Self::OfferCredential(v) => MsgWithType::from(v).serialize(serializer), - Self::ProposeCredential(v) => MsgWithType::from(v).serialize(serializer), - Self::RequestCredential(v) => MsgWithType::from(v).serialize(serializer), - Self::IssueCredential(v) => MsgWithType::from(v).serialize(serializer), - Self::Ack(v) => MsgWithType::from(v).serialize(serializer), - Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), - } - } -} - -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] -pub struct CredentialPreview { - #[serde(rename = "@type")] - msg_type: CredentialPreviewMsgType, - pub attributes: Vec, + V1(CredentialIssuanceV1), + V2(CredentialIssuanceV2), } - -impl CredentialPreview { - pub fn new(attributes: Vec) -> Self { - Self { - msg_type: CredentialPreviewMsgType, - attributes, - } - } -} - -/// Non-standalone message type. -/// This is only encountered as part of an existent message. -/// It is not a message on it's own. -#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq)] -#[serde(try_from = "CowStr")] -struct CredentialPreviewMsgType; - -impl<'a> From<&'a CredentialPreviewMsgType> for CredentialIssuanceTypeV1_0 { - fn from(_value: &'a CredentialPreviewMsgType) -> Self { - CredentialIssuanceTypeV1_0::CredentialPreview - } -} - -impl<'a> TryFrom> for CredentialPreviewMsgType { - type Error = String; - - fn try_from(value: CowStr) -> Result { - let value = MessageType::try_from(value.0.as_ref())?; - - if let Protocol::CredentialIssuanceType(CredentialIssuanceKind::V1( - CredentialIssuanceTypeV1::V1_0(_), - )) = value.protocol - { - if let Ok(CredentialIssuanceTypeV1_0::CredentialPreview) = - CredentialIssuanceTypeV1_0::from_str(value.kind) - { - return Ok(CredentialPreviewMsgType); - } - } - - Err(format!("message kind is not {}", value.kind)) - } -} - -impl Serialize for CredentialPreviewMsgType { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - let protocol = Protocol::from(CredentialIssuanceTypeV1_0::parent()); - let kind = CredentialIssuanceTypeV1_0::from(self); - format_args!("{protocol}/{}", kind.as_ref()).serialize(serializer) - } -} - -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] -#[serde(rename_all = "kebab-case")] -pub struct CredentialAttr { - pub name: String, - pub value: String, - #[builder(default, setter(strip_option))] - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(rename = "mime-type")] - pub mime_type: Option, -} - -transit_to_aries_msg!(OfferCredentialContent: OfferCredentialDecorators, CredentialIssuance); -transit_to_aries_msg!( - ProposeCredentialContent: ProposeCredentialDecorators, - CredentialIssuance -); -transit_to_aries_msg!( - RequestCredentialContent: RequestCredentialDecorators, - CredentialIssuance -); -transit_to_aries_msg!(IssueCredentialContent: IssueCredentialDecorators, CredentialIssuance); -transit_to_aries_msg!(AckCredentialContent: AckDecorators, CredentialIssuance); -transit_to_aries_msg!( - CredIssuanceProblemReportContent: ProblemReportDecorators, - CredentialIssuance -); - -into_msg_with_type!(OfferCredential, CredentialIssuanceTypeV1_0, OfferCredential); -into_msg_with_type!( - ProposeCredential, - CredentialIssuanceTypeV1_0, - ProposeCredential -); -into_msg_with_type!( - RequestCredential, - CredentialIssuanceTypeV1_0, - RequestCredential -); -into_msg_with_type!(IssueCredential, CredentialIssuanceTypeV1_0, IssueCredential); -into_msg_with_type!(AckCredential, CredentialIssuanceTypeV1_0, Ack); -into_msg_with_type!( - CredIssuanceProblemReport, - CredentialIssuanceTypeV1_0, - ProblemReport -); diff --git a/messages/src/msg_fields/protocols/cred_issuance/ack.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/ack.rs similarity index 81% rename from messages/src/msg_fields/protocols/cred_issuance/ack.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/ack.rs index b824f8eaf6..cfd04c1698 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/ack.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/ack.rs @@ -6,22 +6,22 @@ use crate::{ msg_parts::MsgParts, }; -pub type AckCredential = MsgParts; +pub type AckCredentialV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] #[serde(transparent)] -pub struct AckCredentialContent { +pub struct AckCredentialV1Content { pub inner: AckContent, } -impl From for AckCredentialContent { +impl From for AckCredentialV1Content { fn from(value: AckContent) -> Self { Self { inner: value } } } -impl From for Ack { - fn from(value: AckCredential) -> Self { +impl From for Ack { + fn from(value: AckCredentialV1) -> Self { Self::builder() .id(value.id) .content(value.content.inner) @@ -46,7 +46,7 @@ mod tests { #[test] fn test_minimal_ack_cred() { - let content: AckCredentialContent = AckContent::builder().status(AckStatus::Ok).build(); + let content: AckCredentialV1Content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(make_extended_thread()) @@ -67,7 +67,7 @@ mod tests { #[test] fn test_extended_ack_cred() { - let content: AckCredentialContent = AckContent::builder().status(AckStatus::Ok).build(); + let content: AckCredentialV1Content = AckContent::builder().status(AckStatus::Ok).build(); let decorators = AckDecorators::builder() .thread(make_extended_thread()) diff --git a/messages/src/msg_fields/protocols/cred_issuance/issue_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/issue_credential.rs similarity index 87% rename from messages/src/msg_fields/protocols/cred_issuance/issue_credential.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/issue_credential.rs index 3179f1bcf5..161af7d698 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/issue_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/issue_credential.rs @@ -6,10 +6,10 @@ use crate::{ msg_parts::MsgParts, }; -pub type IssueCredential = MsgParts; +pub type IssueCredentialV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct IssueCredentialContent { +pub struct IssueCredentialV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, @@ -18,7 +18,7 @@ pub struct IssueCredentialContent { } #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct IssueCredentialDecorators { +pub struct IssueCredentialV1Decorators { #[serde(rename = "~thread")] pub thread: Thread, #[builder(default, setter(strip_option))] @@ -50,11 +50,11 @@ mod tests { #[test] fn test_minimal_issue_cred() { - let content = IssueCredentialContent::builder() + let content = IssueCredentialV1Content::builder() .credentials_attach(vec![make_extended_attachment()]) .build(); - let decorators = IssueCredentialDecorators::builder() + let decorators = IssueCredentialV1Decorators::builder() .thread(make_extended_thread()) .build(); @@ -73,12 +73,12 @@ mod tests { #[test] fn test_extended_issue_cred() { - let content = IssueCredentialContent::builder() + let content = IssueCredentialV1Content::builder() .credentials_attach(vec![make_extended_attachment()]) .comment("test_comment".to_owned()) .build(); - let decorators = IssueCredentialDecorators::builder() + let decorators = IssueCredentialV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .please_ack(make_minimal_please_ack()) diff --git a/messages/src/msg_fields/protocols/cred_issuance/v1/mod.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/mod.rs new file mode 100644 index 0000000000..a85709a63d --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/mod.rs @@ -0,0 +1,225 @@ +//! Module containing the `issue credential` protocol messages, as defined in the [RFC](). + +pub mod ack; +pub mod issue_credential; +pub mod offer_credential; +pub mod problem_report; +pub mod propose_credential; +pub mod request_credential; + +use std::str::FromStr; + +use derive_more::From; +use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; +use shared_vcx::misc::utils::CowStr; + +use self::{ + ack::{AckCredentialV1, AckCredentialV1Content}, + issue_credential::{IssueCredentialV1, IssueCredentialV1Content, IssueCredentialV1Decorators}, + offer_credential::{OfferCredentialV1, OfferCredentialV1Content, OfferCredentialV1Decorators}, + problem_report::{CredIssuanceV1ProblemReport, CredIssuanceV1ProblemReportContent}, + propose_credential::{ + ProposeCredentialV1, ProposeCredentialV1Content, ProposeCredentialV1Decorators, + }, + request_credential::{ + RequestCredentialV1, RequestCredentialV1Content, RequestCredentialV1Decorators, + }, +}; +use super::{common::CredentialAttr, CredentialIssuance}; +use crate::{ + misc::utils::{self, into_msg_with_type, transit_to_aries_msg}, + msg_fields::{ + protocols::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}, + traits::DelayedSerde, + }, + msg_types::{ + protocols::cred_issuance::{ + CredentialIssuanceType as CredentialIssuanceKind, CredentialIssuanceTypeV1, + CredentialIssuanceTypeV1_0, + }, + traits::MessageKind, + MessageType, MsgWithType, Protocol, + }, +}; + +#[derive(Clone, Debug, From, PartialEq)] +pub enum CredentialIssuanceV1 { + OfferCredential(OfferCredentialV1), + ProposeCredential(ProposeCredentialV1), + RequestCredential(RequestCredentialV1), + IssueCredential(IssueCredentialV1), + Ack(AckCredentialV1), + ProblemReport(CredIssuanceV1ProblemReport), +} + +impl DelayedSerde for CredentialIssuanceV1 { + type MsgType<'a> = (CredentialIssuanceKind, &'a str); + + fn delayed_deserialize<'de, D>( + msg_type: Self::MsgType<'de>, + deserializer: D, + ) -> Result + where + D: Deserializer<'de>, + { + let (protocol, kind_str) = msg_type; + let kind = match protocol { + CredentialIssuanceKind::V1(CredentialIssuanceTypeV1::V1_0(kind)) => { + kind.kind_from_str(kind_str) + } + CredentialIssuanceKind::V2(_) => { + return Err(D::Error::custom( + "Cannot deserialize issue-credential-v2 message type into issue-credential-v1", + )) + } + }; + + match kind.map_err(D::Error::custom)? { + CredentialIssuanceTypeV1_0::OfferCredential => { + OfferCredentialV1::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::ProposeCredential => { + ProposeCredentialV1::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::RequestCredential => { + RequestCredentialV1::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::IssueCredential => { + IssueCredentialV1::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::Ack => { + AckCredentialV1::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::ProblemReport => { + CredIssuanceV1ProblemReport::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV1_0::CredentialPreview => { + Err(utils::not_standalone_msg::(kind_str)) + } + } + } + + fn delayed_serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self { + Self::OfferCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::ProposeCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::RequestCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::IssueCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::Ack(v) => MsgWithType::from(v).serialize(serializer), + Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +pub struct CredentialPreviewV1 { + #[serde(rename = "@type")] + msg_type: CredentialPreviewV1MsgType, + pub attributes: Vec, +} + +impl CredentialPreviewV1 { + pub fn new(attributes: Vec) -> Self { + Self { + msg_type: CredentialPreviewV1MsgType, + attributes, + } + } +} + +/// Non-standalone message type. +/// This is only encountered as part of an existent message. +/// It is not a message on it's own. +#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(try_from = "CowStr")] +struct CredentialPreviewV1MsgType; + +impl<'a> From<&'a CredentialPreviewV1MsgType> for CredentialIssuanceTypeV1_0 { + fn from(_value: &'a CredentialPreviewV1MsgType) -> Self { + CredentialIssuanceTypeV1_0::CredentialPreview + } +} + +impl<'a> TryFrom> for CredentialPreviewV1MsgType { + type Error = String; + + fn try_from(value: CowStr) -> Result { + let value = MessageType::try_from(value.0.as_ref())?; + + if let Protocol::CredentialIssuanceType(CredentialIssuanceKind::V1( + CredentialIssuanceTypeV1::V1_0(_), + )) = value.protocol + { + if let Ok(CredentialIssuanceTypeV1_0::CredentialPreview) = + CredentialIssuanceTypeV1_0::from_str(value.kind) + { + return Ok(CredentialPreviewV1MsgType); + } + } + + Err(format!("message kind is not {}", value.kind)) + } +} + +impl Serialize for CredentialPreviewV1MsgType { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let protocol = Protocol::from(CredentialIssuanceTypeV1_0::parent()); + let kind = CredentialIssuanceTypeV1_0::from(self); + format_args!("{protocol}/{}", kind.as_ref()).serialize(serializer) + } +} + +transit_to_aries_msg!( + OfferCredentialV1Content: OfferCredentialV1Decorators, + CredentialIssuanceV1, CredentialIssuance +); +transit_to_aries_msg!( + ProposeCredentialV1Content: ProposeCredentialV1Decorators, + CredentialIssuanceV1, CredentialIssuance +); +transit_to_aries_msg!( + RequestCredentialV1Content: RequestCredentialV1Decorators, + CredentialIssuanceV1, CredentialIssuance +); +transit_to_aries_msg!( + IssueCredentialV1Content: IssueCredentialV1Decorators, + CredentialIssuanceV1, CredentialIssuance +); +transit_to_aries_msg!(AckCredentialV1Content: AckDecorators, CredentialIssuanceV1, CredentialIssuance); +transit_to_aries_msg!( + CredIssuanceV1ProblemReportContent: ProblemReportDecorators, + CredentialIssuanceV1, CredentialIssuance +); + +into_msg_with_type!( + OfferCredentialV1, + CredentialIssuanceTypeV1_0, + OfferCredential +); +into_msg_with_type!( + ProposeCredentialV1, + CredentialIssuanceTypeV1_0, + ProposeCredential +); +into_msg_with_type!( + RequestCredentialV1, + CredentialIssuanceTypeV1_0, + RequestCredential +); +into_msg_with_type!( + IssueCredentialV1, + CredentialIssuanceTypeV1_0, + IssueCredential +); +into_msg_with_type!(AckCredentialV1, CredentialIssuanceTypeV1_0, Ack); +into_msg_with_type!( + CredIssuanceV1ProblemReport, + CredentialIssuanceTypeV1_0, + ProblemReport +); diff --git a/messages/src/msg_fields/protocols/cred_issuance/offer_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/offer_credential.rs similarity index 81% rename from messages/src/msg_fields/protocols/cred_issuance/offer_credential.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/offer_credential.rs index b596a0fd25..bdc790efee 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/offer_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/offer_credential.rs @@ -1,26 +1,26 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::CredentialPreview; +use super::CredentialPreviewV1; use crate::{ decorators::{attachment::Attachment, thread::Thread, timing::Timing}, msg_parts::MsgParts, }; -pub type OfferCredential = MsgParts; +pub type OfferCredentialV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct OfferCredentialContent { +pub struct OfferCredentialV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, - pub credential_preview: CredentialPreview, + pub credential_preview: CredentialPreviewV1, #[serde(rename = "offers~attach")] pub offers_attach: Vec, } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] -pub struct OfferCredentialDecorators { +pub struct OfferCredentialV1Decorators { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "~thread")] @@ -44,7 +44,7 @@ mod tests { timing::tests::make_extended_timing, }, misc::test_utils, - msg_fields::protocols::cred_issuance::CredentialAttr, + msg_fields::protocols::cred_issuance::v1::CredentialAttr, msg_types::cred_issuance::CredentialIssuanceTypeV1_0, }; @@ -55,13 +55,13 @@ mod tests { .value("test_attribute_value".to_owned()) .build(); - let preview = CredentialPreview::new(vec![attribute]); - let content = OfferCredentialContent::builder() + let preview = CredentialPreviewV1::new(vec![attribute]); + let content = OfferCredentialV1Content::builder() .credential_preview(preview) .offers_attach(vec![make_extended_attachment()]) .build(); - let decorators = OfferCredentialDecorators::default(); + let decorators = OfferCredentialV1Decorators::default(); let expected = json!({ "offers~attach": content.offers_attach, @@ -83,14 +83,14 @@ mod tests { .value("test_attribute_value".to_owned()) .build(); - let preview = CredentialPreview::new(vec![attribute]); - let content = OfferCredentialContent::builder() + let preview = CredentialPreviewV1::new(vec![attribute]); + let content = OfferCredentialV1Content::builder() .credential_preview(preview) .offers_attach(vec![make_extended_attachment()]) .comment("test_comment".to_owned()) .build(); - let decorators = OfferCredentialDecorators::builder() + let decorators = OfferCredentialV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .build(); diff --git a/messages/src/msg_fields/protocols/cred_issuance/problem_report.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/problem_report.rs similarity index 88% rename from messages/src/msg_fields/protocols/cred_issuance/problem_report.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/problem_report.rs index 69324f4c7a..f79f09d161 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/problem_report.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/problem_report.rs @@ -8,23 +8,23 @@ use crate::{ msg_parts::MsgParts, }; -pub type CredIssuanceProblemReport = - MsgParts; +pub type CredIssuanceV1ProblemReport = + MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] #[serde(transparent)] -pub struct CredIssuanceProblemReportContent { +pub struct CredIssuanceV1ProblemReportContent { pub inner: ProblemReportContent, } -impl From for CredIssuanceProblemReportContent { +impl From for CredIssuanceV1ProblemReportContent { fn from(value: ProblemReportContent) -> Self { Self { inner: value } } } -impl From for ProblemReport { - fn from(value: CredIssuanceProblemReport) -> Self { +impl From for ProblemReport { + fn from(value: CredIssuanceV1ProblemReport) -> Self { Self::builder() .id(value.id) .content(value.content.inner) @@ -60,7 +60,7 @@ mod tests { .code("test_problem_report_code".to_owned()) .build(); - let content: CredIssuanceProblemReportContent = ProblemReportContent::builder() + let content: CredIssuanceV1ProblemReportContent = ProblemReportContent::builder() .description(description) .build(); let decorators = ProblemReportDecorators::default(); @@ -121,7 +121,7 @@ mod tests { "fix-hint~l10n": decorators.fix_hint_locale }); - let content = CredIssuanceProblemReportContent::builder() + let content = CredIssuanceV1ProblemReportContent::builder() .inner(content) .build(); diff --git a/messages/src/msg_fields/protocols/cred_issuance/propose_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/propose_credential.rs similarity index 80% rename from messages/src/msg_fields/protocols/cred_issuance/propose_credential.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/propose_credential.rs index 40a4d1fe68..8a16ba20a5 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/propose_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/propose_credential.rs @@ -1,26 +1,26 @@ use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; -use super::CredentialPreview; +use super::CredentialPreviewV1; use crate::{ decorators::{thread::Thread, timing::Timing}, msg_parts::MsgParts, }; -pub type ProposeCredential = MsgParts; +pub type ProposeCredentialV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct ProposeCredentialContent { +pub struct ProposeCredentialV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, - pub credential_proposal: CredentialPreview, + pub credential_proposal: CredentialPreviewV1, pub schema_id: String, pub cred_def_id: String, } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] -pub struct ProposeCredentialDecorators { +pub struct ProposeCredentialV1Decorators { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "~thread")] @@ -41,7 +41,7 @@ mod tests { use crate::{ decorators::{thread::tests::make_extended_thread, timing::tests::make_extended_timing}, misc::test_utils, - msg_fields::protocols::cred_issuance::CredentialAttr, + msg_fields::protocols::cred_issuance::v1::CredentialAttr, msg_types::cred_issuance::CredentialIssuanceTypeV1_0, }; @@ -51,14 +51,14 @@ mod tests { .name("test_attribute_name".to_owned()) .value("test_attribute_value".to_owned()) .build(); - let preview = CredentialPreview::new(vec![attribute]); - let content = ProposeCredentialContent::builder() + let preview = CredentialPreviewV1::new(vec![attribute]); + let content = ProposeCredentialV1Content::builder() .credential_proposal(preview) .schema_id("test_schema_id".to_owned()) .cred_def_id("test_cred_def_id".to_owned()) .build(); - let decorators = ProposeCredentialDecorators::default(); + let decorators = ProposeCredentialV1Decorators::default(); let expected = json!({ "credential_proposal": content.credential_proposal, @@ -80,15 +80,15 @@ mod tests { .name("test_attribute_name".to_owned()) .value("test_attribute_value".to_owned()) .build(); - let preview = CredentialPreview::new(vec![attribute]); - let content = ProposeCredentialContent::builder() + let preview = CredentialPreviewV1::new(vec![attribute]); + let content = ProposeCredentialV1Content::builder() .credential_proposal(preview) .schema_id("test_schema_id".to_owned()) .cred_def_id("test_cred_def_id".to_owned()) .comment("test_comment".to_owned()) .build(); - let decorators = ProposeCredentialDecorators::builder() + let decorators = ProposeCredentialV1Decorators::builder() .thread(make_extended_thread()) .timing(make_extended_timing()) .build(); diff --git a/messages/src/msg_fields/protocols/cred_issuance/request_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v1/request_credential.rs similarity index 84% rename from messages/src/msg_fields/protocols/cred_issuance/request_credential.rs rename to messages/src/msg_fields/protocols/cred_issuance/v1/request_credential.rs index ea4b63907a..d285ebd6f2 100644 --- a/messages/src/msg_fields/protocols/cred_issuance/request_credential.rs +++ b/messages/src/msg_fields/protocols/cred_issuance/v1/request_credential.rs @@ -6,10 +6,10 @@ use crate::{ msg_parts::MsgParts, }; -pub type RequestCredential = MsgParts; +pub type RequestCredentialV1 = MsgParts; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] -pub struct RequestCredentialContent { +pub struct RequestCredentialV1Content { #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] pub comment: Option, @@ -18,7 +18,7 @@ pub struct RequestCredentialContent { } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] -pub struct RequestCredentialDecorators { +pub struct RequestCredentialV1Decorators { #[builder(default, setter(strip_option))] #[serde(rename = "~thread")] #[serde(skip_serializing_if = "Option::is_none")] @@ -46,11 +46,11 @@ mod tests { #[test] fn test_minimal_request_cred() { - let content = RequestCredentialContent::builder() + let content = RequestCredentialV1Content::builder() .requests_attach(vec![make_extended_attachment()]) .build(); - let decorators = RequestCredentialDecorators::default(); + let decorators = RequestCredentialV1Decorators::default(); let expected = json!({ "requests~attach": content.requests_attach, @@ -66,12 +66,12 @@ mod tests { #[test] fn test_extended_request_cred() { - let content = RequestCredentialContent::builder() + let content = RequestCredentialV1Content::builder() .requests_attach(vec![make_extended_attachment()]) .comment("test_comment".to_owned()) .build(); - let decorators = RequestCredentialDecorators::builder() + let decorators = RequestCredentialV1Decorators::builder() .thread(make_extended_thread()) .build(); diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/ack.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/ack.rs new file mode 100644 index 0000000000..39a0ea1d1e --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/ack.rs @@ -0,0 +1,90 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + msg_fields::protocols::notification::ack::{Ack, AckContent, AckDecorators}, + msg_parts::MsgParts, +}; + +pub type AckCredentialV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +#[serde(transparent)] +pub struct AckCredentialV2Content { + pub inner: AckContent, +} + +impl From for AckCredentialV2Content { + fn from(value: AckContent) -> Self { + Self { inner: value } + } +} + +impl From for Ack { + fn from(value: AckCredentialV2) -> Self { + Self::builder() + .id(value.id) + .content(value.content.inner) + .decorators(value.decorators) + .build() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{ + decorators::{thread::tests::make_extended_thread, timing::tests::make_extended_timing}, + misc::test_utils, + msg_fields::protocols::notification::ack::AckStatus, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_ack_cred() { + let content: AckCredentialV2Content = AckContent::builder().status(AckStatus::Ok).build(); + + let decorators = AckDecorators::builder() + .thread(make_extended_thread()) + .build(); + + let expected = json!({ + "status": content.inner.status, + "~thread": decorators.thread + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::Ack, + expected, + ); + } + + #[test] + fn test_extended_ack_cred() { + let content: AckCredentialV2Content = AckContent::builder().status(AckStatus::Ok).build(); + + let decorators = AckDecorators::builder() + .thread(make_extended_thread()) + .timing(make_extended_timing()) + .build(); + + let expected = json!({ + "status": content.inner.status, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::Ack, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs new file mode 100644 index 0000000000..19adc8b769 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/issue_credential.rs @@ -0,0 +1,137 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use super::AttachmentFormatSpecifier; +use crate::{ + decorators::{attachment::Attachment, please_ack::PleaseAck, thread::Thread, timing::Timing}, + msg_parts::MsgParts, +}; + +pub type IssueCredentialV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct IssueCredentialV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub replacement_id: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + pub formats: Vec>, + #[serde(rename = "credentials~attach")] + pub credentials_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct IssueCredentialV2Decorators { + #[serde(rename = "~thread")] + pub thread: Thread, + #[builder(default)] + #[serde(rename = "~please_ack")] + #[serde(skip_serializing_if = "Option::is_none")] + pub please_ack: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum IssueCredentialAttachmentFormatType { + #[serde(rename = "aries/ld-proof-vc@v1.0")] + AriesLdProofVc1_0, + #[serde(rename = "hlindy/cred@v2.0")] + HyperledgerIndyCredential2_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, + please_ack::tests::make_minimal_please_ack, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_issue_cred() { + let content = IssueCredentialV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + IssueCredentialAttachmentFormatType::HyperledgerIndyCredential2_0, + ), + }]) + .credentials_attach(vec![make_extended_attachment()]) + .build(); + + let decorators = IssueCredentialV2Decorators::builder() + .thread(make_extended_thread()) + .build(); + + let expected = json!({ + "formats": content.formats, + "credentials~attach": content.credentials_attach, + "~thread": decorators.thread + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::IssueCredential, + expected, + ); + } + + #[test] + fn test_extended_issue_cred() { + let content = IssueCredentialV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: shared_vcx::maybe_known::MaybeKnown::Known( + IssueCredentialAttachmentFormatType::HyperledgerIndyCredential2_0, + ), + }]) + .credentials_attach(vec![make_extended_attachment()]) + .goal_code(Some("goal.goal".to_owned())) + .replacement_id(Some("replacement-123".to_owned())) + .comment(Some("test_comment".to_owned())) + .build(); + + let decorators = IssueCredentialV2Decorators::builder() + .thread(make_extended_thread()) + .timing(Some(make_extended_timing())) + .please_ack(Some(make_minimal_please_ack())) + .build(); + + let expected = json!({ + "formats": content.formats, + "credentials~attach": content.credentials_attach, + "goal_code": content.goal_code, + "replacement_id": content.replacement_id, + "comment": content.comment, + "~thread": decorators.thread, + "~timing": decorators.timing, + "~please_ack": decorators.please_ack + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::IssueCredential, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs new file mode 100644 index 0000000000..8f9d100c62 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/mod.rs @@ -0,0 +1,232 @@ +//! Module containing the `issue credential` protocol messages, as defined in the [RFC](). + +pub mod ack; +pub mod issue_credential; +pub mod offer_credential; +pub mod problem_report; +pub mod propose_credential; +pub mod request_credential; + +use std::str::FromStr; + +use derive_more::From; +use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; +use shared_vcx::{maybe_known::MaybeKnown, misc::utils::CowStr}; +use typed_builder::TypedBuilder; + +use self::{ + ack::{AckCredentialV2, AckCredentialV2Content}, + issue_credential::{IssueCredentialV2, IssueCredentialV2Content, IssueCredentialV2Decorators}, + offer_credential::{OfferCredentialV2, OfferCredentialV2Content, OfferCredentialV2Decorators}, + problem_report::{CredIssuanceProblemReportV2, CredIssuanceV2ProblemReportContent}, + propose_credential::{ + ProposeCredentialV2, ProposeCredentialV2Content, ProposeCredentialV2Decorators, + }, + request_credential::{ + RequestCredentialV2, RequestCredentialV2Content, RequestCredentialV2Decorators, + }, +}; +use super::{ + super::{notification::ack::AckDecorators, report_problem::ProblemReportDecorators}, + common::CredentialAttr, + CredentialIssuance, +}; +use crate::{ + misc::utils::{self, into_msg_with_type, transit_to_aries_msg}, + msg_fields::traits::DelayedSerde, + msg_types::{ + cred_issuance::{CredentialIssuanceTypeV2, CredentialIssuanceTypeV2_0}, + protocols::cred_issuance::CredentialIssuanceType as CredentialIssuanceKind, + traits::MessageKind, + MessageType, MsgWithType, Protocol, + }, +}; + +#[derive(Clone, Debug, From, PartialEq)] +pub enum CredentialIssuanceV2 { + OfferCredential(OfferCredentialV2), + ProposeCredential(ProposeCredentialV2), + RequestCredential(RequestCredentialV2), + IssueCredential(IssueCredentialV2), + Ack(AckCredentialV2), + ProblemReport(CredIssuanceProblemReportV2), +} + +impl DelayedSerde for CredentialIssuanceV2 { + type MsgType<'a> = (CredentialIssuanceKind, &'a str); + + fn delayed_deserialize<'de, D>( + msg_type: Self::MsgType<'de>, + deserializer: D, + ) -> Result + where + D: Deserializer<'de>, + { + let (protocol, kind_str) = msg_type; + let kind = match protocol { + CredentialIssuanceKind::V2(CredentialIssuanceTypeV2::V2_0(kind)) => { + kind.kind_from_str(kind_str) + } + CredentialIssuanceKind::V1(_) => { + return Err(D::Error::custom( + "Cannot deserialize issue-credential-v1 message type into issue-credential-v2", + )) + } + }; + + match kind.map_err(D::Error::custom)? { + CredentialIssuanceTypeV2_0::OfferCredential => { + OfferCredentialV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::ProposeCredential => { + ProposeCredentialV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::RequestCredential => { + RequestCredentialV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::IssueCredential => { + IssueCredentialV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::Ack => { + AckCredentialV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::ProblemReport => { + CredIssuanceProblemReportV2::deserialize(deserializer).map(From::from) + } + CredentialIssuanceTypeV2_0::CredentialPreview => { + Err(utils::not_standalone_msg::(kind_str)) + } + } + } + + fn delayed_serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match self { + Self::OfferCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::ProposeCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::RequestCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::IssueCredential(v) => MsgWithType::from(v).serialize(serializer), + Self::Ack(v) => MsgWithType::from(v).serialize(serializer), + Self::ProblemReport(v) => MsgWithType::from(v).serialize(serializer), + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +pub struct CredentialPreviewV2 { + #[serde(rename = "@type")] + msg_type: CredentialPreviewV2MsgType, + pub attributes: Vec, +} + +impl CredentialPreviewV2 { + pub fn new(attributes: Vec) -> Self { + Self { + msg_type: CredentialPreviewV2MsgType, + attributes, + } + } +} + +/// Non-standalone message type. +/// This is only encountered as part of an existent message. +/// It is not a message on it's own. +#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(try_from = "CowStr")] +struct CredentialPreviewV2MsgType; + +impl<'a> From<&'a CredentialPreviewV2MsgType> for CredentialIssuanceTypeV2_0 { + fn from(_value: &'a CredentialPreviewV2MsgType) -> Self { + CredentialIssuanceTypeV2_0::CredentialPreview + } +} + +impl<'a> TryFrom> for CredentialPreviewV2MsgType { + type Error = String; + + fn try_from(value: CowStr) -> Result { + let value = MessageType::try_from(value.0.as_ref())?; + + if let Protocol::CredentialIssuanceType(CredentialIssuanceKind::V2( + CredentialIssuanceTypeV2::V2_0(_), + )) = value.protocol + { + if let Ok(CredentialIssuanceTypeV2_0::CredentialPreview) = + CredentialIssuanceTypeV2_0::from_str(value.kind) + { + return Ok(CredentialPreviewV2MsgType); + } + } + + Err(format!("message kind is not {}", value.kind)) + } +} + +impl Serialize for CredentialPreviewV2MsgType { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let protocol = Protocol::from(CredentialIssuanceTypeV2_0::parent()); + let kind = CredentialIssuanceTypeV2_0::from(self); + format_args!("{protocol}/{}", kind.as_ref()).serialize(serializer) + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, TypedBuilder)] +#[serde(rename_all = "snake_case")] +pub struct AttachmentFormatSpecifier { + attach_id: String, + format: MaybeKnown, +} + +transit_to_aries_msg!( + OfferCredentialV2Content: OfferCredentialV2Decorators, + CredentialIssuanceV2, CredentialIssuance +); +transit_to_aries_msg!( + ProposeCredentialV2Content: ProposeCredentialV2Decorators, + CredentialIssuanceV2, CredentialIssuance +); +transit_to_aries_msg!( + RequestCredentialV2Content: RequestCredentialV2Decorators, + CredentialIssuanceV2, CredentialIssuance +); +transit_to_aries_msg!( + IssueCredentialV2Content: IssueCredentialV2Decorators, + CredentialIssuanceV2, CredentialIssuance +); +transit_to_aries_msg!(AckCredentialV2Content: AckDecorators, CredentialIssuanceV2, CredentialIssuance); +transit_to_aries_msg!( + CredIssuanceV2ProblemReportContent: ProblemReportDecorators, + CredentialIssuanceV2, CredentialIssuance +); + +into_msg_with_type!( + OfferCredentialV2, + CredentialIssuanceTypeV2_0, + OfferCredential +); +into_msg_with_type!( + ProposeCredentialV2, + CredentialIssuanceTypeV2_0, + ProposeCredential +); +into_msg_with_type!( + RequestCredentialV2, + CredentialIssuanceTypeV2_0, + RequestCredential +); +into_msg_with_type!( + IssueCredentialV2, + CredentialIssuanceTypeV2_0, + IssueCredential +); +into_msg_with_type!(AckCredentialV2, CredentialIssuanceTypeV2_0, Ack); +into_msg_with_type!( + CredIssuanceProblemReportV2, + CredentialIssuanceTypeV2_0, + ProblemReport +); diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs new file mode 100644 index 0000000000..495ff6f1e4 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/offer_credential.rs @@ -0,0 +1,149 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use super::{AttachmentFormatSpecifier, CredentialPreviewV2}; +use crate::{ + decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_parts::MsgParts, +}; + +pub type OfferCredentialV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct OfferCredentialV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub replacement_id: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + pub credential_preview: CredentialPreviewV2, + pub formats: Vec>, + #[serde(rename = "offers~attach")] + pub offers_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct OfferCredentialV2Decorators { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "~thread")] + pub thread: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum OfferCredentialAttachmentFormatType { + #[serde(rename = "dif/credential-manifest@v1.0")] + DifCredentialManifest1_0, + #[serde(rename = "hlindy/cred-abstract@v2.0")] + HyperledgerIndyCredentialAbstract2_0, + #[serde(rename = "aries/ld-proof-vc-detail@v1.0")] + AriesLdProofVcDetail1_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_fields::protocols::cred_issuance::common::CredentialAttr, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_offer_cred() { + let attribute = CredentialAttr::builder() + .name("test_attribute_name".to_owned()) + .value("test_attribute_value".to_owned()) + .build(); + + let preview = CredentialPreviewV2::new(vec![attribute]); + let content = OfferCredentialV2Content::builder() + .credential_preview(preview) + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + OfferCredentialAttachmentFormatType::HyperledgerIndyCredentialAbstract2_0, + ), + }]) + .offers_attach(vec![make_extended_attachment()]) + .build(); + + let decorators = OfferCredentialV2Decorators::default(); + + let expected = json!({ + "formats": content.formats, + "offers~attach": content.offers_attach, + "credential_preview": content.credential_preview, + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::OfferCredential, + expected, + ); + } + + #[test] + fn test_extended_offer_cred() { + let attribute = CredentialAttr::builder() + .name("test_attribute_name".to_owned()) + .value("test_attribute_value".to_owned()) + .build(); + + let preview = CredentialPreviewV2::new(vec![attribute]); + let content = OfferCredentialV2Content::builder() + .credential_preview(preview) + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + OfferCredentialAttachmentFormatType::HyperledgerIndyCredentialAbstract2_0, + ), + }]) + .offers_attach(vec![make_extended_attachment()]) + .comment(Some("test_comment".to_owned())) + .replacement_id(Some("replacement_id".to_owned())) + .goal_code(Some("goal.goal".to_owned())) + .build(); + + let decorators = OfferCredentialV2Decorators::builder() + .thread(Some(make_extended_thread())) + .timing(Some(make_extended_timing())) + .build(); + + let expected = json!({ + "formats": content.formats, + "offers~attach": content.offers_attach, + "credential_preview": content.credential_preview, + "comment": content.comment, + "goal_code": content.goal_code, + "replacement_id": content.replacement_id, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::OfferCredential, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/problem_report.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/problem_report.rs new file mode 100644 index 0000000000..542142b0bd --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/problem_report.rs @@ -0,0 +1,135 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use crate::{ + msg_fields::protocols::report_problem::{ + ProblemReport, ProblemReportContent, ProblemReportDecorators, + }, + msg_parts::MsgParts, +}; + +pub type CredIssuanceProblemReportV2 = + MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +#[serde(transparent)] +pub struct CredIssuanceV2ProblemReportContent { + pub inner: ProblemReportContent, +} + +impl From for CredIssuanceV2ProblemReportContent { + fn from(value: ProblemReportContent) -> Self { + Self { inner: value } + } +} + +impl From for ProblemReport { + fn from(value: CredIssuanceProblemReportV2) -> Self { + Self::builder() + .id(value.id) + .content(value.content.inner) + .decorators(value.decorators) + .build() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use std::collections::HashMap; + + use serde_json::json; + + use super::*; + use crate::{ + decorators::{ + localization::tests::make_extended_field_localization, + thread::tests::make_extended_thread, timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_fields::protocols::report_problem::{ + Description, Impact, Where, WhereParty, WhoRetries, + }, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_problem_report() { + let description = Description::builder() + .code("test_problem_report_code".to_owned()) + .build(); + + let content: CredIssuanceV2ProblemReportContent = ProblemReportContent::builder() + .description(description) + .build(); + let decorators = ProblemReportDecorators::default(); + + let expected = json!({ + "description": content.inner.description + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::ProblemReport, + expected, + ); + } + + #[test] + fn test_extended_problem_report() { + let description = Description::builder() + .code("test_problem_report_code".to_owned()) + .build(); + + let content: ProblemReportContent = ProblemReportContent::builder() + .description(description) + .who_retries(WhoRetries::Me) + .fix_hint("test_fix_hint".to_owned()) + .impact(Impact::Connection) + .location(Where::new(WhereParty::Me, "test_location".to_owned())) + .noticed_time("test_noticed_time".to_owned()) + .tracking_uri("https://dummy.dummy/dummy".parse().unwrap()) + .escalation_uri("https://dummy.dummy/dummy".parse().unwrap()) + .problem_items(vec![HashMap::from([( + "test_prob_item_key".to_owned(), + "test_prob_item_value".to_owned(), + )])]) + .build(); + + let decorators = ProblemReportDecorators::builder() + .thread(make_extended_thread()) + .timing(make_extended_timing()) + .description_locale(make_extended_field_localization()) + .fix_hint_locale(make_extended_field_localization()) + .build(); + + let expected = json!({ + "description": content.description, + "who_retries": content.who_retries, + "fix-hint": content.fix_hint, + "impact": content.impact, + "where": content.location, + "noticed_time": content.noticed_time, + "tracking-uri": content.tracking_uri, + "escalation-uri": content.escalation_uri, + "problem_items": content.problem_items, + "~thread": decorators.thread, + "~timing": decorators.timing, + "description~l10n": decorators.description_locale, + "fix-hint~l10n": decorators.fix_hint_locale + }); + + let content = CredIssuanceV2ProblemReportContent::builder() + .inner(content) + .build(); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::ProblemReport, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs new file mode 100644 index 0000000000..1350cea084 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/propose_credential.rs @@ -0,0 +1,137 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use super::{AttachmentFormatSpecifier, CredentialPreviewV2}; +use crate::{ + decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_parts::MsgParts, +}; + +pub type ProposeCredentialV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct ProposeCredentialV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, // TODO - spec does not specify what goal codes to use.. + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub credential_preview: Option, + pub formats: Vec>, + #[serde(rename = "filters~attach")] + pub filters_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct ProposeCredentialV2Decorators { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "~thread")] + pub thread: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum ProposeCredentialAttachmentFormatType { + #[serde(rename = "dif/credential-manifest@v1.0")] + DifCredentialManifest1_0, + #[serde(rename = "aries/ld-proof-vc-detail@v1.0")] + AriesLdProofVcDetail1_0, + #[serde(rename = "hlindy/cred-filter@v2.0")] + HyperledgerIndyCredentialFilter2_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, thread::tests::make_extended_thread, + timing::tests::make_extended_timing, + }, + misc::test_utils, + msg_fields::protocols::cred_issuance::common::CredentialAttr, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_propose_cred() { + let content = ProposeCredentialV2Content::builder() + .formats(vec![AttachmentFormatSpecifier { + attach_id: String::from("1"), + format: MaybeKnown::Known( + ProposeCredentialAttachmentFormatType::HyperledgerIndyCredentialFilter2_0, + ), + }]) + .filters_attach(vec![make_extended_attachment()]) + .build(); + + let decorators = ProposeCredentialV2Decorators::default(); + + let expected = json!({ + "formats": content.formats, + "filters~attach": content.filters_attach, + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::ProposeCredential, + expected, + ); + } + + #[test] + fn test_extended_propose_cred() { + let attribute = CredentialAttr::builder() + .name("test_attribute_name".to_owned()) + .value("test_attribute_value".to_owned()) + .build(); + let preview = CredentialPreviewV2::new(vec![attribute]); + let content = ProposeCredentialV2Content::builder() + .credential_preview(Some(preview)) + .formats(vec![AttachmentFormatSpecifier { + attach_id: String::from("1"), + format: MaybeKnown::Known( + ProposeCredentialAttachmentFormatType::HyperledgerIndyCredentialFilter2_0, + ), + }]) + .filters_attach(vec![make_extended_attachment()]) + .comment(Some("test_comment".to_owned())) + .goal_code(Some("goal.goal".to_owned())) + .build(); + + let decorators = ProposeCredentialV2Decorators::builder() + .thread(Some(make_extended_thread())) + .timing(Some(make_extended_timing())) + .build(); + + let expected = json!({ + "credential_preview": content.credential_preview, + "formats": content.formats, + "filters~attach": content.filters_attach, + "comment": content.comment, + "goal_code": content.goal_code, + "~thread": decorators.thread, + "~timing": decorators.timing + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::ProposeCredential, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs b/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs new file mode 100644 index 0000000000..e916f3be67 --- /dev/null +++ b/messages/src/msg_fields/protocols/cred_issuance/v2/request_credential.rs @@ -0,0 +1,123 @@ +use serde::{Deserialize, Serialize}; +use typed_builder::TypedBuilder; + +use super::AttachmentFormatSpecifier; +use crate::{ + decorators::{attachment::Attachment, thread::Thread, timing::Timing}, + msg_parts::MsgParts, +}; + +pub type RequestCredentialV2 = MsgParts; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)] +pub struct RequestCredentialV2Content { + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_code: Option, + #[builder(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + pub formats: Vec>, + #[serde(rename = "requests~attach")] + pub requests_attach: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)] +pub struct RequestCredentialV2Decorators { + #[builder(default)] + #[serde(rename = "~thread")] + #[serde(skip_serializing_if = "Option::is_none")] + pub thread: Option, + #[builder(default)] + #[serde(rename = "~timing")] + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum RequestCredentialAttachmentFormatType { + #[serde(rename = "dif/credential-manifest@v1.0")] + DifCredentialManifest1_0, + #[serde(rename = "hlindy/cred-req@v2.0")] + HyperledgerIndyCredentialRequest2_0, + #[serde(rename = "aries/ld-proof-vc-detail@v1.0")] + AriesLdProofVcDetail1_0, +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +#[allow(clippy::field_reassign_with_default)] +mod tests { + use serde_json::json; + use shared_vcx::maybe_known::MaybeKnown; + + use super::*; + use crate::{ + decorators::{ + attachment::tests::make_extended_attachment, thread::tests::make_extended_thread, + }, + misc::test_utils, + msg_types::cred_issuance::CredentialIssuanceTypeV2_0, + }; + + #[test] + fn test_minimal_request_cred() { + let content = RequestCredentialV2Content::builder() + .requests_attach(vec![make_extended_attachment()]) + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + RequestCredentialAttachmentFormatType::HyperledgerIndyCredentialRequest2_0, + ), + }]) + .build(); + + let decorators = RequestCredentialV2Decorators::default(); + + let expected = json!({ + "requests~attach": content.requests_attach, + "formats": content.formats + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::RequestCredential, + expected, + ); + } + + #[test] + fn test_extended_request_cred() { + let content = RequestCredentialV2Content::builder() + .requests_attach(vec![make_extended_attachment()]) + .formats(vec![AttachmentFormatSpecifier { + attach_id: "1".to_owned(), + format: MaybeKnown::Known( + RequestCredentialAttachmentFormatType::HyperledgerIndyCredentialRequest2_0, + ), + }]) + .comment(Some("test_comment".to_owned())) + .goal_code(Some("goal.goal".to_owned())) + .build(); + + let decorators = RequestCredentialV2Decorators::builder() + .thread(Some(make_extended_thread())) + .build(); + + let expected = json!({ + "requests~attach": content.requests_attach, + "formats": content.formats, + "comment": content.comment, + "goal_code": content.goal_code, + "~thread": decorators.thread + }); + + test_utils::test_msg( + content, + decorators, + CredentialIssuanceTypeV2_0::RequestCredential, + expected, + ); + } +} diff --git a/messages/src/msg_fields/protocols/notification/mod.rs b/messages/src/msg_fields/protocols/notification/mod.rs index d609c59e01..92d10b6159 100644 --- a/messages/src/msg_fields/protocols/notification/mod.rs +++ b/messages/src/msg_fields/protocols/notification/mod.rs @@ -62,7 +62,10 @@ impl DelayedSerde for Notification { } transit_to_aries_msg!(AckContent: AckDecorators, Notification); -transit_to_aries_msg!(NotificationProblemReportContent: ProblemReportDecorators, Notification); +transit_to_aries_msg!( + NotificationProblemReportContent: ProblemReportDecorators, + Notification +); into_msg_with_type!(Ack, NotificationTypeV1_0, Ack); into_msg_with_type!( diff --git a/messages/src/msg_fields/protocols/present_proof/mod.rs b/messages/src/msg_fields/protocols/present_proof/mod.rs index 73e40c5204..e03dc143e7 100644 --- a/messages/src/msg_fields/protocols/present_proof/mod.rs +++ b/messages/src/msg_fields/protocols/present_proof/mod.rs @@ -85,11 +85,20 @@ impl DelayedSerde for PresentProof { } } -transit_to_aries_msg!(ProposePresentationContent: ProposePresentationDecorators, PresentProof); -transit_to_aries_msg!(RequestPresentationContent: RequestPresentationDecorators, PresentProof); +transit_to_aries_msg!( + ProposePresentationContent: ProposePresentationDecorators, + PresentProof +); +transit_to_aries_msg!( + RequestPresentationContent: RequestPresentationDecorators, + PresentProof +); transit_to_aries_msg!(PresentationContent: PresentationDecorators, PresentProof); transit_to_aries_msg!(AckPresentationContent: AckDecorators, PresentProof); -transit_to_aries_msg!(PresentProofProblemReportContent: ProblemReportDecorators, PresentProof); +transit_to_aries_msg!( + PresentProofProblemReportContent: ProblemReportDecorators, + PresentProof +); into_msg_with_type!( ProposePresentation, diff --git a/messages/src/msg_types/protocols/cred_issuance.rs b/messages/src/msg_types/protocols/cred_issuance.rs index e3c5499915..45b4578581 100644 --- a/messages/src/msg_types/protocols/cred_issuance.rs +++ b/messages/src/msg_types/protocols/cred_issuance.rs @@ -10,6 +10,7 @@ use crate::msg_types::{role::Role, MsgKindType}; #[msg_type(protocol = "issue-credential")] pub enum CredentialIssuanceType { V1(CredentialIssuanceTypeV1), + V2(CredentialIssuanceTypeV2), } #[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] @@ -20,6 +21,14 @@ pub enum CredentialIssuanceTypeV1 { V1_0(MsgKindType), } +#[derive(Copy, Clone, Debug, From, TryInto, PartialEq, Transitive, MessageType)] +#[transitive(into(CredentialIssuanceType, Protocol))] +#[msg_type(major = 2)] +pub enum CredentialIssuanceTypeV2 { + #[msg_type(minor = 0, roles = "Role::Holder, Role::Issuer")] + V2_0(MsgKindType), +} + #[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] #[strum(serialize_all = "kebab-case")] pub enum CredentialIssuanceTypeV1_0 { @@ -32,6 +41,18 @@ pub enum CredentialIssuanceTypeV1_0 { ProblemReport, } +#[derive(Copy, Clone, Debug, AsRefStr, EnumString, PartialEq)] +#[strum(serialize_all = "kebab-case")] +pub enum CredentialIssuanceTypeV2_0 { + OfferCredential, + ProposeCredential, + RequestCredential, + IssueCredential, + CredentialPreview, + Ack, + ProblemReport, +} + #[cfg(test)] mod tests { use serde_json::json; @@ -40,7 +61,7 @@ mod tests { use crate::misc::test_utils; #[test] - fn test_protocol_issue_credential() { + fn test_protocol_issue_credential_v1() { test_utils::test_serde( Protocol::from(CredentialIssuanceTypeV1::new_v1_0()), json!("https://didcomm.org/issue-credential/1.0"), @@ -48,7 +69,7 @@ mod tests { } #[test] - fn test_version_resolution_issue_credential() { + fn test_version_resolution_issue_credential_v1() { test_utils::test_msg_type_resolution( "https://didcomm.org/issue-credential/1.255", CredentialIssuanceTypeV1::new_v1_0(), @@ -57,7 +78,7 @@ mod tests { #[test] #[should_panic] - fn test_unsupported_version_issue_credential() { + fn test_unsupported_version_issue_credential_v1() { test_utils::test_serde( Protocol::from(CredentialIssuanceTypeV1::new_v1_0()), json!("https://didcomm.org/issue-credential/2.0"), @@ -65,7 +86,7 @@ mod tests { } #[test] - fn test_msg_type_offer() { + fn test_msg_type_offer_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "offer-credential", @@ -74,7 +95,7 @@ mod tests { } #[test] - fn test_msg_type_propose() { + fn test_msg_type_propose_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "propose-credential", @@ -83,7 +104,7 @@ mod tests { } #[test] - fn test_msg_type_request() { + fn test_msg_type_request_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "request-credential", @@ -92,7 +113,7 @@ mod tests { } #[test] - fn test_msg_type_issue() { + fn test_msg_type_issue_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "issue-credential", @@ -101,7 +122,7 @@ mod tests { } #[test] - fn test_msg_type_preview() { + fn test_msg_type_preview_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "credential-preview", @@ -110,11 +131,90 @@ mod tests { } #[test] - fn test_msg_type_ack() { + fn test_msg_type_ack_v1() { test_utils::test_msg_type( "https://didcomm.org/issue-credential/1.0", "ack", CredentialIssuanceTypeV1::new_v1_0(), ) } + + #[test] + fn test_protocol_issue_credential_v2() { + test_utils::test_serde( + Protocol::from(CredentialIssuanceTypeV2::new_v2_0()), + json!("https://didcomm.org/issue-credential/2.0"), + ) + } + + #[test] + fn test_version_resolution_issue_credential_v2() { + test_utils::test_msg_type_resolution( + "https://didcomm.org/issue-credential/2.255", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + #[should_panic] + fn test_unsupported_version_issue_credential_v2() { + test_utils::test_serde( + Protocol::from(CredentialIssuanceTypeV2::new_v2_0()), + json!("https://didcomm.org/issue-credential/1.0"), + ) + } + + #[test] + fn test_msg_type_offer_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "offer-credential", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_propose_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "propose-credential", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_request_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "request-credential", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_issue_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "issue-credential", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_preview_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "credential-preview", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } + + #[test] + fn test_msg_type_ack_v2() { + test_utils::test_msg_type( + "https://didcomm.org/issue-credential/2.0", + "ack", + CredentialIssuanceTypeV2::new_v2_0(), + ) + } } diff --git a/messages/src/msg_types/registry.rs b/messages/src/msg_types/registry.rs index 4895969676..bdec49cfcc 100644 --- a/messages/src/msg_types/registry.rs +++ b/messages/src/msg_types/registry.rs @@ -5,11 +5,17 @@ use shared_vcx::maybe_known::MaybeKnown; use super::{role::Role, Protocol}; use crate::msg_types::protocols::{ - basic_message::BasicMessageTypeV1, connection::ConnectionTypeV1, - cred_issuance::CredentialIssuanceTypeV1, discover_features::DiscoverFeaturesTypeV1, - notification::NotificationTypeV1, out_of_band::OutOfBandTypeV1, - present_proof::PresentProofTypeV1, report_problem::ReportProblemTypeV1, - revocation::RevocationTypeV2, routing::RoutingTypeV1, signature::SignatureTypeV1, + basic_message::BasicMessageTypeV1, + connection::ConnectionTypeV1, + cred_issuance::{CredentialIssuanceTypeV1, CredentialIssuanceTypeV2}, + discover_features::DiscoverFeaturesTypeV1, + notification::NotificationTypeV1, + out_of_band::OutOfBandTypeV1, + present_proof::PresentProofTypeV1, + report_problem::ReportProblemTypeV1, + revocation::RevocationTypeV2, + routing::RoutingTypeV1, + signature::SignatureTypeV1, trust_ping::TrustPingTypeV1, }; type RegistryMap = HashMap<(&'static str, u8), Vec>; @@ -75,6 +81,7 @@ lazy_static! { map_insert(&mut m, extract_parts!(ConnectionTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(SignatureTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(CredentialIssuanceTypeV1::new_v1_0())); + map_insert(&mut m, extract_parts!(CredentialIssuanceTypeV2::new_v2_0())); map_insert(&mut m, extract_parts!(DiscoverFeaturesTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(NotificationTypeV1::new_v1_0())); map_insert(&mut m, extract_parts!(OutOfBandTypeV1::new_v1_1())); From 636c29525338029aa3a0300457f2a0d3cd3c4503 Mon Sep 17 00:00:00 2001 From: Patrik Date: Thu, 28 Sep 2023 23:52:22 +0200 Subject: [PATCH 4/4] Connection protocol: add encrypt_message, remove auto-problem-report sending (#982) Connection protocol: add encrypt_message, remove auto-problem-report sending (#982) Signed-off-by: Patrik Stas --- .../src/services/connection.rs | 3 +- aries_vcx/src/common/credentials/mod.rs | 2 +- aries_vcx/src/core/profile/ledger.rs | 2 +- .../src/handlers/proof_presentation/types.rs | 2 +- .../src/protocols/connection/generic/mod.rs | 26 ++--- .../src/protocols/connection/invitee/mod.rs | 31 +----- .../src/protocols/connection/inviter/mod.rs | 32 +----- aries_vcx/src/protocols/connection/mod.rs | 104 +++--------------- .../verifier/state_machine.rs | 4 +- aries_vcx/src/utils/devsetup.rs | 10 +- aries_vcx/tests/utils/migration.rs | 2 +- aries_vcx/tests/utils/scenarios/connection.rs | 7 +- did_doc/src/schema/verification_method/mod.rs | 11 +- did_doc_sov/src/lib.rs | 2 +- .../src/numalgos/numalgo2/resolve/helpers.rs | 8 +- .../numalgos/numalgo2/verification_method.rs | 2 +- did_peer/src/peer_did/numalgos/traits.rs | 2 +- did_resolver_sov/src/resolution/utils.rs | 2 +- libvcx_core/src/api_vcx/api_global/pool.rs | 4 +- .../src/api_vcx/api_handle/connection.rs | 5 +- libvcx_core/src/api_vcx/api_handle/schema.rs | 2 +- .../core/src/handlers/connection.rs | 10 +- 22 files changed, 69 insertions(+), 204 deletions(-) diff --git a/agents/rust/aries-vcx-agent/src/services/connection.rs b/agents/rust/aries-vcx-agent/src/services/connection.rs index 41ef2dd2b9..22cfdc80cb 100644 --- a/agents/rust/aries-vcx-agent/src/services/connection.rs +++ b/agents/rust/aries-vcx-agent/src/services/connection.rs @@ -98,7 +98,6 @@ impl ServiceConnections { request, self.service_endpoint.clone(), vec![], - &HttpClient, ) .await?; @@ -122,7 +121,7 @@ impl ServiceConnections { pub async fn accept_response(&self, thread_id: &str, response: Response) -> AgentResult<()> { let invitee: Connection<_, _> = self.connections.get(thread_id)?.try_into()?; let invitee = invitee - .handle_response(&self.profile.inject_wallet(), response, &HttpClient) + .handle_response(&self.profile.inject_wallet(), response) .await?; self.connections.insert(thread_id, invitee.into())?; diff --git a/aries_vcx/src/common/credentials/mod.rs b/aries_vcx/src/common/credentials/mod.rs index 2f40123c9f..2ed8a6982b 100644 --- a/aries_vcx/src/common/credentials/mod.rs +++ b/aries_vcx/src/common/credentials/mod.rs @@ -112,7 +112,7 @@ mod integration_tests { assert_eq!(prover_cred.schema_id, schema.schema_id); assert_eq!(prover_cred.cred_def_id, cred_def.get_cred_def_id()); - assert_eq!(prover_cred.cred_rev_id.unwrap().to_string(), cred_rev_id); + assert_eq!(prover_cred.cred_rev_id.unwrap(), cred_rev_id); assert_eq!(prover_cred.rev_reg_id.unwrap(), rev_reg.rev_reg_id); }) .await; diff --git a/aries_vcx/src/core/profile/ledger.rs b/aries_vcx/src/core/profile/ledger.rs index 62e43427ac..c28fd6d5ed 100644 --- a/aries_vcx/src/core/profile/ledger.rs +++ b/aries_vcx/src/core/profile/ledger.rs @@ -65,7 +65,7 @@ pub fn indyvdr_build_ledger_read( let response_cacher = Arc::new(InMemoryResponseCacher::new(cache_config)); let config_read = IndyVdrLedgerReadConfig { - request_submitter: request_submitter.clone(), + request_submitter, response_parser, response_cacher, protocol_version: ProtocolVersion::node_1_4(), diff --git a/aries_vcx/src/handlers/proof_presentation/types.rs b/aries_vcx/src/handlers/proof_presentation/types.rs index 45064281be..05eacf9bf1 100644 --- a/aries_vcx/src/handlers/proof_presentation/types.rs +++ b/aries_vcx/src/handlers/proof_presentation/types.rs @@ -135,7 +135,7 @@ impl SelectedCredentials { with_tails_dir: Option, ) { self.credential_for_referent.insert( - referent.to_string(), + referent, SelectedCredentialForReferent { credential: SelectedCredentialForReferentCredential::from(retrieved_cred), tails_dir: with_tails_dir, diff --git a/aries_vcx/src/protocols/connection/generic/mod.rs b/aries_vcx/src/protocols/connection/generic/mod.rs index 8a7f53c52f..b7383b4dce 100644 --- a/aries_vcx/src/protocols/connection/generic/mod.rs +++ b/aries_vcx/src/protocols/connection/generic/mod.rs @@ -8,7 +8,7 @@ use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::AriesMessage; pub use self::thin_state::{State, ThinState}; -use super::{trait_bounds::BootstrapDidDoc, wrap_and_send_msg}; +use super::trait_bounds::BootstrapDidDoc; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::AnyInvitation, @@ -194,13 +194,16 @@ impl GenericConnection { where T: Transport, { - let sender_verkey = &self.pairwise_info().pw_vk; let did_doc = self.their_did_doc().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, "No DidDoc present", ))?; - wrap_and_send_msg(wallet, message, sender_verkey, did_doc, transport).await + let msg = self.encrypt_message(wallet, message).await?.0; + let service_endpoint = did_doc.get_endpoint().ok_or_else(|| { + AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") + })?; + transport.send_message(msg, service_endpoint).await } } @@ -445,10 +448,7 @@ mod connection_serde_tests { .decorators(decorators) .build(); - let con = con - .handle_response(&wallet, response, &MockTransport) - .await - .unwrap(); + let con = con.handle_response(&wallet, response).await.unwrap(); con.send_message(&wallet, &con.get_ack().into(), &MockTransport) .await @@ -497,15 +497,9 @@ mod connection_serde_tests { .decorators(decorators) .build(); - con.handle_request( - &wallet, - request, - new_service_endpoint, - new_routing_keys, - &MockTransport, - ) - .await - .unwrap() + con.handle_request(&wallet, request, new_service_endpoint, new_routing_keys) + .await + .unwrap() } async fn make_inviter_completed() -> InviterConnection { diff --git a/aries_vcx/src/protocols/connection/invitee/mod.rs b/aries_vcx/src/protocols/connection/invitee/mod.rs index f6a7023ea5..2a3dd15255 100644 --- a/aries_vcx/src/protocols/connection/invitee/mod.rs +++ b/aries_vcx/src/protocols/connection/invitee/mod.rs @@ -32,7 +32,6 @@ use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, handlers::util::{matches_thread_id, AnyInvitation}, protocols::connection::trait_bounds::ThreadId, - transport::Transport, }; /// Convenience alias @@ -169,15 +168,11 @@ impl InviteeConnection { /// * the thread ID of the response does not match the connection thread ID /// * no recipient verkeys are provided in the response. /// * decoding the signed response fails - pub async fn handle_response( + pub async fn handle_response( self, wallet: &Arc, response: Response, - transport: &T, - ) -> VcxResult> - where - T: Transport, - { + ) -> VcxResult> { let is_match = matches_thread_id!(response, self.state.thread_id()); if !is_match { @@ -197,25 +192,9 @@ impl InviteeConnection { "Cannot handle response: remote verkey not found", ))?; - let did_doc = - match decode_signed_connection_response(wallet, response.content, their_vk).await { - Ok(con_data) => Ok(con_data.did_doc), - Err(err) => { - error!("Request DidDoc validation failed! Sending ProblemReport..."); - - self.send_problem_report( - wallet, - &err, - self.thread_id(), - &self.state.did_doc, - transport, - ) - .await; - - Err(err) - } - }?; - + let did_doc = decode_signed_connection_response(wallet, response.content, their_vk) + .await? + .did_doc; let state = Completed::new(did_doc, self.state.did_doc, self.state.thread_id, None); Ok(Connection { diff --git a/aries_vcx/src/protocols/connection/inviter/mod.rs b/aries_vcx/src/protocols/connection/inviter/mod.rs index 55ab6013a6..b91682c10c 100644 --- a/aries_vcx/src/protocols/connection/inviter/mod.rs +++ b/aries_vcx/src/protocols/connection/inviter/mod.rs @@ -27,7 +27,6 @@ use crate::{ errors::error::VcxResult, handlers::util::{verify_thread_id, AnyInvitation}, protocols::connection::trait_bounds::ThreadId, - transport::Transport, }; pub type InviterConnection = Connection; @@ -163,17 +162,13 @@ impl InviterConnection { /// invitation /// * the [`Request`]'s DidDoc is not valid /// * generating new [`PairwiseInfo`] fails - pub async fn handle_request( + pub async fn handle_request( self, wallet: &Arc, request: Request, new_service_endpoint: Url, new_routing_keys: Vec, - transport: &T, - ) -> VcxResult> - where - T: Transport, - { + ) -> VcxResult> { trace!( "Connection::process_request >>> request: {:?}, service_endpoint: {}, routing_keys: \ {:?}", @@ -185,28 +180,7 @@ impl InviterConnection { // There must be some other way to validate the thread ID other than cloning the entire // Request verify_thread_id(self.thread_id(), &request.clone().into())?; - - // If the request's DidDoc validation fails, we generate and send a ProblemReport. - // We then return early with the provided error. - if let Err(err) = request.content.connection.did_doc.validate() { - error!("Request DidDoc validation failed! Sending ProblemReport..."); - - self.send_problem_report( - wallet, - &err, - request - .decorators - .thread - .as_ref() - .map(|t| t.thid.as_str()) - .unwrap_or(request.id.as_str()), - &request.content.connection.did_doc, - transport, - ) - .await; - - Err(err)?; - } + request.content.connection.did_doc.validate()?; // Generate new pairwise info that will be used from this point on // and incorporate that into the response. diff --git a/aries_vcx/src/protocols/connection/mod.rs b/aries_vcx/src/protocols/connection/mod.rs index 5ccd2873b1..cd1de53643 100644 --- a/aries_vcx/src/protocols/connection/mod.rs +++ b/aries_vcx/src/protocols/connection/mod.rs @@ -6,28 +6,22 @@ pub mod pairwise_info; mod serializable; mod trait_bounds; -use std::{error::Error, sync::Arc}; +use std::sync::Arc; use aries_vcx_core::wallet::base_wallet::BaseWallet; -use chrono::Utc; use diddoc_legacy::aries::diddoc::AriesDidDoc; use messages::{ - decorators::{thread::Thread, timing::Timing}, - msg_fields::protocols::{ - connection::problem_report::{ - ProblemReport, ProblemReportContent, ProblemReportDecorators, - }, - discover_features::{disclose::Disclose, query::QueryContent, ProtocolDescriptor}, + msg_fields::protocols::discover_features::{ + disclose::Disclose, query::QueryContent, ProtocolDescriptor, }, AriesMessage, }; -use uuid::Uuid; pub use self::generic::{GenericConnection, State, ThinState}; use self::{ generic::GenericState, pairwise_info::PairwiseInfo, - trait_bounds::{CompletedState, HandleProblem, TheirDidDoc, ThreadId}, + trait_bounds::{CompletedState, TheirDidDoc, ThreadId}, }; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, @@ -102,6 +96,15 @@ where self.state.their_did_doc() } + pub async fn encrypt_message( + &self, + wallet: &Arc, + message: &AriesMessage, + ) -> VcxResult { + let sender_verkey = &self.pairwise_info().pw_vk; + EncryptionEnvelope::create(wallet, message, Some(sender_verkey), self.their_did_doc()).await + } + pub fn remote_did(&self) -> &str { &self.their_did_doc().id } @@ -126,63 +129,11 @@ where where T: Transport, { - let sender_verkey = &self.pairwise_info().pw_vk; - let did_doc = self.their_did_doc(); - wrap_and_send_msg(wallet, message, sender_verkey, did_doc, transport).await - } -} - -impl Connection -where - S: HandleProblem, -{ - fn create_problem_report(&self, err: &E, thread_id: &str) -> ProblemReport - where - E: Error, - { - let content = ProblemReportContent::builder() - .explain(err.to_string()) - .build(); - - let decorators = ProblemReportDecorators::builder() - .thread(Thread::builder().thid(thread_id.to_owned()).build()) - .timing(Timing::builder().out_time(Utc::now()).build()) - .build(); - - ProblemReport::builder() - .id(Uuid::new_v4().to_string()) - .content(content) - .decorators(decorators) - .build() - } - - async fn send_problem_report( - &self, - wallet: &Arc, - err: &E, - thread_id: &str, - did_doc: &AriesDidDoc, - transport: &T, - ) where - E: Error, - T: Transport, - { - let sender_verkey = &self.pairwise_info().pw_vk; - let problem_report = self.create_problem_report(err, thread_id); - let res = wrap_and_send_msg( - wallet, - &problem_report.into(), - sender_verkey, - did_doc, - transport, - ) - .await; - - if let Err(e) = res { - trace!("Error encountered when sending ProblemReport: {}", e); - } else { - info!("Error report sent!"); - } + let msg = self.encrypt_message(wallet, message).await?.0; + let service_endpoint = self.their_did_doc().get_endpoint().ok_or_else(|| { + AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") + })?; + transport.send_message(msg, service_endpoint).await } } @@ -198,22 +149,3 @@ where self.state.handle_disclose(disclose) } } - -pub(crate) async fn wrap_and_send_msg( - wallet: &Arc, - message: &AriesMessage, - sender_verkey: &str, - did_doc: &AriesDidDoc, - transport: &T, -) -> VcxResult<()> -where - T: Transport, -{ - let env = EncryptionEnvelope::create(wallet, message, Some(sender_verkey), did_doc).await?; - let msg = env.0; - let service_endpoint = did_doc.get_endpoint().ok_or_else(|| { - AriesVcxError::from_msg(AriesVcxErrorKind::InvalidUrl, "No URL in DID Doc") - })?; // This, like many other things, shouldn't clone... - - transport.send_message(msg, service_endpoint).await -} diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs index a3a0789ac5..7d6958f04b 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs @@ -282,9 +282,7 @@ impl VerifierSM { (state, presentation, PresentationVerificationStatus::Invalid) .into(), ), - _ => { - VerifierFullState::Finished((state, problem_report.clone()).into()) - } + _ => VerifierFullState::Finished((state, problem_report).into()), } } } diff --git a/aries_vcx/src/utils/devsetup.rs b/aries_vcx/src/utils/devsetup.rs index c455e132be..5bbb1e8d60 100644 --- a/aries_vcx/src/utils/devsetup.rs +++ b/aries_vcx/src/utils/devsetup.rs @@ -176,7 +176,7 @@ pub fn dev_build_profile_vdrtools( ) -> Arc { info!("dev_build_profile_vdrtools >>"); let vcx_pool_config = VcxPoolConfig { - genesis_file_path: genesis_file_path.clone(), + genesis_file_path, indy_vdr_config: None, response_cache_config: None, }; @@ -185,10 +185,10 @@ pub fn dev_build_profile_vdrtools( build_ledger_components(wallet.clone(), vcx_pool_config).unwrap(); let anoncreds_ledger_read: Arc = ledger_read.clone(); let anoncreds_ledger_write: Arc = ledger_write.clone(); - let indy_ledger_read: Arc = ledger_read.clone(); - let indy_ledger_write: Arc = ledger_write.clone(); + let indy_ledger_read: Arc = ledger_read; + let indy_ledger_write: Arc = ledger_write; Arc::new(VdrtoolsProfile::init( - wallet.clone(), + wallet, anoncreds_ledger_read, anoncreds_ledger_write, indy_ledger_read, @@ -203,7 +203,7 @@ pub fn dev_build_profile_modular( ) -> Arc { info!("dev_build_profile_modular >>"); let vcx_pool_config = VcxPoolConfig { - genesis_file_path: genesis_file_path.clone(), + genesis_file_path, indy_vdr_config: None, response_cache_config: None, }; diff --git a/aries_vcx/tests/utils/migration.rs b/aries_vcx/tests/utils/migration.rs index 96265ba007..ea9fe74d55 100644 --- a/aries_vcx/tests/utils/migration.rs +++ b/aries_vcx/tests/utils/migration.rs @@ -36,7 +36,7 @@ impl Migratable for TestAgent { let old_wh = self.profile.wallet_handle().unwrap(); let new_wh = migrate_to_new_wallet(old_wh).await; let wallet = Arc::new(IndySdkWallet::new(new_wh)); - self.profile = dev_build_profile_modular(self.genesis_file_path.clone(), wallet.clone()); + self.profile = dev_build_profile_modular(self.genesis_file_path.clone(), wallet); } } diff --git a/aries_vcx/tests/utils/scenarios/connection.rs b/aries_vcx/tests/utils/scenarios/connection.rs index f3f3c4ed7e..30e9680bef 100644 --- a/aries_vcx/tests/utils/scenarios/connection.rs +++ b/aries_vcx/tests/utils/scenarios/connection.rs @@ -59,14 +59,13 @@ async fn establish_connection_from_invite( request, "http://dummy.org".parse().unwrap(), vec![], - &DummyHttpClient, ) .await .unwrap(); let response = inviter.get_connection_response_msg(); let invitee = invitee - .handle_response(&alice.profile.inject_wallet(), response, &DummyHttpClient) + .handle_response(&alice.profile.inject_wallet(), response) .await .unwrap(); let ack = invitee.get_ack(); @@ -95,7 +94,7 @@ pub async fn create_connections_via_oob_invite( .unwrap(); // TODO: Create a key and write on ledger instead let inviter_pairwise_info = PairwiseInfo { - pw_did: ddo.clone().id.clone(), + pw_did: ddo.clone().id, pw_vk: ddo.recipient_keys().unwrap().first().unwrap().to_string(), }; establish_connection_from_invite(alice, faber, invitation, inviter_pairwise_info).await @@ -121,7 +120,7 @@ pub async fn create_connections_via_public_invite( .unwrap(); // TODO: Create a key and write on ledger instead let inviter_pairwise_info = PairwiseInfo { - pw_did: ddo.clone().id.clone(), + pw_did: ddo.clone().id, pw_vk: ddo.recipient_keys().unwrap().first().unwrap().to_string(), }; establish_connection_from_invite(alice, faber, public_invite.clone(), inviter_pairwise_info) diff --git a/did_doc/src/schema/verification_method/mod.rs b/did_doc/src/schema/verification_method/mod.rs index b4fcd62c16..df5ab7c02f 100644 --- a/did_doc/src/schema/verification_method/mod.rs +++ b/did_doc/src/schema/verification_method/mod.rs @@ -230,7 +230,7 @@ mod tests { let vm = VerificationMethod::builder(id.clone(), controller.clone(), verification_method_type) - .add_public_key_multibase(public_key_multibase.clone()) + .add_public_key_multibase(public_key_multibase) .build(); assert_eq!(vm.id(), &id); @@ -255,7 +255,7 @@ mod tests { let vm = VerificationMethod::builder(id.clone(), controller.clone(), verification_method_type) - .add_public_key_multibase(public_key_multibase.clone()) + .add_public_key_multibase(public_key_multibase) .build(); assert_eq!(vm.id(), &id); @@ -298,10 +298,9 @@ mod tests { let verification_method_type = create_valid_verification_key_type(); let public_key_multibase_expected = create_valid_multibase(); - let vm = - VerificationMethod::builder(id.clone(), controller.clone(), verification_method_type) - .add_public_key_multibase(public_key_multibase_expected.clone()) - .build(); + let vm = VerificationMethod::builder(id, controller, verification_method_type) + .add_public_key_multibase(public_key_multibase_expected.clone()) + .build(); match vm.public_key_field() { PublicKeyField::Multibase { diff --git a/did_doc_sov/src/lib.rs b/did_doc_sov/src/lib.rs index f8f4364202..8d4077bb6f 100644 --- a/did_doc_sov/src/lib.rs +++ b/did_doc_sov/src/lib.rs @@ -114,7 +114,7 @@ impl DidDocumentSovBuilder { } pub fn add_service(mut self, service: ServiceSov) -> Self { - self.services.push(service.clone()); + self.services.push(service); self } diff --git a/did_peer/src/numalgos/numalgo2/resolve/helpers.rs b/did_peer/src/numalgos/numalgo2/resolve/helpers.rs index fee97a642c..1ea38dc516 100644 --- a/did_peer/src/numalgos/numalgo2/resolve/helpers.rs +++ b/did_peer/src/numalgos/numalgo2/resolve/helpers.rs @@ -159,7 +159,7 @@ fn build_service_aip1( service.service_endpoint().parse()?, ExtraFieldsSov::AIP1(ExtraFieldsAIP1::default()), ) - .add_service_type(service_type.to_string())? + .add_service_type(service_type)? .build()) } @@ -174,7 +174,7 @@ fn build_service_didcommv2( let extra = ExtraFieldsSov::DIDCommV2(extra_builder.build()); Ok( Service::::builder(id, service.service_endpoint().parse()?, extra) - .add_service_type(service_type.to_string())? + .add_service_type(service_type)? .build(), ) } @@ -247,7 +247,7 @@ mod tests { .parse() .unwrap(); let mut index = 0; - let ddo_builder = DidDocumentBuilder::::new(did.clone()); + let ddo_builder = DidDocumentBuilder::::new(did); let built_ddo = process_service_element(purposeless_service_element, ddo_builder, &mut index) .unwrap() @@ -272,7 +272,7 @@ mod tests { .parse() .unwrap(); let mut index = 0; - let ddo_builder = DidDocumentBuilder::::new(did.clone()); + let ddo_builder = DidDocumentBuilder::::new(did); let built_ddo = process_service_element(purposeless_service_element, ddo_builder, &mut index) .unwrap() diff --git a/did_peer/src/numalgos/numalgo2/verification_method.rs b/did_peer/src/numalgos/numalgo2/verification_method.rs index 807aa5d5e0..4e98a74014 100644 --- a/did_peer/src/numalgos/numalgo2/verification_method.rs +++ b/did_peer/src/numalgos/numalgo2/verification_method.rs @@ -80,7 +80,7 @@ fn build_verification_methods_from_bls_multikey( let vm1 = add_public_key_to_builder( VerificationMethod::builder( - id1.to_owned(), + id1, did.to_owned(), VerificationMethodType::Bls12381G1Key2020, ), diff --git a/did_peer/src/peer_did/numalgos/traits.rs b/did_peer/src/peer_did/numalgos/traits.rs index af785f396a..c7283422a5 100644 --- a/did_peer/src/peer_did/numalgos/traits.rs +++ b/did_peer/src/peer_did/numalgos/traits.rs @@ -19,7 +19,7 @@ pub trait Numalgo: Sized + Default { { let did: Did = did.try_into().map_err(Into::into)?; - let numalgo_char = did.id().chars().nth(0).ok_or_else(|| { + let numalgo_char = did.id().chars().next().ok_or_else(|| { DidPeerError::DidValidationError(format!( "Invalid did: unable to read numalgo character in did {}", did.did() diff --git a/did_resolver_sov/src/resolution/utils.rs b/did_resolver_sov/src/resolution/utils.rs index 0bc1ec212c..7a025a1d3a 100644 --- a/did_resolver_sov/src/resolution/utils.rs +++ b/did_resolver_sov/src/resolution/utils.rs @@ -96,7 +96,7 @@ pub(super) async fn ledger_response_to_ddo( did.to_string().try_into()?, VerificationMethodType::Ed25519VerificationKey2018, ) - .add_public_key_base58(verkey.to_string()) + .add_public_key_base58(verkey) .build(); let ddo = DidDocument::builder(ddo_id) diff --git a/libvcx_core/src/api_vcx/api_global/pool.rs b/libvcx_core/src/api_vcx/api_global/pool.rs index 6a8ef6f350..fc4778635f 100644 --- a/libvcx_core/src/api_vcx/api_global/pool.rs +++ b/libvcx_core/src/api_vcx/api_global/pool.rs @@ -115,9 +115,9 @@ async fn build_components_ledger( )); let taa_configurator: Arc = ledger_write.clone(); let anoncreds_write: Arc = ledger_write.clone(); - let indy_write: Arc = ledger_write.clone(); + let indy_write: Arc = ledger_write; let anoncreds_read: Arc = ledger_read.clone(); - let indy_read: Arc = ledger_read.clone(); + let indy_read: Arc = ledger_read; Ok(( anoncreds_read, anoncreds_write, diff --git a/libvcx_core/src/api_vcx/api_handle/connection.rs b/libvcx_core/src/api_vcx/api_handle/connection.rs index 10acb3f92e..691a7df7b4 100644 --- a/libvcx_core/src/api_vcx/api_handle/connection.rs +++ b/libvcx_core/src/api_vcx/api_handle/connection.rs @@ -288,7 +288,6 @@ pub async fn process_request( LibvcxError::from_msg(LibvcxErrorKind::InvalidUrl, err.to_string()) })?, routing_keys, - &HttpClient, ) .await?; @@ -300,9 +299,7 @@ pub async fn process_response(handle: u32, response: &str) -> LibvcxResult<()> { let con = get_cloned_connection(&handle)?; let response = deserialize(response)?; - let con = con - .handle_response(&get_main_wallet()?, response, &HttpClient) - .await?; + let con = con.handle_response(&get_main_wallet()?, response).await?; insert_connection(handle, con) } diff --git a/libvcx_core/src/api_vcx/api_handle/schema.rs b/libvcx_core/src/api_vcx/api_handle/schema.rs index 7329e36107..0e45dac00f 100644 --- a/libvcx_core/src/api_vcx/api_handle/schema.rs +++ b/libvcx_core/src/api_vcx/api_handle/schema.rs @@ -169,7 +169,7 @@ pub mod test_utils { info!("schema: {:?}", schema); assert_eq!(schema.schema_id, schema_id.to_string()); - let mut schema_data = schema.data.clone(); + let mut schema_data = schema.data; schema_data.sort(); let mut vec_data: Vec = serde_json::from_str(data).unwrap(); vec_data.sort(); diff --git a/uniffi_aries_vcx/core/src/handlers/connection.rs b/uniffi_aries_vcx/core/src/handlers/connection.rs index ba68424992..b257902674 100644 --- a/uniffi_aries_vcx/core/src/handlers/connection.rs +++ b/uniffi_aries_vcx/core/src/handlers/connection.rs @@ -147,13 +147,7 @@ impl Connection { block_on(async { let new_conn = connection - .handle_request( - &profile.inner.inject_wallet(), - request, - url, - routing_keys, - &HttpClient, - ) + .handle_request(&profile.inner.inject_wallet(), request, url, routing_keys) .await?; *handler = VcxGenericConnection::from(new_conn); @@ -178,7 +172,7 @@ impl Connection { block_on(async { let new_conn = connection - .handle_response(&profile.inner.inject_wallet(), response, &HttpClient) + .handle_response(&profile.inner.inject_wallet(), response) .await?; *handler = VcxGenericConnection::from(new_conn);