From 516bdb9c91a0f76233f886684d24f3db1514fd1e Mon Sep 17 00:00:00 2001 From: Patrik Date: Wed, 8 Mar 2023 12:39:37 +0100 Subject: [PATCH] Rename prover methods, extend test test_generate_self_attested_proof (#764) * Rename prover & verifier methods, extend test test_generate_self_attested_proof --------- Signed-off-by: Patrik Stas --- agents/node/vcxagent-core/demo/faber.js | 19 +- agents/node/vcxagent-core/src/agent.js | 17 +- .../src/services/service-prover.js | 5 - .../src/services/service-verifier.js | 26 +- .../test/distribute-tails.spec.js | 14 +- .../vcxagent-core/test/issue-verify.spec.js | 138 ++++- .../test/nonmediated-connection.spec.js | 10 +- .../test/nonmediated-endpoint.spec.js | 1 - .../vcxagent-core/test/out-of-band.spec.js | 13 +- agents/node/vcxagent-core/test/utils/alice.js | 17 +- agents/node/vcxagent-core/test/utils/data.js | 36 +- agents/node/vcxagent-core/test/utils/faber.js | 51 +- .../src/handlers/proof_presentation/prover.rs | 13 +- .../handlers/proof_presentation/verifier.rs | 30 +- .../prover/state_machine.rs | 16 +- .../verifier/state_machine.rs | 6 +- aries_vcx/tests/test_creds_proofs.rs | 534 +++++++++--------- libvcx/src/api_c/protocols/disclosed_proof.rs | 2 +- libvcx/src/api_c/protocols/proof.rs | 4 +- .../src/api_vcx/api_handle/disclosed_proof.rs | 5 +- libvcx_core/src/api_vcx/api_handle/proof.rs | 35 +- messages/src/status.rs | 1 + wrappers/node/src/api/proof.ts | 38 +- wrappers/vcx-napi-rs/index.d.ts | 6 +- wrappers/vcx-napi-rs/index.js | 8 +- .../vcx-napi-rs/src/api/disclosed_proof.rs | 2 +- wrappers/vcx-napi-rs/src/api/proof.rs | 16 +- 27 files changed, 653 insertions(+), 410 deletions(-) diff --git a/agents/node/vcxagent-core/demo/faber.js b/agents/node/vcxagent-core/demo/faber.js index 0aed280567..bc5720fef4 100644 --- a/agents/node/vcxagent-core/demo/faber.js +++ b/agents/node/vcxagent-core/demo/faber.js @@ -111,22 +111,23 @@ async function runFaber (options) { } logger.info('#27 Process the proof provided by alice.') - const { proofState, proof } = await vcxProof.getProof() - logger.info(`#27 Proof: proofState=${proofState}, proof=${proof}`) - assert(proofState) - assert(proof) + const presentation = vcxProof.getPresentationMsg() + const verificationState = vcxProof.getPresentationVerificationStatus() + logger.info(`#27 Proof: proofState=${verificationState}, proof=${presentation}`) + assert(verificationState) + assert(presentation) logger.info(`Proof protocol state = ${JSON.stringify(proofProtocolState)}`) - logger.info(`Proof verification state =${proofState}`) - logger.debug(`Proof presentation = ${JSON.stringify(proof, null, 2)}`) + logger.info(`Proof verification state =${verificationState}`) + logger.debug(`Proof presentation = ${JSON.stringify(presentation, null, 2)}`) logger.debug(`Serialized Proof state machine ${JSON.stringify(await vcxProof.serialize())}`) - if (proofState === ProofState.Verified) { + if (verificationState === ProofState.Verified) { if (options.revocation) { throw Error('Proof was verified, but was expected to be invalid, because revocation was enabled.') } else { logger.info('Proof was verified.') } - } else if (proofState === ProofState.Invalid) { + } else if (verificationState === ProofState.Invalid) { if (options.revocation) { logger.info('Proof was determined as invalid, which was expected because the used credential was revoked.') } else { @@ -134,7 +135,7 @@ async function runFaber (options) { } await sleepPromise(1000) } else { - logger.error(`Unexpected proof state '${proofState}'.`) + logger.error(`Unexpected proof state '${verificationState}'.`) process.exit(-1) } diff --git a/agents/node/vcxagent-core/src/agent.js b/agents/node/vcxagent-core/src/agent.js index f705339aa3..5962eeb4f4 100644 --- a/agents/node/vcxagent-core/src/agent.js +++ b/agents/node/vcxagent-core/src/agent.js @@ -1,4 +1,7 @@ -const { getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta, defaultLogger } = require('@hyperledger/node-vcx-wrapper') +const { + getLedgerAuthorAgreement, + setActiveTxnAuthorAgreementMeta +} = require('@hyperledger/node-vcx-wrapper') const { createServiceLedgerCredDef } = require('./services/service-ledger-creddef') const { createServiceLedgerSchema } = require('./services/service-ledger-schema') const { createServiceVerifier } = require('./services/service-verifier') @@ -21,7 +24,7 @@ const { const { createStorageService } = require('./storage/storage-service') const { waitUntilAgencyIsReady, getAgencyConfig } = require('./common') -async function createVcxAgent({ agentName, genesisPath, agencyUrl, seed, walletExtraConfigs, endpointInfo, logger }) { +async function createVcxAgent ({ agentName, genesisPath, agencyUrl, seed, walletExtraConfigs, endpointInfo, logger }) { genesisPath = genesisPath || `${__dirname}/../resources/docker.txn` await waitUntilAgencyIsReady(agencyUrl, logger) @@ -35,7 +38,7 @@ async function createVcxAgent({ agentName, genesisPath, agencyUrl, seed, walletE const agentProvision = await storageService.loadAgentProvision() const issuerDid = agentProvision.issuerConfig.institution_did - async function agentInitVcx() { + async function agentInitVcx () { logger.info(`Initializing ${agentName} vcx session.`) logger.silly(`Using following agent provision to initialize VCX settings ${JSON.stringify(agentProvision, null, 2)}`) @@ -49,17 +52,17 @@ async function createVcxAgent({ agentName, genesisPath, agencyUrl, seed, walletE await openMainPool({ genesis_path: genesisPath }) } - async function agentShutdownVcx() { + async function agentShutdownVcx () { logger.debug(`Shutting down ${agentName} vcx session.`) shutdownVcx() } - async function updateWebhookUrl(webhookUrl) { + async function updateWebhookUrl (webhookUrl) { logger.info(`Updating webhook url to ${webhookUrl}`) await vcxUpdateWebhookUrl({ webhookUrl }) } - async function acceptTaa() { + async function acceptTaa () { const taa = await getLedgerAuthorAgreement() const taaJson = JSON.parse(taa) const utime = Math.floor(new Date() / 1000) @@ -68,7 +71,7 @@ async function createVcxAgent({ agentName, genesisPath, agencyUrl, seed, walletE await setActiveTxnAuthorAgreementMeta(taaJson.text, taaJson.version, null, acceptanceMechanism, utime) } - function getInstitutionDid() { + function getInstitutionDid () { return issuerDid } diff --git a/agents/node/vcxagent-core/src/services/service-prover.js b/agents/node/vcxagent-core/src/services/service-prover.js index 412a9c543f..5484227614 100644 --- a/agents/node/vcxagent-core/src/services/service-prover.js +++ b/agents/node/vcxagent-core/src/services/service-prover.js @@ -114,11 +114,6 @@ module.exports.createServiceProver = function createServiceProver ({ logger, loa } } - async function getVcxDisclosedProof (disclosedProofId) { - logger.warn('Usage of getVcxDisclosedProof is not recommended. You should use vcxagent-core API rather than work with vcx object directly.') - return loadDisclosedProof(disclosedProofId) - } - return { generateProof, selectCredentials, diff --git a/agents/node/vcxagent-core/src/services/service-verifier.js b/agents/node/vcxagent-core/src/services/service-verifier.js index 50f7c92f3d..ddf8597aca 100644 --- a/agents/node/vcxagent-core/src/services/service-verifier.js +++ b/agents/node/vcxagent-core/src/services/service-verifier.js @@ -52,10 +52,24 @@ module.exports.createServiceVerifier = function createServiceVerifier ({ logger, return await proof.getState() } - async function getProofState (proofId) { + async function getPresentationMsg (proofId) { const proof = await loadProof(proofId) - const { proofState } = await proof.getProof() - return proofState + return JSON.parse(proof.getPresentationMsg()) + } + + async function getPresentationAttachment (proofId) { + const proof = await loadProof(proofId) + return JSON.parse(proof.getPresentationAttachment()) + } + + async function getPresentationRequestAttachment (proofId) { + const proof = await loadProof(proofId) + return JSON.parse(proof.getPresentationRequestAttachment()) + } + + async function getPresentationVerificationStatus (proofId) { + const proof = await loadProof(proofId) + return JSON.parse(proof.getPresentationVerificationStatus()) } async function listIds () { @@ -84,6 +98,10 @@ module.exports.createServiceVerifier = function createServiceVerifier ({ logger, listIds, printInfo, getState, - getProofState + + getPresentationMsg, + getPresentationAttachment, + getPresentationRequestAttachment, + getPresentationVerificationStatus } } diff --git a/agents/node/vcxagent-core/test/distribute-tails.spec.js b/agents/node/vcxagent-core/test/distribute-tails.spec.js index 78c2a71d5f..d2aa796da3 100644 --- a/agents/node/vcxagent-core/test/distribute-tails.spec.js +++ b/agents/node/vcxagent-core/test/distribute-tails.spec.js @@ -9,6 +9,8 @@ const uuid = require('uuid') const sleep = require('sleep-promise') const fs = require('fs') const mkdirp = require('mkdirp') +const path = require('path') +const { proofRequestDataStandard } = require('./utils/data') beforeAll(async () => { jest.setTimeout(1000 * 60 * 4) @@ -24,7 +26,7 @@ describe('test tails distribution', () => { const port = 5468 const tailsUrlId = uuid.v4() const tailsUrl = `http://127.0.0.1:${port}/${tailsUrlId}` - await faber.buildLedgerPrimitives(buildRevocationDetails({ supportRevocation: true, tailsDir: `${__dirname}/tmp/faber/tails`, maxCreds: 5, tailsUrl })) + await faber.buildLedgerPrimitives(buildRevocationDetails({ supportRevocation: true, tailsDir: path.join(__dirname, '/tmp/faber/tails'), maxCreds: 5, tailsUrl })) await faber.sendCredentialOffer() await alice.acceptCredentialOffer() await faber.updateStateCredential(IssuerStateType.RequestReceived) @@ -33,20 +35,20 @@ describe('test tails distribution', () => { const faberTailsHash = await faber.getTailsHash() const app = express() - app.use(`/${tailsUrlId}`, express.static(`${__dirname}/tmp/faber/tails/${faberTailsHash}`)) + app.use(`/${tailsUrlId}`, express.static(path.join(__dirname, `/tmp/faber/tails/${faberTailsHash}`))) server = app.listen(port) const aliceTailsLocation = await alice.getTailsLocation() const aliceTailsHash = await alice.getTailsHash() - const aliceTailsFileDir = `${__dirname}/tmp/alice/tails` + const aliceTailsFileDir = path.join(__dirname, '/tmp/alice/tails') const aliceTailsFilePath = aliceTailsFileDir + `/${aliceTailsHash}` await mkdirp(aliceTailsFileDir) axios.default.get(`${aliceTailsLocation}`, { responseType: 'stream' }).then(res => { res.data.pipe(fs.createWriteStream(aliceTailsFilePath)) }) - - const request = await faber.requestProofFromAlice() - await alice.sendHolderProof(JSON.parse(request), revRegId => aliceTailsFileDir) + const issuerDid = faber.getFaberDid() + const request = await faber.requestProofFromAlice(proofRequestDataStandard(issuerDid)) + await alice.sendHolderProof(JSON.parse(request), revRegId => aliceTailsFileDir, { attribute_3: 'Smith' }) await faber.updateStateVerifierProof(VerifierStateType.Finished) await alice.updateStateHolderProof(ProverStateType.Finished) } catch (err) { diff --git a/agents/node/vcxagent-core/test/issue-verify.spec.js b/agents/node/vcxagent-core/test/issue-verify.spec.js index d636aa70b4..ca48ecf1fa 100644 --- a/agents/node/vcxagent-core/test/issue-verify.spec.js +++ b/agents/node/vcxagent-core/test/issue-verify.spec.js @@ -1,36 +1,142 @@ /* eslint-env jest */ require('jest') const { createPairedAliceAndFaber } = require('./utils/utils') -const { IssuerStateType, HolderStateType, ProverStateType, VerifierStateType } = require('@hyperledger/node-vcx-wrapper') +const { IssuerStateType, HolderStateType, ProverStateType, VerifierStateType, ProofState } = require('@hyperledger/node-vcx-wrapper') const sleep = require('sleep-promise') const { initRustLogger } = require('../src') +const { proofRequestDataStandard, proofRequestDataSelfAttest } = require('./utils/data') +const path = require('path') beforeAll(async () => { jest.setTimeout(1000 * 60 * 4) initRustLogger(process.env.RUST_LOG || 'vcx=error') }) +afterAll(async () => { + await sleep(500) +}) + describe('test update state', () => { - it('Faber should send credential to Alice', async () => { - try { - const { alice, faber } = await createPairedAliceAndFaber() - const tailsDir = `${__dirname}/tmp/faber/tails` - await faber.buildLedgerPrimitives({ tailsDir, maxCreds: 5 }) - await faber.rotateRevReg(tailsDir, 5) - await faber.sendCredentialOffer() - await alice.acceptCredentialOffer() + it('Faber should issue credential, verify proof', async () => { + const { alice, faber } = await createPairedAliceAndFaber() + const issuerDid = faber.getFaberDid() + const tailsDir = path.join(__dirname, '/tmp/faber/tails') + await faber.buildLedgerPrimitives({ tailsDir, maxCreds: 5 }) + await faber.rotateRevReg(tailsDir, 5) + await faber.sendCredentialOffer() + await alice.acceptCredentialOffer() - await faber.updateStateCredential(IssuerStateType.RequestReceived) - await faber.sendCredential() - await alice.updateStateCredential(HolderStateType.Finished) - await faber.receiveCredentialAck() + await faber.updateStateCredential(IssuerStateType.RequestReceived) + await faber.sendCredential() + await alice.updateStateCredential(HolderStateType.Finished) + await faber.receiveCredentialAck() - const request = await faber.requestProofFromAlice() - await alice.sendHolderProof(JSON.parse(request), revRegId => tailsDir) + const request = await faber.requestProofFromAlice(proofRequestDataStandard(issuerDid)) + await alice.sendHolderProof(JSON.parse(request), revRegId => tailsDir, { attribute_3: 'Smith' }) + await faber.updateStateVerifierProof(VerifierStateType.Finished) + await alice.updateStateHolderProof(ProverStateType.Finished) + const { presentationVerificationState, presentationAttachment, presentationRequestAttachment } = await faber.getPresentationInfo() + expect(presentationVerificationState).toBe(ProofState.Verified) + expect(presentationRequestAttachment.requested_attributes).toStrictEqual({ + attribute_0: { + names: [ + 'name', + 'last_name', + 'sex' + ], + restrictions: [ + { + issuer_did: 'V4SGRU86Z58d6TV7PBUe6f' + } + ] + }, + attribute_1: { + name: 'date', + restrictions: { + issuer_did: 'V4SGRU86Z58d6TV7PBUe6f' + } + }, + attribute_2: { + name: 'degree', + restrictions: { + 'attr::degree::value': 'maths' + } + }, + attribute_3: { + name: 'nickname', + self_attest_allowed: true + } + }) + expect(presentationAttachment.requested_proof).toStrictEqual({ + revealed_attrs: { + attribute_1: { + sub_proof_index: 0, + raw: '05-2018', + encoded: '101085817956371643310471822530712840836446570298192279302750234554843339322886' + }, + attribute_2: { + sub_proof_index: 0, + raw: 'maths', + encoded: '78137204873448776862705240258723141940757006710839733585634143215803847410018' + } + }, + revealed_attr_groups: { + attribute_0: { + sub_proof_index: 0, + values: { + sex: { + raw: 'female', + encoded: '71957174156108022857985543806816820198680233386048843176560473245156249119752' + }, + name: { + raw: 'alice', + encoded: '19831138297880367962895005496563562590284654704047651305948751287370224856720' + }, + last_name: { + raw: 'clark', + encoded: '51192516729287562420368242940555165528396706187345387515033121164720912081028' + } + } + } + }, + self_attested_attrs: { + attribute_3: 'Smith' + }, + unrevealed_attrs: {}, + predicates: { + predicate_0: { + sub_proof_index: 0 + } + } + }) + }) + + it('Faber should verify proof with self attestation', async () => { + try { + const { alice, faber } = await createPairedAliceAndFaber() + const request = await faber.requestProofFromAlice(proofRequestDataSelfAttest()) + await alice.sendHolderProofSelfAttested(JSON.parse(request), { attribute_0: 'Smith' }) await faber.updateStateVerifierProof(VerifierStateType.Finished) await alice.updateStateHolderProof(ProverStateType.Finished) + const { presentationVerificationState, presentationAttachment, presentationRequestAttachment } = await faber.getPresentationInfo() + expect(presentationVerificationState).toBe(ProofState.Verified) + expect(presentationAttachment.requested_proof).toStrictEqual({ + revealed_attrs: {}, + self_attested_attrs: { + attribute_0: 'Smith' + }, + unrevealed_attrs: {}, + predicates: {} + }) + expect(presentationRequestAttachment.requested_attributes).toStrictEqual({ + attribute_0: { + name: 'nickname', + self_attest_allowed: true + } + }) + await sleep(500) } catch (err) { - await sleep(2000) + await sleep(500) console.error(`err = ${err.message} stack = ${err.stack}`) throw Error(err) } diff --git a/agents/node/vcxagent-core/test/nonmediated-connection.spec.js b/agents/node/vcxagent-core/test/nonmediated-connection.spec.js index 866d78f689..14d48b0ec1 100644 --- a/agents/node/vcxagent-core/test/nonmediated-connection.spec.js +++ b/agents/node/vcxagent-core/test/nonmediated-connection.spec.js @@ -14,7 +14,7 @@ beforeAll(async () => { describe('test establishing and exchanging messages via nonmediated connections', () => { it('Establish nonmediated connection via public endpoint using public invite, exchange messages', async () => { - let faberServer + let faberServer, aliceServer try { const path = '/msg' const faberPort = 5400 @@ -65,7 +65,6 @@ describe('test establishing and exchanging messages via nonmediated connections' await faber.nonmediatedConnectionSendMessage('Hello Alice') const { message: msgAlice } = await alice.unpackMsg(aliceEncryptedMsg) expect(JSON.parse(msgAlice).content).toBe('Hello Alice') - } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) throw Error(err) @@ -81,7 +80,7 @@ describe('test establishing and exchanging messages via nonmediated connections' }) it('Establish nonmediated connection via public endpoint using pairwise invite, exchange messages', async () => { - let faberServer + let faberServer, aliceServer try { const path = '/msg' const faberPort = 5402 @@ -129,7 +128,6 @@ describe('test establishing and exchanging messages via nonmediated connections' await faber.nonmediatedConnectionSendMessage('Hello Alice') const { message: msgAlice } = await alice.unpackMsg(aliceEncryptedMsg) expect(JSON.parse(msgAlice).content).toBe('Hello Alice') - } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) throw Error(err) @@ -145,7 +143,7 @@ describe('test establishing and exchanging messages via nonmediated connections' }) it('Establish nonmediated connection via public endpoint using OOB invite, exchange messages', async () => { - let faberServer + let faberServer, aliceServer try { const path = '/msg' const faberPort = 5404 @@ -194,7 +192,6 @@ describe('test establishing and exchanging messages via nonmediated connections' await faber.nonmediatedConnectionSendMessage('Hello Alice') const { message: msgAlice } = await alice.unpackMsg(aliceEncryptedMsg) expect(JSON.parse(msgAlice).content).toBe('Hello Alice') - } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) throw Error(err) @@ -252,7 +249,6 @@ describe('test establishing and exchanging messages via nonmediated connections' expect(payloadAlice['@id']).toBeDefined() expect(payloadAlice['@type']).toBeDefined() expect(payloadAlice.content).toBe('Hello Alice') - } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) throw Error(err) diff --git a/agents/node/vcxagent-core/test/nonmediated-endpoint.spec.js b/agents/node/vcxagent-core/test/nonmediated-endpoint.spec.js index fc44ae184e..c82d771979 100644 --- a/agents/node/vcxagent-core/test/nonmediated-endpoint.spec.js +++ b/agents/node/vcxagent-core/test/nonmediated-endpoint.spec.js @@ -60,7 +60,6 @@ describe('test connecting via unmediated endpoint', () => { expect(payloadAlice['@id']).toBeDefined() expect(payloadAlice['@type']).toBeDefined() expect(payloadAlice.content).toBe('Hello Alice') - } catch (err) { console.error(`err = ${err.message} stack = ${err.stack}`) await sleep(2000) diff --git a/agents/node/vcxagent-core/test/out-of-band.spec.js b/agents/node/vcxagent-core/test/out-of-band.spec.js index 2d6191741d..251ae93eb3 100644 --- a/agents/node/vcxagent-core/test/out-of-band.spec.js +++ b/agents/node/vcxagent-core/test/out-of-band.spec.js @@ -6,6 +6,8 @@ const { VerifierStateType } = require('@hyperledger/node-vcx-wrapper') const { createPairedAliceAndFaberViaOobMsg, createAliceAndFaber, connectViaOobMessage, createPairedAliceAndFaber } = require('./utils/utils') const { IssuerStateType, HolderStateType, OutOfBandReceiver } = require('@hyperledger/node-vcx-wrapper') const { initRustLogger } = require('../src') +const { proofRequestDataStandard } = require('./utils/data') +const path = require('path') beforeAll(async () => { jest.setTimeout(1000 * 60 * 4) @@ -51,7 +53,7 @@ describe('test out of band communication', () => { it('Faber issues credential via OOB', async () => { try { const { alice, faber } = await createAliceAndFaber() - const tailsDir = `${__dirname}/tmp/faber/tails` + const tailsDir = path.join(__dirname, '/tmp/faber/tails') await faber.buildLedgerPrimitives({ tailsDir, maxCreds: 5 }) const oobCredOfferMsg = await faber.createOobCredOffer() @@ -70,7 +72,7 @@ describe('test out of band communication', () => { it('Faber requests proof via OOB', async () => { try { const { alice, faber } = await createPairedAliceAndFaber() - const tailsDir = `${__dirname}/tmp/faber/tails` + const tailsDir = path.join(__dirname, '/tmp/faber/tails') await faber.buildLedgerPrimitives({ tailsDir, maxCreds: 5 }) await faber.sendCredentialOffer() await alice.acceptCredentialOffer() @@ -78,11 +80,12 @@ describe('test out of band communication', () => { await faber.sendCredential() await alice.updateStateCredential(HolderStateType.Finished) - const oobPresentationRequestMsg = await faber.createOobProofRequest() + const issuerDid = faber.getFaberDid() + const oobPresentationRequestMsg = await faber.createOobProofRequest(proofRequestDataStandard(issuerDid)) const oobReceiver = await OutOfBandReceiver.createWithMessage(oobPresentationRequestMsg) - const presentationRequest = await oobReceiver.extractMessage() - await alice.sendHolderProof(presentationRequest, revRegId => tailsDir) + const presentationRequest = oobReceiver.extractMessage() + await alice.sendHolderProof(presentationRequest, revRegId => tailsDir, { attribute_3: 'Smith' }) await faber.updateStateVerifierProof(VerifierStateType.Finished) } catch (e) { console.error(e.stack) diff --git a/agents/node/vcxagent-core/test/utils/alice.js b/agents/node/vcxagent-core/test/utils/alice.js index 8a1126b897..b404307b58 100644 --- a/agents/node/vcxagent-core/test/utils/alice.js +++ b/agents/node/vcxagent-core/test/utils/alice.js @@ -100,7 +100,7 @@ module.exports.createAlice = async function createAlice (serviceEndpoint = 'http } async function handleMessage (ariesMsg) { - logger.info(`Alice is going to try handle incoming messages`) + logger.info('Alice is going to try handle incoming messages') await vcxAgent.agentInitVcx() await vcxAgent.serviceConnections.handleMessage(connectionId, ariesMsg) @@ -122,7 +122,7 @@ module.exports.createAlice = async function createAlice (serviceEndpoint = 'http logger.info('acceptOobCredentialOffer >>> Alice going to accept oob cred offer.') const oobReceiver = await OutOfBandReceiver.createWithMessage(oobCredOfferMsg) - const credOffer = await oobReceiver.extractMessage() + const credOffer = oobReceiver.extractMessage() logger.info('acceptOobCredentialOffer >>> Extracted attached message') logger.debug(`acceptOobCredentialOffer >>> attached message: ${credOffer}`) await vcxAgent.serviceCredHolder.createCredentialFromOfferAndSendRequest(connectionId, holderCredentialId, credOffer) @@ -132,19 +132,27 @@ module.exports.createAlice = async function createAlice (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function sendHolderProof (proofRequest, _mapRevRegId) { + async function sendHolderProof (proofRequest, _mapRevRegId, selfAttestedAttrs) { await vcxAgent.agentInitVcx() const mapRevRegId = _mapRevRegId || ((_revRegId) => { throw Error('Tails file should not be needed') }) await vcxAgent.serviceProver.buildDisclosedProof(disclosedProofId, proofRequest) 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(ProverStateType.PresentationSent) await vcxAgent.agentShutdownVcx() } + async function sendHolderProofSelfAttested (proofRequest, selfAttestedAttrs) { + await vcxAgent.agentInitVcx() + await vcxAgent.serviceProver.buildDisclosedProof(disclosedProofId, proofRequest) + await vcxAgent.serviceProver.generateProof(disclosedProofId, { }, selfAttestedAttrs) + expect(await vcxAgent.serviceProver.sendDisclosedProof(disclosedProofId, connectionId)).toBe(ProverStateType.PresentationSent) + + await vcxAgent.agentShutdownVcx() + } + async function updateStateHolderProof (expectedNextState) { logger.info(`Holder updating state of disclosed proof, expecting it to be in state ${expectedNextState}`) await vcxAgent.agentInitVcx() @@ -273,6 +281,7 @@ module.exports.createAlice = async function createAlice (serviceEndpoint = 'http acceptCredentialOffer, updateStateCredential, sendHolderProof, + sendHolderProofSelfAttested, updateStateHolderProof, getTailsLocation, getTailsHash, diff --git a/agents/node/vcxagent-core/test/utils/data.js b/agents/node/vcxagent-core/test/utils/data.js index 3067cb7956..98bf466fc6 100644 --- a/agents/node/vcxagent-core/test/utils/data.js +++ b/agents/node/vcxagent-core/test/utils/data.js @@ -2,13 +2,13 @@ function getFaberCredDefName () { return 'DemoCredential123' } -function getFaberProofDataWithNonRevocation (issuerDid, proofName) { - const proofData = getFaberProofData(issuerDid, proofName) +function getFaberProofDataWithNonRevocation (issuerDid) { + const proofData = proofRequestDataStandard(issuerDid) proofData.revocationInterval = { to: Date.now() } return proofData } -function getFaberProofData (issuerDid, proofName) { +function proofRequestDataStandard (issuerDid) { const proofAttributes = [ { names: ['name', 'last_name', 'sex'], @@ -36,7 +36,23 @@ function getFaberProofData (issuerDid, proofName) { sourceId: '213', attrs: proofAttributes, preds: proofPredicates, - name: proofName, + name: 'proof-test-standard', + revocationInterval: { to: null, from: null } + } +} + +function proofRequestDataSelfAttest () { + const proofAttributes = [ + { + name: 'nickname', + self_attest_allowed: true + } + ] + + return { + sourceId: '213', + attrs: proofAttributes, + name: 'proof-test-self-attesting', revocationInterval: { to: null, from: null } } } @@ -51,7 +67,11 @@ function getAliceSchemaAttrs () { age: '25' } } -module.exports.getAliceSchemaAttrs = getAliceSchemaAttrs -module.exports.getFaberCredDefName = getFaberCredDefName -module.exports.getFaberProofData = getFaberProofData -module.exports.getFaberProofDataWithNonRevocation = getFaberProofDataWithNonRevocation + +module.exports = { + getAliceSchemaAttrs, + getFaberCredDefName, + proofRequestDataStandard, + getFaberProofDataWithNonRevocation, + proofRequestDataSelfAttest +} diff --git a/agents/node/vcxagent-core/test/utils/faber.js b/agents/node/vcxagent-core/test/utils/faber.js index f839d8d7c1..f2710929ca 100644 --- a/agents/node/vcxagent-core/test/utils/faber.js +++ b/agents/node/vcxagent-core/test/utils/faber.js @@ -1,9 +1,10 @@ /* eslint-env jest */ const { createVcxAgent, getSampleSchemaData } = require('../../src') -const { ConnectionStateType, IssuerStateType, VerifierStateType, generatePublicInvite, +const { + ConnectionStateType, IssuerStateType, VerifierStateType, generatePublicInvite, createPwInfo, createService, getServiceFromLedger, unpack } = require('@hyperledger/node-vcx-wrapper') -const { getAliceSchemaAttrs, getFaberCredDefName, getFaberProofData } = require('./data') +const { getAliceSchemaAttrs, getFaberCredDefName } = require('./data') const sleep = require('sleep-promise') const assert = require('assert') @@ -65,8 +66,8 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http logger.info('Faber is going to write nonmediated service on the ledger') await vcxAgent.agentInitVcx() - logger.info(`Faber creating pairwise info`) - const pwInfo = await createPwInfo(); + logger.info('Faber creating pairwise info') + const pwInfo = await createPwInfo() logger.info(`Faber creating service for endpoint ${endpoint} and recipient key ${pwInfo.pw_vk}`) await createService(institutionDid, endpoint, [pwInfo.pw_vk], []) @@ -119,11 +120,14 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http return await createOobMessageWithDid(credOfferMsg) } - async function createOobProofRequest () { + function getFaberDid () { + return vcxAgent.getInstitutionDid() + } + + async function createOobProofRequest (proofData) { await vcxAgent.agentInitVcx() - const issuerDid = vcxAgent.getInstitutionDid() - const proofData = getFaberProofData(issuerDid, proofId) + // todo: address logger.info(`Faber is sending proof request to connection ${connectionId}`) const presentationRequestMsg = await vcxAgent.serviceVerifier.buildProofReqAndMarkAsSent(proofId, proofData) @@ -150,7 +154,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http } async function handleMessage (ariesMsg) { - logger.info(`Faber is going to try handle incoming messages`) + logger.info('Faber is going to try handle incoming messages') await vcxAgent.agentInitVcx() await vcxAgent.serviceConnections.handleMessage(connectionId, ariesMsg) @@ -185,7 +189,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http async function rotateRevReg (tailsDir, maxCreds) { await vcxAgent.agentInitVcx() - logger.info('Faber rotating revocation registry'); + logger.info('Faber rotating revocation registry') const credDefLedgerId = await vcxAgent.serviceLedgerCredDef.getCredDefId(credDefId); ({ revRegId } = await vcxAgent.serviceLedgerRevReg.createRevocationRegistry(institutionDid, credDefLedgerId, revRegTagNo + 1, tailsDir, maxCreds)) revRegTagNo += 1 @@ -232,11 +236,9 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } - async function requestProofFromAlice () { + async function requestProofFromAlice (proofData) { logger.info('Faber going to request proof from Alice') await vcxAgent.agentInitVcx() - const issuerDid = vcxAgent.getInstitutionDid() - const proofData = getFaberProofData(issuerDid, proofId) logger.info(`Faber is creating proof ${proofId}`) await vcxAgent.serviceVerifier.createProof(proofId, proofData) logger.info(`Faber is sending proof request to connection ${connectionId}`) @@ -274,7 +276,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http } async function createNonmediatedConnectionWithInvite () { - logger.info(`Faber is going to create a connection with invite`) + logger.info('Faber is going to create a connection with invite') await vcxAgent.agentInitVcx() const invite = await vcxAgent.serviceNonmediatedConnections.inviterConnectionCreatePwInvite(connectionId) @@ -285,7 +287,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http } async function nonmediatedConnectionProcessRequest (request) { - logger.info(`Faber is going to process a connection request`) + logger.info('Faber is going to process a connection request') await vcxAgent.agentInitVcx() expect(await vcxAgent.serviceNonmediatedConnections.getState(connectionId)).toBe(ConnectionStateType.Invited) @@ -388,6 +390,23 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http await vcxAgent.agentShutdownVcx() } + async function getPresentationInfo () { + logger.info('Faber is gather info about received presentation') + await vcxAgent.agentInitVcx() + const presentationMsg = await vcxAgent.serviceVerifier.getPresentationMsg(proofId) + const presentationVerificationState = await vcxAgent.serviceVerifier.getPresentationVerificationStatus(proofId) + const presentationAttachment = await vcxAgent.serviceVerifier.getPresentationAttachment(proofId) + const presentationRequestAttachment = await vcxAgent.serviceVerifier.getPresentationRequestAttachment(proofId) + + await vcxAgent.agentShutdownVcx() + return { + presentationMsg, + presentationVerificationState, + presentationAttachment, + presentationRequestAttachment + } + } + return { buildLedgerPrimitives, rotateRevReg, @@ -407,6 +426,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http createConnectionFromReceivedRequestV2, updateConnection, handleMessage, + getPresentationInfo, sendConnectionResponse, sendCredentialOffer, createOobCredOffer, @@ -422,6 +442,7 @@ module.exports.createFaber = async function createFaber (serviceEndpoint = 'http updateAllReceivedMessages, publishService, readServiceFromLedger, - unpackMsg + unpackMsg, + getFaberDid } } diff --git a/aries_vcx/src/handlers/proof_presentation/prover.rs b/aries_vcx/src/handlers/proof_presentation/prover.rs index 5da0372db1..997f920c40 100644 --- a/aries_vcx/src/handlers/proof_presentation/prover.rs +++ b/aries_vcx/src/handlers/proof_presentation/prover.rs @@ -45,8 +45,7 @@ impl Prover { } pub fn presentation_status(&self) -> u32 { - trace!("Prover::presentation_state >>>"); - self.prover_sm.presentation_status() + self.prover_sm.get_presentation_status() } pub async fn retrieve_credentials(&self, profile: &Arc) -> VcxResult { @@ -77,10 +76,8 @@ impl Prover { Ok(()) } - pub fn generate_presentation_msg(&self) -> VcxResult { - trace!("Prover::generate_presentation_msg >>>"); - let proof = self.prover_sm.presentation()?.to_owned(); - Ok(json!(proof).to_string()) + pub fn get_presentation_msg(&self) -> VcxResult { + Ok(self.prover_sm.get_presentation_msg()?.to_owned()) } pub fn set_presentation(&mut self, presentation: Presentation) -> VcxResult<()> { @@ -135,7 +132,7 @@ impl Prover { pub fn presentation_request_data(&self) -> VcxResult { self.prover_sm - .presentation_request()? + .get_presentation_request()? .request_presentations_attach .content() .map_err(|err| err.into()) @@ -144,7 +141,7 @@ impl Prover { pub fn get_proof_request_attachment(&self) -> VcxResult { let data = self .prover_sm - .presentation_request()? + .get_presentation_request()? .request_presentations_attach .content()?; let proof_request_data: serde_json::Value = serde_json::from_str(&data).map_err(|err| { diff --git a/aries_vcx/src/handlers/proof_presentation/verifier.rs b/aries_vcx/src/handlers/proof_presentation/verifier.rs index cbdc736a4e..2747444e52 100644 --- a/aries_vcx/src/handlers/proof_presentation/verifier.rs +++ b/aries_vcx/src/handlers/proof_presentation/verifier.rs @@ -72,7 +72,7 @@ impl Verifier { pub async fn send_presentation_request(&mut self, send_message: SendClosure) -> VcxResult<()> { if self.verifier_sm.get_state() == VerifierState::PresentationRequestSet { - let offer = self.verifier_sm.presentation_request()?.to_a2a_message(); + let offer = self.verifier_sm.presentation_request_msg()?.to_a2a_message(); send_message(offer).await?; self.verifier_sm = self.verifier_sm.clone().mark_presentation_request_msg_sent()?; } @@ -85,6 +85,7 @@ impl Verifier { Ok(()) } + // todo: verification and sending ack should be separate apis pub async fn verify_presentation( &mut self, profile: &Arc, @@ -123,36 +124,39 @@ impl Verifier { Ok(()) } - pub fn get_presentation_request_msg(&self) -> VcxResult { - let msg = self.verifier_sm.presentation_request()?.to_a2a_message(); - Ok(json!(msg).to_string()) + pub fn get_presentation_request_msg(&self) -> VcxResult { + self.verifier_sm.presentation_request_msg() + } + + pub fn get_presentation_request_attachment(&self) -> VcxResult { + self.verifier_sm + .presentation_request_msg()? + .request_presentations_attach + .content() + .map_err(|err| err.into()) } pub fn get_presentation_request(&self) -> VcxResult { - self.verifier_sm.presentation_request() + self.verifier_sm.presentation_request_msg() } - pub fn get_presentation_msg(&self) -> VcxResult { - trace!("Verifier::get_presentation >>>"); - let msg = self.verifier_sm.presentation()?.to_a2a_message(); - Ok(json!(msg).to_string()) + pub fn get_presentation_msg(&self) -> VcxResult { + self.verifier_sm.get_presentation_msg() } pub fn get_presentation_status(&self) -> Status { - trace!("Verifier::presentation_state >>>"); self.verifier_sm.presentation_status() } pub fn get_presentation_attachment(&self) -> VcxResult { self.verifier_sm - .presentation()? + .get_presentation_msg()? .presentations_attach .content() .map_err(|err| err.into()) } pub fn get_presentation_proposal(&self) -> VcxResult { - trace!("Verifier::get_presentation_proposal >>>"); self.verifier_sm.presentation_proposal() } @@ -271,7 +275,7 @@ mod unit_tests { let mut verifier = _verifier().await; verifier.to_finished_state().await; let presentation = verifier.get_presentation_msg().unwrap(); - assert_eq!(presentation, json!(_presentation().to_a2a_message()).to_string()); + assert_eq!(presentation, _presentation()); assert_eq!(verifier.get_state(), VerifierState::Finished); } } diff --git a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs index 30d54bbf66..be83dbf2e2 100644 --- a/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/prover/state_machine.rs @@ -475,14 +475,14 @@ impl ProverSM { } } - pub fn presentation_status(&self) -> u32 { + pub fn get_presentation_status(&self) -> u32 { match self.state { ProverFullState::Finished(ref state) => state.status.code(), _ => Status::Undefined.code(), } } - pub fn presentation_request(&self) -> VcxResult<&PresentationRequest> { + pub fn get_presentation_request(&self) -> VcxResult<&PresentationRequest> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, @@ -502,7 +502,7 @@ impl ProverSM { } } - pub fn presentation(&self) -> VcxResult<&Presentation> { + pub fn get_presentation_msg(&self) -> VcxResult<&Presentation> { match self.state { ProverFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, @@ -524,7 +524,7 @@ impl ProverSM { ProverFullState::PresentationSent(ref state) => Ok(&state.presentation), ProverFullState::Finished(ref state) => Ok(state.presentation.as_ref().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::NotReady, - "Presentation is not available", + "Presentation is not available in Finished state", ))?), } } @@ -781,7 +781,7 @@ pub mod unit_tests { assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!( Status::Declined(ProblemReport::default()).code(), - prover_sm.presentation_status() + prover_sm.get_presentation_status() ); } @@ -1013,7 +1013,7 @@ pub mod unit_tests { assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!( Status::Failed(ProblemReport::default()).code(), - prover_sm.presentation_status() + prover_sm.get_presentation_status() ); } @@ -1082,7 +1082,7 @@ pub mod unit_tests { .unwrap(); assert_match!(ProverFullState::Finished(_), prover_sm.state); - assert_eq!(Status::Success.code(), prover_sm.presentation_status()); + assert_eq!(Status::Success.code(), prover_sm.get_presentation_status()); } #[tokio::test] @@ -1132,7 +1132,7 @@ pub mod unit_tests { assert_match!(ProverFullState::Finished(_), prover_sm.state); assert_eq!( Status::Failed(ProblemReport::create()).code(), - prover_sm.presentation_status() + prover_sm.get_presentation_status() ); } diff --git a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs index b905e28845..c20a7e01df 100644 --- a/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs +++ b/aries_vcx/src/protocols/proof_presentation/verifier/state_machine.rs @@ -438,7 +438,7 @@ impl VerifierSM { } } - pub fn presentation_request(&self) -> VcxResult { + pub fn presentation_request_msg(&self) -> VcxResult { match self.state { VerifierFullState::Initial(_) => Err(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, @@ -460,7 +460,7 @@ impl VerifierSM { } } - pub fn presentation(&self) -> VcxResult { + pub fn get_presentation_msg(&self) -> VcxResult { match self.state { VerifierFullState::Finished(ref state) => state.presentation.clone().ok_or(AriesVcxError::from_msg( AriesVcxErrorKind::InvalidState, @@ -668,7 +668,7 @@ pub mod unit_tests { assert_match!(VerifierFullState::PresentationRequestSet(_), verifier_sm.state); - let msg_presentation_request = verifier_sm.presentation_request().unwrap(); + let msg_presentation_request = verifier_sm.presentation_request_msg().unwrap(); let out_time = msg_presentation_request.timing.unwrap().out_time.unwrap(); assert!(was_in_past(&out_time, chrono::Duration::milliseconds(100)).unwrap()); } diff --git a/aries_vcx/tests/test_creds_proofs.rs b/aries_vcx/tests/test_creds_proofs.rs index 25d414c699..23e6df5afa 100644 --- a/aries_vcx/tests/test_creds_proofs.rs +++ b/aries_vcx/tests/test_creds_proofs.rs @@ -14,11 +14,16 @@ mod integration_tests { create_and_store_credential, create_and_store_nonrevocable_credential, create_and_store_nonrevocable_credential_def, create_indy_proof, }; + use aries_vcx::errors::error::VcxResult; use aries_vcx::handlers::proof_presentation::prover::Prover; + use aries_vcx::handlers::proof_presentation::verifier::Verifier; use aries_vcx::messages::protocols::proof_presentation::presentation_request::PresentationRequest; use aries_vcx::utils::constants::{DEFAULT_SCHEMA_ATTRS, TAILS_DIR}; use aries_vcx::utils::devsetup::{init_holder_setup_in_indy_context, SetupProfile}; use aries_vcx::utils::get_temp_dir_path; + use messages::a2a::A2AMessage; + use messages::protocols::proof_presentation::presentation_request; + use messages::status::Status; #[tokio::test] async fn test_retrieve_credentials() { @@ -234,49 +239,6 @@ mod integration_tests { .await; } - #[tokio::test] - async fn test_generate_self_attested_proof() { - // todo - use SetupProfile::run after modular impls - SetupProfile::run_indy(|setup| async move { - let indy_proof_req = json!({ - "nonce":"123432421212", - "name":"proof_req_1", - "version":"0.1", - "requested_attributes": json!({ - "address1_1": json!({ - "name":"address1", - }), - "zip_2": json!({ - "name":"zip", - }), - }), - "requested_predicates": json!({}), - }) - .to_string(); - - let pres_req_data: PresentationRequestData = serde_json::from_str(&indy_proof_req).unwrap(); - let proof_req = PresentationRequest::create() - .set_request_presentations_attach(&json!(pres_req_data).to_string()) - .unwrap(); - let mut proof: Prover = Prover::create_from_request("1", proof_req).unwrap(); - - let selected_credentials: serde_json::Value = json!({}); - let self_attested: serde_json::Value = json!({ - "address1_1":"attested_address", - "zip_2": "attested_zip" - }); - let generated_proof = proof - .generate_presentation( - &setup.profile, - selected_credentials.to_string(), - self_attested.to_string(), - ) - .await; - assert!(generated_proof.is_ok()); - }) - .await; - } - #[tokio::test] async fn test_generate_proof_with_predicates() { // todo - use SetupProfile::run after modular impls @@ -349,14 +311,72 @@ mod integration_tests { }) .await; } + + #[tokio::test] + async fn test_generate_self_attested_proof() { + // todo - use SetupProfile::run after modular impls + SetupProfile::run_indy(|setup| async move { + let indy_proof_req = json!({ + "nonce":"123432421212", + "name":"proof_req_1", + "version":"0.1", + "requested_attributes": json!({ + "address1_1": json!({ + "name":"address1", + }), + "zip_2": json!({ + "name":"zip", + }), + }), + "requested_predicates": json!({}), + }) + .to_string(); + let pres_req_data: PresentationRequestData = serde_json::from_str(&indy_proof_req).unwrap(); + let mut verifier = Verifier::create_from_request("foo".into(), &pres_req_data).unwrap(); + let presentation_request = verifier.get_presentation_request_msg().unwrap(); + verifier.mark_presentation_request_msg_sent().unwrap(); + + // prover receives request and generates presentation + let mut proof: Prover = Prover::create_from_request("1", presentation_request).unwrap(); + + let selected_credentials: serde_json::Value = json!({}); + let self_attested: serde_json::Value = json!({ + "address1_1":"attested_address", + "zip_2": "attested_zip" + }); + proof + .generate_presentation( + &setup.profile, + selected_credentials.to_string(), + self_attested.to_string(), + ) + .await + .unwrap(); + let presentation = proof.get_presentation_msg().unwrap(); + + // verifier receives the presentation + verifier + .verify_presentation( + &setup.profile, + presentation, + Box::new(|_: A2AMessage| Box::pin(async { Ok(()) })), + ) + .await + .unwrap(); + + let status = verifier.get_presentation_status(); + assert_eq!(status, Status::Success); + }) + .await; + } } #[cfg(test)] #[cfg(feature = "agency_pool_tests")] mod tests { - use aries_vcx::common::test_utils::create_and_store_nonrevocable_credential_def; use serde_json::Value; + use aries_vcx::common::test_utils::create_and_store_nonrevocable_credential_def; use aries_vcx::handlers::issuance::holder::Holder; use aries_vcx::handlers::proof_presentation::prover::Prover; use aries_vcx::handlers::proof_presentation::verifier::Verifier; @@ -548,85 +568,85 @@ mod tests { #[tokio::test] async fn test_double_issuance_separate_issuer_and_consumers() { SetupPool::run(|setup| async move { - let mut issuer = Faber::setup(setup.pool_handle).await; - let mut verifier = Faber::setup(setup.pool_handle).await; - let mut consumer1 = create_test_alice_instance(&setup).await; - let mut consumer2 = create_test_alice_instance(&setup).await; - - let (consumer1_to_verifier, verifier_to_consumer1) = - create_connected_connections(&mut consumer1, &mut verifier).await; - let (consumer1_to_issuer, issuer_to_consumer1) = - create_connected_connections(&mut consumer1, &mut issuer).await; - let (consumer2_to_verifier, verifier_to_consumer2) = - create_connected_connections(&mut consumer2, &mut verifier).await; - let (consumer2_to_issuer, issuer_to_consumer2) = - create_connected_connections(&mut consumer2, &mut issuer).await; - - let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = - _create_address_schema(&issuer.profile, &issuer.config_issuer.institution_did).await; - let (address1, address2, city, state, zip) = attr_names(); - let credential_data1 = json!({address1.clone(): "123 Main St", address2.clone(): "Suite 3", city.clone(): "Draper", state.clone(): "UT", zip.clone(): "84000"}).to_string(); - let _credential_handle1 = _exchange_credential( - &mut consumer1, - &mut issuer, - credential_data1, - &cred_def, - &rev_reg, - &consumer1_to_issuer, - &issuer_to_consumer1, - None, - ) - .await; - let credential_data2 = json!({address1.clone(): "101 Tela Lane", address2.clone(): "Suite 1", city.clone(): "SLC", state.clone(): "WA", zip.clone(): "8721"}).to_string(); - let _credential_handle2 = _exchange_credential( - &mut consumer2, - &mut issuer, - credential_data2, - &cred_def, - &rev_reg, - &consumer2_to_issuer, - &issuer_to_consumer2, - None, - ) - .await; + let mut issuer = Faber::setup(setup.pool_handle).await; + let mut verifier = Faber::setup(setup.pool_handle).await; + let mut consumer1 = create_test_alice_instance(&setup).await; + let mut consumer2 = create_test_alice_instance(&setup).await; + + let (consumer1_to_verifier, verifier_to_consumer1) = + create_connected_connections(&mut consumer1, &mut verifier).await; + let (consumer1_to_issuer, issuer_to_consumer1) = + create_connected_connections(&mut consumer1, &mut issuer).await; + let (consumer2_to_verifier, verifier_to_consumer2) = + create_connected_connections(&mut consumer2, &mut verifier).await; + let (consumer2_to_issuer, issuer_to_consumer2) = + create_connected_connections(&mut consumer2, &mut issuer).await; + + let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = + _create_address_schema(&issuer.profile, &issuer.config_issuer.institution_did).await; + let (address1, address2, city, state, zip) = attr_names(); + let credential_data1 = json!({address1.clone(): "123 Main St", address2.clone(): "Suite 3", city.clone(): "Draper", state.clone(): "UT", zip.clone(): "84000"}).to_string(); + let _credential_handle1 = _exchange_credential( + &mut consumer1, + &mut issuer, + credential_data1, + &cred_def, + &rev_reg, + &consumer1_to_issuer, + &issuer_to_consumer1, + None, + ) + .await; + let credential_data2 = json!({address1.clone(): "101 Tela Lane", address2.clone(): "Suite 1", city.clone(): "SLC", state.clone(): "WA", zip.clone(): "8721"}).to_string(); + let _credential_handle2 = _exchange_credential( + &mut consumer2, + &mut issuer, + credential_data2, + &cred_def, + &rev_reg, + &consumer2_to_issuer, + &issuer_to_consumer2, + None, + ) + .await; - let request_name1 = Some("request1"); - let mut proof_verifier = verifier_create_proof_and_send_request( - &mut verifier, - &verifier_to_consumer1, - &schema_id, - &cred_def_id, - request_name1, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer1, &consumer1_to_verifier, None, None).await; - proof_verifier - .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer1) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(proof_verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); - - let request_name2 = Some("request2"); - let mut proof_verifier = verifier_create_proof_and_send_request( - &mut verifier, - &verifier_to_consumer2, - &schema_id, - &cred_def_id, - request_name2, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer2, &consumer2_to_verifier, None, None).await; - proof_verifier - .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer2) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(proof_verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); + let request_name1 = Some("request1"); + let mut proof_verifier = verifier_create_proof_and_send_request( + &mut verifier, + &verifier_to_consumer1, + &schema_id, + &cred_def_id, + request_name1, + ) + .await; + prover_select_credentials_and_send_proof(&mut consumer1, &consumer1_to_verifier, None, None).await; + proof_verifier + .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer1) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(proof_verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); + + let request_name2 = Some("request2"); + let mut proof_verifier = verifier_create_proof_and_send_request( + &mut verifier, + &verifier_to_consumer2, + &schema_id, + &cred_def_id, + request_name2, + ) + .await; + prover_select_credentials_and_send_proof(&mut consumer2, &consumer2_to_verifier, None, None).await; + proof_verifier + .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer2) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(proof_verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); }).await; } @@ -688,73 +708,73 @@ mod tests { #[tokio::test] async fn test_double_issuance_issuer_is_verifier() { SetupPool::run(|setup| async move { - let mut institution = Faber::setup(setup.pool_handle).await; - let mut consumer = create_test_alice_instance(&setup).await; - - let (consumer_to_institution, institution_to_consumer) = - create_connected_connections(&mut consumer, &mut institution).await; - - let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = - _create_address_schema(&institution.profile, &institution.config_issuer.institution_did).await; - let (address1, address, city, state, zip) = attr_names(); - let credential_data = json!({address1.clone(): "5th Avenue", address.clone(): "Suite 1234", city.clone(): "NYC", state.clone(): "NYS", zip.clone(): "84712"}).to_string(); - let _credential_handle = _exchange_credential( - &mut consumer, - &mut institution, - credential_data, - &cred_def, - &rev_reg, - &consumer_to_institution, - &institution_to_consumer, - None, - ) - .await; + let mut institution = Faber::setup(setup.pool_handle).await; + let mut consumer = create_test_alice_instance(&setup).await; - let request_name1 = Some("request1"); - let mut verifier = verifier_create_proof_and_send_request( - &mut institution, - &institution_to_consumer, - &schema_id, - &cred_def_id, - request_name1, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_institution, request_name1, None).await; - verifier - .update_state( - &institution.profile, - &institution.agency_client, + let (consumer_to_institution, institution_to_consumer) = + create_connected_connections(&mut consumer, &mut institution).await; + + let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = + _create_address_schema(&institution.profile, &institution.config_issuer.institution_did).await; + let (address1, address, city, state, zip) = attr_names(); + let credential_data = json!({address1.clone(): "5th Avenue", address.clone(): "Suite 1234", city.clone(): "NYC", state.clone(): "NYS", zip.clone(): "84712"}).to_string(); + let _credential_handle = _exchange_credential( + &mut consumer, + &mut institution, + credential_data, + &cred_def, + &rev_reg, + &consumer_to_institution, &institution_to_consumer, + None, ) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); - - let request_name2 = Some("request2"); - let mut verifier = verifier_create_proof_and_send_request( - &mut institution, - &institution_to_consumer, - &schema_id, - &cred_def_id, - request_name2, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_institution, request_name2, None).await; - verifier - .update_state( - &institution.profile, - &institution.agency_client, + .await; + + let request_name1 = Some("request1"); + let mut verifier = verifier_create_proof_and_send_request( + &mut institution, &institution_to_consumer, + &schema_id, + &cred_def_id, + request_name1, ) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); + .await; + prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_institution, request_name1, None).await; + verifier + .update_state( + &institution.profile, + &institution.agency_client, + &institution_to_consumer, + ) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); + + let request_name2 = Some("request2"); + let mut verifier = verifier_create_proof_and_send_request( + &mut institution, + &institution_to_consumer, + &schema_id, + &cred_def_id, + request_name2, + ) + .await; + prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_institution, request_name2, None).await; + verifier + .update_state( + &institution.profile, + &institution.agency_client, + &institution_to_consumer, + ) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); }).await; } @@ -881,80 +901,80 @@ mod tests { #[tokio::test] async fn test_two_creds_one_rev_reg() { SetupPool::run(|setup| async move { - let mut issuer = Faber::setup(setup.pool_handle).await; - let mut verifier = Faber::setup(setup.pool_handle).await; - let mut consumer = create_test_alice_instance(&setup).await; - - let (consumer_to_verifier, verifier_to_consumer) = - create_connected_connections(&mut consumer, &mut verifier).await; - let (consumer_to_issuer, issuer_to_consumer) = create_connected_connections(&mut consumer, &mut issuer).await; - - let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = - _create_address_schema(&issuer.profile, &issuer.config_issuer.institution_did).await; - let (address1, address2, city, state, zip) = attr_names(); - let (req1, req2) = (Some("request1"), Some("request2")); - let credential_data1 = json!({address1.clone(): "123 Main St", address2.clone(): "Suite 3", city.clone(): "Draper", state.clone(): "UT", zip.clone(): "84000"}).to_string(); - let _credential_handle1 = _exchange_credential( - &mut consumer, - &mut issuer, - credential_data1.clone(), - &cred_def, - &rev_reg, - &consumer_to_issuer, - &issuer_to_consumer, - req1, - ) - .await; - let credential_data2 = json!({address1.clone(): "101 Tela Lane", address2.clone(): "Suite 1", city.clone(): "SLC", state.clone(): "WA", zip.clone(): "8721"}).to_string(); - let _credential_handle2 = _exchange_credential( - &mut consumer, - &mut issuer, - credential_data2.clone(), - &cred_def, - &rev_reg, - &consumer_to_issuer, - &issuer_to_consumer, - req2, - ) - .await; + let mut issuer = Faber::setup(setup.pool_handle).await; + let mut verifier = Faber::setup(setup.pool_handle).await; + let mut consumer = create_test_alice_instance(&setup).await; - let mut proof_verifier = verifier_create_proof_and_send_request( - &mut verifier, - &verifier_to_consumer, - &schema_id, - &cred_def_id, - req1, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_verifier, req1, Some(&credential_data1)) - .await; - proof_verifier - .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(proof_verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); - - let mut proof_verifier = verifier_create_proof_and_send_request( - &mut verifier, - &verifier_to_consumer, - &schema_id, - &cred_def_id, - req2, - ) - .await; - prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_verifier, req2, Some(&credential_data2)) - .await; - proof_verifier - .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer) - .await - .unwrap(); - assert_eq!( - ProofStateType::from(proof_verifier.get_presentation_status()), - ProofStateType::ProofValidated - ); + let (consumer_to_verifier, verifier_to_consumer) = + create_connected_connections(&mut consumer, &mut verifier).await; + let (consumer_to_issuer, issuer_to_consumer) = create_connected_connections(&mut consumer, &mut issuer).await; + + let (schema_id, _schema_json, cred_def_id, _cred_def_json, cred_def, rev_reg, _rev_reg_id) = + _create_address_schema(&issuer.profile, &issuer.config_issuer.institution_did).await; + let (address1, address2, city, state, zip) = attr_names(); + let (req1, req2) = (Some("request1"), Some("request2")); + let credential_data1 = json!({address1.clone(): "123 Main St", address2.clone(): "Suite 3", city.clone(): "Draper", state.clone(): "UT", zip.clone(): "84000"}).to_string(); + let _credential_handle1 = _exchange_credential( + &mut consumer, + &mut issuer, + credential_data1.clone(), + &cred_def, + &rev_reg, + &consumer_to_issuer, + &issuer_to_consumer, + req1, + ) + .await; + let credential_data2 = json!({address1.clone(): "101 Tela Lane", address2.clone(): "Suite 1", city.clone(): "SLC", state.clone(): "WA", zip.clone(): "8721"}).to_string(); + let _credential_handle2 = _exchange_credential( + &mut consumer, + &mut issuer, + credential_data2.clone(), + &cred_def, + &rev_reg, + &consumer_to_issuer, + &issuer_to_consumer, + req2, + ) + .await; + + let mut proof_verifier = verifier_create_proof_and_send_request( + &mut verifier, + &verifier_to_consumer, + &schema_id, + &cred_def_id, + req1, + ) + .await; + prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_verifier, req1, Some(&credential_data1)) + .await; + proof_verifier + .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(proof_verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); + + let mut proof_verifier = verifier_create_proof_and_send_request( + &mut verifier, + &verifier_to_consumer, + &schema_id, + &cred_def_id, + req2, + ) + .await; + prover_select_credentials_and_send_proof(&mut consumer, &consumer_to_verifier, req2, Some(&credential_data2)) + .await; + proof_verifier + .update_state(&verifier.profile, &verifier.agency_client, &verifier_to_consumer) + .await + .unwrap(); + assert_eq!( + ProofStateType::from(proof_verifier.get_presentation_status()), + ProofStateType::ProofValidated + ); }).await; } diff --git a/libvcx/src/api_c/protocols/disclosed_proof.rs b/libvcx/src/api_c/protocols/disclosed_proof.rs index e53b979ea2..4c59b5f86e 100644 --- a/libvcx/src/api_c/protocols/disclosed_proof.rs +++ b/libvcx/src/api_c/protocols/disclosed_proof.rs @@ -326,7 +326,7 @@ pub extern "C" fn vcx_disclosed_proof_get_proof_msg( ); execute(move || { - match disclosed_proof::generate_proof_msg(proof_handle) { + match disclosed_proof::get_presentation_msg(proof_handle) { Ok(msg) => { let msg = CStringUtils::string_to_cstring(msg); trace!( diff --git a/libvcx/src/api_c/protocols/proof.rs b/libvcx/src/api_c/protocols/proof.rs index ae2731f1a3..3f556b4343 100644 --- a/libvcx/src/api_c/protocols/proof.rs +++ b/libvcx/src/api_c/protocols/proof.rs @@ -672,7 +672,7 @@ pub extern "C" fn vcx_get_proof_msg( cb( command_handle, SUCCESS_ERR_CODE, - proof::get_proof_state(proof_handle).unwrap_or(0), + proof::proof_get_presentation_verification_status(proof_handle).unwrap_or(0), msg.as_ptr(), ); } @@ -685,7 +685,7 @@ pub extern "C" fn vcx_get_proof_msg( cb( command_handle, err.into(), - proof::get_proof_state(proof_handle).unwrap_or(0), + proof::proof_get_presentation_verification_status(proof_handle).unwrap_or(0), ptr::null_mut(), ); } diff --git a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs index 40a9d45b34..ce81ed7664 100644 --- a/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/disclosed_proof.rs @@ -135,9 +135,10 @@ pub fn release_all() { HANDLE_MAP.drain().ok(); } -pub fn generate_proof_msg(handle: u32) -> LibvcxResult { +pub fn get_presentation_msg(handle: u32) -> LibvcxResult { HANDLE_MAP.get(handle, |proof| { - proof.generate_presentation_msg().map_err(|err| err.into()) + let presentation = proof.get_presentation_msg()?; + Ok(json!(presentation).to_string()) }) } diff --git a/libvcx_core/src/api_vcx/api_handle/proof.rs b/libvcx_core/src/api_vcx/api_handle/proof.rs index 649487b15c..2860316f21 100644 --- a/libvcx_core/src/api_vcx/api_handle/proof.rs +++ b/libvcx_core/src/api_vcx/api_handle/proof.rs @@ -8,6 +8,7 @@ use aries_vcx::messages::a2a::A2AMessage; use crate::api_vcx::api_global::profile::get_main_profile; use crate::api_vcx::api_handle::connection::HttpClient; use crate::api_vcx::api_handle::object_cache::ObjectCache; +use crate::api_vcx::api_handle::out_of_band::to_a2a_message; use crate::api_vcx::api_handle::{connection, mediated_connection}; use crate::errors::error::{LibvcxError, LibvcxErrorKind, LibvcxResult}; @@ -128,10 +129,6 @@ pub fn get_state(handle: u32) -> LibvcxResult { PROOF_MAP.get(handle, |proof| Ok(proof.get_state().into())) } -pub fn get_proof_state(handle: u32) -> LibvcxResult { - PROOF_MAP.get(handle, |proof| Ok(proof.get_presentation_status().code())) -} - pub fn release(handle: u32) -> LibvcxResult<()> { PROOF_MAP .release(handle) @@ -192,22 +189,44 @@ pub async fn send_proof_request_nonmediated(handle: u32, connection_handle: u32) PROOF_MAP.insert(handle, proof) } +// --- Presentation request --- pub fn mark_presentation_request_msg_sent(handle: u32) -> LibvcxResult<()> { let mut proof = PROOF_MAP.get_cloned(handle)?; proof.mark_presentation_request_msg_sent()?; PROOF_MAP.insert(handle, proof) } -pub fn get_presentation_request_msg(handle: u32) -> LibvcxResult { +pub fn get_presentation_request_attachment(handle: u32) -> LibvcxResult { PROOF_MAP.get(handle, |proof| { - proof.get_presentation_request_msg().map_err(|err| err.into()) + proof.get_presentation_request_attachment().map_err(|err| err.into()) }) } +pub fn get_presentation_request_msg(handle: u32) -> LibvcxResult { + PROOF_MAP.get(handle, |proof| { + let msg = proof.get_presentation_request_msg()?.to_a2a_message(); + Ok(json!(msg).to_string()) + }) +} +// --- Presentation --- pub fn get_presentation_msg(handle: u32) -> LibvcxResult { - PROOF_MAP.get(handle, |proof| proof.get_presentation_msg().map_err(|err| err.into())) + PROOF_MAP.get(handle, |proof| { + let msg = proof.get_presentation_msg()?.to_a2a_message(); + Ok(json!(msg).to_string()) + }) +} + +pub fn get_presentation_attachment(handle: u32) -> LibvcxResult { + PROOF_MAP.get(handle, |proof| { + proof.get_presentation_attachment().map_err(|err| err.into()) + }) +} + +pub fn proof_get_presentation_verification_status(handle: u32) -> LibvcxResult { + PROOF_MAP.get(handle, |proof| Ok(proof.get_presentation_status().code())) } +// --- General --- pub fn get_thread_id(handle: u32) -> LibvcxResult { PROOF_MAP.get(handle, |proof| proof.get_thread_id().map_err(|err| err.into())) } @@ -590,7 +609,7 @@ pub mod tests { send_proof_request(bad_handle, handle_conn).await.unwrap_err().kind(), LibvcxErrorKind::InvalidHandle ); - assert_eq!(get_proof_state(handle_proof).unwrap(), 0); + assert_eq!(proof_get_presentation_verification_status(handle_proof).unwrap(), 0); assert_eq!( create_proof( "my source id".to_string(), diff --git a/messages/src/status.rs b/messages/src/status.rs index 60f9d29e3a..9e9e7f7d58 100644 --- a/messages/src/status.rs +++ b/messages/src/status.rs @@ -1,5 +1,6 @@ use crate::concepts::problem_report::ProblemReport; +// todo: this is shared by multiple protocols to express different things - needs to be split #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum Status { Undefined, diff --git a/wrappers/node/src/api/proof.ts b/wrappers/node/src/api/proof.ts index c6c1e8ed2b..85814d8b4f 100644 --- a/wrappers/node/src/api/proof.ts +++ b/wrappers/node/src/api/proof.ts @@ -31,11 +31,6 @@ export interface IProofData { proof: any; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface IProofResponses { - proof?: string; - proofState: ProofState; -} - export enum ProofFieldType { Revealed = 'revealed', Unrevealed = 'unrevealed', @@ -190,14 +185,33 @@ export class Proof extends VcxBaseWithState { } } - public getProof(): IProofResponses { + public getPresentationMsg(): string { + try { + return ffi.proofGetPresentationMsg(this.handle); + } catch (err: any) { + throw new VCXInternalError(err); + } + } + + public getPresentationVerificationStatus(): ProofState { + try { + return ffi.proofGetPresentationVerificationStatus(this.handle); + } catch (err: any) { + throw new VCXInternalError(err); + } + } + + public getPresentationAttachment(): string { + try { + return ffi.proofGetPresentationAttachment(this.handle); + } catch (err: any) { + throw new VCXInternalError(err); + } + } + + public getPresentationRequestAttachment(): string { try { - const proof = ffi.proofGetProofMsg(this.handle); - const proofState = ffi.proofGetProofState(this.handle); - return { - proof, - proofState, - }; + return ffi.proofGetPresentationRequestAttachment(this.handle); } catch (err: any) { throw new VCXInternalError(err); } diff --git a/wrappers/vcx-napi-rs/index.d.ts b/wrappers/vcx-napi-rs/index.d.ts index 0c0bd3aa23..ff77185809 100644 --- a/wrappers/vcx-napi-rs/index.d.ts +++ b/wrappers/vcx-napi-rs/index.d.ts @@ -147,7 +147,9 @@ export function outOfBandSenderRelease(handle: number): void export function openMainPool(poolConfig: string): Promise export function closeMainPool(): Promise export function proofCreate(sourceId: string, requestedAttrs: string, requestedPredicates: string, revocationDetails: string, name: string): Promise -export function proofGetProofMsg(handle: number): string +export function proofGetPresentationMsg(handle: number): string +export function proofGetPresentationRequestAttachment(handle: number): string +export function proofGetPresentationAttachment(handle: number): string export function proofRelease(handle: number): void export function proofSendRequest(handleProof: number, handleConnection: number): Promise export function proofSendRequestNonmediated(handleProof: number, handleConnection: number): Promise @@ -158,7 +160,7 @@ export function v2ProofUpdateState(handleProof: number, connectionHandle: number export function v2ProofUpdateStateWithMessage(handleProof: number, message: string, connectionHandle: number): Promise export function proofUpdateStateWithMessageNonmediated(handleProof: number, connectionHandle: number, message: string): Promise export function proofGetState(handle: number): number -export function proofGetProofState(handle: number): number +export function proofGetPresentationVerificationStatus(handle: number): number export function proofGetThreadId(handle: number): string export function markPresentationRequestMsgSent(handle: number): void export function revocationRegistryCreate(config: string): Promise diff --git a/wrappers/vcx-napi-rs/index.js b/wrappers/vcx-napi-rs/index.js index 0edb99d7a9..1f24ef6f53 100644 --- a/wrappers/vcx-napi-rs/index.js +++ b/wrappers/vcx-napi-rs/index.js @@ -246,7 +246,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { updateWebhookUrl, createAgencyClientForMainWallet, provisionCloudAgent, messagesUpdateStatus, generatePublicInvitation, connectionCreateInviter, connectionCreateInvitee, connectionGetThreadId, connectionGetPairwiseInfo, connectionGetRemoteDid, connectionGetRemoteVk, connectionGetState, connectionGetInvitation, connectionProcessInvite, connectionProcessRequest, connectionProcessResponse, connectionProcessAck, connectionProcessProblemReport, connectionSendResponse, connectionSendRequest, connectionSendAck, connectionSendGenericMessage, connectionSendAriesMessage, connectionCreateInvite, connectionSerialize, connectionDeserialize, connectionRelease, credentialCreateWithOffer, credentialRelease, credentialSendRequest, credentialDeclineOffer, credentialSerialize, credentialDeserialize, v2CredentialUpdateStateWithMessage, v2CredentialUpdateState, credentialGetState, credentialGetOffers, credentialGetAttributes, credentialGetAttachment, credentialGetTailsLocation, credentialGetTailsHash, credentialGetRevRegId, credentialGetThreadId, credentialdefCreateV2, credentialdefPublish, credentialdefDeserialize, credentialdefRelease, credentialdefSerialize, credentialdefGetCredDefId, credentialdefUpdateState, credentialdefGetState, disclosedProofCreateWithRequest, disclosedProofRelease, disclosedProofSendProof, disclosedProofRejectProof, disclosedProofGetProofMsg, disclosedProofSerialize, disclosedProofDeserialize, v2DisclosedProofUpdateState, v2DisclosedProofUpdateStateWithMessage, disclosedProofGetState, disclosedProofGetRequests, disclosedProofRetrieveCredentials, disclosedProofGetProofRequestAttachment, disclosedProofGenerateProof, disclosedProofDeclinePresentationRequest, disclosedProofGetThreadId, issuerCredentialDeserialize, issuerCredentialSerialize, issuerCredentialUpdateStateV2, issuerCredentialUpdateStateWithMessageV2, issuerCredentialUpdateStateWithMessageNonmediated, issuerCredentialGetState, issuerCredentialGetRevRegId, issuerCredentialCreate, issuerCredentialRevokeLocal, issuerCredentialIsRevokable, issuerCredentialSendCredential, issuerCredentialSendCredentialNonmediated, issuerCredentialSendOfferV2, issuerCredentialSendOfferNonmediated, issuerCredentialMarkOfferMsgSent, issuerCredentialBuildOfferMsgV2, issuerCredentialGetOfferMsg, issuerCredentialRelease, issuerCredentialGetThreadId, getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta, createService, createServiceV2, getServiceFromLedger, getAttrFromLedger, clearAttrFromLedger, getVerkeyFromLedger, getLedgerTxn, initDefaultLogger, mediatedConnectionGeneratePublicInvite, mediatedConnectionGetPwDid, mediatedConnectionGetTheirPwDid, mediatedConnectionGetThreadId, mediatedConnectionGetState, mediatedConnectionGetSourceId, mediatedConnectionCreate, mediatedConnectionCreateWithInvite, mediatedConnectionSendMessage, mediatedConnectionCreateWithConnectionRequestV2, mediatedConnectionSendHandshakeReuse, mediatedConnectionUpdateStateWithMessage, mediatedConnectionHandleMessage, mediatedConnectionUpdateState, mediatedConnectionDeleteConnection, mediatedConnectionConnect, mediatedConnectionSerialize, mediatedConnectionDeserialize, mediatedConnectionRelease, mediatedConnectionInviteDetails, mediatedConnectionSendPing, mediatedConnectionSendDiscoveryFeatures, mediatedConnectionInfo, mediatedConnectionMessagesDownload, mediatedConnectionSignData, mediatedConnectionVerifySignature, outOfBandBuildHandshakeReuseAcceptedMsg, outOfBandReceiverCreate, outOfBandReceiverExtractMessage, outOfBandReceiverConnectionExists, outOfBandReceiverNonmediatedConnectionExists, outOfBandReceiverBuildConnection, outOfBandReceiverGetThreadId, outOfBandReceiverSerialize, outOfBandReceiverDeserialize, outOfBandReceiverRelease, outOfBandSenderCreate, outOfBandSenderAppendMessage, outOfBandSenderAppendService, outOfBandSenderAppendServiceDid, outOfBandSenderToMessage, outOfBandSenderGetThreadId, outOfBandSenderSerialize, outOfBandSenderDeserialize, outOfBandSenderRelease, openMainPool, closeMainPool, proofCreate, proofGetProofMsg, proofRelease, proofSendRequest, proofSendRequestNonmediated, proofGetRequestMsg, proofSerialize, proofDeserialize, v2ProofUpdateState, v2ProofUpdateStateWithMessage, proofUpdateStateWithMessageNonmediated, proofGetState, proofGetProofState, proofGetThreadId, markPresentationRequestMsgSent, revocationRegistryCreate, revocationRegistryPublish, revocationRegistryPublishRevocations, revocationRegistryGetRevRegId, revocationRegistryGetTailsHash, revocationRegistrySerialize, revocationRegistryDeserialize, revocationRegistryRelease, schemaGetAttributes, schemaPrepareForEndorser, schemaCreate, schemaGetSchemaId, schemaDeserialize, schemaSerialize, schemaRelease, schemaUpdateState, schemaGetState, enableMocks, trustpingBuildResponseMsg, trustpingBuildPing, shutdown, getVersion, walletOpenAsMain, walletCreateMain, walletCloseMain, vcxInitIssuerConfig, configureIssuerWallet, unpack, createPairwiseInfo, walletImport, walletExport, getVerkeyFromWallet, rotateVerkey, rotateVerkeyStart, rotateVerkeyApply } = nativeBinding +const { updateWebhookUrl, createAgencyClientForMainWallet, provisionCloudAgent, messagesUpdateStatus, generatePublicInvitation, connectionCreateInviter, connectionCreateInvitee, connectionGetThreadId, connectionGetPairwiseInfo, connectionGetRemoteDid, connectionGetRemoteVk, connectionGetState, connectionGetInvitation, connectionProcessInvite, connectionProcessRequest, connectionProcessResponse, connectionProcessAck, connectionProcessProblemReport, connectionSendResponse, connectionSendRequest, connectionSendAck, connectionSendGenericMessage, connectionSendAriesMessage, connectionCreateInvite, connectionSerialize, connectionDeserialize, connectionRelease, credentialCreateWithOffer, credentialRelease, credentialSendRequest, credentialDeclineOffer, credentialSerialize, credentialDeserialize, v2CredentialUpdateStateWithMessage, v2CredentialUpdateState, credentialGetState, credentialGetOffers, credentialGetAttributes, credentialGetAttachment, credentialGetTailsLocation, credentialGetTailsHash, credentialGetRevRegId, credentialGetThreadId, credentialdefCreateV2, credentialdefPublish, credentialdefDeserialize, credentialdefRelease, credentialdefSerialize, credentialdefGetCredDefId, credentialdefUpdateState, credentialdefGetState, disclosedProofCreateWithRequest, disclosedProofRelease, disclosedProofSendProof, disclosedProofRejectProof, disclosedProofGetProofMsg, disclosedProofSerialize, disclosedProofDeserialize, v2DisclosedProofUpdateState, v2DisclosedProofUpdateStateWithMessage, disclosedProofGetState, disclosedProofGetRequests, disclosedProofRetrieveCredentials, disclosedProofGetProofRequestAttachment, disclosedProofGenerateProof, disclosedProofDeclinePresentationRequest, disclosedProofGetThreadId, issuerCredentialDeserialize, issuerCredentialSerialize, issuerCredentialUpdateStateV2, issuerCredentialUpdateStateWithMessageV2, issuerCredentialUpdateStateWithMessageNonmediated, issuerCredentialGetState, issuerCredentialGetRevRegId, issuerCredentialCreate, issuerCredentialRevokeLocal, issuerCredentialIsRevokable, issuerCredentialSendCredential, issuerCredentialSendCredentialNonmediated, issuerCredentialSendOfferV2, issuerCredentialSendOfferNonmediated, issuerCredentialMarkOfferMsgSent, issuerCredentialBuildOfferMsgV2, issuerCredentialGetOfferMsg, issuerCredentialRelease, issuerCredentialGetThreadId, getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta, createService, createServiceV2, getServiceFromLedger, getAttrFromLedger, clearAttrFromLedger, getVerkeyFromLedger, getLedgerTxn, initDefaultLogger, mediatedConnectionGeneratePublicInvite, mediatedConnectionGetPwDid, mediatedConnectionGetTheirPwDid, mediatedConnectionGetThreadId, mediatedConnectionGetState, mediatedConnectionGetSourceId, mediatedConnectionCreate, mediatedConnectionCreateWithInvite, mediatedConnectionSendMessage, mediatedConnectionCreateWithConnectionRequestV2, mediatedConnectionSendHandshakeReuse, mediatedConnectionUpdateStateWithMessage, mediatedConnectionHandleMessage, mediatedConnectionUpdateState, mediatedConnectionDeleteConnection, mediatedConnectionConnect, mediatedConnectionSerialize, mediatedConnectionDeserialize, mediatedConnectionRelease, mediatedConnectionInviteDetails, mediatedConnectionSendPing, mediatedConnectionSendDiscoveryFeatures, mediatedConnectionInfo, mediatedConnectionMessagesDownload, mediatedConnectionSignData, mediatedConnectionVerifySignature, outOfBandBuildHandshakeReuseAcceptedMsg, outOfBandReceiverCreate, outOfBandReceiverExtractMessage, outOfBandReceiverConnectionExists, outOfBandReceiverNonmediatedConnectionExists, outOfBandReceiverBuildConnection, outOfBandReceiverGetThreadId, outOfBandReceiverSerialize, outOfBandReceiverDeserialize, outOfBandReceiverRelease, outOfBandSenderCreate, outOfBandSenderAppendMessage, outOfBandSenderAppendService, outOfBandSenderAppendServiceDid, outOfBandSenderToMessage, outOfBandSenderGetThreadId, outOfBandSenderSerialize, outOfBandSenderDeserialize, outOfBandSenderRelease, openMainPool, closeMainPool, proofCreate, proofGetPresentationMsg, proofGetPresentationRequestAttachment, proofGetPresentationAttachment, proofRelease, proofSendRequest, proofSendRequestNonmediated, proofGetRequestMsg, proofSerialize, proofDeserialize, v2ProofUpdateState, v2ProofUpdateStateWithMessage, proofUpdateStateWithMessageNonmediated, proofGetState, proofGetPresentationVerificationStatus, proofGetThreadId, markPresentationRequestMsgSent, revocationRegistryCreate, revocationRegistryPublish, revocationRegistryPublishRevocations, revocationRegistryGetRevRegId, revocationRegistryGetTailsHash, revocationRegistrySerialize, revocationRegistryDeserialize, revocationRegistryRelease, schemaGetAttributes, schemaPrepareForEndorser, schemaCreate, schemaGetSchemaId, schemaDeserialize, schemaSerialize, schemaRelease, schemaUpdateState, schemaGetState, enableMocks, trustpingBuildResponseMsg, trustpingBuildPing, shutdown, getVersion, walletOpenAsMain, walletCreateMain, walletCloseMain, vcxInitIssuerConfig, configureIssuerWallet, unpack, createPairwiseInfo, walletImport, walletExport, getVerkeyFromWallet, rotateVerkey, rotateVerkeyStart, rotateVerkeyApply } = nativeBinding module.exports.updateWebhookUrl = updateWebhookUrl module.exports.createAgencyClientForMainWallet = createAgencyClientForMainWallet @@ -392,7 +392,9 @@ module.exports.outOfBandSenderRelease = outOfBandSenderRelease module.exports.openMainPool = openMainPool module.exports.closeMainPool = closeMainPool module.exports.proofCreate = proofCreate -module.exports.proofGetProofMsg = proofGetProofMsg +module.exports.proofGetPresentationMsg = proofGetPresentationMsg +module.exports.proofGetPresentationRequestAttachment = proofGetPresentationRequestAttachment +module.exports.proofGetPresentationAttachment = proofGetPresentationAttachment module.exports.proofRelease = proofRelease module.exports.proofSendRequest = proofSendRequest module.exports.proofSendRequestNonmediated = proofSendRequestNonmediated @@ -403,7 +405,7 @@ module.exports.v2ProofUpdateState = v2ProofUpdateState module.exports.v2ProofUpdateStateWithMessage = v2ProofUpdateStateWithMessage module.exports.proofUpdateStateWithMessageNonmediated = proofUpdateStateWithMessageNonmediated module.exports.proofGetState = proofGetState -module.exports.proofGetProofState = proofGetProofState +module.exports.proofGetPresentationVerificationStatus = proofGetPresentationVerificationStatus module.exports.proofGetThreadId = proofGetThreadId module.exports.markPresentationRequestMsgSent = markPresentationRequestMsgSent module.exports.revocationRegistryCreate = revocationRegistryCreate diff --git a/wrappers/vcx-napi-rs/src/api/disclosed_proof.rs b/wrappers/vcx-napi-rs/src/api/disclosed_proof.rs index 0ad069e9e5..f165ed9ddc 100644 --- a/wrappers/vcx-napi-rs/src/api/disclosed_proof.rs +++ b/wrappers/vcx-napi-rs/src/api/disclosed_proof.rs @@ -30,7 +30,7 @@ async fn disclosed_proof_reject_proof(handle: u32, handle_connection: u32) -> na #[napi] fn disclosed_proof_get_proof_msg(handle: u32) -> napi::Result { - disclosed_proof::generate_proof_msg(handle).map_err(to_napi_err) + disclosed_proof::get_presentation_msg(handle).map_err(to_napi_err) } #[napi] diff --git a/wrappers/vcx-napi-rs/src/api/proof.rs b/wrappers/vcx-napi-rs/src/api/proof.rs index adc786fe00..d56b58f163 100644 --- a/wrappers/vcx-napi-rs/src/api/proof.rs +++ b/wrappers/vcx-napi-rs/src/api/proof.rs @@ -24,10 +24,20 @@ async fn proof_create( } #[napi] -fn proof_get_proof_msg(handle: u32) -> napi::Result { +fn proof_get_presentation_msg(handle: u32) -> napi::Result { proof::get_presentation_msg(handle).map_err(to_napi_err) } +#[napi] +fn proof_get_presentation_request_attachment(handle: u32) -> napi::Result { + proof::get_presentation_request_attachment(handle).map_err(to_napi_err) +} + +#[napi] +fn proof_get_presentation_attachment(handle: u32) -> napi::Result { + proof::get_presentation_attachment(handle).map_err(to_napi_err) +} + #[napi] fn proof_release(handle: u32) -> napi::Result<()> { proof::release(handle).map_err(to_napi_err) @@ -98,8 +108,8 @@ fn proof_get_state(handle: u32) -> napi::Result { } #[napi] -fn proof_get_proof_state(handle: u32) -> napi::Result { - proof::get_proof_state(handle).map_err(to_napi_err) +fn proof_get_presentation_verification_status(handle: u32) -> napi::Result { + proof::proof_get_presentation_verification_status(handle).map_err(to_napi_err) } #[napi]