-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathhybrid.ts
281 lines (241 loc) · 10.4 KB
/
hybrid.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
// Copyright 2024 Fondazione Links
// SPDX-License-Identifier: Apache-2.0
import {
CoreDID,
Credential,
Duration,
FailFast,
IotaDocument,
IotaIdentityClient,
JwkPqMemStore,
JwsSignatureOptions,
JwsVerificationOptions,
Jwt,
PQJwsVerifier,
EdDSAJwsVerifier,
JwtCredentialValidationOptions,
JwtCredentialValidator,
JwtPresentationOptions,
JwtPresentationValidationOptions,
JwtPresentationValidator,
KeyIdMemStore,
MethodScope,
Presentation,
Resolver,
Storage,
SubjectHolderRelationship,
Timestamp,
CompositeAlgId,
JwtCredentialValidatorHybrid,
JwtPresentationValidatorHybrid,
} from "@iota/identity-wasm/node";
import { Address, AliasOutput, Client, MnemonicSecretManager, SecretManager, SecretManagerType, Utils } from "@iota/sdk-wasm/node";
import { API_ENDPOINT, ensureAddressHasFunds } from "../util";
async function createHybridDid(client: Client, secretManager: SecretManagerType, storage: Storage): Promise<{
address: Address;
document: IotaDocument;
fragment: string;
}> {
const didClient = new IotaIdentityClient(client);
const networkHrp: string = await didClient.getNetworkHrp();
const secretManagerInstance = new SecretManager(secretManager);
const walletAddressBech32 = (await secretManagerInstance.generateEd25519Addresses({
accountIndex: 0,
range: {
start: 0,
end: 1,
},
bech32Hrp: networkHrp,
}))[0];
console.log("Wallet address Bech32:", walletAddressBech32);
await ensureAddressHasFunds(client, walletAddressBech32);
const address: Address = Utils.parseBech32Address(walletAddressBech32);
// Create a new DID document with a placeholder DID.
// The DID will be derived from the Alias Id of the Alias Output after publishing.
const document = new IotaDocument(networkHrp);
// Create a new method with PQ/T algorithm.
const fragment = await document.generateMethodHybrid(
storage,
CompositeAlgId.IdMldsa44Ed25519,
"#0",
MethodScope.VerificationMethod(),
);
// Construct an Alias Output containing the DID document, with the wallet address
// set as both the state controller and governor.
const aliasOutput: AliasOutput = await didClient.newDidOutput(address, document);
// Publish the Alias Output and get the published DID document.
const published = await didClient.publishDidOutput(secretManager, aliasOutput);
return { address, document: published, fragment };
}
/**
* This example shows how to create an hybrid Verifiable Presentation and validate it
*/
export async function hybrid() {
// ===========================================================================
// Step 1: Create identities for the issuer and the holder.
// ===========================================================================
const client = new Client({
primaryNode: API_ENDPOINT,
localPow: true,
});
const didClient = new IotaIdentityClient(client);
// Creates a new wallet and identity (see "0_create_did" example).
const issuerSecretManager: MnemonicSecretManager = {
mnemonic: Utils.generateMnemonic(),
};
const issuerStorage: Storage = new Storage(
new JwkPqMemStore(),
new KeyIdMemStore(),
);
let { document: issuerDocument, fragment: issuerFragment } = await createHybridDid(
client,
issuerSecretManager,
issuerStorage,
);
// Create an identity for the holder, in this case also the subject.
const aliceSecretManager: MnemonicSecretManager = {
mnemonic: Utils.generateMnemonic(),
};
const aliceStorage: Storage = new Storage(
new JwkPqMemStore(),
new KeyIdMemStore(),
);
let { document: aliceDocument, fragment: aliceFragment } = await createHybridDid(
client,
aliceSecretManager,
aliceStorage,
);
// ===========================================================================
// Step 2: Issuer creates and signs a Verifiable Credential.
// ===========================================================================
const subject = {
id: aliceDocument.id(),
name: "Alice",
degreeName: "Bachelor of Science and Arts",
degreeType: "BachelorDegree",
GPA: "4.0",
};
// Create an unsigned `UniversityDegree` credential for Alice
const unsignedVc = new Credential({
id: "https://example.edu/credentials/3732",
type: "UniversityDegreeCredential",
issuer: issuerDocument.id(),
credentialSubject: subject,
});
// Create a Credential JWT with the issuer's hybrid verification method.
const credentialJwt = await issuerDocument.createCredentialJwtHybrid(
issuerStorage,
issuerFragment,
unsignedVc,
new JwsSignatureOptions(),
);
const res = new JwtCredentialValidatorHybrid(new EdDSAJwsVerifier, new PQJwsVerifier()).validate(
credentialJwt,
issuerDocument,
new JwtCredentialValidationOptions(),
FailFast.FirstError,
);
console.log("credentialjwt validation", res.intoCredential());
// ===========================================================================
// Step 3: Issuer sends the Verifiable Credential to the holder.
// ===========================================================================
// The credential is then serialized to JSON and transmitted to the holder in a secure manner.
// Note that the credential is NOT published to the IOTA Tangle. It is sent and stored off-chain.
console.log(`Sending credential (as JWT) to the holder`, unsignedVc.toJSON());
// ===========================================================================
// Step 4: Verifier sends the holder a challenge and requests a signed Verifiable Presentation.
// ===========================================================================
// A unique random challenge generated by the requester per presentation can mitigate replay attacks.
const nonce = "475a7984-1bb5-4c4c-a56f-822bccd46440";
// The verifier and holder also agree that the signature should have an expiry date
// 10 minutes from now.
const expires = Timestamp.nowUTC().checkedAdd(Duration.minutes(10));
// ===========================================================================
// Step 5: Holder creates a verifiable presentation from the issued credential for the verifier to validate.
// ===========================================================================
// Create a Verifiable Presentation from the Credential
const unsignedVp = new Presentation({
holder: aliceDocument.id(),
verifiableCredential: [credentialJwt],
});
// Create a Hybrid JWT verifiable presentation using the holder's verification method
// and include the requested challenge and expiry timestamp.
const presentationJwt = await aliceDocument.createPresentationJwtHybrid(
aliceStorage,
aliceFragment,
unsignedVp,
new JwsSignatureOptions({ nonce }),
new JwtPresentationOptions({ expirationDate: expires }),
);
// ===========================================================================
// Step 6: Holder sends a verifiable presentation to the verifier.
// ===========================================================================
console.log(
`Sending presentation (as JWT) to the verifier`,
unsignedVp.toJSON(),
);
// ===========================================================================
// Step 7: Verifier receives the Verifiable Presentation and verifies it.
// ===========================================================================
// The verifier wants the following requirements to be satisfied:
// - JWT verification of the presentation (including checking the requested challenge to mitigate replay attacks)
// - JWT verification of the credentials.
// - The presentation holder must always be the subject, regardless of the presence of the nonTransferable property
// - The issuance date must not be in the future.
const jwtPresentationValidationOptions = new JwtPresentationValidationOptions(
{
presentationVerifierOptions: new JwsVerificationOptions({ nonce }),
},
);
const resolver = new Resolver({
client: didClient,
});
// Resolve the presentation holder.
const presentationHolderDID: CoreDID = JwtPresentationValidator.extractHolder(presentationJwt);
const resolvedHolder = await resolver.resolve(
presentationHolderDID.toString(),
);
// Validate presentation. Note that this doesn't validate the included credentials.
let decodedPresentation = new JwtPresentationValidatorHybrid(new EdDSAJwsVerifier, new PQJwsVerifier()).validate(
presentationJwt,
resolvedHolder,
jwtPresentationValidationOptions,
);
// Validate the hybrid credentials in the presentation.
let credentialValidator = new JwtCredentialValidatorHybrid(new EdDSAJwsVerifier, new PQJwsVerifier());
let validationOptions = new JwtCredentialValidationOptions({
subjectHolderRelationship: [
presentationHolderDID.toString(),
SubjectHolderRelationship.AlwaysSubject,
],
});
let jwtCredentials: Jwt[] = decodedPresentation
.presentation()
.verifiableCredential()
.map((credential) => {
const jwt = credential.tryIntoJwt();
if (!jwt) {
throw new Error("expected a JWT credential");
} else {
return jwt;
}
});
// Concurrently resolve the issuers' documents.
let issuers: string[] = [];
for (let jwtCredential of jwtCredentials) {
let issuer = JwtCredentialValidator.extractIssuerFromJwt(jwtCredential);
issuers.push(issuer.toString());
}
let resolvedIssuers = await resolver.resolveMultiple(issuers);
// Validate the credentials in the presentation.
for (let i = 0; i < jwtCredentials.length; i++) {
credentialValidator.validate(
jwtCredentials[i],
resolvedIssuers[i],
validationOptions,
FailFast.FirstError,
);
}
// Since no errors were thrown we know that the validation was successful.
console.log(`VP successfully validated`);
}