-
Notifications
You must be signed in to change notification settings - Fork 13
/
agent.ts
579 lines (485 loc) · 15.4 KB
/
agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import {
AnonCredsModule,
LegacyIndyCredentialFormatService,
LegacyIndyProofFormatService,
V1CredentialProtocol,
V1ProofProtocol
} from '@aries-framework/anoncreds';
import {
IndySdkAnonCredsRegistry,
IndySdkModule,
IndySdkIndyDidRegistrar,
IndySdkSovDidResolver,
IndySdkIndyDidResolver
} from '@aries-framework/indy-sdk'
var indySdk = require('indy-sdk')
// import { ariesAskar } from '@hyperledger/aries-askar-react-native'
// import { AskarModule } from '@aries-framework/askar'
import {
Agent,
BasicMessageEventTypes,
ConnectionEventTypes,
ConsoleLogger,
CredentialEventTypes,
CredentialsModule,
CredentialState,
DidCommMimeType,
DidExchangeState,
DidsModule,
HttpOutboundTransport,
LogLevel,
MediationRecipientModule,
MediatorPickupStrategy,
ProofEventTypes,
ProofsModule,
ProofState,
TransportEventTypes,
TrustPingEventTypes,
V2CredentialProtocol,
V2ProofProtocol,
WsOutboundTransport
} from '@aries-framework/core';
import {
agentDependencies,
HttpInboundTransport
} from '@aries-framework/node';
var config = require('./config.js')
var deferred = require('deferred')
var process = require('process')
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const legacyIndyCredentialFormat = new LegacyIndyCredentialFormatService()
const legacyIndyProofFormat = new LegacyIndyProofFormatService()
function generateString(length) {
let result = ''
const charactersLength = characters.length
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}
return result
}
const initializeAgent = async (withMediation, port, agentConfig = null) => {
// Simple agent configuration. This sets some basic fields like the wallet
// configuration and the label. It also sets the mediator invitation url,
// because this is most likely required in a mobile environment.
let mediation_url = config.mediation_url
let endpoints = ['http://' + config.agent_ip + ':' + port]
if (!agentConfig || agentConfig === null || agentConfig.length === 0) {
agentConfig = {
label: generateString(14),
walletConfig: {
id: generateString(32),
key: generateString(32),
},
autoAcceptConnections: true,
endpoints: endpoints,
autoAcceptInvitation: true,
// logger: new ConsoleLogger(LogLevel.trace),
didCommMimeType: DidCommMimeType.V0,
}
}
let modules = {
indySdk: new IndySdkModule({
indySdk,
networks: [config.ledger]
}),
// askar: new AskarModule({
// ariesAskar,
// }),
mediationRecipient: new MediationRecipientModule({
mediatorInvitationUrl: mediation_url,
// mediatorPickupStrategy: MediatorPickupStrategy.PickUpV2,
mediatorPickupStrategy: MediatorPickupStrategy.Implicit,
}),
anoncreds: new AnonCredsModule({
registries: [new IndySdkAnonCredsRegistry()],
}),
proofs: new ProofsModule({
proofProtocols: [
new V1ProofProtocol({
indyProofFormat: legacyIndyProofFormat,
}),
new V2ProofProtocol({
proofFormats: [legacyIndyProofFormat],
}),
],
}),
credentials: new CredentialsModule({
credentialProtocols: [
new V1CredentialProtocol({
indyCredentialFormat: legacyIndyCredentialFormat,
}),
new V2CredentialProtocol({
credentialFormats: [legacyIndyCredentialFormat],
}),
],
}),
dids: new DidsModule({
registrars: [new IndySdkIndyDidRegistrar()],
resolvers: [new IndySdkSovDidResolver(), new IndySdkIndyDidResolver()],
})
}
// configure mediator or endpoints
if (withMediation) {
delete agentConfig['endpoints']
} else {
delete modules['mediationRecipient']
}
// A new instance of an agent is created here
const agent = new Agent({
config: agentConfig,
dependencies: agentDependencies,
modules: modules
})
// Register a simple `WebSocket` outbound transport
agent.registerOutboundTransport(new WsOutboundTransport())
// Register a simple `Http` outbound transport
agent.registerOutboundTransport(new HttpOutboundTransport())
if (withMediation) {
// wait for medation to be configured
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
var onConnectedMediation = async (event) => {
let mediatorConnection = null
let interval = 100;
for (let i = 0; i < (timeout - interval); i++)
{
// OutboundWebSocketOpenedEvent occurs before mediation is finalized, so we want to check
// for the default mediation connection until it is not null or we hit a timeout
// we sleep a small amount between requests just to be kind to our CPU.
await new Promise(r => setTimeout(r, interval))
mediatorConnection = await agent.mediationRecipient.findDefaultMediatorConnection()
if (mediatorConnection != null) {
break;
}
}
if (event.payload.connectionId === mediatorConnection?.id) {
def.resolve(true)
// we no longer need to listen to the event
agent.events.off(
TransportEventTypes.OutboundWebSocketOpenedEvent,
onConnectedMediation
)
}
}
agent.events.on(
TransportEventTypes.OutboundWebSocketOpenedEvent,
onConnectedMediation
)
// Initialize the agent
await agent.initialize()
// wait for ws to be configured
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// we no longer need to listen to the event in case of failure
agent.events.off(
TransportEventTypes.OutboundWebSocketOpenedEvent,
onConnectedMediation
)
throw 'Mediator timeout!'
}
} else {
agent.registerInboundTransport(
new HttpInboundTransport({ port: port })
)
await agent.initialize()
}
return [agent, agentConfig]
}
const pingMediator = async (agent) => {
// Find mediator
// wait for the ping
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
var onPingResponse = async (event) => {
const mediatorConnection =
await agent.mediationRecipient.findDefaultMediatorConnection()
if (event.payload.connectionRecord.id === mediatorConnection?.id) {
// we no longer need to listen to the event
agent.events.off(
TrustPingEventTypes.TrustPingResponseReceivedEvent,
onPingResponse
)
def.resolve(true)
}
}
agent.events.on(
TrustPingEventTypes.TrustPingResponseReceivedEvent,
onPingResponse
)
let mediatorConnection =
await agent.mediationRecipient.findDefaultMediatorConnection()
if (mediatorConnection) {
//await agent.connections.acceptResponse(mediatorConnection.id)
await agent.connections.sendPing(mediatorConnection.id, {})
}
// wait for ping repsonse
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// we no longer need to listen to the event in case of failure
agent.events.off(
TrustPingEventTypes.TrustPingResponseReceivedEvent,
onPingResponse
)
throw 'Mediator timeout!'
}
}
let deleteOobRecordById = async (agent, id) => {
try {
const resp = await agent.oob.deleteById(id);
} catch (error) {
process.stderr.write('ERROR'+ '\n' + error + '\n')
}
};
let receiveInvitation = async (agent, invitationUrl) => {
// wait for the connection
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
var onConnection = async (event) => {
{
let payload = event.payload
if (
payload.connectionRecord.state === DidExchangeState.Completed
) {
// the connection is now ready for usage in other protocols!
// console.log(`Connection for out-of-band id ${payload.connectionRecord.outOfBandId} completed`)
// Custom business logic can be included here
// In this example we can send a basic message to the connection, but
// anything is possible
agent.events.off(
ConnectionEventTypes.ConnectionStateChanged,
onConnection
)
def.resolve(true)
}
}
}
agent.events.on(
ConnectionEventTypes.ConnectionStateChanged,
onConnection
)
const { outOfBandRecord } = await agent.oob.receiveInvitationFromUrl(
invitationUrl
)
// wait for connection
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// we no longer need to listen to the event in case of failure
agent.events.off(
ConnectionEventTypes.ConnectionStateChanged,
onConnection
)
throw 'Connection timeout!'
}
return outOfBandRecord
}
let receiveCredential = async (agent) => {
// wait for the ping
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
let onCredential = async (event) => {
let payload = event.payload
switch (payload.credentialRecord.state) {
case CredentialState.OfferReceived:
//console.log('received a credential')
// custom logic here
await agent.credentials.acceptOffer({
credentialRecordId: payload.credentialRecord.id,
})
break
case CredentialState.CredentialReceived:
//console.log(`Credential for credential id ${payload.credentialRecord.id} is accepted`)
// For demo purposes we exit the program here.
agent.events.off(
CredentialEventTypes.CredentialStateChanged,
onCredential
)
def.resolve(true)
break
}
}
agent.events.on(
CredentialEventTypes.CredentialStateChanged,
onCredential
)
// Nothing for us to do
// wait for credential
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// we no longer need to listen to the event in case of failure
agent.events.off(
CredentialEventTypes.CredentialStateChanged,
onCredential
)
throw 'Credential timeout!'
}
}
let presentationExchange = async (agent) => {
// wait for the ping
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
let onRequest = async (event) => {
let payload = event.payload
switch (payload.proofRecord.state) {
case ProofState.RequestReceived:
const requestedCredentials =
await agent.proofs.selectCredentialsForRequest({
proofRecordId: payload.proofRecord.id,
// config: {
// filterByPresentationPreview: true,
// },
})
await agent.proofs.acceptRequest({
proofRecordId: payload.proofRecord.id,
proofFormats: requestedCredentials.proofFormats,
})
agent.events.off(ProofEventTypes.ProofStateChanged, onRequest)
def.resolve(true)
break
}
}
agent.events.on(ProofEventTypes.ProofStateChanged, onRequest)
// Wait for presentation
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// No longer need to listen to the event in case of failure
agent.events.off(ProofEventTypes.ProofStateChanged, onRequest)
throw 'Presentation timeout!'
}
}
let receiveMessage = async (agent) => {
// wait for the ping
let timeout = config.verified_timeout_seconds * 1000
const TimeDelay = new Promise((resolve, reject) => {
setTimeout(resolve, timeout, false)
})
var def = deferred()
let onMessage = async (event) => {
let payload = event.payload
// console.error(payload)
agent.events.off(
BasicMessageEventTypes.BasicMessageStateChanged,
onMessage
)
def.resolve(true)
}
agent.events.on(
BasicMessageEventTypes.BasicMessageStateChanged,
onMessage
)
// Nothing for us to do
// wait for credential
let value = await Promise.race([TimeDelay, def.promise])
if (!value) {
// we no longer need to listen to the event in case of failure
agent.events.off(
BasicMessageEventTypes.BasicMessageStateChanged,
onMessage
)
throw 'Message timeout!'
}
}
var readline = require('readline')
var rl = readline.createInterface(process.stdin, null)
var agent = null
var agentConfig = null
rl.setPrompt('')
rl.prompt(false)
const handleError = async (e) => {
process.stdout.write(JSON.stringify({ error: 1, result: e }) + '\n')
}
rl.on('line', async (line) => {
try {
var command = JSON.parse(line)
if (command['cmd'] == 'start') {
[agent, agentConfig] = await initializeAgent(
command['withMediation'],
command['port'],
command['agentConfig']
)
// if (command["agentConfig"] === null || !command["agentConfig"]) {
// [agent, agentConfig] = await initializeAgent(
// command["withMediation"],
// command["port"]
// );
// } else {
// [agent, agentConfig] = await initializeAgent();
// }
// process.stdout.write(
// JSON.stringify({ error: 0, result: "Initialized agent..." }) + "\n"
// );
process.stdout.write(
JSON.stringify({ error: 0, result: agentConfig }) + '\n'
)
} else if (command['cmd'] == 'ping_mediator') {
await pingMediator(agent)
process.stdout.write(
JSON.stringify({ error: 0, result: 'Ping Mediator' }) + '\n'
)
} else if (command['cmd'] == 'deleteOobRecordById') {
await deleteOobRecordById(agent, command['id'])
process.stdout.write(
JSON.stringify({ error: 0, result: 'Delete OOB Record' }) + '\n'
)
} else if (command['cmd'] == 'receiveInvitation') {
let connection = await receiveInvitation(agent, command['invitationUrl'])
process.stdout.write(
JSON.stringify({
error: 0,
result: 'Receive Connection',
connection: connection,
}) + '\n'
)
} else if (command['cmd'] == 'receiveCredential') {
await receiveCredential(agent)
process.stdout.write(
JSON.stringify({ error: 0, result: 'Receive Credential' }) + '\n'
)
} else if (command['cmd'] == 'presentationExchange') {
await presentationExchange(agent)
process.stdout.write(
JSON.stringify({ error: 0, result: 'Presentation Exchange' }) + '\n'
)
} else if (command['cmd'] == 'receiveMessage') {
await receiveMessage(agent)
process.stdout.write(
JSON.stringify({ error: 0, result: 'Receive Message' }) + '\n'
)
} else if (command['cmd'] == 'shutdown') {
process.stdout.write(
JSON.stringify({ error: 0, result: 'Shutting down agent' }) + '\n'
)
rl.close()
await agent.shutdown()
process.exit(1)
} else {
handleError('Invalid command')
}
} catch (e) {
if (e.name === 'JSONDecodeError') {
process.stdout.write(
JSON.stringify({ error: 0, result: 'JSONDecodeError received' }) + '\n'
)
}
handleError(e)
}
})
process.once('SIGTERM', function (code) {
process.stderr.write('SIGTERM received...' + '\n')
process.exit(1)
})