Skip to content

Commit

Permalink
Merge pull request #91 from AbsaOSS/feature/vcx-init-split
Browse files Browse the repository at this point in the history
Add functions to init memory, wallet, pool separately
  • Loading branch information
mirgee authored Sep 24, 2020
2 parents c12df6d + bac255a commit ffff156
Show file tree
Hide file tree
Showing 25 changed files with 754 additions and 152 deletions.
2 changes: 1 addition & 1 deletion agents/node/vcxagent-core/demo/alice.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ async function runAlice (options) {
protocolType: options.protocolType,
agencyUrl: 'http://localhost:8080',
seed: '000000000000000000000000Trustee1',
webhookUrl: `http://localhost:7209/notifications/${agentName}`,
usePostgresWallet: false,
logger
})
await vcxClient.updateWebhookUrl(`http://localhost:7209/notifications/${agentName}`)

const invitationString = await getInvitationString(options['autofetch-invitation-url'])
const connectionToFaber = await vcxClient.inviteeConnectionAcceptFromInvitation(agentName, invitationString)
Expand Down
2 changes: 1 addition & 1 deletion agents/node/vcxagent-core/demo/faber.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ async function runFaber (options) {
protocolType: options.protocolType,
agencyUrl: 'http://localhost:8080',
seed: '000000000000000000000000Trustee1',
webhookUrl: `http://localhost:7209/notifications/${agentName}`,
usePostgresWallet: false,
logger
})
await vcxClient.updateWebhookUrl(`http://localhost:7209/notifications/${agentName}`)

if (process.env.ACCEPT_TAA || false) {
await vcxClient.acceptTaa()
Expand Down
55 changes: 55 additions & 0 deletions agents/node/vcxagent-core/demo/notification-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const express = require('express')
const bodyParser = require('body-parser')

const PORT = 7209

const app = express()
app.use(bodyParser.json())

const FgRed = '\x1b[31m'
const FgGreen = '\x1b[32m'
const FgYellow = '\x1b[33m'
const FgBlue = '\x1b[34m'
const FgMagenta = '\x1b[35m'
const FgCyan = '\x1b[36m'
const FgWhite = '\x1b[37m'

const colors = [FgRed, FgGreen, FgYellow, FgBlue, FgMagenta, FgCyan, FgWhite]
let colorIdx = 0

const agentColors = {}

function getAgentColor (agentId) {
if (!agentColors[agentId]) {
agentColors[agentId] = colors[colorIdx]
colorIdx = (colorIdx + 1) % colors.length
}
return agentColors[agentId]
}

async function run () {
const notifications = {}

app.post('/notifications/:agentId', async function (req, res) {
const { agentId } = req.params
console.log(getAgentColor(agentId), `${new Date()}] ${agentId}: ${JSON.stringify(req.body, null, 2)}`)
if (!notifications[agentId]) {
notifications[agentId] = []
}
notifications[agentId].push(req.body)
return res.status(200).send()
})

app.get('/notifications', async function (req, res) {
return res.status(200).send(JSON.stringify(notifications))
})

app.use(function (req, res, next) {
console.error(`Request ${req.method} '${req.originalUrl}' was not matched with any handler.\nRequest header:${JSON.stringify(req.headers, null, 2)}\nRequest body: ${JSON.stringify(req.body, null, 2)}`)
res.status(404).send({ message: `Your request: '${req.originalUrl}' didn't reach any handler.` })
})

app.listen(PORT, () => console.log(`Server listening on port ${PORT}!`))
}

run()
2 changes: 1 addition & 1 deletion agents/node/vcxagent-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"lint:fix": "standard --fix",
"demo:notifyserver": "node notification-server.js",
"demo:notifyserver": "node demo/notification-server.js",
"demo:alice": "node demo/alice.js",
"demo:faber": "node demo/faber.js",
"demo:faber:rev": "node demo/faber.js --revocation",
Expand Down
59 changes: 53 additions & 6 deletions agents/node/vcxagent-core/vcx-agent.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
const { getMessagesForPwDid } = require('./messages')
const { provisionAgentInAgency, initRustapi } = require('./vcx-workflows')
const { Schema, CredentialDef, Connection, StateType, IssuerCredential, Credential, Proof, DisclosedProof, initVcxWithConfig, getLedgerAuthorAgreement, setActiveTxnAuthorAgreementMeta } = require('@absaoss/node-vcx-wrapper')
const {
Schema,
CredentialDef,
Connection,
StateType,
IssuerCredential,
Credential,
Proof,
DisclosedProof,
initVcxWithConfig,
initVcxCore,
openVcxWallet,
openVcxPool,
vcxUpdateWebhookUrl,
getLedgerAuthorAgreement,
setActiveTxnAuthorAgreementMeta
} = require('@absaoss/node-vcx-wrapper')
const { createStorageService } = require('./storage-service')
const { pollFunction, waitUntilAgencyIsReady } = require('./common')
const { pollFunction, waitUntilAgencyIsReady, getRandomInt } = require('./common')
const { getFaberSchemaData } = require('./test/data')

async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webhookUrl, usePostgresWallet, logger }) {
Expand All @@ -23,19 +39,43 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
connections[connectionName] = connection
}

