-
Notifications
You must be signed in to change notification settings - Fork 519
/
Copy pathBbsBlsSignatureProof2020.py
387 lines (312 loc) · 13.7 KB
/
BbsBlsSignatureProof2020.py
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
"""BbsBlsSignatureProof2020 class."""
from os import urandom
from pyld import jsonld
from typing import List
from .BbsBlsSignature2020Base import BbsBlsSignature2020Base
if BbsBlsSignature2020Base.BBS_SUPPORTED:
from ursa_bbs_signatures import (
create_proof as bls_create_proof,
verify_proof as bls_verify_proof,
CreateProofRequest,
VerifyProofRequest,
get_total_message_count,
ProofMessage,
BlsKeyPair,
ProofMessageType,
)
from ....utils.dependencies import assert_ursa_bbs_signatures_installed
from ....wallet.util import b64_to_bytes, bytes_to_b64
from ..crypto import KeyPair
from ..error import LinkedDataProofException
from ..validation_result import ProofResult
from ..document_loader import DocumentLoaderMethod
from ..purposes import ProofPurpose
from .BbsBlsSignature2020 import BbsBlsSignature2020
from .LinkedDataProof import DeriveProofResult
class BbsBlsSignatureProof2020(BbsBlsSignature2020Base):
"""BbsBlsSignatureProof2020 class."""
signature_type = "BbsBlsSignatureProof2020"
def __init__(
self,
*,
key_pair: KeyPair,
):
"""Create new BbsBlsSignatureProof2020 instance.
Args:
key_pair (KeyPair): Key pair to use. Must provide BBS signatures
"""
super().__init__(
signature_type=BbsBlsSignatureProof2020.signature_type,
supported_derive_proof_types=(
BbsBlsSignatureProof2020.supported_derive_proof_types
),
)
self.key_pair = key_pair
self.mapped_derived_proof_type = "BbsBlsSignature2020"
async def derive_proof(
self,
*,
proof: dict,
document: dict,
reveal_document: dict,
document_loader: DocumentLoaderMethod,
nonce: bytes = None,
):
"""Derive proof for document, return dict with derived document and proof."""
assert_ursa_bbs_signatures_installed()
# Validate that the input proof document has a proof compatible with this suite
if proof.get("type") not in self.supported_derive_proof_types:
raise LinkedDataProofException(
f"Proof document proof incompatible, expected proof types of"
f" {self.supported_derive_proof_types}, received " + proof["type"]
)
# Extract the BBS signature from the input proof
signature = b64_to_bytes(proof["proofValue"])
# Initialize the BBS signature suite
# This is used for creating the input document verification data
# NOTE: both suite._create_verify_xxx_data and self._create_verify_xxx_data
# are used in this file. They have small changes in behavior
suite = BbsBlsSignature2020(key_pair=self.key_pair)
# Initialize the derived proof
derived_proof = self.proof.copy() if self.proof else {}
# Ensure proof type is set
derived_proof["type"] = self.signature_type
# Get the input document and proof statements
document_statements = suite._create_verify_document_data(
document=document, document_loader=document_loader
)
proof_statements = suite._create_verify_proof_data(
proof=proof, document=document, document_loader=document_loader
)
# Transform any blank node identifiers for the input
# document statements into actual node identifiers
# e.g _:c14n0 => urn:bnid:_:c14n0
transformed_input_document_statements = (
self._transform_blank_node_ids_into_placeholder_node_ids(
document_statements
)
)
# Transform the resulting RDF statements back into JSON-LD
compact_input_proof_document = jsonld.from_rdf(
"\n".join(transformed_input_document_statements)
)
# Frame the result to create the reveal document result
reveal_document_result = jsonld.frame(
compact_input_proof_document,
reveal_document,
{"documentLoader": document_loader},
)
# Canonicalize the resulting reveal document
reveal_document_statements = suite._create_verify_document_data(
document=reveal_document_result, document_loader=document_loader
)
# Get the indices of the revealed statements from the transformed input document
# offset by the number of proof statements
number_of_proof_statements = len(proof_statements)
# Always reveal all the statements associated to the original proof
# these are always the first statements in the normalized form
proof_reveal_indices = [indice for indice in range(number_of_proof_statements)]
# Reveal the statements indicated from the reveal document
document_reveal_indices = list(
map(
lambda reveal_statement: transformed_input_document_statements.index(
reveal_statement
)
+ number_of_proof_statements,
reveal_document_statements,
)
)
# Check there is not a mismatch
if len(document_reveal_indices) != len(reveal_document_statements):
raise LinkedDataProofException(
"Some statements in the reveal document not found in original proof"
)
# Combine all indices to get the resulting list of revealed indices
reveal_indices = [*proof_reveal_indices, *document_reveal_indices]
# Create a nonce if one is not supplied
nonce = nonce or urandom(50)
derived_proof["nonce"] = bytes_to_b64(
nonce, urlsafe=False, pad=True, encoding="utf-8"
)
# Combine all the input statements that were originally signed
# NOTE: we use plain strings here as input for the bbs lib.
# the MATTR lib uses bytes, but the wrapper expects strings
# it also works if we pass bytes as input
all_input_statements = [*proof_statements, *document_statements]
# Fetch the verification method
verification_method = self._get_verification_method(
proof=proof, document_loader=document_loader
)
# Create key pair from public key in verification method
key_pair = self.key_pair.from_verification_method(verification_method)
# Get the proof messages (revealed or not)
proof_messages = []
for input_statement_index in range(len(all_input_statements)):
# if input statement index in revealed messages indexes use revealed type
# otherwise use blinding
proof_type = (
ProofMessageType.Revealed
if input_statement_index in reveal_indices
else ProofMessageType.HiddenProofSpecificBlinding
)
proof_messages.append(
ProofMessage(
message=all_input_statements[input_statement_index],
proof_type=proof_type,
)
)
# get bbs key from bls key pair
bbs_public_key = BlsKeyPair(public_key=key_pair.public_key).get_bbs_key(
len(all_input_statements)
)
# Compute the proof
proof_request = CreateProofRequest(
public_key=bbs_public_key,
messages=proof_messages,
signature=signature,
nonce=nonce,
)
output_proof = bls_create_proof(proof_request)
# Set the proof value on the derived proof
derived_proof["proofValue"] = bytes_to_b64(
output_proof, urlsafe=False, pad=True, encoding="utf-8"
)
# Set the relevant proof elements on the derived proof from the input proof
derived_proof["verificationMethod"] = proof["verificationMethod"]
derived_proof["proofPurpose"] = proof["proofPurpose"]
derived_proof["created"] = proof["created"]
return DeriveProofResult(
document={**reveal_document_result}, proof=derived_proof
)
async def verify_proof(
self,
*,
proof: dict,
document: dict,
purpose: ProofPurpose,
document_loader: DocumentLoaderMethod,
) -> ProofResult:
"""Verify proof against document and proof purpose."""
assert_ursa_bbs_signatures_installed()
try:
proof["type"] = self.mapped_derived_proof_type
# Get the proof and document statements
proof_statements = self._create_verify_proof_data(
proof=proof, document=document, document_loader=document_loader
)
document_statements = self._create_verify_document_data(
document=document, document_loader=document_loader
)
# Transform the blank node identifier placeholders for the document statements
# back into actual blank node identifiers
transformed_document_statements = (
self._transform_placeholder_node_ids_into_blank_node_ids(
document_statements
)
)
# Combine all the statements to be verified
# NOTE: we use plain strings here as input for the bbs lib.
# the MATTR lib uses bytes, but the wrapper expects strings
# it also works if we pass bytes as input
statements_to_verify = [*proof_statements, *transformed_document_statements]
# Fetch the verification method
verification_method = self._get_verification_method(
proof=proof, document_loader=document_loader
)
key_pair = self.key_pair.from_verification_method(verification_method)
proof_bytes = b64_to_bytes(proof["proofValue"])
total_message_count = get_total_message_count(proof_bytes)
# get bbs key from bls key pair
bbs_public_key = BlsKeyPair(public_key=key_pair.public_key).get_bbs_key(
total_message_count
)
# verify dervied proof
verify_request = VerifyProofRequest(
public_key=bbs_public_key,
proof=proof_bytes,
messages=statements_to_verify,
nonce=b64_to_bytes(proof["nonce"]),
)
verified = bls_verify_proof(verify_request)
if not verified:
raise LinkedDataProofException(
f"Invalid signature on document {document}"
)
purpose_result = purpose.validate(
proof=proof,
document=document,
suite=self,
verification_method=verification_method,
document_loader=document_loader,
)
if not purpose_result.valid:
return ProofResult(
verified=False,
purpose_result=purpose_result,
error=purpose_result.error,
)
return ProofResult(verified=True, purpose_result=purpose_result)
except Exception as err:
return ProofResult(verified=False, error=err)
def _canonize_proof(
self, *, proof: dict, document: dict, document_loader: DocumentLoaderMethod
):
"""Canonize proof dictionary. Removes proofValue."""
proof = {**proof, "@context": document.get("@context") or self._default_proof}
proof.pop("proofValue", None)
proof.pop("nonce", None)
return self._canonize(input=proof, document_loader=document_loader)
def _transform_blank_node_ids_into_placeholder_node_ids(
self,
statements: List[str],
) -> List[str]:
"""Transform blank node identifiers for the input into actual node identifiers.
e.g _:c14n0 => urn:bnid:_:c14n0
Args:
statements (List[str]): List with possible blank node identifiers
Returns:
List[str]: List of transformed output statements
"""
transformed_statements = []
for statement in statements:
if "_:c14n" in statement:
prefix_index = statement.index("_:c14n")
space_index = statement.index(" ", prefix_index)
statement = statement.replace(
statement[prefix_index:space_index],
"<urn:bnid:{ident}>".format(
ident=statement[prefix_index:space_index]
),
)
transformed_statements.append(statement)
return transformed_statements
def _transform_placeholder_node_ids_into_blank_node_ids(
self,
statements: List[str],
) -> List[str]:
"""Transform the blank node placeholder identifiers back into actual blank nodes.
e.g urn:bnid:_:c14n0 => _:c14n0
Args:
statements (List[str]): List with possible placeholder node identifiers
Returns:
List[str]: List of transformed output statements
"""
transformed_statements = []
prefix_string = "<urn:bnid:"
for statement in statements:
if "<urn:bnid:_:c14n" in statement:
prefix_index = statement.index(prefix_string)
closing_index = statement.index(">", prefix_index)
urn_id_close = closing_index + 1 # >
urn_id_prefix_end = prefix_index + len(prefix_string) # <urn:bnid:
statement = statement.replace(
statement[prefix_index:urn_id_close],
statement[urn_id_prefix_end:closing_index],
)
transformed_statements.append(statement)
return transformed_statements
supported_derive_proof_types = [
"BbsBlsSignature2020",
"sec:BbsBlsSignature2020",
"https://w3id.org/security#BbsBlsSignature2020",
]