-
Notifications
You must be signed in to change notification settings - Fork 182
/
ProofService.ts
1020 lines (883 loc) · 36.9 KB
/
ProofService.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { AgentMessage } from '../../../agent/AgentMessage'
import type { InboundMessageContext } from '../../../agent/models/InboundMessageContext'
import type { Logger } from '../../../logger'
import type { ConnectionRecord } from '../../connections'
import type { AutoAcceptProof } from '../ProofAutoAcceptType'
import type { ProofStateChangedEvent } from '../ProofEvents'
import type { PresentationPreview, PresentationPreviewAttribute } from '../messages'
import type { CredDef, IndyProof, Schema } from 'indy-sdk'
import { validateOrReject } from 'class-validator'
import { inject, Lifecycle, scoped } from 'tsyringe'
import { AgentConfig } from '../../../agent/AgentConfig'
import { EventEmitter } from '../../../agent/EventEmitter'
import { InjectionSymbols } from '../../../constants'
import { Attachment, AttachmentData } from '../../../decorators/attachment/Attachment'
import { AriesFrameworkError } from '../../../error'
import { JsonEncoder } from '../../../utils/JsonEncoder'
import { JsonTransformer } from '../../../utils/JsonTransformer'
import { uuid } from '../../../utils/uuid'
import { Wallet } from '../../../wallet/Wallet'
import { AckStatus } from '../../common'
import { ConnectionService } from '../../connections'
import { CredentialUtils, Credential, CredentialRepository } from '../../credentials'
import { IndyHolderService, IndyVerifierService } from '../../indy'
import { IndyLedgerService } from '../../ledger/services/IndyLedgerService'
import { ProofEventTypes } from '../ProofEvents'
import { ProofState } from '../ProofState'
import {
INDY_PROOF_ATTACHMENT_ID,
INDY_PROOF_REQUEST_ATTACHMENT_ID,
PresentationAckMessage,
PresentationMessage,
ProposePresentationMessage,
RequestPresentationMessage,
} from '../messages'
import {
AttributeFilter,
PartialProof,
ProofAttributeInfo,
ProofPredicateInfo,
ProofRequest,
RequestedAttribute,
RequestedCredentials,
RequestedPredicate,
RetrievedCredentials,
} from '../models'
import { ProofRepository } from '../repository'
import { ProofRecord } from '../repository/ProofRecord'
/**
* @todo add method to check if request matches proposal. Useful to see if a request I received is the same as the proposal I sent.
* @todo add method to reject / revoke messages
* @todo validate attachments / messages
*/
@scoped(Lifecycle.ContainerScoped)
export class ProofService {
private proofRepository: ProofRepository
private credentialRepository: CredentialRepository
private ledgerService: IndyLedgerService
private wallet: Wallet
private logger: Logger
private indyHolderService: IndyHolderService
private indyVerifierService: IndyVerifierService
private connectionService: ConnectionService
private eventEmitter: EventEmitter
public constructor(
proofRepository: ProofRepository,
ledgerService: IndyLedgerService,
@inject(InjectionSymbols.Wallet) wallet: Wallet,
agentConfig: AgentConfig,
indyHolderService: IndyHolderService,
indyVerifierService: IndyVerifierService,
connectionService: ConnectionService,
eventEmitter: EventEmitter,
credentialRepository: CredentialRepository
) {
this.proofRepository = proofRepository
this.credentialRepository = credentialRepository
this.ledgerService = ledgerService
this.wallet = wallet
this.logger = agentConfig.logger
this.indyHolderService = indyHolderService
this.indyVerifierService = indyVerifierService
this.connectionService = connectionService
this.eventEmitter = eventEmitter
}
/**
* Create a {@link ProposePresentationMessage} not bound to an existing presentation exchange.
* To create a proposal as response to an existing presentation exchange, use {@link ProofService.createProposalAsResponse}.
*
* @param connectionRecord The connection for which to create the presentation proposal
* @param presentationProposal The presentation proposal to include in the message
* @param config Additional configuration to use for the proposal
* @returns Object containing proposal message and associated proof record
*
*/
public async createProposal(
connectionRecord: ConnectionRecord,
presentationProposal: PresentationPreview,
config?: {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
): Promise<ProofProtocolMsgReturnType<ProposePresentationMessage>> {
// Assert
connectionRecord.assertReady()
// Create message
const proposalMessage = new ProposePresentationMessage({
comment: config?.comment,
presentationProposal,
})
// Create record
const proofRecord = new ProofRecord({
connectionId: connectionRecord.id,
threadId: proposalMessage.threadId,
state: ProofState.ProposalSent,
proposalMessage,
autoAcceptProof: config?.autoAcceptProof,
})
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
return { message: proposalMessage, proofRecord }
}
/**
* Create a {@link ProposePresentationMessage} as response to a received presentation request.
* To create a proposal not bound to an existing presentation exchange, use {@link ProofService.createProposal}.
*
* @param proofRecord The proof record for which to create the presentation proposal
* @param presentationProposal The presentation proposal to include in the message
* @param config Additional configuration to use for the proposal
* @returns Object containing proposal message and associated proof record
*
*/
public async createProposalAsResponse(
proofRecord: ProofRecord,
presentationProposal: PresentationPreview,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<ProposePresentationMessage>> {
// Assert
proofRecord.assertState(ProofState.RequestReceived)
// Create message
const proposalMessage = new ProposePresentationMessage({
comment: config?.comment,
presentationProposal,
})
proposalMessage.setThread({ threadId: proofRecord.threadId })
// Update record
proofRecord.proposalMessage = proposalMessage
this.updateState(proofRecord, ProofState.ProposalSent)
return { message: proposalMessage, proofRecord }
}
/**
* Decline a proof request
* @param proofRecord The proof request to be declined
*/
public async declineRequest(proofRecord: ProofRecord): Promise<ProofRecord> {
proofRecord.assertState(ProofState.RequestReceived)
await this.updateState(proofRecord, ProofState.Declined)
return proofRecord
}
/**
* Process a received {@link ProposePresentationMessage}. This will not accept the presentation proposal
* or send a presentation request. It will only create a new, or update the existing proof record with
* the information from the presentation proposal message. Use {@link ProofService.createRequestAsResponse}
* after calling this method to create a presentation request.
*
* @param messageContext The message context containing a presentation proposal message
* @returns proof record associated with the presentation proposal message
*
*/
public async processProposal(
messageContext: InboundMessageContext<ProposePresentationMessage>
): Promise<ProofRecord> {
let proofRecord: ProofRecord
const { message: proposalMessage, connection } = messageContext
this.logger.debug(`Processing presentation proposal with id ${proposalMessage.id}`)
try {
// Proof record already exists
proofRecord = await this.getByThreadAndConnectionId(proposalMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.RequestSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.proposalMessage,
previousSentMessage: proofRecord.requestMessage,
})
// Update record
proofRecord.proposalMessage = proposalMessage
await this.updateState(proofRecord, ProofState.ProposalReceived)
} catch {
// No proof record exists with thread id
proofRecord = new ProofRecord({
connectionId: connection?.id,
threadId: proposalMessage.threadId,
proposalMessage,
state: ProofState.ProposalReceived,
})
// Assert
this.connectionService.assertConnectionOrServiceDecorator(messageContext)
// Save record
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: {
proofRecord,
previousState: null,
},
})
}
return proofRecord
}
/**
* Create a {@link RequestPresentationMessage} as response to a received presentation proposal.
* To create a request not bound to an existing presentation exchange, use {@link ProofService.createRequest}.
*
* @param proofRecord The proof record for which to create the presentation request
* @param proofRequest The proof request to include in the message
* @param config Additional configuration to use for the request
* @returns Object containing request message and associated proof record
*
*/
public async createRequestAsResponse(
proofRecord: ProofRecord,
proofRequest: ProofRequest,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<RequestPresentationMessage>> {
// Assert
proofRecord.assertState(ProofState.ProposalReceived)
// Create message
const attachment = new Attachment({
id: INDY_PROOF_REQUEST_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proofRequest),
}),
})
const requestPresentationMessage = new RequestPresentationMessage({
comment: config?.comment,
requestPresentationAttachments: [attachment],
})
requestPresentationMessage.setThread({
threadId: proofRecord.threadId,
})
// Update record
proofRecord.requestMessage = requestPresentationMessage
await this.updateState(proofRecord, ProofState.RequestSent)
return { message: requestPresentationMessage, proofRecord }
}
/**
* Create a {@link RequestPresentationMessage} not bound to an existing presentation exchange.
* To create a request as response to an existing presentation exchange, use {@link ProofService#createRequestAsResponse}.
*
* @param proofRequestTemplate The proof request template
* @param connectionRecord The connection for which to create the presentation request
* @returns Object containing request message and associated proof record
*
*/
public async createRequest(
proofRequest: ProofRequest,
connectionRecord?: ConnectionRecord,
config?: {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
): Promise<ProofProtocolMsgReturnType<RequestPresentationMessage>> {
this.logger.debug(`Creating proof request`)
// Assert
connectionRecord?.assertReady()
// Create message
const attachment = new Attachment({
id: INDY_PROOF_REQUEST_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proofRequest),
}),
})
const requestPresentationMessage = new RequestPresentationMessage({
comment: config?.comment,
requestPresentationAttachments: [attachment],
})
// Create record
const proofRecord = new ProofRecord({
connectionId: connectionRecord?.id,
threadId: requestPresentationMessage.threadId,
requestMessage: requestPresentationMessage,
state: ProofState.RequestSent,
autoAcceptProof: config?.autoAcceptProof,
})
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
return { message: requestPresentationMessage, proofRecord }
}
/**
* Process a received {@link RequestPresentationMessage}. This will not accept the presentation request
* or send a presentation. It will only create a new, or update the existing proof record with
* the information from the presentation request message. Use {@link ProofService.createPresentation}
* after calling this method to create a presentation.
*
* @param messageContext The message context containing a presentation request message
* @returns proof record associated with the presentation request message
*
*/
public async processRequest(messageContext: InboundMessageContext<RequestPresentationMessage>): Promise<ProofRecord> {
let proofRecord: ProofRecord
const { message: proofRequestMessage, connection } = messageContext
this.logger.debug(`Processing presentation request with id ${proofRequestMessage.id}`)
const proofRequest = proofRequestMessage.indyProofRequest
// Assert attachment
if (!proofRequest) {
throw new AriesFrameworkError(
`Missing required base64 encoded attachment data for presentation request with thread id ${proofRequestMessage.threadId}`
)
}
await validateOrReject(proofRequest)
this.logger.debug('received proof request', proofRequest)
try {
// Proof record already exists
proofRecord = await this.getByThreadAndConnectionId(proofRequestMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.ProposalSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.requestMessage,
previousSentMessage: proofRecord.proposalMessage,
})
// Update record
proofRecord.requestMessage = proofRequestMessage
await this.updateState(proofRecord, ProofState.RequestReceived)
} catch {
// No proof record exists with thread id
proofRecord = new ProofRecord({
connectionId: connection?.id,
threadId: proofRequestMessage.threadId,
requestMessage: proofRequestMessage,
state: ProofState.RequestReceived,
})
// Assert
this.connectionService.assertConnectionOrServiceDecorator(messageContext)
// Save in repository
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
}
return proofRecord
}
/**
* Create a {@link PresentationMessage} as response to a received presentation request.
*
* @param proofRecord The proof record for which to create the presentation
* @param requestedCredentials The requested credentials object specifying which credentials to use for the proof
* @param config Additional configuration to use for the presentation
* @returns Object containing presentation message and associated proof record
*
*/
public async createPresentation(
proofRecord: ProofRecord,
requestedCredentials: RequestedCredentials,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<PresentationMessage>> {
this.logger.debug(`Creating presentation for proof record with id ${proofRecord.id}`)
// Assert
proofRecord.assertState(ProofState.RequestReceived)
const indyProofRequest = proofRecord.requestMessage?.indyProofRequest
if (!indyProofRequest) {
throw new AriesFrameworkError(
`Missing required base64 encoded attachment data for presentation with thread id ${proofRecord.threadId}`
)
}
// Get the matching attachments to the requested credentials
const attachments = await this.getRequestedAttachmentsForRequestedCredentials(
indyProofRequest,
requestedCredentials
)
// Create proof
const proof = await this.createProof(indyProofRequest, requestedCredentials)
// Create message
const attachment = new Attachment({
id: INDY_PROOF_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proof),
}),
})
const presentationMessage = new PresentationMessage({
comment: config?.comment,
presentationAttachments: [attachment],
attachments,
})
presentationMessage.setThread({ threadId: proofRecord.threadId })
// Update record
proofRecord.presentationMessage = presentationMessage
await this.updateState(proofRecord, ProofState.PresentationSent)
return { message: presentationMessage, proofRecord }
}
/**
* Process a received {@link PresentationMessage}. This will not accept the presentation
* or send a presentation acknowledgement. It will only update the existing proof record with
* the information from the presentation message. Use {@link ProofService.createAck}
* after calling this method to create a presentation acknowledgement.
*
* @param messageContext The message context containing a presentation message
* @returns proof record associated with the presentation message
*
*/
public async processPresentation(messageContext: InboundMessageContext<PresentationMessage>): Promise<ProofRecord> {
const { message: presentationMessage, connection } = messageContext
this.logger.debug(`Processing presentation with id ${presentationMessage.id}`)
const proofRecord = await this.getByThreadAndConnectionId(presentationMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.RequestSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.proposalMessage,
previousSentMessage: proofRecord.requestMessage,
})
// TODO: add proof class with validator
const indyProofJson = presentationMessage.indyProof
const indyProofRequest = proofRecord.requestMessage?.indyProofRequest
if (!indyProofJson) {
throw new AriesFrameworkError(
`Missing required base64 encoded attachment data for presentation with thread id ${presentationMessage.threadId}`
)
}
if (!indyProofRequest) {
throw new AriesFrameworkError(
`Missing required base64 encoded attachment data for presentation request with thread id ${presentationMessage.threadId}`
)
}
const isValid = await this.verifyProof(indyProofJson, indyProofRequest)
// Update record
proofRecord.isVerified = isValid
proofRecord.presentationMessage = presentationMessage
await this.updateState(proofRecord, ProofState.PresentationReceived)
return proofRecord
}
/**
* Create a {@link PresentationAckMessage} as response to a received presentation.
*
* @param proofRecord The proof record for which to create the presentation acknowledgement
* @returns Object containing presentation acknowledgement message and associated proof record
*
*/
public async createAck(proofRecord: ProofRecord): Promise<ProofProtocolMsgReturnType<PresentationAckMessage>> {
this.logger.debug(`Creating presentation ack for proof record with id ${proofRecord.id}`)
// Assert
proofRecord.assertState(ProofState.PresentationReceived)
// Create message
const ackMessage = new PresentationAckMessage({
status: AckStatus.OK,
threadId: proofRecord.threadId,
})
// Update record
await this.updateState(proofRecord, ProofState.Done)
return { message: ackMessage, proofRecord }
}
/**
* Process a received {@link PresentationAckMessage}.
*
* @param messageContext The message context containing a presentation acknowledgement message
* @returns proof record associated with the presentation acknowledgement message
*
*/
public async processAck(messageContext: InboundMessageContext<PresentationAckMessage>): Promise<ProofRecord> {
const { message: presentationAckMessage, connection } = messageContext
this.logger.debug(`Processing presentation ack with id ${presentationAckMessage.id}`)
const proofRecord = await this.getByThreadAndConnectionId(presentationAckMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.PresentationSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.requestMessage,
previousSentMessage: proofRecord.presentationMessage,
})
// Update record
await this.updateState(proofRecord, ProofState.Done)
return proofRecord
}
public async generateProofRequestNonce() {
return this.wallet.generateNonce()
}
/**
* Create a {@link ProofRequest} from a presentation proposal. This method can be used to create the
* proof request from a received proposal for use in {@link ProofService.createRequestAsResponse}
*
* @param presentationProposal The presentation proposal to create a proof request from
* @param config Additional configuration to use for the proof request
* @returns proof request object
*
*/
public async createProofRequestFromProposal(
presentationProposal: PresentationPreview,
config: { name: string; version: string; nonce?: string }
): Promise<ProofRequest> {
const nonce = config.nonce ?? (await this.generateProofRequestNonce())
const proofRequest = new ProofRequest({
name: config.name,
version: config.version,
nonce,
})
/**
* Create mapping of attributes by referent. This required the
* attributes to come from the same credential.
* @see https://github.com/hyperledger/aries-rfcs/blob/master/features/0037-present-proof/README.md#referent
*
* {
* "referent1": [Attribute1, Attribute2],
* "referent2": [Attribute3]
* }
*/
const attributesByReferent: Record<string, PresentationPreviewAttribute[]> = {}
for (const proposedAttributes of presentationProposal.attributes) {
if (!proposedAttributes.referent) proposedAttributes.referent = uuid()
const referentAttributes = attributesByReferent[proposedAttributes.referent]
// Referent key already exist, add to list
if (referentAttributes) {
referentAttributes.push(proposedAttributes)
}
// Referent key does not exist yet, create new entry
else {
attributesByReferent[proposedAttributes.referent] = [proposedAttributes]
}
}
// Transform attributes by referent to requested attributes
for (const [referent, proposedAttributes] of Object.entries(attributesByReferent)) {
// Either attributeName or attributeNames will be undefined
const attributeName = proposedAttributes.length == 1 ? proposedAttributes[0].name : undefined
const attributeNames = proposedAttributes.length > 1 ? proposedAttributes.map((a) => a.name) : undefined
const requestedAttribute = new ProofAttributeInfo({
name: attributeName,
names: attributeNames,
restrictions: [
new AttributeFilter({
credentialDefinitionId: proposedAttributes[0].credentialDefinitionId,
}),
],
})
proofRequest.requestedAttributes.set(referent, requestedAttribute)
}
this.logger.debug('proposal predicates', presentationProposal.predicates)
// Transform proposed predicates to requested predicates
for (const proposedPredicate of presentationProposal.predicates) {
const requestedPredicate = new ProofPredicateInfo({
name: proposedPredicate.name,
predicateType: proposedPredicate.predicate,
predicateValue: proposedPredicate.threshold,
restrictions: [
new AttributeFilter({
credentialDefinitionId: proposedPredicate.credentialDefinitionId,
}),
],
})
proofRequest.requestedPredicates.set(uuid(), requestedPredicate)
}
return proofRequest
}
/**
* Retrieves the linked attachments for an {@link indyProofRequest}
* @param indyProofRequest The proof request for which the linked attachments have to be found
* @param requestedCredentials The requested credentials
* @returns a list of attachments that are linked to the requested credentials
*/
public async getRequestedAttachmentsForRequestedCredentials(
indyProofRequest: ProofRequest,
requestedCredentials: RequestedCredentials
): Promise<Attachment[] | undefined> {
const attachments: Attachment[] = []
const credentialIds = new Set<string>()
const requestedAttributesNames: (string | undefined)[] = []
// Get the credentialIds if it contains a hashlink
for (const [referent, requestedAttribute] of Object.entries(requestedCredentials.requestedAttributes)) {
// Find the requested Attributes
const requestedAttributes = indyProofRequest.requestedAttributes.get(referent) as ProofAttributeInfo
// List the requested attributes
requestedAttributesNames.push(...(requestedAttributes.names ?? [requestedAttributes.name]))
// Find the attributes that have a hashlink as a value
for (const attribute of Object.values(requestedAttribute.credentialInfo.attributes)) {
if (attribute.toLowerCase().startsWith('hl:')) {
credentialIds.add(requestedAttribute.credentialId)
}
}
}
// Only continues if there is an attribute value that contains a hashlink
for (const credentialId of credentialIds) {
// Get the credentialRecord that matches the ID
const credentialRecord = await this.credentialRepository.getSingleByQuery({ credentialId })
if (credentialRecord.linkedAttachments) {
// Get the credentials that have a hashlink as value and are requested
const requestedCredentials = credentialRecord.credentialAttributes?.filter(
(credential) =>
credential.value.toLowerCase().startsWith('hl:') && requestedAttributesNames.includes(credential.name)
)
// Get the linked attachments that match the requestedCredentials
const linkedAttachments = credentialRecord.linkedAttachments.filter((attachment) =>
requestedCredentials?.map((credential) => credential.value.split(':')[1]).includes(attachment.id)
)
if (linkedAttachments) {
attachments.push(...linkedAttachments)
}
}
}
return attachments.length ? attachments : undefined
}
/**
* Create a {@link RetrievedCredentials} object. Given input proof request and presentation proposal,
* use credentials in the wallet to build indy requested credentials object for input to proof creation.
* If restrictions allow, self attested attributes will be used.
*
*
* @param proofRequest The proof request to build the requested credentials object from
* @param presentationProposal Optional presentation proposal to improve credential selection algorithm
* @returns RetrievedCredentials object
*/
public async getRequestedCredentialsForProofRequest(
proofRequest: ProofRequest,
presentationProposal?: PresentationPreview
): Promise<RetrievedCredentials> {
const retrievedCredentials = new RetrievedCredentials({})
for (const [referent, requestedAttribute] of proofRequest.requestedAttributes.entries()) {
let credentialMatch: Credential[] = []
const credentials = await this.getCredentialsForProofRequest(proofRequest, referent)
// If we have exactly one credential, or no proposal to pick preferences
// on the credentials to use, we will use the first one
if (credentials.length === 1 || !presentationProposal) {
credentialMatch = credentials
}
// If we have a proposal we will use that to determine the credentials to use
else {
const names = requestedAttribute.names ?? [requestedAttribute.name]
// Find credentials that matches all parameters from the proposal
credentialMatch = credentials.filter((credential) => {
const { attributes, credentialDefinitionId } = credential.credentialInfo
// Check if credentials matches all parameters from proposal
return names.every((name) =>
presentationProposal.attributes.find(
(a) =>
a.name === name &&
a.credentialDefinitionId === credentialDefinitionId &&
(!a.value || a.value === attributes[name])
)
)
})
}
retrievedCredentials.requestedAttributes[referent] = credentialMatch.map((credential: Credential) => {
return new RequestedAttribute({
credentialId: credential.credentialInfo.referent,
revealed: true,
credentialInfo: credential.credentialInfo,
})
})
}
for (const [referent] of proofRequest.requestedPredicates.entries()) {
const credentials = await this.getCredentialsForProofRequest(proofRequest, referent)
retrievedCredentials.requestedPredicates[referent] = credentials.map((credential) => {
return new RequestedPredicate({
credentialId: credential.credentialInfo.referent,
credentialInfo: credential.credentialInfo,
})
})
}
return retrievedCredentials
}
/**
* Takes a RetrievedCredentials object and auto selects credentials in a RequestedCredentials object
*
* Use the return value of this method as input to {@link ProofService.createPresentation} to
* automatically accept a received presentation request.
*
* @param retrievedCredentials The retrieved credentials object to get credentials from
*
* @returns RequestedCredentials
*/
public autoSelectCredentialsForProofRequest(retrievedCredentials: RetrievedCredentials): RequestedCredentials {
const requestedCredentials = new RequestedCredentials({})
Object.keys(retrievedCredentials.requestedAttributes).forEach((attributeName) => {
const attributeArray = retrievedCredentials.requestedAttributes[attributeName]
if (attributeArray.length === 0) {
throw new AriesFrameworkError('Unable to automatically select requested attributes.')
} else {
requestedCredentials.requestedAttributes[attributeName] = attributeArray[0]
}
})
Object.keys(retrievedCredentials.requestedPredicates).forEach((attributeName) => {
if (retrievedCredentials.requestedPredicates[attributeName].length === 0) {
throw new AriesFrameworkError('Unable to automatically select requested predicates.')
} else {
requestedCredentials.requestedPredicates[attributeName] =
retrievedCredentials.requestedPredicates[attributeName][0]
}
})
return requestedCredentials
}
/**
* Verify an indy proof object. Will also verify raw values against encodings.
*
* @param proofRequest The proof request to use for proof verification
* @param proofJson The proof object to verify
* @throws {Error} If the raw values do not match the encoded values
* @returns Boolean whether the proof is valid
*
*/
public async verifyProof(proofJson: IndyProof, proofRequest: ProofRequest): Promise<boolean> {
const proof = JsonTransformer.fromJSON(proofJson, PartialProof)
for (const [referent, attribute] of proof.requestedProof.revealedAttributes.entries()) {
if (!CredentialUtils.checkValidEncoding(attribute.raw, attribute.encoded)) {
throw new AriesFrameworkError(
`The encoded value for '${referent}' is invalid. ` +
`Expected '${CredentialUtils.encode(attribute.raw)}'. ` +
`Actual '${attribute.encoded}'`
)
}
}
// TODO: pre verify proof json
// I'm not 100% sure how much indy does. Also if it checks whether the proof requests matches the proof
// @see https://github.com/hyperledger/aries-cloudagent-python/blob/master/aries_cloudagent/indy/sdk/verifier.py#L79-L164
const schemas = await this.getSchemas(new Set(proof.identifiers.map((i) => i.schemaId)))
const credentialDefinitions = await this.getCredentialDefinitions(
new Set(proof.identifiers.map((i) => i.credentialDefinitionId))
)
return await this.indyVerifierService.verifyProof({
proofRequest: proofRequest.toJSON(),
proof: proofJson,
schemas,
credentialDefinitions,
})
}
/**
* Retrieve all proof records
*
* @returns List containing all proof records
*/
public async getAll(): Promise<ProofRecord[]> {
return this.proofRepository.getAll()
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @throws {RecordNotFoundError} If no record is found
* @return The proof record
*
*/
public async getById(proofRecordId: string): Promise<ProofRecord> {
return this.proofRepository.getById(proofRecordId)
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @return The proof record or null if not found
*
*/
public async findById(proofRecordId: string): Promise<ProofRecord | null> {
return this.proofRepository.findById(proofRecordId)
}
/**
* Delete a proof record by id
*
* @param proofId the proof record id
*/
public async deleteById(proofId: string) {
const proofRecord = await this.getById(proofId)
return this.proofRepository.delete(proofRecord)
}
/**
* Retrieve a proof record by connection id and thread id
*
* @param connectionId The connection id
* @param threadId The thread id
* @throws {RecordNotFoundError} If no record is found
* @throws {RecordDuplicateError} If multiple records are found
* @returns The proof record
*/
public async getByThreadAndConnectionId(threadId: string, connectionId?: string): Promise<ProofRecord> {
return this.proofRepository.getSingleByQuery({ threadId, connectionId })
}
public update(proofRecord: ProofRecord) {
return this.proofRepository.update(proofRecord)
}
/**
* Create indy proof from a given proof request and requested credential object.
*
* @param proofRequest The proof request to create the proof for
* @param requestedCredentials The requested credentials object specifying which credentials to use for the proof
* @returns indy proof object
*/
private async createProof(
proofRequest: ProofRequest,
requestedCredentials: RequestedCredentials
): Promise<IndyProof> {
const credentialObjects = [
...Object.values(requestedCredentials.requestedAttributes),
...Object.values(requestedCredentials.requestedPredicates),
].map((c) => c.credentialInfo)
const schemas = await this.getSchemas(new Set(credentialObjects.map((c) => c.schemaId)))
const credentialDefinitions = await this.getCredentialDefinitions(
new Set(credentialObjects.map((c) => c.credentialDefinitionId))
)
const proof = await this.indyHolderService.createProof({
proofRequest: proofRequest.toJSON(),
requestedCredentials: requestedCredentials.toJSON(),
schemas,
credentialDefinitions,
})
return proof
}
private async getCredentialsForProofRequest(
proofRequest: ProofRequest,
attributeReferent: string
): Promise<Credential[]> {
const credentialsJson = await this.indyHolderService.getCredentialsForProofRequest({
proofRequest: proofRequest.toJSON(),
attributeReferent,
})
return JsonTransformer.fromJSON(credentialsJson, Credential) as unknown as Credential[]
}
/**
* Update the record to a new state and emit an state changed event. Also updates the record
* in storage.
*
* @param proofRecord The proof record to update the state for
* @param newState The state to update to
*
*/
private async updateState(proofRecord: ProofRecord, newState: ProofState) {
const previousState = proofRecord.state
proofRecord.state = newState
await this.proofRepository.update(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: previousState },
})
}
/**
* Build schemas object needed to create and verify proof objects.
*
* Creates object with `{ schemaId: Schema }` mapping
*
* @param schemaIds List of schema ids
* @returns Object containing schemas for specified schema ids
*
*/
private async getSchemas(schemaIds: Set<string>) {
const schemas: { [key: string]: Schema } = {}
for (const schemaId of schemaIds) {
const schema = await this.ledgerService.getSchema(schemaId)
schemas[schemaId] = schema
}
return schemas
}
/**
* Build credential definitions object needed to create and verify proof objects.
*
* Creates object with `{ credentialDefinitionId: CredentialDefinition }` mapping
*
* @param credentialDefinitionIds List of credential definition ids
* @returns Object containing credential definitions for specified credential definition ids
*
*/
private async getCredentialDefinitions(credentialDefinitionIds: Set<string>) {