async function initVcx (name = agentName) {
logger.info(`Initializing VCX of ${name}`)
/**
* Initializes libvcx configuration, open pool, open wallet, set webhook url if present in agent provison
*/
async function initVcxOld (name = agentName) {
logger.info(`Initializing VCX agent ${name}`)
logger.debug(`Using following agent provision to initialize VCX ${JSON.stringify(agentProvision, null, 2)}`)
await initVcxWithConfig(JSON.stringify(agentProvision))
}

/**
* Performs the same as initVcxOld, except for the fact it ignores webhook_url in agent provision. You have to
* update webhook_url by calling function vcxUpdateWebhookUrl.
*/
async function initVcx (name = agentName) {
logger.info(`Initializing VCX agent ${name}`)
logger.debug(`Using following agent provision to initialize VCX settings ${JSON.stringify(agentProvision, null, 2)}`)
await initVcxCore(JSON.stringify(agentProvision))
logger.debug('Opening wallet and pool')
const promises = []
promises.push(openVcxPool())
promises.push(openVcxWallet())
await Promise.all(promises)
logger.debug('LibVCX fully initialized')
}

async function acceptTaa () {
const taa = await getLedgerAuthorAgreement()
const taaJson = JSON.parse(taa)
const utime = Math.floor(new Date() / 1000)
await setActiveTxnAuthorAgreementMeta(taaJson.text, taaJson.version, null, Object.keys(taaJson.aml)[0], utime)
}

async function updateWebhookUrl (webhookUrl) {
logger.info(`Updating webhook url to ${webhookUrl}`)
await vcxUpdateWebhookUrl({ webhookUrl })
}

async function createSchema (_schemaData) {
const schemaData = _schemaData || getFaberSchemaData()
logger.info(`Creating a new schema on the ledger: ${JSON.stringify(schemaData, null, 2)}`)
Expand Down Expand Up @@ -147,6 +187,7 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
return { result: null, isFinished: true }
}
}

const [error] = await pollFunction(progressToAcceptedState, 'Progress connection', logger, attemptsThreshold, timeout)
if (error) {
throw Error(`Couldn't progress connection to Accepted state. ${error}`)
Expand Down Expand Up @@ -186,7 +227,7 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
logger.info(`Found ${offers.length} credential offers.`)
}

async function sendOffer ({ schemaAttrs, credDefName, connectionNameReceiver, connection, skipProgress }) {
async function sendOffer ({ schemaAttrs, credDefName, connectionNameReceiver, connection, revoke, skipProgress }) {
logger.info(`Going to issue credential from credential definition ${credDefName}`)
const credDefSerialized = await storageService.loadCredentialDefinition(credDefName)
const credDef = await CredentialDef.deserialize(credDefSerialized)
Expand Down Expand Up @@ -229,6 +270,8 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
await issuerCred.sendCredential(connectionToReceiver)
logger.debug(`IssuerCredential after credential was sent:\n${JSON.stringify(await issuerCred.serialize())}`)

const serCredential = await issuerCred.serialize()

if (!skipProgress) {
logger.info('Wait for alice to accept credential')
await _progressIssuerCredentialToState(issuerCred, StateType.Accepted, 10, 2000)
Expand Down Expand Up @@ -258,6 +301,7 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
return { result: offers, isFinished: true }
}
}

const [error, offers] = await pollFunction(findSomeCredOffer, 'Get credential offer', logger, attemptsThreshold, timeout)
if (error) {
throw Error(`Couldn't get credential offers. ${error}`)
Expand All @@ -275,6 +319,7 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
return { result: null, isFinished: true }
}
}

const [error] = await pollFunction(progressToAcceptedState, `Progress CredentialSM to state ${credentialStateTarget}`, logger, attemptsThreshold, timeout)
if (error) {
throw Error(`Couldn't progress credential to Accepted state. ${error}`)
Expand All @@ -291,6 +336,7 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
return { result: null, isFinished: true }
}
}

const [error, offers] = await pollFunction(progressToAcceptedState, `Progress IssuerCredentialSM to state ${credentialStateTarget}`, logger, attemptsThreshold, timeout)
if (error) {
throw Error(`Couldn't get credential offers. ${error}`)
Expand Down Expand Up @@ -393,10 +439,11 @@ async function createVcxAgent ({ agentName, protocolType, agencyUrl, seed, webho
getCredentialOffers,
getInstitutionDid,
createConnection,
initVcx,
initVcx: initVcxOld,
createInvite,
inviteeConnectionCreateFromInvite,
storeConnection,
updateWebhookUrl,
sendMessage,
getMessages,
verifierCreateProof,
Expand Down
10 changes: 0 additions & 10 deletions agents/node/vcxagent-core/vcx-workflows.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ async function provisionAgentInAgency (agentName, protocolType, agencyUrl, seed,
if (!seed) {
throw Error('seed not specified')
}
if (!webhookUrl) {
throw Error('webhookUrl not specified')
}
const provisionConfig = {
agency_url: agencyUrl,
agency_did: 'VsKV7grR1BUE29mG2Fm2kX',
Expand All @@ -83,13 +80,6 @@ async function provisionAgentInAgency (agentName, protocolType, agencyUrl, seed,
logger.info('Running with builtin wallet.')
}

if (await isPortReachable(url.parse(webhookUrl).port, { host: url.parse(webhookUrl).hostname })) { // eslint-disable-line
provisionConfig.webhook_url = webhookUrl
logger.info(`Running with webhook notifications enabled! Webhook url = ${webhookUrl}`)
} else {
logger.info('Webhook url will not be used')
}

logger.info(`Using following config to create agent provision: ${JSON.stringify(provisionConfig, null, 2)}`)
const agentProvision = JSON.parse(await provisionAgent(JSON.stringify(provisionConfig)))
agentProvision.institution_name = agentName
Expand Down
2 changes: 1 addition & 1 deletion libvcx/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion libvcx/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]

name = "libvcx"
version = "0.9.1"
version = "0.10.0"
authors = ["Absa Group Limited", "Hyperledger Indy Contributors <hyperledger-indy@lists.hyperledger.org>"]
publish = false
description = "Absa's fork of HL LibVCX"
Expand Down
Loading

0 comments on commit ffff156

Please sign in to comment.