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
|
from abc import (
ABC,
abstractmethod,
)
from hashlib import (
sha256,
)
from math import (
ceil,
log2,
)
from typing import (
Sequence,
)
from eth_typing import (
BLSPubkey,
BLSSignature,
)
from eth_utils import (
ValidationError,
)
from py_ecc.fields import (
optimized_bls12_381_FQ12 as FQ12,
)
from py_ecc.optimized_bls12_381 import (
G1,
Z1,
Z2,
add,
curve_order,
final_exponentiate,
multiply,
neg,
pairing,
)
from .g2_primitives import (
G1_to_pubkey,
G2_to_signature,
is_inf,
pubkey_to_G1,
signature_to_G2,
subgroup_check,
)
from .hash import (
hkdf_expand,
hkdf_extract,
i2osp,
os2ip,
)
from .hash_to_curve import (
hash_to_G2,
)
class BaseG2Ciphersuite(ABC):
DST = b""
xmd_hash_function = sha256
#
# Input validation helpers
#
@staticmethod
def _is_valid_privkey(privkey: int) -> bool:
return isinstance(privkey, int) and privkey > 0 and privkey < curve_order
@staticmethod
def _is_valid_pubkey(pubkey: bytes) -> bool:
# SV: minimal-pubkey-size
return isinstance(pubkey, bytes) and len(pubkey) == 48
@staticmethod
def _is_valid_message(message: bytes) -> bool:
return isinstance(message, bytes)
@staticmethod
def _is_valid_signature(signature: bytes) -> bool:
# SV: minimal-pubkey-size
return isinstance(signature, bytes) and len(signature) == 96
#
# APIs
#
@classmethod
def SkToPk(cls, privkey: int) -> BLSPubkey:
"""
The SkToPk algorithm takes a secret key SK and outputs the
corresponding public key PK.
Raise `ValidationError` when there is input validation error.
"""
if not cls._is_valid_privkey(privkey):
raise ValidationError("Invalid private key")
# Procedure
return G1_to_pubkey(multiply(G1, privkey))
@classmethod
def KeyGen(cls, IKM: bytes, key_info: bytes = b"") -> int:
salt = b"BLS-SIG-KEYGEN-SALT-"
SK = 0
while SK == 0:
salt = cls.xmd_hash_function(salt).digest()
prk = hkdf_extract(salt, IKM + b"\x00")
l = ceil((1.5 * ceil(log2(curve_order))) / 8) # noqa: E741
okm = hkdf_expand(prk, key_info + i2osp(l, 2), l)
SK = os2ip(okm) % curve_order
return SK
@staticmethod
def KeyValidate(PK: BLSPubkey) -> bool:
try:
pubkey_point = pubkey_to_G1(PK)
except (ValidationError, ValueError, AssertionError):
return False
if is_inf(pubkey_point):
return False
if not subgroup_check(pubkey_point):
return False
return True
@classmethod
def _CoreSign(cls, SK: int, message: bytes, DST: bytes) -> BLSSignature:
"""
The CoreSign algorithm computes a signature from SK, a secret key,
and message, an octet string.
Raise `ValidationError` when there is input validation error.
"""
# Inputs validation
if not cls._is_valid_privkey(SK):
raise ValidationError("Invalid secret key")
if not cls._is_valid_message(message):
raise ValidationError("Invalid message")
# Procedure
message_point = hash_to_G2(message, DST, cls.xmd_hash_function)
signature_point = multiply(message_point, SK)
return G2_to_signature(signature_point)
@classmethod
def _CoreVerify(
cls, PK: BLSPubkey, message: bytes, signature: BLSSignature, DST: bytes
) -> bool:
try:
# Inputs validation
if not cls._is_valid_pubkey(PK):
raise ValidationError("Invalid public key")
if not cls._is_valid_message(message):
raise ValidationError("Invalid message")
if not cls._is_valid_signature(signature):
raise ValidationError("Invalid signature")
# Procedure
if not cls.KeyValidate(PK):
raise ValidationError("Invalid public key")
signature_point = signature_to_G2(signature)
if not subgroup_check(signature_point):
return False
final_exponentiation = final_exponentiate(
pairing(
signature_point,
G1,
final_exponentiate=False,
)
* pairing(
hash_to_G2(message, DST, cls.xmd_hash_function),
neg(pubkey_to_G1(PK)),
final_exponentiate=False,
)
)
return final_exponentiation == FQ12.one()
except (ValidationError, ValueError, AssertionError):
return False
@classmethod
def Aggregate(cls, signatures: Sequence[BLSSignature]) -> BLSSignature:
"""
The Aggregate algorithm aggregates multiple signatures into one.
Raise `ValidationError` when there is input validation error.
"""
# Preconditions
if len(signatures) < 1:
raise ValidationError("Insufficient number of signatures. (n < 1)")
# Inputs validation
for signature in signatures:
if not cls._is_valid_signature(signature):
raise ValidationError("Invalid signature")
# Procedure
aggregate = Z2 # Seed with the point at infinity
for signature in signatures:
signature_point = signature_to_G2(signature)
aggregate = add(aggregate, signature_point)
return G2_to_signature(aggregate)
@classmethod
def _CoreAggregateVerify(
cls,
PKs: Sequence[BLSPubkey],
messages: Sequence[bytes],
signature: BLSSignature,
DST: bytes,
) -> bool:
try:
# Inputs validation
for pk in PKs:
if not cls._is_valid_pubkey(pk):
raise ValidationError("Invalid public key")
for message in messages:
if not cls._is_valid_message(message):
raise ValidationError("Invalid message")
if not len(PKs) == len(messages):
raise ValidationError("Inconsistent number of PKs and messages")
if not cls._is_valid_signature(signature):
raise ValidationError("Invalid signature")
# Preconditions
if len(PKs) < 1:
raise ValidationError("Insufficient number of PKs. (n < 1)")
# Procedure
signature_point = signature_to_G2(signature)
if not subgroup_check(signature_point):
return False
aggregate = FQ12.one()
for pk, message in zip(PKs, messages):
if not cls.KeyValidate(pk):
raise ValidationError("Invalid public key")
pubkey_point = pubkey_to_G1(pk)
message_point = hash_to_G2(message, DST, cls.xmd_hash_function)
aggregate *= pairing(
message_point, pubkey_point, final_exponentiate=False
)
aggregate *= pairing(signature_point, neg(G1), final_exponentiate=False)
return final_exponentiate(aggregate) == FQ12.one()
except (ValidationError, ValueError, AssertionError):
return False
@classmethod
def Sign(cls, SK: int, message: bytes) -> BLSSignature:
return cls._CoreSign(SK, message, cls.DST)
@classmethod
def Verify(cls, PK: BLSPubkey, message: bytes, signature: BLSSignature) -> bool:
return cls._CoreVerify(PK, message, signature, cls.DST)
@classmethod
@abstractmethod
def AggregateVerify(
cls,
PKs: Sequence[BLSPubkey],
messages: Sequence[bytes],
signature: BLSSignature,
) -> bool:
...
class G2Basic(BaseG2Ciphersuite):
DST = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"
@classmethod
def AggregateVerify(
cls,
PKs: Sequence[BLSPubkey],
messages: Sequence[bytes],
signature: BLSSignature,
) -> bool:
if len(messages) != len(set(messages)): # Messages are not unique
return False
return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST)
class G2MessageAugmentation(BaseG2Ciphersuite):
DST = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_"
@classmethod
def Sign(cls, SK: int, message: bytes) -> BLSSignature:
PK = cls.SkToPk(SK)
return cls._CoreSign(SK, PK + message, cls.DST)
@classmethod
def Verify(cls, PK: BLSPubkey, message: bytes, signature: BLSSignature) -> bool:
return cls._CoreVerify(PK, PK + message, signature, cls.DST)
@classmethod
def AggregateVerify(
cls,
PKs: Sequence[BLSPubkey],
messages: Sequence[bytes],
signature: BLSSignature,
) -> bool:
if len(PKs) != len(messages):
return False
messages = [pk + msg for pk, msg in zip(PKs, messages)]
return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST)
class G2ProofOfPossession(BaseG2Ciphersuite):
DST = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_"
POP_TAG = b"BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_"
@classmethod
def _is_valid_pubkey(cls, pubkey: bytes) -> bool:
"""
Note: PopVerify is a precondition for -Verify APIs
However, it's difficult to verify it with the API interface in runtime.
To ensure KeyValidate has been checked, we check it in the input validation.
See https://github.com/cfrg/draft-irtf-cfrg-bls-signature/issues/27 for
the discussion.
"""
if not super()._is_valid_pubkey(pubkey):
return False
return cls.KeyValidate(BLSPubkey(pubkey))
@classmethod
def AggregateVerify(
cls,
PKs: Sequence[BLSPubkey],
messages: Sequence[bytes],
signature: BLSSignature,
) -> bool:
return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST)
@classmethod
def PopProve(cls, SK: int) -> BLSSignature:
pubkey = cls.SkToPk(SK)
return cls._CoreSign(SK, pubkey, cls.POP_TAG)
@classmethod
def PopVerify(cls, PK: BLSPubkey, proof: BLSSignature) -> bool:
return cls._CoreVerify(PK, PK, proof, cls.POP_TAG)
@staticmethod
def _AggregatePKs(PKs: Sequence[BLSPubkey]) -> BLSPubkey:
"""
Aggregate the public keys.
Raise `ValidationError` when there is input validation error.
"""
if len(PKs) < 1:
raise ValidationError("Insufficient number of PKs. (n < 1)")
aggregate = Z1 # Seed with the point at infinity
for pk in PKs:
pubkey_point = pubkey_to_G1(pk)
aggregate = add(aggregate, pubkey_point)
return G1_to_pubkey(aggregate)
@classmethod
def FastAggregateVerify(
cls, PKs: Sequence[BLSPubkey], message: bytes, signature: BLSSignature
) -> bool:
try:
# Inputs validation
for pk in PKs:
if not cls._is_valid_pubkey(pk):
raise ValidationError("Invalid public key")
if not cls._is_valid_message(message):
raise ValidationError("Invalid message")
if not cls._is_valid_signature(signature):
raise ValidationError("Invalid signature")
# Preconditions
if len(PKs) < 1:
raise ValidationError("Insufficient number of PKs. (n < 1)")
# Procedure
aggregate_pubkey = cls._AggregatePKs(PKs)
except (ValidationError, AssertionError):
return False
else:
return cls.Verify(aggregate_pubkey, message, signature)
|