This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathBbsBlsSignatureProof2020.ts
450 lines (391 loc) · 13.6 KB
/
BbsBlsSignatureProof2020.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
/*
* Copyright 2020 - MATTR Limited
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import jsonld from "jsonld";
import { suites, SECURITY_CONTEXT_URL } from "jsonld-signatures";
import { blsCreateProof, blsVerifyProof } from "@mattrglobal/bbs-signatures";
import {
DeriveProofOptions,
DidDocumentPublicKey,
VerifyProofOptions,
CreateVerifyDataOptions,
CanonizeOptions
} from "./types";
import { BbsBlsSignature2020 } from "./BbsBlsSignature2020";
import { randomBytes } from "@stablelib/random";
import { VerifyProofResult } from "./types/VerifyProofResult";
import { Bls12381G2KeyPair } from "@mattrglobal/bls12381-key-pair";
export class BbsBlsSignatureProof2020 extends suites.LinkedDataProof {
constructor({ useNativeCanonize, key, LDKeyClass }: any = {}) {
super({
type: "sec:BbsBlsSignatureProof2020"
});
this.proof = {
"@context": [
{
sec: "https://w3id.org/security#",
proof: {
"@id": "sec:proof",
"@type": "@id",
"@container": "@graph"
}
},
"https://w3id.org/security/bbs/v1"
],
type: "BbsBlsSignatureProof2020"
};
this.mappedDerivedProofType =
"https://w3id.org/security#BbsBlsSignature2020";
this.supportedDeriveProofType =
BbsBlsSignatureProof2020.supportedDerivedProofType;
this.LDKeyClass = LDKeyClass ?? Bls12381G2KeyPair;
this.proofSignatureKey = "proofValue";
this.key = key;
this.useNativeCanonize = useNativeCanonize;
}
/**
* Derive a proof from a proof and reveal document
*
* @param options {object} options for deriving a proof.
*
* @returns {Promise<object>} Resolves with the derived proof object.
*/
async deriveProof(options: DeriveProofOptions): Promise<object> {
const {
document,
proof,
revealDocument,
documentLoader,
expansionMap,
skipProofCompaction
} = options;
let { nonce } = options;
// Validate that the input proof document has a proof compatible with this suite
if (
!BbsBlsSignatureProof2020.supportedDerivedProofType.includes(proof.type)
) {
throw new TypeError(
`proof document proof incompatible, expected proof types of ${JSON.stringify(
BbsBlsSignatureProof2020.supportedDerivedProofType
)} received ${proof.type}`
);
}
//Extract the BBS signature from the input proof
const signature = Buffer.from(proof[this.proofSignatureKey], "base64");
//Initialize the BBS signature suite
const suite = new BbsBlsSignature2020();
//Initialize the derived proof
let derivedProof;
if (this.proof) {
// use proof JSON-LD document passed to API
derivedProof = await jsonld.compact(this.proof, SECURITY_CONTEXT_URL, {
documentLoader,
expansionMap,
compactToRelative: false
});
} else {
// create proof JSON-LD document
derivedProof = { "@context": SECURITY_CONTEXT_URL };
}
// ensure proof type is set
derivedProof.type = this.type;
// Get the input document statements
const documentStatements = await suite.createVerifyDocumentData(document, {
documentLoader,
expansionMap,
compactProof: !skipProofCompaction
});
// Get the proof statements
const proofStatements = await suite.createVerifyProofData(proof, {
documentLoader,
expansionMap,
compactProof: !skipProofCompaction
});
// Transform any blank node identifiers for the input
// document statements into actual node identifiers
// e.g _:c14n0 => urn:bnid:_:c14n0
const transformedInputDocumentStatements = documentStatements.map(element =>
element.replace(/(_:c14n[0-9]+)/g, "<urn:bnid:$1>")
);
//Transform the resulting RDF statements back into JSON-LD
const compactInputProofDocument = await jsonld.fromRDF(
transformedInputDocumentStatements.join("\n")
);
// Frame the result to create the reveal document result
const revealDocumentResult = await jsonld.frame(
compactInputProofDocument,
revealDocument,
{ documentLoader }
);
// Canonicalize the resulting reveal document
const revealDocumentStatements = await suite.createVerifyDocumentData(
revealDocumentResult,
{
documentLoader,
expansionMap
}
);
//Get the indicies of the revealed statements from the transformed input document offset
//by the number of proof statements
const numberOfProofStatements = proofStatements.length;
//Always reveal all the statements associated to the original proof
//these are always the first statements in the normalized form
const proofRevealIndicies = Array.from(
Array(numberOfProofStatements).keys()
);
//Reveal the statements indicated from the reveal document
const documentRevealIndicies = revealDocumentStatements.map(
key =>
transformedInputDocumentStatements.indexOf(key) +
numberOfProofStatements
);
// Check there is not a mismatch
if (documentRevealIndicies.length !== revealDocumentStatements.length) {
throw new Error(
"Some statements in the reveal document not found in original proof"
);
}
// Combine all indicies to get the resulting list of revealed indicies
const revealIndicies = proofRevealIndicies.concat(documentRevealIndicies);
// Create a nonce if one is not supplied
if (!nonce) {
nonce = await randomBytes(50);
}
// Set the nonce on the derived proof
derivedProof.nonce = Buffer.from(nonce).toString("base64");
//Combine all the input statements that
//were originally signed to generate the proof
const allInputStatements: Uint8Array[] = proofStatements
.concat(documentStatements)
.map(item => new Uint8Array(Buffer.from(item)));
// Fetch the verification method
const verificationMethod = await this.getVerificationMethod({
proof,
document,
documentLoader,
expansionMap
});
// Construct a key pair class from the returned verification method
const key = verificationMethod.publicKeyJwk
? await this.LDKeyClass.fromJwk(verificationMethod)
: await this.LDKeyClass.from(verificationMethod);
// Compute the proof
const outputProof = await blsCreateProof({
signature: new Uint8Array(signature),
publicKey: new Uint8Array(key.publicKeyBuffer),
messages: allInputStatements,
nonce: nonce,
revealed: revealIndicies
});
// Set the proof value on the derived proof
derivedProof.proofValue = Buffer.from(outputProof).toString("base64");
// Set the relevant proof elements on the derived proof from the input proof
derivedProof.verificationMethod = proof.verificationMethod;
derivedProof.proofPurpose = proof.proofPurpose;
derivedProof.created = proof.created;
return {
document: { ...revealDocumentResult },
proof: derivedProof
};
}
/**
* @param options {object} options for verifying the proof.
*
* @returns {Promise<{object}>} Resolves with the verification result.
*/
async verifyProof(options: VerifyProofOptions): Promise<VerifyProofResult> {
const { document, documentLoader, expansionMap, purpose } = options;
const { proof } = options;
try {
proof.type = this.mappedDerivedProofType;
// Get the proof statements
const proofStatements = await this.createVerifyProofData(proof, {
documentLoader,
expansionMap
});
// Get the document statements
const documentStatements = await this.createVerifyProofData(document, {
documentLoader,
expansionMap
});
// Transform the blank node identifier placeholders for the document statements
// back into actual blank node identifiers
const transformedDocumentStatements = documentStatements.map(element =>
element.replace(/<urn:bnid:(_:c14n[0-9]+)>/g, "$1")
);
// Combine all the statements to be verified
const statementsToVerify: Uint8Array[] = proofStatements
.concat(transformedDocumentStatements)
.map(item => new Uint8Array(Buffer.from(item)));
// Fetch the verification method
const verificationMethod = await this.getVerificationMethod({
proof,
document,
documentLoader,
expansionMap
});
// Construct a key pair class from the returned verification method
const key = verificationMethod.publicKeyJwk
? await this.LDKeyClass.fromJwk(verificationMethod)
: await this.LDKeyClass.from(verificationMethod);
// Verify the proof
const verified = await blsVerifyProof({
proof: new Uint8Array(Buffer.from(proof.proofValue, "base64")),
publicKey: new Uint8Array(key.publicKeyBuffer),
messages: statementsToVerify,
nonce: new Uint8Array(Buffer.from(proof.nonce as string, "base64"))
});
// Ensure proof was performed for a valid purpose
const { valid, error } = await purpose.validate(proof, {
document,
suite: this,
verificationMethod,
documentLoader,
expansionMap
});
if (!valid) {
throw error;
}
return verified;
} catch (error) {
return { verified: false, error };
}
}
async canonize(input: any, options: CanonizeOptions): Promise<string> {
const { documentLoader, expansionMap, skipExpansion } = options;
return jsonld.canonize(input, {
algorithm: "URDNA2015",
format: "application/n-quads",
documentLoader,
expansionMap,
skipExpansion,
useNative: this.useNativeCanonize
});
}
async canonizeProof(proof: any, options: CanonizeOptions): Promise<string> {
const { documentLoader, expansionMap } = options;
proof = { ...proof };
delete proof.nonce;
delete proof.proofValue;
return this.canonize(proof, {
documentLoader,
expansionMap,
skipExpansion: false
});
}
/**
* @param document {CreateVerifyDataOptions} options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyData(options: CreateVerifyDataOptions): Promise<string[]> {
const { proof, document, documentLoader, expansionMap } = options;
const proofStatements = await this.createVerifyProofData(proof, {
documentLoader,
expansionMap
});
const documentStatements = await this.createVerifyDocumentData(document, {
documentLoader,
expansionMap
});
// concatenate c14n proof options and c14n document
return proofStatements.concat(documentStatements);
}
/**
* @param proof to canonicalize
* @param options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyProofData(
proof: any,
{ documentLoader, expansionMap }: any
): Promise<string[]> {
const c14nProofOptions = await this.canonizeProof(proof, {
documentLoader,
expansionMap
});
return c14nProofOptions.split("\n").filter(_ => _.length > 0);
}
/**
* @param document to canonicalize
* @param options to create verify data
*
* @returns {Promise<{string[]>}.
*/
async createVerifyDocumentData(
document: any,
{ documentLoader, expansionMap }: any
): Promise<string[]> {
const c14nDocument = await this.canonize(document, {
documentLoader,
expansionMap
});
return c14nDocument.split("\n").filter(_ => _.length > 0);
}
/**
* @param document {object} to be signed.
* @param proof {object}
* @param documentLoader {function}
* @param expansionMap {function}
*/
async getVerificationMethod({
proof,
documentLoader
}: any): Promise<DidDocumentPublicKey> {
let { verificationMethod } = proof;
if (typeof verificationMethod === "object") {
verificationMethod = verificationMethod.id;
}
if (!verificationMethod) {
throw new Error('No "verificationMethod" found in proof.');
}
// Note: `expansionMap` is intentionally not passed; we can safely drop
// properties here and must allow for it
const result = await jsonld.frame(
verificationMethod,
{
// adding jws-2020 context to allow publicKeyJwk
"@context": [
"https://w3id.org/security/v2",
"https://w3id.org/security/suites/jws-2020/v1"
],
"@embed": "@always",
id: verificationMethod
},
{
documentLoader,
compactToRelative: false,
expandContext: SECURITY_CONTEXT_URL
}
);
if (!result) {
throw new Error(`Verification method ${verificationMethod} not found.`);
}
// ensure verification method has not been revoked
if (result.revoked !== undefined) {
throw new Error("The verification method has been revoked.");
}
return result;
}
static proofType = [
"BbsBlsSignatureProof2020",
"sec:BbsBlsSignatureProof2020",
"https://w3id.org/security#BbsBlsSignatureProof2020"
];
static supportedDerivedProofType = [
"BbsBlsSignature2020",
"sec:BbsBlsSignature2020",
"https://w3id.org/security#BbsBlsSignature2020"
];
}