-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDIDCommAgent+Credentials.swift
282 lines (258 loc) · 10.5 KB
/
DIDCommAgent+Credentials.swift
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
import Core
import Combine
import Domain
import Foundation
import Logging
import JSONWebToken
public extension DIDCommAgent {
/// This function initiates a presentation request for a specific type of credential, specifying the sender's and receiver's DIDs, and any claim filters applicable.
///
/// - Parameters:
/// - type: The type of the credential for which the presentation is requested.
/// - fromDID: The decentralized identifier (DID) of the entity initiating the request.
/// - toDID: The decentralized identifier (DID) of the entity to which the request is being sent.
/// - claimFilters: A collection of filters specifying the claims required in the credential.
/// - Returns: The initiated request for presentation.
/// - Throws: EdgeAgentError, if there is a problem initiating the presentation request.
func initiatePresentationRequest(
type: CredentialType,
fromDID: DID,
toDID: DID,
claimFilters: [ClaimFilter]
) async throws -> RequestPresentation {
let rqstStr = try await edgeAgent.initiatePresentationRequest(
type: type,
fromDID: fromDID,
toDID: toDID,
claimFilters: claimFilters
)
let attachment: AttachmentDescriptor
switch type {
case .jwt:
let data = try AttachmentBase64(base64: rqstStr.tryToData().base64URLEncoded())
attachment = AttachmentDescriptor(
mediaType: "application/json",
data: data,
format: "dif/presentation-exchange/[email protected]"
)
case .anoncred:
let data = try AttachmentBase64(base64: rqstStr.tryToData().base64URLEncoded())
attachment = AttachmentDescriptor(
mediaType: "application/json",
data: data,
format: "anoncreds/[email protected]"
)
}
return RequestPresentation(
body: .init(
proofTypes: [ProofTypes(
schema: "",
requiredFields: claimFilters.flatMap(\.paths),
trustIssuers: nil
)]
),
attachments: [attachment],
thid: nil,
from: fromDID,
to: toDID
)
}
/// This function verifies the presentation contained within a message.
///
/// - Parameters:
/// - message: The message containing the presentation to be verified.
/// - Returns: A Boolean value indicating whether the presentation is valid (`true`) or not (`false`).
/// - Throws: EdgeAgentError, if there is a problem verifying the presentation.
func verifyPresentation(message: Message) async throws -> Bool {
do {
let downloader = DownloadDataWithResolver(castor: castor)
guard
let attachment = message.attachments.first,
let requestId = message.thid
else {
throw PolluxError.couldNotFindPresentationInAttachments
}
let jsonData: Data
switch attachment.data {
case let attchedData as AttachmentBase64:
guard let decoded = Data(fromBase64URL: attchedData.base64) else {
throw CommonError.invalidCoding(message: "Invalid base64 url attachment")
}
jsonData = decoded
case let attchedData as AttachmentJsonData:
jsonData = attchedData.data
default:
throw EdgeAgentError.invalidAttachmentFormat(nil)
}
guard let format = attachment.format else {
throw EdgeAgentError.invalidAttachmentFormat(nil)
}
return try await pollux.verifyPresentation(
type: format,
presentationPayload: jsonData,
options: [
.presentationRequestId(requestId),
.credentialDefinitionDownloader(downloader: downloader),
.schemaDownloader(downloader: downloader)
])
} catch {
logger.error(error: error)
throw error
}
}
/// This function parses an issued credential message, stores and returns the verifiable credential.
///
/// - Parameters:
/// - message: Issue credential Message.
/// - Returns: The parsed verifiable credential.
/// - Throws: EdgeAgentError, if there is a problem parsing the credential.
func processIssuedCredentialMessage(message: IssueCredential3_0) async throws -> Credential {
guard
let linkSecret = try await pluto.getLinkSecret().first().await()
else { throw EdgeAgentError.cannotFindDIDKeyPairIndex }
let restored = try await self.apollo.restoreKey(linkSecret)
guard
let linkSecretString = String(data: restored.raw, encoding: .utf8)
else { throw EdgeAgentError.cannotFindDIDKeyPairIndex }
let downloader = DownloadDataWithResolver(castor: castor)
guard
let attachment = message.attachments.first,
let format = attachment.format
else {
throw PolluxError.unsupportedIssuedMessage
}
let jsonData: Data
switch attachment.data {
case let attchedData as AttachmentBase64:
guard let decoded = Data(fromBase64URL: attchedData.base64) else {
throw CommonError.invalidCoding(message: "Invalid base64 url attachment")
}
jsonData = decoded
case let attchedData as AttachmentJsonData:
jsonData = attchedData.data
default:
throw EdgeAgentError.invalidAttachmentFormat(nil)
}
let credential = try await pollux.parseCredential(
type: format,
credentialPayload: jsonData,
options: [
.linkSecret(id: "", secret: linkSecretString),
.credentialDefinitionDownloader(downloader: downloader),
.schemaDownloader(downloader: downloader)
]
)
guard let storableCredential = credential.storable else {
return credential
}
try await pluto
.storeCredential(credential: storableCredential)
.first()
.await()
return credential
}
/// This function prepares a request credential from an offer given the subject DID.
///
/// - Parameters:
/// - did: Subject DID.
/// - did: Received offer credential.
/// - Returns: Created request credential
/// - Throws: EdgeAgentError, if there is a problem creating the request credential.
func prepareRequestCredentialWithIssuer(did: DID, offer: OfferCredential3_0) async throws -> RequestCredential3_0? {
guard did.method == "prism" else { throw PolluxError.invalidPrismDID }
let didInfo = try await pluto
.getDIDInfo(did: did)
.first()
.await()
guard let storedPrivateKey = didInfo?.privateKeys.first else { throw EdgeAgentError.cannotFindDIDKeyPairIndex }
let privateKey = try await apollo.restorePrivateKey(storedPrivateKey)
guard
let exporting = privateKey.exporting,
let linkSecret = try await pluto.getLinkSecret().first().await()
else { throw EdgeAgentError.cannotFindDIDKeyPairIndex }
let restored = try await self.apollo.restoreKey(linkSecret)
guard
let linkSecretString = String(data: restored.raw, encoding: .utf8)
else { throw EdgeAgentError.cannotFindDIDKeyPairIndex }
let downloader = DownloadDataWithResolver(castor: castor)
guard
let attachment = offer.attachments.first,
let offerFormat = attachment.format
else {
throw PolluxError.unsupportedIssuedMessage
}
let jsonData: Data
switch attachment.data {
case let attchedData as AttachmentBase64:
guard let decoded = Data(fromBase64URL: attchedData.base64) else {
throw CommonError.invalidCoding(message: "Invalid base64 url attachment")
}
jsonData = decoded
case let attchedData as AttachmentJsonData:
jsonData = attchedData.data
default:
throw EdgeAgentError.invalidAttachmentFormat(nil)
}
let requestString = try await pollux.processCredentialRequest(
type: offerFormat,
offerPayload: jsonData,
options: [
.exportableKey(exporting),
.subjectDID(did),
.linkSecret(id: did.string, secret: linkSecretString),
.credentialDefinitionDownloader(downloader: downloader),
.schemaDownloader(downloader: downloader)
]
)
guard
let base64String = requestString.data(using: .utf8)?.base64EncodedString()
else {
throw CommonError.invalidCoding(message: "Could not encode to base64")
}
guard
let offerPiuri = ProtocolTypes(rawValue: offer.type)
else {
throw EdgeAgentError.invalidMessageType(
type: offer.type,
shouldBe: [
ProtocolTypes.didcommOfferCredential3_0.rawValue
]
)
}
let format: String
switch offerFormat {
case "prism/jwt":
format = "prism/jwt"
case "vc+sd-jwt":
format = "vc+sd-jwt"
case "anoncreds/[email protected]":
format = "anoncreds/[email protected]"
default:
throw EdgeAgentError.invalidMessageType(
type: offerFormat,
shouldBe: [
"prism/jwt",
"anoncreds/[email protected]"
]
)
}
let type = offerPiuri == .didcommOfferCredential ?
ProtocolTypes.didcommRequestCredential :
ProtocolTypes.didcommRequestCredential3_0
let requestCredential = RequestCredential3_0(
body: .init(
goalCode: offer.body.goalCode,
comment: offer.body.comment
),
type: type.rawValue,
attachments: [.init(
data: AttachmentBase64(base64: base64String),
format: format
)],
thid: offer.thid,
from: offer.to,
to: offer.from
)
return requestCredential
}
}