-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCastorShared.kt
576 lines (525 loc) · 24 KB
/
CastorShared.kt
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
package io.iohk.atala.prism.walletsdk.castor.shared
import io.iohk.atala.prism.apollo.base64.base64Encoded
import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes
import io.iohk.atala.prism.apollo.base64.base64UrlEncoded
import io.iohk.atala.prism.apollo.hashing.SHA256
import io.iohk.atala.prism.apollo.hashing.internal.toHexString
import io.iohk.atala.prism.didcomm.didpeer.DIDCommServicePeerDID
import io.iohk.atala.prism.didcomm.didpeer.DIDDocPeerDID
import io.iohk.atala.prism.didcomm.didpeer.MalformedPeerDIDException
import io.iohk.atala.prism.didcomm.didpeer.ServiceEndpoint
import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialAgreement
import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialAuthentication
import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialFormatPeerDID
import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodPeerDID
import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAgreement
import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAuthentication
import io.iohk.atala.prism.didcomm.didpeer.core.toJsonElement
import io.iohk.atala.prism.didcomm.didpeer.createPeerDIDNumalgo2
import io.iohk.atala.prism.protos.AtalaOperation
import io.iohk.atala.prism.protos.CreateDIDOperation
import io.iohk.atala.prism.protos.Service
import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair
import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey
import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1KeyPair
import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey
import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair
import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PublicKey
import io.iohk.atala.prism.walletsdk.castor.DID
import io.iohk.atala.prism.walletsdk.castor.PRISM
import io.iohk.atala.prism.walletsdk.castor.did.DIDParser
import io.iohk.atala.prism.walletsdk.castor.did.DIDUrlParser
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.LongFormPrismDID
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDMethodId
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDPublicKey
import io.iohk.atala.prism.walletsdk.castor.did.prismdid.defaultId
import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo
import io.iohk.atala.prism.walletsdk.domain.models.CastorError
import io.iohk.atala.prism.walletsdk.domain.models.Curve
import io.iohk.atala.prism.walletsdk.domain.models.DID
import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument
import io.iohk.atala.prism.walletsdk.domain.models.DIDDocumentCoreProperty
import io.iohk.atala.prism.walletsdk.domain.models.DIDResolver
import io.iohk.atala.prism.walletsdk.domain.models.DIDUrl
import io.iohk.atala.prism.walletsdk.domain.models.OctetPublicKey
import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair
import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey
import io.iohk.atala.prism.walletsdk.logger.LogComponent
import io.iohk.atala.prism.walletsdk.logger.LogLevel
import io.iohk.atala.prism.walletsdk.logger.Metadata
import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import pbandk.decodeFromByteArray
import pbandk.encodeToByteArray
import kotlin.jvm.Throws
import io.iohk.atala.prism.didcomm.didpeer.resolvePeerDID as mercuryPeerDIDResolve
/**
* The `CastorShared` class provides a set of logging methods for the Castor module.
*/
internal class CastorShared {
companion object {
/**
* The logger property is a PrismLoggerImpl instance for logging purposes.
* It is used to log debug, info, warning, and error messages, along with the associated metadata.
*
* @property logger The logger instance.
*/
private val logger = PrismLoggerImpl(LogComponent.CASTOR)
/**
* parseDID parses a string representation of a Decentralized Identifier (DID) into a DID object.
*
* @param did The string representation of the DID.
* @return The [DID] object.
* @throws [CastorError.InvalidDIDString] if the string is not a valid DID.
*/
@JvmStatic
@Throws(CastorError.InvalidDIDString::class)
fun parseDID(did: String): DID {
return DIDParser.parse(did)
}
/**
* createPrismDID creates a DID for a prism (a device or server that acts as a DID owner and controller) using a
* given master public key and list of services.
*
* @param apollo the cryptography suit representation.
* @param masterPublicKey master public key used in creating the Prism DID.
* @param services list of services.
* @return [DID].
*/
@JvmStatic
internal fun createPrismDID(
apollo: Apollo,
masterPublicKey: PublicKey,
services: Array<DIDDocument.Service>?
): DID {
val atalaOperation = AtalaOperation(
operation = AtalaOperation.Operation.CreateDid(
CreateDIDOperation(
didData = CreateDIDOperation.DIDCreationData(
publicKeys = listOf(
PrismDIDPublicKey(
apollo = apollo,
id = PrismDIDPublicKey.Usage.MASTER_KEY.defaultId(),
usage = PrismDIDPublicKey.Usage.MASTER_KEY,
keyData = masterPublicKey
).toProto(),
PrismDIDPublicKey(
apollo = apollo,
id = PrismDIDPublicKey.Usage.AUTHENTICATION_KEY.defaultId(),
usage = PrismDIDPublicKey.Usage.AUTHENTICATION_KEY,
keyData = masterPublicKey
).toProto()
),
services = services?.map {
Service(
id = it.id,
type = it.type.first(),
serviceEndpoint = listOf(it.serviceEndpoint.uri)
)
} ?: emptyList()
)
)
)
)
val encodedState = atalaOperation.encodeToByteArray()
val stateHash = SHA256().digest(encodedState).toHexString()
val base64State = encodedState.base64UrlEncoded
val methodSpecificId = PrismDIDMethodId(
sections = listOf(
stateHash,
base64State
)
)
return DID(
schema = DID,
method = PRISM,
methodId = methodSpecificId.toString()
)
}
/**
* Resolve PeerDID String to [DIDDocument].
*
* @param didString that we need to resolve.
* @return [DIDDocument]
* @throws [CastorError.InvalidPeerDIDError] when the provided DID is invalid.
* @throws [CastorError.NotPossibleToResolveDID] when unable to resolve the provided DID.
*/
@JvmStatic
@Throws(CastorError.InvalidPeerDIDError::class, CastorError.NotPossibleToResolveDID::class)
internal suspend fun resolvePeerDID(didString: String): DIDDocument {
val peerDIDDocument = try {
DIDDocPeerDID.fromJson(mercuryPeerDIDResolve(didString))
} catch (e: MalformedPeerDIDException) {
throw CastorError.InvalidPeerDIDError(e.message, e.cause)
} catch (e: Throwable) {
throw CastorError.NotPossibleToResolveDID(
did = didString,
reason = "Method or method id are invalid",
e
)
}
val coreProperties: MutableList<DIDDocumentCoreProperty> = mutableListOf()
coreProperties.add(
DIDDocument.Authentication(
urls = arrayOf(),
verificationMethods = peerDIDDocument.authentication.map {
fromVerificationMethodPeerDID(it.id, it)
}.toTypedArray()
)
)
coreProperties.add(
DIDDocument.KeyAgreement(
urls = arrayOf(),
verificationMethods = peerDIDDocument.keyAgreement.map {
fromVerificationMethodPeerDID(it.id, it)
}.toTypedArray()
)
)
val peerDIDServices = peerDIDDocument.service ?: listOf()
val services: MutableList<DIDDocument.Service> = mutableListOf()
peerDIDServices.forEach { service ->
run {
if (service is DIDCommServicePeerDID) {
services.add(
DIDDocument.Service(
id = service.id,
type = arrayOf(service.type),
serviceEndpoint = DIDDocument.ServiceEndpoint(
uri = service.serviceEndpoint.uri,
accept = service.serviceEndpoint.accept.toTypedArray(),
routingKeys = service.serviceEndpoint.routingKeys.toTypedArray()
)
)
)
}
}
}
coreProperties.add(
DIDDocument.Services(
services.toTypedArray()
)
)
val did = DIDParser.parse(didString)
return DIDDocument(
id = did,
coreProperties = coreProperties.toTypedArray()
)
}
/**
* Extract the [DIDDocument.VerificationMethod] for the [did] based on the [verificationMethod].
*
* @param did string of the PeerDID
* @param verificationMethod of the PeerDID
* @return [DIDDocument.VerificationMethod]
* @throws [CastorError.InvalidKeyError] if provided [verificationMethod] is not supported.
*/
@JvmStatic
@Throws(CastorError.InvalidKeyError::class)
private fun fromVerificationMethodPeerDID(
did: String,
verificationMethod: VerificationMethodPeerDID
): DIDDocument.VerificationMethod {
val didUrl = DIDUrlParser.parse(did)
val controller = DIDParser.parse(verificationMethod.controller)
val type = when (verificationMethod.verMaterial.type.value) {
VerificationMethodTypeAuthentication.ED25519VerificationKey2020.value,
VerificationMethodTypeAuthentication.ED25519VerificationKey2018.value -> {
Curve.ED25519.value
}
VerificationMethodTypeAgreement.X25519KeyAgreementKey2020.value,
VerificationMethodTypeAgreement.X25519KeyAgreementKey2019.value -> {
Curve.X25519.value
}
else -> {
throw CastorError.InvalidKeyError()
}
}
return when (verificationMethod.verMaterial.format) {
VerificationMaterialFormatPeerDID.JWK -> {
DIDDocument.VerificationMethod(
didUrl,
controller,
type,
Json.decodeFromString<Map<String, String>>(verificationMethod.verMaterial.value as String)
)
}
VerificationMaterialFormatPeerDID.BASE58 -> {
DIDDocument.VerificationMethod(
didUrl,
controller,
type,
null,
verificationMethod.verMaterial.value as String
)
}
VerificationMaterialFormatPeerDID.MULTIBASE -> {
DIDDocument.VerificationMethod(
didUrl,
controller,
type,
null,
verificationMethod.verMaterial.value as String
)
}
}
}
/**
* Resolve Long Form of Prism DID.
*
* @param apollo the cryptography suit representation.
* @param didString The DID string we want to resolve.
* @return [DIDDocument]
* @throws [CastorError.InitialStateOfDIDChanged] when decoding the state fails.
*/
@JvmStatic
@Throws(CastorError.InitialStateOfDIDChanged::class)
internal suspend fun resolveLongFormPrismDID(apollo: Apollo, didString: String): DIDDocument {
val did = DIDParser.parse(didString)
val prismDID = LongFormPrismDID(did)
val (verificationMethods, services) = try {
decodeState(
apollo = apollo,
did = did,
stateHash = prismDID.stateHash,
encodedData = prismDID.encodedState.base64UrlDecodedBytes
)
} catch (e: Throwable) {
logger.error(
message = "The DID state hash does not match the state",
metadata = arrayOf(
Metadata.MaskedMetadataByLevel(
key = "DID",
value = didString,
level = LogLevel.DEBUG
)
)
)
throw CastorError.InitialStateOfDIDChanged(e.message)
}
val servicesProperty = DIDDocument.Services(services.toTypedArray())
val verificationMethodsProperty = DIDDocument.VerificationMethods(verificationMethods.values.toTypedArray())
val coreProperties = mutableListOf<DIDDocumentCoreProperty>()
val authenticate = verificationMethods.entries.map {
DIDDocument.Authentication(
urls = arrayOf(it.key),
verificationMethods = verificationMethods.values.toTypedArray()
)
}
authenticate.forEach {
coreProperties.add(it)
}
coreProperties.add(servicesProperty)
coreProperties.add(verificationMethodsProperty)
return DIDDocument(
id = did,
coreProperties = coreProperties.toTypedArray()
)
}
/**
* Decode the provided [encodedData] to [Pair] of a [Map] and of List<[DIDDocument.Service]> where the [Map] is
* key as [String] and its value [DIDDocument.VerificationMethod].
*
* @param apollo the cryptography suit representation.
* @param did the DID that is used in to decode.
* @param stateHash the hashed version of the [encodedData] in Hex string format.
* @param encodedData the [ByteArray]
* @return [Pair] of a [Map] and of List<[DIDDocument.Service]> where the [Map] is key as [String] and its value
* [DIDDocument.VerificationMethod].
* @throws [CastorError.InitialStateOfDIDChanged]
* @throws [Exception]
*/
@JvmStatic
@Throws(CastorError.InitialStateOfDIDChanged::class, Exception::class)
private fun decodeState(
apollo: Apollo,
did: DID,
stateHash: String,
encodedData: ByteArray
): Pair<Map<String, DIDDocument.VerificationMethod>, List<DIDDocument.Service>> {
val sha256 = SHA256()
val verifyEncodedState = sha256.digest(encodedData)
val verifyEncodedStateHex = verifyEncodedState.toHexString()
require(stateHash == verifyEncodedStateHex) {
throw CastorError.InitialStateOfDIDChanged()
}
val operation = AtalaOperation.decodeFromByteArray(encodedData)
val publicKeys = operation.createDid?.didData?.publicKeys?.map {
try {
PrismDIDPublicKey(apollo, it)
} catch (e: Exception) {
logger.error(
message = "Failed to decode public key from document",
metadata = arrayOf(
Metadata.MaskedMetadataByLevel(
key = "DID",
value = did.toString(),
level = LogLevel.DEBUG
)
)
)
throw e
}
} ?: listOf()
val services = operation.createDid?.didData?.services?.map {
DIDDocument.Service(
it.id,
arrayOf(it.type),
DIDDocument.ServiceEndpoint(
uri = it.serviceEndpoint.first()
)
)
} ?: listOf()
val verificationMethods =
publicKeys.fold(emptyMap<String, DIDDocument.VerificationMethod>()) { partialResult, publicKey ->
val didUrl = DIDUrl(
did = did,
fragment = publicKey.id
)
val method = DIDDocument.VerificationMethod(
id = didUrl,
controller = did,
type = publicKey.keyData.getCurve(),
publicKeyMultibase = publicKey.keyData.getValue().base64Encoded
)
partialResult + (didUrl.string() to method)
}
return Pair(verificationMethods, services)
}
/**
* Get a DID resolver based on the provided DID string.
*
* @param did the DID string.
* @param resolvers list of available resolvers.
* @throws [CastorError.NotPossibleToResolveDID] if no resolver was found.
*/
@JvmStatic
@Throws(CastorError.NotPossibleToResolveDID::class)
internal fun getDIDResolver(did: String, resolvers: Array<DIDResolver>): DIDResolver {
val parsedDID = parseDID(did)
return resolvers.find { it.method == parsedDID.method } ?: throw CastorError.NotPossibleToResolveDID(
did,
"Method or method id are invalid"
)
}
/**
* Extract list of [PublicKey] from a list of [DIDDocumentCoreProperty].
*
* @param coreProperties list of [DIDDocumentCoreProperty] that we are going to extract a list of [DIDDocumentCoreProperty].
* @return List<[PublicKey]>
*/
@JvmStatic
internal fun getKeyPairFromCoreProperties(coreProperties: Array<DIDDocumentCoreProperty>): List<PublicKey> {
return coreProperties
.filterIsInstance<DIDDocument.Authentication>()
.flatMap { it.verificationMethods.toList() }
.mapNotNull {
it.publicKeyMultibase?.let { publicKey ->
when (DIDDocument.VerificationMethod.getCurveByType(it.type)) {
Curve.SECP256K1 -> {
Secp256k1PublicKey(publicKey.encodeToByteArray())
}
Curve.ED25519 -> {
Ed25519PublicKey(publicKey.encodeToByteArray())
}
Curve.X25519 -> {
X25519PublicKey(publicKey.encodeToByteArray())
}
}
}
}
}
/**
* Create [OctetPublicKey] from a [KeyPair].
*
* @param keyPair keyPair to be used in creating [OctetPublicKey].
* @return [OctetPublicKey].
*/
@JvmStatic
private fun octetPublicKey(keyPair: KeyPair): OctetPublicKey {
val curve = when (keyPair::class) {
Secp256k1KeyPair::class -> {
Curve.SECP256K1
}
Ed25519KeyPair::class -> {
Curve.ED25519
}
X25519KeyPair::class -> {
Curve.X25519
}
else -> {
throw CastorError.KeyCurveNotSupported(KeyPair::class.simpleName ?: "")
}
}
return OctetPublicKey(crv = curve.value, x = keyPair.publicKey.getValue().base64UrlEncoded)
}
/**
* createPeerDID creates a DID for a peer (a device or server that acts as a DID subject) using given key agreement
* and authentication key pairs and a list of services.
*
* @param keyPairs The key pair used for key agreement (establishing secure communication between peers) and
* authentication (verifying the identity of a peer)
* @param services The list of services offered by the peer
* @return The [DID] of the peer
*/
@JvmStatic
@Throws(CastorError.InvalidKeyError::class)
internal fun createPeerDID(
keyPairs: Array<KeyPair>,
services: Array<DIDDocument.Service>
): DID {
val encryptionKeys: MutableList<VerificationMaterialAgreement> = mutableListOf()
val signingKeys: MutableList<VerificationMaterialAuthentication> = mutableListOf()
keyPairs.forEach {
when (it::class) {
X25519KeyPair::class -> {
val octetString = Json.encodeToString(octetPublicKey(it))
encryptionKeys.add(
VerificationMaterialAgreement(
format = VerificationMaterialFormatPeerDID.JWK,
value = octetString,
type = VerificationMethodTypeAgreement.JsonWebKey2020
)
)
}
Ed25519KeyPair::class -> {
val octetString = Json.encodeToString(octetPublicKey(it))
signingKeys.add(
VerificationMaterialAuthentication(
format = VerificationMaterialFormatPeerDID.JWK,
value = octetString,
type = VerificationMethodTypeAuthentication.JsonWebKey2020
)
)
}
else -> {
throw CastorError.InvalidKeyError()
}
}
}
if (signingKeys.isEmpty() || encryptionKeys.isEmpty()) {
throw CastorError.InvalidKeyError()
}
val peerDID = createPeerDIDNumalgo2(
encryptionKeys = encryptionKeys,
signingKeys = signingKeys,
service = services.map {
val serviceEndpoint = ServiceEndpoint(
uri = it.serviceEndpoint.uri,
routingKeys = it.serviceEndpoint.routingKeys?.toList() ?: listOf(),
accept = it.serviceEndpoint.accept?.asList() ?: listOf()
)
Json.encodeToString(
DIDCommServicePeerDID(
id = it.id,
type = it.type[0],
serviceEndpoint = serviceEndpoint
).toDict().toJsonElement()
)
}.firstOrNull()
)
return DIDParser.parse(peerDID)
}
}
}