From 59938d7893db2fda381bac945202e10680a06681 Mon Sep 17 00:00:00 2001 From: Bogdan Mircea <98585737+bobozaur@users.noreply.github.com> Date: Wed, 4 Oct 2023 17:41:00 +0300 Subject: [PATCH] Refactor/remove mocks (#1005) * Removed mocks from aries_vcx_core * Removed global issuer DID in libvcx_core * Removed mocks from aries_vcx * Added usage of issuerDid in node agent functions * Fixed seed and restored test in node JS wrapper --------- Signed-off-by: Bogdan Mircea --- .github/workflows/main.yml | 23 +- Cargo.lock | 1 + agents/node/vcxagent-core/demo/faber.js | 12 +- agents/node/vcxagent-core/src/agent.js | 15 +- .../src/services/service-ledger-creddef.js | 11 +- .../src/services/service-ledger-schema.js | 10 +- .../services/service-revocation-registry.js | 4 +- agents/node/vcxagent-core/test/utils/faber.js | 83 +-- agents/rust/aries-vcx-agent/src/agent/init.rs | 6 +- .../src/services/connection.rs | 2 +- .../src/services/credential_definition.rs | 2 +- .../aries-vcx-agent/src/services/holder.rs | 2 +- .../aries-vcx-agent/src/services/issuer.rs | 2 +- .../aries-vcx-agent/src/services/prover.rs | 2 +- .../src/services/revocation_registry.rs | 2 +- .../aries-vcx-agent/src/services/schema.rs | 2 +- .../aries-vcx-agent/src/services/verifier.rs | 2 +- aries_vcx/src/common/anoncreds.rs | 13 +- aries_vcx/src/common/credentials/mod.rs | 9 +- aries_vcx/src/common/ledger/transactions.rs | 4 - .../primitives/credential_definition.rs | 14 +- .../common/primitives/credential_schema.rs | 26 +- .../common/primitives/revocation_registry.rs | 14 +- aries_vcx/src/common/proofs/prover/mod.rs | 76 ++- aries_vcx/src/common/proofs/prover/prover.rs | 74 -- .../common/proofs/prover/prover_internal.rs | 5 +- aries_vcx/src/common/proofs/verifier/mod.rs | 645 +++++++++++++++++- .../src/common/proofs/verifier/verifier.rs | 643 ----------------- .../proofs/verifier/verifier_internal.rs | 6 +- aries_vcx/src/core/profile/mod.rs | 44 +- .../src/core/profile/modular_libs_profile.rs | 2 +- aries_vcx/src/core/profile/profile.rs | 36 - .../src/core/profile/vdr_proxy_profile.rs | 2 +- .../src/core/profile/vdrtools_profile.rs | 2 +- aries_vcx/src/global/settings.rs | 162 ----- .../src/handlers/out_of_band/receiver.rs | 12 +- aries_vcx/src/handlers/out_of_band/sender.rs | 12 +- aries_vcx/src/handlers/util.rs | 7 - aries_vcx/src/lib.rs | 18 - .../issuance/holder/state_machine.rs | 2 +- .../issuance/holder/states/initial.rs | 6 +- .../states/presentation_request_received.rs | 2 +- .../states/presentation_request_sent.rs | 5 +- .../receiver/state_machine.rs | 2 +- .../receiver/states/initial.rs | 8 +- .../sender/state_machine.rs | 2 +- .../sender/states/initial.rs | 8 +- aries_vcx/src/utils/devsetup.rs | 53 +- aries_vcx/src/utils/encryption_envelope.rs | 6 +- .../utils/mockdata/profile/mock_profile.rs | 2 +- aries_vcx/tests/test_connection.rs | 2 +- aries_vcx/tests/test_credential_retrieval.rs | 2 +- aries_vcx/tests/test_mysql_wallet.rs | 9 +- aries_vcx/tests/test_pool.rs | 4 +- aries_vcx/tests/test_proof_presentation.rs | 2 +- aries_vcx/tests/test_revocations.rs | 2 +- aries_vcx/tests/utils/migration.rs | 2 +- aries_vcx/tests/utils/scenarios/connection.rs | 2 +- .../utils/scenarios/credential_issuance.rs | 2 +- .../utils/scenarios/proof_presentation.rs | 2 +- aries_vcx/tests/utils/test_agent.rs | 2 +- .../anoncreds/indy/credentials/holder/mod.rs | 17 +- .../anoncreds/indy/credentials/issuer/mod.rs | 15 - .../src/anoncreds/indy/proofs/prover.rs | 13 +- aries_vcx_core/src/global/settings.rs | 108 --- .../src/wallet/indy/internal/mod.rs | 44 +- aries_vcx_core/src/wallet/indy/signing.rs | 17 - aries_vcx_core/src/wallet/indy/wallet.rs | 19 - did_resolver_sov/tests/resolution.rs | 3 +- libvcx_core/Cargo.toml | 1 + .../src/api_vcx/api_global/agency_client.rs | 23 +- libvcx_core/src/api_vcx/api_global/ledger.rs | 28 +- libvcx_core/src/api_vcx/api_global/mod.rs | 1 - libvcx_core/src/api_vcx/api_global/pool.rs | 5 +- libvcx_core/src/api_vcx/api_global/profile.rs | 4 - .../src/api_vcx/api_global/settings.rs | 23 - libvcx_core/src/api_vcx/api_global/state.rs | 68 -- .../src/api_vcx/api_handle/credential.rs | 92 +-- .../src/api_vcx/api_handle/credential_def.rs | 140 +--- .../src/api_vcx/api_handle/disclosed_proof.rs | 171 +---- .../api_vcx/api_handle/issuer_credential.rs | 93 +-- .../api_vcx/api_handle/mediated_connection.rs | 251 +------ libvcx_core/src/api_vcx/api_handle/proof.rs | 293 +------- .../api_vcx/api_handle/revocation_registry.rs | 15 +- libvcx_core/src/api_vcx/api_handle/schema.rs | 193 +----- libvcx_core/src/api_vcx/utils/devsetup.rs | 7 +- uniffi_aries_vcx/core/src/core/profile.rs | 2 +- .../core/src/core/unpack_message.rs | 2 +- .../core/src/handlers/connection.rs | 2 +- wrappers/node/src/api/credential-def.ts | 4 +- wrappers/node/src/api/init.ts | 14 +- wrappers/node/src/api/revocation-registry.ts | 4 +- wrappers/node/src/api/schema.ts | 3 +- wrappers/node/test/helpers/entities.ts | 41 +- wrappers/node/test/helpers/mockdata.ts | 2 + wrappers/node/test/helpers/utils.ts | 8 - wrappers/node/test/integration/ledger.test.ts | 10 +- .../test/suite1/ariesvcx-connection.test.ts | 8 +- .../suite1/ariesvcx-credential-def.test.ts | 4 +- .../test/suite1/ariesvcx-credential.test.ts | 4 +- .../suite1/ariesvcx-disclosed-proof.test.ts | 4 +- .../suite1/ariesvcx-issuer-credential.test.ts | 4 +- .../ariesvcx-mediated-connection.test.ts | 4 +- .../node/test/suite1/ariesvcx-oob.test.ts | 4 +- .../node/test/suite1/ariesvcx-proof.test.ts | 4 +- .../node/test/suite1/ariesvcx-schema.test.ts | 4 +- .../node/test/suite1/ariesvcx-utils.test.ts | 4 +- .../node/test/suite1/ariesvcx-wallet.test.ts | 4 +- wrappers/vcx-napi-rs/index.d.ts | 8 +- wrappers/vcx-napi-rs/index.js | 4 +- .../src/api/credential_definition.rs | 3 +- wrappers/vcx-napi-rs/src/api/mod.rs | 1 - .../src/api/revocation_registry.rs | 7 +- wrappers/vcx-napi-rs/src/api/schema.rs | 3 +- wrappers/vcx-napi-rs/src/api/testing.rs | 10 - wrappers/vcx-napi-rs/src/api/wallet.rs | 17 +- wrappers/vcx-napi-rs/tsconfig.json | 24 +- 117 files changed, 1071 insertions(+), 2924 deletions(-) delete mode 100644 aries_vcx/src/common/proofs/prover/prover.rs delete mode 100644 aries_vcx/src/common/proofs/verifier/verifier.rs delete mode 100644 aries_vcx/src/core/profile/profile.rs delete mode 100644 libvcx_core/src/api_vcx/api_global/settings.rs delete mode 100644 wrappers/vcx-napi-rs/src/api/testing.rs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ff2c4ba172..f6315514a4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -438,25 +438,6 @@ jobs: run: | RUST_TEST_THREADS=1 cargo test -p did_doc -p did_parser -p did_resolver -p did_resolver_registry -p did_resolver_sov -p did_resolver_web -p did_doc_sov -p did_key -p did_peer --test "*" - test-node-wrapper: - needs: workflow-setup - if: ${{ needs.workflow-setup.outputs.SKIP_CI != 'true' }} - runs-on: ubuntu-22.04 - strategy: - matrix: - node-version: [18.x] - steps: - - name: "Git checkout" - uses: actions/checkout@v3 - - name: "Setup NodeJS libvcx testing environment" - uses: ./.github/actions/setup-testing-nodejs - with: - rust-toolchain-version: ${{ env.RUST_TOOLCHAIN_VERSON }} - skip-docker-setup: true - node-version: ${{ matrix.node-version }} - - name: "Run tests" - run: cd wrappers/node && npm run test - test-integration-node-wrapper: needs: workflow-setup if: ${{ needs.workflow-setup.outputs.SKIP_CI != 'true' }} @@ -613,7 +594,7 @@ jobs: - test-integration-libvcx - test-integration-aries-vcx - test-integration-aries-vcx-mysql - - test-node-wrapper + # - test-node-wrapper - test-integration-node-wrapper - workflow-setup - build-napi @@ -637,7 +618,7 @@ jobs: - test-integration-libvcx - test-integration-aries-vcx - test-integration-aries-vcx-mysql - - test-node-wrapper + # - test-node-wrapper - test-integration-node-wrapper if: ${{ needs.workflow-setup.outputs.RELEASE == 'true' || needs.workflow-setup.outputs.PRERELEASE == 'true' }} outputs: diff --git a/Cargo.lock b/Cargo.lock index d0e6ff839f..6c019f7cce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2975,6 +2975,7 @@ version = "0.59.1" dependencies = [ "agency_client", "aries-vcx", + "aries_vcx_core", "async-trait", "cfg-if 1.0.0", "chrono", diff --git a/agents/node/vcxagent-core/demo/faber.js b/agents/node/vcxagent-core/demo/faber.js index ea7616e56c..c3ceba3c75 100644 --- a/agents/node/vcxagent-core/demo/faber.js +++ b/agents/node/vcxagent-core/demo/faber.js @@ -17,7 +17,7 @@ const mkdirp = require('mkdirp') const tailsDir = '/tmp/tails' -async function runFaber (options) { +async function runFaber(options) { logger.info(`Starting Faber. Revocation enabled=${options.revocation}`) mkdirp.sync(tailsDir) initRustLogger(process.env.RUST_LOG || 'vcx=error') @@ -49,10 +49,10 @@ async function runFaber (options) { await vcxAgent.acceptTaa() } - const schemaId = await vcxAgent.serviceLedgerSchema.createSchema(getSampleSchemaData()) - await sleep(500) - const vcxCredDef = await vcxAgent.serviceLedgerCredDef.createCredentialDefinitionV2(schemaId, getFaberCredDefName(), true, 'tag1') const issuerDid = vcxAgent.getInstitutionDid() + const schemaId = await vcxAgent.serviceLedgerSchema.createSchema(getSampleSchemaData(), issuerDid) + await sleep(500) + const vcxCredDef = await vcxAgent.serviceLedgerCredDef.createCredentialDefinitionV2(issuerDid, schemaId, getFaberCredDefName(), true, 'tag1') const { revReg, revRegId } = await vcxAgent.serviceLedgerRevReg.createRevocationRegistry(issuerDid, await vcxCredDef.getCredDefId(), 1, tailsDir, 5, testTailsUrl) await vcxAgent.serviceConnections.inviterConnectionCreateAndAccept(connectionId, (invitationString) => { @@ -89,7 +89,7 @@ async function runFaber (options) { logger.info('Faber is revoking issued credential') await vcxAgent.serviceCredIssuer.revokeCredentialLocal(issuerCredId) logger.info('Faber is publishing revocation') - await revReg.publishRevocations() + await revReg.publishRevocations(issuerDid) } logger.info('#19 Create a Proof object') @@ -195,7 +195,7 @@ const usage = [ } ] -function areOptionsValid (_options) { +function areOptionsValid(_options) { return true } diff --git a/agents/node/vcxagent-core/src/agent.js b/agents/node/vcxagent-core/src/agent.js index b1997a0b7b..392b31b580 100644 --- a/agents/node/vcxagent-core/src/agent.js +++ b/agents/node/vcxagent-core/src/agent.js @@ -15,7 +15,6 @@ const { createServiceLedgerRevocationRegistry } = require('./services/service-re const { provisionAgentInAgency } = require('./utils/vcx-workflows') const { createAgencyClientForMainWallet, - initIssuerConfig, openMainWallet, openMainPool, vcxUpdateWebhookUrl, @@ -25,7 +24,7 @@ const { createStorageService } = require('./storage/storage-service') const { waitUntilAgencyIsReady, getAgencyConfig } = require('./common') const path = require('path') -async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, walletExtraConfigs, endpointInfo, logger }) { +async function createVcxAgent({ agentName, genesisPath, agencyUrl, seed, walletExtraConfigs, endpointInfo, logger }) { genesisPath = genesisPath || path.join(__dirname, '/../resources/docker.txn') await waitUntilAgencyIsReady(agencyUrl, logger) @@ -39,12 +38,10 @@ async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, wallet const agentProvision = await storageService.loadAgentProvision() const issuerDid = agentProvision.issuerConfig.institution_did - async function agentInitVcx () { + async function agentInitVcx() { logger.info(`Initializing ${agentName} vcx session.`) logger.silly(`Using following agent provision to initialize VCX settings ${JSON.stringify(agentProvision, null, 2)}`) - logger.silly('Initializing issuer config') - await initIssuerConfig(agentProvision.issuerConfig) logger.silly('Opening main wallet') await openMainWallet(agentProvision.walletConfig) logger.silly('Creating cloud agency config') @@ -53,17 +50,17 @@ async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, wallet await openMainPool({ genesis_path: genesisPath }) } - async function agentShutdownVcx () { + async function agentShutdownVcx() { logger.debug(`Shutting down ${agentName} vcx session.`) shutdownVcx() } - async function updateWebhookUrl (webhookUrl) { + async function updateWebhookUrl(webhookUrl) { logger.info(`Updating webhook url to ${webhookUrl}`) await vcxUpdateWebhookUrl({ webhookUrl }) } - async function acceptTaa () { + async function acceptTaa() { const taa = await getLedgerAuthorAgreement() const taaJson = JSON.parse(taa) const acceptanceMechanism = Object.keys(taaJson.aml)[0] @@ -71,7 +68,7 @@ async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, wallet await setActiveTxnAuthorAgreementMeta(taaJson.text, taaJson.version, acceptanceMechanism) } - function getInstitutionDid () { + function getInstitutionDid() { return issuerDid } diff --git a/agents/node/vcxagent-core/src/services/service-ledger-creddef.js b/agents/node/vcxagent-core/src/services/service-ledger-creddef.js index 2e6aeaf29a..da6f373347 100644 --- a/agents/node/vcxagent-core/src/services/service-ledger-creddef.js +++ b/agents/node/vcxagent-core/src/services/service-ledger-creddef.js @@ -1,8 +1,9 @@ const { CredentialDef } = require('@hyperledger/node-vcx-wrapper') -module.exports.createServiceLedgerCredDef = function createServiceLedgerCredDef ({ logger, saveCredDef, loadCredDef, listCredDefIds }) { - async function createCredentialDefinitionV2 (schemaId, credDefId, supportRevocation, tag = 'tag1') { +module.exports.createServiceLedgerCredDef = function createServiceLedgerCredDef({ logger, saveCredDef, loadCredDef, listCredDefIds }) { + async function createCredentialDefinitionV2(issuerDid, schemaId, credDefId, supportRevocation, tag = 'tag1') { const data = { + issuerDid, supportRevocation, schemaId, sourceId: credDefId, @@ -16,11 +17,11 @@ module.exports.createServiceLedgerCredDef = function createServiceLedgerCredDef return credDef } - async function listIds () { + async function listIds() { return listCredDefIds() } - async function printInfo (credDefIds) { + async function printInfo(credDefIds) { for (const id of credDefIds) { const credDef = await loadCredDef(id) const serCredDef = credDef.serialize() @@ -28,7 +29,7 @@ module.exports.createServiceLedgerCredDef = function createServiceLedgerCredDef } } - async function getCredDefId (credDefId) { + async function getCredDefId(credDefId) { const credDef = await loadCredDef(credDefId) logger.info(`Getting credDefId for credential definition ${credDefId}`) return credDef.getCredDefId() diff --git a/agents/node/vcxagent-core/src/services/service-ledger-schema.js b/agents/node/vcxagent-core/src/services/service-ledger-schema.js index 9f5465924b..db2249f746 100644 --- a/agents/node/vcxagent-core/src/services/service-ledger-schema.js +++ b/agents/node/vcxagent-core/src/services/service-ledger-schema.js @@ -1,20 +1,20 @@ const { Schema } = require('@hyperledger/node-vcx-wrapper') -module.exports.createServiceLedgerSchema = function createServiceLedgerSchema ({ logger, saveSchema, loadSchema, listSchemaIds }) { - async function createSchema (schemaData) { +module.exports.createServiceLedgerSchema = function createServiceLedgerSchema({ logger, saveSchema, loadSchema, listSchemaIds }) { + async function createSchema(schemaData, issuerDid) { logger.info(`Creating a new schema on the ledger: ${JSON.stringify(schemaData, null, 2)}`) - const schema = await Schema.create(schemaData) + const schema = await Schema.create(schemaData, issuerDid) const schemaId = await schema.getSchemaId() await saveSchema(schemaId, schema) return schemaId } - async function listIds () { + async function listIds() { return listSchemaIds() } - async function printInfo (schemaIds) { + async function printInfo(schemaIds) { for (const id of schemaIds) { const serSchema = await loadSchema(id) logger.info(`Schema ${id}: ${JSON.stringify(serSchema)}`) diff --git a/agents/node/vcxagent-core/src/services/service-revocation-registry.js b/agents/node/vcxagent-core/src/services/service-revocation-registry.js index f0ebcaacd5..1130c11cc9 100644 --- a/agents/node/vcxagent-core/src/services/service-revocation-registry.js +++ b/agents/node/vcxagent-core/src/services/service-revocation-registry.js @@ -32,10 +32,10 @@ module.exports.createServiceLedgerRevocationRegistry = function createServiceLed return { revReg: newRevReg, revRegId: newRevRegId } } - async function publishRevocations (revRegId) { + async function publishRevocations (revRegId, submittderDid) { logger.info(`Publishing revocations for revocation registry ${revRegId}`) const revReg = await loadRevReg(revRegId) - await revReg.publishRevocations() + await revReg.publishRevocations(submittderDid) } async function getTailsFile (credDefId) { diff --git a/agents/node/vcxagent-core/test/utils/faber.js b/agents/node/vcxagent-core/test/utils/faber.js index 042a67c432..68aec8f4be 100644 --- a/agents/node/vcxagent-core/test/utils/faber.js +++ b/agents/node/vcxagent-core/test/utils/faber.js @@ -8,7 +8,7 @@ const { getAliceSchemaAttrs, getFaberCredDefName } = require('./data') const sleep = require('sleep-promise') const assert = require('assert') -module.exports.createFaber = async function createFaber (serviceEndpoint = 'http://localhost:5400') { +module.exports.createFaber = async function createFaber(serviceEndpoint = 'http://localhost:5400') { const agentName = `faber-${Math.floor(new Date() / 1000)}` const connectionId = 'connection-faber-to-alice' const issuerCredId = 'credential-for-alice' @@ -34,7 +34,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentInitVcx() await vcxAgent.agentShutdownVcx() - async function createInvite () { + async function createInvite() { logger.info('Faber is going to generate invite') await vcxAgent.agentInitVcx() @@ -48,7 +48,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return invite } - async function createPublicInvite () { + async function createPublicInvite() { logger.info('Faber is going to generate public invite') await vcxAgent.agentInitVcx() @@ -62,7 +62,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return publicInvitation } - async function publishService (endpoint) { + async function publishService(endpoint) { logger.info('Faber is going to write nonmediated service on the ledger') await vcxAgent.agentInitVcx() @@ -76,7 +76,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return pwInfo } - async function readServiceFromLedger () { + async function readServiceFromLedger() { logger.info('Faber is going to read service from the ledger') await vcxAgent.agentInitVcx() @@ -87,7 +87,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return service } - async function unpackMsg (encryptedMsg) { + async function unpackMsg(encryptedMsg) { assert(encryptedMsg) logger.info(`Faber is going to unpack message of length ${encryptedMsg.length}`) await vcxAgent.agentInitVcx() @@ -100,7 +100,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return { message, senderVerkey } } - async function createOobMessageWithDid (wrappedMessage) { + async function createOobMessageWithDid(wrappedMessage) { logger.info('Faber is going to generate out of band message') await vcxAgent.agentInitVcx() @@ -112,7 +112,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return oobMsg } - async function createOobCredOffer () { + async function createOobCredOffer() { await vcxAgent.agentInitVcx() const schemaAttrs = getAliceSchemaAttrs() const credOfferMsg = await vcxAgent.serviceCredIssuer.buildOfferAndMarkAsSent(issuerCredId, credDefId, revRegId, schemaAttrs) @@ -120,11 +120,11 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return await createOobMessageWithDid(credOfferMsg) } - function getFaberDid () { + function getFaberDid() { return vcxAgent.getInstitutionDid() } - async function createOobProofRequest (proofData) { + async function createOobProofRequest(proofData) { await vcxAgent.agentInitVcx() // todo: address @@ -135,7 +135,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return await createOobMessageWithDid(presentationRequestMsg) } - async function sendConnectionResponse () { + async function sendConnectionResponse() { logger.info('Faber is going to generate invite') await vcxAgent.agentInitVcx() @@ -144,7 +144,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function updateConnection (expectedNextState) { + async function updateConnection(expectedNextState) { logger.info(`Faber is going to update connection, expecting new state of ${expectedNextState}`) await vcxAgent.agentInitVcx() @@ -153,7 +153,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function handleMessage (ariesMsg) { + async function handleMessage(ariesMsg) { logger.info('Faber is going to try handle incoming messages') await vcxAgent.agentInitVcx() @@ -162,16 +162,18 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function buildLedgerPrimitives (revocationDetails) { + async function buildLedgerPrimitives(revocationDetails) { await vcxAgent.agentInitVcx() logger.info('Faber writing schema on ledger') - const schemaId = await vcxAgent.serviceLedgerSchema.createSchema(getSampleSchemaData()) + const issuerDid = vcxAgent.getInstitutionDid() + const schemaId = await vcxAgent.serviceLedgerSchema.createSchema(getSampleSchemaData(), issuerDid) await sleep(500) logger.info('Faber writing credential definition on ledger') const supportRevocation = !!revocationDetails await vcxAgent.serviceLedgerCredDef.createCredentialDefinitionV2( + issuerDid, schemaId, getFaberCredDefName(), supportRevocation @@ -186,7 +188,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function rotateRevReg (tailsDir, maxCreds) { + async function rotateRevReg(tailsDir, maxCreds) { await vcxAgent.agentInitVcx() logger.info('Faber rotating revocation registry') @@ -197,7 +199,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function sendCredentialOffer () { + async function sendCredentialOffer() { await vcxAgent.agentInitVcx() logger.info('Issuer sending credential offer') @@ -207,7 +209,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function updateStateCredential (expectedState) { + async function updateStateCredential(expectedState) { await vcxAgent.agentInitVcx() logger.info('Issuer updating state of credential with connection') @@ -216,7 +218,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function sendCredential () { + async function sendCredential() { await vcxAgent.agentInitVcx() logger.info('Issuer sending credential') @@ -227,14 +229,15 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function revokeCredential () { + async function revokeCredential() { await vcxAgent.agentInitVcx() await vcxAgent.serviceCredIssuer.revokeCredentialLocal(issuerCredId) - await vcxAgent.serviceLedgerRevReg.publishRevocations(revRegId) + const issuerDid = vcxAgent.getInstitutionDid() + await vcxAgent.serviceLedgerRevReg.publishRevocations(revRegId, issuerDid) await vcxAgent.agentShutdownVcx() } - async function receiveCredentialAck () { + async function receiveCredentialAck() { await vcxAgent.agentInitVcx() logger.info('Issuer waiting for credential ack') @@ -244,7 +247,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function requestProofFromAlice (proofData) { + async function requestProofFromAlice(proofData) { logger.info('Faber going to request proof from Alice') await vcxAgent.agentInitVcx() logger.info(`Faber is creating proof ${proofId}`) @@ -256,7 +259,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return proofRequestMessage } - async function updateStateVerifierProof (expectedNextState) { + async function updateStateVerifierProof(expectedNextState) { logger.info(`Verifier updating state of proof, expecting it to be in state ${expectedNextState}`) await vcxAgent.agentInitVcx() @@ -265,7 +268,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function verifySignature (dataBase64, signatureBase64) { + async function verifySignature(dataBase64, signatureBase64) { logger.debug(`Faber is going to verify signed data. Data=${dataBase64} signature=${signatureBase64}`) await vcxAgent.agentInitVcx() @@ -275,7 +278,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return isValid } - async function downloadReceivedMessages () { + async function downloadReceivedMessages() { logger.info('Faber is going to download messages using getMessages') await vcxAgent.agentInitVcx() const agencyMessages = await vcxAgent.serviceConnections.getMessages(connectionId, ['MS-103']) @@ -283,7 +286,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return agencyMessages } - async function createNonmediatedConnectionWithInvite () { + async function createNonmediatedConnectionWithInvite() { logger.info('Faber is going to create a connection with invite') await vcxAgent.agentInitVcx() @@ -294,7 +297,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return invite } - async function nonmediatedConnectionProcessRequest (request) { + async function nonmediatedConnectionProcessRequest(request) { logger.info('Faber is going to process a connection request') await vcxAgent.agentInitVcx() @@ -305,7 +308,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function createNonmediatedConnectionFromRequest (request, pwInfo) { + async function createNonmediatedConnectionFromRequest(request, pwInfo) { logger.info(`Faber is going to create a connection from a request: ${request}`) await vcxAgent.agentInitVcx() @@ -315,7 +318,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function nonmediatedConnectionProcessAck (ack) { + async function nonmediatedConnectionProcessAck(ack) { logger.info(`Faber is processing ack: ${ack}`) await vcxAgent.agentInitVcx() @@ -325,7 +328,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function createConnectionFromReceivedRequestV2 (pwInfo, request) { + async function createConnectionFromReceivedRequestV2(pwInfo, request) { logger.info(`Faber is going to create a connection from a request: ${request}, using pwInfo: ${JSON.stringify(pwInfo)}`) await vcxAgent.agentInitVcx() @@ -335,19 +338,19 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function updateMessageStatus (uids) { + async function updateMessageStatus(uids) { await vcxAgent.agentInitVcx() await vcxAgent.serviceConnections.updateMessagesStatus(connectionId, uids) await vcxAgent.agentShutdownVcx() } - async function updateAllReceivedMessages () { + async function updateAllReceivedMessages() { await vcxAgent.agentInitVcx() await vcxAgent.serviceConnections.updateAllReceivedMessages(connectionId) await vcxAgent.agentShutdownVcx() } - async function downloadReceivedMessagesV2 () { + async function downloadReceivedMessagesV2() { logger.info('Faber is going to download messages using getMessagesV2') await vcxAgent.agentInitVcx() const agencyMessages = await vcxAgent.serviceConnections.getMessagesV2(connectionId, ['MS-103']) @@ -355,7 +358,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return agencyMessages } - async function getCredentialRevRegId () { + async function getCredentialRevRegId() { logger.info(`Faber is going to obtain rev reg id for cred id ${issuerCredId}`) await vcxAgent.agentInitVcx() const revRegId = await vcxAgent.serviceCredIssuer.getRevRegId(issuerCredId) @@ -364,7 +367,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return revRegId } - async function getTailsFile () { + async function getTailsFile() { logger.info(`Faber is going to obtain tails file for rev reg id ${revRegId}`) await vcxAgent.agentInitVcx() const tailsFile = await vcxAgent.serviceLedgerCredDef.getTailsFile(issuerCredId) @@ -373,7 +376,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return tailsFile } - async function getTailsHash () { + async function getTailsHash() { logger.info(`Faber is going to obtain tails hash for rev reg id ${revRegId}`) await vcxAgent.agentInitVcx() const tailsHash = await vcxAgent.serviceLedgerRevReg.getTailsHash(revRegId) @@ -382,14 +385,14 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return tailsHash } - async function sendMessage (message) { + async function sendMessage(message) { logger.info('Faber is going to send message') await vcxAgent.agentInitVcx() await vcxAgent.serviceConnections.sendMessage(connectionId, message) await vcxAgent.agentShutdownVcx() } - async function nonmediatedConnectionSendMessage (message) { + async function nonmediatedConnectionSendMessage(message) { logger.info('Faber is going to send message') await vcxAgent.agentInitVcx() @@ -398,7 +401,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function getPresentationInfo () { + async function getPresentationInfo() { logger.info('Faber is gather info about received presentation') await vcxAgent.agentInitVcx() const presentationMsg = await vcxAgent.serviceVerifier.getPresentationMsg(proofId) diff --git a/agents/rust/aries-vcx-agent/src/agent/init.rs b/agents/rust/aries-vcx-agent/src/agent/init.rs index 1319c6d19e..b7bc4af9c1 100644 --- a/agents/rust/aries-vcx-agent/src/agent/init.rs +++ b/agents/rust/aries-vcx-agent/src/agent/init.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{ledger::VcxPoolConfig, profile::Profile, vdrtools_profile::VdrtoolsProfile}, - global::settings::{init_issuer_config, DEFAULT_LINK_SECRET_ALIAS}, + core::profile::{ledger::VcxPoolConfig, vdrtools_profile::VdrtoolsProfile, Profile}, + global::settings::DEFAULT_LINK_SECRET_ALIAS, }; use aries_vcx_core::{ self, @@ -63,7 +63,7 @@ impl Agent { let config_issuer = wallet_configure_issuer(wallet_handle, &init_config.enterprise_seed) .await .unwrap(); - init_issuer_config(&config_issuer.institution_did).unwrap(); + let wallet = Arc::new(IndySdkWallet::new(wallet_handle)); let pool_config = VcxPoolConfig { diff --git a/agents/rust/aries-vcx-agent/src/services/connection.rs b/agents/rust/aries-vcx-agent/src/services/connection.rs index 91ede5f8e4..a50252b2d8 100644 --- a/agents/rust/aries-vcx-agent/src/services/connection.rs +++ b/agents/rust/aries-vcx-agent/src/services/connection.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, handlers::util::AnyInvitation, messages::msg_fields::protocols::{ connection::{request::Request, response::Response}, diff --git a/agents/rust/aries-vcx-agent/src/services/credential_definition.rs b/agents/rust/aries-vcx-agent/src/services/credential_definition.rs index 46afff8d6a..bb56ef3a8f 100644 --- a/agents/rust/aries-vcx-agent/src/services/credential_definition.rs +++ b/agents/rust/aries-vcx-agent/src/services/credential_definition.rs @@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ common::primitives::credential_definition::{CredentialDef, CredentialDefConfig}, - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, }; use crate::{ diff --git a/agents/rust/aries-vcx-agent/src/services/holder.rs b/agents/rust/aries-vcx-agent/src/services/holder.rs index 49cf0d95ed..cf3ce72c27 100644 --- a/agents/rust/aries-vcx-agent/src/services/holder.rs +++ b/agents/rust/aries-vcx-agent/src/services/holder.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, handlers::issuance::holder::Holder, messages::{ msg_fields::protocols::cred_issuance::v1::{ diff --git a/agents/rust/aries-vcx-agent/src/services/issuer.rs b/agents/rust/aries-vcx-agent/src/services/issuer.rs index ef3b27473b..ab2088eeb9 100644 --- a/agents/rust/aries-vcx-agent/src/services/issuer.rs +++ b/agents/rust/aries-vcx-agent/src/services/issuer.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, handlers::{issuance::issuer::Issuer, util::OfferInfo}, messages::{ msg_fields::protocols::cred_issuance::v1::{ diff --git a/agents/rust/aries-vcx-agent/src/services/prover.rs b/agents/rust/aries-vcx-agent/src/services/prover.rs index fad50a47be..7fc9cc7e1d 100644 --- a/agents/rust/aries-vcx-agent/src/services/prover.rs +++ b/agents/rust/aries-vcx-agent/src/services/prover.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, sync::Arc}; use aries_vcx::{ - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, handlers::{ proof_presentation::{prover::Prover, types::SelectedCredentials}, util::PresentationProposalData, diff --git a/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs b/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs index d8802bf524..55f5017267 100644 --- a/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs +++ b/agents/rust/aries-vcx-agent/src/services/revocation_registry.rs @@ -5,7 +5,7 @@ use std::{ use aries_vcx::{ common::primitives::revocation_registry::RevocationRegistry, - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, }; use crate::{ diff --git a/agents/rust/aries-vcx-agent/src/services/schema.rs b/agents/rust/aries-vcx-agent/src/services/schema.rs index 402d934c21..e28c77a2ec 100644 --- a/agents/rust/aries-vcx-agent/src/services/schema.rs +++ b/agents/rust/aries-vcx-agent/src/services/schema.rs @@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ common::primitives::credential_schema::Schema, - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, }; use aries_vcx_core::ledger::base_ledger::AnoncredsLedgerRead; diff --git a/agents/rust/aries-vcx-agent/src/services/verifier.rs b/agents/rust/aries-vcx-agent/src/services/verifier.rs index c1b5779e2e..d8a252c1a4 100644 --- a/agents/rust/aries-vcx-agent/src/services/verifier.rs +++ b/agents/rust/aries-vcx-agent/src/services/verifier.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use aries_vcx::{ common::proofs::proof_request::PresentationRequestData, - core::profile::{profile::Profile, vdrtools_profile::VdrtoolsProfile}, + core::profile::{vdrtools_profile::VdrtoolsProfile, Profile}, handlers::proof_presentation::verifier::Verifier, messages::{ msg_fields::protocols::present_proof::{ diff --git a/aries_vcx/src/common/anoncreds.rs b/aries_vcx/src/common/anoncreds.rs index 265774083e..8dc06ea9d0 100644 --- a/aries_vcx/src/common/anoncreds.rs +++ b/aries_vcx/src/common/anoncreds.rs @@ -7,15 +7,12 @@ pub mod integration_tests { ledger::{base_ledger::AnoncredsLedgerRead, indy::pool::test_utils::get_temp_dir_path}, }; - use crate::{ - common::{ - credentials::get_cred_rev_id, - test_utils::{ - create_and_publish_test_rev_reg, create_and_write_credential, - create_and_write_test_cred_def, create_and_write_test_schema, - }, + use crate::common::{ + credentials::get_cred_rev_id, + test_utils::{ + create_and_publish_test_rev_reg, create_and_write_credential, + create_and_write_test_cred_def, create_and_write_test_schema, }, - utils::devsetup::SetupProfile, }; #[tokio::test] diff --git a/aries_vcx/src/common/credentials/mod.rs b/aries_vcx/src/common/credentials/mod.rs index 89a987b08a..7f734580c7 100644 --- a/aries_vcx/src/common/credentials/mod.rs +++ b/aries_vcx/src/common/credentials/mod.rs @@ -52,12 +52,9 @@ pub async fn is_cred_revoked( #[allow(clippy::unwrap_used)] mod integration_tests { use super::*; - use crate::{ - common::test_utils::{ - create_and_publish_test_rev_reg, create_and_write_credential, - create_and_write_test_cred_def, create_and_write_test_schema, - }, - utils::devsetup::SetupProfile, + use crate::common::test_utils::{ + create_and_publish_test_rev_reg, create_and_write_credential, + create_and_write_test_cred_def, create_and_write_test_schema, }; #[tokio::test] diff --git a/aries_vcx/src/common/ledger/transactions.rs b/aries_vcx/src/common/ledger/transactions.rs index 2adc71f7e1..3f34c8723c 100644 --- a/aries_vcx/src/common/ledger/transactions.rs +++ b/aries_vcx/src/common/ledger/transactions.rs @@ -18,7 +18,6 @@ use serde_json::Value; use crate::{ common::{keys::get_verkey_from_ledger, ledger::service_didsov::EndpointDidSov}, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - global::settings, handlers::util::AnyInvitation, }; @@ -361,9 +360,6 @@ pub async fn clear_attr( } fn check_response(response: &str) -> VcxResult<()> { - if settings::indy_mocks_enabled() { - return Ok(()); - } match parse_response(response)? { Response::Reply(_) => Ok(()), Response::Reject(res) | Response::ReqNACK(res) => Err(AriesVcxError::from_msg( diff --git a/aries_vcx/src/common/primitives/credential_definition.rs b/aries_vcx/src/common/primitives/credential_definition.rs index 2575ab80b8..e2a3fb26a7 100644 --- a/aries_vcx/src/common/primitives/credential_definition.rs +++ b/aries_vcx/src/common/primitives/credential_definition.rs @@ -8,11 +8,7 @@ use aries_vcx_core::{ use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - global::settings::indy_mocks_enabled, - utils::{ - constants::{CRED_DEF_ID, CRED_DEF_JSON, DEFAULT_SERIALIZE_VERSION}, - serialization::ObjectWithVersion, - }, + utils::{constants::DEFAULT_SERIALIZE_VERSION, serialization::ObjectWithVersion}, }; #[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Default)] @@ -85,9 +81,6 @@ async fn _try_get_cred_def_from_ledger( issuer_did: &str, cred_def_id: &str, ) -> VcxResult> { - if indy_mocks_enabled() { - return Ok(None); - } match ledger.get_cred_def(cred_def_id, Some(issuer_did)).await { Ok(cred_def) => Ok(Some(cred_def)), Err(err) if err.kind() == AriesVcxCoreErrorKind::LedgerItemNotFound => Ok(None), @@ -255,9 +248,6 @@ pub async fn generate_cred_def( sig_type, support_revocation ); - if indy_mocks_enabled() { - return Ok((CRED_DEF_ID.to_string(), CRED_DEF_JSON.to_string())); - } let config_json = json!({"support_revocation": support_revocation.unwrap_or(false)}).to_string(); @@ -289,7 +279,7 @@ pub mod integration_tests { }, test_utils::create_and_write_test_schema, }, - utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::SetupProfile}, + utils::constants::DEFAULT_SCHEMA_ATTRS, }; #[tokio::test] diff --git a/aries_vcx/src/common/primitives/credential_schema.rs b/aries_vcx/src/common/primitives/credential_schema.rs index adf15f9563..2c13416dc8 100644 --- a/aries_vcx/src/common/primitives/credential_schema.rs +++ b/aries_vcx/src/common/primitives/credential_schema.rs @@ -8,11 +8,7 @@ use aries_vcx_core::{ use super::credential_definition::PublicEntityStateType; use crate::{ errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - global::settings, - utils::{ - constants::{DEFAULT_SERIALIZE_VERSION, SCHEMA_ID, SCHEMA_JSON}, - serialization::ObjectWithVersion, - }, + utils::{constants::DEFAULT_SERIALIZE_VERSION, serialization::ObjectWithVersion}, }; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] @@ -55,19 +51,6 @@ impl Schema { data ); - if settings::indy_mocks_enabled() { - return Ok(Self { - source_id: source_id.to_string(), - version: version.to_string(), - submitter_did: submitter_did.to_string(), - schema_id: SCHEMA_ID.to_string(), - schema_json: SCHEMA_JSON.to_string(), - name: name.to_string(), - state: PublicEntityStateType::Built, - ..Self::default() - }); - } - let data_str = serde_json::to_string(data).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::SerializationError, @@ -98,13 +81,6 @@ impl Schema { pub async fn publish(self, ledger: &impl AnoncredsLedgerWrite) -> VcxResult { trace!("Schema::publish >>>"); - if settings::indy_mocks_enabled() { - return Ok(Self { - state: PublicEntityStateType::Published, - ..self - }); - } - ledger .publish_schema(&self.schema_json, &self.submitter_did, None) .await?; diff --git a/aries_vcx/src/common/primitives/revocation_registry.rs b/aries_vcx/src/common/primitives/revocation_registry.rs index 3189fe58a5..fa6321babf 100644 --- a/aries_vcx/src/common/primitives/revocation_registry.rs +++ b/aries_vcx/src/common/primitives/revocation_registry.rs @@ -4,11 +4,7 @@ use aries_vcx_core::{ }; use super::credential_definition::PublicEntityStateType; -use crate::{ - errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - global::settings, - utils::constants::REV_REG_ID, -}; +use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; #[derive(Clone, Deserialize, Debug, Serialize, PartialEq, Eq)] pub struct RevocationRegistry { @@ -302,14 +298,6 @@ pub async fn generate_rev_reg( max_creds, tag ); - if settings::indy_mocks_enabled() { - debug!("generate_rev_reg >>> returning mocked value"); - return Ok(( - REV_REG_ID.to_string(), - RevocationRegistryDefinition::default(), - "".to_string(), - )); - } let (rev_reg_id, rev_reg_def_json, rev_reg_entry_json) = anoncreds .issuer_create_and_store_revoc_reg(issuer_did, cred_def_id, tails_dir, max_creds, tag) diff --git a/aries_vcx/src/common/proofs/prover/mod.rs b/aries_vcx/src/common/proofs/prover/mod.rs index e09cafae7a..0f364f3afe 100644 --- a/aries_vcx/src/common/proofs/prover/mod.rs +++ b/aries_vcx/src/common/proofs/prover/mod.rs @@ -1,2 +1,76 @@ -pub mod prover; mod prover_internal; + +use std::collections::HashMap; + +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, +}; + +use crate::{ + common::proofs::{ + proof_request::ProofRequestData, + prover::prover_internal::{ + build_cred_defs_json_prover, build_requested_credentials_json, build_rev_states_json, + build_schemas_json_prover, credential_def_identifiers, + }, + }, + errors::error::prelude::*, + global::settings, + handlers::proof_presentation::types::SelectedCredentials, + utils::mockdata::mock_settings::get_mock_generate_indy_proof, +}; + +pub async fn generate_indy_proof( + ledger: &impl AnoncredsLedgerRead, + anoncreds: &impl BaseAnonCreds, + credentials: &SelectedCredentials, + self_attested_attrs: &HashMap, + proof_req_data_json: &str, +) -> VcxResult { + trace!( + "generate_indy_proof >>> credentials: {:?}, self_attested_attrs: {:?}", + secret!(&credentials), + secret!(&self_attested_attrs) + ); + + match get_mock_generate_indy_proof() { + None => {} + Some(mocked_indy_proof) => { + warn!("generate_indy_proof :: returning mocked response"); + return Ok(mocked_indy_proof); + } + } + let proof_request: ProofRequestData = + serde_json::from_str(proof_req_data_json).map_err(|err| { + AriesVcxError::from_msg( + AriesVcxErrorKind::InvalidJson, + format!("Cannot deserialize proof request: {}", err), + ) + })?; + + let mut credentials_identifiers = credential_def_identifiers(credentials, &proof_request)?; + + let revoc_states_json = + build_rev_states_json(ledger, anoncreds, &mut credentials_identifiers).await?; + let requested_credentials = build_requested_credentials_json( + &credentials_identifiers, + self_attested_attrs, + &proof_request, + )?; + + let schemas_json = build_schemas_json_prover(ledger, &credentials_identifiers).await?; + let credential_defs_json = + build_cred_defs_json_prover(ledger, &credentials_identifiers).await?; + + let proof = anoncreds + .prover_create_proof( + proof_req_data_json, + &requested_credentials, + settings::DEFAULT_LINK_SECRET_ALIAS, + &schemas_json, + &credential_defs_json, + Some(&revoc_states_json), + ) + .await?; + Ok(proof) +} diff --git a/aries_vcx/src/common/proofs/prover/prover.rs b/aries_vcx/src/common/proofs/prover/prover.rs deleted file mode 100644 index f2ecff96b9..0000000000 --- a/aries_vcx/src/common/proofs/prover/prover.rs +++ /dev/null @@ -1,74 +0,0 @@ -use std::collections::HashMap; - -use aries_vcx_core::{ - anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, -}; - -use crate::{ - common::proofs::{ - proof_request::ProofRequestData, - prover::prover_internal::{ - build_cred_defs_json_prover, build_requested_credentials_json, build_rev_states_json, - build_schemas_json_prover, credential_def_identifiers, - }, - }, - errors::error::prelude::*, - global::settings, - handlers::proof_presentation::types::SelectedCredentials, - utils::mockdata::mock_settings::get_mock_generate_indy_proof, -}; - -pub async fn generate_indy_proof( - ledger: &impl AnoncredsLedgerRead, - anoncreds: &impl BaseAnonCreds, - credentials: &SelectedCredentials, - self_attested_attrs: &HashMap, - proof_req_data_json: &str, -) -> VcxResult { - trace!( - "generate_indy_proof >>> credentials: {:?}, self_attested_attrs: {:?}", - secret!(&credentials), - secret!(&self_attested_attrs) - ); - - match get_mock_generate_indy_proof() { - None => {} - Some(mocked_indy_proof) => { - warn!("generate_indy_proof :: returning mocked response"); - return Ok(mocked_indy_proof); - } - } - let proof_request: ProofRequestData = - serde_json::from_str(proof_req_data_json).map_err(|err| { - AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidJson, - format!("Cannot deserialize proof request: {}", err), - ) - })?; - - let mut credentials_identifiers = credential_def_identifiers(credentials, &proof_request)?; - - let revoc_states_json = - build_rev_states_json(ledger, anoncreds, &mut credentials_identifiers).await?; - let requested_credentials = build_requested_credentials_json( - &credentials_identifiers, - self_attested_attrs, - &proof_request, - )?; - - let schemas_json = build_schemas_json_prover(ledger, &credentials_identifiers).await?; - let credential_defs_json = - build_cred_defs_json_prover(ledger, &credentials_identifiers).await?; - - let proof = anoncreds - .prover_create_proof( - proof_req_data_json, - &requested_credentials, - settings::DEFAULT_LINK_SECRET_ALIAS, - &schemas_json, - &credential_defs_json, - Some(&revoc_states_json), - ) - .await?; - Ok(proof) -} diff --git a/aries_vcx/src/common/proofs/prover/prover_internal.rs b/aries_vcx/src/common/proofs/prover/prover_internal.rs index feef43d180..733c64d12a 100644 --- a/aries_vcx/src/common/proofs/prover/prover_internal.rs +++ b/aries_vcx/src/common/proofs/prover/prover_internal.rs @@ -281,10 +281,7 @@ pub mod pool_tests { use crate::{ common::proofs::prover::prover_internal::{build_rev_states_json, CredInfoProver}, - utils::{ - constants::{CRED_DEF_ID, CRED_REV_ID, LICENCE_CRED_ID, SCHEMA_ID}, - devsetup::SetupProfile, - }, + utils::constants::{CRED_DEF_ID, CRED_REV_ID, LICENCE_CRED_ID, SCHEMA_ID}, }; #[tokio::test] diff --git a/aries_vcx/src/common/proofs/verifier/mod.rs b/aries_vcx/src/common/proofs/verifier/mod.rs index 6ce73fb9af..ed0ec3e4c7 100644 --- a/aries_vcx/src/common/proofs/verifier/mod.rs +++ b/aries_vcx/src/common/proofs/verifier/mod.rs @@ -1,2 +1,645 @@ -pub mod verifier; mod verifier_internal; + +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, +}; + +use crate::{ + common::proofs::verifier::verifier_internal::{ + build_cred_defs_json_verifier, build_rev_reg_defs_json, build_rev_reg_json, + build_schemas_json_verifier, get_credential_info, validate_proof_revealed_attributes, + }, + errors::error::prelude::*, + utils::mockdata::mock_settings::get_mock_result_for_validate_indy_proof, +}; + +pub async fn validate_indy_proof( + ledger: &impl AnoncredsLedgerRead, + anoncreds: &impl BaseAnonCreds, + proof_json: &str, + proof_req_json: &str, +) -> VcxResult { + if let Some(mock_result) = get_mock_result_for_validate_indy_proof() { + return mock_result; + } + validate_proof_revealed_attributes(proof_json)?; + + let credential_data = get_credential_info(proof_json)?; + debug!("validate_indy_proof >> credential_data: {credential_data:?}"); + let credential_defs_json = build_cred_defs_json_verifier(ledger, &credential_data).await?; + let schemas_json = build_schemas_json_verifier(ledger, &credential_data).await?; + let rev_reg_defs_json = build_rev_reg_defs_json(ledger, &credential_data) + .await + .unwrap_or(json!({}).to_string()); + let rev_regs_json = build_rev_reg_json(ledger, &credential_data) + .await + .unwrap_or(json!({}).to_string()); + + debug!("validate_indy_proof >> credential_defs_json: {credential_defs_json}"); + debug!("validate_indy_proof >> schemas_json: {schemas_json}"); + trace!("validate_indy_proof >> proof_json: {proof_json}"); + debug!("validate_indy_proof >> proof_req_json: {proof_req_json}"); + debug!("validate_indy_proof >> rev_reg_defs_json: {rev_reg_defs_json}"); + debug!("validate_indy_proof >> rev_regs_json: {rev_regs_json}"); + anoncreds + .verifier_verify_proof( + proof_req_json, + proof_json, + &schemas_json, + &credential_defs_json, + &rev_reg_defs_json, + &rev_regs_json, + ) + .await + .map_err(|err| err.into()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +pub mod integration_tests { + use std::time::Duration; + + use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, + }; + + use super::*; + use crate::{ + common::{ + primitives::{credential_definition::CredentialDef, credential_schema::Schema}, + proofs::proof_request::ProofRequestData, + test_utils::{ + create_and_write_credential, create_and_write_test_cred_def, + create_and_write_test_schema, + }, + }, + errors::error::AriesVcxErrorKind, + utils::{self, constants::DEFAULT_SCHEMA_ATTRS}, + }; + + // FUTURE - issuer and holder seperation only needed whilst modular deps not fully implemented + async fn create_indy_proof( + anoncreds_issuer: &impl BaseAnonCreds, + anoncreds_holder: &impl BaseAnonCreds, + ledger_read: &impl AnoncredsLedgerRead, + ledger_write: &impl AnoncredsLedgerWrite, + did: &str, + ) -> (String, String, String, String) { + let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + anoncreds_issuer, + anoncreds_holder, + ledger_read, + ledger_write, + did, + DEFAULT_SCHEMA_ATTRS, + ) + .await; + let proof_req = json!({ + "nonce":"123432421212", + "name":"proof_req_1", + "version":"0.1", + "requested_attributes": json!({ + "address1_1": json!({ + "name":"address1", + "restrictions": [json!({ "issuer_did": did })] + }), + "zip_2": json!({ + "name":"zip", + "restrictions": [json!({ "issuer_did": did })] + }), + "self_attest_3": json!({ + "name":"self_attest", + }), + }), + "requested_predicates": json!({}), + }) + .to_string(); + let requested_credentials_json = json!({ + "self_attested_attributes":{ + "self_attest_3": "my_self_attested_val" + }, + "requested_attributes":{ + "address1_1": {"cred_id": cred_id, "revealed": true}, + "zip_2": {"cred_id": cred_id, "revealed": true} + }, + "requested_predicates":{} + }) + .to_string(); + + let schema_id = schema.schema_id.clone(); + let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); + let schemas = json!({ + schema_id: schema_json, + }) + .to_string(); + + let cred_def_json: serde_json::Value = + serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); + let cred_defs = json!({ + cred_def.get_cred_def_id(): cred_def_json, + }) + .to_string(); + + anoncreds_holder + .prover_get_credentials_for_proof_req(&proof_req) + .await + .unwrap(); + + let proof = anoncreds_holder + .prover_create_proof( + &proof_req, + &requested_credentials_json, + "main", + &schemas, + &cred_defs, + None, + ) + .await + .unwrap(); + (schemas, cred_defs, proof_req, proof) + } + + async fn create_proof_with_predicate( + anoncreds_issuer: &impl BaseAnonCreds, + anoncreds_holder: &impl BaseAnonCreds, + ledger_read: &impl AnoncredsLedgerRead, + ledger_write: &impl AnoncredsLedgerWrite, + did: &str, + include_predicate_cred: bool, + ) -> (String, String, String, String) { + let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + anoncreds_issuer, + anoncreds_holder, + ledger_read, + ledger_write, + did, + DEFAULT_SCHEMA_ATTRS, + ) + .await; + + let proof_req = json!({ + "nonce":"123432421212", + "name":"proof_req_1", + "version":"0.1", + "requested_attributes": json!({ + "address1_1": json!({ + "name":"address1", + "restrictions": [json!({ "issuer_did": did })] + }), + "self_attest_3": json!({ + "name":"self_attest", + }), + }), + "requested_predicates": json!({ + "zip_3": {"name":"zip", "p_type":">=", "p_value":18} + }), + }) + .to_string(); + + let requested_credentials_json = if include_predicate_cred { + json!({ + "self_attested_attributes":{ + "self_attest_3": "my_self_attested_val" + }, + "requested_attributes":{ + "address1_1": {"cred_id": cred_id, "revealed": true} + }, + "requested_predicates":{ + "zip_3": {"cred_id": cred_id} + } + }) + .to_string() + } else { + json!({ + "self_attested_attributes":{ + "self_attest_3": "my_self_attested_val" + }, + "requested_attributes":{ + "address1_1": {"cred_id": cred_id, "revealed": true} + }, + "requested_predicates":{ + } + }) + .to_string() + }; + + let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); + let schemas = json!({ + schema.schema_id: schema_json, + }) + .to_string(); + + let cred_def_json: serde_json::Value = + serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); + let cred_defs = json!({ + cred_def.get_cred_def_id(): cred_def_json, + }) + .to_string(); + + anoncreds_holder + .prover_get_credentials_for_proof_req(&proof_req) + .await + .unwrap(); + + let proof = anoncreds_holder + .prover_create_proof( + &proof_req, + &requested_credentials_json, + "main", + &schemas, + &cred_defs, + None, + ) + .await + .unwrap(); + (schemas, cred_defs, proof_req, proof) + } + + async fn create_and_store_nonrevocable_credential( + anoncreds_issuer: &impl BaseAnonCreds, + anoncreds_holder: &impl BaseAnonCreds, + ledger_read: &impl AnoncredsLedgerRead, + ledger_write: &impl AnoncredsLedgerWrite, + issuer_did: &str, + attr_list: &str, + ) -> (Schema, CredentialDef, String) { + let schema = + create_and_write_test_schema(anoncreds_issuer, ledger_write, issuer_did, attr_list) + .await; + + let cred_def = create_and_write_test_cred_def( + anoncreds_issuer, + ledger_read, + ledger_write, + issuer_did, + &schema.schema_id, + false, + ) + .await; + tokio::time::sleep(Duration::from_millis(500)).await; + + let cred_id = create_and_write_credential( + anoncreds_issuer, + anoncreds_holder, + issuer_did, + &cred_def, + None, + ) + .await; + (schema, cred_def, cred_id) + } + + #[tokio::test] + #[ignore] + async fn test_pool_proof_self_attested_proof_validation() { + run_setup!(|setup| async move { + let requested_attrs = json!([ + json!({ + "name":"address1", + "self_attest_allowed": true, + }), + json!({ + "name":"zip", + "self_attest_allowed": true, + }), + ]) + .to_string(); + let requested_predicates = json!([]).to_string(); + let revocation_details = r#"{"support_revocation":false}"#.to_string(); + let name = "Optional".to_owned(); + + let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + .await + .unwrap() + .set_requested_attributes_as_string(requested_attrs) + .unwrap() + .set_requested_predicates_as_string(requested_predicates) + .unwrap() + .set_not_revoked_interval(revocation_details) + .unwrap(); + + let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); + + let anoncreds = setup.profile.anoncreds(); + let prover_proof_json = anoncreds + .prover_create_proof( + &proof_req_json, + &json!({ + "self_attested_attributes":{ + "attribute_0": "my_self_attested_address", + "attribute_1": "my_self_attested_zip" + }, + "requested_attributes":{}, + "requested_predicates":{} + }) + .to_string(), + "main", + &json!({}).to_string(), + &json!({}).to_string(), + None, + ) + .await + .unwrap(); + + assert!(validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json + ) + .await + .unwrap()); + }) + .await; + } + + #[tokio::test] + #[ignore] + async fn test_pool_proof_restrictions() { + run_setup!(|setup| async move { + let requested_attrs = json!([ + json!({ + "name":"address1", + "restrictions": [{ "issuer_did": "Not Here" }], + }), + json!({ + "name":"zip", + }), + json!({ + "name":"self_attest", + "self_attest_allowed": true, + }), + ]) + .to_string(); + let requested_predicates = json!([]).to_string(); + let revocation_details = r#"{"support_revocation":true}"#.to_string(); + let name = "Optional".to_owned(); + + let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + .await + .unwrap() + .set_requested_attributes_as_string(requested_attrs) + .unwrap() + .set_requested_predicates_as_string(requested_predicates) + .unwrap() + .set_not_revoked_interval(revocation_details) + .unwrap(); + + let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); + + let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + setup.profile.anoncreds(), + setup.profile.anoncreds(), + setup.profile.ledger_read(), + setup.profile.ledger_write(), + &setup.institution_did, + utils::constants::DEFAULT_SCHEMA_ATTRS, + ) + .await; + let cred_def_json: serde_json::Value = + serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); + let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); + + let anoncreds = setup.profile.anoncreds(); + let prover_proof_json = anoncreds + .prover_create_proof( + &proof_req_json, + &json!({ + "self_attested_attributes":{ + "attribute_2": "my_self_attested_val" + }, + "requested_attributes":{ + "attribute_0": {"cred_id": cred_id, "revealed": true}, + "attribute_1": {"cred_id": cred_id, "revealed": true} + }, + "requested_predicates":{} + }) + .to_string(), + "main", + &json!({ schema.schema_id: schema_json }).to_string(), + &json!({ cred_def.get_cred_def_id(): cred_def_json }).to_string(), + None, + ) + .await + .unwrap(); + assert_eq!( + validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json + ) + .await + .unwrap_err() + .kind(), + AriesVcxErrorKind::ProofRejected + ); + + let mut proof_req_json: serde_json::Value = + serde_json::from_str(&proof_req_json).unwrap(); + proof_req_json["requested_attributes"]["attribute_0"]["restrictions"] = json!({}); + assert!(validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json.to_string() + ) + .await + .unwrap()); + }) + .await; + } + + #[tokio::test] + #[ignore] + async fn test_pool_proof_validate_attribute() { + run_setup!(|setup| async move { + let requested_attrs = json!([ + json!({ + "name":"address1", + "restrictions": [json!({ "issuer_did": setup.institution_did })] + }), + json!({ + "name":"zip", + "restrictions": [json!({ "issuer_did": setup.institution_did })] + }), + json!({ + "name":"self_attest", + "self_attest_allowed": true, + }), + ]) + .to_string(); + let requested_predicates = json!([]).to_string(); + let revocation_details = r#"{"support_revocation":true}"#.to_string(); + let name = "Optional".to_owned(); + + let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) + .await + .unwrap() + .set_requested_attributes_as_string(requested_attrs) + .unwrap() + .set_requested_predicates_as_string(requested_predicates) + .unwrap() + .set_not_revoked_interval(revocation_details) + .unwrap(); + + let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); + + let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( + setup.profile.anoncreds(), + setup.profile.anoncreds(), + setup.profile.ledger_read(), + setup.profile.ledger_write(), + &setup.institution_did, + utils::constants::DEFAULT_SCHEMA_ATTRS, + ) + .await; + let cred_def_json: serde_json::Value = + serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); + let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); + + let anoncreds = setup.profile.anoncreds(); + let prover_proof_json = anoncreds + .prover_create_proof( + &proof_req_json, + &json!({ + "self_attested_attributes":{ + "attribute_2": "my_self_attested_val" + }, + "requested_attributes":{ + "attribute_0": {"cred_id": cred_id, "revealed": true}, + "attribute_1": {"cred_id": cred_id, "revealed": true} + }, + "requested_predicates":{} + }) + .to_string(), + "main", + &json!({ schema.schema_id: schema_json }).to_string(), + &json!({ cred_def.get_cred_def_id(): cred_def_json }).to_string(), + None, + ) + .await + .unwrap(); + assert!(validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json + ) + .await + .unwrap()); + + let mut proof_obj: serde_json::Value = + serde_json::from_str(&prover_proof_json).unwrap(); + { + proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["raw"] = + json!("Other Value"); + let prover_proof_json = serde_json::to_string(&proof_obj).unwrap(); + + assert_eq!( + validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json + ) + .await + .unwrap_err() + .kind(), + AriesVcxErrorKind::InvalidProof + ); + } + { + proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["encoded"] = + json!("1111111111111111111111111111111111111111111111111111111111"); + let prover_proof_json = serde_json::to_string(&proof_obj).unwrap(); + + assert_eq!( + validate_indy_proof( + setup.profile.ledger_read(), + setup.profile.anoncreds(), + &prover_proof_json, + &proof_req_json + ) + .await + .unwrap_err() + .kind(), + AriesVcxErrorKind::InvalidProof + ); + } + }) + .await; + } + #[tokio::test] + #[ignore] + async fn test_pool_prover_verify_proof() { + run_setup!(|setup| async move { + let (schemas, cred_defs, proof_req, proof) = create_indy_proof( + setup.profile.anoncreds(), + setup.profile.anoncreds(), + setup.profile.ledger_read(), + setup.profile.ledger_write(), + &setup.institution_did, + ) + .await; + + let anoncreds = setup.profile.anoncreds(); + let proof_validation = anoncreds + .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") + .await + .unwrap(); + + assert!(proof_validation); + }) + .await; + } + + #[tokio::test] + #[ignore] + async fn test_pool_prover_verify_proof_with_predicate_success_case() { + run_setup!(|setup| async move { + let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( + setup.profile.anoncreds(), + setup.profile.anoncreds(), + setup.profile.ledger_read(), + setup.profile.ledger_write(), + &setup.institution_did, + true, + ) + .await; + + let anoncreds = setup.profile.anoncreds(); + let proof_validation = anoncreds + .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") + .await + .unwrap(); + + assert!(proof_validation); + }) + .await; + } + + #[tokio::test] + #[ignore] + async fn test_pool_prover_verify_proof_with_predicate_fail_case() { + run_setup!(|setup| async move { + let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( + setup.profile.anoncreds(), + setup.profile.anoncreds(), + setup.profile.ledger_read(), + setup.profile.ledger_write(), + &setup.institution_did, + false, + ) + .await; + + let anoncreds = setup.profile.anoncreds(); + anoncreds + .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") + .await + .unwrap_err(); + }) + .await; + } +} diff --git a/aries_vcx/src/common/proofs/verifier/verifier.rs b/aries_vcx/src/common/proofs/verifier/verifier.rs deleted file mode 100644 index 354e46d4d4..0000000000 --- a/aries_vcx/src/common/proofs/verifier/verifier.rs +++ /dev/null @@ -1,643 +0,0 @@ -use aries_vcx_core::{ - anoncreds::base_anoncreds::BaseAnonCreds, ledger::base_ledger::AnoncredsLedgerRead, -}; - -use crate::{ - common::proofs::verifier::verifier_internal::{ - build_cred_defs_json_verifier, build_rev_reg_defs_json, build_rev_reg_json, - build_schemas_json_verifier, get_credential_info, validate_proof_revealed_attributes, - }, - errors::error::prelude::*, - utils::mockdata::mock_settings::get_mock_result_for_validate_indy_proof, -}; - -pub async fn validate_indy_proof( - ledger: &impl AnoncredsLedgerRead, - anoncreds: &impl BaseAnonCreds, - proof_json: &str, - proof_req_json: &str, -) -> VcxResult { - if let Some(mock_result) = get_mock_result_for_validate_indy_proof() { - return mock_result; - } - validate_proof_revealed_attributes(proof_json)?; - - let credential_data = get_credential_info(proof_json)?; - debug!("validate_indy_proof >> credential_data: {credential_data:?}"); - let credential_defs_json = build_cred_defs_json_verifier(ledger, &credential_data).await?; - let schemas_json = build_schemas_json_verifier(ledger, &credential_data).await?; - let rev_reg_defs_json = build_rev_reg_defs_json(ledger, &credential_data) - .await - .unwrap_or(json!({}).to_string()); - let rev_regs_json = build_rev_reg_json(ledger, &credential_data) - .await - .unwrap_or(json!({}).to_string()); - - debug!("validate_indy_proof >> credential_defs_json: {credential_defs_json}"); - debug!("validate_indy_proof >> schemas_json: {schemas_json}"); - trace!("validate_indy_proof >> proof_json: {proof_json}"); - debug!("validate_indy_proof >> proof_req_json: {proof_req_json}"); - debug!("validate_indy_proof >> rev_reg_defs_json: {rev_reg_defs_json}"); - debug!("validate_indy_proof >> rev_regs_json: {rev_regs_json}"); - anoncreds - .verifier_verify_proof( - proof_req_json, - proof_json, - &schemas_json, - &credential_defs_json, - &rev_reg_defs_json, - &rev_regs_json, - ) - .await - .map_err(|err| err.into()) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -pub mod integration_tests { - use std::time::Duration; - - use aries_vcx_core::{ - anoncreds::base_anoncreds::BaseAnonCreds, - ledger::base_ledger::{AnoncredsLedgerRead, AnoncredsLedgerWrite}, - }; - - use super::*; - use crate::{ - common::{ - primitives::{credential_definition::CredentialDef, credential_schema::Schema}, - proofs::proof_request::ProofRequestData, - test_utils::{ - create_and_write_credential, create_and_write_test_cred_def, - create_and_write_test_schema, - }, - }, - errors::error::AriesVcxErrorKind, - utils::{self, constants::DEFAULT_SCHEMA_ATTRS, devsetup::SetupProfile}, - }; - - // FUTURE - issuer and holder seperation only needed whilst modular deps not fully implemented - async fn create_indy_proof( - anoncreds_issuer: &impl BaseAnonCreds, - anoncreds_holder: &impl BaseAnonCreds, - ledger_read: &impl AnoncredsLedgerRead, - ledger_write: &impl AnoncredsLedgerWrite, - did: &str, - ) -> (String, String, String, String) { - let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - anoncreds_issuer, - anoncreds_holder, - ledger_read, - ledger_write, - did, - DEFAULT_SCHEMA_ATTRS, - ) - .await; - let proof_req = json!({ - "nonce":"123432421212", - "name":"proof_req_1", - "version":"0.1", - "requested_attributes": json!({ - "address1_1": json!({ - "name":"address1", - "restrictions": [json!({ "issuer_did": did })] - }), - "zip_2": json!({ - "name":"zip", - "restrictions": [json!({ "issuer_did": did })] - }), - "self_attest_3": json!({ - "name":"self_attest", - }), - }), - "requested_predicates": json!({}), - }) - .to_string(); - let requested_credentials_json = json!({ - "self_attested_attributes":{ - "self_attest_3": "my_self_attested_val" - }, - "requested_attributes":{ - "address1_1": {"cred_id": cred_id, "revealed": true}, - "zip_2": {"cred_id": cred_id, "revealed": true} - }, - "requested_predicates":{} - }) - .to_string(); - - let schema_id = schema.schema_id.clone(); - let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - let schemas = json!({ - schema_id: schema_json, - }) - .to_string(); - - let cred_def_json: serde_json::Value = - serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); - let cred_defs = json!({ - cred_def.get_cred_def_id(): cred_def_json, - }) - .to_string(); - - anoncreds_holder - .prover_get_credentials_for_proof_req(&proof_req) - .await - .unwrap(); - - let proof = anoncreds_holder - .prover_create_proof( - &proof_req, - &requested_credentials_json, - "main", - &schemas, - &cred_defs, - None, - ) - .await - .unwrap(); - (schemas, cred_defs, proof_req, proof) - } - - async fn create_proof_with_predicate( - anoncreds_issuer: &impl BaseAnonCreds, - anoncreds_holder: &impl BaseAnonCreds, - ledger_read: &impl AnoncredsLedgerRead, - ledger_write: &impl AnoncredsLedgerWrite, - did: &str, - include_predicate_cred: bool, - ) -> (String, String, String, String) { - let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - anoncreds_issuer, - anoncreds_holder, - ledger_read, - ledger_write, - did, - DEFAULT_SCHEMA_ATTRS, - ) - .await; - - let proof_req = json!({ - "nonce":"123432421212", - "name":"proof_req_1", - "version":"0.1", - "requested_attributes": json!({ - "address1_1": json!({ - "name":"address1", - "restrictions": [json!({ "issuer_did": did })] - }), - "self_attest_3": json!({ - "name":"self_attest", - }), - }), - "requested_predicates": json!({ - "zip_3": {"name":"zip", "p_type":">=", "p_value":18} - }), - }) - .to_string(); - - let requested_credentials_json = if include_predicate_cred { - json!({ - "self_attested_attributes":{ - "self_attest_3": "my_self_attested_val" - }, - "requested_attributes":{ - "address1_1": {"cred_id": cred_id, "revealed": true} - }, - "requested_predicates":{ - "zip_3": {"cred_id": cred_id} - } - }) - .to_string() - } else { - json!({ - "self_attested_attributes":{ - "self_attest_3": "my_self_attested_val" - }, - "requested_attributes":{ - "address1_1": {"cred_id": cred_id, "revealed": true} - }, - "requested_predicates":{ - } - }) - .to_string() - }; - - let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - let schemas = json!({ - schema.schema_id: schema_json, - }) - .to_string(); - - let cred_def_json: serde_json::Value = - serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); - let cred_defs = json!({ - cred_def.get_cred_def_id(): cred_def_json, - }) - .to_string(); - - anoncreds_holder - .prover_get_credentials_for_proof_req(&proof_req) - .await - .unwrap(); - - let proof = anoncreds_holder - .prover_create_proof( - &proof_req, - &requested_credentials_json, - "main", - &schemas, - &cred_defs, - None, - ) - .await - .unwrap(); - (schemas, cred_defs, proof_req, proof) - } - - async fn create_and_store_nonrevocable_credential( - anoncreds_issuer: &impl BaseAnonCreds, - anoncreds_holder: &impl BaseAnonCreds, - ledger_read: &impl AnoncredsLedgerRead, - ledger_write: &impl AnoncredsLedgerWrite, - issuer_did: &str, - attr_list: &str, - ) -> (Schema, CredentialDef, String) { - let schema = - create_and_write_test_schema(anoncreds_issuer, ledger_write, issuer_did, attr_list) - .await; - - let cred_def = create_and_write_test_cred_def( - anoncreds_issuer, - ledger_read, - ledger_write, - issuer_did, - &schema.schema_id, - false, - ) - .await; - tokio::time::sleep(Duration::from_millis(500)).await; - - let cred_id = create_and_write_credential( - anoncreds_issuer, - anoncreds_holder, - issuer_did, - &cred_def, - None, - ) - .await; - (schema, cred_def, cred_id) - } - - #[tokio::test] - #[ignore] - async fn test_pool_proof_self_attested_proof_validation() { - run_setup!(|setup| async move { - let requested_attrs = json!([ - json!({ - "name":"address1", - "self_attest_allowed": true, - }), - json!({ - "name":"zip", - "self_attest_allowed": true, - }), - ]) - .to_string(); - let requested_predicates = json!([]).to_string(); - let revocation_details = r#"{"support_revocation":false}"#.to_string(); - let name = "Optional".to_owned(); - - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) - .await - .unwrap() - .set_requested_attributes_as_string(requested_attrs) - .unwrap() - .set_requested_predicates_as_string(requested_predicates) - .unwrap() - .set_not_revoked_interval(revocation_details) - .unwrap(); - - let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); - - let anoncreds = setup.profile.anoncreds(); - let prover_proof_json = anoncreds - .prover_create_proof( - &proof_req_json, - &json!({ - "self_attested_attributes":{ - "attribute_0": "my_self_attested_address", - "attribute_1": "my_self_attested_zip" - }, - "requested_attributes":{}, - "requested_predicates":{} - }) - .to_string(), - "main", - &json!({}).to_string(), - &json!({}).to_string(), - None, - ) - .await - .unwrap(); - - assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json - ) - .await - .unwrap()); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_pool_proof_restrictions() { - run_setup!(|setup| async move { - let requested_attrs = json!([ - json!({ - "name":"address1", - "restrictions": [{ "issuer_did": "Not Here" }], - }), - json!({ - "name":"zip", - }), - json!({ - "name":"self_attest", - "self_attest_allowed": true, - }), - ]) - .to_string(); - let requested_predicates = json!([]).to_string(); - let revocation_details = r#"{"support_revocation":true}"#.to_string(); - let name = "Optional".to_owned(); - - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) - .await - .unwrap() - .set_requested_attributes_as_string(requested_attrs) - .unwrap() - .set_requested_predicates_as_string(requested_predicates) - .unwrap() - .set_not_revoked_interval(revocation_details) - .unwrap(); - - let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); - - let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), - &setup.institution_did, - utils::constants::DEFAULT_SCHEMA_ATTRS, - ) - .await; - let cred_def_json: serde_json::Value = - serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); - let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - - let anoncreds = setup.profile.anoncreds(); - let prover_proof_json = anoncreds - .prover_create_proof( - &proof_req_json, - &json!({ - "self_attested_attributes":{ - "attribute_2": "my_self_attested_val" - }, - "requested_attributes":{ - "attribute_0": {"cred_id": cred_id, "revealed": true}, - "attribute_1": {"cred_id": cred_id, "revealed": true} - }, - "requested_predicates":{} - }) - .to_string(), - "main", - &json!({ schema.schema_id: schema_json }).to_string(), - &json!({ cred_def.get_cred_def_id(): cred_def_json }).to_string(), - None, - ) - .await - .unwrap(); - assert_eq!( - validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json - ) - .await - .unwrap_err() - .kind(), - AriesVcxErrorKind::ProofRejected - ); - - let mut proof_req_json: serde_json::Value = - serde_json::from_str(&proof_req_json).unwrap(); - proof_req_json["requested_attributes"]["attribute_0"]["restrictions"] = json!({}); - assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json.to_string() - ) - .await - .unwrap()); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_pool_proof_validate_attribute() { - run_setup!(|setup| async move { - let requested_attrs = json!([ - json!({ - "name":"address1", - "restrictions": [json!({ "issuer_did": setup.institution_did })] - }), - json!({ - "name":"zip", - "restrictions": [json!({ "issuer_did": setup.institution_did })] - }), - json!({ - "name":"self_attest", - "self_attest_allowed": true, - }), - ]) - .to_string(); - let requested_predicates = json!([]).to_string(); - let revocation_details = r#"{"support_revocation":true}"#.to_string(); - let name = "Optional".to_owned(); - - let proof_req_json = ProofRequestData::create(setup.profile.anoncreds(), &name) - .await - .unwrap() - .set_requested_attributes_as_string(requested_attrs) - .unwrap() - .set_requested_predicates_as_string(requested_predicates) - .unwrap() - .set_not_revoked_interval(revocation_details) - .unwrap(); - - let proof_req_json = serde_json::to_string(&proof_req_json).unwrap(); - - let (schema, cred_def, cred_id) = create_and_store_nonrevocable_credential( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), - &setup.institution_did, - utils::constants::DEFAULT_SCHEMA_ATTRS, - ) - .await; - let cred_def_json: serde_json::Value = - serde_json::from_str(cred_def.get_cred_def_json()).unwrap(); - let schema_json: serde_json::Value = serde_json::from_str(&schema.schema_json).unwrap(); - - let anoncreds = setup.profile.anoncreds(); - let prover_proof_json = anoncreds - .prover_create_proof( - &proof_req_json, - &json!({ - "self_attested_attributes":{ - "attribute_2": "my_self_attested_val" - }, - "requested_attributes":{ - "attribute_0": {"cred_id": cred_id, "revealed": true}, - "attribute_1": {"cred_id": cred_id, "revealed": true} - }, - "requested_predicates":{} - }) - .to_string(), - "main", - &json!({ schema.schema_id: schema_json }).to_string(), - &json!({ cred_def.get_cred_def_id(): cred_def_json }).to_string(), - None, - ) - .await - .unwrap(); - assert!(validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json - ) - .await - .unwrap()); - - let mut proof_obj: serde_json::Value = - serde_json::from_str(&prover_proof_json).unwrap(); - { - proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["raw"] = - json!("Other Value"); - let prover_proof_json = serde_json::to_string(&proof_obj).unwrap(); - - assert_eq!( - validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json - ) - .await - .unwrap_err() - .kind(), - AriesVcxErrorKind::InvalidProof - ); - } - { - proof_obj["requested_proof"]["revealed_attrs"]["address1_1"]["encoded"] = - json!("1111111111111111111111111111111111111111111111111111111111"); - let prover_proof_json = serde_json::to_string(&proof_obj).unwrap(); - - assert_eq!( - validate_indy_proof( - setup.profile.ledger_read(), - setup.profile.anoncreds(), - &prover_proof_json, - &proof_req_json - ) - .await - .unwrap_err() - .kind(), - AriesVcxErrorKind::InvalidProof - ); - } - }) - .await; - } - #[tokio::test] - #[ignore] - async fn test_pool_prover_verify_proof() { - run_setup!(|setup| async move { - let (schemas, cred_defs, proof_req, proof) = create_indy_proof( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), - &setup.institution_did, - ) - .await; - - let anoncreds = setup.profile.anoncreds(); - let proof_validation = anoncreds - .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") - .await - .unwrap(); - - assert!(proof_validation); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_pool_prover_verify_proof_with_predicate_success_case() { - run_setup!(|setup| async move { - let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), - &setup.institution_did, - true, - ) - .await; - - let anoncreds = setup.profile.anoncreds(); - let proof_validation = anoncreds - .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") - .await - .unwrap(); - - assert!(proof_validation); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_pool_prover_verify_proof_with_predicate_fail_case() { - run_setup!(|setup| async move { - let (schemas, cred_defs, proof_req, proof) = create_proof_with_predicate( - setup.profile.anoncreds(), - setup.profile.anoncreds(), - setup.profile.ledger_read(), - setup.profile.ledger_write(), - &setup.institution_did, - false, - ) - .await; - - let anoncreds = setup.profile.anoncreds(); - anoncreds - .verifier_verify_proof(&proof_req, &proof, &schemas, &cred_defs, "{}", "{}") - .await - .unwrap_err(); - }) - .await; - } -} diff --git a/aries_vcx/src/common/proofs/verifier/verifier_internal.rs b/aries_vcx/src/common/proofs/verifier/verifier_internal.rs index 3f6c9f91ee..022d0be206 100644 --- a/aries_vcx/src/common/proofs/verifier/verifier_internal.rs +++ b/aries_vcx/src/common/proofs/verifier/verifier_internal.rs @@ -3,7 +3,7 @@ use aries_vcx_core::{ }; use serde_json::{self, Value}; -use crate::{errors::error::prelude::*, global::settings, utils::openssl::encode}; +use crate::{errors::error::prelude::*, utils::openssl::encode}; #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct CredInfoVerifier { @@ -51,10 +51,6 @@ pub fn get_credential_info(proof: &str) -> VcxResult> { } pub fn validate_proof_revealed_attributes(proof_json: &str) -> VcxResult<()> { - if settings::indy_mocks_enabled() { - return Ok(()); - } - let proof: Value = serde_json::from_str(proof_json).map_err(|err| { AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, diff --git a/aries_vcx/src/core/profile/mod.rs b/aries_vcx/src/core/profile/mod.rs index 42d95aa51e..6aa0ef0188 100644 --- a/aries_vcx/src/core/profile/mod.rs +++ b/aries_vcx/src/core/profile/mod.rs @@ -1,23 +1,32 @@ pub mod ledger; #[cfg(feature = "modular_libs")] pub mod modular_libs_profile; -pub mod profile; #[cfg(feature = "vdr_proxy_ledger")] pub mod vdr_proxy_profile; #[cfg(feature = "vdrtools")] pub mod vdrtools_profile; -const DEFAULT_AML_LABEL: &str = "eula"; - use std::sync::Arc; -use aries_vcx_core::ledger::{ - base_ledger::{IndyLedgerRead, TxnAuthrAgrmtOptions}, - indy_vdr_ledger::GetTxnAuthorAgreementData, +#[cfg(feature = "migration")] +use aries_vcx_core::WalletHandle; +use aries_vcx_core::{ + anoncreds::base_anoncreds::BaseAnonCreds, + ledger::{ + base_ledger::{ + AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, + TxnAuthrAgrmtOptions, + }, + indy_vdr_ledger::GetTxnAuthorAgreementData, + }, + wallet::base_wallet::BaseWallet, }; +use async_trait::async_trait; use crate::errors::error::VcxResult; +const DEFAULT_AML_LABEL: &str = "eula"; + pub async fn prepare_taa_options( ledger_read: Arc, ) -> VcxResult> { @@ -32,3 +41,26 @@ pub async fn prepare_taa_options( Ok(None) } } + +#[async_trait] +pub trait Profile: std::fmt::Debug + Send + Sync { + type LedgerRead: IndyLedgerRead + AnoncredsLedgerRead; + type LedgerWrite: IndyLedgerWrite + AnoncredsLedgerWrite; + type Anoncreds: BaseAnonCreds; + type Wallet: BaseWallet; + + fn ledger_read(&self) -> &Self::LedgerRead; + + fn ledger_write(&self) -> &Self::LedgerWrite; + + fn anoncreds(&self) -> &Self::Anoncreds; + + fn wallet(&self) -> &Self::Wallet; + + #[cfg(feature = "migration")] + fn wallet_handle(&self) -> Option { + None + } + + fn update_taa_configuration(&self, taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()>; +} diff --git a/aries_vcx/src/core/profile/modular_libs_profile.rs b/aries_vcx/src/core/profile/modular_libs_profile.rs index dd54547575..c7f0f310b4 100644 --- a/aries_vcx/src/core/profile/modular_libs_profile.rs +++ b/aries_vcx/src/core/profile/modular_libs_profile.rs @@ -9,7 +9,7 @@ use async_trait::async_trait; use super::{ ledger::{ArcIndyVdrLedgerRead, ArcIndyVdrLedgerWrite}, - profile::Profile, + Profile, }; use crate::{ core::profile::ledger::{build_ledger_components, VcxPoolConfig}, diff --git a/aries_vcx/src/core/profile/profile.rs b/aries_vcx/src/core/profile/profile.rs deleted file mode 100644 index 20af07a8ee..0000000000 --- a/aries_vcx/src/core/profile/profile.rs +++ /dev/null @@ -1,36 +0,0 @@ -#[cfg(feature = "migration")] -use aries_vcx_core::WalletHandle; -use aries_vcx_core::{ - anoncreds::base_anoncreds::BaseAnonCreds, - ledger::base_ledger::{ - AnoncredsLedgerRead, AnoncredsLedgerWrite, IndyLedgerRead, IndyLedgerWrite, - TxnAuthrAgrmtOptions, - }, - wallet::base_wallet::BaseWallet, -}; -use async_trait::async_trait; - -use crate::errors::error::VcxResult; - -#[async_trait] -pub trait Profile: std::fmt::Debug + Send + Sync { - type LedgerRead: IndyLedgerRead + AnoncredsLedgerRead; - type LedgerWrite: IndyLedgerWrite + AnoncredsLedgerWrite; - type Anoncreds: BaseAnonCreds; - type Wallet: BaseWallet; - - fn ledger_read(&self) -> &Self::LedgerRead; - - fn ledger_write(&self) -> &Self::LedgerWrite; - - fn anoncreds(&self) -> &Self::Anoncreds; - - fn wallet(&self) -> &Self::Wallet; - - #[cfg(feature = "migration")] - fn wallet_handle(&self) -> Option { - None - } - - fn update_taa_configuration(&self, taa_options: TxnAuthrAgrmtOptions) -> VcxResult<()>; -} diff --git a/aries_vcx/src/core/profile/vdr_proxy_profile.rs b/aries_vcx/src/core/profile/vdr_proxy_profile.rs index cf2e70f414..d575db1966 100644 --- a/aries_vcx/src/core/profile/vdr_proxy_profile.rs +++ b/aries_vcx/src/core/profile/vdr_proxy_profile.rs @@ -17,7 +17,7 @@ use aries_vcx_core::{ }; use async_trait::async_trait; -use super::{prepare_taa_options, profile::Profile}; +use super::{prepare_taa_options, Profile}; use crate::errors::error::VcxResult; #[derive(Debug)] diff --git a/aries_vcx/src/core/profile/vdrtools_profile.rs b/aries_vcx/src/core/profile/vdrtools_profile.rs index 6c9661331e..8b76e6035f 100644 --- a/aries_vcx/src/core/profile/vdrtools_profile.rs +++ b/aries_vcx/src/core/profile/vdrtools_profile.rs @@ -8,7 +8,7 @@ use async_trait::async_trait; use super::{ ledger::{build_ledger_components, ArcIndyVdrLedgerRead, ArcIndyVdrLedgerWrite, VcxPoolConfig}, - profile::Profile, + Profile, }; use crate::errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}; diff --git a/aries_vcx/src/global/settings.rs b/aries_vcx/src/global/settings.rs index 8f55a3c17b..1149a6e1df 100644 --- a/aries_vcx/src/global/settings.rs +++ b/aries_vcx/src/global/settings.rs @@ -1,171 +1,9 @@ -use std::{collections::HashMap, sync::RwLock}; - -use aries_vcx_core::global::settings::{disable_indy_mocks, enable_indy_mocks}; - -use crate::errors::error::prelude::*; - -pub static CONFIG_SDK_TO_REMOTE_ROLE: &str = "sdk_to_remote_role"; -pub static CONFIG_INSTITUTION_DID: &str = "institution_did"; -pub static CONFIG_INSTITUTION_VERKEY: &str = "institution_verkey"; - -// functionally not used -pub static CONFIG_WEBHOOK_URL: &str = "webhook_url"; -pub static CONFIG_ENABLE_TEST_MODE: &str = "enable_test_mode"; -pub static CONFIG_GENESIS_PATH: &str = "genesis_path"; -pub static CONFIG_LOG_CONFIG: &str = "log_config"; -pub static CONFIG_EXPORTED_WALLET_PATH: &str = "exported_wallet_path"; -pub static CONFIG_WALLET_KEY: &str = "wallet_key"; -pub static CONFIG_WALLET_NAME: &str = "wallet_name"; -pub static CONFIG_WALLET_TYPE: &str = "wallet_type"; -pub static CONFIG_WALLET_KEY_DERIVATION: &str = "wallet_key_derivation"; -pub static CONFIG_PROTOCOL_VERSION: &str = "protocol_version"; -pub static CONFIG_TXN_AUTHOR_AGREEMENT: &str = "author_agreement"; -pub static CONFIG_POOL_CONFIG: &str = "pool_config"; -pub static CONFIG_DID_METHOD: &str = "did_method"; -pub static DEFAULT_PROTOCOL_VERSION: usize = 2; -pub static MAX_SUPPORTED_PROTOCOL_VERSION: usize = 2; -pub static UNINITIALIZED_WALLET_KEY: &str = ""; pub static DEFAULT_GENESIS_PATH: &str = "genesis.txn"; -pub static DEFAULT_WALLET_NAME: &str = "LIBVCX_SDK_WALLET"; -pub static DEFAULT_POOL_NAME: &str = "pool1"; pub static DEFAULT_LINK_SECRET_ALIAS: &str = "main"; pub static DEFAULT_DID: &str = "2hoqvcwupRTUNkXn6ArYzs"; -pub static DEFAULT_ROLE: &str = "0"; pub static DEFAULT_WALLET_BACKUP_KEY: &str = "backup_wallet_key"; pub static DEFAULT_WALLET_KEY: &str = "8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY"; -pub static MASK_VALUE: &str = "********"; pub static WALLET_KDF_RAW: &str = "RAW"; pub static WALLET_KDF_ARGON2I_INT: &str = "ARGON2I_INT"; pub static WALLET_KDF_ARGON2I_MOD: &str = "ARGON2I_MOD"; pub static WALLET_KDF_DEFAULT: &str = WALLET_KDF_ARGON2I_MOD; - -lazy_static! { - static ref SETTINGS: RwLock> = RwLock::new(HashMap::new()); -} - -pub fn aries_vcx_enable_indy_mocks() -> VcxResult<()> { - debug!("enable_indy_mocks >>>"); - enable_indy_mocks()?; - set_config_value(CONFIG_ENABLE_TEST_MODE, "true") -} - -pub fn aries_vcx_disable_indy_mocks() -> VcxResult<()> { - debug!("disable_indy_mocks >>>"); - disable_indy_mocks()?; - set_config_value(CONFIG_ENABLE_TEST_MODE, "false") -} - -pub fn indy_mocks_enabled() -> bool { - let config = SETTINGS.read().expect("Unable to access SETTINGS"); - - match config.get(CONFIG_ENABLE_TEST_MODE) { - None => false, - Some(value) => { - debug!("indy_mocks_enabled >>> {}", value); - value == "true" || value == "indy" - } - } -} - -pub fn get_config_value(key: &str) -> VcxResult { - trace!("get_config_value >>> key: {}", key); - - SETTINGS - .read() - .or(Err(AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidConfiguration, - "Cannot read settings", - )))? - .get(key) - .map(|v| v.to_string()) - .ok_or(AriesVcxError::from_msg( - AriesVcxErrorKind::InvalidConfiguration, - format!("Cannot read \"{}\" from settings", key), - )) -} - -pub fn set_config_value(key: &str, value: &str) -> VcxResult<()> { - trace!("set_config_value >>> key: {}, value: {}", key, value); - SETTINGS - .write() - .or(Err(AriesVcxError::from_msg( - AriesVcxErrorKind::UnknownError, - "Cannot write settings", - )))? - .insert(key.to_string(), value.to_string()); - Ok(()) -} - -pub fn reset_config_values_ariesvcx() -> VcxResult<()> { - trace!("reset_config_values >>>"); - let mut config = SETTINGS.write()?; - config.clear(); - Ok(()) -} - -pub fn get_protocol_version() -> usize { - let protocol_version = match get_config_value(CONFIG_PROTOCOL_VERSION) { - Ok(ver) => ver.parse::().unwrap_or_else(|err| { - warn!( - "Can't parse value of protocol version from config ({}), use default one ({})", - err, DEFAULT_PROTOCOL_VERSION - ); - DEFAULT_PROTOCOL_VERSION - }), - Err(err) => { - info!( - "Can't fetch protocol version from config ({}), use default one ({})", - err, DEFAULT_PROTOCOL_VERSION - ); - DEFAULT_PROTOCOL_VERSION - } - }; - if protocol_version > MAX_SUPPORTED_PROTOCOL_VERSION { - error!( - "Protocol version from config {}, greater then maximal supported {}, use maximum one", - protocol_version, MAX_SUPPORTED_PROTOCOL_VERSION - ); - MAX_SUPPORTED_PROTOCOL_VERSION - } else { - protocol_version - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -pub mod unit_tests { - use super::*; - use crate::utils::devsetup::SetupDefaults; - - fn _pool_config() -> String { - r#"{"timeout":40}"#.to_string() - } - - fn _mandatory_config() -> HashMap { - let mut config: HashMap = HashMap::new(); - config.insert(CONFIG_WALLET_KEY.to_string(), "password".to_string()); - config - } - - #[test] - fn test_get_and_set_values() { - let _setup = SetupDefaults::init(); - - let key = "key1".to_string(); - let value1 = "value1".to_string(); - - // Fails with invalid key - assert_eq!( - get_config_value(&key).unwrap_err().kind(), - AriesVcxErrorKind::InvalidConfiguration - ); - - set_config_value(&key, &value1).unwrap(); - assert_eq!(get_config_value(&key).unwrap(), value1); - } -} - -pub fn init_issuer_config(institution_did: &str) -> VcxResult<()> { - set_config_value(CONFIG_INSTITUTION_DID, institution_did)?; - Ok(()) -} diff --git a/aries_vcx/src/handlers/out_of_band/receiver.rs b/aries_vcx/src/handlers/out_of_band/receiver.rs index 9513ce4869..956b14faf3 100644 --- a/aries_vcx/src/handlers/out_of_band/receiver.rs +++ b/aries_vcx/src/handlers/out_of_band/receiver.rs @@ -1,4 +1,4 @@ -use std::{clone::Clone, str::FromStr}; +use std::{clone::Clone, fmt::Display, str::FromStr}; use agency_client::agency_client::AgencyClient; use aries_vcx_core::{ledger::base_ledger::IndyLedgerRead, wallet::base_wallet::BaseWallet}; @@ -323,13 +323,15 @@ impl OutOfBandReceiver { self.oob.clone().into() } - pub fn to_string(&self) -> String { - json!(AriesMessage::from(self.oob.clone())).to_string() - } - pub fn from_string(oob_data: &str) -> VcxResult { Ok(Self { oob: serde_json::from_str(oob_data)?, }) } } + +impl Display for OutOfBandReceiver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", json!(AriesMessage::from(self.oob.clone()))) + } +} diff --git a/aries_vcx/src/handlers/out_of_band/sender.rs b/aries_vcx/src/handlers/out_of_band/sender.rs index d49fbf0ce3..d849993a6f 100644 --- a/aries_vcx/src/handlers/out_of_band/sender.rs +++ b/aries_vcx/src/handlers/out_of_band/sender.rs @@ -1,3 +1,5 @@ +use std::fmt::Display; + use messages::{ msg_fields::protocols::{ cred_issuance::{v1::CredentialIssuanceV1, CredentialIssuance}, @@ -122,10 +124,6 @@ impl OutOfBandSender { self.oob.clone().into() } - pub fn to_string(&self) -> String { - json!(AriesMessage::from(self.oob.clone())).to_string() - } - pub fn from_string(oob_data: &str) -> VcxResult { Ok(Self { oob: serde_json::from_str(oob_data)?, @@ -133,6 +131,12 @@ impl OutOfBandSender { } } +impl Display for OutOfBandSender { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", json!(AriesMessage::from(self.oob.clone()))) + } +} + // #[cfg(test)] // mod unit_tests { // use crate::utils::devsetup::SetupMocks; diff --git a/aries_vcx/src/handlers/util.rs b/aries_vcx/src/handlers/util.rs index c5c6f022bb..7426d9d7a7 100644 --- a/aries_vcx/src/handlers/util.rs +++ b/aries_vcx/src/handlers/util.rs @@ -74,14 +74,7 @@ pub(crate) use make_attach_from_str; pub(crate) use matches_opt_thread_id; pub(crate) use matches_thread_id; -use crate::global::settings; - pub fn verify_thread_id(thread_id: &str, message: &AriesMessage) -> VcxResult<()> { - // todo: ultimately remove this - improve tests - // libvcx_core unit tests are passing in hardcoded message which have mismatching thid - if settings::indy_mocks_enabled() { - return Ok(()); - } let is_match = match message { AriesMessage::BasicMessage(msg) => matches_opt_thread_id!(msg, thread_id), AriesMessage::Connection(Connection::Invitation(msg)) => msg.id == thread_id, diff --git a/aries_vcx/src/lib.rs b/aries_vcx/src/lib.rs index 2976905877..4feabd20f6 100644 --- a/aries_vcx/src/lib.rs +++ b/aries_vcx/src/lib.rs @@ -1,13 +1,5 @@ -#![allow(clippy::or_fun_call)] -#![allow(clippy::module_inception)] -#![allow(clippy::derive_partial_eq_without_eq)] -#![allow(clippy::new_without_default)] -#![allow(clippy::inherent_to_string)] #![allow(clippy::large_enum_variant)] #![allow(clippy::diverging_sub_expression)] -#![deny(clippy::unwrap_used)] -#![cfg_attr(feature = "fatal_warnings", deny(warnings))] -#![crate_name = "aries_vcx"] //this is needed for some large json macro invocations #![recursion_limit = "128"] @@ -28,9 +20,6 @@ extern crate serde_json; #[macro_use] extern crate derive_builder; -#[cfg(test)] -extern crate async_channel; - pub extern crate aries_vcx_core; pub extern crate messages; @@ -47,10 +36,3 @@ pub mod common; pub mod core; pub mod errors; pub mod transport; - -#[cfg(test)] -pub mod test { - pub fn source_id() -> String { - String::from("test source id") - } -} diff --git a/aries_vcx/src/protocols/issuance/holder/state_machine.rs b/aries_vcx/src/protocols/issuance/holder/state_machine.rs index c8c5cebe76..6d9e53ed2d 100644 --- a/aries_vcx/src/protocols/issuance/holder/state_machine.rs +++ b/aries_vcx/src/protocols/issuance/holder/state_machine.rs @@ -107,7 +107,7 @@ impl HolderSM { pub fn new(source_id: String) -> Self { HolderSM { thread_id: Uuid::new_v4().to_string(), - state: HolderFullState::Initial(InitialHolderState::new()), + state: HolderFullState::Initial(InitialHolderState), source_id, } } diff --git a/aries_vcx/src/protocols/issuance/holder/states/initial.rs b/aries_vcx/src/protocols/issuance/holder/states/initial.rs index 6d1eb5f80a..d0d4804286 100644 --- a/aries_vcx/src/protocols/issuance/holder/states/initial.rs +++ b/aries_vcx/src/protocols/issuance/holder/states/initial.rs @@ -1,13 +1,9 @@ use crate::errors::error::prelude::*; #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct InitialHolderState {} +pub struct InitialHolderState; impl InitialHolderState { - pub fn new() -> Self { - Self {} - } - pub fn is_revokable(&self) -> VcxResult { Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, diff --git a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs index 42ffd21339..ae9fcd4cd9 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/states/presentation_request_received.rs @@ -13,7 +13,7 @@ use messages::msg_fields::protocols::{ use uuid::Uuid; use crate::{ - common::proofs::prover::prover::generate_indy_proof, + common::proofs::prover::generate_indy_proof, errors::error::prelude::*, handlers::{ proof_presentation::types::SelectedCredentials, diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs index f7a95223b0..3b18743f14 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/states/presentation_request_sent.rs @@ -7,9 +7,8 @@ use messages::msg_fields::protocols::{ }; use crate::{ - common::proofs::verifier::verifier::validate_indy_proof, + common::proofs::verifier::validate_indy_proof, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, - global::settings, handlers::util::{get_attach_as_string, matches_thread_id, Status}, protocols::proof_presentation::verifier::{ states::finished::FinishedState, verification_status::PresentationVerificationStatus, @@ -29,7 +28,7 @@ impl PresentationRequestSentState { presentation: &Presentation, thread_id: &str, ) -> VcxResult<()> { - if !settings::indy_mocks_enabled() && !matches_thread_id!(presentation, thread_id) { + if !matches_thread_id!(presentation, thread_id) { return Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidJson, format!( diff --git a/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs b/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs index 75526513b1..28f0d23a3a 100644 --- a/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs +++ b/aries_vcx/src/protocols/revocation_notification/receiver/state_machine.rs @@ -39,7 +39,7 @@ pub enum ReceiverFullState { impl RevocationNotificationReceiverSM { pub fn create(rev_reg_id: String, cred_rev_id: String) -> Self { Self { - state: ReceiverFullState::Initial(InitialState::new()), + state: ReceiverFullState::Initial(InitialState), rev_reg_id, cred_rev_id, } diff --git a/aries_vcx/src/protocols/revocation_notification/receiver/states/initial.rs b/aries_vcx/src/protocols/revocation_notification/receiver/states/initial.rs index 57c1641a6a..1f8325ee03 100644 --- a/aries_vcx/src/protocols/revocation_notification/receiver/states/initial.rs +++ b/aries_vcx/src/protocols/revocation_notification/receiver/states/initial.rs @@ -1,8 +1,2 @@ #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct InitialState {} - -impl InitialState { - pub fn new() -> Self { - Self {} - } -} +pub struct InitialState; diff --git a/aries_vcx/src/protocols/revocation_notification/sender/state_machine.rs b/aries_vcx/src/protocols/revocation_notification/sender/state_machine.rs index 26b579a69c..b515714f4c 100644 --- a/aries_vcx/src/protocols/revocation_notification/sender/state_machine.rs +++ b/aries_vcx/src/protocols/revocation_notification/sender/state_machine.rs @@ -42,7 +42,7 @@ pub struct SenderConfig { impl RevocationNotificationSenderSM { pub fn create() -> Self { Self { - state: SenderFullState::Initial(InitialState::new()), + state: SenderFullState::Initial(InitialState), } } diff --git a/aries_vcx/src/protocols/revocation_notification/sender/states/initial.rs b/aries_vcx/src/protocols/revocation_notification/sender/states/initial.rs index 57c1641a6a..1f8325ee03 100644 --- a/aries_vcx/src/protocols/revocation_notification/sender/states/initial.rs +++ b/aries_vcx/src/protocols/revocation_notification/sender/states/initial.rs @@ -1,8 +1,2 @@ #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] -pub struct InitialState {} - -impl InitialState { - pub fn new() -> Self { - Self {} - } -} +pub struct InitialState; diff --git a/aries_vcx/src/utils/devsetup.rs b/aries_vcx/src/utils/devsetup.rs index fe1a6b7519..fcc64814e4 100644 --- a/aries_vcx/src/utils/devsetup.rs +++ b/aries_vcx/src/utils/devsetup.rs @@ -8,10 +8,6 @@ use std::{ use agency_client::testing::mocking::{enable_agency_mocks, AgencyMockDecrypted}; use aries_vcx_core::{ - global::settings::{ - disable_indy_mocks as disable_indy_mocks_core, enable_indy_mocks as enable_indy_mocks_core, - reset_config_values_ariesvcxcore, - }, ledger::indy::pool::test_utils::{create_testpool_genesis_txn_file, get_temp_file_path}, wallet::indy::{ did_mocks::DidMocks, @@ -29,27 +25,11 @@ use crate::core::profile::vdr_proxy_profile::VdrProxyProfile; #[cfg(feature = "vdrtools")] use crate::core::profile::vdrtools_profile::VdrtoolsProfile; use crate::{ - core::profile::{ledger::VcxPoolConfig, profile::Profile}, - global::{ - settings, - settings::{ - aries_vcx_disable_indy_mocks, aries_vcx_enable_indy_mocks, init_issuer_config, - reset_config_values_ariesvcx, set_config_value, CONFIG_INSTITUTION_DID, DEFAULT_DID, - }, - }, + core::profile::{ledger::VcxPoolConfig, Profile}, + global::settings, utils::{constants::POOL1_TXN, file::write_file, test_logger::LibvcxDefaultLogger}, }; -#[macro_export] -macro_rules! assert_match { - ($pattern:pat, $var:expr) => { - assert!(match $var { - $pattern => true, - _ => false, - }) - }; -} - lazy_static! { static ref TEST_LOGGING_INIT: Once = Once::new(); } @@ -60,16 +40,11 @@ pub fn init_test_logging() { }) } -pub fn create_new_seed() -> String { - let x = rand::random::(); - format!("{x:032}") -} - pub struct SetupEmpty; pub struct SetupDefaults; -pub struct SetupMocks {} +pub struct SetupMocks; pub const AGENCY_ENDPOINT: &str = "http://localhost:8080"; pub const AGENCY_DID: &str = "VsKV7grR1BUE29mG2Fm2kX"; @@ -90,10 +65,6 @@ pub fn reset_global_state() { warn!("reset_global_state >>"); AgencyMockDecrypted::clear_mocks(); DidMocks::clear_mocks(); - aries_vcx_disable_indy_mocks().unwrap(); - disable_indy_mocks_core().unwrap(); - reset_config_values_ariesvcx().unwrap(); - reset_config_values_ariesvcxcore().unwrap() } impl SetupEmpty { @@ -126,9 +97,6 @@ impl SetupMocks { pub fn init() -> SetupMocks { init_test_logging(); enable_agency_mocks(); - aries_vcx_enable_indy_mocks().unwrap(); - enable_indy_mocks_core().unwrap(); - set_config_value(CONFIG_INSTITUTION_DID, DEFAULT_DID).unwrap(); SetupMocks {} } } @@ -156,8 +124,7 @@ pub async fn dev_setup_wallet_indy(key_seed: &str) -> (String, WalletHandle) { let (did, _vk) = create_and_store_my_did(wallet_handle, Some(key_seed), None) .await .unwrap(); - // todo: can we remove following line completely? - init_issuer_config(&did).unwrap(); + (did, wallet_handle) } @@ -239,7 +206,7 @@ pub async fn dev_build_featured_profile( macro_rules! run_setup { ($func:expr) => {{ use aries_vcx_core::anoncreds::base_anoncreds::BaseAnonCreds; - use $crate::core::profile::profile::Profile; + use $crate::core::profile::Profile; $crate::utils::devsetup::init_test_logging(); @@ -268,9 +235,13 @@ macro_rules! run_setup { .await .unwrap(); - SetupProfile::new(public_did.to_string(), profile, genesis_file_path) - .await - .run($func) + $crate::utils::devsetup::SetupProfile::new( + public_did.to_string(), + profile, + genesis_file_path, + ) + .await + .run($func) }}; } diff --git a/aries_vcx/src/utils/encryption_envelope.rs b/aries_vcx/src/utils/encryption_envelope.rs index 342fabb385..d62907ae7a 100644 --- a/aries_vcx/src/utils/encryption_envelope.rs +++ b/aries_vcx/src/utils/encryption_envelope.rs @@ -8,7 +8,7 @@ use messages::{ }; use uuid::Uuid; -use crate::{errors::error::prelude::*, global::settings, utils::constants}; +use crate::{errors::error::prelude::*, utils::constants}; #[derive(Debug)] pub struct EncryptionEnvelope(pub Vec); @@ -29,10 +29,6 @@ impl EncryptionEnvelope { did_doc ); - if settings::indy_mocks_enabled() { - return Ok(EncryptionEnvelope(vec![])); - } - EncryptionEnvelope::encrypt_for_pairwise(wallet, message, pw_verkey, did_doc) .and_then(|message| async move { EncryptionEnvelope::wrap_into_forward_messages(wallet, message, did_doc).await diff --git a/aries_vcx/src/utils/mockdata/profile/mock_profile.rs b/aries_vcx/src/utils/mockdata/profile/mock_profile.rs index 044139898a..357a9421d4 100644 --- a/aries_vcx/src/utils/mockdata/profile/mock_profile.rs +++ b/aries_vcx/src/utils/mockdata/profile/mock_profile.rs @@ -2,7 +2,7 @@ use aries_vcx_core::{ledger::base_ledger::TxnAuthrAgrmtOptions, wallet::mock_wal use async_trait::async_trait; use super::{mock_anoncreds::MockAnoncreds, mock_ledger::MockLedger}; -use crate::{core::profile::profile::Profile, errors::error::VcxResult}; +use crate::{core::profile::Profile, errors::error::VcxResult}; /// Implementation of a [Profile] which uses [MockLedger], [MockAnoncreds] and [MockWallet] to /// return mock data for all Profile methods. Only for unit testing purposes diff --git a/aries_vcx/tests/test_connection.rs b/aries_vcx/tests/test_connection.rs index 1ebdf22cdd..15be5b549b 100644 --- a/aries_vcx/tests/test_connection.rs +++ b/aries_vcx/tests/test_connection.rs @@ -6,7 +6,7 @@ pub mod utils; use aries_vcx::{ common::ledger::transactions::write_endpoint_legacy, - core::profile::profile::Profile, + core::profile::Profile, protocols::{connection::GenericConnection, mediated_connection::pairwise_info::PairwiseInfo}, utils::{devsetup::*, encryption_envelope::EncryptionEnvelope}, }; diff --git a/aries_vcx/tests/test_credential_retrieval.rs b/aries_vcx/tests/test_credential_retrieval.rs index 75393b0089..e80ebd9535 100644 --- a/aries_vcx/tests/test_credential_retrieval.rs +++ b/aries_vcx/tests/test_credential_retrieval.rs @@ -22,7 +22,7 @@ use aries_vcx::{ util::AttachmentId, }, run_setup, - utils::{constants::DEFAULT_SCHEMA_ATTRS, devsetup::SetupProfile}, + utils::constants::DEFAULT_SCHEMA_ATTRS, }; use messages::{ decorators::attachment::{Attachment, AttachmentData, AttachmentType}, diff --git a/aries_vcx/tests/test_mysql_wallet.rs b/aries_vcx/tests/test_mysql_wallet.rs index 42d32e5d15..2853e6c7ef 100644 --- a/aries_vcx/tests/test_mysql_wallet.rs +++ b/aries_vcx/tests/test_mysql_wallet.rs @@ -3,10 +3,7 @@ extern crate serde_json; #[cfg(test)] mod dbtests { - use aries_vcx::{ - global::{settings, settings::init_issuer_config}, - utils::test_logger::LibvcxDefaultLogger, - }; + use aries_vcx::{global::settings, utils::test_logger::LibvcxDefaultLogger}; use aries_vcx_core::wallet::{ base_wallet::BaseWallet, indy::{ @@ -45,10 +42,10 @@ mod dbtests { .unwrap(); let wallet_handle = create_and_open_wallet(&config_wallet).await.unwrap(); - let config_issuer = wallet_configure_issuer(wallet_handle, enterprise_seed) + let _config_issuer = wallet_configure_issuer(wallet_handle, enterprise_seed) .await .unwrap(); - init_issuer_config(&config_issuer.institution_did).unwrap(); + let (_, _) = IndySdkWallet::new(wallet_handle) .create_and_store_my_did(None, None) .await diff --git a/aries_vcx/tests/test_pool.rs b/aries_vcx/tests/test_pool.rs index 235ee9b020..e8ddf87bad 100644 --- a/aries_vcx/tests/test_pool.rs +++ b/aries_vcx/tests/test_pool.rs @@ -29,12 +29,12 @@ use aries_vcx::{ create_and_write_test_schema, }, }, - core::profile::profile::Profile, + core::profile::Profile, errors::error::AriesVcxErrorKind, run_setup, utils::{ constants::{DEFAULT_SCHEMA_ATTRS, TEST_TAILS_URL}, - devsetup::{SetupPoolDirectory, SetupProfile}, + devsetup::SetupPoolDirectory, }, }; use aries_vcx_core::{ diff --git a/aries_vcx/tests/test_proof_presentation.rs b/aries_vcx/tests/test_proof_presentation.rs index 0bb2426f0c..0e51073ffb 100644 --- a/aries_vcx/tests/test_proof_presentation.rs +++ b/aries_vcx/tests/test_proof_presentation.rs @@ -23,7 +23,7 @@ use aries_vcx::{ }, }, run_setup, - utils::devsetup::{SetupProfile, *}, + utils::devsetup::*, }; use messages::{msg_fields::protocols::present_proof::PresentProof, AriesMessage}; diff --git a/aries_vcx/tests/test_revocations.rs b/aries_vcx/tests/test_revocations.rs index eb504c9ba3..f1e390daa3 100644 --- a/aries_vcx/tests/test_revocations.rs +++ b/aries_vcx/tests/test_revocations.rs @@ -8,7 +8,7 @@ pub mod utils; use std::{thread, time::Duration}; use aries_vcx::{ - core::profile::profile::Profile, + core::profile::Profile, protocols::proof_presentation::verifier::{ state_machine::VerifierState, verification_status::PresentationVerificationStatus, }, diff --git a/aries_vcx/tests/utils/migration.rs b/aries_vcx/tests/utils/migration.rs index 3b69f0327f..7c3b0ca7f7 100644 --- a/aries_vcx/tests/utils/migration.rs +++ b/aries_vcx/tests/utils/migration.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::{modular_libs_profile::ModularLibsProfile, profile::Profile}, + core::profile::{modular_libs_profile::ModularLibsProfile, Profile}, global::settings::WALLET_KDF_RAW, utils::devsetup::{dev_build_profile_modular, SetupProfile}, }; diff --git a/aries_vcx/tests/utils/scenarios/connection.rs b/aries_vcx/tests/utils/scenarios/connection.rs index fbbeead80d..dfee4c1359 100644 --- a/aries_vcx/tests/utils/scenarios/connection.rs +++ b/aries_vcx/tests/utils/scenarios/connection.rs @@ -1,6 +1,6 @@ use aries_vcx::{ common::ledger::transactions::into_did_doc, - core::profile::profile::Profile, + core::profile::Profile, errors::error::VcxResult, handlers::{out_of_band::sender::OutOfBandSender, util::AnyInvitation}, protocols::{ diff --git a/aries_vcx/tests/utils/scenarios/credential_issuance.rs b/aries_vcx/tests/utils/scenarios/credential_issuance.rs index a0aef3420f..7763ce78e0 100644 --- a/aries_vcx/tests/utils/scenarios/credential_issuance.rs +++ b/aries_vcx/tests/utils/scenarios/credential_issuance.rs @@ -11,7 +11,7 @@ use aries_vcx::{ create_and_write_test_schema, }, }, - core::profile::profile::Profile, + core::profile::Profile, handlers::{ issuance::{holder::Holder, issuer::Issuer}, util::OfferInfo, diff --git a/aries_vcx/tests/utils/scenarios/proof_presentation.rs b/aries_vcx/tests/utils/scenarios/proof_presentation.rs index 1903dde9a0..1b6d327d0b 100644 --- a/aries_vcx/tests/utils/scenarios/proof_presentation.rs +++ b/aries_vcx/tests/utils/scenarios/proof_presentation.rs @@ -7,7 +7,7 @@ use aries_vcx::{ }, proofs::{proof_request::PresentationRequestData, proof_request_internal::AttrInfo}, }, - core::profile::profile::Profile, + core::profile::Profile, handlers::{ issuance::issuer::Issuer, proof_presentation::{ diff --git a/aries_vcx/tests/utils/test_agent.rs b/aries_vcx/tests/utils/test_agent.rs index c801c59355..38b2ba77d8 100644 --- a/aries_vcx/tests/utils/test_agent.rs +++ b/aries_vcx/tests/utils/test_agent.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use aries_vcx::{ - core::profile::profile::Profile, + core::profile::Profile, global::settings::DEFAULT_LINK_SECRET_ALIAS, utils::{ constants::TRUSTEE_SEED, diff --git a/aries_vcx_core/src/anoncreds/indy/credentials/holder/mod.rs b/aries_vcx_core/src/anoncreds/indy/credentials/holder/mod.rs index 5e328d3f54..eb60c159b9 100644 --- a/aries_vcx_core/src/anoncreds/indy/credentials/holder/mod.rs +++ b/aries_vcx_core/src/anoncreds/indy/credentials/holder/mod.rs @@ -3,7 +3,7 @@ use vdrtools::{ Locator, RevocationRegistryDefinition, }; -use crate::{errors::error::VcxCoreResult, global::settings, utils, WalletHandle}; +use crate::{errors::error::VcxCoreResult, WalletHandle}; pub async fn libindy_prover_store_credential( wallet_handle: WalletHandle, @@ -23,10 +23,6 @@ pub async fn libindy_prover_store_credential( rev_reg_def_json, ); - if settings::indy_mocks_enabled() { - return Ok("cred_id".to_string()); - } - let cred_req_meta = serde_json::from_str::(cred_req_meta)?; let cred_json = serde_json::from_str::(cred_json)?; @@ -83,10 +79,6 @@ pub async fn libindy_prover_create_master_secret( wallet_handle: WalletHandle, master_secret_id: &str, ) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - return Ok(settings::DEFAULT_LINK_SECRET_ALIAS.to_string()); - } - let res = Locator::instance() .prover_controller .create_master_secret(wallet_handle, Some(master_secret_id.into())) @@ -102,13 +94,6 @@ pub async fn libindy_prover_create_credential_req( credential_def_json: &str, master_secret_name: &str, ) -> VcxCoreResult<(String, String)> { - if settings::indy_mocks_enabled() { - return Ok(( - utils::constants::CREDENTIAL_REQ_STRING.to_owned(), - String::new(), - )); - } - let cred_offer = serde_json::from_str::(credential_offer_json)?; let cred_def = serde_json::from_str::(credential_def_json)?; diff --git a/aries_vcx_core/src/anoncreds/indy/credentials/issuer/mod.rs b/aries_vcx_core/src/anoncreds/indy/credentials/issuer/mod.rs index efd9e4046b..874b7cf3a1 100644 --- a/aries_vcx_core/src/anoncreds/indy/credentials/issuer/mod.rs +++ b/aries_vcx_core/src/anoncreds/indy/credentials/issuer/mod.rs @@ -5,10 +5,7 @@ use vdrtools::{ use crate::{ anoncreds::indy::{general, general::blob_storage_open_reader}, errors::error::VcxCoreResult, - global::settings, indy::utils::parse_and_validate, - utils, - utils::constants::LIBINDY_CRED_OFFER, wallet::indy::wallet_non_secrets::{get_rev_reg_delta, set_rev_reg_delta}, WalletHandle, }; @@ -17,10 +14,6 @@ pub async fn libindy_issuer_create_credential_offer( wallet_handle: WalletHandle, cred_def_id: &str, ) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - return Ok(LIBINDY_CRED_OFFER.to_string()); - } - let res = Locator::instance() .issuer_controller .create_credential_offer( @@ -40,10 +33,6 @@ pub async fn libindy_issuer_create_credential( rev_reg_id: Option, tails_file: Option, ) -> VcxCoreResult<(String, Option, Option)> { - if settings::indy_mocks_enabled() { - return Ok((utils::constants::CREDENTIAL_JSON.to_owned(), None, None)); - } - let blob_handle = match tails_file { Some(x) => Some(blob_storage_open_reader(&x).await?), None => None, @@ -148,10 +137,6 @@ pub async fn revoke_credential_local( rev_reg_id: &str, cred_rev_id: &str, ) -> VcxCoreResult<()> { - if settings::indy_mocks_enabled() { - return Ok(()); - } - let mut new_delta_json = libindy_issuer_revoke_credential(wallet_handle, tails_file, rev_reg_id, cred_rev_id) .await?; diff --git a/aries_vcx_core/src/anoncreds/indy/proofs/prover.rs b/aries_vcx_core/src/anoncreds/indy/proofs/prover.rs index 2ff5e63c99..237333e155 100644 --- a/aries_vcx_core/src/anoncreds/indy/proofs/prover.rs +++ b/aries_vcx_core/src/anoncreds/indy/proofs/prover.rs @@ -4,10 +4,9 @@ use vdrtools::{Locator, SearchHandle}; use crate::{ anoncreds::indy::general::{blob_storage_open_reader, close_search_handle}, errors::error::{prelude::*, VcxCoreResult}, - global::{mockdata::mock_settings::get_mock_creds_retrieved_for_proof_request, settings}, + global::mockdata::mock_settings::get_mock_creds_retrieved_for_proof_request, indy::utils::parse_and_validate, - utils, - utils::constants::{ATTRS, PROOF_REQUESTED_PREDICATES, REQUESTED_ATTRIBUTES, REV_STATE_JSON}, + utils::constants::{ATTRS, PROOF_REQUESTED_PREDICATES, REQUESTED_ATTRIBUTES}, WalletHandle, }; @@ -18,10 +17,6 @@ pub async fn libindy_prover_create_revocation_state( timestamp: u64, cred_rev_id: &str, ) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - return Ok(REV_STATE_JSON.to_string()); - } - let blob_handle = blob_storage_open_reader(tails_file_path).await?; let res = Locator::instance() @@ -47,10 +42,6 @@ pub async fn libindy_prover_create_proof( credential_defs_json: &str, revoc_states_json: Option<&str>, ) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - return Ok(utils::constants::PROOF_JSON.to_owned()); - } - let revoc_states_json = revoc_states_json.unwrap_or("{}"); let res = Locator::instance() diff --git a/aries_vcx_core/src/global/settings.rs b/aries_vcx_core/src/global/settings.rs index a43cad9c47..2da0d5556d 100644 --- a/aries_vcx_core/src/global/settings.rs +++ b/aries_vcx_core/src/global/settings.rs @@ -1,110 +1,2 @@ -use std::{collections::HashMap, sync::RwLock}; - -use crate::errors::error::prelude::*; - -pub static CONFIG_INSTITUTION_DID: &str = "institution_did"; - -// functionally not used -pub static CONFIG_ENABLE_TEST_MODE: &str = "enable_test_mode"; -pub static CONFIG_WALLET_BACKUP_KEY: &str = "backup_key"; -pub static CONFIG_WALLET_KEY: &str = "wallet_key"; -pub static CONFIG_PROTOCOL_VERSION: &str = "protocol_version"; -pub static CONFIG_TXN_AUTHOR_AGREEMENT: &str = "author_agreement"; -pub static DEFAULT_PROTOCOL_VERSION: usize = 2; -pub static MAX_SUPPORTED_PROTOCOL_VERSION: usize = 2; pub static DEFAULT_LINK_SECRET_ALIAS: &str = "main"; pub static DEFAULT_DID: &str = "2hoqvcwupRTUNkXn6ArYzs"; - -lazy_static! { - static ref SETTINGS: RwLock> = RwLock::new(HashMap::new()); -} - -pub fn enable_indy_mocks() -> VcxCoreResult<()> { - debug!("enable_indy_mocks >>>"); - set_config_value(CONFIG_ENABLE_TEST_MODE, "true") -} - -pub fn disable_indy_mocks() -> VcxCoreResult<()> { - debug!("disable_indy_mocks >>>"); - set_config_value(CONFIG_ENABLE_TEST_MODE, "false") -} - -pub fn indy_mocks_enabled() -> bool { - let config = SETTINGS.read().expect("Unable to access SETTINGS"); - - match config.get(CONFIG_ENABLE_TEST_MODE) { - None => false, - Some(value) => { - debug!("indy_mocks_enabled >>> {}", value); - value == "true" || value == "indy" - } - } -} - -pub fn get_config_value(key: &str) -> VcxCoreResult { - trace!("get_config_value >>> key: {}", key); - - SETTINGS - .read() - .or(Err(AriesVcxCoreError::from_msg( - AriesVcxCoreErrorKind::InvalidConfiguration, - "Cannot read settings", - )))? - .get(key) - .map(|v| v.to_string()) - .ok_or(AriesVcxCoreError::from_msg( - AriesVcxCoreErrorKind::InvalidConfiguration, - format!("Cannot read \"{key}\" from settings"), - )) -} - -pub fn set_config_value(key: &str, value: &str) -> VcxCoreResult<()> { - trace!("set_config_value >>> key: {}, value: {}", key, value); - SETTINGS - .write() - .or(Err(AriesVcxCoreError::from_msg( - AriesVcxCoreErrorKind::UnknownError, - "Cannot write settings", - )))? - .insert(key.to_string(), value.to_string()); - Ok(()) -} - -pub fn reset_config_values_ariesvcxcore() -> VcxCoreResult<()> { - trace!("reset_config_values >>>"); - let mut config = SETTINGS.write()?; - config.clear(); - Ok(()) -} - -pub fn get_protocol_version() -> usize { - let protocol_version = match get_config_value(CONFIG_PROTOCOL_VERSION) { - Ok(ver) => ver.parse::().unwrap_or_else(|err| { - warn!( - "Can't parse value of protocol version from config ({}), use default one ({})", - err, DEFAULT_PROTOCOL_VERSION - ); - DEFAULT_PROTOCOL_VERSION - }), - Err(err) => { - info!( - "Can't fetch protocol version from config ({}), use default one ({})", - err, DEFAULT_PROTOCOL_VERSION - ); - DEFAULT_PROTOCOL_VERSION - } - }; - if protocol_version > MAX_SUPPORTED_PROTOCOL_VERSION { - error!( - "Protocol version from config {}, greater then maximal supported {}, use maximum one", - protocol_version, MAX_SUPPORTED_PROTOCOL_VERSION - ); - MAX_SUPPORTED_PROTOCOL_VERSION - } else { - protocol_version - } -} - -pub fn get_sample_did() -> String { - DEFAULT_DID.to_string() -} diff --git a/aries_vcx_core/src/wallet/indy/internal/mod.rs b/aries_vcx_core/src/wallet/indy/internal/mod.rs index 288cce97c1..9736937c29 100644 --- a/aries_vcx_core/src/wallet/indy/internal/mod.rs +++ b/aries_vcx_core/src/wallet/indy/internal/mod.rs @@ -1,6 +1,6 @@ use vdrtools::{Locator, SearchHandle, WalletHandle}; -use crate::{errors::error::VcxCoreResult, global::settings}; +use crate::errors::error::VcxCoreResult; pub(crate) async fn add_wallet_record( wallet_handle: WalletHandle, @@ -17,10 +17,6 @@ pub(crate) async fn add_wallet_record( secret!(&tags) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .add_record( @@ -48,12 +44,6 @@ pub(crate) async fn get_wallet_record( options ); - if settings::indy_mocks_enabled() { - return Ok( - r#"{"id":"123","type":"record type","value":"record value","tags":null}"#.to_string(), - ); - } - let res = Locator::instance() .non_secret_controller .get_record(wallet_handle, xtype.into(), id.into(), options.into()) @@ -73,10 +63,6 @@ pub async fn delete_wallet_record( secret!(&id) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .delete_record(wallet_handle, xtype.into(), id.into()) @@ -98,10 +84,6 @@ pub(crate) async fn update_wallet_record_value( secret!(&value) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .update_record_value(wallet_handle, xtype.into(), id.into(), value.into()) @@ -123,10 +105,6 @@ pub(crate) async fn add_wallet_record_tags( secret!(&tags) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .add_record_tags( @@ -153,10 +131,6 @@ pub(crate) async fn update_wallet_record_tags( secret!(&tags) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .update_record_tags( @@ -183,10 +157,6 @@ pub(crate) async fn delete_wallet_record_tags( secret!(&tag_names) ); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .delete_record_tags(wallet_handle, xtype.into(), id.into(), tag_names.into()) @@ -209,10 +179,6 @@ pub async fn open_search_wallet( options ); - if settings::indy_mocks_enabled() { - return Ok(SearchHandle(1)); - } - let res = Locator::instance() .non_secret_controller .open_search(wallet_handle, xtype.into(), query.into(), options.into()) @@ -233,10 +199,6 @@ pub async fn fetch_next_records_wallet( count ); - if settings::indy_mocks_enabled() { - return Ok(String::from("{}")); - } - let res = Locator::instance() .non_secret_controller .fetch_search_next_records(wallet_handle, search_handle, count) @@ -249,10 +211,6 @@ pub async fn fetch_next_records_wallet( pub async fn close_search_wallet(search_handle: SearchHandle) -> VcxCoreResult<()> { trace!("close_search >>> search_handle: {:?}", search_handle); - if settings::indy_mocks_enabled() { - return Ok(()); - } - Locator::instance() .non_secret_controller .close_search(search_handle) diff --git a/aries_vcx_core/src/wallet/indy/signing.rs b/aries_vcx_core/src/wallet/indy/signing.rs index d19f1d07e6..0ae9910754 100644 --- a/aries_vcx_core/src/wallet/indy/signing.rs +++ b/aries_vcx_core/src/wallet/indy/signing.rs @@ -2,15 +2,10 @@ use vdrtools::Locator; use crate::{ errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}, - global::settings, WalletHandle, }; pub async fn sign(wallet_handle: WalletHandle, my_vk: &str, msg: &[u8]) -> VcxCoreResult> { - if settings::indy_mocks_enabled() { - return Ok(Vec::from(msg)); - } - let res = Locator::instance() .crypto_controller .crypto_sign(wallet_handle, my_vk, msg) @@ -20,10 +15,6 @@ pub async fn sign(wallet_handle: WalletHandle, my_vk: &str, msg: &[u8]) -> VcxCo } pub async fn verify(vk: &str, msg: &[u8], signature: &[u8]) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - return Ok(true); - } - let res = Locator::instance() .crypto_controller .crypto_verify(vk, msg, signature) @@ -38,10 +29,6 @@ pub async fn pack_message( receiver_keys: &str, msg: &[u8], ) -> VcxCoreResult> { - if settings::indy_mocks_enabled() { - return Ok(msg.to_vec()); - } - // parse json array of keys let receiver_list = serde_json::from_str::>(receiver_keys) .map_err(|_| { @@ -76,10 +63,6 @@ pub async fn pack_message( } pub async fn unpack_message(wallet_handle: WalletHandle, msg: &[u8]) -> VcxCoreResult> { - if settings::indy_mocks_enabled() { - return Ok(Vec::from(msg)); - } - let res = Locator::instance() .crypto_controller .unpack_msg(serde_json::from_slice(msg)?, wallet_handle) diff --git a/aries_vcx_core/src/wallet/indy/wallet.rs b/aries_vcx_core/src/wallet/indy/wallet.rs index c5e0b61941..4bf556c602 100644 --- a/aries_vcx_core/src/wallet/indy/wallet.rs +++ b/aries_vcx_core/src/wallet/indy/wallet.rs @@ -8,8 +8,6 @@ use vdrtools::{ use crate::{ errors::error::{AriesVcxCoreError, AriesVcxCoreErrorKind, VcxCoreResult}, - global::settings, - utils, wallet::indy::{ did_mocks::{did_mocks_enabled, DidMocks}, IssuerConfig, RestoreWalletConfigs, WalletConfig, @@ -271,11 +269,6 @@ pub async fn export_wallet( } pub async fn create_and_open_wallet(wallet_config: &WalletConfig) -> VcxCoreResult { - if settings::indy_mocks_enabled() { - warn!("create_and_open_wallet ::: Indy mocks enabled, skipping opening main wallet."); - return Ok(WalletHandle(0)); - } - create_indy_wallet(wallet_config).await?; let handle = open_wallet(wallet_config).await?; @@ -286,11 +279,6 @@ pub async fn create_and_open_wallet(wallet_config: &WalletConfig) -> VcxCoreResu pub async fn close_wallet(wallet_handle: WalletHandle) -> VcxCoreResult<()> { trace!("close_wallet >>>"); - if settings::indy_mocks_enabled() { - warn!("close_wallet >>> Indy mocks enabled, skipping closing wallet"); - return Ok(()); - } - Locator::instance() .wallet_controller .close(wallet_handle) @@ -310,13 +298,6 @@ pub async fn create_and_store_my_did( method_name ); - if settings::indy_mocks_enabled() { - return Ok(( - utils::constants::DID.to_string(), - utils::constants::VERKEY.to_string(), - )); - } - let res = Locator::instance() .did_controller .create_and_store_my_did( diff --git a/did_resolver_sov/tests/resolution.rs b/did_resolver_sov/tests/resolution.rs index c66095d496..38dc4b41b2 100644 --- a/did_resolver_sov/tests/resolution.rs +++ b/did_resolver_sov/tests/resolution.rs @@ -5,9 +5,8 @@ use aries_vcx::{ service_didsov::{DidSovServiceType, EndpointDidSov}, transactions::write_endpoint, }, - core::profile::profile::Profile, + core::profile::Profile, run_setup, - utils::devsetup::SetupProfile, }; use did_resolver::{ did_parser::Did, diff --git a/libvcx_core/Cargo.toml b/libvcx_core/Cargo.toml index d5b7ab20e8..1da0eb6515 100644 --- a/libvcx_core/Cargo.toml +++ b/libvcx_core/Cargo.toml @@ -27,6 +27,7 @@ serde_json = "1.0.40" serde_derive = "1.0.97" futures = { version = "0.3", default-features = false } aries-vcx = { path = "../aries_vcx" } +aries_vcx_core = { path = "../aries_vcx_core" } diddoc_legacy = { path = "../diddoc_legacy" } thiserror = "1.0.37" uuid = { version = "0.7.4", default-features = false, features = ["v4"] } diff --git a/libvcx_core/src/api_vcx/api_global/agency_client.rs b/libvcx_core/src/api_vcx/api_global/agency_client.rs index 3730d40f9f..06634b61a5 100644 --- a/libvcx_core/src/api_vcx/api_global/agency_client.rs +++ b/libvcx_core/src/api_vcx/api_global/agency_client.rs @@ -93,15 +93,13 @@ pub async fn provision_cloud_agent( pub mod tests { use aries_vcx::{ agency_client::{ - configuration::AgentProvisionConfig, messages::update_message::UIDsByConn, - testing::mocking::AgencyMockDecrypted, MessageStatusCode, + messages::update_message::UIDsByConn, testing::mocking::AgencyMockDecrypted, + MessageStatusCode, }, utils::{constants, devsetup::SetupMocks}, }; - use crate::api_vcx::api_global::agency_client::{ - agency_update_messages, provision_cloud_agent, update_webhook_url, - }; + use crate::api_vcx::api_global::agency_client::{agency_update_messages, update_webhook_url}; #[tokio::test] async fn test_update_institution_webhook() { @@ -109,21 +107,6 @@ pub mod tests { update_webhook_url("https://example.com").await.unwrap(); } - #[tokio::test] - async fn test_provision_cloud_agent() { - let _setup = SetupMocks::init(); - - let config = AgentProvisionConfig { - agency_did: "Ab8TvZa3Q19VNkQVzAWVL7".into(), - agency_verkey: "5LXaR43B1aQyeh94VBP8LG1Sgvjk7aNfqiksBCSjwqbf".into(), - agency_endpoint: "https://enym-eagency.pdev.evernym.com" - .parse() - .expect("valid url"), - agent_seed: None, - }; - provision_cloud_agent(&config).await.unwrap(); - } - #[tokio::test] async fn test_messages_update_status() { let _setup = SetupMocks::init(); diff --git a/libvcx_core/src/api_vcx/api_global/ledger.rs b/libvcx_core/src/api_vcx/api_global/ledger.rs index dc288f73cb..374e483ac8 100644 --- a/libvcx_core/src/api_vcx/api_global/ledger.rs +++ b/libvcx_core/src/api_vcx/api_global/ledger.rs @@ -9,18 +9,13 @@ use aries_vcx::{ write_endpoint_legacy, }, }, - global::settings::CONFIG_INSTITUTION_DID, }; use diddoc_legacy::aries::service::AriesService; use url::Url; use crate::{ - api_vcx::api_global::{ - profile::{ - get_main_indy_ledger_read, get_main_indy_ledger_write, get_main_profile, - get_main_wallet, - }, - settings::get_config_value, + api_vcx::api_global::profile::{ + get_main_indy_ledger_read, get_main_indy_ledger_write, get_main_profile, get_main_wallet, }, errors::{ error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -29,11 +24,9 @@ use crate::{ }, }; -pub async fn endorse_transaction(transaction: &str) -> LibvcxResult<()> { - let endorser_did = get_config_value(CONFIG_INSTITUTION_DID)?; - +pub async fn endorse_transaction(transaction: &str, endorser_did: &str) -> LibvcxResult<()> { let ledger = get_main_indy_ledger_write()?; - map_ariesvcx_core_result(ledger.endorse_transaction(&endorser_did, transaction).await) + map_ariesvcx_core_result(ledger.endorse_transaction(endorser_did, transaction).await) } pub async fn get_ledger_txn(seq_no: i32, submitter_did: Option) -> LibvcxResult { @@ -164,7 +157,7 @@ pub mod tests { get_txns_sovrin_testnet, }, global::settings::DEFAULT_GENESIS_PATH, - utils::devsetup::{SetupEmpty, SetupMocks}, + utils::devsetup::SetupEmpty, }; use crate::api_vcx::api_global::{ @@ -232,15 +225,4 @@ pub mod tests { let auth_agreement = serde_json::to_value(auth_agreement).unwrap(); assert_eq!(expected, auth_agreement); } - - #[tokio::test] - async fn test_vcx_get_ledger_author_agreement() { - let _setup = SetupMocks::init(); - - let agreement = ledger_get_txn_author_agreement().await.unwrap(); - assert_eq!( - aries_vcx::utils::constants::DEFAULT_AUTHOR_AGREEMENT, - agreement - ); - } } diff --git a/libvcx_core/src/api_vcx/api_global/mod.rs b/libvcx_core/src/api_vcx/api_global/mod.rs index e90da0656b..443fe33765 100644 --- a/libvcx_core/src/api_vcx/api_global/mod.rs +++ b/libvcx_core/src/api_vcx/api_global/mod.rs @@ -2,7 +2,6 @@ pub mod agency_client; pub mod ledger; pub mod pool; pub mod profile; -pub mod settings; pub mod state; pub mod wallet; diff --git a/libvcx_core/src/api_vcx/api_global/pool.rs b/libvcx_core/src/api_vcx/api_global/pool.rs index c3b5c3b817..2d4b57baa1 100644 --- a/libvcx_core/src/api_vcx/api_global/pool.rs +++ b/libvcx_core/src/api_vcx/api_global/pool.rs @@ -197,7 +197,7 @@ pub mod tests { aries_vcx_core::ledger::indy::pool::test_utils::{ create_testpool_genesis_txn_file, get_temp_file_path, }, - global::settings::{set_config_value, CONFIG_GENESIS_PATH, DEFAULT_GENESIS_PATH}, + global::settings::DEFAULT_GENESIS_PATH, utils::{ constants::POOL1_TXN, devsetup::{SetupDefaults, SetupEmpty, TempFile}, @@ -284,9 +284,8 @@ pub mod tests { let _setup = SetupEmpty::init(); _create_and_open_wallet().await.unwrap(); - let genesis_transactions = + let _genesis_transactions = TempFile::create_with_data(POOL1_TXN, "{ \"invalid\": \"genesis\" }"); - set_config_value(CONFIG_GENESIS_PATH, &genesis_transactions.path).unwrap(); // todo: indy-vdr panics if the file is invalid, see: // indy-vdr-0.3.4/src/pool/runner.rs:44:22 diff --git a/libvcx_core/src/api_vcx/api_global/profile.rs b/libvcx_core/src/api_vcx/api_global/profile.rs index ea3a6f4f7a..40423e618c 100644 --- a/libvcx_core/src/api_vcx/api_global/profile.rs +++ b/libvcx_core/src/api_vcx/api_global/profile.rs @@ -12,7 +12,6 @@ use aries_vcx::{ }, wallet::{base_wallet::BaseWallet, mock_wallet::MockWallet}, }, - global::settings::indy_mocks_enabled, utils::mockdata::profile::{ mock_anoncreds::MockAnoncreds, mock_ledger::MockLedger, mock_profile::MockProfile, }, @@ -211,9 +210,6 @@ impl ProfileV2 for MockProfile { } pub fn get_main_profile() -> Arc { - if indy_mocks_enabled() { - return Arc::new(MockProfile {}); - } Arc::new(GLOBAL_PROFILE.clone()) } diff --git a/libvcx_core/src/api_vcx/api_global/settings.rs b/libvcx_core/src/api_vcx/api_global/settings.rs deleted file mode 100644 index 61987ff73f..0000000000 --- a/libvcx_core/src/api_vcx/api_global/settings.rs +++ /dev/null @@ -1,23 +0,0 @@ -use aries_vcx::{ - agency_client::testing::mocking::enable_agency_mocks, - aries_vcx_core::wallet::indy::IssuerConfig, - global::{ - settings, - settings::{aries_vcx_enable_indy_mocks, init_issuer_config}, - }, -}; - -use crate::errors::{error::LibvcxResult, mapping_from_ariesvcx::map_ariesvcx_result}; - -pub fn enable_mocks() -> LibvcxResult<()> { - enable_agency_mocks(); - map_ariesvcx_result(aries_vcx_enable_indy_mocks()) -} - -pub fn get_config_value(key: &str) -> LibvcxResult { - map_ariesvcx_result(settings::get_config_value(key)) -} - -pub fn settings_init_issuer_config(issuer_config: &IssuerConfig) -> LibvcxResult<()> { - map_ariesvcx_result(init_issuer_config(&issuer_config.institution_did)) -} diff --git a/libvcx_core/src/api_vcx/api_global/state.rs b/libvcx_core/src/api_vcx/api_global/state.rs index 3c985b9cd8..075ecadfc9 100644 --- a/libvcx_core/src/api_vcx/api_global/state.rs +++ b/libvcx_core/src/api_vcx/api_global/state.rs @@ -1,5 +1,3 @@ -use aries_vcx::global::settings::reset_config_values_ariesvcx; - use crate::api_vcx::api_global::{ agency_client::reset_main_agency_client, pool::{close_main_pool, reset_ledger_components}, @@ -20,7 +18,6 @@ pub fn state_vcx_shutdown() { crate::api_vcx::api_handle::disclosed_proof::release_all(); crate::api_vcx::api_handle::credential::release_all(); - let _ = reset_config_values_ariesvcx(); reset_main_agency_client(); match reset_ledger_components() { Ok(_) => {} @@ -29,68 +26,3 @@ pub fn state_vcx_shutdown() { } } } - -#[cfg(test)] -pub mod tests { - use aries_vcx::utils::{ - devsetup::SetupMocks, - mockdata::{ - mockdata_credex::ARIES_CREDENTIAL_OFFER, - mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION, - }, - }; - - use crate::api_vcx::{ - api_global::{profile::get_main_wallet, state::state_vcx_shutdown}, - api_handle::{ - credential, credential::credential_create_with_offer, credential_def, disclosed_proof, - disclosed_proof::create_with_proof_request, issuer_credential, mediated_connection, - proof, schema, schema::create_and_publish_schema, - }, - }; - - #[tokio::test] - async fn test_shutdown() { - let _setup = SetupMocks::init(); - - let data = r#"["name","male"]"#; - let connection = - mediated_connection::test_utils::build_test_connection_inviter_invited().await; - let credential_def = credential_def::create( - "SID".to_string(), - "id".to_string(), - "tag".to_string(), - false, - ) - .await - .unwrap(); - let issuer_credential = - issuer_credential::issuer_credential_create("1".to_string()).unwrap(); - let proof = proof::create_proof( - "1".to_string(), - "[]".to_string(), - "[]".to_string(), - r#"{"support_revocation":false}"#.to_string(), - "Optional".to_owned(), - ) - .await - .unwrap(); - let schema = - create_and_publish_schema("5", "name".to_string(), "0.1".to_string(), data.to_string()) - .await - .unwrap(); - let disclosed_proof = - create_with_proof_request("id", ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); - let credential = credential_create_with_offer("name", ARIES_CREDENTIAL_OFFER).unwrap(); - - state_vcx_shutdown(); - assert!(!mediated_connection::is_valid_handle(connection)); - assert!(!issuer_credential::is_valid_handle(issuer_credential)); - assert!(!schema::is_valid_handle(schema)); - assert!(!proof::is_valid_handle(proof)); - assert!(!credential_def::is_valid_handle(credential_def)); - assert!(!credential::is_valid_handle(credential)); - assert!(!disclosed_proof::is_valid_handle(disclosed_proof)); - assert!(get_main_wallet().is_err()); - } -} diff --git a/libvcx_core/src/api_vcx/api_handle/credential.rs b/libvcx_core/src/api_vcx/api_handle/credential.rs index 98524c0da6..ccda8d71ec 100644 --- a/libvcx_core/src/api_vcx/api_handle/credential.rs +++ b/libvcx_core/src/api_vcx/api_handle/credential.rs @@ -1,6 +1,5 @@ use aries_vcx::{ agency_client::testing::mocking::AgencyMockDecrypted, - global::settings::indy_mocks_enabled, handlers::issuance::{holder::Holder, mediated_holder::holder_find_message_to_handle}, messages::{ msg_fields::protocols::cred_issuance::{ @@ -282,10 +281,6 @@ async fn get_credential_offer_msg(connection_handle: u32, msg_id: &str) -> Libvc msg_id ); - if indy_mocks_enabled() { - 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 { @@ -422,21 +417,19 @@ pub mod tests { mockdata_credex, mockdata_credex::{ ARIES_CREDENTIAL_OFFER, ARIES_CREDENTIAL_OFFER_JSON_FORMAT, - ARIES_CREDENTIAL_RESPONSE, CREDENTIAL_SM_FINISHED, + CREDENTIAL_SM_FINISHED, }, }, }, }; use super::*; - #[cfg(test)] - use crate::api_vcx::api_handle::credential::tests_utils::BAD_CREDENTIAL_OFFER; - use crate::api_vcx::api_handle::credential::{ - credential_create_with_offer, get_attributes, get_credential, send_credential_request, - }; - #[cfg(test)] - use crate::api_vcx::api_handle::mediated_connection::test_utils::{ - build_test_connection_invitee_completed, build_test_connection_inviter_requested, + use crate::api_vcx::api_handle::{ + credential::{ + credential_create_with_offer, get_attributes, get_credential, + tests_utils::BAD_CREDENTIAL_OFFER, + }, + mediated_connection::test_utils::build_test_connection_invitee_completed, }; async fn _get_offer(handle: u32) -> String { @@ -519,77 +512,6 @@ pub mod tests { assert_eq!(cred_original_serialized, cred_restored_serialized); } - #[tokio::test] - async fn full_credential_test() { - let _setup = SetupMocks::init(); - - info!("full_credential_test:: going to build_test_connection"); - let handle_conn = build_test_connection_inviter_requested().await; - - info!("full_credential_test:: going to _get_offer"); - let offer = _get_offer(handle_conn).await; - - info!("full_credential_test:: going to credential_create_with_offer"); - let handle_cred = credential_create_with_offer("TEST_CREDENTIAL", &offer).unwrap(); - assert_eq!( - HolderState::OfferReceived as u32, - get_state(handle_cred).unwrap() - ); - - info!("full_credential_test:: going get offered attributes from offer received state"); - let offer_attrs: String = get_attributes(handle_cred).unwrap(); - info!( - "full_credential_test:: obtained offered attributes: {}", - offer_attrs - ); - let offer_attrs: serde_json::Value = serde_json::from_str(&offer_attrs).unwrap(); - let offer_attrs_expected: serde_json::Value = - serde_json::from_str(mockdata_credex::OFFERED_ATTRIBUTES).unwrap(); - assert_eq!(offer_attrs, offer_attrs_expected); - - info!("full_credential_test:: going to send_credential_request"); - send_credential_request(handle_cred, handle_conn) - .await - .unwrap(); - assert_eq!( - HolderState::RequestSet as u32, - get_state(handle_cred).unwrap() - ); - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_CREDENTIAL_RESPONSE); - - info!("full_credential_test:: going to update_state, should receive credential"); - update_state(handle_cred, None, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_cred).unwrap(), - HolderState::Finished as u32 - ); - - info!("full_credential_test:: going to get_credential"); - let msg = get_credential(handle_cred).unwrap(); - info!("full_credential_test:: get_credential returned {}", msg); - let msg_value: serde_json::Value = serde_json::from_str(&msg).unwrap(); - - info!( - "full_credential_test:: going to deserialize credential: {:?}", - msg_value - ); - 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"); - let offer_attrs: String = get_attributes(handle_cred).unwrap(); - info!( - "full_credential_test:: obtained offered attributes: {}", - offer_attrs - ); - let offer_attrs: serde_json::Value = serde_json::from_str(&offer_attrs).unwrap(); - let offer_attrs_expected: serde_json::Value = - serde_json::from_str(mockdata_credex::OFFERED_ATTRIBUTES).unwrap(); - assert_eq!(offer_attrs, offer_attrs_expected); - } - #[tokio::test] async fn test_get_attributes_json_attach() { let _setup = SetupMocks::init(); diff --git a/libvcx_core/src/api_vcx/api_handle/credential_def.rs b/libvcx_core/src/api_vcx/api_handle/credential_def.rs index b8ef158e6c..600b9a3a74 100644 --- a/libvcx_core/src/api_vcx/api_handle/credential_def.rs +++ b/libvcx_core/src/api_vcx/api_handle/credential_def.rs @@ -1,17 +1,11 @@ -use aries_vcx::{ - common::primitives::credential_definition::{ - CredentialDef, CredentialDefConfigBuilder, PublicEntityStateType, - }, - global::settings::CONFIG_INSTITUTION_DID, +use aries_vcx::common::primitives::credential_definition::{ + CredentialDef, CredentialDefConfigBuilder, PublicEntityStateType, }; use crate::{ api_vcx::{ - api_global::{ - profile::{ - get_main_anoncreds, get_main_anoncreds_ledger_read, get_main_anoncreds_ledger_write, - }, - settings::get_config_value, + api_global::profile::{ + get_main_anoncreds, get_main_anoncreds_ledger_read, get_main_anoncreds_ledger_write, }, api_handle::object_cache::ObjectCache, }, @@ -24,12 +18,12 @@ lazy_static! { } pub async fn create( + issuer_did: String, source_id: String, schema_id: String, tag: String, support_revocation: bool, ) -> LibvcxResult { - let issuer_did = get_config_value(CONFIG_INSTITUTION_DID)?; let config = CredentialDefConfigBuilder::default() .issuer_did(issuer_did) .schema_id(schema_id) @@ -122,131 +116,27 @@ pub fn check_is_published(handle: u32) -> LibvcxResult { pub mod tests { use std::{thread::sleep, time::Duration}; - use aries_vcx::{ - global::settings::CONFIG_INSTITUTION_DID, - utils::{constants::SCHEMA_ID, devsetup::SetupMocks}, - }; + use aries_vcx::global::settings::DEFAULT_DID; - use super::*; - use crate::api_vcx::{ - api_global::settings::get_config_value, api_handle::schema, - utils::devsetup::SetupGlobalsWalletPoolAgency, - }; + use super::{create, publish}; + use crate::api_vcx::api_handle::schema; - #[tokio::test] - async fn test_vcx_credentialdef_release() { - let _setup = SetupMocks::init(); - let schema_handle = schema::test_utils::create_schema_real().await; - sleep(Duration::from_secs(1)); - - let schema_id = schema::get_schema_id(schema_handle).unwrap(); - let _issuer_did = get_config_value(CONFIG_INSTITUTION_DID).unwrap(); - let cred_def_handle = create("1".to_string(), schema_id, "tag_1".to_string(), false) - .await - .unwrap(); - release(cred_def_handle).unwrap(); - assert_eq!( - to_string(cred_def_handle).unwrap_err().kind, - LibvcxErrorKind::InvalidHandle - ) - } - - // TODO: Get rid of this - #[cfg(test)] pub async fn create_and_publish_nonrevocable_creddef() -> (u32, u32) { let schema_handle = schema::test_utils::create_schema_real().await; sleep(Duration::from_secs(1)); let schema_id = schema::get_schema_id(schema_handle).unwrap(); - let _issuer_did = get_config_value(CONFIG_INSTITUTION_DID).unwrap(); - let cred_def_handle = create("1".to_string(), schema_id, "tag_1".to_string(), false) - .await - .unwrap(); - - publish(cred_def_handle).await.unwrap(); - (schema_handle, cred_def_handle) - } - - #[tokio::test] - async fn test_create_cred_def() { - let _setup = SetupMocks::init(); - let (_, _) = create_and_publish_nonrevocable_creddef().await; - } - - #[tokio::test] - #[ignore] - async fn test_create_credential_def_real() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let (_, handle) = create_and_publish_nonrevocable_creddef().await; - - let _source_id = get_source_id(handle).unwrap(); - let _cred_def_id = get_cred_def_id(handle).unwrap(); - let _schema_json = to_string(handle).unwrap(); - }) - .await; - } - - #[tokio::test] - async fn test_to_string_succeeds() { - let _setup = SetupMocks::init(); - - let (_, cred_def_handle) = create_and_publish_nonrevocable_creddef().await; - - let credential_string = to_string(cred_def_handle).unwrap(); - let credential_values: serde_json::Value = - serde_json::from_str(&credential_string).unwrap(); - assert_eq!(credential_values["version"].clone(), "1.0"); - } - - #[tokio::test] - async fn test_from_string_succeeds() { - let _setup = SetupMocks::init(); - - let (_, cred_def_handle) = create_and_publish_nonrevocable_creddef().await; - let credentialdef_data = to_string(cred_def_handle).unwrap(); - assert!(!credentialdef_data.is_empty()); - release(cred_def_handle).unwrap(); - - let new_handle = from_string(&credentialdef_data).unwrap(); - let new_credentialdef_data = to_string(new_handle).unwrap(); - - let credentialdef1: CredentialDef = - CredentialDef::from_string(&credentialdef_data).unwrap(); - let credentialdef2: CredentialDef = - CredentialDef::from_string(&new_credentialdef_data).unwrap(); - - assert_eq!(credentialdef1, credentialdef2); - assert_eq!( - from_string("{}").unwrap_err().kind(), - LibvcxErrorKind::CreateCredDef - ); - } - - #[tokio::test] - async fn test_release_all() { - let _setup = SetupMocks::init(); - - let _issuer_did = String::from("4fUDR9R7fjwELRvH9JT6HH"); - let h1 = create( - "SourceId".to_string(), - SCHEMA_ID.to_string(), - "tag".to_string(), - false, - ) - .await - .unwrap(); - let h2 = create( - "SourceId".to_string(), - SCHEMA_ID.to_string(), - "tag".to_string(), + let cred_def_handle = create( + DEFAULT_DID.to_owned(), + "1".to_string(), + schema_id, + "tag_1".to_string(), false, ) .await .unwrap(); - release_all(); - - assert!(!is_valid_handle(h1)); - assert!(!is_valid_handle(h2)); + publish(cred_def_handle).await.unwrap(); + (schema_handle, cred_def_handle) } } diff --git a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs index 4c807e5c84..d41f9cc233 100644 --- a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs @@ -1,6 +1,4 @@ use aries_vcx::{ - agency_client::testing::mocking::AgencyMockDecrypted, - global::settings::indy_mocks_enabled, handlers::proof_presentation::{ mediated_prover::prover_find_message_to_handle, prover::Prover, }, @@ -8,10 +6,6 @@ use aries_vcx::{ msg_fields::protocols::present_proof::{request::RequestPresentation, PresentProof}, AriesMessage, }, - utils::{ - constants::GET_MESSAGES_DECRYPTED_RESPONSE, - mockdata::mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION, - }, }; use serde_json; @@ -278,11 +272,6 @@ pub fn get_thread_id(handle: u32) -> LibvcxResult { } async fn get_proof_request(connection_handle: u32, msg_id: &str) -> LibvcxResult { - if indy_mocks_enabled() { - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_PROOF_REQUEST_PRESENTATION); - } - let presentation_request = { trace!( "Prover::get_presentation_request >>> connection_handle: {:?}, msg_id: {:?}", @@ -349,29 +338,14 @@ mod tests { use aries_vcx::{ utils, utils::{ - constants::{ - ARIES_PROVER_CREDENTIALS, ARIES_PROVER_SELF_ATTESTED_ATTRS, - GET_MESSAGES_DECRYPTED_RESPONSE, - }, devsetup::{SetupDefaults, SetupMocks}, - mockdata::{ - mock_settings::MockBuilder, - mockdata_proof, - mockdata_proof::{ARIES_PROOF_PRESENTATION_ACK, ARIES_PROOF_REQUEST_PRESENTATION}, - }, + mockdata::mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION, }, }; use serde_json::Value; use super::*; - #[cfg(test)] - use crate::api_vcx::api_handle::mediated_connection::test_utils::{ - build_test_connection_invitee_completed, build_test_connection_inviter_requested, - }; - use crate::aries_vcx::{ - common::proofs::proof_request::PresentationRequestData, - protocols::proof_presentation::prover::state_machine::ProverState, - }; + use crate::aries_vcx::protocols::proof_presentation::prover::state_machine::ProverState; async fn _get_proof_request_messages(connection_h: u32) -> String { let requests = get_proof_request_messages(connection_h).await.unwrap(); @@ -408,116 +382,6 @@ mod tests { ); } - #[tokio::test] - async fn test_proof_cycle() { - let _setup = SetupMocks::init(); - - let connection_h = build_test_connection_inviter_requested().await; - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_PROOF_REQUEST_PRESENTATION); - - let request = _get_proof_request_messages(connection_h).await; - - let handle_proof = create_with_proof_request("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!( - ProverState::PresentationRequestReceived as u32, - get_state(handle_proof).unwrap() - ); - - let _mock_builder = - MockBuilder::init().set_mock_generate_indy_proof("{\"selected\":\"credentials\"}"); - - generate_proof(handle_proof, "{\"selected\":\"credentials\"}", "{}") - .await - .unwrap(); - send_proof(handle_proof, connection_h).await.unwrap(); - assert_eq!( - ProverState::PresentationSent as u32, - get_state(handle_proof).unwrap() - ); - - update_state( - handle_proof, - Some(ARIES_PROOF_PRESENTATION_ACK), - connection_h, - ) - .await - .unwrap(); - assert_eq!( - ProverState::Finished as u32, - get_state(handle_proof).unwrap() - ); - } - - #[tokio::test] - async fn test_proof_update_state_v2() { - let _setup = SetupMocks::init(); - - let connection_handle = build_test_connection_inviter_requested().await; - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(mockdata_proof::ARIES_PRESENTATION_REQUEST); - - let request = _get_proof_request_messages(connection_handle).await; - - let handle = create_with_proof_request("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!( - ProverState::PresentationRequestReceived as u32, - get_state(handle).unwrap() - ); - - generate_proof( - handle, - ARIES_PROVER_CREDENTIALS, - ARIES_PROVER_SELF_ATTESTED_ATTRS, - ) - .await - .unwrap(); - assert_eq!( - ProverState::PresentationPrepared as u32, - get_state(handle).unwrap() - ); - - send_proof(handle, connection_handle).await.unwrap(); - assert_eq!( - ProverState::PresentationSent as u32, - get_state(handle).unwrap() - ); - - mediated_connection::release(connection_handle).unwrap(); - let connection_handle = build_test_connection_inviter_requested().await; - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message( - mockdata_proof::ARIES_PROOF_PRESENTATION_ACK, - ); - - update_state(handle, None, connection_handle).await.unwrap(); - assert_eq!(ProverState::Finished as u32, get_state(handle).unwrap()); - } - - #[tokio::test] - async fn test_proof_reject_cycle() { - let _setup = SetupMocks::init(); - - let connection_h = build_test_connection_inviter_requested().await; - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_PROOF_REQUEST_PRESENTATION); - - let request = _get_proof_request_messages(connection_h).await; - - let handle = create_with_proof_request("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!( - ProverState::PresentationRequestReceived as u32, - get_state(handle).unwrap() - ); - - reject_proof(handle, connection_h).await.unwrap(); - assert_eq!(ProverState::Failed as u32, get_state(handle).unwrap()); - } - #[tokio::test] async fn get_state_test() { let _setup = SetupMocks::init(); @@ -553,16 +417,6 @@ mod tests { ); } - #[tokio::test] - async fn test_get_proof_request() { - let _setup = SetupMocks::init(); - - let connection_h = build_test_connection_invitee_completed(); - - let request = get_proof_request(connection_h, "123").await.unwrap(); - let _request: RequestPresentation = serde_json::from_str(&request).unwrap(); - } - #[tokio::test] async fn test_deserialize_succeeds_with_self_attest_allowed() { let _setup = SetupDefaults::init(); @@ -572,25 +426,4 @@ mod tests { let serialized = to_string(handle).unwrap(); from_string(&serialized).unwrap(); } - - #[tokio::test] - async fn test_get_proof_request_attachment() { - let _setup = SetupMocks::init(); - - let connection_h = build_test_connection_inviter_requested().await; - - AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_PROOF_REQUEST_PRESENTATION); - - let request = _get_proof_request_messages(connection_h).await; - - let handle = create_with_proof_request("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!( - ProverState::PresentationRequestReceived as u32, - get_state(handle).unwrap() - ); - - let attrs = get_proof_request_attachment(handle).unwrap(); - let _attrs: PresentationRequestData = serde_json::from_str(&attrs).unwrap(); - } } diff --git a/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs b/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs index 92e283fc58..cf48d11d56 100644 --- a/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs +++ b/libvcx_core/src/api_vcx/api_handle/issuer_credential.rs @@ -307,21 +307,9 @@ pub fn get_thread_id(handle: u32) -> LibvcxResult { #[cfg(test)] #[allow(clippy::unwrap_used)] pub mod tests { - use aries_vcx::utils::{ - constants::V3_OBJECT_SERIALIZE_VERSION, - devsetup::SetupMocks, - mockdata::{ - mockdata_credex::ARIES_CREDENTIAL_REQUEST, - mockdata_mediated_connection::ARIES_CONNECTION_ACK, - }, - }; + use aries_vcx::utils::{constants::V3_OBJECT_SERIALIZE_VERSION, devsetup::SetupMocks}; use super::*; - #[cfg(test)] - use crate::api_vcx::api_handle::credential_def::tests::create_and_publish_nonrevocable_creddef; - #[cfg(test)] - use crate::api_vcx::api_handle::mediated_connection::test_utils::build_test_connection_inviter_requested; - use crate::aries_vcx::protocols::issuance::issuer::state_machine::IssuerState; fn _issuer_credential_create() -> u32 { issuer_credential_create("1".to_string()).unwrap() @@ -359,27 +347,6 @@ pub mod tests { assert!(!string.is_empty()); } - #[tokio::test] - async fn test_send_credential_offer() { - let _setup = SetupMocks::init(); - - let connection_handle = build_test_connection_inviter_requested().await; - - let credential_handle = _issuer_credential_create(); - - let (_, cred_def_handle) = create_and_publish_nonrevocable_creddef().await; - build_credential_offer_msg_v2(credential_handle, cred_def_handle, 123, _cred_json(), None) - .await - .unwrap(); - send_credential_offer_v2(credential_handle, connection_handle) - .await - .unwrap(); - assert_eq!( - get_state(credential_handle).unwrap(), - u32::from(IssuerState::OfferSet) - ); - } - #[tokio::test] async fn test_from_string_succeeds() { let _setup = SetupMocks::init(); @@ -399,64 +366,6 @@ pub mod tests { assert_eq!(new_string, string); } - #[tokio::test] - async fn test_update_state_with_message() { - let _setup = SetupMocks::init(); - - let connection_handle = build_test_connection_inviter_requested().await; - let credential_handle = _issuer_credential_create(); - let (_, cred_def_handle) = create_and_publish_nonrevocable_creddef().await; - build_credential_offer_msg_v2(credential_handle, cred_def_handle, 1234, _cred_json(), None) - .await - .unwrap(); - send_credential_offer_v2(credential_handle, connection_handle) - .await - .unwrap(); - assert_eq!( - get_state(credential_handle).unwrap(), - u32::from(IssuerState::OfferSet) - ); - - update_state( - credential_handle, - Some(ARIES_CREDENTIAL_REQUEST), - connection_handle, - ) - .await - .unwrap(); - assert_eq!( - get_state(credential_handle).unwrap(), - u32::from(IssuerState::RequestReceived) - ); - } - - #[tokio::test] - async fn test_update_state_with_bad_message() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_cred = _issuer_credential_create(); - let (_, cred_def_handle) = create_and_publish_nonrevocable_creddef().await; - build_credential_offer_msg_v2(handle_cred, cred_def_handle, 1234, _cred_json(), None) - .await - .unwrap(); - send_credential_offer_v2(handle_cred, handle_conn) - .await - .unwrap(); - assert_eq!( - get_state(handle_cred).unwrap(), - u32::from(IssuerState::OfferSet) - ); - - // try to update state with nonsense message - let result = update_state(handle_cred, Some(ARIES_CONNECTION_ACK), handle_conn).await; - assert!(result.is_ok()); // todo: maybe we should rather return error if update_state doesn't progress state - assert_eq!( - get_state(handle_cred).unwrap(), - u32::from(IssuerState::OfferSet) - ); - } - #[tokio::test] async fn test_release_all() { let _setup = SetupMocks::init(); diff --git a/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs b/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs index f10693fc49..7ed7f93e0a 100644 --- a/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs +++ b/libvcx_core/src/api_vcx/api_handle/mediated_connection.rs @@ -534,23 +534,15 @@ pub mod test_utils { pub mod tests { use aries_vcx::{ self, - agency_client::testing::mocking::AgencyMockDecrypted, - messages::msg_fields::protocols::connection::invitation::InvitationContent, utils::{ constants, devsetup::{SetupEmpty, SetupMocks}, - mockdata::mockdata_mediated_connection::{ - ARIES_CONNECTION_ACK, ARIES_CONNECTION_INVITATION, ARIES_CONNECTION_REQUEST, - }, }, }; - use diddoc_legacy::aries::diddoc::test_utils::*; use serde_json::Value; use super::*; - #[cfg(test)] - use crate::api_vcx::api_handle::mediated_connection::test_utils::build_test_connection_inviter_invited; - use crate::api_vcx::{api_handle::mediated_connection, VcxStateType}; + use crate::api_vcx::VcxStateType; fn _setup() { let _setup = SetupEmpty::init(); @@ -560,152 +552,6 @@ pub mod tests { "test connection" } - #[tokio::test] - async fn test_vcx_connection_release() { - let _setup = SetupMocks::init(); - let handle = mediated_connection::create_connection(_source_id()) - .await - .unwrap(); - release(handle).unwrap(); - assert_eq!( - to_string(handle).unwrap_err().kind, - LibvcxErrorKind::InvalidHandle - ) - } - - #[tokio::test] - async fn test_create_connection_works() { - let _setup = SetupMocks::init(); - let connection_handle = mediated_connection::create_connection(_source_id()) - .await - .unwrap(); - assert!(mediated_connection::is_valid_handle(connection_handle)); - assert_eq!(0, mediated_connection::get_state(connection_handle)); - } - - #[tokio::test] - async fn test_create_connection_with_pairwise_invite() { - let _setup = SetupMocks::init(); - - let id = Uuid::new_v4().to_string(); - let content = InvitationContent::builder_pairwise() - .label(_label()) - .recipient_keys(_recipient_keys()) - .routing_keys(_routing_keys()) - .service_endpoint(_service_endpoint()) - .build(); - - let msg: AriesMessage = Invitation::builder().id(id).content(content).build(); - - let connection_handle = mediated_connection::create_connection_with_invite( - _source_id(), - &serde_json::to_string(&msg).unwrap(), - ) - .await - .unwrap(); - assert!(mediated_connection::is_valid_handle(connection_handle)); - assert_eq!(1, mediated_connection::get_state(connection_handle)); - } - - #[tokio::test] - async fn test_create_connection_with_public_invite() { - let _setup = SetupMocks::init(); - - let id = Uuid::new_v4().to_string(); - let content = InvitationContent::builder_public() - .label(_label()) - .did(_did()) - .build(); - let invitation: Invitation = Invitation::builder().id(id).content(content).build(); - let msg = AriesMessage::from(invitation); - - let connection_handle = mediated_connection::create_connection_with_invite( - _source_id(), - &serde_json::to_string(&msg).unwrap(), - ) - .await - .unwrap(); - assert!(mediated_connection::is_valid_handle(connection_handle)); - assert_eq!(1, mediated_connection::get_state(connection_handle)); - } - - #[tokio::test] - async fn test_get_connection_state_works() { - let _setup = SetupMocks::init(); - let connection_handle = mediated_connection::create_connection(_source_id()) - .await - .unwrap(); - assert_eq!(0, mediated_connection::get_state(connection_handle)); - } - - #[tokio::test] - async fn test_connection_delete() { - let _setup = SetupMocks::init(); - warn!(">> test_connection_delete going to create connection"); - let connection_handle = mediated_connection::create_connection(_source_id()) - .await - .unwrap(); - warn!(">> test_connection_delete checking is valid handle"); - assert!(mediated_connection::is_valid_handle(connection_handle)); - - mediated_connection::release(connection_handle).unwrap(); - assert!(!mediated_connection::is_valid_handle(connection_handle)); - } - - #[tokio::test] - async fn test_create_connection() { - let _setup = SetupMocks::init(); - - let handle = create_connection("test_create_connection").await.unwrap(); - assert_eq!(get_state(handle), VcxStateType::VcxStateNone as u32); - - connect(handle).await.unwrap(); - assert_eq!(get_pw_did(handle).unwrap(), constants::DID); - assert_eq!(get_pw_verkey(handle).unwrap(), constants::VERKEY); - - AgencyMockDecrypted::set_next_decrypted_response( - constants::GET_MESSAGES_DECRYPTED_RESPONSE, - ); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_CONNECTION_REQUEST); - update_state(handle).await.unwrap(); - assert_eq!( - get_state(handle), - VcxStateType::VcxStateRequestReceived as u32 - ); - - AgencyMockDecrypted::set_next_decrypted_response( - constants::GET_MESSAGES_DECRYPTED_RESPONSE, - ); - AgencyMockDecrypted::set_next_decrypted_message(ARIES_CONNECTION_ACK); - update_state(handle).await.unwrap(); - assert_eq!(get_state(handle), VcxStateType::VcxStateAccepted as u32); - - // This errors b/c we release handle in delete connection - assert!(release(handle).is_ok()); - } - - #[tokio::test] - async fn test_create_drop_create() { - let _setup = SetupMocks::init(); - - let handle = create_connection("test_create_drop_create").await.unwrap(); - - assert_eq!(get_state(handle), VcxStateType::VcxStateNone as u32); - let did1 = get_pw_did(handle).unwrap(); - - release(handle).unwrap(); - - let handle2 = create_connection("test_create_drop_create").await.unwrap(); - - assert_eq!(get_state(handle2), VcxStateType::VcxStateNone as u32); - let did2 = get_pw_did(handle2).unwrap(); - - assert_ne!(handle, handle2); - assert_eq!(did1, did2); - - release(handle2).unwrap(); - } - #[tokio::test] async fn test_get_state_fails() { let _setup = SetupEmpty::init(); @@ -722,101 +568,6 @@ pub mod tests { assert_eq!(rc.unwrap_err().kind(), LibvcxErrorKind::InvalidHandle); } - #[tokio::test] - async fn test_get_service_endpoint() { - let _setup = SetupMocks::init(); - - let handle = create_connection("test_get_qr_code_data").await.unwrap(); - - connect(handle).await.unwrap(); - - let details = get_invite_details(handle).unwrap(); - assert!(details.contains("\"serviceEndpoint\":")); - - assert_eq!( - get_invite_details(0).unwrap_err().kind(), - LibvcxErrorKind::InvalidConnectionHandle - ); - } - - #[tokio::test] - async fn test_retry_connection() { - let _setup = SetupMocks::init(); - - let handle = create_connection("test_serialize_deserialize") - .await - .unwrap(); - - assert_eq!(get_state(handle), VcxStateType::VcxStateNone as u32); - - connect(handle).await.unwrap(); - connect(handle).await.unwrap(); - } - - #[tokio::test] - async fn test_release_all() { - let _setup = SetupMocks::init(); - - let h1 = create_connection("rel1").await.unwrap(); - let h2 = create_connection("rel2").await.unwrap(); - let h3 = create_connection("rel3").await.unwrap(); - release_all(); - assert!(!is_valid_handle(h1)); - assert!(!is_valid_handle(h2)); - assert!(!is_valid_handle(h3)); - } - - #[tokio::test] - async fn test_create_with_valid_invite_details() { - let _setup = SetupMocks::init(); - - let handle = create_connection_with_invite("alice", ARIES_CONNECTION_INVITATION) - .await - .unwrap(); - connect(handle).await.unwrap(); - - let handle_2 = create_connection_with_invite("alice", ARIES_CONNECTION_INVITATION) - .await - .unwrap(); - connect(handle_2).await.unwrap(); - } - - #[tokio::test] - async fn test_process_acceptance_message() { - let _setup = SetupMocks::init(); - - let handle = create_connection("test_process_acceptance_message") - .await - .unwrap(); - update_state_with_message(handle, ARIES_CONNECTION_REQUEST) - .await - .unwrap(); - } - - // #[tokio::test] - // #[cfg(feature = "general_test")] - // async fn test_connection_handle_is_found() { - // let _setup = SetupMocks::init(); - // let handle = create_connection_with_invite("alice", - // ARIES_CONNECTION_INVITATION).await.unwrap(); - // - // CONNECTION_MAP.get_mut(handle, |_connection| { - // { Ok(()) }.boxed() - // }).await.unwrap(); - // } - - #[tokio::test] - async fn test_send_generic_message_fails_with_invalid_connection() { - let _setup = SetupMocks::init(); - - let handle = build_test_connection_inviter_invited().await; - - let err = send_generic_message(handle, "this is the message") - .await - .unwrap_err(); - assert_eq!(err.kind(), LibvcxErrorKind::NotReady); - } - #[test] fn test_generate_public_invitation() { let _setup = SetupMocks::init(); diff --git a/libvcx_core/src/api_vcx/api_handle/proof.rs b/libvcx_core/src/api_vcx/api_handle/proof.rs index dc0fd5178c..53aeed0367 100644 --- a/libvcx_core/src/api_vcx/api_handle/proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/proof.rs @@ -316,26 +316,13 @@ pub fn get_thread_id(handle: u32) -> LibvcxResult { #[cfg(test)] #[allow(clippy::unwrap_used)] pub mod tests { - use aries_vcx::{ - agency_client::testing::mocking::HttpClientMockResponse, - utils::{ - constants::{ - PROOF_REJECT_RESPONSE_STR_V2, REQUESTED_ATTRS, REQUESTED_PREDICATES, - V3_OBJECT_SERIALIZE_VERSION, - }, - devsetup::SetupMocks, - mockdata::{mock_settings::MockBuilder, mockdata_proof}, - }, + use aries_vcx::utils::{ + constants::{REQUESTED_ATTRS, REQUESTED_PREDICATES, V3_OBJECT_SERIALIZE_VERSION}, + devsetup::SetupMocks, }; use serde_json::Value; use super::*; - #[cfg(test)] - use crate::api_vcx::api_handle::mediated_connection::test_utils::build_test_connection_inviter_requested; - use crate::{ - api_vcx::api_handle::proof, - aries_vcx::protocols::proof_presentation::verifier::state_machine::VerifierState, - }; async fn create_default_proof() -> u32 { create_proof( @@ -420,20 +407,6 @@ pub mod tests { assert!(!is_valid_handle(handle)); } - #[tokio::test] - async fn test_send_proof_request() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - - let handle_proof = create_default_proof().await; - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - } - #[tokio::test] async fn test_get_proof_fails_with_no_proof() { let _setup = SetupMocks::init(); @@ -443,160 +416,6 @@ pub mod tests { assert!(get_presentation_msg(handle).is_err()) } - #[tokio::test] - async fn test_proof_update_state_v2() { - let _setup = SetupMocks::init(); - let _mock_builder = MockBuilder::init().set_mock_result_for_validate_indy_proof(Ok(true)); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - - mediated_connection::release(handle_conn).unwrap(); - let handle_conn = build_test_connection_inviter_requested().await; - - update_state( - handle_proof, - Some(mockdata_proof::ARIES_PROOF_PRESENTATION), - handle_conn, - ) - .await - .unwrap(); - - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::Finished as u32 - ); - } - - #[tokio::test] - async fn test_update_state() { - let _setup = SetupMocks::init(); - let _mock_builder = MockBuilder::init().set_mock_result_for_validate_indy_proof(Ok(true)); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - - update_state( - handle_proof, - Some(mockdata_proof::ARIES_PROOF_PRESENTATION), - handle_conn, - ) - .await - .unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::Finished as u32 - ); - } - - #[tokio::test] - async fn test_proof_validation_with_predicate() { - let _setup = SetupMocks::init(); - let _mock_builder = MockBuilder::init().set_mock_result_for_validate_indy_proof(Ok(true)); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - - update_state( - handle_proof, - Some(mockdata_proof::ARIES_PROOF_PRESENTATION), - handle_conn, - ) - .await - .unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::Finished as u32 - ); - } - - #[tokio::test] - async fn test_update_state_with_reject_message() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - - update_state( - handle_proof, - Some(PROOF_REJECT_RESPONSE_STR_V2), - handle_conn, - ) - .await - .unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::Failed as u32 - ); - } - - #[tokio::test] - async fn test_send_presentation_request() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - } - - #[tokio::test] - async fn test_get_proof() { - let _setup = SetupMocks::init(); - let _mock_builder = MockBuilder::init().set_mock_result_for_validate_indy_proof(Ok(true)); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - - update_state( - handle_proof, - Some(mockdata_proof::ARIES_PROOF_PRESENTATION), - handle_conn, - ) - .await - .unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::Finished as u32 - ); - - let proof_str = get_presentation_msg(handle_proof).unwrap(); - assert_eq!( - proof_str, - mockdata_proof::ARIES_PROOF_PRESENTATION.replace(['\n', ' '], "") - ); - } - #[tokio::test] async fn test_release_all() { let _setup = SetupMocks::init(); @@ -633,110 +452,4 @@ pub mod tests { assert!(!is_valid_handle(h2)); assert!(!is_valid_handle(h3)); } - - #[tokio::test] - async fn test_send_proof_request_can_be_retried() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - let _request = get_presentation_request_msg(handle_proof).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), 1); - - HttpClientMockResponse::set_next_response( - aries_vcx::agency_client::errors::error::AgencyClientResult::Err( - aries_vcx::agency_client::errors::error::AgencyClientError::from_msg( - aries_vcx::agency_client::errors::error::AgencyClientErrorKind::IOError, - "Sending message timeout.", - ), - ), - ); - assert_eq!( - send_proof_request(handle_proof, handle_conn) - .await - .unwrap_err() - .kind(), - LibvcxErrorKind::IOError - ); - assert_eq!(get_state(handle_proof).unwrap(), 1); - - // Retry sending proof request - send_proof_request(handle_proof, handle_conn).await.unwrap(); - assert_eq!( - get_state(handle_proof).unwrap(), - VerifierState::PresentationRequestSent as u32 - ); - } - - #[tokio::test] - async fn test_proof_accepted() { - let _setup = SetupMocks::init(); - let _mock_builder = MockBuilder::init().set_mock_result_for_validate_indy_proof(Ok(true)); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - let _request = get_presentation_request_msg(handle_proof).unwrap(); - send_proof_request(handle_proof, handle_conn).await.unwrap(); - update_state( - handle_proof, - Some(mockdata_proof::ARIES_PROOF_PRESENTATION), - handle_conn, - ) - .await - .unwrap(); - assert_eq!( - proof::get_state(handle_proof).unwrap(), - VerifierState::Finished as u32 - ); - } - - #[tokio::test] - async fn test_proof_errors() { - let _setup = SetupMocks::init(); - - let handle_conn = build_test_connection_inviter_requested().await; - let handle_proof = create_default_proof().await; - - let bad_handle = 100000; - let empty = r#""#; - - assert_eq!( - send_proof_request(bad_handle, handle_conn) - .await - .unwrap_err() - .kind(), - LibvcxErrorKind::InvalidHandle - ); - assert_eq!( - get_verification_status(handle_proof).unwrap(), - VcxPresentationVerificationStatus::Unavailable - ); - assert_eq!( - create_proof( - "my source id".to_string(), - empty.to_string(), - "{}".to_string(), - r#"{"support_revocation":false}"#.to_string(), - "my name".to_string(), - ) - .await - .unwrap_err() - .kind(), - LibvcxErrorKind::InvalidJson - ); - assert_eq!( - to_string(bad_handle).unwrap_err().kind(), - LibvcxErrorKind::InvalidHandle - ); - assert_eq!( - get_source_id(bad_handle).unwrap_err().kind(), - LibvcxErrorKind::InvalidHandle - ); - assert_eq!( - from_string(empty).unwrap_err().kind(), - LibvcxErrorKind::InvalidJson - ); - } } diff --git a/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs b/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs index c82c02ee2d..5c14367363 100644 --- a/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs +++ b/libvcx_core/src/api_vcx/api_handle/revocation_registry.rs @@ -1,14 +1,10 @@ -use aries_vcx::{ - common::primitives::revocation_registry::{RevocationRegistry, RevocationRegistryDefinition}, - global::settings::CONFIG_INSTITUTION_DID, +use aries_vcx::common::primitives::revocation_registry::{ + RevocationRegistry, RevocationRegistryDefinition, }; use crate::{ api_vcx::{ - api_global::{ - profile::{get_main_anoncreds, get_main_anoncreds_ledger_write}, - settings::get_config_value, - }, + api_global::profile::{get_main_anoncreds, get_main_anoncreds_ledger_write}, api_handle::object_cache::ObjectCache, }, errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}, @@ -57,14 +53,13 @@ pub async fn publish(handle: u32, tails_url: &str) -> LibvcxResult { Ok(handle) } -pub async fn publish_revocations(handle: u32) -> LibvcxResult<()> { - let submitter_did = get_config_value(CONFIG_INSTITUTION_DID)?; +pub async fn publish_revocations(handle: u32, submitter_did: &str) -> LibvcxResult<()> { let rev_reg = REV_REG_MAP.get_cloned(handle)?; rev_reg .publish_local_revocations( &get_main_anoncreds()?, &get_main_anoncreds_ledger_write()?, - &submitter_did, + submitter_did, ) .await?; diff --git a/libvcx_core/src/api_vcx/api_handle/schema.rs b/libvcx_core/src/api_vcx/api_handle/schema.rs index 84eecfa5d3..5f914cfce5 100644 --- a/libvcx_core/src/api_vcx/api_handle/schema.rs +++ b/libvcx_core/src/api_vcx/api_handle/schema.rs @@ -1,17 +1,12 @@ use std::string::ToString; -use aries_vcx::{ - common::primitives::credential_schema::Schema, global::settings::CONFIG_INSTITUTION_DID, -}; +use aries_vcx::common::primitives::credential_schema::Schema; use serde_json; use crate::{ api_vcx::{ - api_global::{ - profile::{ - get_main_anoncreds, get_main_anoncreds_ledger_read, get_main_anoncreds_ledger_write, - }, - settings::get_config_value, + api_global::profile::{ + get_main_anoncreds, get_main_anoncreds_ledger_read, get_main_anoncreds_ledger_write, }, api_handle::object_cache::ObjectCache, }, @@ -23,13 +18,12 @@ lazy_static! { } pub async fn create_and_publish_schema( + issuer_did: &str, source_id: &str, name: String, version: String, data: String, ) -> LibvcxResult { - let issuer_did = get_config_value(CONFIG_INSTITUTION_DID)?; - trace!( "create_new_schema >>> source_id: {}, issuer_did: {}, name: {}, version: {}, data: {}", source_id, @@ -52,7 +46,7 @@ pub async fn create_and_publish_schema( let schema = Schema::create( &get_main_anoncreds()?, source_id, - &issuer_did, + issuer_did, &name, &version, &data, @@ -119,10 +113,10 @@ pub fn get_state(handle: u32) -> LibvcxResult { #[allow(clippy::unwrap_used)] pub mod test_utils { + use aries_vcx::global::settings::DEFAULT_DID; use rand::Rng; use super::*; - use crate::api_vcx::api_global::settings::get_config_value; pub fn prepare_schema_data() -> (String, String, String, String) { let data = json!(data()).to_string(); @@ -132,7 +126,7 @@ pub mod test_utils { rand::thread_rng().gen::(), rand::thread_rng().gen::() ); - let did = get_config_value(CONFIG_INSTITUTION_DID).unwrap(); + let did = DEFAULT_DID.to_owned(); (did, schema_name, schema_version, data) } @@ -140,7 +134,7 @@ pub mod test_utils { // TODO: Reuse test utils code and data pub async fn create_schema_real() -> u32 { let (_did, schema_name, schema_version, data) = prepare_schema_data(); - create_and_publish_schema("id", schema_name, schema_version, data) + create_and_publish_schema(DEFAULT_DID, "id", schema_name, schema_version, data) .await .unwrap() } @@ -173,127 +167,28 @@ pub mod test_utils { #[cfg(test)] pub mod tests { use aries_vcx::{ - global::settings::{set_config_value, DEFAULT_DID}, - utils::devsetup::{SetupDefaults, SetupEmpty, SetupMocks}, + global::settings::DEFAULT_DID, + utils::devsetup::{SetupDefaults, SetupEmpty}, }; use super::*; - use crate::api_vcx::{ - api_handle::{ - schema, - schema::test_utils::{create_schema_real, prepare_schema_data}, - }, - utils::devsetup::SetupGlobalsWalletPoolAgency, - }; - - #[tokio::test] - async fn test_vcx_schema_release() { - let _setup = SetupMocks::init(); - - let (_did, schema_name, schema_version, data) = prepare_schema_data(); - let handle = create_and_publish_schema( - "test_create_schema_success", - schema_name, - schema_version, - data.clone(), - ) - .await - .unwrap(); - release(handle).unwrap(); - assert_eq!( - to_string(handle).unwrap_err().kind, - LibvcxErrorKind::InvalidHandle - ) - } #[tokio::test] - async fn test_create_schema_success() { - let _setup = SetupMocks::init(); + async fn test_create_schema_fails() { + let _setup = SetupDefaults::init(); - let (_did, schema_name, schema_version, data) = prepare_schema_data(); - create_and_publish_schema( - "test_create_schema_success", - schema_name, - schema_version, - data, + let err = create_and_publish_schema( + DEFAULT_DID, + "1", + "name".to_string(), + "1.0".to_string(), + "".to_string(), ) .await - .unwrap(); - } - - #[tokio::test] - async fn test_create_schema_fails() { - let _setup = SetupDefaults::init(); - set_config_value(CONFIG_INSTITUTION_DID, DEFAULT_DID).unwrap(); - let err = - create_and_publish_schema("1", "name".to_string(), "1.0".to_string(), "".to_string()) - .await - .unwrap_err(); + .unwrap_err(); assert_eq!(err.kind(), LibvcxErrorKind::SerializationError) } - #[tokio::test] - #[ignore] - async fn test_create_schema_with_pool() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let handle = create_schema_real().await; - - let _source_id = get_source_id(handle).unwrap(); - let _schema_id = get_schema_id(handle).unwrap(); - let _schema_json = to_string(handle).unwrap(); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_create_duplicate_fails() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let (_did, schema_name, schema_version, data) = prepare_schema_data(); - - create_and_publish_schema( - "id", - schema_name.clone(), - schema_version.clone(), - data.clone(), - ) - .await - .unwrap(); - - let err = create_and_publish_schema("id_2", schema_name, schema_version, data) - .await - .unwrap_err(); - error!("err: {:?}", err); - // .unwrap_err(); - - assert_eq!(err.kind(), LibvcxErrorKind::DuplicationSchema); - }) - .await; - } - - #[tokio::test] - async fn test_release_all() { - let _setup = SetupMocks::init(); - - let (_did, schema_name, version, data) = prepare_schema_data(); - - let h1 = create_and_publish_schema("1", schema_name.clone(), version.clone(), data.clone()) - .await - .unwrap(); - let h2 = create_and_publish_schema("2", schema_name.clone(), version.clone(), data.clone()) - .await - .unwrap(); - let h3 = create_and_publish_schema("3", schema_name.clone(), version.clone(), data.clone()) - .await - .unwrap(); - - release_all(); - - assert!(!is_valid_handle(h1)); - assert!(!is_valid_handle(h2)); - assert!(!is_valid_handle(h3)); - } - #[test] fn test_handle_errors() { let _setup = SetupEmpty::init(); @@ -303,54 +198,4 @@ pub mod tests { LibvcxErrorKind::InvalidHandle ); } - - #[tokio::test] - #[ignore] - async fn test_vcx_schema_get_state_with_ledger() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let handle = create_schema_real().await; - assert_eq!(1, get_state(handle).unwrap()); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_vcx_create_schema_with_pool() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let (_issuer_did, schema_name, schema_version, schema_data) = prepare_schema_data(); - let _schema_handle = schema::create_and_publish_schema( - "source_id", - schema_name, - schema_version, - schema_data, - ) - .await - .unwrap(); - }) - .await; - } - - #[tokio::test] - #[ignore] - async fn test_vcx_schema_serialize_contains_version() { - SetupGlobalsWalletPoolAgency::run(|_setup| async move { - let (_issuer_did, schema_name, schema_version, schema_data) = prepare_schema_data(); - let schema_handle = schema::create_and_publish_schema( - "source_id", - schema_name, - schema_version, - schema_data, - ) - .await - .unwrap(); - - let schema_json = schema::to_string(schema_handle).unwrap(); - - let j: serde_json::Value = serde_json::from_str(&schema_json).unwrap(); - let _schema: Schema = serde_json::from_value(j["data"].clone()).unwrap(); - assert_eq!(j["version"], "1.0"); - }) - .await; - } } diff --git a/libvcx_core/src/api_vcx/utils/devsetup.rs b/libvcx_core/src/api_vcx/utils/devsetup.rs index a68cc888fe..82de7e8f3b 100644 --- a/libvcx_core/src/api_vcx/utils/devsetup.rs +++ b/libvcx_core/src/api_vcx/utils/devsetup.rs @@ -9,10 +9,7 @@ use aries_vcx::{ }, WalletHandle, }, - global::settings::{ - self, init_issuer_config, set_config_value, CONFIG_INSTITUTION_DID, DEFAULT_DID, - DEFAULT_GENESIS_PATH, - }, + global::settings::{self, DEFAULT_GENESIS_PATH}, utils::devsetup::{init_test_logging, reset_global_state}, }; @@ -37,7 +34,6 @@ async fn dev_setup_issuer_wallet_and_agency_client() -> (String, WalletHandle) { let config_issuer = wallet_configure_issuer(wallet_handle, enterprise_seed) .await .unwrap(); - init_issuer_config(&config_issuer.institution_did).unwrap(); (config_issuer.institution_did, wallet_handle) } @@ -51,7 +47,6 @@ impl SetupGlobalsWalletPoolAgency { pub async fn init() -> SetupGlobalsWalletPoolAgency { reset_global_state(); init_test_logging(); - set_config_value(CONFIG_INSTITUTION_DID, DEFAULT_DID).unwrap(); let (institution_did, wallet_handle) = dev_setup_issuer_wallet_and_agency_client().await; SetupGlobalsWalletPoolAgency { institution_did, diff --git a/uniffi_aries_vcx/core/src/core/profile.rs b/uniffi_aries_vcx/core/src/core/profile.rs index 6aac15bdbd..24d877555c 100644 --- a/uniffi_aries_vcx/core/src/core/profile.rs +++ b/uniffi_aries_vcx/core/src/core/profile.rs @@ -6,7 +6,7 @@ use aries_vcx::{ ledger::base_ledger::TxnAuthrAgrmtOptions, wallet::indy::{wallet::create_and_open_wallet, IndySdkWallet, WalletConfig}, }, - core::profile::profile::Profile, + core::profile::Profile, errors::error::{AriesVcxError, AriesVcxErrorKind, VcxResult}, utils::mockdata::profile::mock_ledger::MockLedger, }; diff --git a/uniffi_aries_vcx/core/src/core/unpack_message.rs b/uniffi_aries_vcx/core/src/core/unpack_message.rs index 691d6e0cd4..5c5673119f 100644 --- a/uniffi_aries_vcx/core/src/core/unpack_message.rs +++ b/uniffi_aries_vcx/core/src/core/unpack_message.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use aries_vcx::{ aries_vcx_core::wallet::{base_wallet::BaseWallet, structs_io::UnpackMessageOutput}, - core::profile::profile::Profile, + core::profile::Profile, }; use super::profile::ProfileHolder; diff --git a/uniffi_aries_vcx/core/src/handlers/connection.rs b/uniffi_aries_vcx/core/src/handlers/connection.rs index a39e8f20b5..48aec88c46 100644 --- a/uniffi_aries_vcx/core/src/handlers/connection.rs +++ b/uniffi_aries_vcx/core/src/handlers/connection.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Mutex}; use aries_vcx::{ - core::profile::profile::Profile, + core::profile::Profile, errors::error::{AriesVcxError, AriesVcxErrorKind}, protocols::connection::{ pairwise_info::PairwiseInfo, Connection as VcxConnection, diff --git a/wrappers/node/src/api/credential-def.ts b/wrappers/node/src/api/credential-def.ts index 9bf9d79492..8660d84cc6 100644 --- a/wrappers/node/src/api/credential-def.ts +++ b/wrappers/node/src/api/credential-def.ts @@ -4,6 +4,7 @@ import { VcxBase } from './vcx-base'; import { VCXInternalError } from '../errors'; export interface ICredentialDefCreateDataV2 { + issuerDid: string; sourceId: string; schemaId: string; supportRevocation: boolean; @@ -44,6 +45,7 @@ export enum CredentialDefState { export class CredentialDef extends VcxBase { public static async create({ + issuerDid, supportRevocation, schemaId, sourceId, @@ -51,7 +53,7 @@ export class CredentialDef extends VcxBase { }: ICredentialDefCreateDataV2): Promise { try { const credentialDef = new CredentialDef({ schemaId }); - const handle = await ffi.credentialdefCreateV2(sourceId, schemaId, tag, supportRevocation); + const handle = await ffi.credentialdefCreateV2(issuerDid, sourceId, schemaId, tag, supportRevocation); credentialDef._setHandle(handle); return credentialDef; } catch (err: any) { diff --git a/wrappers/node/src/api/init.ts b/wrappers/node/src/api/init.ts index 8b26891b23..e0ba3b72b5 100644 --- a/wrappers/node/src/api/init.ts +++ b/wrappers/node/src/api/init.ts @@ -9,22 +9,10 @@ export function createAgencyClientForMainWallet(config: object): void { } } -export async function initIssuerConfig(config: object): Promise { - try { - return await ffiNapi.vcxInitIssuerConfig(JSON.stringify(config)); - } catch (err: any) { - throw new VCXInternalError(err); - } -} - export async function openMainPool(config: object): Promise { try { return await ffiNapi.openMainPool(JSON.stringify(config)); } catch (err: any) { throw new VCXInternalError(err); } -} - -export function enableMocks(): void { - return ffiNapi.enableMocks(); -} +} \ No newline at end of file diff --git a/wrappers/node/src/api/revocation-registry.ts b/wrappers/node/src/api/revocation-registry.ts index 63fcc3fdb4..5d59b0930c 100644 --- a/wrappers/node/src/api/revocation-registry.ts +++ b/wrappers/node/src/api/revocation-registry.ts @@ -63,9 +63,9 @@ export class RevocationRegistry extends VcxBase { } } - public async publishRevocations(): Promise { + public async publishRevocations(submittderDid: string): Promise { try { - await ffi.revocationRegistryPublishRevocations(this.handle); + await ffi.revocationRegistryPublishRevocations(this.handle, submittderDid); } catch (err: any) { throw new VCXInternalError(err); } diff --git a/wrappers/node/src/api/schema.ts b/wrappers/node/src/api/schema.ts index 5e1456f736..74dcc7de17 100644 --- a/wrappers/node/src/api/schema.ts +++ b/wrappers/node/src/api/schema.ts @@ -70,10 +70,11 @@ export class Schema extends VcxBase { return this._name; } - public static async create({ data, sourceId }: ISchemaCreateData): Promise { + public static async create({ data, sourceId }: ISchemaCreateData, issuerDid: string): Promise { try { const schema = new Schema({ name: data.name, schemaId: '', schemaAttrs: data }); const handle = await ffi.schemaCreate( + issuerDid, sourceId, schema._name, data.version, diff --git a/wrappers/node/test/helpers/entities.ts b/wrappers/node/test/helpers/entities.ts index 8cb142123b..878ccdd753 100644 --- a/wrappers/node/test/helpers/entities.ts +++ b/wrappers/node/test/helpers/entities.ts @@ -2,26 +2,26 @@ import '../module-resolver-helper'; import { assert } from 'chai'; import { - ARIES_CREDENTIAL_OFFER, - ARIES_PROOF_REQUEST, - Connection, - Credential, - CredentialDef, - DisclosedProof, - IConnectionCreateData, - ICredentialCreateWithOffer, - ICredentialDefCreateDataV2, - IDisclosedProofCreateData, - IIssuerCredentialBuildOfferDataV2, - IProofCreateData, IProofCreateDataV2, - ISchemaCreateData, - IssuerCredential, - Proof, - RevocationRegistry, - Schema, + ARIES_CREDENTIAL_OFFER, + ARIES_PROOF_REQUEST, + Connection, + Credential, + CredentialDef, + DisclosedProof, + IConnectionCreateData, + ICredentialCreateWithOffer, + ICredentialDefCreateDataV2, + IDisclosedProofCreateData, + IIssuerCredentialBuildOfferDataV2, + IProofCreateData, IProofCreateDataV2, + ISchemaCreateData, + IssuerCredential, + Proof, + RevocationRegistry, + Schema, } from 'src'; import * as uuid from 'uuid'; -import { ARIES_CONNECTION_ACK, ARIES_CONNECTION_REQUEST } from './mockdata'; +import { ARIES_CONNECTION_ACK, ARIES_CONNECTION_REQUEST, ARIES_ISSUER_DID } from './mockdata'; export const dataConnectionCreate = (): IConnectionCreateData => ({ id: `testConnectionId-${uuid.v4()}`, @@ -60,6 +60,7 @@ export const createConnectionInviterFinished = async ( }; export const dataCredentialDefCreate = (): ICredentialDefCreateDataV2 => ({ + issuerDid: ARIES_ISSUER_DID, schemaId: 'testCredentialDefSchemaId', sourceId: 'testCredentialDefSourceId', supportRevocation: true, @@ -165,7 +166,7 @@ export const dataProofCreate = (): IProofCreateDataV2 => ({ ref3: { names: ['attr3', 'attr4'] }, }, name: 'Proof', - preds: { pred1: { name: 'pred1', p_type: 'GE', p_value: 123 }}, + preds: { pred1: { name: 'pred1', p_type: 'GE', p_value: 123 } }, revocationInterval: { from: undefined, to: undefined, @@ -189,7 +190,7 @@ export const dataSchemaCreate = (): ISchemaCreateData => ({ }); export const schemaCreate = async (data = dataSchemaCreate()): Promise => { - const schema = await Schema.create(data); + const schema = await Schema.create(data, ARIES_ISSUER_DID); assert.notEqual(schema.handle, undefined); assert.equal(schema.name, data.data.name); assert.deepEqual(schema.schemaAttrs, data.data); diff --git a/wrappers/node/test/helpers/mockdata.ts b/wrappers/node/test/helpers/mockdata.ts index 81c786f6a3..4fc24317d3 100644 --- a/wrappers/node/test/helpers/mockdata.ts +++ b/wrappers/node/test/helpers/mockdata.ts @@ -1,3 +1,5 @@ +export const ARIES_ISSUER_DID = "2hoqvcwupRTUNkXn6ArYzs"; + export const ARIES_PING = { '@type': 'https://didcomm.org/trust_ping/1.0/ping', '@id': '518be002-de8e-456e-b3d5-8fe472477a86', diff --git a/wrappers/node/test/helpers/utils.ts b/wrappers/node/test/helpers/utils.ts index 372aa91f2b..4c517a3595 100644 --- a/wrappers/node/test/helpers/utils.ts +++ b/wrappers/node/test/helpers/utils.ts @@ -34,12 +34,6 @@ function generateWalletConfig() { }; } -export async function initVcxTestMode(): Promise { - const institution_did = await initVcx(); - vcx.enableMocks(); - return institution_did -} - export async function initVcx(): Promise { const rustLogPattern = process.env.RUST_LOG || 'vcx=error'; vcx.defaultLogger(rustLogPattern); @@ -50,9 +44,7 @@ export async function initVcx(): Promise { const issuerConfig = { institution_did, }; - await vcx.initIssuerConfig(issuerConfig); vcx.createAgencyClientForMainWallet(configAgency); - vcx.enableMocks(); return institution_did } diff --git a/wrappers/node/test/integration/ledger.test.ts b/wrappers/node/test/integration/ledger.test.ts index fb32cf1a04..c86162145b 100644 --- a/wrappers/node/test/integration/ledger.test.ts +++ b/wrappers/node/test/integration/ledger.test.ts @@ -1,10 +1,10 @@ import '../module-resolver-helper'; import * as path from 'path'; -import {createAndStoreDid, openMainPool, shutdownVcx, writeEndorserDid} from 'src'; -import { initVcx, initVcxTestMode } from '../helpers/utils'; +import { createAndStoreDid, openMainPool, shutdownVcx, writeEndorserDid } from 'src'; +import { initVcx } from '../helpers/utils'; import { expect } from 'chai'; -const seed = '1234567890123456789012'; +const seed = '00000LookAtMeIAmARandomSeed00000'; // @ts-ignore let publicDid: string; @@ -24,8 +24,8 @@ describe('wallet', () => { const genesisPath = path.join(__dirname, '/../../resources/localhost.txn'); await openMainPool({ genesis_path: genesisPath }); const pwInfo = await createAndStoreDid(seed); - expect(pwInfo.pw_did).equal('FhrSrYtQcw3p9xwf7NYemf'); - expect(pwInfo.pw_vk).equal('91qMFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE'); + expect(pwInfo.pw_did).equal('WSM9V5siLPUbx4BNnLH6Fj'); + expect(pwInfo.pw_vk).equal('H3Zchkv2nSYRZTVL66rhLnwJF9veJCYAm5eeBPoANyTH'); }); it('write new endorser did', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-connection.test.ts b/wrappers/node/test/suite1/ariesvcx-connection.test.ts index bb78907e48..25f7b290af 100644 --- a/wrappers/node/test/suite1/ariesvcx-connection.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-connection.test.ts @@ -1,17 +1,17 @@ import '../module-resolver-helper'; import { assert, expect } from 'chai'; -import { initVcxTestMode } from 'helpers/utils'; -import {ConnectionStateType } from 'src'; +import { initVcx } from 'helpers/utils'; +import { ConnectionStateType } from 'src'; import { NonmediatedConnection } from 'src'; describe('Nonmediated connection:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create invitation:', () => { it('success', async () => { const serviceEndpoint = 'http://localhost:8080/'; - const routingKeys = [ 'routingKey' ]; + const routingKeys = ['routingKey']; const connection = await NonmediatedConnection.createInviter(); assert.equal(connection.getState(), ConnectionStateType.Initial); diff --git a/wrappers/node/test/suite1/ariesvcx-credential-def.test.ts b/wrappers/node/test/suite1/ariesvcx-credential-def.test.ts index 2fab19ec15..6eeb3824f1 100644 --- a/wrappers/node/test/suite1/ariesvcx-credential-def.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-credential-def.test.ts @@ -2,11 +2,11 @@ import '../module-resolver-helper'; import { assert } from 'chai'; import { credentialDefCreate } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { CredentialDef, VCXCode } from 'src'; describe('CredentialDef:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-credential.test.ts b/wrappers/node/test/suite1/ariesvcx-credential.test.ts index d49bbfd63f..a08933670d 100644 --- a/wrappers/node/test/suite1/ariesvcx-credential.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-credential.test.ts @@ -6,11 +6,11 @@ import { credentialCreateWithOffer, dataCredentialCreateWithOffer, } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { Credential, HolderStateType, VCXCode } from 'src'; describe('Credential:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts b/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts index 5f8f7a3d82..24c3ce1990 100644 --- a/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts @@ -6,11 +6,11 @@ import { dataDisclosedProofCreateWithRequest, disclosedProofCreateWithRequest, } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { DisclosedProof, ProverStateType, VCXCode } from 'src'; describe('DisclosedProof', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success1', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts b/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts index 3630100142..8d2e677b56 100644 --- a/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts @@ -7,11 +7,11 @@ import { dataCredentialCreateWithOffer, issuerCredentialCreate, } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { Connection, Credential, IssuerCredential, IssuerStateType, VCXCode } from 'src'; describe('IssuerCredential:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-mediated-connection.test.ts b/wrappers/node/test/suite1/ariesvcx-mediated-connection.test.ts index 6658a12b9e..ff0a27e231 100644 --- a/wrappers/node/test/suite1/ariesvcx-mediated-connection.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-mediated-connection.test.ts @@ -8,12 +8,12 @@ import { createConnectionInviterRequested, dataConnectionCreate, } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { Connection, MediatedConnectionStateType, VCXCode } from 'src'; import { ARIES_PING, ARIES_PING_RESPONSE } from '../helpers/mockdata'; describe('Connection:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-oob.test.ts b/wrappers/node/test/suite1/ariesvcx-oob.test.ts index 6b6a5cc0bd..d87f671d08 100644 --- a/wrappers/node/test/suite1/ariesvcx-oob.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-oob.test.ts @@ -1,6 +1,6 @@ import '../module-resolver-helper'; -import { initVcxTestMode } from 'helpers/utils'; +import { initVcx } from 'helpers/utils'; import { GoalCode, OutOfBandSender, OutOfBandReceiver, HandshakeProtocol } from 'src'; import { assert } from 'chai'; @@ -28,7 +28,7 @@ const credentialOffer = { }; describe('Out of Band:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-proof.test.ts b/wrappers/node/test/suite1/ariesvcx-proof.test.ts index 9c1916b832..507bd81cf1 100644 --- a/wrappers/node/test/suite1/ariesvcx-proof.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-proof.test.ts @@ -7,11 +7,11 @@ import { dataProofCreateLegacy, dataProofCreate, proofCreate, } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { Proof, VerifierStateType, VCXCode } from 'src'; describe('Proof:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('lgeacy success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-schema.test.ts b/wrappers/node/test/suite1/ariesvcx-schema.test.ts index 12f5419ca9..ab7d723e87 100644 --- a/wrappers/node/test/suite1/ariesvcx-schema.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-schema.test.ts @@ -2,11 +2,11 @@ import '../module-resolver-helper'; import { assert } from 'chai'; import { dataSchemaCreate, schemaCreate } from 'helpers/entities'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { Schema, SchemaState, VCXCode } from 'src'; describe('Schema:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('create:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-utils.test.ts b/wrappers/node/test/suite1/ariesvcx-utils.test.ts index fee3cd59ca..5e1ab1cc75 100644 --- a/wrappers/node/test/suite1/ariesvcx-utils.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-utils.test.ts @@ -1,7 +1,7 @@ import '../module-resolver-helper'; import { assert } from 'chai'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { getLedgerAuthorAgreement, getVersion, @@ -11,7 +11,7 @@ import { } from 'src'; describe('utils:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('provisionAgent:', () => { it('success', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-wallet.test.ts b/wrappers/node/test/suite1/ariesvcx-wallet.test.ts index c8a0e3bb4b..853c6d5a3b 100644 --- a/wrappers/node/test/suite1/ariesvcx-wallet.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-wallet.test.ts @@ -1,10 +1,10 @@ import '../module-resolver-helper'; import { assert } from 'chai'; -import { initVcxTestMode, shouldThrow } from 'helpers/utils'; +import { initVcx, shouldThrow } from 'helpers/utils'; import { shutdownVcx, VCXCode, Wallet } from 'src'; describe('Wallet:', () => { - before(() => initVcxTestMode()); + before(() => initVcx()); describe('import:', () => { it('throws: libindy error', async () => { diff --git a/wrappers/vcx-napi-rs/index.d.ts b/wrappers/vcx-napi-rs/index.d.ts index c204a738d6..80d8f0cc6d 100644 --- a/wrappers/vcx-napi-rs/index.d.ts +++ b/wrappers/vcx-napi-rs/index.d.ts @@ -46,7 +46,7 @@ export function credentialGetTailsLocation(handle: number): string export function credentialGetTailsHash(handle: number): string export function credentialGetRevRegId(handle: number): string export function credentialGetThreadId(handle: number): string -export function credentialdefCreateV2(sourceId: string, schemaId: string, tag: string, supportRevocation: boolean): Promise +export function credentialdefCreateV2(issuerDid: string, sourceId: string, schemaId: string, tag: string, supportRevocation: boolean): Promise export function credentialdefPublish(handle: number): Promise export function credentialdefDeserialize(serialized: string): number export function credentialdefRelease(handle: number): void @@ -166,7 +166,7 @@ export function proofGetThreadId(handle: number): string export function markPresentationRequestMsgSent(handle: number): void export function revocationRegistryCreate(config: string): Promise export function revocationRegistryPublish(handle: number, tailsUrl: string): Promise -export function revocationRegistryPublishRevocations(handle: number): Promise +export function revocationRegistryPublishRevocations(handle: number, submitterDid: string): Promise export function revocationRegistryGetRevRegId(handle: number): string export function revocationRegistryGetTailsHash(handle: number): string export function revocationRegistrySerialize(handle: number): string @@ -174,14 +174,13 @@ export function revocationRegistryDeserialize(data: string): number export function revocationRegistryRelease(handle: number): void export function schemaGetAttributes(sourceId: string, schemaId: string): void export function schemaPrepareForEndorser(): void -export function schemaCreate(sourceId: string, name: string, version: string, data: string): Promise +export function schemaCreate(issuerDid: string, sourceId: string, name: string, version: string, data: string): Promise export function schemaGetSchemaId(handleSchema: number): string export function schemaDeserialize(serialized: string): number export function schemaSerialize(handleSchema: number): string export function schemaRelease(handleSchema: number): void export function schemaUpdateState(handleSchema: number): Promise export function schemaGetState(handleSchema: number): number -export function enableMocks(): void export function trustpingBuildResponseMsg(ping: string): string export function trustpingBuildPing(requestResponse: boolean, comment?: string | undefined | null): string export function shutdown(deleteAll?: boolean | undefined | null): void @@ -189,7 +188,6 @@ export function getVersion(): string export function walletOpenAsMain(walletConfig: string): Promise export function walletCreateMain(walletConfig: string): Promise export function walletCloseMain(): Promise -export function vcxInitIssuerConfig(config: string): Promise export function configureIssuerWallet(enterpriseSeed: string): Promise export function unpack(data: Buffer): Promise export function createAndStoreDid(seed?: string | undefined | null): Promise diff --git a/wrappers/vcx-napi-rs/index.js b/wrappers/vcx-napi-rs/index.js index d64eb7c039..33378a515c 100644 --- a/wrappers/vcx-napi-rs/index.js +++ b/wrappers/vcx-napi-rs/index.js @@ -252,7 +252,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { updateWebhookUrl, createAgencyClientForMainWallet, provisionCloudAgent, messagesUpdateStatus, generatePublicInvitation, connectionCreateInviter, connectionCreateInvitee, connectionGetThreadId, connectionGetPairwiseInfo, connectionGetRemoteDid, connectionGetRemoteVk, connectionGetState, connectionGetInvitation, connectionProcessInvite, connectionProcessRequest, connectionProcessResponse, connectionProcessAck, connectionProcessProblemReport, connectionSendResponse, connectionSendRequest, connectionSendAck, connectionSendGenericMessage, connectionSendAriesMessage, connectionCreateInvite, connectionSerialize, connectionDeserialize, connectionRelease, credentialCreateWithOffer, credentialRelease, credentialSendRequest, credentialDeclineOffer, credentialSerialize, credentialDeserialize, v2CredentialUpdateStateWithMessage, v2CredentialUpdateState, credentialGetState, credentialGetOffers, credentialGetAttributes, credentialGetAttachment, credentialGetTailsLocation, credentialGetTailsHash, credentialGetRevRegId, credentialGetThreadId, credentialdefCreateV2, credentialdefPublish, credentialdefDeserialize, credentialdefRelease, credentialdefSerialize, credentialdefGetCredDefId, credentialdefUpdateState, credentialdefGetState, disclosedProofCreateWithRequest, disclosedProofRelease, disclosedProofSendProof, disclosedProofRejectProof, disclosedProofGetProofMsg, disclosedProofSerialize, disclosedProofDeserialize, v2DisclosedProofUpdateState, v2DisclosedProofUpdateStateWithMessage, disclosedProofGetState, disclosedProofGetRequests, disclosedProofRetrieveCredentials, disclosedProofGetProofRequestAttachment, disclosedProofGenerateProof, disclosedProofDeclinePresentationRequest, disclosedProofGetThreadId, issuerCredentialDeserialize, issuerCredentialSerialize, issuerCredentialUpdateStateV2, issuerCredentialUpdateStateWithMessageV2, issuerCredentialUpdateStateWithMessageNonmediated, issuerCredentialGetState, issuerCredentialGetRevRegId, issuerCredentialCreate, issuerCredentialRevokeLocal, issuerCredentialIsRevokable, issuerCredentialGetRevocationId, issuerCredentialSendCredential, issuerCredentialSendCredentialNonmediated, issuerCredentialSendOfferV2, issuerCredentialSendOfferNonmediated, issuerCredentialBuildOfferMsgV2, issuerCredentialGetOfferMsg, issuerCredentialRelease, issuerCredentialGetThreadId, getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta, createService, createServiceV2, getServiceFromLedger, getAttrFromLedger, clearAttrFromLedger, writeEndorserDid, getVerkeyFromLedger, getLedgerTxn, initDefaultLogger, mediatedConnectionGeneratePublicInvite, mediatedConnectionGetPwDid, mediatedConnectionGetTheirPwDid, mediatedConnectionGetThreadId, mediatedConnectionGetState, mediatedConnectionGetSourceId, mediatedConnectionCreate, mediatedConnectionCreateWithInvite, mediatedConnectionSendMessage, mediatedConnectionCreateWithConnectionRequestV2, mediatedConnectionSendHandshakeReuse, mediatedConnectionUpdateStateWithMessage, mediatedConnectionHandleMessage, mediatedConnectionUpdateState, mediatedConnectionDeleteConnection, mediatedConnectionConnect, mediatedConnectionSerialize, mediatedConnectionDeserialize, mediatedConnectionRelease, mediatedConnectionInviteDetails, mediatedConnectionSendPing, mediatedConnectionSendDiscoveryFeatures, mediatedConnectionInfo, mediatedConnectionMessagesDownload, mediatedConnectionSignData, mediatedConnectionVerifySignature, outOfBandBuildHandshakeReuseAcceptedMsg, outOfBandReceiverCreate, outOfBandReceiverExtractMessage, outOfBandReceiverConnectionExists, outOfBandReceiverNonmediatedConnectionExists, outOfBandReceiverBuildConnection, outOfBandReceiverGetThreadId, outOfBandReceiverSerialize, outOfBandReceiverDeserialize, outOfBandReceiverRelease, outOfBandSenderCreate, outOfBandSenderAppendMessage, outOfBandSenderAppendService, outOfBandSenderAppendServiceDid, outOfBandSenderToMessage, outOfBandSenderGetThreadId, outOfBandSenderSerialize, outOfBandSenderDeserialize, outOfBandSenderRelease, openMainPool, closeMainPool, proofCreate, proofGetPresentationMsg, proofGetPresentationRequestAttachment, proofGetPresentationAttachment, proofRelease, proofSendRequest, proofSendRequestNonmediated, proofGetRequestMsg, proofSerialize, proofDeserialize, v2ProofUpdateState, v2ProofUpdateStateWithMessage, proofUpdateStateWithMessageNonmediated, proofGetState, proofGetVerificationStatus, proofGetThreadId, markPresentationRequestMsgSent, revocationRegistryCreate, revocationRegistryPublish, revocationRegistryPublishRevocations, revocationRegistryGetRevRegId, revocationRegistryGetTailsHash, revocationRegistrySerialize, revocationRegistryDeserialize, revocationRegistryRelease, schemaGetAttributes, schemaPrepareForEndorser, schemaCreate, schemaGetSchemaId, schemaDeserialize, schemaSerialize, schemaRelease, schemaUpdateState, schemaGetState, enableMocks, trustpingBuildResponseMsg, trustpingBuildPing, shutdown, getVersion, walletOpenAsMain, walletCreateMain, walletCloseMain, vcxInitIssuerConfig, configureIssuerWallet, unpack, createAndStoreDid, walletImport, walletExport, walletMigrate, walletDelete, getVerkeyFromWallet, rotateVerkey, rotateVerkeyStart, rotateVerkeyApply } = nativeBinding +const { updateWebhookUrl, createAgencyClientForMainWallet, provisionCloudAgent, messagesUpdateStatus, generatePublicInvitation, connectionCreateInviter, connectionCreateInvitee, connectionGetThreadId, connectionGetPairwiseInfo, connectionGetRemoteDid, connectionGetRemoteVk, connectionGetState, connectionGetInvitation, connectionProcessInvite, connectionProcessRequest, connectionProcessResponse, connectionProcessAck, connectionProcessProblemReport, connectionSendResponse, connectionSendRequest, connectionSendAck, connectionSendGenericMessage, connectionSendAriesMessage, connectionCreateInvite, connectionSerialize, connectionDeserialize, connectionRelease, credentialCreateWithOffer, credentialRelease, credentialSendRequest, credentialDeclineOffer, credentialSerialize, credentialDeserialize, v2CredentialUpdateStateWithMessage, v2CredentialUpdateState, credentialGetState, credentialGetOffers, credentialGetAttributes, credentialGetAttachment, credentialGetTailsLocation, credentialGetTailsHash, credentialGetRevRegId, credentialGetThreadId, credentialdefCreateV2, credentialdefPublish, credentialdefDeserialize, credentialdefRelease, credentialdefSerialize, credentialdefGetCredDefId, credentialdefUpdateState, credentialdefGetState, disclosedProofCreateWithRequest, disclosedProofRelease, disclosedProofSendProof, disclosedProofRejectProof, disclosedProofGetProofMsg, disclosedProofSerialize, disclosedProofDeserialize, v2DisclosedProofUpdateState, v2DisclosedProofUpdateStateWithMessage, disclosedProofGetState, disclosedProofGetRequests, disclosedProofRetrieveCredentials, disclosedProofGetProofRequestAttachment, disclosedProofGenerateProof, disclosedProofDeclinePresentationRequest, disclosedProofGetThreadId, issuerCredentialDeserialize, issuerCredentialSerialize, issuerCredentialUpdateStateV2, issuerCredentialUpdateStateWithMessageV2, issuerCredentialUpdateStateWithMessageNonmediated, issuerCredentialGetState, issuerCredentialGetRevRegId, issuerCredentialCreate, issuerCredentialRevokeLocal, issuerCredentialIsRevokable, issuerCredentialGetRevocationId, issuerCredentialSendCredential, issuerCredentialSendCredentialNonmediated, issuerCredentialSendOfferV2, issuerCredentialSendOfferNonmediated, issuerCredentialBuildOfferMsgV2, issuerCredentialGetOfferMsg, issuerCredentialRelease, issuerCredentialGetThreadId, getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta, createService, createServiceV2, getServiceFromLedger, getAttrFromLedger, clearAttrFromLedger, writeEndorserDid, getVerkeyFromLedger, getLedgerTxn, initDefaultLogger, mediatedConnectionGeneratePublicInvite, mediatedConnectionGetPwDid, mediatedConnectionGetTheirPwDid, mediatedConnectionGetThreadId, mediatedConnectionGetState, mediatedConnectionGetSourceId, mediatedConnectionCreate, mediatedConnectionCreateWithInvite, mediatedConnectionSendMessage, mediatedConnectionCreateWithConnectionRequestV2, mediatedConnectionSendHandshakeReuse, mediatedConnectionUpdateStateWithMessage, mediatedConnectionHandleMessage, mediatedConnectionUpdateState, mediatedConnectionDeleteConnection, mediatedConnectionConnect, mediatedConnectionSerialize, mediatedConnectionDeserialize, mediatedConnectionRelease, mediatedConnectionInviteDetails, mediatedConnectionSendPing, mediatedConnectionSendDiscoveryFeatures, mediatedConnectionInfo, mediatedConnectionMessagesDownload, mediatedConnectionSignData, mediatedConnectionVerifySignature, outOfBandBuildHandshakeReuseAcceptedMsg, outOfBandReceiverCreate, outOfBandReceiverExtractMessage, outOfBandReceiverConnectionExists, outOfBandReceiverNonmediatedConnectionExists, outOfBandReceiverBuildConnection, outOfBandReceiverGetThreadId, outOfBandReceiverSerialize, outOfBandReceiverDeserialize, outOfBandReceiverRelease, outOfBandSenderCreate, outOfBandSenderAppendMessage, outOfBandSenderAppendService, outOfBandSenderAppendServiceDid, outOfBandSenderToMessage, outOfBandSenderGetThreadId, outOfBandSenderSerialize, outOfBandSenderDeserialize, outOfBandSenderRelease, openMainPool, closeMainPool, proofCreate, proofGetPresentationMsg, proofGetPresentationRequestAttachment, proofGetPresentationAttachment, proofRelease, proofSendRequest, proofSendRequestNonmediated, proofGetRequestMsg, proofSerialize, proofDeserialize, v2ProofUpdateState, v2ProofUpdateStateWithMessage, proofUpdateStateWithMessageNonmediated, proofGetState, proofGetVerificationStatus, proofGetThreadId, markPresentationRequestMsgSent, revocationRegistryCreate, revocationRegistryPublish, revocationRegistryPublishRevocations, revocationRegistryGetRevRegId, revocationRegistryGetTailsHash, revocationRegistrySerialize, revocationRegistryDeserialize, revocationRegistryRelease, schemaGetAttributes, schemaPrepareForEndorser, schemaCreate, schemaGetSchemaId, schemaDeserialize, schemaSerialize, schemaRelease, schemaUpdateState, schemaGetState, trustpingBuildResponseMsg, trustpingBuildPing, shutdown, getVersion, walletOpenAsMain, walletCreateMain, walletCloseMain, configureIssuerWallet, unpack, createAndStoreDid, walletImport, walletExport, walletMigrate, walletDelete, getVerkeyFromWallet, rotateVerkey, rotateVerkeyStart, rotateVerkeyApply } = nativeBinding module.exports.updateWebhookUrl = updateWebhookUrl module.exports.createAgencyClientForMainWallet = createAgencyClientForMainWallet @@ -432,7 +432,6 @@ module.exports.schemaSerialize = schemaSerialize module.exports.schemaRelease = schemaRelease module.exports.schemaUpdateState = schemaUpdateState module.exports.schemaGetState = schemaGetState -module.exports.enableMocks = enableMocks module.exports.trustpingBuildResponseMsg = trustpingBuildResponseMsg module.exports.trustpingBuildPing = trustpingBuildPing module.exports.shutdown = shutdown @@ -440,7 +439,6 @@ module.exports.getVersion = getVersion module.exports.walletOpenAsMain = walletOpenAsMain module.exports.walletCreateMain = walletCreateMain module.exports.walletCloseMain = walletCloseMain -module.exports.vcxInitIssuerConfig = vcxInitIssuerConfig module.exports.configureIssuerWallet = configureIssuerWallet module.exports.unpack = unpack module.exports.createAndStoreDid = createAndStoreDid diff --git a/wrappers/vcx-napi-rs/src/api/credential_definition.rs b/wrappers/vcx-napi-rs/src/api/credential_definition.rs index b841cc6837..42d5a0a8e6 100644 --- a/wrappers/vcx-napi-rs/src/api/credential_definition.rs +++ b/wrappers/vcx-napi-rs/src/api/credential_definition.rs @@ -5,12 +5,13 @@ use crate::error::to_napi_err; #[napi] async fn credentialdef_create_v2_( + issuer_did: String, source_id: String, schema_id: String, tag: String, support_revocation: bool, ) -> napi::Result { - credential_def::create(source_id, schema_id, tag, support_revocation) + credential_def::create(issuer_did, source_id, schema_id, tag, support_revocation) .await .map_err(to_napi_err) } diff --git a/wrappers/vcx-napi-rs/src/api/mod.rs b/wrappers/vcx-napi-rs/src/api/mod.rs index bb94976c21..741d61ee88 100644 --- a/wrappers/vcx-napi-rs/src/api/mod.rs +++ b/wrappers/vcx-napi-rs/src/api/mod.rs @@ -15,7 +15,6 @@ pub mod pool; pub mod proof; pub mod revocation_registry; pub mod schema; -pub mod testing; pub mod trustping; pub mod utils; pub mod wallet; diff --git a/wrappers/vcx-napi-rs/src/api/revocation_registry.rs b/wrappers/vcx-napi-rs/src/api/revocation_registry.rs index dfd9522eed..2ef9d8c0ef 100644 --- a/wrappers/vcx-napi-rs/src/api/revocation_registry.rs +++ b/wrappers/vcx-napi-rs/src/api/revocation_registry.rs @@ -30,8 +30,11 @@ async fn revocation_registry_publish(handle: u32, tails_url: String) -> napi::Re } #[napi] -async fn revocation_registry_publish_revocations(handle: u32) -> napi::Result<()> { - revocation_registry::publish_revocations(handle) +async fn revocation_registry_publish_revocations( + handle: u32, + submitter_did: String, +) -> napi::Result<()> { + revocation_registry::publish_revocations(handle, &submitter_did) .await .map_err(to_napi_err) } diff --git a/wrappers/vcx-napi-rs/src/api/schema.rs b/wrappers/vcx-napi-rs/src/api/schema.rs index 2d93a3f2f3..02949df21a 100644 --- a/wrappers/vcx-napi-rs/src/api/schema.rs +++ b/wrappers/vcx-napi-rs/src/api/schema.rs @@ -15,12 +15,13 @@ fn schema_prepare_for_endorser() -> napi::Result<()> { #[napi] async fn schema_create( + issuer_did: String, source_id: String, name: String, version: String, data: String, ) -> napi::Result { - schema::create_and_publish_schema(&source_id, name, version, data) + schema::create_and_publish_schema(&issuer_did, &source_id, name, version, data) .await .map_err(to_napi_err) } diff --git a/wrappers/vcx-napi-rs/src/api/testing.rs b/wrappers/vcx-napi-rs/src/api/testing.rs deleted file mode 100644 index 59b148cab2..0000000000 --- a/wrappers/vcx-napi-rs/src/api/testing.rs +++ /dev/null @@ -1,10 +0,0 @@ -use libvcx_core::api_vcx::api_global::settings; -use napi_derive::napi; - -use crate::error::to_napi_err; - -#[napi] -pub fn enable_mocks() -> ::napi::Result<()> { - settings::enable_mocks().map_err(to_napi_err)?; - Ok(()) -} diff --git a/wrappers/vcx-napi-rs/src/api/wallet.rs b/wrappers/vcx-napi-rs/src/api/wallet.rs index e06a612893..d089b46ada 100644 --- a/wrappers/vcx-napi-rs/src/api/wallet.rs +++ b/wrappers/vcx-napi-rs/src/api/wallet.rs @@ -1,7 +1,7 @@ use libvcx_core::{ - api_vcx::api_global::{ledger, settings::settings_init_issuer_config, wallet}, + api_vcx::api_global::{ledger, wallet}, aries_vcx::aries_vcx_core::wallet::indy::{ - wallet::delete_wallet, IssuerConfig, RestoreWalletConfigs, WalletConfig, + wallet::delete_wallet, RestoreWalletConfigs, WalletConfig, }, errors::error::{LibvcxError, LibvcxErrorKind}, serde_json, @@ -48,19 +48,6 @@ pub async fn wallet_close_main() -> napi::Result<()> { wallet::close_main_wallet().await.map_err(to_napi_err) } -#[napi] -pub async fn vcx_init_issuer_config(config: String) -> napi::Result<()> { - let config = serde_json::from_str::(&config) - .map_err(|err| { - LibvcxError::from_msg( - LibvcxErrorKind::InvalidConfiguration, - format!("Serialization error: {:?}", err), - ) - }) - .map_err(to_napi_err)?; - settings_init_issuer_config(&config).map_err(to_napi_err) -} - #[napi] pub async fn configure_issuer_wallet(enterprise_seed: String) -> napi::Result { let res = wallet::wallet_configure_issuer(&enterprise_seed) diff --git a/wrappers/vcx-napi-rs/tsconfig.json b/wrappers/vcx-napi-rs/tsconfig.json index 605f4bd4c7..716c67db71 100644 --- a/wrappers/vcx-napi-rs/tsconfig.json +++ b/wrappers/vcx-napi-rs/tsconfig.json @@ -12,23 +12,29 @@ "noUnusedLocals": true, "noUnusedParameters": true, "strict": true, - "skipLibCheck": true, - "suppressImplicitAnyIndexErrors": true, - "suppressExcessPropertyErrors": true, "forceConsistentCasingInFileNames": true, "preserveSymlinks": true, - "target": "ES2015", "sourceMap": true, "esModuleInterop": true, "stripInternal": true, "resolveJsonModule": true, "importsNotUsedAsValues": "remove", - "outDir": "scripts", - "lib": ["dom", "DOM.Iterable", "ES2019", "ES2020", "esnext"], + "lib": [ + "dom", + "DOM.Iterable", + "ES2019", + "ES2020", + "esnext" + ], "outDir": "./dist", "target": "ES2018", "skipLibCheck": false }, - "include": ["."], - "exclude": ["dist", "node_modules"] -} + "include": [ + "." + ], + "exclude": [ + "dist", + "node_modules" + ] +} \ No newline at end of file