From 6d468885e95fa554a59d87caf3d9ecff2513ae49 Mon Sep 17 00:00:00 2001 From: Miroslav Kovar Date: Mon, 19 Jul 2021 10:31:33 +0200 Subject: [PATCH] Remove dependence of aries module on VcxStateType (#314) * Modify numeric representation of aries protocols states (breaking) * Reject on FFI error in getState() and updateState() (breaking) * Remove dependence of aries module on VcxStateType (refactoring) * Move agency pool test (refactoring) * Make state type generic on typescript wrapper level (refactoring) Signed-off-by: Miroslav Kovar --- agents/node/vcxagent-core/demo/alice.js | 2 +- agents/node/vcxagent-core/demo/faber.js | 8 +- agents/node/vcxagent-core/src/agent.js | 4 +- .../src/services/service-connections.js | 4 +- .../src/services/service-cred-holder.js | 5 +- .../src/services/service-cred-issuer.js | 11 +- .../src/services/service-prover.js | 6 +- .../vcxagent-core/src/utils/vcx-workflows.js | 3 +- .../test/distribute-tails.spec.js | 10 +- .../test/feature-discovery.spec.js | 1 - .../vcxagent-core/test/sign-messaging.spec.js | 4 +- .../test/update-state-v2.spec.js | 11 +- agents/node/vcxagent-core/test/utils/alice.js | 6 +- agents/node/vcxagent-core/test/utils/faber.js | 10 +- agents/node/vcxagent-core/test/utils/utils.js | 8 +- libvcx/src/api_lib/api_c/connection.rs | 8 +- libvcx/src/api_lib/api_c/credential.rs | 26 +-- libvcx/src/api_lib/api_c/credential_def.rs | 5 +- libvcx/src/api_lib/api_c/disclosed_proof.rs | 11 +- libvcx/src/api_lib/api_c/issuer_credential.rs | 19 +-- libvcx/src/api_lib/api_c/proof.rs | 11 +- libvcx/src/api_lib/api_c/wallet.rs | 1 - libvcx/src/api_lib/api_handle/connection.rs | 27 +-- libvcx/src/api_lib/api_handle/credential.rs | 18 +- .../src/api_lib/api_handle/disclosed_proof.rs | 30 ++-- .../api_lib/api_handle/issuer_credential.rs | 42 ++--- libvcx/src/api_lib/api_handle/proof.rs | 38 ++--- libvcx/src/api_lib/utils_c/fsm_states.rs | 52 ++++++ .../aries/handlers/connection/connection.rs | 16 +- .../connection/invitee/state_machine.rs | 2 +- .../connection/inviter/state_machine.rs | 2 +- .../aries/handlers/issuance/holder/holder.rs | 14 +- .../handlers/issuance/holder/state_machine.rs | 112 ++++++------ .../aries/handlers/issuance/issuer/issuer.rs | 22 ++- .../handlers/issuance/issuer/state_machine.rs | 150 ++++++++-------- .../proof_presentation/prover/prover.rs | 18 +- .../prover/state_machine.rs | 160 +++++++++--------- .../verifier/state_machine.rs | 99 ++++++----- .../proof_presentation/verifier/verifier.rs | 21 ++- libvcx/src/aries/mod.rs | 12 +- libvcx/src/lib.rs | 24 ++- libvcx/src/libindy/utils/wallet.rs | 4 +- libvcx/src/utils/devsetup.rs | 19 --- libvcx/src/utils/devsetup_agent.rs | 20 +-- wrappers/node/src/api/common.ts | 50 ++++-- wrappers/node/src/api/connection.ts | 14 +- wrappers/node/src/api/credential.ts | 4 +- wrappers/node/src/api/disclosed-proof.ts | 4 +- wrappers/node/src/api/issuer-credential.ts | 35 +--- wrappers/node/src/api/proof.ts | 54 +----- wrappers/node/src/api/vcx-base-with-state.ts | 11 +- wrappers/node/test/helpers/entities.ts | 1 + .../test/suite1/ariesvcx-connection.test.ts | 35 ++-- .../test/suite1/ariesvcx-credential.test.ts | 10 +- .../suite1/ariesvcx-disclosed-proof.test.ts | 23 +-- .../suite1/ariesvcx-issuer-credential.test.ts | 6 +- .../node/test/suite1/ariesvcx-proof.test.ts | 24 ++- 57 files changed, 674 insertions(+), 673 deletions(-) diff --git a/agents/node/vcxagent-core/demo/alice.js b/agents/node/vcxagent-core/demo/alice.js index cea7a01666..6f7b053c8a 100644 --- a/agents/node/vcxagent-core/demo/alice.js +++ b/agents/node/vcxagent-core/demo/alice.js @@ -93,7 +93,7 @@ async function runAlice (options) { function _validateMsgs (msgs) { logger.debug(`Validating messages:\n${JSON.stringify(msgs, null, 2)}`) - assert(msgs.length === 5) + assert(msgs.length === 4) assert(msgs[0].uid) assert(msgs[0].statusCode) assert(msgs[0].decryptedMsg) diff --git a/agents/node/vcxagent-core/demo/faber.js b/agents/node/vcxagent-core/demo/faber.js index c5875418a1..bfc49c1dfc 100644 --- a/agents/node/vcxagent-core/demo/faber.js +++ b/agents/node/vcxagent-core/demo/faber.js @@ -1,4 +1,4 @@ -const { StateType, ProofState, Proof } = require('@hyperledger/node-vcx-wrapper') +const { VerifierStateType, ProofState, Proof } = require('@hyperledger/node-vcx-wrapper') const sleepPromise = require('sleep-promise') const { runScript } = require('./script-common') const { testTailsUrl } = require('../src/common') @@ -88,12 +88,12 @@ async function runFaber (options) { let proofProtocolState = await vcxProof.updateStateV2(connectionToAlice) logger.debug(`vcxProof = ${JSON.stringify(vcxProof)}`) logger.debug(`proofState = ${proofProtocolState}`) - while (proofProtocolState !== StateType.Accepted) { // even if revoked credential was used, state should in final state be StateType.Accepted + while (![VerifierStateType.Finished, VerifierStateType.Failed].includes(proofProtocolState)) { await sleepPromise(2000) proofProtocolState = await vcxProof.updateStateV2(connectionToAlice) logger.info(`proofState=${proofProtocolState}`) - if (proofProtocolState === StateType.None) { - logger.error(`Faber proof protocol state is ${StateType.None} which an error has ocurred.`) + if (proofProtocolState === VerifierStateType.Failed) { + logger.error(`Faber proof protocol state is ${3} which an error has ocurred.`) logger.error(`Serialized proof state = ${JSON.stringify(await vcxProof.serialize())}`) process.exit(-1) } diff --git a/agents/node/vcxagent-core/src/agent.js b/agents/node/vcxagent-core/src/agent.js index 0ad8011815..81b957a02c 100644 --- a/agents/node/vcxagent-core/src/agent.js +++ b/agents/node/vcxagent-core/src/agent.js @@ -30,6 +30,7 @@ async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, usePos await storageService.saveAgentProvision(agentProvision) } const agentProvision = await storageService.loadAgentProvision() + const issuerDid = agentProvision.issuerConfig["institution_did"] async function agentInitVcx () { logger.info(`Initializing ${agentName} vcx session.`) @@ -93,7 +94,8 @@ async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, usePos loadCredDef: storageService.loadCredentialDefinition, saveIssuerCredential: storageService.saveCredIssuer, loadIssuerCredential: storageService.loadCredIssuer, - listIssuerCredentialIds: storageService.listCredIssuerKeys + listIssuerCredentialIds: storageService.listCredIssuerKeys, + issuerDid }) const serviceCredHolder = createServiceCredHolder({ logger, diff --git a/agents/node/vcxagent-core/src/services/service-connections.js b/agents/node/vcxagent-core/src/services/service-connections.js index 81a63d5ab0..c6594a56a4 100644 --- a/agents/node/vcxagent-core/src/services/service-connections.js +++ b/agents/node/vcxagent-core/src/services/service-connections.js @@ -2,7 +2,7 @@ const { getMessagesForConnection } = require('../utils/messages') const { updateMessages, Connection, - StateType + ConnectionStateType } = require('@hyperledger/node-vcx-wrapper') const { pollFunction } = require('../common') @@ -50,7 +50,7 @@ module.exports.createServiceConnections = function createServiceConnections ({ l async function _progressConnectionToAcceptedState (connection, attemptsThreshold, timeoutMs) { async function progressToAcceptedState () { - if (await connection.updateState() !== StateType.Accepted) { + if (await connection.updateState() !== ConnectionStateType.Finished) { return { result: undefined, isFinished: false } } else { return { result: null, isFinished: true } diff --git a/agents/node/vcxagent-core/src/services/service-cred-holder.js b/agents/node/vcxagent-core/src/services/service-cred-holder.js index 15319538f0..243e50e97c 100644 --- a/agents/node/vcxagent-core/src/services/service-cred-holder.js +++ b/agents/node/vcxagent-core/src/services/service-cred-holder.js @@ -2,7 +2,7 @@ const {filterOffersByCredentialName} = require('../utils/credentials') const { filterOffersByAttr } = require('../utils/credentials') const { filterOffersBySchema } = require('../utils/credentials') const { - StateType, + HolderStateType, Credential } = require('@hyperledger/node-vcx-wrapper') const { pollFunction } = require('../common') @@ -11,6 +11,7 @@ module.exports.createServiceCredHolder = function createServiceCredHolder ({ log async function _getOffers (connection, filter, attemptsThreshold, timeoutMs) { async function findSomeCredOffer () { let offers = await Credential.getOffers(connection) + logger.info(`Offers: ${offers}`) if (filter && filter.schemaIdRegex) { offers = filterOffersBySchema(offers, filter.schemaIdRegex) } @@ -49,7 +50,7 @@ module.exports.createServiceCredHolder = function createServiceCredHolder ({ log async function waitForCredential (connectionId, holderCredentialId, attemptsThreshold = 10, timeoutMs = 2000) { const connection = await loadConnection(connectionId) const credential = await loadHolderCredential(holderCredentialId) - await _progressCredentialToState(credential, connection, StateType.Accepted, attemptsThreshold, timeoutMs) + await _progressCredentialToState(credential, connection, HolderStateType.Finished, attemptsThreshold, timeoutMs) logger.info('Credential has been received.') await saveHolderCredential(holderCredentialId, credential) return getCredentialData(holderCredentialId) diff --git a/agents/node/vcxagent-core/src/services/service-cred-issuer.js b/agents/node/vcxagent-core/src/services/service-cred-issuer.js index 8142d9a4b6..bb72c5fdec 100644 --- a/agents/node/vcxagent-core/src/services/service-cred-issuer.js +++ b/agents/node/vcxagent-core/src/services/service-cred-issuer.js @@ -1,10 +1,10 @@ const { - StateType, + IssuerStateType, IssuerCredential } = require('@hyperledger/node-vcx-wrapper') const { pollFunction } = require('../common') -module.exports.createServiceCredIssuer = function createServiceCredIssuer ({ logger, loadConnection, loadCredDef, saveIssuerCredential, loadIssuerCredential, listIssuerCredentialIds }) { +module.exports.createServiceCredIssuer = function createServiceCredIssuer ({ logger, loadConnection, loadCredDef, saveIssuerCredential, loadIssuerCredential, listIssuerCredentialIds, issuerDid }) { async function sendOffer (issuerCredId, connectionId, credDefId, schemaAttrs) { const connection = await loadConnection(connectionId) const credDef = await loadCredDef(credDefId) @@ -14,7 +14,8 @@ module.exports.createServiceCredIssuer = function createServiceCredIssuer ({ log sourceId: 'alice_degree', credDefHandle: credDef.handle, credentialName: 'cred', - price: '0' + price: '0', + issuerDid }) logger.info(`Per issuer credential ${issuerCredId}, sending cred offer to connection ${connectionId}`) await issuerCred.sendOffer(connection) @@ -36,7 +37,7 @@ module.exports.createServiceCredIssuer = function createServiceCredIssuer ({ log const issuerCred = await loadIssuerCredential(issuerCredId) const connection = await loadConnection(connectionId) logger.debug('Going to wait until credential request is received.') - await _progressIssuerCredentialToState(issuerCred, connection, StateType.RequestReceived, 10, 2000) + await _progressIssuerCredentialToState(issuerCred, connection, IssuerStateType.RequestReceived, 10, 2000) await saveIssuerCredential(issuerCredId, issuerCred) } @@ -45,7 +46,7 @@ module.exports.createServiceCredIssuer = function createServiceCredIssuer ({ log const connection = await loadConnection(connectionId) const issuerCred = await loadIssuerCredential(issuerCredId) logger.info('Going to wait until counterparty accepts the credential.') - await _progressIssuerCredentialToState(issuerCred, connection, StateType.Accepted, 10, 2000) + await _progressIssuerCredentialToState(issuerCred, connection, IssuerStateType.Finished, 10, 2000) await saveIssuerCredential(issuerCredId, issuerCred) } diff --git a/agents/node/vcxagent-core/src/services/service-prover.js b/agents/node/vcxagent-core/src/services/service-prover.js index c65b848e16..2fff12b5e8 100644 --- a/agents/node/vcxagent-core/src/services/service-prover.js +++ b/agents/node/vcxagent-core/src/services/service-prover.js @@ -2,7 +2,7 @@ const { pollFunction } = require('../common') const { holderSelectCredentialsForProof } = require('../utils/proofs') const { DisclosedProof, - StateType + ProverStateType } = require('@hyperledger/node-vcx-wrapper') module.exports.createServiceProver = function createServiceProver ({ logger, loadConnection, saveDisclosedProof, loadDisclosedProof, listDislosedProofIds }) { @@ -35,7 +35,7 @@ module.exports.createServiceProver = function createServiceProver ({ logger, loa } } - const [error, proofRequests] = await pollFunction(findSomeRequests, 'Get credential offer', logger, attemptsThreshold, timeoutMs) + const [error, proofRequests] = await pollFunction(findSomeRequests, 'Get proof request', logger, attemptsThreshold, timeoutMs) if (error) { throw Error(`Couldn't find any proof request. ${error}`) } @@ -84,7 +84,7 @@ module.exports.createServiceProver = function createServiceProver ({ logger, loa await sendDisclosedProof(disclosedProofId, connectionId) const disclosedProof = await loadDisclosedProof(disclosedProofId) const connection = await loadConnection(connectionId) - await _progressProofToState(disclosedProof, connection, [StateType.Accepted, StateType.None]) + await _progressProofToState(disclosedProof, connection, [ProverStateType.PresentationPreparationFailed, ProverStateType.PresentationSent]) const state = await disclosedProof.getState() await saveDisclosedProof(disclosedProofId, disclosedProof) return state diff --git a/agents/node/vcxagent-core/src/utils/vcx-workflows.js b/agents/node/vcxagent-core/src/utils/vcx-workflows.js index 58a1956f52..d23a8cebcb 100644 --- a/agents/node/vcxagent-core/src/utils/vcx-workflows.js +++ b/agents/node/vcxagent-core/src/utils/vcx-workflows.js @@ -85,9 +85,10 @@ async function provisionAgentInAgency (agentName, genesisPath, agencyUrl, seed, logger.debug(`Configuring issuer's wallet with seed: ${seed}`) const issuerConfig = JSON.parse(await configureIssuerWallet(seed)) issuerConfig.institution_name = agentName + logger.debug(`Configured issuer wallet with config: ${JSON.stringify(issuerConfig, null, 2)}`) logger.debug(`Provisioning agent with config: ${JSON.stringify(agencyConfig, null, 2)}`) agencyConfig = JSON.parse(await provisionCloudAgent(agencyConfig)) - logger.debug(`Provisined agent with config: ${JSON.stringify(agencyConfig, null, 2)}`) + logger.debug(`Provisioned agent with config: ${JSON.stringify(agencyConfig, null, 2)}`) await closeMainWallet() return { agencyConfig, issuerConfig, walletConfig } diff --git a/agents/node/vcxagent-core/test/distribute-tails.spec.js b/agents/node/vcxagent-core/test/distribute-tails.spec.js index 8c9b5a9403..a0d08f01a1 100644 --- a/agents/node/vcxagent-core/test/distribute-tails.spec.js +++ b/agents/node/vcxagent-core/test/distribute-tails.spec.js @@ -5,7 +5,7 @@ const axios = require('axios') const { buildRevocationDetails } = require('../src') const { createPairedAliceAndFaber } = require('./utils/utils') const { initRustapi } = require('../src/index') -const { StateType } = require('@hyperledger/node-vcx-wrapper') +const { IssuerStateType, HolderStateType, VerifierStateType, ProverStateType } = require('@hyperledger/node-vcx-wrapper') const uuid = require('uuid') const sleep = require('sleep-promise') const fs = require('fs') @@ -27,9 +27,9 @@ describe('test tails distribution', () => { const tailsUrl = `http://127.0.0.1:${port}/${tailsUrlId}` await faber.sendCredentialOffer(buildRevocationDetails({ supportRevocation: true, tailsFile: `${__dirname}/tmp/faber/tails`, tailsUrl, maxCreds: 5 })) await alice.acceptCredentialOffer() - await faber.updateStateCredentialV2(StateType.RequestReceived) + await faber.updateStateCredentialV2(IssuerStateType.RequestReceived) await faber.sendCredential() - await alice.updateStateCredentialV2(StateType.Accepted) + await alice.updateStateCredentialV2(HolderStateType.Finished) const faberTailsHash = await faber.getTailsHash() const app = express() @@ -47,8 +47,8 @@ describe('test tails distribution', () => { const request = await faber.requestProofFromAlice() await alice.sendHolderProof(JSON.parse(request), revRegId => aliceTailsFileDir) - await faber.updateStateVerifierProofV2(StateType.Accepted) - await alice.updateStateHolderProofV2(StateType.Accepted) + await faber.updateStateVerifierProofV2(VerifierStateType.Finished) + await alice.updateStateHolderProofV2(ProverStateType.Finished) } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) if (server) { diff --git a/agents/node/vcxagent-core/test/feature-discovery.spec.js b/agents/node/vcxagent-core/test/feature-discovery.spec.js index 2820cbf7f8..e44c04c233 100644 --- a/agents/node/vcxagent-core/test/feature-discovery.spec.js +++ b/agents/node/vcxagent-core/test/feature-discovery.spec.js @@ -10,7 +10,6 @@ beforeAll(async () => { }) describe('send ping, get ping', () => { - it('Faber should send credential to Alice', async () => { try { const { alice, faber } = await createPairedAliceAndFaber() diff --git a/agents/node/vcxagent-core/test/sign-messaging.spec.js b/agents/node/vcxagent-core/test/sign-messaging.spec.js index 654f8c61f5..99987a87e1 100644 --- a/agents/node/vcxagent-core/test/sign-messaging.spec.js +++ b/agents/node/vcxagent-core/test/sign-messaging.spec.js @@ -1,7 +1,7 @@ /* eslint-env jest */ require('jest') -const {createPairedAliceAndFaber} = require('./utils/utils') -const {initRustapi} = require('../src/index') +const { createPairedAliceAndFaber } = require('./utils/utils') +const { initRustapi } = require('../src/index') const sleep = require('sleep-promise') beforeAll(async () => { diff --git a/agents/node/vcxagent-core/test/update-state-v2.spec.js b/agents/node/vcxagent-core/test/update-state-v2.spec.js index 9562671a19..e8249da0be 100644 --- a/agents/node/vcxagent-core/test/update-state-v2.spec.js +++ b/agents/node/vcxagent-core/test/update-state-v2.spec.js @@ -1,9 +1,8 @@ /* eslint-env jest */ require('jest') -const { shutdownVcx } = require('@hyperledger/node-vcx-wrapper') const { createPairedAliceAndFaber } = require('./utils/utils') const { initRustapi } = require('../src/index') -const { StateType } = require('@hyperledger/node-vcx-wrapper') +const { IssuerStateType, HolderStateType, ProverStateType, VerifierStateType } = require('@hyperledger/node-vcx-wrapper') const sleep = require('sleep-promise') beforeAll(async () => { @@ -19,14 +18,14 @@ describe('test update state', () => { await faber.sendCredentialOffer() await alice.acceptCredentialOffer() - await faber.updateStateCredentialV2(StateType.RequestReceived) + await faber.updateStateCredentialV2(IssuerStateType.RequestReceived) await faber.sendCredential() - await alice.updateStateCredentialV2(StateType.Accepted) + await alice.updateStateCredentialV2(HolderStateType.Finished) const request = await faber.requestProofFromAlice() await alice.sendHolderProof(JSON.parse(request)) - await faber.updateStateVerifierProofV2(StateType.Accepted) - await alice.updateStateHolderProofV2(StateType.Accepted) + await faber.updateStateVerifierProofV2(VerifierStateType.Finished) + await alice.updateStateHolderProofV2(ProverStateType.Finished) } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) await sleep(2000) diff --git a/agents/node/vcxagent-core/test/utils/alice.js b/agents/node/vcxagent-core/test/utils/alice.js index a25923f716..fefca01729 100644 --- a/agents/node/vcxagent-core/test/utils/alice.js +++ b/agents/node/vcxagent-core/test/utils/alice.js @@ -1,6 +1,6 @@ /* eslint-env jest */ const { createVcxAgent } = require('../../src/index') -const { StateType } = require('@hyperledger/node-vcx-wrapper') +const { ConnectionStateType, ProverStateType } = require('@hyperledger/node-vcx-wrapper') module.exports.createAlice = async function createAlice () { const agentName = `alice-${Math.floor(new Date() / 1000)}` @@ -26,7 +26,7 @@ module.exports.createAlice = async function createAlice () { await vcxAgent.serviceConnections.inviteeConnectionAcceptFromInvitation(connectionId, invite) const connection = await vcxAgent.serviceConnections.getVcxConnection(connectionId) - expect(await connection.getState()).toBe(StateType.OfferSent) + expect(await connection.getState()).toBe(ConnectionStateType.Requested) await vcxAgent.agentShutdownVcx() } @@ -56,7 +56,7 @@ module.exports.createAlice = async function createAlice () { const { selectedCreds } = await vcxAgent.serviceProver.selectCredentials(disclosedProofId, mapRevRegId) const selfAttestedAttrs = { attribute_3: 'Smith' } await vcxAgent.serviceProver.generateProof(disclosedProofId, selectedCreds, selfAttestedAttrs) - expect(await vcxAgent.serviceProver.sendDisclosedProof(disclosedProofId, connectionId)).toBe(StateType.OfferSent) + expect(await vcxAgent.serviceProver.sendDisclosedProof(disclosedProofId, connectionId)).toBe(ProverStateType.PresentationSent) await vcxAgent.agentShutdownVcx() } diff --git a/agents/node/vcxagent-core/test/utils/faber.js b/agents/node/vcxagent-core/test/utils/faber.js index 0bdc147c14..4be958dd0c 100644 --- a/agents/node/vcxagent-core/test/utils/faber.js +++ b/agents/node/vcxagent-core/test/utils/faber.js @@ -1,7 +1,7 @@ /* eslint-env jest */ const { buildRevocationDetails } = require('../../src') const { createVcxAgent, getSampleSchemaData } = require('../../src') -const { StateType } = require('@hyperledger/node-vcx-wrapper') +const { ConnectionStateType, IssuerStateType, VerifierStateType } = require('@hyperledger/node-vcx-wrapper') const { getAliceSchemaAttrs, getFaberCredDefName, getFaberProofData } = require('./data') module.exports.createFaber = async function createFaber () { @@ -30,7 +30,7 @@ module.exports.createFaber = async function createFaber () { const invite = await vcxAgent.serviceConnections.inviterConnectionCreate(connectionId, undefined) logger.info(`Faber generated invite:\n${invite}`) const connection = await vcxAgent.serviceConnections.getVcxConnection(connectionId) - expect(await connection.getState()).toBe(StateType.Initialized) + expect(await connection.getState()).toBe(ConnectionStateType.Invited) await vcxAgent.agentShutdownVcx() @@ -41,7 +41,7 @@ module.exports.createFaber = async function createFaber () { logger.info('Faber is going to generate invite') await vcxAgent.agentInitVcx() - expect(await vcxAgent.serviceConnections.connectionUpdate(connectionId)).toBe(StateType.RequestReceived) + expect(await vcxAgent.serviceConnections.connectionUpdate(connectionId)).toBe(ConnectionStateType.Responded) await vcxAgent.agentShutdownVcx() } @@ -90,7 +90,7 @@ module.exports.createFaber = async function createFaber () { await vcxAgent.agentInitVcx() logger.info('Issuer sending credential') - expect(await vcxAgent.serviceCredIssuer.sendCredential(issuerCredId, connectionId)).toBe(StateType.Accepted) + expect(await vcxAgent.serviceCredIssuer.sendCredential(issuerCredId, connectionId)).toBe(IssuerStateType.Finished) logger.info('Credential sent') await vcxAgent.agentShutdownVcx() @@ -105,7 +105,7 @@ module.exports.createFaber = async function createFaber () { await vcxAgent.serviceVerifier.createProof(proofId, proofData) logger.info(`Faber is sending proof request to connection ${connectionId}`) const { state, proofRequestMessage } = await vcxAgent.serviceVerifier.sendProofRequest(connectionId, proofId) - expect(state).toBe(StateType.OfferSent) + expect(state).toBe(VerifierStateType.PresentationRequestSent) await vcxAgent.agentShutdownVcx() return proofRequestMessage } diff --git a/agents/node/vcxagent-core/test/utils/utils.js b/agents/node/vcxagent-core/test/utils/utils.js index fcdcfd60bb..3c0cb50b5f 100644 --- a/agents/node/vcxagent-core/test/utils/utils.js +++ b/agents/node/vcxagent-core/test/utils/utils.js @@ -1,14 +1,14 @@ const { createFaber } = require('./faber') const { createAlice } = require('./alice') -const { StateType } = require('@hyperledger/node-vcx-wrapper') +const { ConnectionStateType } = require('@hyperledger/node-vcx-wrapper') module.exports.createPairedAliceAndFaber = async function createPairedAliceAndFaber () { const alice = await createAlice() const faber = await createFaber() const invite = await faber.createInvite() await alice.acceptInvite(invite) - await faber.updateConnection(StateType.RequestReceived) - await alice.updateConnection(StateType.Accepted) - await faber.updateConnection(StateType.Accepted) + await faber.updateConnection(ConnectionStateType.Responded) + await alice.updateConnection(ConnectionStateType.Finished) + await faber.updateConnection(ConnectionStateType.Finished) return { alice, faber } } diff --git a/libvcx/src/api_lib/api_c/connection.rs b/libvcx/src/api_lib/api_c/connection.rs index 04d82629f9..df546da640 100644 --- a/libvcx/src/api_lib/api_c/connection.rs +++ b/libvcx/src/api_lib/api_c/connection.rs @@ -8,7 +8,6 @@ use crate::api_lib::api_handle::connection; use crate::api_lib::utils_c; use crate::api_lib::utils_c::cstring::CStringUtils; use crate::api_lib::utils_c::runtime::execute; -use crate::aries::messages::a2a::A2AMessage; use crate::error::prelude::*; use crate::libindy; use crate::utils::error; @@ -548,13 +547,8 @@ pub extern fn vcx_connection_update_state_with_message(command_handle: CommandHa return VcxError::from(VcxErrorKind::InvalidConnectionHandle).into(); } - let message: A2AMessage = match serde_json::from_str(&message) { - Ok(x) => x, - Err(_) => return VcxError::from(VcxErrorKind::InvalidJson).into(), - }; - execute(move || { - let result = update_state_with_message(connection_handle, message); + let result = update_state_with_message(connection_handle, &message); let rc = match result { Ok(x) => { diff --git a/libvcx/src/api_lib/api_c/credential.rs b/libvcx/src/api_lib/api_c/credential.rs index bab4bd169f..ba50f1e736 100644 --- a/libvcx/src/api_lib/api_c/credential.rs +++ b/libvcx/src/api_lib/api_c/credential.rs @@ -989,8 +989,6 @@ pub extern fn vcx_credential_get_payment_txn(command_handle: CommandHandle, #[cfg(test)] mod tests { - extern crate serde_json; - use std::ffi::CString; use serde_json::Value; @@ -1004,6 +1002,7 @@ mod tests { use crate::utils::constants::{GET_MESSAGES_DECRYPTED_RESPONSE, V3_OBJECT_SERIALIZE_VERSION}; use crate::utils::devsetup::*; use crate::utils::mockdata::mockdata_credex::{ARIES_CREDENTIAL_OFFER, ARIES_CREDENTIAL_RESPONSE, CREDENTIAL_SM_FINISHED}; + use crate::aries::handlers::issuance::holder::holder::HolderState; use super::*; @@ -1064,21 +1063,6 @@ mod tests { assert!(handle > 0); } - #[test] - #[cfg(feature = "general_test")] - fn test_vcx_credential_send_request() { - let _setup = SetupMocks::init(); - - let handle = credential::credential_create_with_offer("test_send_request", ARIES_CREDENTIAL_OFFER).unwrap(); - assert_eq!(credential::get_state(handle).unwrap(), VcxStateType::VcxStateRequestReceived as u32); - - let connection_handle = connection::tests::build_test_connection_inviter_requested(); - - let cb = return_types_u32::Return_U32::new().unwrap(); - assert_eq!(vcx_credential_send_request(cb.command_handle, handle, connection_handle, 0, Some(cb.get_callback())), error::SUCCESS.code_num); - cb.receive(TimeoutUtils::some_medium()).unwrap(); - } - #[test] #[cfg(feature = "general_test")] fn test_vcx_credential_get_new_offers() { @@ -1119,7 +1103,7 @@ mod tests { let cb = return_types_u32::Return_U32_U32::new().unwrap(); assert_eq!(vcx_credential_get_state(cb.command_handle, handle, Some(cb.get_callback())), error::SUCCESS.code_num); - assert_eq!(cb.receive(TimeoutUtils::some_medium()).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(cb.receive(TimeoutUtils::some_medium()).unwrap(), HolderState::OfferReceived as u32); } #[test] @@ -1130,20 +1114,20 @@ mod tests { let handle_conn = connection::tests::build_test_connection_inviter_requested(); let handle_cred = _vcx_credential_create_with_offer_c_closure(ARIES_CREDENTIAL_OFFER).unwrap(); - assert_eq!(credential::get_state(handle_cred).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(credential::get_state(handle_cred).unwrap(), HolderState::OfferReceived as u32); debug!("credential handle = {}", handle_cred); let cb = return_types_u32::Return_U32::new().unwrap(); assert_eq!(vcx_credential_send_request(cb.command_handle, handle_cred, handle_conn, 0, Some(cb.get_callback())), error::SUCCESS.code_num); cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(credential::get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(credential::get_state(handle_cred).unwrap(), HolderState::RequestSent as u32); AgencyMockDecrypted::set_next_decrypted_response(GET_MESSAGES_DECRYPTED_RESPONSE); AgencyMockDecrypted::set_next_decrypted_message(ARIES_CREDENTIAL_RESPONSE); let cb = return_types_u32::Return_U32_U32::new().unwrap(); assert_eq!(vcx_v2_credential_update_state(cb.command_handle, handle_cred, handle_conn, Some(cb.get_callback())), error::SUCCESS.code_num); cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(credential::get_state(handle_cred).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(credential::get_state(handle_cred).unwrap(), HolderState::Finished as u32); let cb = return_types_u32::Return_U32_STR::new().unwrap(); assert_eq!(vcx_credential_get_rev_reg_id(cb.command_handle, handle_cred, Some(cb.get_callback())), error::SUCCESS.code_num); diff --git a/libvcx/src/api_lib/api_c/credential_def.rs b/libvcx/src/api_lib/api_c/credential_def.rs index 24234a5b93..498fd1e4ad 100644 --- a/libvcx/src/api_lib/api_c/credential_def.rs +++ b/libvcx/src/api_lib/api_c/credential_def.rs @@ -2,7 +2,6 @@ use std::ptr; use indy_sys::CommandHandle; use libc::c_char; -use serde_json; use crate::api_lib::api_handle::credential_def; use crate::api_lib::utils_c::cstring::CStringUtils; @@ -516,11 +515,9 @@ pub extern fn vcx_credentialdef_get_rev_reg_id(command_handle: CommandHandle, #[cfg(test)] mod tests { - extern crate serde_json; - use std::ffi::CString; - use crate::{api_lib, settings, utils}; + use crate::{api_lib, utils}; use crate::api_lib::utils_c::return_types_u32; use crate::api_lib::utils_c::timeout::TimeoutUtils; use crate::utils::constants::SCHEMA_ID; diff --git a/libvcx/src/api_lib/api_c/disclosed_proof.rs b/libvcx/src/api_lib/api_c/disclosed_proof.rs index e1eddccfd9..4fe7e8e6de 100644 --- a/libvcx/src/api_lib/api_c/disclosed_proof.rs +++ b/libvcx/src/api_lib/api_c/disclosed_proof.rs @@ -947,8 +947,6 @@ pub extern fn vcx_disclosed_proof_release(handle: u32) -> u32 { #[cfg(test)] mod tests { - extern crate serde_json; - use std::ffi::CString; use serde_json::Value; @@ -963,6 +961,7 @@ mod tests { use crate::utils::mockdata::mock_settings::MockBuilder; use crate::utils::mockdata::mockdata_credex::ARIES_CREDENTIAL_REQUEST; use crate::utils::mockdata::mockdata_proof::ARIES_PROOF_REQUEST_PRESENTATION; + use crate::aries::handlers::proof_presentation::prover::prover::ProverState; use super::*; @@ -1079,7 +1078,7 @@ mod tests { let _setup = SetupMocks::init(); let handle_proof = _vcx_disclosed_proof_create_with_request_c_closure(ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); - assert_eq!(disclosed_proof::get_state(handle_proof).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(disclosed_proof::get_state(handle_proof).unwrap(), ProverState::Initial as u32); let handle_conn = connection::tests::build_test_connection_inviter_requested(); @@ -1094,7 +1093,7 @@ mod tests { let _setup = SetupMocks::init(); let handle = _vcx_disclosed_proof_create_with_request_c_closure(ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); - assert_eq!(disclosed_proof::get_state(handle).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(disclosed_proof::get_state(handle).unwrap(), ProverState::Initial as u32); let connection_handle = connection::tests::build_test_connection_inviter_requested(); @@ -1111,7 +1110,7 @@ mod tests { let handle = _vcx_disclosed_proof_create_with_request_c_closure(ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); - assert_eq!(disclosed_proof::get_state(handle).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(disclosed_proof::get_state(handle).unwrap(), ProverState::Initial as u32); let _connection_handle = connection::tests::build_test_connection_inviter_requested(); @@ -1145,7 +1144,7 @@ mod tests { let cb = return_types_u32::Return_U32_U32::new().unwrap(); assert_eq!(vcx_disclosed_proof_get_state(cb.command_handle, handle, Some(cb.get_callback())), error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(state, ProverState::Initial as u32); } #[test] diff --git a/libvcx/src/api_lib/api_c/issuer_credential.rs b/libvcx/src/api_lib/api_c/issuer_credential.rs index 37b0c042a2..e980362113 100644 --- a/libvcx/src/api_lib/api_c/issuer_credential.rs +++ b/libvcx/src/api_lib/api_c/issuer_credential.rs @@ -7,7 +7,6 @@ use crate::api_lib::api_handle::{connection, credential_def, issuer_credential}; use crate::api_lib::utils_c::cstring::CStringUtils; use crate::api_lib::utils_c::runtime::execute; use crate::error::prelude::*; -use crate::settings; use crate::utils::error; /* @@ -94,16 +93,7 @@ pub extern fn vcx_issuer_create_credential(command_handle: CommandHandle, check_useful_c_str!(credential_name, VcxErrorKind::InvalidOption); check_useful_c_str!(source_id, VcxErrorKind::InvalidOption); check_useful_c_str!(price, VcxErrorKind::InvalidOption); - - let issuer_did: String = if !issuer_did.is_null() { - check_useful_c_str!(issuer_did, VcxErrorKind::InvalidOption); - issuer_did.to_owned() - } else { - match settings::get_config_value(settings::CONFIG_INSTITUTION_DID) { - Ok(x) => x, - Err(x) => return x.into() - } - }; + check_useful_c_str!(issuer_did, VcxErrorKind::InvalidOption); let price: u64 = match price.parse::() { Ok(x) => x, @@ -858,6 +848,7 @@ pub mod tests { use crate::utils::devsetup::*; use crate::utils::get_temp_dir_path; use crate::utils::mockdata::mockdata_credex::{ARIES_CREDENTIAL_REQUEST, CREDENTIAL_ISSUER_SM_FINISHED}; + use crate::aries::handlers::issuance::issuer::issuer::IssuerState; use super::*; @@ -1022,7 +1013,7 @@ pub mod tests { CString::new(ARIES_CREDENTIAL_REQUEST).unwrap().into_raw(), Some(cb.get_callback())), error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(state, IssuerState::RequestReceived as u32); } #[test] @@ -1057,7 +1048,7 @@ pub mod tests { connection_handle, Some(cb.get_callback())), error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateOfferSent as u32); + assert_eq!(state, IssuerState::OfferSent as u32); } @@ -1152,7 +1143,7 @@ pub mod tests { Some(cb.get_callback())), error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateInitialized as u32); + assert_eq!(state, IssuerState::Initial as u32); } #[test] diff --git a/libvcx/src/api_lib/api_c/proof.rs b/libvcx/src/api_lib/api_c/proof.rs index 51dad283aa..4cec1fc781 100644 --- a/libvcx/src/api_lib/api_c/proof.rs +++ b/libvcx/src/api_lib/api_c/proof.rs @@ -623,6 +623,7 @@ mod tests { use crate::utils::devsetup::*; use crate::utils::mockdata::mock_settings::MockBuilder; use crate::utils::mockdata::mockdata_proof; + use crate::aries::handlers::proof_presentation::verifier::verifier::VerifierState; use super::*; @@ -725,7 +726,7 @@ mod tests { Some(cb.get_callback())), error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateInitialized as u32); + assert_eq!(state, VerifierState::Initial as u32); } #[test] @@ -737,7 +738,7 @@ mod tests { let proof_handle = create_proof_util().unwrap(); - assert_eq!(proof::get_state(proof_handle).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(proof::get_state(proof_handle).unwrap(), VerifierState::Initial as u32); let connection_handle = build_test_connection_inviter_requested(); @@ -749,7 +750,7 @@ mod tests { error::SUCCESS.code_num); cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(proof::get_state(proof_handle).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(proof::get_state(proof_handle).unwrap(), VerifierState::PresentationRequestSent as u32); let cb = return_types_u32::Return_U32_U32::new().unwrap(); assert_eq!(vcx_v2_proof_update_state_with_message(cb.command_handle, @@ -760,7 +761,7 @@ mod tests { error::SUCCESS.code_num); let _state = cb.receive(TimeoutUtils::some_medium()).unwrap(); - assert_eq!(proof::get_state(proof_handle).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(proof::get_state(proof_handle).unwrap(), VerifierState::Finished as u32); } #[test] @@ -808,6 +809,6 @@ mod tests { let rc = vcx_proof_get_state(cb.command_handle, handle, Some(cb.get_callback())); assert_eq!(rc, error::SUCCESS.code_num); let state = cb.receive(TimeoutUtils::some_short()).unwrap(); - assert_eq!(state, VcxStateType::VcxStateOfferSent as u32); + assert_eq!(state, VerifierState::PresentationRequestSent as u32); } } diff --git a/libvcx/src/api_lib/api_c/wallet.rs b/libvcx/src/api_lib/api_c/wallet.rs index 2f9a7e4e2c..2950cfd953 100644 --- a/libvcx/src/api_lib/api_c/wallet.rs +++ b/libvcx/src/api_lib/api_c/wallet.rs @@ -13,7 +13,6 @@ use crate::init::open_as_main_wallet; use crate::libindy::utils::payments::{create_address, get_wallet_token_info, pay_a_payee, sign_with_address, verify_with_address}; use crate::libindy::utils::wallet; use crate::libindy::utils::wallet::{export_main_wallet, import, RestoreWalletConfigs, WalletConfig}; -use crate::utils; use crate::utils::error; /// Creates new wallet and master secret using provided config. Keeps wallet closed. diff --git a/libvcx/src/api_lib/api_handle/connection.rs b/libvcx/src/api_lib/api_handle/connection.rs index 7eba17760b..c4a17d1ff6 100644 --- a/libvcx/src/api_lib/api_handle/connection.rs +++ b/libvcx/src/api_lib/api_handle/connection.rs @@ -7,9 +7,7 @@ use agency_client::get_message::MessageByConnection; use agency_client::MessageStatusCode; use crate::api_lib::api_handle::object_cache::ObjectCache; -use crate::aries::handlers::connection::cloud_agent::CloudAgentInfo; -use crate::aries::handlers::connection::connection::{Connection, SmConnectionState}; -use crate::aries::handlers::connection::pairwise_info::PairwiseInfo; +use crate::aries::handlers::connection::connection::Connection; use crate::aries::messages::a2a::A2AMessage; use crate::aries::messages::connection::invite::Invitation as InvitationV3; use crate::error::prelude::*; @@ -99,7 +97,10 @@ pub fn send_generic_message(connection_handle: u32, msg: &str) -> VcxResult VcxResult { +pub fn update_state_with_message(handle: u32, message: &str) -> VcxResult { + let message: A2AMessage = serde_json::from_str(&message) + .map_err(|err| VcxError::from_msg(VcxErrorKind::InvalidJson, format!("Failed to deserialize message {} into A2AMessage, err: {:?}", message, err)))?; + CONNECTION_MAP.get_mut(handle, |connection| { connection.update_state_with_message(&message)?; Ok(error::SUCCESS.code_num) @@ -159,18 +160,6 @@ pub fn from_string(connection_data: &str) -> VcxResult { Ok(handle) } -impl Into<(SmConnectionState, PairwiseInfo, CloudAgentInfo, String)> for Connection { - fn into(self) -> (SmConnectionState, PairwiseInfo, CloudAgentInfo, String) { - (self.state_object(), self.pairwise_info().to_owned(), self.cloud_agent_info().to_owned(), self.source_id()) - } -} - -impl From<(SmConnectionState, PairwiseInfo, CloudAgentInfo, String)> for Connection { - fn from((state, pairwise_info, cloud_agent_info, source_id): (SmConnectionState, PairwiseInfo, CloudAgentInfo, String)) -> Connection { - Connection::from_parts(source_id, pairwise_info, cloud_agent_info, state, true) - } -} - pub fn release(handle: u32) -> VcxResult<()> { CONNECTION_MAP.release(handle) .or(Err(VcxError::from(VcxErrorKind::InvalidConnectionHandle))) @@ -357,8 +346,7 @@ pub mod tests { pub fn build_test_connection_inviter_requested() -> u32 { let handle = build_test_connection_inviter_invited(); - let msg: A2AMessage = serde_json::from_str(ARIES_CONNECTION_REQUEST).unwrap(); - update_state_with_message(handle, msg).unwrap(); + update_state_with_message(handle, ARIES_CONNECTION_REQUEST).unwrap(); handle } @@ -513,8 +501,7 @@ pub mod tests { let _setup = SetupMocks::init(); let handle = create_connection("test_process_acceptance_message").unwrap(); - let message = serde_json::from_str(ARIES_CONNECTION_REQUEST).unwrap(); - assert_eq!(error::SUCCESS.code_num, update_state_with_message(handle, message).unwrap()); + assert_eq!(error::SUCCESS.code_num, update_state_with_message(handle, ARIES_CONNECTION_REQUEST).unwrap()); } #[test] diff --git a/libvcx/src/api_lib/api_handle/credential.rs b/libvcx/src/api_lib/api_handle/credential.rs index b04a3864bf..3e8707e5f1 100644 --- a/libvcx/src/api_lib/api_handle/credential.rs +++ b/libvcx/src/api_lib/api_handle/credential.rs @@ -86,7 +86,7 @@ pub fn credential_create_with_msgid(source_id: &str, connection_handle: u32, msg pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) -> VcxResult { HANDLE_MAP.get_mut(handle, |credential| { trace!("credential::update_state >>> "); - if credential.is_terminal_state() { return Ok(credential.get_state()); } + if credential.is_terminal_state() { return Ok(credential.get_state().into()); } let send_message = connection::send_message_closure(connection_handle)?; if let Some(message) = message { @@ -100,7 +100,7 @@ pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) connection::update_message_status(connection_handle, uid)?; } } - Ok(credential.get_state()) + Ok(credential.get_state().into()) }) } @@ -170,7 +170,7 @@ pub fn get_credential_offer(handle: u32) -> VcxResult { pub fn get_state(handle: u32) -> VcxResult { HANDLE_MAP.get(handle, |credential| { - Ok(credential.get_state()) + Ok(credential.get_state().into()) }).map_err(handle_err) } @@ -287,12 +287,12 @@ pub fn get_credential_status(handle: u32) -> VcxResult { pub mod tests { use crate::api_lib::api_handle::connection; use crate::api_lib::api_handle::credential::{credential_create_with_offer, get_attributes, get_credential, send_credential_request}; - use crate::api_lib::VcxStateType; use crate::aries::messages::issuance::credential::Credential; use crate::error::VcxErrorKind; use crate::utils::devsetup::*; use crate::utils::mockdata::mockdata_credex::{ARIES_CREDENTIAL_OFFER, ARIES_CREDENTIAL_OFFER_JSON_FORMAT, ARIES_CREDENTIAL_RESPONSE, CREDENTIAL_SM_FINISHED, CREDENTIAL_SM_OFFER_RECEIVED}; use crate::utils::mockdata::mockdata_credex; + use crate::aries::handlers::issuance::holder::holder::HolderState; use super::*; @@ -363,7 +363,7 @@ pub mod tests { info!("full_credential_test:: going to credential_create_with_offer"); let handle_cred = credential_create_with_offer("TEST_CREDENTIAL", &offer).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle_cred).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(); @@ -374,14 +374,14 @@ pub mod tests { info!("full_credential_test:: going to send_credential_request"); send_credential_request(handle_cred, handle_conn).unwrap(); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, get_state(handle_cred).unwrap()); + assert_eq!(HolderState::RequestSent 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).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateAccepted as u32); + 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(); @@ -405,7 +405,7 @@ pub mod tests { let _setup = SetupMocks::init(); let handle_cred = credential_create_with_offer("TEST_CREDENTIAL", ARIES_CREDENTIAL_OFFER_JSON_FORMAT).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle_cred).unwrap()); + assert_eq!(HolderState::OfferReceived as u32, get_state(handle_cred).unwrap()); let offer_attrs: String = get_attributes(handle_cred).unwrap(); let offer_attrs: serde_json::Value = serde_json::from_str(&offer_attrs).unwrap(); @@ -427,7 +427,7 @@ pub mod tests { let their_pw_did = connection::get_their_pw_did(connection_h).unwrap(); let c_h = credential_create_with_offer("TEST_CREDENTIAL", &offer).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(c_h).unwrap()); + assert_eq!(HolderState::OfferReceived as u32, get_state(c_h).unwrap()); let msg = generate_credential_request_msg(c_h, &my_pw_did, &their_pw_did).unwrap(); // serde_json::from_str::(&msg).unwrap(); diff --git a/libvcx/src/api_lib/api_handle/disclosed_proof.rs b/libvcx/src/api_lib/api_handle/disclosed_proof.rs index 121dc887ff..3fd080d3e9 100644 --- a/libvcx/src/api_lib/api_handle/disclosed_proof.rs +++ b/libvcx/src/api_lib/api_handle/disclosed_proof.rs @@ -67,7 +67,7 @@ pub fn create_proof_with_msgid(source_id: &str, connection_handle: u32, msg_id: pub fn get_state(handle: u32) -> VcxResult { HANDLE_MAP.get(handle, |proof| { - Ok(proof.state()) + Ok(proof.get_state().into()) }).or(Err(VcxError::from(VcxErrorKind::InvalidConnectionHandle))) } @@ -76,7 +76,7 @@ pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) trace!("disclosed_proof::update_state >>> connection_handle: {:?}, message: {:?}", connection_handle, message); if !proof.has_transitions() { trace!("disclosed_proof::update_state >> found no available transition"); - return Ok(proof.state()); + return Ok(proof.get_state().into()); } let send_message = connection::send_message_closure(connection_handle)?; @@ -93,7 +93,7 @@ pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) connection::update_message_status(connection_handle, uid)?; }; } - Ok(proof.state()) + Ok(proof.get_state().into()) }) } @@ -259,7 +259,6 @@ mod tests { use serde_json::Value; - use crate::api_lib::VcxStateType; use crate::aries::messages::proof_presentation::presentation_request::PresentationRequestData; use crate::utils; use crate::utils::constants::{ARIES_PROVER_CREDENTIALS, ARIES_PROVER_SELF_ATTESTED_ATTRS, GET_MESSAGES_DECRYPTED_RESPONSE}; @@ -267,6 +266,7 @@ mod tests { use crate::utils::mockdata::mock_settings::MockBuilder; use crate::utils::mockdata::mockdata_proof; use crate::utils::mockdata::mockdata_proof::{ARIES_PROOF_PRESENTATION_ACK, ARIES_PROOF_REQUEST_PRESENTATION}; + use crate::aries::handlers::proof_presentation::prover::prover::ProverState; use super::*; @@ -306,17 +306,17 @@ mod tests { let request = _get_proof_request_messages(connection_h); let handle_proof = create_proof("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle_proof).unwrap()); + assert_eq!(ProverState::Initial as u32, get_state(handle_proof).unwrap()); let _mock_builder = MockBuilder::init(). set_mock_generate_indy_proof("{\"selected\":\"credentials\"}"); generate_proof(handle_proof, String::from("{\"selected\":\"credentials\"}"), "{}".to_string()).unwrap(); send_proof(handle_proof, connection_h).unwrap(); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, get_state(handle_proof).unwrap()); + assert_eq!(ProverState::PresentationSent as u32, get_state(handle_proof).unwrap()); update_state(handle_proof, Some(ARIES_PROOF_PRESENTATION_ACK), connection_h).unwrap(); - assert_eq!(VcxStateType::VcxStateAccepted as u32, get_state(handle_proof).unwrap()); + assert_eq!(ProverState::Finished as u32, get_state(handle_proof).unwrap()); } #[test] @@ -332,13 +332,13 @@ mod tests { let request = _get_proof_request_messages(connection_handle); let handle = create_proof("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::Initial as u32, get_state(handle).unwrap()); generate_proof(handle, ARIES_PROVER_CREDENTIALS.to_string(), ARIES_PROVER_SELF_ATTESTED_ATTRS.to_string()).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::PresentationPrepared as u32, get_state(handle).unwrap()); send_proof(handle, connection_handle).unwrap(); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::PresentationSent as u32, get_state(handle).unwrap()); connection::release(connection_handle).unwrap(); let connection_handle = connection::tests::build_test_connection_inviter_requested(); @@ -347,7 +347,7 @@ mod tests { AgencyMockDecrypted::set_next_decrypted_message(mockdata_proof::ARIES_PROOF_PRESENTATION_ACK); update_state(handle, None, connection_handle).unwrap(); - assert_eq!(VcxStateType::VcxStateAccepted as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::Finished as u32, get_state(handle).unwrap()); } #[test] @@ -363,10 +363,10 @@ mod tests { let request = _get_proof_request_messages(connection_h); let handle = create_proof("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::Initial as u32, get_state(handle).unwrap()); reject_proof(handle, connection_h).unwrap(); - assert_eq!(VcxStateType::VcxStateNone as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::Failed as u32, get_state(handle).unwrap()); } #[test] @@ -375,7 +375,7 @@ mod tests { let _setup = SetupMocks::init(); let handle = create_proof("id", ARIES_PROOF_REQUEST_PRESENTATION).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle).unwrap()) + assert_eq!(ProverState::Initial as u32, get_state(handle).unwrap()) } #[test] @@ -436,7 +436,7 @@ mod tests { let request = _get_proof_request_messages(connection_h); let handle = create_proof("TEST_CREDENTIAL", &request).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, get_state(handle).unwrap()); + assert_eq!(ProverState::Initial 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/src/api_lib/api_handle/issuer_credential.rs b/libvcx/src/api_lib/api_handle/issuer_credential.rs index f04cbd4627..74d72ac8c7 100644 --- a/libvcx/src/api_lib/api_handle/issuer_credential.rs +++ b/libvcx/src/api_lib/api_handle/issuer_credential.rs @@ -39,7 +39,7 @@ pub fn issuer_credential_create(cred_def_handle: u32, pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) -> VcxResult { ISSUER_CREDENTIAL_MAP.get_mut(handle, |credential| { trace!("issuer_credential::update_state >>> "); - if credential.is_terminal_state() { return credential.get_state(); } + if credential.is_terminal_state() { return Ok(credential.get_state().into()); } let send_message = connection::send_message_closure(connection_handle)?; if let Some(message) = message { @@ -53,13 +53,13 @@ pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) connection::update_message_status(connection_handle, uid)?; } } - credential.get_state() + Ok(credential.get_state().into()) }) } pub fn get_state(handle: u32) -> VcxResult { ISSUER_CREDENTIAL_MAP.get(handle, |credential| { - credential.get_state() + Ok(credential.get_state().into()) }) } @@ -178,7 +178,6 @@ pub mod tests { use crate::api_lib::api_handle::connection::tests::build_test_connection_inviter_requested; use crate::api_lib::api_handle::credential_def::tests::create_cred_def_fake; use crate::api_lib::api_handle::issuer_credential; - use crate::api_lib::VcxStateType; use crate::libindy::utils::anoncreds::libindy_create_and_store_credential_def; use crate::libindy::utils::LibindyMock; use crate::settings; @@ -187,6 +186,7 @@ pub mod tests { use crate::utils::devsetup::*; use crate::utils::mockdata::mockdata_connection::ARIES_CONNECTION_ACK; use crate::utils::mockdata::mockdata_credex::ARIES_CREDENTIAL_REQUEST; + use crate::aries::handlers::issuance::issuer::issuer::IssuerState; use super::*; @@ -236,7 +236,7 @@ pub mod tests { let handle_cred = _issuer_credential_create(); assert_eq!(send_credential_offer(handle_cred, handle_conn, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); } #[cfg(feature = "pool_tests")] @@ -257,17 +257,17 @@ pub mod tests { let connection_handle = build_test_connection_inviter_requested(); let handle = _issuer_credential_create(); - assert_eq!(get_state(handle).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle).unwrap(), IssuerState::Initial as u32); LibindyMock::set_next_result(error::TIMEOUT_LIBINDY_ERROR.code_num); let res = send_credential_offer(handle, connection_handle, None).unwrap_err(); assert_eq!(res.kind(), VcxErrorKind::InvalidState); - assert_eq!(get_state(handle).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle).unwrap(), IssuerState::Initial as u32); // Can retry after initial failure assert_eq!(send_credential_offer(handle, connection_handle, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle).unwrap(), IssuerState::OfferSent as u32); } #[test] @@ -278,27 +278,27 @@ pub mod tests { let handle_conn = build_test_connection_inviter_requested(); let handle_cred = _issuer_credential_create(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::Initial as u32); assert_eq!(get_rev_reg_id(handle_cred).unwrap(), REV_REG_ID); assert_eq!(send_credential_offer(handle_cred, handle_conn, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); assert_eq!(get_rev_reg_id(handle_cred).unwrap(), REV_REG_ID); issuer_credential::update_state(handle_cred, Some(ARIES_CREDENTIAL_REQUEST), handle_conn).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::RequestReceived as u32); assert_eq!(get_rev_reg_id(handle_cred).unwrap(), REV_REG_ID); // First attempt to send credential fails HttpClientMockResponse::set_next_response(agency_client::error::AgencyClientResult::Err(agency_client::error::AgencyClientError::from_msg(agency_client::error::AgencyClientErrorKind::IOError, "Sending message timeout."))); let send_result = issuer_credential::send_credential(handle_cred, handle_conn); assert_eq!(send_result.is_err(), true); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::RequestReceived as u32); assert_eq!(get_rev_reg_id(handle_cred).unwrap(), REV_REG_ID); // Can retry after initial failure issuer_credential::send_credential(handle_cred, handle_conn).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::Finished as u32); assert_eq!(get_rev_reg_id(handle_cred).unwrap(), REV_REG_ID); } @@ -331,10 +331,10 @@ pub mod tests { let handle_cred = _issuer_credential_create(); assert_eq!(send_credential_offer(handle_cred, handle_conn, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); issuer_credential::update_state(handle_cred, Some(ARIES_CREDENTIAL_REQUEST), handle_conn).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::RequestReceived as u32); } #[test] @@ -346,12 +346,12 @@ pub mod tests { let handle_cred = _issuer_credential_create(); assert_eq!(send_credential_offer(handle_cred, handle_conn, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); // try to update state with nonsense message let result = issuer_credential::update_state(handle_cred, Some(ARIES_CONNECTION_ACK), handle_conn); 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(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); } #[test] @@ -389,16 +389,16 @@ pub mod tests { let handle_conn = build_test_connection_inviter_requested(); let handle_cred = _issuer_credential_create(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::Initial as u32); assert_eq!(send_credential_offer(handle_cred, handle_conn, None).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::OfferSent as u32); issuer_credential::update_state(handle_cred, Some(ARIES_CREDENTIAL_REQUEST), handle_conn).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateRequestReceived as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::RequestReceived as u32); issuer_credential::send_credential(handle_cred, handle_conn).unwrap(); - assert_eq!(get_state(handle_cred).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_cred).unwrap(), IssuerState::Finished as u32); let revoc_result = issuer_credential::revoke_credential(handle_cred); assert_eq!(revoc_result.unwrap_err().kind(), VcxErrorKind::InvalidRevocationDetails) diff --git a/libvcx/src/api_lib/api_handle/proof.rs b/libvcx/src/api_lib/api_handle/proof.rs index 1e557f9348..730c326a5c 100644 --- a/libvcx/src/api_lib/api_handle/proof.rs +++ b/libvcx/src/api_lib/api_handle/proof.rs @@ -35,7 +35,7 @@ pub fn is_valid_handle(handle: u32) -> bool { pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) -> VcxResult { PROOF_MAP.get_mut(handle, |proof| { trace!("proof::update_state >>> handle: {}, message: {:?}, connection_handle: {}", handle, message, connection_handle); - if !proof.has_transitions() { return Ok(proof.state()); } + if !proof.has_transitions() { return Ok(proof.get_state().into()); } let send_message = connection::send_message_closure(connection_handle)?; if let Some(message) = message { @@ -51,13 +51,13 @@ pub fn update_state(handle: u32, message: Option<&str>, connection_handle: u32) connection::update_message_status(connection_handle, uid)?; }; } - Ok(proof.state()) + Ok(proof.get_state().into()) }) } pub fn get_state(handle: u32) -> VcxResult { PROOF_MAP.get(handle, |proof| { - Ok(proof.state()) + Ok(proof.get_state().into()) }) } @@ -124,13 +124,13 @@ pub mod tests { use crate::api_lib::api_handle::connection::tests::build_test_connection_inviter_requested; use crate::api_lib::api_handle::proof; - use crate::api_lib::VcxStateType; use crate::aries::handlers::proof_presentation::verifier::verifier::Verifier; use crate::aries::messages::proof_presentation::presentation::tests::_comment; use crate::utils::constants::*; use crate::utils::devsetup::*; use crate::utils::mockdata::mock_settings::MockBuilder; use crate::utils::mockdata::mockdata_proof; + use crate::aries::handlers::proof_presentation::verifier::verifier::VerifierState; use super::*; @@ -212,7 +212,7 @@ pub mod tests { let handle_proof = create_default_proof(); assert_eq!(send_proof_request(handle_proof, handle_conn, _comment()).unwrap(), error::SUCCESS.code_num); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); } #[test] @@ -236,14 +236,14 @@ pub mod tests { let handle_proof = create_default_proof(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); connection::release(handle_conn).unwrap(); let handle_conn = build_test_connection_inviter_requested(); update_state(handle_proof, Some(mockdata_proof::ARIES_PROOF_PRESENTATION), handle_conn).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Finished as u32); } #[test] @@ -257,10 +257,10 @@ pub mod tests { let handle_proof = create_default_proof(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); update_state(handle_proof, Some(mockdata_proof::ARIES_PROOF_PRESENTATION), handle_conn).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Finished as u32); } #[test] @@ -274,10 +274,10 @@ pub mod tests { let handle_proof = create_default_proof(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); update_state(handle_proof, Some(mockdata_proof::ARIES_PROOF_PRESENTATION), handle_conn).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Finished as u32); } #[test] @@ -291,7 +291,7 @@ pub mod tests { send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); update_state(handle_proof, Some(PROOF_REJECT_RESPONSE_STR_V2), handle_conn).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateNone as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Failed as u32); } #[test] @@ -303,7 +303,7 @@ pub mod tests { let handle_proof = create_default_proof(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); } #[test] @@ -317,10 +317,10 @@ pub mod tests { let handle_proof = create_default_proof(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); update_state(handle_proof, Some(mockdata_proof::ARIES_PROOF_PRESENTATION), handle_conn).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Finished as u32); let proof_str = get_proof(handle_proof).unwrap(); assert_eq!(proof_str, mockdata_proof::ARIES_PROOF_PRESENTATION.replace("\n", "").replace(" ", "")); @@ -353,15 +353,15 @@ pub mod tests { let handle_proof = create_default_proof(); let _request = generate_proof_request_msg(handle_proof).unwrap(); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Initial as u32); HttpClientMockResponse::set_next_response(agency_client::error::AgencyClientResult::Err(agency_client::error::AgencyClientError::from_msg(agency_client::error::AgencyClientErrorKind::IOError, "Sending message timeout."))); assert_eq!(send_proof_request(handle_proof, handle_conn, _comment()).unwrap_err().kind(), VcxErrorKind::IOError); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateInitialized as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::Initial as u32); // Retry sending proof request assert_eq!(send_proof_request(handle_proof, handle_conn, _comment()).unwrap(), 0); - assert_eq!(get_state(handle_proof).unwrap(), VcxStateType::VcxStateOfferSent as u32); + assert_eq!(get_state(handle_proof).unwrap(), VerifierState::PresentationRequestSent as u32); } #[test] @@ -377,7 +377,7 @@ pub mod tests { let _request = generate_proof_request_msg(handle_proof).unwrap(); send_proof_request(handle_proof, handle_conn, _comment()).unwrap(); update_state(handle_proof, Some(mockdata_proof::ARIES_PROOF_PRESENTATION), handle_conn).unwrap(); - assert_eq!(proof::get_state(handle_proof).unwrap(), VcxStateType::VcxStateAccepted as u32); + assert_eq!(proof::get_state(handle_proof).unwrap(), VerifierState::Finished as u32); } #[test] diff --git a/libvcx/src/api_lib/utils_c/fsm_states.rs b/libvcx/src/api_lib/utils_c/fsm_states.rs index ff7b72b518..927ccb7732 100644 --- a/libvcx/src/api_lib/utils_c/fsm_states.rs +++ b/libvcx/src/api_lib/utils_c/fsm_states.rs @@ -1,6 +1,10 @@ use crate::aries::handlers::connection::connection::ConnectionState; use crate::aries::handlers::connection::invitee::state_machine::InviteeState; use crate::aries::handlers::connection::inviter::state_machine::InviterState; +use crate::aries::handlers::issuance::holder::holder::HolderState; +use crate::aries::handlers::issuance::issuer::issuer::IssuerState; +use crate::aries::handlers::proof_presentation::prover::prover::ProverState; +use crate::aries::handlers::proof_presentation::verifier::verifier::VerifierState; impl From for u32 { fn from(state: ConnectionState) -> u32 { @@ -26,3 +30,51 @@ impl From for u32 { } } } + +impl From for u32 { + fn from(state: HolderState) -> u32 { + match state { + HolderState::OfferReceived => 0, + HolderState::RequestSent => 1, + HolderState::Finished => 2, + HolderState::Failed => 3 + } + } +} + +impl From for u32 { + fn from(state: IssuerState) -> u32 { + match state { + IssuerState::Initial => 0, + IssuerState::OfferSent => 1, + IssuerState::RequestReceived => 2, + IssuerState::CredentialSent => 3, + IssuerState::Finished => 4, + IssuerState::Failed => 5 + } + } +} + +impl From for u32 { + fn from(state: ProverState) -> u32 { + match state { + ProverState::Initial => 0, + ProverState::PresentationPrepared => 1, + ProverState::PresentationPreparationFailed => 2, + ProverState::PresentationSent => 3, + ProverState::Finished => 4, + ProverState::Failed => 5 + } + } +} + +impl From for u32 { + fn from(state: VerifierState) -> u32 { + match state { + VerifierState::Initial => 0, + VerifierState::PresentationRequestSent => 1, + VerifierState::Finished => 2, + VerifierState::Failed => 3 + } + } +} diff --git a/libvcx/src/aries/handlers/connection/connection.rs b/libvcx/src/aries/handlers/connection/connection.rs index da279edec8..dba5ef77cb 100644 --- a/libvcx/src/aries/handlers/connection/connection.rs +++ b/libvcx/src/aries/handlers/connection/connection.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::de::{EnumAccess, Error, MapAccess, SeqAccess, Unexpected, Visitor}; use serde_json::Value; -use agency_client::get_message::{Message, MessageByConnection}; +use agency_client::get_message::Message; use agency_client::MessageStatusCode; use crate::aries::handlers::connection::cloud_agent::CloudAgentInfo; @@ -54,7 +54,6 @@ pub enum ConnectionState { Invitee(InviteeState), } - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SideConnectionInfo { @@ -746,6 +745,19 @@ impl<'de> Deserialize<'de> for Connection { } } +impl Into<(SmConnectionState, PairwiseInfo, CloudAgentInfo, String)> for Connection { + fn into(self) -> (SmConnectionState, PairwiseInfo, CloudAgentInfo, String) { + (self.state_object(), self.pairwise_info().to_owned(), self.cloud_agent_info().to_owned(), self.source_id()) + } +} + +impl From<(SmConnectionState, PairwiseInfo, CloudAgentInfo, String)> for Connection { + fn from((state, pairwise_info, cloud_agent_info, source_id): (SmConnectionState, PairwiseInfo, CloudAgentInfo, String)) -> Connection { + Connection::from_parts(source_id, pairwise_info, cloud_agent_info, state, true) + } +} + + #[cfg(test)] pub mod tests { use std::thread; diff --git a/libvcx/src/aries/handlers/connection/invitee/state_machine.rs b/libvcx/src/aries/handlers/connection/invitee/state_machine.rs index 9d2a77664e..a45d0eb61b 100644 --- a/libvcx/src/aries/handlers/connection/invitee/state_machine.rs +++ b/libvcx/src/aries/handlers/connection/invitee/state_machine.rs @@ -38,7 +38,7 @@ pub enum InviteeFullState { Completed(CompleteState), } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, PartialEq)] pub enum InviteeState { Null, Invited, diff --git a/libvcx/src/aries/handlers/connection/inviter/state_machine.rs b/libvcx/src/aries/handlers/connection/inviter/state_machine.rs index 97e6be6d48..51d984ee02 100644 --- a/libvcx/src/aries/handlers/connection/inviter/state_machine.rs +++ b/libvcx/src/aries/handlers/connection/inviter/state_machine.rs @@ -37,7 +37,7 @@ pub enum InviterFullState { Completed(CompleteState), } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, PartialEq)] pub enum InviterState { Null, Invited, diff --git a/libvcx/src/aries/handlers/issuance/holder/holder.rs b/libvcx/src/aries/handlers/issuance/holder/holder.rs index 45fbfefff5..8ec9e00046 100644 --- a/libvcx/src/aries/handlers/issuance/holder/holder.rs +++ b/libvcx/src/aries/handlers/issuance/holder/holder.rs @@ -12,6 +12,14 @@ pub struct Holder { holder_sm: HolderSM } +#[derive(Debug, PartialEq)] +pub enum HolderState { + OfferReceived, + RequestSent, + Finished, + Failed +} + impl Holder { pub fn create(credential_offer: CredentialOffer, source_id: &str) -> VcxResult { trace!("Holder::holder_create_credential >>> credential_offer: {:?}, source_id: {:?}", credential_offer, source_id); @@ -33,8 +41,8 @@ impl Holder { self.holder_sm.find_message_to_handle(messages) } - pub fn get_state(&self) -> u32 { - self.holder_sm.state() + pub fn get_state(&self) -> HolderState { + self.holder_sm.get_state() } pub fn get_source_id(&self) -> String { @@ -82,7 +90,7 @@ impl Holder { Ok(()) } - pub fn update_state(&mut self, connection: &Connection) -> VcxResult { + pub fn update_state(&mut self, connection: &Connection) -> VcxResult { trace!("Holder::update_state >>> "); if self.is_terminal_state() { return Ok(self.get_state()); } let send_message = connection.send_message_closure()?; diff --git a/libvcx/src/aries/handlers/issuance/holder/state_machine.rs b/libvcx/src/aries/handlers/issuance/holder/state_machine.rs index 0db9e931c2..6d34f4a29c 100644 --- a/libvcx/src/aries/handlers/issuance/holder/state_machine.rs +++ b/libvcx/src/aries/handlers/issuance/holder/state_machine.rs @@ -1,9 +1,9 @@ use std::collections::HashMap; -use crate::api_lib::VcxStateType; use crate::aries::handlers::issuance::holder::states::finished::FinishedHolderState; use crate::aries::handlers::issuance::holder::states::offer_received::OfferReceivedState; use crate::aries::handlers::issuance::holder::states::request_sent::RequestSentState; +use crate::aries::handlers::issuance::holder::holder::HolderState; use crate::aries::handlers::issuance::messages::CredentialIssuanceMessage; use crate::aries::messages::a2a::A2AMessage; use crate::aries::messages::error::ProblemReport; @@ -16,7 +16,7 @@ use crate::error::prelude::*; use crate::libindy::utils::anoncreds::{self, get_cred_def_json, libindy_prover_create_credential_req, libindy_prover_delete_credential, libindy_prover_store_credential}; #[derive(Serialize, Deserialize, Debug, Clone)] -pub enum HolderState { +pub enum HolderFullState { OfferReceived(OfferReceivedState), RequestSent(RequestSentState), Finished(FinishedHolderState), @@ -24,7 +24,7 @@ pub enum HolderState { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HolderSM { - state: HolderState, + state: HolderFullState, source_id: String, thread_id: String, } @@ -33,7 +33,7 @@ impl HolderSM { pub fn new(offer: CredentialOffer, source_id: String) -> Self { HolderSM { thread_id: offer.id.0.clone(), - state: HolderState::OfferReceived(OfferReceivedState::new(offer)), + state: HolderFullState::OfferReceived(OfferReceivedState::new(offer)), source_id, } } @@ -42,14 +42,14 @@ impl HolderSM { self.source_id.clone() } - pub fn state(&self) -> u32 { + pub fn get_state(&self) -> HolderState { match self.state { - HolderState::OfferReceived(_) => VcxStateType::VcxStateRequestReceived as u32, - HolderState::RequestSent(_) => VcxStateType::VcxStateOfferSent as u32, - HolderState::Finished(ref status) => { + HolderFullState::OfferReceived(_) => HolderState::OfferReceived, + HolderFullState::RequestSent(_) => HolderState::RequestSent, + HolderFullState::Finished(ref status) => { match status.status { - Status::Success => VcxStateType::VcxStateAccepted as u32, - _ => VcxStateType::VcxStateNone as u32, + Status::Success => HolderState::Finished, + _ => HolderState::Failed } } } @@ -60,10 +60,10 @@ impl HolderSM { for (uid, message) in messages { match self.state { - HolderState::OfferReceived(_) => { + HolderFullState::OfferReceived(_) => { // do not process messages } - HolderState::RequestSent(_) => { + HolderFullState::RequestSent(_) => { match message { A2AMessage::Credential(credential) => { if credential.from_thread(&self.thread_id) { @@ -78,7 +78,7 @@ impl HolderSM { _ => {} } } - HolderState::Finished(_) => { + HolderFullState::Finished(_) => { // do not process messages } }; @@ -87,7 +87,7 @@ impl HolderSM { None } - pub fn step(state: HolderState, source_id: String, thread_id: String) -> Self { + pub fn step(state: HolderFullState, source_id: String, thread_id: String) -> Self { HolderSM { state, source_id, thread_id } } @@ -96,7 +96,7 @@ impl HolderSM { let HolderSM { state, source_id, thread_id } = self; let state = match state { - HolderState::OfferReceived(state_data) => match cim { + HolderFullState::OfferReceived(state_data) => match cim { CredentialIssuanceMessage::CredentialRequestSend(my_pw_did) => { let request = _make_credential_request(my_pw_did, &state_data.offer); match request { @@ -106,7 +106,7 @@ impl HolderSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&cred_request.to_a2a_message())?; - HolderState::RequestSent((state_data, req_meta, cred_def_json).into()) + HolderFullState::RequestSent((state_data, req_meta, cred_def_json).into()) } Err(err) => { let problem_report = ProblemReport::create() @@ -115,16 +115,16 @@ impl HolderSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&problem_report.to_a2a_message())?; - HolderState::Finished((state_data, problem_report).into()) + HolderFullState::Finished((state_data, problem_report).into()) } } } _ => { warn!("Credential Issuance can only start on holder side with Credential Offer"); - HolderState::OfferReceived(state_data) + HolderFullState::OfferReceived(state_data) } }, - HolderState::RequestSent(state_data) => match cim { + HolderFullState::RequestSent(state_data) => match cim { CredentialIssuanceMessage::Credential(credential) => { let result = _store_credential(&credential, &state_data.req_meta, &state_data.cred_def_json); match result { @@ -136,7 +136,7 @@ impl HolderSM { )?(&A2AMessage::CredentialAck(ack))?; } - HolderState::Finished((state_data, cred_id, credential, rev_reg_def_json).into()) + HolderFullState::Finished((state_data, cred_id, credential, rev_reg_def_json).into()) } Err(err) => { let problem_report = ProblemReport::create() @@ -145,21 +145,21 @@ impl HolderSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&problem_report.to_a2a_message())?; - HolderState::Finished((state_data, problem_report).into()) + HolderFullState::Finished((state_data, problem_report).into()) } } } CredentialIssuanceMessage::ProblemReport(problem_report) => { - HolderState::Finished((state_data, problem_report).into()) + HolderFullState::Finished((state_data, problem_report).into()) } _ => { warn!("In this state Credential Issuance can accept only Credential and Problem Report"); - HolderState::RequestSent(state_data) + HolderFullState::RequestSent(state_data) } }, - HolderState::Finished(state_data) => { + HolderFullState::Finished(state_data) => { warn!("Exchange is finished, no messages can be sent or received"); - HolderState::Finished(state_data) + HolderFullState::Finished(state_data) } }; Ok(HolderSM::step(state, source_id, thread_id)) @@ -167,21 +167,21 @@ impl HolderSM { pub fn credential_status(&self) -> u32 { match self.state { - HolderState::Finished(ref state) => state.status.code(), + HolderFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code() } } pub fn is_terminal_state(&self) -> bool { match self.state { - HolderState::Finished(_) => true, + HolderFullState::Finished(_) => true, _ => false } } pub fn get_credential(&self) -> VcxResult<(String, A2AMessage)> { match self.state { - HolderState::Finished(ref state) => { + HolderFullState::Finished(ref state) => { let cred_id = state.cred_id.clone().ok_or(VcxError::from_msg(VcxErrorKind::InvalidState, "Cannot get credential: Credential Id not found"))?; let credential = state.credential.clone().ok_or(VcxError::from_msg(VcxErrorKind::InvalidState, "Cannot get credential: Credential not found"))?; Ok((cred_id, credential.to_a2a_message())) @@ -192,46 +192,46 @@ impl HolderSM { pub fn get_attributes(&self) -> VcxResult { match self.state { - HolderState::Finished(ref state) => state.get_attributes(), - HolderState::OfferReceived(ref state) => state.get_attributes(), + HolderFullState::Finished(ref state) => state.get_attributes(), + HolderFullState::OfferReceived(ref state) => state.get_attributes(), _ => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot get credential attributes: credential offer or credential must be receieved first")) } } pub fn get_attachment(&self) -> VcxResult { match self.state { - HolderState::Finished(ref state) => state.get_attachment(), - HolderState::OfferReceived(ref state) => state.get_attachment(), + HolderFullState::Finished(ref state) => state.get_attachment(), + HolderFullState::OfferReceived(ref state) => state.get_attachment(), _ => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot get credential attachment: credential offer or credential must be receieved first")) } } pub fn get_tails_location(&self) -> VcxResult { match self.state { - HolderState::Finished(ref state) => state.get_tails_location(), + HolderFullState::Finished(ref state) => state.get_tails_location(), _ => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot get tails location: credential exchange not finished yet")) } } pub fn get_tails_hash(&self) -> VcxResult { match self.state { - HolderState::Finished(ref state) => state.get_tails_hash(), + HolderFullState::Finished(ref state) => state.get_tails_hash(), _ => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot get tails hash: credential exchange not finished yet")) } } pub fn get_rev_reg_id(&self) -> VcxResult { match self.state { - HolderState::Finished(ref state) => state.get_rev_reg_id(), + HolderFullState::Finished(ref state) => state.get_rev_reg_id(), _ => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot get tails hash: credential exchange not finished yet")) } } pub fn is_revokable(&self) -> VcxResult { match self.state { - HolderState::OfferReceived(ref state) => state.is_revokable(), - HolderState::RequestSent(ref state) => state.is_revokable(), - HolderState::Finished(ref state) => state.is_revokable() + HolderFullState::OfferReceived(ref state) => state.is_revokable(), + HolderFullState::RequestSent(ref state) => state.is_revokable(), + HolderFullState::Finished(ref state) => state.is_revokable() } } @@ -239,7 +239,7 @@ impl HolderSM { trace!("Holder::delete_credential"); match self.state { - HolderState::Finished(ref state) => { + HolderFullState::Finished(ref state) => { let cred_id = state.cred_id.clone().ok_or(VcxError::from_msg(VcxErrorKind::InvalidState, "Cannot get credential: credential id not found"))?; _delete_credential(&cred_id) } @@ -362,7 +362,7 @@ mod test { let holder_sm = _holder_sm(); - assert_match!(HolderState::OfferReceived(_), holder_sm.state); + assert_match!(HolderFullState::OfferReceived(_), holder_sm.state); assert_eq!(source_id(), holder_sm.get_source_id()); } } @@ -376,7 +376,7 @@ mod test { let _setup = SetupMocks::init(); let holder_sm = _holder_sm(); - assert_match!(HolderState::OfferReceived(_), holder_sm.state); + assert_match!(HolderFullState::OfferReceived(_), holder_sm.state); } #[test] @@ -387,7 +387,7 @@ mod test { let mut holder_sm = _holder_sm(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); - assert_match!(HolderState::RequestSent(_), holder_sm.state); + assert_match!(HolderFullState::RequestSent(_), holder_sm.state); } #[test] @@ -400,7 +400,7 @@ mod test { let mut holder_sm = HolderSM::new(credential_offer, "test source".to_string()); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), holder_sm.credential_status()); } @@ -411,10 +411,10 @@ mod test { let mut holder_sm = _holder_sm(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); - assert_match!(HolderState::OfferReceived(_), holder_sm.state); + assert_match!(HolderFullState::OfferReceived(_), holder_sm.state); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::ProblemReport(_problem_report()), _send_message()).unwrap(); - assert_match!(HolderState::OfferReceived(_), holder_sm.state); + assert_match!(HolderFullState::OfferReceived(_), holder_sm.state); } #[test] @@ -426,7 +426,7 @@ mod test { holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); assert_eq!(Status::Success.code(), holder_sm.credential_status()); } @@ -439,7 +439,7 @@ mod test { holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::Credential(Credential::create()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), holder_sm.credential_status()); } @@ -452,7 +452,7 @@ mod test { holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::ProblemReport(_problem_report()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), holder_sm.credential_status()); } @@ -465,10 +465,10 @@ mod test { holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialRequestSend(_my_pw_did()), _send_message()).unwrap(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialOffer(_credential_offer()), _send_message()).unwrap(); - assert_match!(HolderState::RequestSent(_), holder_sm.state); + assert_match!(HolderFullState::RequestSent(_), holder_sm.state); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialAck(_ack()), _send_message()).unwrap(); - assert_match!(HolderState::RequestSent(_), holder_sm.state); + assert_match!(HolderFullState::RequestSent(_), holder_sm.state); } #[test] @@ -481,13 +481,13 @@ mod test { holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialOffer(_credential_offer()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); holder_sm = holder_sm.handle_message(CredentialIssuanceMessage::CredentialAck(_ack()), _send_message()).unwrap(); - assert_match!(HolderState::Finished(_), holder_sm.state); + assert_match!(HolderFullState::Finished(_), holder_sm.state); } } @@ -610,9 +610,9 @@ mod test { fn test_get_state() { let _setup = SetupMocks::init(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, _holder_sm().state()); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, _holder_sm().to_request_sent_state().state()); - assert_eq!(VcxStateType::VcxStateAccepted as u32, _holder_sm().to_finished_state().state()); + assert_eq!(HolderState::OfferReceived, _holder_sm().get_state()); + assert_eq!(HolderState::RequestSent, _holder_sm().to_request_sent_state().get_state()); + assert_eq!(HolderState::Finished, _holder_sm().to_finished_state().get_state()); } } diff --git a/libvcx/src/aries/handlers/issuance/issuer/issuer.rs b/libvcx/src/aries/handlers/issuance/issuer/issuer.rs index ea9a6f633b..c62b686bac 100644 --- a/libvcx/src/aries/handlers/issuance/issuer/issuer.rs +++ b/libvcx/src/aries/handlers/issuance/issuer/issuer.rs @@ -18,6 +18,16 @@ pub struct IssuerConfig { pub tails_file: Option } +#[derive(Debug, PartialEq)] +pub enum IssuerState { + Initial, + OfferSent, + RequestReceived, + CredentialSent, + Finished, + Failed +} + impl Issuer { pub fn create(issuer_config: &IssuerConfig, credential_data: &str, source_id: &str) -> VcxResult { trace!("Issuer::issuer_create_credential >>> issuer_config: {:?}, credential_data: {:?}, source_id: {:?}", issuer_config, credential_data, source_id); @@ -34,8 +44,8 @@ impl Issuer { self.step(CredentialIssuanceMessage::CredentialSend(), Some(&send_message)) } - pub fn get_state(&self) -> VcxResult { - Ok(self.issuer_sm.state()) + pub fn get_state(&self) -> IssuerState { + self.issuer_sm.get_state() } pub fn get_source_id(&self) -> VcxResult { @@ -71,9 +81,9 @@ impl Issuer { Ok(()) } - pub fn update_state(&mut self, connection: &Connection) -> VcxResult { - trace!("Issuer::update_state >>> "); - if self.is_terminal_state() { return self.get_state(); } + pub fn update_state(&mut self, connection: &Connection) -> VcxResult { + trace!("Issuer::update_state >>>"); + if self.is_terminal_state() { return Ok(self.get_state()); } let send_message = connection.send_message_closure()?; let messages = connection.get_messages()?; @@ -81,6 +91,6 @@ impl Issuer { self.step(msg.into(), Some(&send_message))?; connection.update_message_status(uid)?; } - self.get_state() + Ok(self.get_state()) } } diff --git a/libvcx/src/aries/handlers/issuance/issuer/state_machine.rs b/libvcx/src/aries/handlers/issuance/issuer/state_machine.rs index a8226433e3..35f1dfaec6 100644 --- a/libvcx/src/aries/handlers/issuance/issuer/state_machine.rs +++ b/libvcx/src/aries/handlers/issuance/issuer/state_machine.rs @@ -7,6 +7,7 @@ use crate::aries::handlers::issuance::issuer::states::finished::FinishedState; use crate::aries::handlers::issuance::issuer::states::initial::InitialState; use crate::aries::handlers::issuance::issuer::states::offer_sent::OfferSentState; use crate::aries::handlers::issuance::issuer::states::requested_received::RequestReceivedState; +use crate::aries::handlers::issuance::issuer::issuer::IssuerState; use crate::aries::handlers::issuance::issuer::utils::encode_attributes; use crate::aries::handlers::issuance::messages::CredentialIssuanceMessage; use crate::aries::messages::a2a::A2AMessage; @@ -17,10 +18,9 @@ use crate::aries::messages::issuance::credential_request::CredentialRequest; use crate::aries::messages::mime_type::MimeType; use crate::aries::messages::status::Status; use crate::error::{VcxError, VcxErrorKind, VcxResult}; -use crate::api_lib::VcxStateType; #[derive(Serialize, Deserialize, Debug, Clone)] -pub enum IssuerState { +pub enum IssuerFullState { Initial(InitialState), OfferSent(OfferSentState), RequestReceived(RequestReceivedState), @@ -35,28 +35,28 @@ pub struct RevocationInfoV1 { pub tails_file: Option, } -impl IssuerState { +impl IssuerFullState { pub fn thread_id(&self) -> String { match self { - IssuerState::Initial(_) => String::new(), - IssuerState::OfferSent(state) => state.thread_id.clone(), - IssuerState::RequestReceived(state) => state.thread_id.clone(), - IssuerState::CredentialSent(state) => state.thread_id.clone(), - IssuerState::Finished(state) => state.thread_id.clone(), + IssuerFullState::Initial(_) => String::new(), + IssuerFullState::OfferSent(state) => state.thread_id.clone(), + IssuerFullState::RequestReceived(state) => state.thread_id.clone(), + IssuerFullState::CredentialSent(state) => state.thread_id.clone(), + IssuerFullState::Finished(state) => state.thread_id.clone(), } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct IssuerSM { - state: IssuerState, + state: IssuerFullState, source_id: String, } impl IssuerSM { pub fn new(cred_def_id: &str, credential_data: &str, rev_reg_id: Option, tails_file: Option, source_id: &str) -> Self { IssuerSM { - state: IssuerState::Initial(InitialState::new(cred_def_id, credential_data, rev_reg_id, tails_file)), + state: IssuerFullState::Initial(InitialState::new(cred_def_id, credential_data, rev_reg_id, tails_file)), source_id: source_id.to_string(), } } @@ -65,7 +65,7 @@ impl IssuerSM { self.source_id.clone() } - pub fn step(state: IssuerState, source_id: String) -> Self { + pub fn step(state: IssuerFullState, source_id: String) -> Self { IssuerSM { state, source_id, @@ -75,7 +75,7 @@ impl IssuerSM { pub fn revoke(&self, publish: bool) -> VcxResult<()> { trace!("Issuer::revoke >>> publish={}", publish); match &self.state { - IssuerState::Finished(state) => { + IssuerFullState::Finished(state) => { match &state.revocation_info_v1 { Some(rev_info) => { if let (Some(cred_rev_id), Some(rev_reg_id), Some(tails_file)) = (&rev_info.cred_rev_id, &rev_info.rev_reg_id, &rev_info.tails_file) { @@ -99,13 +99,13 @@ impl IssuerSM { pub fn get_rev_reg_id(&self) -> VcxResult { let rev_registry = match &self.state { - IssuerState::Initial(state) => state.rev_reg_id.clone(), - IssuerState::OfferSent(state) => state.rev_reg_id.clone(), - IssuerState::RequestReceived(state) => state.rev_reg_id.clone(), - IssuerState::CredentialSent(state) => state.revocation_info_v1.clone() + IssuerFullState::Initial(state) => state.rev_reg_id.clone(), + IssuerFullState::OfferSent(state) => state.rev_reg_id.clone(), + IssuerFullState::RequestReceived(state) => state.rev_reg_id.clone(), + IssuerFullState::CredentialSent(state) => state.revocation_info_v1.clone() .ok_or(VcxError::from_msg(VcxErrorKind::InvalidState, "No revocation info found - is this credential revokable?"))? .rev_reg_id, - IssuerState::Finished(state) => state.revocation_info_v1.clone() + IssuerFullState::Finished(state) => state.revocation_info_v1.clone() .ok_or(VcxError::from_msg(VcxErrorKind::InvalidState, "No revocation info found - is this credential revokable?"))? .rev_reg_id }; @@ -114,11 +114,11 @@ impl IssuerSM { pub fn is_revokable(&self) -> VcxResult { match &self.state { - IssuerState::Initial(state) => Ok(state.rev_reg_id.is_some()), - IssuerState::OfferSent(state) => Ok(state.rev_reg_id.is_some()), - IssuerState::RequestReceived(state) => Ok(state.rev_reg_id.is_some()), - IssuerState::CredentialSent(state) => Ok(state.revocation_info_v1.is_some()), - IssuerState::Finished(state) => Ok(state.revocation_info_v1.is_some()) + IssuerFullState::Initial(state) => Ok(state.rev_reg_id.is_some()), + IssuerFullState::OfferSent(state) => Ok(state.rev_reg_id.is_some()), + IssuerFullState::RequestReceived(state) => Ok(state.rev_reg_id.is_some()), + IssuerFullState::CredentialSent(state) => Ok(state.revocation_info_v1.is_some()), + IssuerFullState::Finished(state) => Ok(state.revocation_info_v1.is_some()) } } @@ -127,10 +127,10 @@ impl IssuerSM { for (uid, message) in messages { match self.state { - IssuerState::Initial(_) => { + IssuerFullState::Initial(_) => { // do not process messages } - IssuerState::OfferSent(_) => { + IssuerFullState::OfferSent(_) => { match message { A2AMessage::CredentialRequest(credential) => { if credential.from_thread(&self.state.thread_id()) { @@ -152,10 +152,10 @@ impl IssuerSM { _ => {} } } - IssuerState::RequestReceived(_) => { + IssuerFullState::RequestReceived(_) => { // do not process messages } - IssuerState::CredentialSent(_) => { + IssuerFullState::CredentialSent(_) => { match message { A2AMessage::Ack(ack) | A2AMessage::CredentialAck(ack) => { if ack.from_thread(&self.state.thread_id()) { @@ -170,7 +170,7 @@ impl IssuerSM { _ => {} } } - IssuerState::Finished(_) => { + IssuerFullState::Finished(_) => { // do not process messages } }; @@ -179,16 +179,16 @@ impl IssuerSM { None } - pub fn state(&self) -> u32 { + pub fn get_state(&self) -> IssuerState { match self.state { - IssuerState::Initial(_) => VcxStateType::VcxStateInitialized as u32, - IssuerState::OfferSent(_) => VcxStateType::VcxStateOfferSent as u32, - IssuerState::RequestReceived(_) => VcxStateType::VcxStateRequestReceived as u32, - IssuerState::CredentialSent(_) => VcxStateType::VcxStateAccepted as u32, - IssuerState::Finished(ref status) => { + IssuerFullState::Initial(_) => IssuerState::Initial, + IssuerFullState::OfferSent(_) => IssuerState::OfferSent, + IssuerFullState::RequestReceived(_) => IssuerState::RequestReceived, + IssuerFullState::CredentialSent(_) => IssuerState::CredentialSent, + IssuerFullState::Finished(ref status) => { match status.status { - Status::Success => VcxStateType::VcxStateAccepted as u32, - _ => VcxStateType::VcxStateNone as u32, + Status::Success => IssuerState::Finished, + _ => IssuerState::Failed } } } @@ -199,7 +199,7 @@ impl IssuerSM { let IssuerSM { state, source_id } = self; let state = match state { - IssuerState::Initial(state_data) => match cim { + IssuerFullState::Initial(state_data) => match cim { CredentialIssuanceMessage::CredentialInit(comment) => { let cred_offer = libindy_issuer_create_credential_offer(&state_data.cred_def_id)?; let cred_offer_msg = CredentialOffer::create() @@ -209,16 +209,16 @@ impl IssuerSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&cred_offer_msg.to_a2a_message())?; - IssuerState::OfferSent((state_data, cred_offer, cred_offer_msg.id).into()) + IssuerFullState::OfferSent((state_data, cred_offer, cred_offer_msg.id).into()) } _ => { warn!("Credential Issuance can only start on issuer side with init"); - IssuerState::Initial(state_data) + IssuerFullState::Initial(state_data) } } - IssuerState::OfferSent(state_data) => match cim { + IssuerFullState::OfferSent(state_data) => match cim { CredentialIssuanceMessage::CredentialRequest(request) => { - IssuerState::RequestReceived((state_data, request).into()) + IssuerFullState::RequestReceived((state_data, request).into()) } CredentialIssuanceMessage::CredentialProposal(_) => { let problem_report = ProblemReport::create() @@ -228,17 +228,17 @@ impl IssuerSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&problem_report.to_a2a_message())?; - IssuerState::Finished((state_data, problem_report).into()) + IssuerFullState::Finished((state_data, problem_report).into()) } CredentialIssuanceMessage::ProblemReport(problem_report) => { - IssuerState::Finished((state_data, problem_report).into()) + IssuerFullState::Finished((state_data, problem_report).into()) } _ => { warn!("In this state Credential Issuance can accept only Request, Proposal and Problem Report"); - IssuerState::OfferSent(state_data) + IssuerFullState::OfferSent(state_data) } }, - IssuerState::RequestReceived(state_data) => match cim { + IssuerFullState::RequestReceived(state_data) => match cim { CredentialIssuanceMessage::CredentialSend() => { let credential_msg = _create_credential(&state_data.request, &state_data.rev_reg_id, &state_data.tails_file, &state_data.offer, &state_data.cred_data); match credential_msg { @@ -247,7 +247,7 @@ impl IssuerSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&credential_msg.to_a2a_message())?; - IssuerState::Finished((state_data, cred_rev_id).into()) + IssuerFullState::Finished((state_data, cred_rev_id).into()) } Err(err) => { let problem_report = ProblemReport::create() @@ -257,32 +257,32 @@ impl IssuerSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&problem_report.to_a2a_message())?; - IssuerState::Finished((state_data, problem_report).into()) + IssuerFullState::Finished((state_data, problem_report).into()) } } } _ => { warn!("In this state Credential Issuance can accept only CredentialSend"); - IssuerState::RequestReceived(state_data) + IssuerFullState::RequestReceived(state_data) } } - IssuerState::CredentialSent(state_data) => match cim { + IssuerFullState::CredentialSent(state_data) => match cim { CredentialIssuanceMessage::ProblemReport(_problem_report) => { info!("Interaction closed with failure"); - IssuerState::Finished(state_data.into()) + IssuerFullState::Finished(state_data.into()) } CredentialIssuanceMessage::CredentialAck(_ack) => { info!("Interaction closed with success"); - IssuerState::Finished(state_data.into()) + IssuerFullState::Finished(state_data.into()) } _ => { warn!("In this state Credential Issuance can accept only Ack and Problem Report"); - IssuerState::CredentialSent(state_data) + IssuerFullState::CredentialSent(state_data) } } - IssuerState::Finished(state_data) => { + IssuerFullState::Finished(state_data) => { warn!("Exchange is finished, no messages can be sent or received"); - IssuerState::Finished(state_data) + IssuerFullState::Finished(state_data) } }; @@ -293,14 +293,14 @@ impl IssuerSM { trace!("Issuer::credential_status >>>"); match self.state { - IssuerState::Finished(ref state) => state.status.code(), + IssuerFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code() } } pub fn is_terminal_state(&self) -> bool { match self.state { - IssuerState::Finished(_) => true, + IssuerFullState::Finished(_) => true, _ => false } } @@ -417,7 +417,7 @@ pub mod test { let issuer_sm = _issuer_sm(); - assert_match!(IssuerState::Initial(_), issuer_sm.state); + assert_match!(IssuerFullState::Initial(_), issuer_sm.state); assert_eq!(source_id(), issuer_sm.get_source_id()); } } @@ -432,7 +432,7 @@ pub mod test { let issuer_sm = _issuer_sm(); - assert_match!(IssuerState::Initial(_), issuer_sm.state); + assert_match!(IssuerFullState::Initial(_), issuer_sm.state); } #[test] @@ -443,7 +443,7 @@ pub mod test { let mut issuer_sm = _issuer_sm(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); - assert_match!(IssuerState::OfferSent(_), issuer_sm.state); + assert_match!(IssuerFullState::OfferSent(_), issuer_sm.state); } #[test] @@ -454,10 +454,10 @@ pub mod test { let mut issuer_sm = _issuer_sm(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); - assert_match!(IssuerState::Initial(_), issuer_sm.state); + assert_match!(IssuerFullState::Initial(_), issuer_sm.state); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialRequest(_credential_request()), _send_message()).unwrap(); - assert_match!(IssuerState::Initial(_), issuer_sm.state); + assert_match!(IssuerFullState::Initial(_), issuer_sm.state); } #[test] @@ -469,7 +469,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialRequest(_credential_request()), _send_message()).unwrap(); - assert_match!(IssuerState::RequestReceived(_), issuer_sm.state); + assert_match!(IssuerFullState::RequestReceived(_), issuer_sm.state); } #[test] @@ -481,7 +481,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialProposal(_credential_proposal()), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), issuer_sm.credential_status()); } @@ -494,7 +494,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::ProblemReport(_problem_report()), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), issuer_sm.credential_status()); } @@ -507,7 +507,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); - assert_match!(IssuerState::OfferSent(_), issuer_sm.state); + assert_match!(IssuerFullState::OfferSent(_), issuer_sm.state); } #[test] @@ -520,7 +520,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialRequest(_credential_request()), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); assert_eq!(Status::Success.code(), issuer_sm.credential_status()); } @@ -534,7 +534,7 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialRequest(CredentialRequest::create()), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), issuer_sm.credential_status()); } @@ -549,10 +549,10 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialAck(_ack()), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); } // TRANSITIONS TO/FROM CREDENTIAL SENT STATE AREN'T POSSIBLE NOW @@ -568,13 +568,13 @@ pub mod test { issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialSend(), _send_message()).unwrap(); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialInit(None), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::CredentialRequest(_credential_request()), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); issuer_sm = issuer_sm.handle_message(CredentialIssuanceMessage::Credential(_credential()), _send_message()).unwrap(); - assert_match!(IssuerState::Finished(_), issuer_sm.state); + assert_match!(IssuerFullState::Finished(_), issuer_sm.state); } } @@ -728,10 +728,10 @@ pub mod test { fn test_get_state() { let _setup = SetupMocks::init(); - assert_eq!(VcxStateType::VcxStateInitialized as u32, _issuer_sm().state()); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, _issuer_sm().to_offer_sent_state().state()); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, _issuer_sm().to_request_received_state().state()); - assert_eq!(VcxStateType::VcxStateAccepted as u32, _issuer_sm().to_finished_state().state()); + assert_eq!(IssuerState::Initial, _issuer_sm().get_state()); + assert_eq!(IssuerState::OfferSent, _issuer_sm().to_offer_sent_state().get_state()); + assert_eq!(IssuerState::RequestReceived, _issuer_sm().to_request_received_state().get_state()); + assert_eq!(IssuerState::Finished, _issuer_sm().to_finished_state().get_state()); } } diff --git a/libvcx/src/aries/handlers/proof_presentation/prover/prover.rs b/libvcx/src/aries/handlers/proof_presentation/prover/prover.rs index 7fa8f44d85..67aa87860d 100644 --- a/libvcx/src/aries/handlers/proof_presentation/prover/prover.rs +++ b/libvcx/src/aries/handlers/proof_presentation/prover/prover.rs @@ -15,6 +15,16 @@ pub struct Prover { prover_sm: ProverSM, } +#[derive(Debug, PartialEq)] +pub enum ProverState { + Initial, + PresentationPrepared, + PresentationPreparationFailed, + PresentationSent, + Finished, + Failed +} + impl Prover { pub fn create(source_id: &str, presentation_request: PresentationRequest) -> VcxResult { trace!("Prover::create >>> source_id: {}, presentation_request: {:?}", source_id, presentation_request); @@ -23,7 +33,7 @@ impl Prover { }) } - pub fn state(&self) -> u32 { self.prover_sm.state() } + pub fn get_state(&self) -> ProverState { self.prover_sm.get_state() } pub fn presentation_status(&self) -> u32 { trace!("Prover::presentation_state >>>"); @@ -113,9 +123,9 @@ impl Prover { } } - pub fn update_state(&mut self, connection: &Connection) -> VcxResult { + pub fn update_state(&mut self, connection: &Connection) -> VcxResult { trace!("Prover::update_state >>> "); - if !self.has_transitions() { return Ok(self.state()); } + if !self.has_transitions() { return Ok(self.get_state()); } let send_message = connection.send_message_closure()?; let messages = connection.get_messages()?; @@ -123,7 +133,7 @@ impl Prover { self.step(msg.into(), Some(&send_message))?; connection.update_message_status(uid)?; } - Ok(self.state()) + Ok(self.get_state()) } } diff --git a/libvcx/src/aries/handlers/proof_presentation/prover/state_machine.rs b/libvcx/src/aries/handlers/proof_presentation/prover/state_machine.rs index dffedd19c9..d790eb3250 100644 --- a/libvcx/src/aries/handlers/proof_presentation/prover/state_machine.rs +++ b/libvcx/src/aries/handlers/proof_presentation/prover/state_machine.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use crate::api_lib::VcxStateType; +use crate::aries::handlers::proof_presentation::prover::prover::ProverState; use crate::aries::handlers::proof_presentation::prover::messages::ProverMessages; use crate::aries::handlers::proof_presentation::prover::states::finished::FinishedState; use crate::aries::handlers::proof_presentation::prover::states::initial::InitialState; @@ -21,12 +21,12 @@ use crate::error::prelude::*; pub struct ProverSM { source_id: String, thread_id: String, - state: ProverState, + state: ProverFullState, } impl ProverSM { pub fn new(presentation_request: PresentationRequest, source_id: String) -> ProverSM { - ProverSM { source_id, thread_id: presentation_request.id.0.clone(), state: ProverState::Initiated(InitialState { presentation_request }) } + ProverSM { source_id, thread_id: presentation_request.id.0.clone(), state: ProverFullState::Initiated(InitialState { presentation_request }) } } } @@ -37,7 +37,7 @@ impl ProverSM { // PresentationPreparationFailedState -> Finished // PresentationSent -> Finished #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub enum ProverState { +pub enum ProverFullState { Initiated(InitialState), PresentationPrepared(PresentationPreparedState), PresentationPreparationFailed(PresentationPreparationFailedState), @@ -51,7 +51,7 @@ impl ProverSM { for (uid, message) in messages { match self.state { - ProverState::Initiated(_) => { + ProverFullState::Initiated(_) => { match message { A2AMessage::PresentationRequest(_) => { // ignore it here?? @@ -59,13 +59,13 @@ impl ProverSM { _ => {} } } - ProverState::PresentationPrepared(_) => { + ProverFullState::PresentationPrepared(_) => { // do not process messages } - ProverState::PresentationPreparationFailed(_) => { + ProverFullState::PresentationPreparationFailed(_) => { // do not process messages } - ProverState::PresentationSent(_) => { + ProverFullState::PresentationSent(_) => { match message { A2AMessage::Ack(ack) | A2AMessage::PresentationAck(ack) => { if ack.from_thread(&self.thread_id) { @@ -80,7 +80,7 @@ impl ProverSM { _ => {} } } - ProverState::Finished(_) => { + ProverFullState::Finished(_) => { // do not process messages } }; @@ -98,11 +98,11 @@ impl ProverSM { let ProverSM { source_id, state, thread_id } = self; let state = match state { - ProverState::Initiated(state) => { + ProverFullState::Initiated(state) => { match message { ProverMessages::SetPresentation(presentation) => { let presentation = presentation.set_thread_id(&thread_id); - ProverState::PresentationPrepared((state, presentation).into()) + ProverFullState::PresentationPrepared((state, presentation).into()) } ProverMessages::PreparePresentation((credentials, self_attested_attrs)) => { match state.build_presentation(&credentials, &self_attested_attrs) { @@ -112,7 +112,7 @@ impl ProverSM { .set_thread_id(&thread_id) .set_presentations_attach(presentation)?; - ProverState::PresentationPrepared((state, presentation).into()) + ProverFullState::PresentationPrepared((state, presentation).into()) } Err(err) => { let problem_report = @@ -120,14 +120,14 @@ impl ProverSM { .set_comment(err.to_string()) .set_thread_id(&thread_id); - ProverState::PresentationPreparationFailed((state, problem_report).into()) + ProverFullState::PresentationPreparationFailed((state, problem_report).into()) } } } ProverMessages::RejectPresentationRequest(reason) => { if let Some(send_message) = send_message { Self::_handle_reject_presentation_request(send_message, &reason, &thread_id)?; - ProverState::Finished(state.into()) + ProverFullState::Finished(state.into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } @@ -135,22 +135,22 @@ impl ProverSM { ProverMessages::ProposePresentation(preview) => { if let Some(send_message) = send_message { Self::_handle_presentation_proposal(send_message, preview, &thread_id)?; - ProverState::Finished(state.into()) + ProverFullState::Finished(state.into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } } _ => { - ProverState::Initiated(state) + ProverFullState::Initiated(state) } } } - ProverState::PresentationPrepared(state) => { + ProverFullState::PresentationPrepared(state) => { match message { ProverMessages::SendPresentation => { if let Some(send_message) = send_message { send_message(&state.presentation.to_a2a_message())?; - ProverState::PresentationSent((state).into()) + ProverFullState::PresentationSent((state).into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } @@ -158,7 +158,7 @@ impl ProverSM { ProverMessages::RejectPresentationRequest(reason) => { if let Some(send_message) = send_message { Self::_handle_reject_presentation_request(send_message, &reason, &thread_id)?; - ProverState::Finished(state.into()) + ProverFullState::Finished(state.into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } @@ -166,48 +166,48 @@ impl ProverSM { ProverMessages::ProposePresentation(preview) => { if let Some(send_message) = send_message { Self::_handle_presentation_proposal(send_message, preview, &thread_id)?; - ProverState::Finished(state.into()) + ProverFullState::Finished(state.into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } } _ => { - ProverState::PresentationPrepared(state) + ProverFullState::PresentationPrepared(state) } } } - ProverState::PresentationPreparationFailed(state) => { + ProverFullState::PresentationPreparationFailed(state) => { match message { ProverMessages::SendPresentation => { if let Some(send_message) = send_message { send_message(&state.problem_report.to_a2a_message())?; - ProverState::Finished((state).into()) + ProverFullState::Finished((state).into()) } else { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Send message closure is required.")); } } _ => { - ProverState::PresentationPreparationFailed(state) + ProverFullState::PresentationPreparationFailed(state) } } } - ProverState::PresentationSent(state) => { + ProverFullState::PresentationSent(state) => { match message { ProverMessages::PresentationAckReceived(ack) => { - ProverState::Finished((state, ack).into()) + ProverFullState::Finished((state, ack).into()) } ProverMessages::PresentationRejectReceived(problem_report) => { - ProverState::Finished((state, problem_report).into()) + ProverFullState::Finished((state, problem_report).into()) } ProverMessages::RejectPresentationRequest(_) => { return Err(VcxError::from_msg(VcxErrorKind::ActionNotSupported, "Presentation is already sent")); } _ => { - ProverState::PresentationSent(state) + ProverFullState::PresentationSent(state) } } } - ProverState::Finished(state) => ProverState::Finished(state) + ProverFullState::Finished(state) => ProverFullState::Finished(state) }; Ok(ProverSM { source_id, state, thread_id }) @@ -239,16 +239,16 @@ impl ProverSM { pub fn source_id(&self) -> String { self.source_id.clone() } - pub fn state(&self) -> u32 { + pub fn get_state(&self) -> ProverState { match self.state { - ProverState::Initiated(_) => VcxStateType::VcxStateRequestReceived as u32, - ProverState::PresentationPrepared(_) => VcxStateType::VcxStateRequestReceived as u32, - ProverState::PresentationPreparationFailed(_) => VcxStateType::VcxStateRequestReceived as u32, - ProverState::PresentationSent(_) => VcxStateType::VcxStateOfferSent as u32, // TODO: maybe VcxStateType::VcxStateAccepted - ProverState::Finished(ref status) => { + ProverFullState::Initiated(_) => ProverState::Initial, + ProverFullState::PresentationPrepared(_) => ProverState::PresentationPrepared, + ProverFullState::PresentationPreparationFailed(_) => ProverState::PresentationPreparationFailed, + ProverFullState::PresentationSent(_) => ProverState::PresentationSent, + ProverFullState::Finished(ref status) => { match status.status { - Status::Success => VcxStateType::VcxStateAccepted as u32, - _ => VcxStateType::VcxStateNone as u32, + Status::Success => ProverState::Finished, + _ => ProverState::Failed } } } @@ -257,38 +257,38 @@ impl ProverSM { pub fn has_transitions(&self) -> bool { trace!("Prover::states::has_transitions >> state: {:?}", self.state); match self.state { - ProverState::Initiated(_) => false, - ProverState::PresentationPrepared(_) => true, - ProverState::PresentationPreparationFailed(_) => true, - ProverState::PresentationSent(_) => true, - ProverState::Finished(_) => false, + ProverFullState::Initiated(_) => false, + ProverFullState::PresentationPrepared(_) => true, + ProverFullState::PresentationPreparationFailed(_) => true, + ProverFullState::PresentationSent(_) => true, + ProverFullState::Finished(_) => false, } } pub fn presentation_status(&self) -> u32 { match self.state { - ProverState::Finished(ref state) => state.status.code(), + ProverFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code() } } pub fn presentation_request(&self) -> &PresentationRequest { match self.state { - ProverState::Initiated(ref state) => &state.presentation_request, - ProverState::PresentationPrepared(ref state) => &state.presentation_request, - ProverState::PresentationPreparationFailed(ref state) => &state.presentation_request, - ProverState::PresentationSent(ref state) => &state.presentation_request, - ProverState::Finished(ref state) => &state.presentation_request, + ProverFullState::Initiated(ref state) => &state.presentation_request, + ProverFullState::PresentationPrepared(ref state) => &state.presentation_request, + ProverFullState::PresentationPreparationFailed(ref state) => &state.presentation_request, + ProverFullState::PresentationSent(ref state) => &state.presentation_request, + ProverFullState::Finished(ref state) => &state.presentation_request, } } pub fn presentation(&self) -> VcxResult<&Presentation> { match self.state { - ProverState::Initiated(_) => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Presentation is not created yet")), - ProverState::PresentationPrepared(ref state) => Ok(&state.presentation), - ProverState::PresentationPreparationFailed(_) => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Presentation is not created yet")), - ProverState::PresentationSent(ref state) => Ok(&state.presentation), - ProverState::Finished(ref state) => Ok(&state.presentation), + ProverFullState::Initiated(_) => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Presentation is not created yet")), + ProverFullState::PresentationPrepared(ref state) => Ok(&state.presentation), + ProverFullState::PresentationPreparationFailed(_) => Err(VcxError::from_msg(VcxErrorKind::NotReady, "Presentation is not created yet")), + ProverFullState::PresentationSent(ref state) => Ok(&state.presentation), + ProverFullState::Finished(ref state) => Ok(&state.presentation), } } } @@ -361,7 +361,7 @@ pub mod test { let prover_sm = _prover_sm(); - assert_match!(ProverState::Initiated(_), prover_sm.state); + assert_match!(ProverFullState::Initiated(_), prover_sm.state); assert_eq!(source_id(), prover_sm.source_id()); } } @@ -378,7 +378,7 @@ pub mod test { let _setup = SetupMocks::init(); let prover_sm = _prover_sm(); - assert_match!(ProverState::Initiated(_), prover_sm.state); + assert_match!(ProverFullState::Initiated(_), prover_sm.state); } #[test] @@ -390,7 +390,7 @@ pub mod test { let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::PreparePresentation((_credentials(), _self_attested())), send_message).unwrap(); - assert_match!(ProverState::PresentationPrepared(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPrepared(_), prover_sm.state); } #[test] @@ -404,7 +404,7 @@ pub mod test { let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::PreparePresentation(("invalid".to_string(), _self_attested())), send_message).unwrap(); - assert_match!(ProverState::PresentationPreparationFailed(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPreparationFailed(_), prover_sm.state); } #[test] @@ -416,7 +416,7 @@ pub mod test { let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::RejectPresentationRequest(String::from("reject request")), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); } #[test] @@ -428,7 +428,7 @@ pub mod test { let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::ProposePresentation((_presentation_preview())), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); } #[test] @@ -440,10 +440,10 @@ pub mod test { let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); - assert_match!(ProverState::Initiated(_), prover_sm.state); + assert_match!(ProverFullState::Initiated(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); - assert_match!(ProverState::Initiated(_), prover_sm.state); + assert_match!(ProverFullState::Initiated(_), prover_sm.state); } #[test] @@ -457,7 +457,7 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::PreparePresentation((_credentials(), _self_attested())), send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); - assert_match!(ProverState::PresentationSent(_), prover_sm.state); + assert_match!(ProverFullState::PresentationSent(_), prover_sm.state); } #[test] @@ -469,10 +469,10 @@ pub mod test { let mut prover_sm = _prover_sm().to_presentation_prepared_state(); prover_sm = prover_sm.step(ProverMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(ProverState::PresentationPrepared(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPrepared(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); - assert_match!(ProverState::PresentationPrepared(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPrepared(_), prover_sm.state); } #[test] @@ -485,7 +485,7 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::RejectPresentationRequest(String::from("reject request")), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); } #[test] @@ -497,7 +497,7 @@ pub mod test { let mut prover_sm = _prover_sm().to_presentation_prepared_state(); prover_sm = prover_sm.step(ProverMessages::ProposePresentation(_presentation_preview()), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); } #[test] @@ -510,10 +510,10 @@ pub mod test { let send_message = Some(&|_: &A2AMessage| VcxResult::Ok(())); let mut prover_sm = _prover_sm(); prover_sm = prover_sm.step(ProverMessages::PreparePresentation(("invalid".to_string(), _self_attested())), send_message).unwrap(); - assert_match!(ProverState::PresentationPreparationFailed(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPreparationFailed(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!(Status::Failed(ProblemReport::default()).code(), prover_sm.presentation_status()); } @@ -529,10 +529,10 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::PreparePresentation(("invalid".to_string(), _self_attested())), send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(ProverState::PresentationPreparationFailed(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPreparationFailed(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); - assert_match!(ProverState::PresentationPreparationFailed(_), prover_sm.state); + assert_match!(ProverFullState::PresentationPreparationFailed(_), prover_sm.state); } #[test] @@ -546,7 +546,7 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!(Status::Success.code(), prover_sm.presentation_status()); } @@ -572,7 +572,7 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!(Status::Failed(ProblemReport::create()).code(), prover_sm.presentation_status()); } @@ -587,10 +587,10 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::PreparePresentation((_credentials(), _self_attested())), send_message).unwrap(); - assert_match!(ProverState::PresentationSent(_), prover_sm.state); + assert_match!(ProverFullState::PresentationSent(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::SendPresentation, send_message).unwrap(); - assert_match!(ProverState::PresentationSent(_), prover_sm.state); + assert_match!(ProverFullState::PresentationSent(_), prover_sm.state); } #[test] @@ -605,10 +605,10 @@ pub mod test { prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); prover_sm = prover_sm.step(ProverMessages::PresentationAckReceived(_ack()), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); prover_sm = prover_sm.step(ProverMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(ProverState::Finished(_), prover_sm.state); + assert_match!(ProverFullState::Finished(_), prover_sm.state); } } @@ -743,10 +743,10 @@ pub mod test { fn test_get_state() { let _setup = SetupMocks::init(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, _prover_sm().state()); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, _prover_sm().to_presentation_prepared_state().state()); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, _prover_sm().to_presentation_sent_state().state()); - assert_eq!(VcxStateType::VcxStateAccepted as u32, _prover_sm().to_finished_state().state()); + assert_eq!(ProverState::Initial, _prover_sm().get_state()); + assert_eq!(ProverState::PresentationPrepared, _prover_sm().to_presentation_prepared_state().get_state()); + assert_eq!(ProverState::PresentationSent, _prover_sm().to_presentation_sent_state().get_state()); + assert_eq!(ProverState::Finished, _prover_sm().to_finished_state().get_state()); } } } diff --git a/libvcx/src/aries/handlers/proof_presentation/verifier/state_machine.rs b/libvcx/src/aries/handlers/proof_presentation/verifier/state_machine.rs index f607291e2e..eac4a24c51 100644 --- a/libvcx/src/aries/handlers/proof_presentation/verifier/state_machine.rs +++ b/libvcx/src/aries/handlers/proof_presentation/verifier/state_machine.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; -use crate::api_lib::VcxStateType; use crate::error::prelude::*; use crate::aries::handlers::proof_presentation::verifier::messages::VerifierMessages; +use crate::aries::handlers::proof_presentation::verifier::verifier::VerifierState; use crate::aries::messages::a2a::A2AMessage; use crate::aries::messages::error::ProblemReport; use crate::aries::messages::proof_presentation::presentation::Presentation; @@ -15,23 +15,22 @@ use crate::aries::handlers::proof_presentation::verifier::states::finished::Fini #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VerifierSM { source_id: String, - state: VerifierState, + state: VerifierFullState, } impl VerifierSM { pub fn new(presentation_request: PresentationRequestData, source_id: String) -> VerifierSM { - VerifierSM { source_id, state: VerifierState::Initiated(InitialState { presentation_request_data: presentation_request }) } + VerifierSM { source_id, state: VerifierFullState::Initiated(InitialState { presentation_request_data: presentation_request }) } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub enum VerifierState { +pub enum VerifierFullState { Initiated(InitialState), PresentationRequestSent(PresentationRequestSentState), Finished(FinishedState), } - #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum RevocationStatus { Revoked, @@ -44,10 +43,10 @@ impl VerifierSM { for (uid, message) in messages { match self.state { - VerifierState::Initiated(_) => { + VerifierFullState::Initiated(_) => { // do not process message } - VerifierState::PresentationRequestSent(_) => { + VerifierFullState::PresentationRequestSent(_) => { match message { A2AMessage::Presentation(presentation) => { if presentation.from_thread(&self.thread_id()) { @@ -67,7 +66,7 @@ impl VerifierSM { _ => {} } } - VerifierState::Finished(_) => { + VerifierFullState::Finished(_) => { // do not process message } }; @@ -82,7 +81,7 @@ impl VerifierSM { let VerifierSM { source_id, state } = self; let state = match state { - VerifierState::Initiated(state) => { + VerifierFullState::Initiated(state) => { match message { VerifierMessages::SendPresentationRequest(comment) => { let presentation_request = @@ -92,19 +91,19 @@ impl VerifierSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&presentation_request.to_a2a_message())?; - VerifierState::PresentationRequestSent((state, presentation_request).into()) + VerifierFullState::PresentationRequestSent((state, presentation_request).into()) } _ => { - VerifierState::Initiated(state) + VerifierFullState::Initiated(state) } } } - VerifierState::PresentationRequestSent(state) => { + VerifierFullState::PresentationRequestSent(state) => { match message { VerifierMessages::VerifyPresentation(presentation) => { match state.verify_presentation(&presentation, send_message) { Ok(()) => { - VerifierState::Finished((state, presentation, RevocationStatus::NonRevoked).into()) + VerifierFullState::Finished((state, presentation, RevocationStatus::NonRevoked).into()) } Err(err) => { let problem_report = @@ -116,15 +115,15 @@ impl VerifierSM { )?(&problem_report.to_a2a_message())?; match err.kind() { VcxErrorKind::InvalidProof => { - VerifierState::Finished((state, presentation, RevocationStatus::Revoked).into()) + VerifierFullState::Finished((state, presentation, RevocationStatus::Revoked).into()) } - _ => VerifierState::Finished((state, problem_report).into()) + _ => VerifierFullState::Finished((state, problem_report).into()) } } } } VerifierMessages::PresentationRejectReceived(problem_report) => { - VerifierState::Finished((state, problem_report).into()) + VerifierFullState::Finished((state, problem_report).into()) } VerifierMessages::PresentationProposalReceived(_) => { // TODO: handle Presentation Proposal let problem_report = @@ -134,14 +133,14 @@ impl VerifierSM { send_message.ok_or( VcxError::from_msg(VcxErrorKind::InvalidState, "Attempted to call undefined send_message callback") )?(&problem_report.to_a2a_message())?; - VerifierState::Finished((state, problem_report).into()) + VerifierFullState::Finished((state, problem_report).into()) } _ => { - VerifierState::PresentationRequestSent(state) + VerifierFullState::PresentationRequestSent(state) } } } - VerifierState::Finished(state) => VerifierState::Finished(state) + VerifierFullState::Finished(state) => VerifierFullState::Finished(state) }; Ok(VerifierSM { source_id, state }) @@ -151,14 +150,14 @@ impl VerifierSM { pub fn thread_id(&self) -> String { self.presentation_request().map(|request| request.id.0.clone()).unwrap_or_default() } - pub fn state(&self) -> u32 { + pub fn get_state(&self) -> VerifierState { match self.state { - VerifierState::Initiated(_) => VcxStateType::VcxStateInitialized as u32, - VerifierState::PresentationRequestSent(_) => VcxStateType::VcxStateOfferSent as u32, - VerifierState::Finished(ref status) => { + VerifierFullState::Initiated(_) => VerifierState::Initial, + VerifierFullState::PresentationRequestSent(_) => VerifierState::PresentationRequestSent, + VerifierFullState::Finished(ref status) => { match status.status { - Status::Success => VcxStateType::VcxStateAccepted as u32, - _ => VcxStateType::VcxStateNone as u32, + Status::Success => VerifierState::Finished, + _ => VerifierState::Failed } } } @@ -166,15 +165,15 @@ impl VerifierSM { pub fn has_transitions(&self) -> bool { match self.state { - VerifierState::Initiated(_) => false, - VerifierState::PresentationRequestSent(_) => true, - VerifierState::Finished(_) => false, + VerifierFullState::Initiated(_) => false, + VerifierFullState::PresentationRequestSent(_) => true, + VerifierFullState::Finished(_) => false, } } pub fn presentation_status(&self) -> u32 { match self.state { - VerifierState::Finished(ref state) => { + VerifierFullState::Finished(ref state) => { match &state.status { Status::Success => { match state.revocation_status { @@ -195,17 +194,17 @@ impl VerifierSM { pub fn presentation_request(&self) -> VcxResult { match self.state { - VerifierState::Initiated(ref state) => { + VerifierFullState::Initiated(ref state) => { PresentationRequest::create().set_request_presentations_attach(&state.presentation_request_data) } - VerifierState::PresentationRequestSent(ref state) => Ok(state.presentation_request.clone()), - VerifierState::Finished(ref state) => Ok(state.presentation_request.clone()), + VerifierFullState::PresentationRequestSent(ref state) => Ok(state.presentation_request.clone()), + VerifierFullState::Finished(ref state) => Ok(state.presentation_request.clone()), } } pub fn presentation(&self) -> VcxResult { match self.state { - VerifierState::Finished(ref state) => { + VerifierFullState::Finished(ref state) => { state.presentation.clone() .ok_or(VcxError::from(VcxErrorKind::InvalidProofHandle)) } @@ -255,7 +254,7 @@ pub mod test { let verifier_sm = _verifier_sm(); - assert_match!(VerifierState::Initiated(_), verifier_sm.state); + assert_match!(VerifierFullState::Initiated(_), verifier_sm.state); assert_eq!(source_id(), verifier_sm.source_id()); } } @@ -270,7 +269,7 @@ pub mod test { let _setup = SetupMocks::init(); let verifier_sm = _verifier_sm(); - assert_match!(VerifierState::Initiated(_), verifier_sm.state); + assert_match!(VerifierFullState::Initiated(_), verifier_sm.state); } #[test] @@ -282,7 +281,7 @@ pub mod test { let mut verifier_sm = _verifier_sm(); verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); - assert_match!(VerifierState::PresentationRequestSent(_), verifier_sm.state); + assert_match!(VerifierFullState::PresentationRequestSent(_), verifier_sm.state); } #[test] @@ -294,10 +293,10 @@ pub mod test { let mut verifier_sm = _verifier_sm(); verifier_sm = verifier_sm.step(VerifierMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(VerifierState::Initiated(_), verifier_sm.state); + assert_match!(VerifierFullState::Initiated(_), verifier_sm.state); verifier_sm = verifier_sm.step(VerifierMessages::VerifyPresentation(_presentation()), send_message).unwrap(); - assert_match!(VerifierState::Initiated(_), verifier_sm.state); + assert_match!(VerifierFullState::Initiated(_), verifier_sm.state); } #[test] @@ -312,7 +311,7 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::VerifyPresentation(_presentation()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); assert_eq!(Status::Success.code(), verifier_sm.presentation_status()); } @@ -328,8 +327,8 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::VerifyPresentation(_presentation()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); - assert_eq!(VcxStateType::VcxStateAccepted as u32, verifier_sm.state()); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); + assert_eq!(VerifierState::Finished, verifier_sm.get_state()); assert_eq!(Status::Failed(ProblemReport::create()).code(), verifier_sm.presentation_status()); } @@ -341,7 +340,7 @@ pub mod test { // verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment())(mock_connection())).unwrap(); // verifier_sm = verifier_sm.step(VerifierMessages::VerifyPresentation(_presentation())).unwrap(); // - // assert_match!(VerifierState::Finished(_), verifier_sm.state); + // assert_match!(VerifierFullState::Finished(_), verifier_sm.state); // assert_eq!(Status::Failed(_problem_report()).code(), verifier_sm.presentation_status()); // } @@ -355,7 +354,7 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::PresentationProposalReceived(_presentation_proposal()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); assert_eq!(Status::Failed(_problem_report()).code(), verifier_sm.presentation_status()); } @@ -369,7 +368,7 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); assert_eq!(Status::Failed(_problem_report()).code(), verifier_sm.presentation_status()); } @@ -383,7 +382,7 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::SendPresentationRequest(_comment()), send_message).unwrap(); - assert_match!(VerifierState::PresentationRequestSent(_), verifier_sm.state); + assert_match!(VerifierFullState::PresentationRequestSent(_), verifier_sm.state); } #[test] @@ -397,10 +396,10 @@ pub mod test { verifier_sm = verifier_sm.step(VerifierMessages::VerifyPresentation(_presentation()), send_message).unwrap(); verifier_sm = verifier_sm.step(VerifierMessages::PresentationRejectReceived(_problem_report()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); verifier_sm = verifier_sm.step(VerifierMessages::PresentationProposalReceived(_presentation_proposal()), send_message).unwrap(); - assert_match!(VerifierState::Finished(_), verifier_sm.state); + assert_match!(VerifierFullState::Finished(_), verifier_sm.state); } } @@ -529,9 +528,9 @@ pub mod test { let _mock_builder = MockBuilder::init(). set_mock_result_for_validate_indy_proof(Ok(true)); - assert_eq!(VcxStateType::VcxStateInitialized as u32, _verifier_sm().state()); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, _verifier_sm().to_presentation_request_sent_state().state()); - assert_eq!(VcxStateType::VcxStateAccepted as u32, _verifier_sm().to_finished_state().state()); + assert_eq!(VerifierState::Initial, _verifier_sm().get_state()); + assert_eq!(VerifierState::PresentationRequestSent, _verifier_sm().to_presentation_request_sent_state().get_state()); + assert_eq!(VerifierState::Finished, _verifier_sm().to_finished_state().get_state()); } } } diff --git a/libvcx/src/aries/handlers/proof_presentation/verifier/verifier.rs b/libvcx/src/aries/handlers/proof_presentation/verifier/verifier.rs index e822a65660..ea01286792 100644 --- a/libvcx/src/aries/handlers/proof_presentation/verifier/verifier.rs +++ b/libvcx/src/aries/handlers/proof_presentation/verifier/verifier.rs @@ -3,7 +3,6 @@ use crate::aries::handlers::proof_presentation::verifier::messages::VerifierMess use crate::aries::handlers::proof_presentation::verifier::state_machine::VerifierSM; use crate::aries::handlers::connection::connection::Connection; use crate::aries::messages::a2a::A2AMessage; -use crate::aries::messages::proof_presentation::presentation::Presentation; use crate::aries::messages::proof_presentation::presentation_request::*; use std::collections::HashMap; @@ -12,6 +11,14 @@ pub struct Verifier { verifier_sm: VerifierSM } +#[derive(Debug, PartialEq)] +pub enum VerifierState { + Initial, + PresentationRequestSent, + Finished, + Failed +} + impl Verifier { pub fn create(source_id: String, requested_attrs: String, @@ -36,9 +43,9 @@ impl Verifier { pub fn get_source_id(&self) -> String { self.verifier_sm.source_id() } - pub fn state(&self) -> u32 { - trace!("Verifier::state >>>"); - self.verifier_sm.state() + pub fn get_state(&self) -> VerifierState { + trace!("Verifier::get_state >>>"); + self.verifier_sm.get_state() } pub fn presentation_status(&self) -> u32 { @@ -86,9 +93,9 @@ impl Verifier { self.verifier_sm.find_message_to_handle(messages) } - pub fn update_state(&mut self, connection: &Connection) -> VcxResult { + pub fn update_state(&mut self, connection: &Connection) -> VcxResult { trace!("Verifier::update_state >>> "); - if !self.has_transitions() { return Ok(self.state()); } + if !self.has_transitions() { return Ok(self.get_state()); } let send_message = connection.send_message_closure()?; let messages = connection.get_messages()?; @@ -96,6 +103,6 @@ impl Verifier { self.step(msg.into(), Some(&send_message))?; connection.update_message_status(uid)?; } - Ok(self.state()) + Ok(self.get_state()) } } diff --git a/libvcx/src/aries/mod.rs b/libvcx/src/aries/mod.rs index 1306df9420..68fc727851 100644 --- a/libvcx/src/aries/mod.rs +++ b/libvcx/src/aries/mod.rs @@ -164,7 +164,7 @@ pub mod test { alice.credential_handle = credential_handle; credential::send_credential_request(alice.credential_handle, alice_connection_by_handle).unwrap(); - assert_eq!(2, credential::get_state(alice.credential_handle).unwrap()); + assert_eq!(1, credential::get_state(alice.credential_handle).unwrap()); } faber.send_credential(); @@ -183,11 +183,11 @@ pub mod test { let credentials = alice.get_credentials_for_presentation(); disclosed_proof::generate_proof(alice.presentation_handle, credentials.to_string(), String::from("{}")).unwrap(); - assert_eq!(3, disclosed_proof::get_state(alice.presentation_handle).unwrap()); + assert_eq!(1, disclosed_proof::get_state(alice.presentation_handle).unwrap()); let alice_connection_by_handle = connection::store_connection(alice.connection.clone()).unwrap(); disclosed_proof::send_proof(alice.presentation_handle, alice_connection_by_handle).unwrap(); - assert_eq!(2, disclosed_proof::get_state(alice.presentation_handle).unwrap()); + assert_eq!(3, disclosed_proof::get_state(alice.presentation_handle).unwrap()); } faber.verify_presentation(); @@ -235,7 +235,7 @@ pub mod test { let alice_connection_by_handle = connection::store_connection(alice.connection.clone()).unwrap(); credential::send_credential_request(alice.credential_handle, alice_connection_by_handle).unwrap(); - assert_eq!(2, credential::get_state(alice.credential_handle).unwrap()); + assert_eq!(1, credential::get_state(alice.credential_handle).unwrap()); } faber.send_credential(); @@ -255,11 +255,11 @@ pub mod test { let credentials = alice.get_credentials_for_presentation(); disclosed_proof::generate_proof(alice.presentation_handle, credentials.to_string(), String::from("{}")).unwrap(); - assert_eq!(3, disclosed_proof::get_state(alice.presentation_handle).unwrap()); + assert_eq!(1, disclosed_proof::get_state(alice.presentation_handle).unwrap()); let alice_connection_by_handle = connection::store_connection(alice.connection.clone()).unwrap(); disclosed_proof::send_proof(alice.presentation_handle, alice_connection_by_handle).unwrap(); - assert_eq!(2, disclosed_proof::get_state(alice.presentation_handle).unwrap()); + assert_eq!(3, disclosed_proof::get_state(alice.presentation_handle).unwrap()); } faber.verify_presentation(); diff --git a/libvcx/src/lib.rs b/libvcx/src/lib.rs index 1689f9458b..682dbb5068 100644 --- a/libvcx/src/lib.rs +++ b/libvcx/src/lib.rs @@ -60,7 +60,6 @@ mod tests { use crate::api_lib::api_handle::issuer_credential; use crate::api_lib::api_handle::proof; use crate::api_lib::ProofStateType; - use crate::api_lib::VcxStateType; use crate::filters; use crate::settings; use crate::utils::{ @@ -69,6 +68,10 @@ mod tests { }; use crate::utils::devsetup::*; use crate::utils::devsetup_agent::test::{Alice, Faber, TestAgent}; + use crate::aries::handlers::issuance::holder::holder::HolderState; + use crate::aries::handlers::issuance::issuer::issuer::IssuerState; + use crate::aries::handlers::proof_presentation::prover::prover::ProverState; + use crate::aries::handlers::proof_presentation::verifier::verifier::VerifierState; use super::*; @@ -179,7 +182,7 @@ mod tests { let offers = serde_json::to_string(&offers[0]).unwrap(); info!("send_cred_req :: creating credential from offer"); let credential = credential::credential_create_with_offer("TEST_CREDENTIAL", &offers).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, credential::get_state(credential).unwrap()); + assert_eq!(HolderState::OfferReceived as u32, credential::get_state(credential).unwrap()); info!("send_cred_req :: sending credential request"); credential::send_credential_request(credential, connection).unwrap(); thread::sleep(Duration::from_millis(2000)); @@ -191,7 +194,7 @@ mod tests { info!("send_credential >>> getting offers"); assert_eq!(issuer_credential::is_revokable(handle_issuer_credential).unwrap(), revokable); issuer_credential::update_state(handle_issuer_credential, None, issuer_to_consumer).unwrap(); - assert_eq!(VcxStateType::VcxStateRequestReceived as u32, issuer_credential::get_state(handle_issuer_credential).unwrap()); + assert_eq!(IssuerState::RequestReceived as u32, issuer_credential::get_state(handle_issuer_credential).unwrap()); assert_eq!(issuer_credential::is_revokable(handle_issuer_credential).unwrap(), revokable); info!("send_credential >>> sending credential"); @@ -202,7 +205,7 @@ mod tests { info!("send_credential >>> storing credential"); assert_eq!(credential::is_revokable(handle_holder_credential).unwrap(), revokable); credential::update_state(handle_holder_credential, None, consumer_to_issuer).unwrap(); - assert_eq!(VcxStateType::VcxStateAccepted as u32, credential::get_state(handle_holder_credential).unwrap()); + assert_eq!(HolderState::Finished as u32, credential::get_state(handle_holder_credential).unwrap()); assert_eq!(credential::is_revokable(handle_holder_credential).unwrap(), revokable); if revokable { @@ -254,7 +257,7 @@ mod tests { disclosed_proof::send_proof(proof_handle, connection_handle).unwrap(); info!("generate_and_send_proof :: proof sent"); - assert_eq!(VcxStateType::VcxStateOfferSent as u32, disclosed_proof::get_state(proof_handle).unwrap()); + assert_eq!(ProverState::PresentationSent as u32, disclosed_proof::get_state(proof_handle).unwrap()); thread::sleep(Duration::from_millis(5000)); } @@ -928,4 +931,15 @@ mod tests { proof::update_state(proof_handle_verifier, None, verifier_to_consumer).unwrap(); assert_eq!(proof::get_proof_state(proof_handle_verifier).unwrap(), ProofStateType::ProofInvalid as u32); } + + #[test] + #[cfg(feature = "agency_pool_tests")] + pub fn test_two_enterprise_connections() { + let _setup = SetupLibraryAgencyV2ZeroFees::init(); + let mut institution = Faber::setup(); + let mut consumer1 = Alice::setup(); + + let (_faber, _alice) = connection::tests::create_and_store_connected_connections(&mut consumer1, &mut institution); + let (_faber, _alice) = connection::tests::create_and_store_connected_connections(&mut consumer1, &mut institution); + } } diff --git a/libvcx/src/libindy/utils/wallet.rs b/libvcx/src/libindy/utils/wallet.rs index a5f03ebc7f..9aac9823a1 100644 --- a/libvcx/src/libindy/utils/wallet.rs +++ b/libvcx/src/libindy/utils/wallet.rs @@ -357,8 +357,6 @@ pub fn import(restore_config: &RestoreWalletConfigs) -> VcxResult<()> { pub mod tests { use agency_client::agency_settings; - use crate::api_lib; - use crate::api_lib::api_c; use crate::libindy::utils::signus::create_and_store_my_did; use crate::utils::devsetup::{SetupDefaults, SetupLibraryWallet, TempFile}; use crate::utils::get_temp_dir_path; @@ -544,7 +542,7 @@ pub mod tests { let id = "id1"; let value = "value1"; - api_c::vcx::vcx_shutdown(true); + // api_c::vcx::vcx_shutdown(true); let import_config = RestoreWalletConfigs { wallet_name: wallet_name.clone(), diff --git a/libvcx/src/utils/devsetup.rs b/libvcx/src/utils/devsetup.rs index ebc4194743..6541bdeb66 100644 --- a/libvcx/src/utils/devsetup.rs +++ b/libvcx/src/utils/devsetup.rs @@ -15,7 +15,6 @@ use crate::utils::devsetup_agent::test::{Alice, Faber, TestAgent}; use crate::utils::file::write_file; use crate::utils::get_temp_dir_path; use crate::utils::logger::LibvcxDefaultLogger; -use crate::api_lib::api_handle::object_cache::ObjectCache; use crate::utils::plugins::init_plugin; pub struct SetupEmpty; // clears settings, setups up logging @@ -429,21 +428,3 @@ impl Drop for TempFile { fs::remove_file(&self.path).unwrap() } } - -#[cfg(feature = "agency_pool_tests")] -mod tests { - use crate::api_lib::api_handle::connection; - - use super::*; - - #[cfg(feature = "agency_pool_tests")] - #[test] - pub fn test_two_enterprise_connections() { - let _setup = SetupLibraryAgencyV2ZeroFees::init(); - let mut institution = Faber::setup(); - let mut consumer1 = Alice::setup(); - - let (_faber, _alice) = connection::tests::create_and_store_connected_connections(&mut consumer1, &mut institution); - let (_faber, _alice) = connection::tests::create_and_store_connected_connections(&mut consumer1, &mut institution); - } -} diff --git a/libvcx/src/utils/devsetup_agent.rs b/libvcx/src/utils/devsetup_agent.rs index 36dd99a512..499af906ef 100644 --- a/libvcx/src/utils/devsetup_agent.rs +++ b/libvcx/src/utils/devsetup_agent.rs @@ -240,14 +240,14 @@ pub mod test { let connection_by_handle = connection::store_connection(self.connection.clone()).unwrap(); issuer_credential::send_credential_offer(self.credential_handle, connection_by_handle, None).unwrap(); issuer_credential::update_state(self.credential_handle, None, connection_by_handle).unwrap(); - assert_eq!(2, issuer_credential::get_state(self.credential_handle).unwrap()); + assert_eq!(1, issuer_credential::get_state(self.credential_handle).unwrap()); } pub fn send_credential(&mut self) { self.activate().unwrap(); let connection_by_handle = connection::store_connection(self.connection.clone()).unwrap(); issuer_credential::update_state(self.credential_handle, None, connection_by_handle).unwrap(); - assert_eq!(3, issuer_credential::get_state(self.credential_handle).unwrap()); + assert_eq!(2, issuer_credential::get_state(self.credential_handle).unwrap()); issuer_credential::send_credential(self.credential_handle, connection_by_handle).unwrap(); issuer_credential::update_state(self.credential_handle, None, connection_by_handle).unwrap(); @@ -258,18 +258,18 @@ pub mod test { pub fn request_presentation(&mut self) { self.activate().unwrap(); self.presentation_handle = self.create_presentation_request(); - assert_eq!(1, proof::get_state(self.presentation_handle).unwrap()); + assert_eq!(0, proof::get_state(self.presentation_handle).unwrap()); let connection_by_handle = connection::store_connection(self.connection.clone()).unwrap(); proof::send_proof_request(self.presentation_handle, connection_by_handle, None).unwrap(); proof::update_state(self.presentation_handle, None, connection_by_handle).unwrap(); - assert_eq!(2, proof::get_state(self.presentation_handle).unwrap()); + assert_eq!(1, proof::get_state(self.presentation_handle).unwrap()); } pub fn verify_presentation(&mut self) { self.activate().unwrap(); - self.update_proof_state(4, aries::messages::status::Status::Success.code()) + self.update_proof_state(2, aries::messages::status::Status::Success.code()) } pub fn update_proof_state(&mut self, expected_state: u32, expected_status: u32) { @@ -363,17 +363,17 @@ pub mod test { let offer_json = serde_json::to_string(&offer).unwrap(); self.credential_handle = credential::credential_create_with_offer("degree", &offer_json).unwrap(); - assert_eq!(3, credential::get_state(self.credential_handle).unwrap()); + assert_eq!(0, credential::get_state(self.credential_handle).unwrap()); credential::send_credential_request(self.credential_handle, connection_by_handle).unwrap(); - assert_eq!(2, credential::get_state(self.credential_handle).unwrap()); + assert_eq!(1, credential::get_state(self.credential_handle).unwrap()); } pub fn accept_credential(&mut self) { self.activate().unwrap(); let connection_by_handle = connection::store_connection(self.connection.clone()).unwrap(); credential::update_state(self.credential_handle, None, connection_by_handle).unwrap(); - assert_eq!(4, credential::get_state(self.credential_handle).unwrap()); + assert_eq!(2, credential::get_state(self.credential_handle).unwrap()); assert_eq!(aries::messages::status::Status::Success.code(), credential::get_credential_status(self.credential_handle).unwrap()); } @@ -410,11 +410,11 @@ pub mod test { let credentials = self.get_credentials_for_presentation(); disclosed_proof::generate_proof(self.presentation_handle, credentials.to_string(), String::from("{}")).unwrap(); - assert_eq!(3, disclosed_proof::get_state(self.presentation_handle).unwrap()); + assert_eq!(1, disclosed_proof::get_state(self.presentation_handle).unwrap()); let connection_by_handle = connection::store_connection(self.connection.clone()).unwrap(); disclosed_proof::send_proof(self.presentation_handle, connection_by_handle).unwrap(); - assert_eq!(2, disclosed_proof::get_state(self.presentation_handle).unwrap()); + assert_eq!(3, disclosed_proof::get_state(self.presentation_handle).unwrap()); } pub fn decline_presentation_request(&mut self) { diff --git a/wrappers/node/src/api/common.ts b/wrappers/node/src/api/common.ts index d08d0ebdce..a79c64d84a 100644 --- a/wrappers/node/src/api/common.ts +++ b/wrappers/node/src/api/common.ts @@ -105,19 +105,47 @@ export enum VCXCode { INVALID_REDIRECT_DETAILS = 1104, NO_AGENT_INFO = 1106, } -export enum StateType { - None = 0, - Initialized = 1, - OfferSent = 2, - RequestReceived = 3, - Accepted = 4, - Unfulfilled = 5, - Expired = 6, - Revoked = 7, - Redirected = 8, - Rejected = 9, +export enum ConnectionStateType { + Null = 0, + Invited = 1, + Requested = 2, + Responded = 3, + Finished = 4, } +export enum HolderStateType { + OfferReceived = 0, + RequestSent = 1, + Finished = 2, + Failed = 3, +} + +export enum IssuerStateType { + Initial = 0, + OfferSent = 1, + RequestReceived = 2, + CredentialSent = 3, + Finished = 4, + Failed = 5, +} + +export enum ProverStateType { + Initial = 0, + PresentationPrepared = 1, + PresentationPreparationFailed = 2, + PresentationSent = 3, + Finished = 4, + Failed = 5, +} + +export enum VerifierStateType { + Initial = 0, + PresentationRequestSent = 1, + Finished = 2, + Failed = 3, +} + + export interface IInitVCXOptions { libVCXPath?: string; } diff --git a/wrappers/node/src/api/connection.ts b/wrappers/node/src/api/connection.ts index 59327d4e64..a8d3b5c6ef 100644 --- a/wrappers/node/src/api/connection.ts +++ b/wrappers/node/src/api/connection.ts @@ -3,7 +3,7 @@ import * as ref from 'ref-napi'; import { VCXInternalError } from '../errors'; import { rustAPI } from '../rustlib'; import { createFFICallbackPromise, ICbRef } from '../utils/ffi-helpers'; -import { ISerializedData, StateType } from './common'; +import { ISerializedData, ConnectionStateType } from './common'; import { VCXBaseWithState } from './vcx-base-with-state'; import { PtrBuffer } from './utils'; @@ -105,7 +105,7 @@ export interface IConnectionData { endpoint: string; uuid: string; wallet: string; - state: StateType; + state: ConnectionStateType; } /** @@ -237,7 +237,7 @@ export async function downloadMessagesV2({ /** * @class Class representing a Connection */ -export class Connection extends VCXBaseWithState { +export class Connection extends VCXBaseWithState { /** * Create a connection object, represents a single endpoint and can be used for sending and receiving * credentials and proofs @@ -335,14 +335,14 @@ export class Connection extends VCXBaseWithState { cb, ); if (rc) { - resolve(StateType.None); + resolve(0); } }, (resolve, reject) => ffi.Callback( 'void', ['uint32', 'uint32', 'uint32'], - (handle: number, err: number, _state: StateType) => { + (handle: number, err: number, _state: number) => { if (err) { reject(err); } @@ -373,14 +373,14 @@ export class Connection extends VCXBaseWithState { (resolve, reject, cb) => { const rc = this._updateStFn(commandHandle, this.handle, cb); if (rc) { - resolve(StateType.None); + resolve(0); } }, (resolve, reject) => ffi.Callback( 'void', ['uint32', 'uint32', 'uint32'], - (handle: number, err: number, _state: StateType) => { + (handle: number, err: number, _state: number) => { if (err) { reject(err); } diff --git a/wrappers/node/src/api/credential.ts b/wrappers/node/src/api/credential.ts index b8ecb2cf6b..46ff7c42b3 100644 --- a/wrappers/node/src/api/credential.ts +++ b/wrappers/node/src/api/credential.ts @@ -3,7 +3,7 @@ import { Callback } from 'ffi-napi'; import { VCXInternalError } from '../errors'; import { rustAPI } from '../rustlib'; import { createFFICallbackPromise } from '../utils/ffi-helpers'; -import { ISerializedData } from './common'; +import { ISerializedData, HolderStateType } from './common'; import { Connection } from './connection'; import { VCXBaseWithState } from './vcx-base-with-state'; import { PaymentManager } from './vcx-payment-txn'; @@ -104,7 +104,7 @@ export class CredentialPaymentManager extends PaymentManager { /** * A Credential Object, which is issued by the issuing party to the prover and stored in the prover's wallet. */ -export class Credential extends VCXBaseWithState { +export class Credential extends VCXBaseWithState { /** * Creates a credential with an offer. * diff --git a/wrappers/node/src/api/disclosed-proof.ts b/wrappers/node/src/api/disclosed-proof.ts index 4bd44926fd..255e4b6533 100644 --- a/wrappers/node/src/api/disclosed-proof.ts +++ b/wrappers/node/src/api/disclosed-proof.ts @@ -3,7 +3,7 @@ import { Callback } from 'ffi-napi'; import { VCXInternalError } from '../errors'; import { rustAPI } from '../rustlib'; import { createFFICallbackPromise } from '../utils/ffi-helpers'; -import { ISerializedData } from './common'; +import { ISerializedData, ProverStateType } from './common'; import { Connection } from './connection'; import { VCXBaseWithState } from './vcx-base-with-state'; @@ -126,7 +126,7 @@ export interface IDeclinePresentationRequestData { proposal?: any; // eslint-disable-line @typescript-eslint/no-explicit-any } -export class DisclosedProof extends VCXBaseWithState { +export class DisclosedProof extends VCXBaseWithState { /** * Create a proof for fulfilling a corresponding proof request * diff --git a/wrappers/node/src/api/issuer-credential.ts b/wrappers/node/src/api/issuer-credential.ts index abd0f1c3d3..2e16dd4c57 100644 --- a/wrappers/node/src/api/issuer-credential.ts +++ b/wrappers/node/src/api/issuer-credential.ts @@ -2,7 +2,7 @@ import * as ffi from 'ffi-napi'; import { VCXInternalError } from '../errors'; import { rustAPI } from '../rustlib'; import { createFFICallbackPromise } from '../utils/ffi-helpers'; -import { ISerializedData } from './common'; +import { ISerializedData, IssuerStateType } from './common'; import { Connection } from './connection'; import { VCXBaseWithState } from './vcx-base-with-state'; import { PaymentManager } from './vcx-payment-txn'; @@ -66,6 +66,7 @@ export interface IIssuerCredentialCreateData { credentialName: string; // price of credential price: string; + issuerDid: string; } export interface IIssuerCredentialVCXAttributes { @@ -96,7 +97,7 @@ export class IssuerCredentialPaymentManager extends PaymentManager { /** * A Credential created by the issuing party (institution) */ -export class IssuerCredential extends VCXBaseWithState { +export class IssuerCredential extends VCXBaseWithState { /** * Create a Issuer Credential object that provides a credential for an enterprise's user * Assumes a credential definition has been already written to the ledger. @@ -112,6 +113,7 @@ export class IssuerCredential extends VCXBaseWithState { credDefHandle, credentialName, price, + issuerDid, }: IIssuerCredentialCreateData): Promise { try { const attrsVCX: IIssuerCredentialVCXAttributes = attr; @@ -123,7 +125,6 @@ export class IssuerCredential extends VCXBaseWithState { }); const attrsStringified = attrsVCX ? JSON.stringify(attrsVCX) : attrsVCX; const commandHandle = 0; - const issuerDid = null; await credential._create((cb) => rustAPI().vcx_issuer_create_credential( commandHandle, @@ -288,15 +289,6 @@ export class IssuerCredential extends VCXBaseWithState { * Sends the credential to the end user. * * Credential is made up of the data sent during Credential Offer - * ``` - * connection = await connectionCreateConnect() - * issuerCredential = await issuerCredentialCreate() - * await issuerCredential.sendOffer(connection) - * await issuerCredential.updateState() - * assert.equal(await issuerCredential.getState(), StateType.RequestReceived) - * await issuerCredential.sendCredential(connection) - * ``` - * */ public async sendCredential(connection: Connection): Promise { try { @@ -325,15 +317,6 @@ export class IssuerCredential extends VCXBaseWithState { * Gets the credential message for sending to connection. * * Credential is made up of the data sent during Credential Offer - * ``` - * connection = await connectionCreateConnect() - * issuerCredential = await issuerCredentialCreate() - * await issuerCredential.sendOffer(connection) - * await issuerCredential.updateState() - * assert.equal(await issuerCredential.getState(), StateType.RequestReceived) - * await issuerCredential.getCredentialMsg() - * ``` - * */ public async getCredentialMsg(myPwDid: string): Promise { try { @@ -370,16 +353,6 @@ export class IssuerCredential extends VCXBaseWithState { * Revokes credential. * * Credential is made up of the data sent during Credential Offer - * ``` - * connection = await connectionCreateConnect() - * issuerCredential = await issuerCredentialCreate() - * await issuerCredential.sendOffer(connection) - * await issuerCredential.updateState() - * assert.equal(await issuerCredential.getState(), StateType.RequestReceived) - * await issuerCredential.sendCredential(connection) - * await issuerCredential.revokeCredential() - * ``` - * */ public async revokeCredential(): Promise { try { diff --git a/wrappers/node/src/api/proof.ts b/wrappers/node/src/api/proof.ts index 0f9da6bba0..96f368ec12 100644 --- a/wrappers/node/src/api/proof.ts +++ b/wrappers/node/src/api/proof.ts @@ -2,7 +2,7 @@ import * as ffi from 'ffi-napi'; import { VCXInternalError } from '../errors'; import { rustAPI } from '../rustlib'; import { createFFICallbackPromise } from '../utils/ffi-helpers'; -import { ISerializedData, StateType } from './common'; +import { ISerializedData, VerifierStateType } from './common'; import { Connection } from './connection'; import { VCXBaseWithState } from './vcx-base-with-state'; @@ -78,7 +78,7 @@ export interface IProofData { requested_attrs: string; requested_predicates: string; prover_did: string; - state: StateType; + state: number; name: string; proof_state: ProofState; proof: any; // eslint-disable-line @typescript-eslint/no-explicit-any @@ -166,46 +166,15 @@ export interface IRevocationInterval { /** * Class representing a Proof */ -export class Proof extends VCXBaseWithState { +export class Proof extends VCXBaseWithState { /** * Get the state of the proof - * - * Example - * ``` - * data = { - * attrs: [ - * { name: 'attr1' }, - * { name: 'attr2' }], - * name: 'Proof', - * sourceId: 'testProofSourceId' - * } - * proof = await Proof.create(data) - * await proof.requestProof(connection) - * assert.equal(await proof.getState(), StateType.OfferSent) - * ``` */ get proofState(): ProofState | null { return this._proofState; } /** * Get the attributes of the proof - * - * Example - * ``` - * data = { - * attrs: [ - * { name: 'attr1' }, - * { name: 'attr2' }], - * name: 'Proof', - * sourceId: 'testProofSourceId' - * } - * proof = await Proof.create(data) - * await proof.requestProof(connection) - * assert.equal(await proof.getState(), StateType.OfferSent) - * proofData = await proof.getProof(connection) - * await proof.updateState() - * assert.equal(await proof.requestedAttributes(), data.attrs) - * ``` */ get requestedAttributes(): IProofAttr[] { return this._requestedAttributes; @@ -217,23 +186,6 @@ export class Proof extends VCXBaseWithState { /** * Get the name of the proof - * - * Example - * ``` - * data = { - * attrs: [ - * { name: 'attr1' }, - * { name: 'attr2' }], - * name: 'Proof', - * sourceId: 'testProofSourceId' - * } - * proof = await Proof.create(data) - * await proof.requestProof(connection) - * assert.equal(await proof.getState(), StateType.OfferSent) - * proofData = await proof.getProof(connection) - * await proof.updateState() - * assert.equal(await proof.name(), data.name) - * ``` */ get name(): string { return this._name; diff --git a/wrappers/node/src/api/vcx-base-with-state.ts b/wrappers/node/src/api/vcx-base-with-state.ts index b23640729a..31d6c39c42 100644 --- a/wrappers/node/src/api/vcx-base-with-state.ts +++ b/wrappers/node/src/api/vcx-base-with-state.ts @@ -1,11 +1,10 @@ import * as ffi from 'ffi-napi'; import { VCXInternalError } from '../errors'; import { createFFICallbackPromise, ICbRef } from '../utils/ffi-helpers'; -import { StateType } from './common'; import { Connection } from './connection'; import { VCXBase } from './vcx-base'; -export abstract class VCXBaseWithState extends VCXBase { +export abstract class VCXBaseWithState extends VCXBase { protected abstract _updateStFnV2: ( commandHandle: number, handle: number, @@ -14,14 +13,14 @@ export abstract class VCXBaseWithState extends VCXBase number; protected abstract _getStFn: (commandHandle: number, handle: number, cb: ICbRef) => number; - public async updateStateV2(connection: Connection): Promise { + public async updateStateV2(connection: Connection): Promise { try { const commandHandle = 0; - const state = await createFFICallbackPromise( + const state = await createFFICallbackPromise( (resolve, reject, cb) => { const rc = this._updateStFnV2(commandHandle, this.handle, connection.handle, cb); if (rc) { - resolve(StateType.None); + reject(rc); } }, (resolve, reject) => @@ -58,7 +57,7 @@ export abstract class VCXBaseWithState extends VCXBase { const rc = this._getStFn(commandHandle, this.handle, cb); if (rc) { - resolve(StateType.None); + reject(rc); } }, (resolve, reject) => diff --git a/wrappers/node/test/helpers/entities.ts b/wrappers/node/test/helpers/entities.ts index 805572a20f..ffa5549a38 100644 --- a/wrappers/node/test/helpers/entities.ts +++ b/wrappers/node/test/helpers/entities.ts @@ -214,6 +214,7 @@ export const dataIssuerCredentialCreate = async (): Promise { before(() => initVcxTestMode()); @@ -130,45 +130,48 @@ describe('Connection:', () => { }); describe('updateState:', () => { - it(`returns ${StateType.None}: not initialized`, async () => { + it('throws error when not initialized', async () => { + let caught_error; const connection = new (Connection as any)(); - const state1 = await connection.updateState(); - const state2 = await connection.getState(); - assert.equal(state1, state2); - assert.equal(state2, StateType.None); + try { + await connection.updateState(); + } catch (err) { + caught_error = err; + } + assert.isNotNull(caught_error); }); - it(`returns ${StateType.Initialized}: not connected`, async () => { + it(`returns ${ConnectionStateType.Null}: not connected`, async () => { const connection = await connectionCreateInviterNull({ id: 'alice' }); await connection.updateState(); - assert.equal(await connection.getState(), StateType.None); + assert.equal(await connection.getState(), ConnectionStateType.Null); }); // todo : restore for aries - it.skip(`returns ${StateType.OfferSent}: connected`, async () => { + it.skip(`returns ${ConnectionStateType.Finished}: connected`, async () => { const connection = await createConnectionInviterRequested(); VCXMock.setVcxMock(VCXMockMessage.AcceptInvite); // todo: must return Aries mock data await connection.updateState(); - assert.equal(await connection.getState(), StateType.Accepted); + assert.equal(await connection.getState(), ConnectionStateType.Finished); }); // todo : restore for aries - it.skip(`returns ${StateType.Accepted}: mocked accepted`, async () => { + it.skip(`returns ${ConnectionStateType.Finished}: mocked accepted`, async () => { const connection = await createConnectionInviterRequested(); VCXMock.setVcxMock(VCXMockMessage.GetMessages); await connection.updateState(); - assert.equal(await connection.getState(), StateType.Accepted); + assert.equal(await connection.getState(), ConnectionStateType.Finished); }); // todo : restore for aries - it.skip(`returns ${StateType.Accepted}: mocked accepted`, async () => { + it.skip(`returns ${ConnectionStateType.Finished}: mocked accepted`, async () => { const connection = await createConnectionInviterRequested(); await connection.updateStateWithMessage(INVITE_ACCEPTED_MESSAGE); - assert.equal(await connection.getState(), StateType.Accepted); + assert.equal(await connection.getState(), ConnectionStateType.Finished); }); // todo : restore for aries - it.skip(`returns ${StateType.Accepted}: mocked accepted in parallel`, async () => { + it.skip(`returns ${ConnectionStateType.Finished}: mocked accepted in parallel`, async () => { const numConnections = 50; const interval = 50; const sleepTime = 100; @@ -184,7 +187,7 @@ describe('Connection:', () => { const states = await Promise.all( connectionsWithTimers.map(({ connection }) => connection.getState()), ); - cond = states.every((state) => state === StateType.Accepted); + cond = states.every((state) => state === ConnectionStateType.Finished); VCXMock.setVcxMock(VCXMockMessage.GetMessages); await sleep(sleepTime); } diff --git a/wrappers/node/test/suite1/ariesvcx-credential.test.ts b/wrappers/node/test/suite1/ariesvcx-credential.test.ts index 78a1969d7d..518e5b0600 100644 --- a/wrappers/node/test/suite1/ariesvcx-credential.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-credential.test.ts @@ -14,7 +14,7 @@ import { initVcxTestMode, shouldThrow } from 'helpers/utils'; import { Credential, CredentialPaymentManager, - StateType, + HolderStateType, VCXCode, VCXMock, VCXMockMessage, @@ -94,9 +94,9 @@ describe('Credential:', () => { const connection = await createConnectionInviterRequested(); const data = await dataCredentialCreateWithOffer(); const credential = await Credential.create(data); - assert.equal(await credential.getState(), StateType.RequestReceived); + assert.equal(await credential.getState(), HolderStateType.OfferReceived); credential.sendRequest({ connection, payment: 0 }); - assert.equal(await credential.getState(), StateType.OfferSent); + assert.equal(await credential.getState(), HolderStateType.RequestSent); }); }); @@ -105,14 +105,14 @@ describe('Credential:', () => { const data = await dataCredentialCreateWithOffer(); const credential = await credentialCreateWithOffer(data); await credential.sendRequest({ connection: data.connection, payment: 0 }); - assert.equal(await credential.getState(), StateType.OfferSent); + assert.equal(await credential.getState(), HolderStateType.RequestSent); }); it('success: with message id', async () => { const data = await dataCredentialCreateWithMsgId(); const credential = await credentialCreateWithMsgId(data); await credential.sendRequest({ connection: data.connection, payment: 0 }); - assert.equal(await credential.getState(), StateType.OfferSent); + assert.equal(await credential.getState(), HolderStateType.RequestSent); }); }); diff --git a/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts b/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts index cc3f252d06..c267b66450 100644 --- a/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-disclosed-proof.test.ts @@ -11,7 +11,7 @@ import { } from 'helpers/entities' import { initVcxTestMode, shouldThrow } from 'helpers/utils'; import { mapValues } from 'lodash'; -import { DisclosedProof, StateType, VCXCode } from 'src'; +import { DisclosedProof, ProverStateType, VCXCode } from 'src'; describe('DisclosedProof', () => { before(() => initVcxTestMode()); @@ -120,20 +120,23 @@ describe('DisclosedProof', () => { }); describe('updateState:', () => { - it(`returns ${StateType.None}: not initialized`, async () => { + it('Throws error when not initialized', async () => { + let caught_error; const disclosedProof = new (DisclosedProof as any)(); const connection = await createConnectionInviterRequested(); - const state1 = await disclosedProof.updateStateV2(connection); - const state2 = await disclosedProof.getState(); - assert.equal(state1, state2); - assert.equal(state2, StateType.None); + try { + await disclosedProof.updateStateV2(connection); + } catch (err) { + caught_error = err; + } + assert.isNotNull(caught_error); }); - it(`returns ${StateType.RequestReceived}: created`, async () => { + it(`returns ${ProverStateType.Initial}: created`, async () => { const disclosedProof = await disclosedProofCreateWithRequest(); const connection = await createConnectionInviterRequested(); await disclosedProof.updateStateV2(connection); - assert.equal(await disclosedProof.getState(), StateType.RequestReceived); + assert.equal(await disclosedProof.getState(), ProverStateType.Initial); }); }); @@ -142,7 +145,7 @@ describe('DisclosedProof', () => { const data = await dataDisclosedProofCreateWithRequest(); const disclosedProof = await disclosedProofCreateWithRequest(data); await disclosedProof.sendProof(data.connection); - assert.equal(await disclosedProof.getState(), StateType.Accepted); + assert.equal(await disclosedProof.getState(), ProverStateType.PresentationSent); }); }); @@ -159,7 +162,7 @@ describe('DisclosedProof', () => { sourceId: 'disclosedProofTestSourceId', }); await disclosedProof.updateStateV2(connection); - assert.equal(await disclosedProof.getState(), StateType.RequestReceived); + assert.equal(await disclosedProof.getState(), ProverStateType.Finished); }); }); diff --git a/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts b/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts index 005d978303..ed7cfaeb36 100644 --- a/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-issuer-credential.test.ts @@ -7,7 +7,7 @@ import { issuerCredentialCreate, } from 'helpers/entities'; import { initVcxTestMode, shouldThrow } from 'helpers/utils'; -import { Connection, IssuerCredential, StateType, VCXCode } from 'src'; +import { Connection, IssuerCredential, IssuerStateType, VCXCode } from 'src'; describe('IssuerCredential:', () => { before(() => initVcxTestMode()); @@ -120,7 +120,7 @@ describe('IssuerCredential:', () => { const issuerCredential = await issuerCredentialCreate(); const connection = await createConnectionInviterRequested(); await issuerCredential.sendOffer(connection); - assert.equal(await issuerCredential.getState(), StateType.OfferSent); + assert.equal(await issuerCredential.getState(), IssuerStateType.OfferSent); }); }); @@ -129,7 +129,7 @@ describe('IssuerCredential:', () => { const connection = await createConnectionInviterRequested(); const issuerCredential = await issuerCredentialCreate(); await issuerCredential.sendOffer(connection); - assert.equal(await issuerCredential.getState(), StateType.OfferSent); + assert.equal(await issuerCredential.getState(), IssuerStateType.OfferSent); }); it('throws: not initialized', async () => { diff --git a/wrappers/node/test/suite1/ariesvcx-proof.test.ts b/wrappers/node/test/suite1/ariesvcx-proof.test.ts index 481a775db9..a82f349078 100644 --- a/wrappers/node/test/suite1/ariesvcx-proof.test.ts +++ b/wrappers/node/test/suite1/ariesvcx-proof.test.ts @@ -8,7 +8,7 @@ import { DisclosedProof, Proof, ProofState, - StateType, + VerifierStateType, VCXCode, VCXMock, VCXMockMessage, @@ -109,20 +109,16 @@ describe('Proof:', () => { }); describe('updateState:', () => { - it(`returns ${StateType.None}: not initialized`, async () => { + it(`throws error when not initialized`, async () => { + let caught_error; const proof = new Proof(null as any, {} as any); const connection = await createConnectionInviterRequested(); - const state1 = await proof.updateStateV2(connection); - const state2 = await proof.getState(); - assert.equal(state1, state2); - assert.equal(state2, StateType.None); - }); - - it(`returns ${StateType.Initialized}: created`, async () => { - const connection = await createConnectionInviterRequested(); - const proof = await proofCreate(); - await proof.updateStateV2(connection); - assert.equal(await proof.getState(), StateType.Initialized); + try { + await proof.updateStateV2(connection); + } catch (err) { + caught_error = err; + } + assert.isNotNull(caught_error); }); }); @@ -131,7 +127,7 @@ describe('Proof:', () => { const connection = await createConnectionInviterRequested(); const proof = await proofCreate(); await proof.requestProof(connection); - assert.equal(await proof.getState(), StateType.OfferSent); + assert.equal(await proof.getState(), VerifierStateType.PresentationRequestSent); }); it('successfully get request message', async () => {