py-multihash 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
multihash/funcs.py ADDED
@@ -0,0 +1,789 @@
1
+ # py-multihash: Python implementation of the multihash specification
2
+
3
+ """Enumeration of standard multihash functions, and function registry.
4
+
5
+ This module provides:
6
+ - Func: IntEnum of supported hash functions
7
+ - FuncReg: Registry for managing hash function implementations
8
+ - IdentityHash: hashlib-compatible identity hash
9
+ - ShakeHash: Wrapper for variable-length SHAKE hashes
10
+
11
+ The FuncReg class maintains a registry of hash functions that can be:
12
+ - Retrieved by code, name, or hashlib object
13
+ - Extended with custom app-specific functions (codes 0x01-0x0F)
14
+ - Used to create hashlib-compatible hash objects
15
+
16
+ Standard functions are pre-registered. App-specific functions can be
17
+ registered/unregistered at runtime.
18
+ """
19
+
20
+ import hashlib
21
+ from collections import namedtuple
22
+ from enum import IntEnum
23
+ from numbers import Integral
24
+ from typing import ClassVar
25
+
26
+ import blake3
27
+ import mmh3
28
+
29
+ from .constants import HASH_CODES
30
+
31
+
32
+ def _is_app_specific_func(code: int) -> bool:
33
+ """Is the given hash function integer `code` application-specific?"""
34
+ return isinstance(code, Integral) and (0x01 <= code <= 0x0F)
35
+
36
+
37
+ class Func(IntEnum):
38
+ """An enumeration of hash functions supported by multihash.
39
+
40
+ The name of each member has its hyphens replaced by underscores.
41
+ The value of each member corresponds to its integer code.
42
+
43
+ >>> Func.sha2_512.value == 0x13
44
+ True
45
+ """
46
+
47
+ # Blake2 variants (sorted alphabetically)
48
+ blake2b_8 = HASH_CODES["blake2b-8"] # 0xB201
49
+ blake2b_16 = HASH_CODES["blake2b-16"] # 0xB202
50
+ blake2b_24 = HASH_CODES["blake2b-24"] # 0xB203
51
+ blake2b_32 = HASH_CODES["blake2b-32"] # 0xB204
52
+ blake2b_40 = HASH_CODES["blake2b-40"] # 0xB205
53
+ blake2b_48 = HASH_CODES["blake2b-48"] # 0xB206
54
+ blake2b_56 = HASH_CODES["blake2b-56"] # 0xB207
55
+ blake2b_64 = HASH_CODES["blake2b-64"] # 0xB208
56
+ blake2b_72 = HASH_CODES["blake2b-72"] # 0xB209
57
+ blake2b_80 = HASH_CODES["blake2b-80"] # 0xB20A
58
+ blake2b_88 = HASH_CODES["blake2b-88"] # 0xB20B
59
+ blake2b_96 = HASH_CODES["blake2b-96"] # 0xB20C
60
+ blake2b_104 = HASH_CODES["blake2b-104"] # 0xB20D
61
+ blake2b_112 = HASH_CODES["blake2b-112"] # 0xB20E
62
+ blake2b_120 = HASH_CODES["blake2b-120"] # 0xB20F
63
+ blake2b_128 = HASH_CODES["blake2b-128"] # 0xB210
64
+ blake2b_136 = HASH_CODES["blake2b-136"] # 0xB211
65
+ blake2b_144 = HASH_CODES["blake2b-144"] # 0xB212
66
+ blake2b_152 = HASH_CODES["blake2b-152"] # 0xB213
67
+ blake2b_160 = HASH_CODES["blake2b-160"] # 0xB214
68
+ blake2b_168 = HASH_CODES["blake2b-168"] # 0xB215
69
+ blake2b_176 = HASH_CODES["blake2b-176"] # 0xB216
70
+ blake2b_184 = HASH_CODES["blake2b-184"] # 0xB217
71
+ blake2b_192 = HASH_CODES["blake2b-192"] # 0xB218
72
+ blake2b_200 = HASH_CODES["blake2b-200"] # 0xB219
73
+ blake2b_208 = HASH_CODES["blake2b-208"] # 0xB21A
74
+ blake2b_216 = HASH_CODES["blake2b-216"] # 0xB21B
75
+ blake2b_224 = HASH_CODES["blake2b-224"] # 0xB21C
76
+ blake2b_232 = HASH_CODES["blake2b-232"] # 0xB21D
77
+ blake2b_240 = HASH_CODES["blake2b-240"] # 0xB21E
78
+ blake2b_248 = HASH_CODES["blake2b-248"] # 0xB21F
79
+ blake2b_256 = HASH_CODES["blake2b-256"] # 0xB220
80
+ blake2b_264 = HASH_CODES["blake2b-264"] # 0xB221
81
+ blake2b_272 = HASH_CODES["blake2b-272"] # 0xB222
82
+ blake2b_280 = HASH_CODES["blake2b-280"] # 0xB223
83
+ blake2b_288 = HASH_CODES["blake2b-288"] # 0xB224
84
+ blake2b_296 = HASH_CODES["blake2b-296"] # 0xB225
85
+ blake2b_304 = HASH_CODES["blake2b-304"] # 0xB226
86
+ blake2b_312 = HASH_CODES["blake2b-312"] # 0xB227
87
+ blake2b_320 = HASH_CODES["blake2b-320"] # 0xB228
88
+ blake2b_328 = HASH_CODES["blake2b-328"] # 0xB229
89
+ blake2b_336 = HASH_CODES["blake2b-336"] # 0xB22A
90
+ blake2b_344 = HASH_CODES["blake2b-344"] # 0xB22B
91
+ blake2b_352 = HASH_CODES["blake2b-352"] # 0xB22C
92
+ blake2b_360 = HASH_CODES["blake2b-360"] # 0xB22D
93
+ blake2b_368 = HASH_CODES["blake2b-368"] # 0xB22E
94
+ blake2b_376 = HASH_CODES["blake2b-376"] # 0xB22F
95
+ blake2b_384 = HASH_CODES["blake2b-384"] # 0xB230
96
+ blake2b_392 = HASH_CODES["blake2b-392"] # 0xB231
97
+ blake2b_400 = HASH_CODES["blake2b-400"] # 0xB232
98
+ blake2b_408 = HASH_CODES["blake2b-408"] # 0xB233
99
+ blake2b_416 = HASH_CODES["blake2b-416"] # 0xB234
100
+ blake2b_424 = HASH_CODES["blake2b-424"] # 0xB235
101
+ blake2b_432 = HASH_CODES["blake2b-432"] # 0xB236
102
+ blake2b_440 = HASH_CODES["blake2b-440"] # 0xB237
103
+ blake2b_448 = HASH_CODES["blake2b-448"] # 0xB238
104
+ blake2b_456 = HASH_CODES["blake2b-456"] # 0xB239
105
+ blake2b_464 = HASH_CODES["blake2b-464"] # 0xB23A
106
+ blake2b_472 = HASH_CODES["blake2b-472"] # 0xB23B
107
+ blake2b_480 = HASH_CODES["blake2b-480"] # 0xB23C
108
+ blake2b_488 = HASH_CODES["blake2b-488"] # 0xB23D
109
+ blake2b_496 = HASH_CODES["blake2b-496"] # 0xB23E
110
+ blake2b_504 = HASH_CODES["blake2b-504"] # 0xB23F
111
+ blake2b_512 = HASH_CODES["blake2b-512"] # 0xB240
112
+ blake2s_8 = HASH_CODES["blake2s-8"] # 0xB241
113
+ blake2s_16 = HASH_CODES["blake2s-16"] # 0xB242
114
+ blake2s_24 = HASH_CODES["blake2s-24"] # 0xB243
115
+ blake2s_32 = HASH_CODES["blake2s-32"] # 0xB244
116
+ blake2s_40 = HASH_CODES["blake2s-40"] # 0xB245
117
+ blake2s_48 = HASH_CODES["blake2s-48"] # 0xB246
118
+ blake2s_56 = HASH_CODES["blake2s-56"] # 0xB247
119
+ blake2s_64 = HASH_CODES["blake2s-64"] # 0xB248
120
+ blake2s_72 = HASH_CODES["blake2s-72"] # 0xB249
121
+ blake2s_80 = HASH_CODES["blake2s-80"] # 0xB24A
122
+ blake2s_88 = HASH_CODES["blake2s-88"] # 0xB24B
123
+ blake2s_96 = HASH_CODES["blake2s-96"] # 0xB24C
124
+ blake2s_104 = HASH_CODES["blake2s-104"] # 0xB24D
125
+ blake2s_112 = HASH_CODES["blake2s-112"] # 0xB24E
126
+ blake2s_120 = HASH_CODES["blake2s-120"] # 0xB24F
127
+ blake2s_128 = HASH_CODES["blake2s-128"] # 0xB250
128
+ blake2s_136 = HASH_CODES["blake2s-136"] # 0xB251
129
+ blake2s_144 = HASH_CODES["blake2s-144"] # 0xB252
130
+ blake2s_152 = HASH_CODES["blake2s-152"] # 0xB253
131
+ blake2s_160 = HASH_CODES["blake2s-160"] # 0xB254
132
+ blake2s_168 = HASH_CODES["blake2s-168"] # 0xB255
133
+ blake2s_176 = HASH_CODES["blake2s-176"] # 0xB256
134
+ blake2s_184 = HASH_CODES["blake2s-184"] # 0xB257
135
+ blake2s_192 = HASH_CODES["blake2s-192"] # 0xB258
136
+ blake2s_200 = HASH_CODES["blake2s-200"] # 0xB259
137
+ blake2s_208 = HASH_CODES["blake2s-208"] # 0xB25A
138
+ blake2s_216 = HASH_CODES["blake2s-216"] # 0xB25B
139
+ blake2s_224 = HASH_CODES["blake2s-224"] # 0xB25C
140
+ blake2s_232 = HASH_CODES["blake2s-232"] # 0xB25D
141
+ blake2s_240 = HASH_CODES["blake2s-240"] # 0xB25E
142
+ blake2s_248 = HASH_CODES["blake2s-248"] # 0xB25F
143
+ blake2s_256 = HASH_CODES["blake2s-256"] # 0xB260
144
+ blake3 = HASH_CODES["blake3"] # 0x1E
145
+ dbl_sha2_256 = HASH_CODES["dbl-sha2-256"] # 0x56
146
+ identity = HASH_CODES["id"] # 0x00
147
+ keccak_224 = HASH_CODES["keccak-224"] # 0x1A
148
+ keccak_256 = HASH_CODES["keccak-256"] # 0x1B
149
+ keccak_384 = HASH_CODES["keccak-384"] # 0x1C
150
+ keccak_512 = HASH_CODES["keccak-512"] # 0x1D
151
+ md4 = HASH_CODES["md4"] # 0xD4
152
+ md5 = HASH_CODES["md5"] # 0xD5
153
+ murmur3_128 = HASH_CODES["murmur3-128"] # 0x22
154
+ murmur3_32 = HASH_CODES["murmur3-32"] # 0x23
155
+ ripemd_128 = HASH_CODES["ripemd-128"] # 0x1052
156
+ ripemd_160 = HASH_CODES["ripemd-160"] # 0x1053
157
+ ripemd_256 = HASH_CODES["ripemd-256"] # 0x1054
158
+ ripemd_320 = HASH_CODES["ripemd-320"] # 0x1055
159
+ sha1 = HASH_CODES["sha1"] # 0x11
160
+ sha2_224 = HASH_CODES["sha2-224"] # 0x1013
161
+ sha2_256 = HASH_CODES["sha2-256"] # 0x12
162
+ sha2_256_trunc254_padded = HASH_CODES["sha2-256-trunc254-padded"] # 0x1012
163
+ sha2_384 = HASH_CODES["sha2-384"] # 0x20
164
+ sha2_512 = HASH_CODES["sha2-512"] # 0x13
165
+ sha2_512_224 = HASH_CODES["sha2-512-224"] # 0x1014
166
+ sha2_512_256 = HASH_CODES["sha2-512-256"] # 0x1015
167
+ sha3_224 = HASH_CODES["sha3-224"] # 0x17
168
+ sha3_256 = HASH_CODES["sha3-256"] # 0x16
169
+ sha3_384 = HASH_CODES["sha3-384"] # 0x15
170
+ sha3_512 = HASH_CODES["sha3-512"] # 0x14
171
+ shake_128 = HASH_CODES["shake-128"] # 0x18
172
+ shake_256 = HASH_CODES["shake-256"] # 0x19
173
+
174
+
175
+ class IdentityHash:
176
+ """hashlib-compatible algorithm where the input is the digest."""
177
+
178
+ name: str = "identity"
179
+
180
+ def __init__(self) -> None:
181
+ self._data = b""
182
+
183
+ @property
184
+ def digest_size(self) -> int:
185
+ return len(self._data)
186
+
187
+ @property
188
+ def block_size(self) -> int:
189
+ return 1
190
+
191
+ def update(self, data: bytes) -> None:
192
+ self._data += data
193
+
194
+ def digest(self) -> bytes:
195
+ return self._data
196
+
197
+ def hexdigest(self) -> str:
198
+ return self._data.hex()
199
+
200
+ def copy(self) -> "IdentityHash":
201
+ c = IdentityHash()
202
+ c._data = self._data
203
+ return c
204
+
205
+
206
+ class _FuncRegMeta(type):
207
+ _func_hash: dict
208
+
209
+ def __contains__(cls, func) -> bool:
210
+ """Return whether `func` is a registered function."""
211
+ return func in cls._func_hash
212
+
213
+ def __iter__(cls):
214
+ """Iterate over registered functions."""
215
+ return iter(cls._func_hash)
216
+
217
+
218
+ class ShakeHash:
219
+ """Wrapper for SHAKE variable-length hash functions."""
220
+
221
+ def __init__(self, shake_func, length: int):
222
+ """Initialize SHAKE hash with specified output length.
223
+
224
+ Args:
225
+ shake_func: hashlib.shake_128 or hashlib.shake_256
226
+ length: Output digest length in bytes
227
+ """
228
+ self._shake_func = shake_func
229
+ self._hasher = shake_func()
230
+ self._length = length
231
+ self.name = self._hasher.name
232
+
233
+ def update(self, data: bytes) -> None:
234
+ """Update the hash with data."""
235
+ self._hasher.update(data)
236
+
237
+ def digest(self) -> bytes:
238
+ """Return digest of specified length."""
239
+ return self._hasher.digest(self._length)
240
+
241
+ def hexdigest(self) -> str:
242
+ """Return hex digest."""
243
+ return self.digest().hex()
244
+
245
+ def copy(self) -> "ShakeHash":
246
+ """Create a copy of the hash state."""
247
+ c = ShakeHash(self._shake_func, self._length)
248
+ c._hasher = self._hasher.copy()
249
+ return c
250
+
251
+
252
+ class Blake3Hash:
253
+ """hashlib-compatible wrapper for Blake3 using official blake3 library.
254
+
255
+ BLAKE3 is a cryptographic hash function that is much faster than MD5, SHA-1, SHA-2,
256
+ and SHA-3, yet is just as secure as the latest standard SHA-3.
257
+
258
+ Example:
259
+ >>> from multihash import digest
260
+ >>> mh = digest(b"hello world", "blake3")
261
+ >>> mh.digest.hex() # doctest: +ELLIPSIS
262
+ '...'
263
+ >>> # Or use the hash class directly:
264
+ >>> h = Blake3Hash()
265
+ >>> h.update(b"hello ")
266
+ >>> h.update(b"world")
267
+ >>> h.hexdigest() # doctest: +ELLIPSIS
268
+ '...'
269
+ """
270
+
271
+ name: str = "blake3"
272
+ digest_size: int = 32
273
+ block_size: int = 64
274
+
275
+ def __init__(self) -> None:
276
+ self._hasher = blake3.blake3()
277
+
278
+ def update(self, data: bytes) -> None:
279
+ """Update the hash with data."""
280
+ self._hasher.update(data)
281
+
282
+ def digest(self) -> bytes:
283
+ """Return digest."""
284
+ return self._hasher.digest()
285
+
286
+ def hexdigest(self) -> str:
287
+ """Return hex digest."""
288
+ return self._hasher.hexdigest()
289
+
290
+ def copy(self) -> "Blake3Hash":
291
+ """Create a copy of the hash state."""
292
+ c = Blake3Hash()
293
+ c._hasher = self._hasher.copy()
294
+ return c
295
+
296
+
297
+ class Murmur3_128Hash:
298
+ """hashlib-compatible wrapper for MurmurHash3 128-bit using official mmh3 library.
299
+
300
+ MurmurHash3 is a fast, non-cryptographic hash function suitable for hash-based lookups.
301
+ Note: Not suitable for cryptographic purposes.
302
+
303
+ Example:
304
+ >>> from multihash import digest
305
+ >>> mh = digest(b"hello world", "murmur3-128")
306
+ >>> mh.digest.hex() # doctest: +ELLIPSIS
307
+ '...'
308
+ >>> # Or use the hash class directly with a custom seed:
309
+ >>> h = Murmur3_128Hash(seed=42)
310
+ >>> h.update(b"data")
311
+ >>> h.hexdigest() # doctest: +ELLIPSIS
312
+ '...'
313
+ """
314
+
315
+ name: str = "murmur3-128"
316
+ digest_size: int = 16
317
+ block_size: int = 1
318
+
319
+ def __init__(self, seed: int = 0) -> None:
320
+ self._data = b""
321
+ self._seed = seed
322
+
323
+ def update(self, data: bytes) -> None:
324
+ """Update the hash with data."""
325
+ self._data += data
326
+
327
+ def digest(self) -> bytes:
328
+ """Return 128-bit digest."""
329
+ # mmh3.hash128 returns a 128-bit integer
330
+ hash_value = mmh3.hash128(self._data, seed=self._seed, signed=False)
331
+ return hash_value.to_bytes(16, byteorder="little")
332
+
333
+ def hexdigest(self) -> str:
334
+ """Return hex digest."""
335
+ return self.digest().hex()
336
+
337
+ def copy(self) -> "Murmur3_128Hash":
338
+ """Create a copy of the hash state."""
339
+ c = Murmur3_128Hash(seed=self._seed)
340
+ c._data = self._data
341
+ return c
342
+
343
+
344
+ class Murmur3_32Hash:
345
+ """hashlib-compatible wrapper for MurmurHash3 32-bit using official mmh3 library.
346
+
347
+ MurmurHash3 32-bit variant is a fast, non-cryptographic hash function.
348
+ Note: Not suitable for cryptographic purposes.
349
+
350
+ Example:
351
+ >>> from multihash import digest
352
+ >>> mh = digest(b"hello world", "murmur3-32")
353
+ >>> mh.digest.hex() # doctest: +ELLIPSIS
354
+ '...'
355
+ >>> # Or use the hash class directly with a custom seed:
356
+ >>> h = Murmur3_32Hash(seed=0)
357
+ >>> h.update(b"data")
358
+ >>> h.hexdigest() # doctest: +ELLIPSIS
359
+ '...'
360
+ """
361
+
362
+ name: str = "murmur3-32"
363
+ digest_size: int = 4
364
+ block_size: int = 1
365
+
366
+ def __init__(self, seed: int = 0) -> None:
367
+ self._data = b""
368
+ self._seed = seed
369
+
370
+ def update(self, data: bytes) -> None:
371
+ """Update the hash with data."""
372
+ self._data += data
373
+
374
+ def digest(self) -> bytes:
375
+ """Return 32-bit digest."""
376
+ # mmh3.hash returns a 32-bit integer
377
+ hash_value = mmh3.hash(self._data, seed=self._seed, signed=False)
378
+ return hash_value.to_bytes(4, byteorder="little")
379
+
380
+ def hexdigest(self) -> str:
381
+ """Return hex digest."""
382
+ return self.digest().hex()
383
+
384
+ def copy(self) -> "Murmur3_32Hash":
385
+ """Create a copy of the hash state."""
386
+ c = Murmur3_32Hash(seed=self._seed)
387
+ c._data = self._data
388
+ return c
389
+
390
+
391
+ class DoubleSHA256Hash:
392
+ """hashlib-compatible wrapper for double SHA2-256 (used in Bitcoin).
393
+
394
+ Applies SHA-256 twice: SHA-256(SHA-256(data)). This is commonly used in Bitcoin
395
+ and other cryptocurrencies for additional security.
396
+
397
+ Example:
398
+ >>> from multihash import digest
399
+ >>> mh = digest(b"hello world", "dbl-sha2-256")
400
+ >>> mh.digest.hex() # doctest: +ELLIPSIS
401
+ '...'
402
+ >>> # Or use the hash class directly:
403
+ >>> h = DoubleSHA256Hash()
404
+ >>> h.update(b"data")
405
+ >>> h.hexdigest() # doctest: +ELLIPSIS
406
+ '...'
407
+ """
408
+
409
+ name: str = "dbl-sha2-256"
410
+ digest_size: int = 32
411
+ block_size: int = 64
412
+
413
+ def __init__(self) -> None:
414
+ self._hasher = hashlib.sha256()
415
+
416
+ def update(self, data: bytes) -> None:
417
+ """Update the hash with data."""
418
+ self._hasher.update(data)
419
+
420
+ def digest(self) -> bytes:
421
+ """Return digest (double SHA-256)."""
422
+ first_hash = self._hasher.digest()
423
+ return hashlib.sha256(first_hash).digest()
424
+
425
+ def hexdigest(self) -> str:
426
+ """Return hex digest."""
427
+ return self.digest().hex()
428
+
429
+ def copy(self) -> "DoubleSHA256Hash":
430
+ """Create a copy of the hash state."""
431
+ c = DoubleSHA256Hash()
432
+ c._hasher = self._hasher.copy()
433
+ return c
434
+
435
+
436
+ class SHA2_256_Trunc254_Padded_Hash:
437
+ """hashlib-compatible wrapper for SHA2-256 truncated to 254 bits and padded."""
438
+
439
+ name: str = "sha2-256-trunc254-padded"
440
+ digest_size: int = 31 # 254 bits = 31.75 bytes, but we use 31 bytes
441
+ block_size: int = 64
442
+
443
+ def __init__(self) -> None:
444
+ self._hasher = hashlib.sha256()
445
+
446
+ def update(self, data: bytes) -> None:
447
+ """Update the hash with data."""
448
+ self._hasher.update(data)
449
+
450
+ def digest(self) -> bytes:
451
+ """Return digest (SHA-256 truncated to 254 bits = 31 bytes)."""
452
+ full_hash = self._hasher.digest()
453
+ # Truncate to 254 bits (31 bytes) by taking first 31 bytes
454
+ return full_hash[:31]
455
+
456
+ def hexdigest(self) -> str:
457
+ """Return hex digest."""
458
+ return self.digest().hex()
459
+
460
+ def copy(self) -> "SHA2_256_Trunc254_Padded_Hash":
461
+ """Create a copy of the hash state."""
462
+ c = SHA2_256_Trunc254_Padded_Hash()
463
+ c._hasher = self._hasher.copy()
464
+ return c
465
+
466
+
467
+ def _create_blake2_variant(variant: str, digest_bytes: int):
468
+ """Factory function to create Blake2 variant classes.
469
+
470
+ Args:
471
+ variant: Either 'blake2b' or 'blake2s'
472
+ digest_bytes: Number of bytes in the digest (1-64 for blake2b, 1-32 for blake2s)
473
+
474
+ Returns:
475
+ A hashlib-compatible hash class for the specified Blake2 variant
476
+
477
+ Example:
478
+ >>> from multihash import digest
479
+ >>> # Use BLAKE2b with 256-bit output
480
+ >>> mh = digest(b"hello", "blake2b-256")
481
+ >>>
482
+ >>> # Use BLAKE2s with 128-bit output
483
+ >>> mh = digest(b"hello", "blake2s-128")
484
+ >>>
485
+ >>> # All variants from 8 to 512 bits (blake2b) or 8 to 256 bits (blake2s) are supported
486
+ >>> mh = digest(b"data", "blake2b-384")
487
+ """
488
+
489
+ class Blake2Variant:
490
+ name: str = f"{variant}-{digest_bytes * 8}"
491
+ digest_size: int = digest_bytes
492
+ block_size: int = 128 if variant == "blake2b" else 64
493
+
494
+ def __init__(self) -> None:
495
+ hash_func = getattr(hashlib, variant)
496
+ self._hasher = hash_func(digest_size=digest_bytes)
497
+
498
+ def update(self, data: bytes) -> None:
499
+ """Update the hash with data."""
500
+ self._hasher.update(data)
501
+
502
+ def digest(self) -> bytes:
503
+ """Return digest."""
504
+ return self._hasher.digest()
505
+
506
+ def hexdigest(self) -> str:
507
+ """Return hex digest."""
508
+ return self._hasher.hexdigest()
509
+
510
+ def copy(self) -> "Blake2Variant":
511
+ """Create a copy of the hash state."""
512
+ c = Blake2Variant()
513
+ c._hasher = self._hasher.copy()
514
+ return c
515
+
516
+ return Blake2Variant
517
+
518
+
519
+ class FuncReg(metaclass=_FuncRegMeta):
520
+ """Registry of supported hash functions.
521
+
522
+ The FuncReg class maintains a registry of hash functions that can be:
523
+ - Retrieved by code, name, or hashlib object
524
+ - Extended with custom app-specific functions (codes 0x01-0x0F)
525
+ - Used to create hashlib-compatible hash objects
526
+
527
+ Standard functions are pre-registered. App-specific functions can be
528
+ registered/unregistered at runtime.
529
+
530
+ Example:
531
+ Register an app-specific hash function:
532
+ >>> FuncReg.register(0x05, "my-custom-hash", "myhash", lambda: MyHash())
533
+ >>> func = FuncReg.get("my-custom-hash")
534
+ >>> hash_obj = FuncReg.hash_from_func(func)
535
+
536
+ Unregister an app-specific function:
537
+ >>> FuncReg.unregister(0x05)
538
+ """
539
+
540
+ _hash = namedtuple("_hash", "name new")
541
+
542
+ # Class-level registry attributes
543
+ _func_from_name: ClassVar[dict] = {}
544
+ _func_from_hash: ClassVar[dict] = {}
545
+ _func_hash: ClassVar[dict] = {}
546
+
547
+ # Standard hash function data: (func, hashlib_name, constructor)
548
+ _std_func_data: ClassVar[list] = [
549
+ (Func.identity, "identity", IdentityHash),
550
+ (Func.sha1, "sha1", hashlib.sha1),
551
+ (Func.sha2_256, "sha256", hashlib.sha256),
552
+ (Func.sha2_512, "sha512", hashlib.sha512),
553
+ (Func.sha3_512, "sha3_512", hashlib.sha3_512),
554
+ (Func.sha3_384, "sha3_384", hashlib.sha3_384),
555
+ (Func.sha3_256, "sha3_256", hashlib.sha3_256),
556
+ (Func.sha3_224, "sha3_224", hashlib.sha3_224),
557
+ (Func.shake_128, "shake_128", None), # Variable length - use ShakeHash wrapper
558
+ (Func.shake_256, "shake_256", None), # Variable length - use ShakeHash wrapper
559
+ (Func.blake2b_256, "blake2b", lambda: hashlib.blake2b(digest_size=32)),
560
+ (Func.blake2b_512, "blake2b", lambda: hashlib.blake2b(digest_size=64)),
561
+ (Func.blake2s_256, "blake2s", lambda: hashlib.blake2s(digest_size=32)),
562
+ (Func.md5, "md5", hashlib.md5),
563
+ ]
564
+
565
+ # Additional hash functions (conditionally added if available)
566
+ _optional_func_data: ClassVar[list] = [
567
+ # SHA2 variants (if available in hashlib)
568
+ (Func.sha2_224, "sha224", hashlib.sha224 if hasattr(hashlib, "sha224") else None),
569
+ (Func.sha2_384, "sha384", hashlib.sha384 if hasattr(hashlib, "sha384") else None),
570
+ # SHA2-512 truncated variants (Python 3.6+)
571
+ (Func.sha2_512_224, "sha512_224", getattr(hashlib, "sha512_224", None)),
572
+ (Func.sha2_512_256, "sha512_256", getattr(hashlib, "sha512_256", None)),
573
+ # Blake3 (using official blake3 library)
574
+ (Func.blake3, "blake3", Blake3Hash),
575
+ # Murmur3 variants (using official mmh3 library)
576
+ (Func.murmur3_128, "murmur3-128", Murmur3_128Hash),
577
+ (Func.murmur3_32, "murmur3-32", Murmur3_32Hash),
578
+ # Double SHA2-256 (always available, uses hashlib)
579
+ (Func.dbl_sha2_256, "dbl-sha2-256", DoubleSHA256Hash),
580
+ # SHA2-256 truncated and padded
581
+ (Func.sha2_256_trunc254_padded, "sha2-256-trunc254-padded", SHA2_256_Trunc254_Padded_Hash),
582
+ # Legacy hash functions - RIPEMD variants
583
+ (Func.ripemd_128, "ripemd128", getattr(hashlib, "ripemd128", None)),
584
+ (Func.ripemd_160, "ripemd160", getattr(hashlib, "ripemd160", None)),
585
+ (Func.ripemd_256, "ripemd256", getattr(hashlib, "ripemd256", None)),
586
+ (Func.ripemd_320, "ripemd320", getattr(hashlib, "ripemd320", None)),
587
+ # MD4 (legacy, weak)
588
+ (Func.md4, "md4", getattr(hashlib, "md4", None)),
589
+ ]
590
+
591
+ # Blake2 variants - generated programmatically
592
+ @classmethod
593
+ def _generate_blake2_variants(cls):
594
+ """Generate all Blake2b and Blake2s variant registrations."""
595
+ blake2_variants = []
596
+
597
+ # Blake2b variants (8 to 512 bits, in 8-bit increments)
598
+ # Skip 256 and 512 as they're already in std_func_data
599
+ for bits in range(8, 520, 8):
600
+ if bits in (256, 512): # Skip already defined variants
601
+ continue
602
+ digest_bytes = bits // 8
603
+ func_name = f"blake2b_{bits}"
604
+ if hasattr(Func, func_name):
605
+ func = getattr(Func, func_name)
606
+ hash_name = f"blake2b-{bits}"
607
+ hash_class = _create_blake2_variant("blake2b", digest_bytes)
608
+ blake2_variants.append((func, hash_name, hash_class))
609
+
610
+ # Blake2s variants (8 to 256 bits, in 8-bit increments)
611
+ # Skip 256 as it's already in std_func_data
612
+ for bits in range(8, 264, 8):
613
+ if bits == 256: # Skip already defined variant
614
+ continue
615
+ digest_bytes = bits // 8
616
+ func_name = f"blake2s_{bits}"
617
+ if hasattr(Func, func_name):
618
+ func = getattr(Func, func_name)
619
+ hash_name = f"blake2s-{bits}"
620
+ hash_class = _create_blake2_variant("blake2s", digest_bytes)
621
+ blake2_variants.append((func, hash_name, hash_class))
622
+
623
+ return blake2_variants
624
+
625
+ @classmethod
626
+ def reset(cls) -> None:
627
+ """Reset the registry to the standard multihash functions."""
628
+ cls._func_from_name = {}
629
+ cls._func_from_hash = {}
630
+ cls._func_hash = {}
631
+
632
+ for func, hash_name, hash_new in cls._std_func_data:
633
+ cls._do_register(func, func.name, hash_name, hash_new)
634
+
635
+ # Register optional functions if available
636
+ for func, hash_name, hash_new in cls._optional_func_data:
637
+ if hash_new is not None:
638
+ try:
639
+ # Test that the function is actually available by creating an instance.
640
+ # We don't use the result, just verify it can be instantiated.
641
+ # The unused variable is intentional - we only care about the side effect
642
+ # of successful instantiation, not the hash object itself.
643
+ _ = hash_new()
644
+ cls._do_register(func, func.name, hash_name, hash_new)
645
+ except (AttributeError, ValueError, TypeError):
646
+ # Function not available, skip
647
+ pass
648
+
649
+ # Register Blake2 variants
650
+ for func, hash_name, hash_class in cls._generate_blake2_variants():
651
+ try:
652
+ # Test instantiation
653
+ _ = hash_class()
654
+ cls._do_register(func, func.name, hash_name, hash_class)
655
+ except (AttributeError, ValueError, TypeError):
656
+ # Variant not available, skip
657
+ pass
658
+
659
+ @classmethod
660
+ def get(cls, func_hint: Func | str | int) -> Func | int:
661
+ """Return a registered hash function matching the given hint."""
662
+ if isinstance(func_hint, int):
663
+ try:
664
+ return Func(func_hint)
665
+ except ValueError:
666
+ pass
667
+ if isinstance(func_hint, str) and func_hint in cls._func_from_name:
668
+ return cls._func_from_name[func_hint]
669
+ if isinstance(func_hint, int) and func_hint in cls._func_hash:
670
+ return func_hint
671
+ raise KeyError("unknown hash function", func_hint)
672
+
673
+ @classmethod
674
+ def _do_register(cls, code: int, name: str, hash_name: str | None = None, hash_new=None) -> None:
675
+ """Add hash function data to the registry without checks.
676
+
677
+ This method registers the function name in both hyphen and underscore
678
+ variants (e.g., "sha2-256" and "sha2_256") to provide flexibility
679
+ for users who may use either naming convention.
680
+ """
681
+ cls._func_from_name[name.replace("-", "_")] = code
682
+ cls._func_from_name[name.replace("_", "-")] = code
683
+ if hash_name:
684
+ cls._func_from_hash[hash_name] = code
685
+ cls._func_hash[code] = cls._hash(hash_name, hash_new)
686
+
687
+ @classmethod
688
+ def register(cls, code: int, name: str, hash_name: str | None = None, hash_new=None) -> None:
689
+ """Add a function to the registry.
690
+
691
+ For standard functions already registered, this updates the hash_new
692
+ if provided. For app-specific functions (0x01-0x0f), replaces existing.
693
+ """
694
+ # Check if this is a standard function
695
+ try:
696
+ Func(code)
697
+ is_std_func = True
698
+ except ValueError:
699
+ is_std_func = False
700
+
701
+ # For standard functions, just update hash_new if provided
702
+ if is_std_func and code in cls._func_hash:
703
+ if hash_new is not None:
704
+ old_hash = cls._func_hash[code]
705
+ cls._func_hash[code] = cls._hash(old_hash.name or hash_name, hash_new)
706
+ return
707
+
708
+ # Check for name conflicts
709
+ for mapping, nameinmap, errmsg in [
710
+ (cls._func_from_name, name, "function name already registered"),
711
+ (cls._func_from_hash, hash_name, "hashlib name already registered"),
712
+ ]:
713
+ if nameinmap is None:
714
+ continue
715
+ existing = mapping.get(nameinmap, code)
716
+ if existing != code:
717
+ raise ValueError(errmsg, existing)
718
+
719
+ # Unregister app-specific if existing
720
+ if code in cls._func_hash and _is_app_specific_func(code):
721
+ cls.unregister(code)
722
+
723
+ cls._do_register(code, name, hash_name, hash_new)
724
+
725
+ @classmethod
726
+ def unregister(cls, code: int) -> None:
727
+ """Remove an application-specific function from the registry."""
728
+ if not _is_app_specific_func(code):
729
+ raise ValueError("only application-specific functions can be unregistered")
730
+
731
+ func_names = {n for n, f in cls._func_from_name.items() if f == code}
732
+ for func_name in func_names:
733
+ del cls._func_from_name[func_name]
734
+
735
+ hash_data = cls._func_hash.pop(code)
736
+ if hash_data.name:
737
+ del cls._func_from_hash[hash_data.name]
738
+
739
+ @classmethod
740
+ def func_from_hash(cls, hash_obj) -> Func | int:
741
+ """Return the multihash Func for a hashlib-compatible hash object.
742
+
743
+ Args:
744
+ hash_obj: Hashlib-compatible hash object
745
+
746
+ Returns:
747
+ Func enum or int code
748
+
749
+ Raises:
750
+ KeyError: If hash object name is not registered
751
+ """
752
+ try:
753
+ return cls._func_from_hash[hash_obj.name]
754
+ except KeyError:
755
+ raise KeyError(f"unknown hash object name: {hash_obj.name}")
756
+
757
+ @classmethod
758
+ def hash_from_func(cls, func: Func | int, length: int | None = None):
759
+ """Return a hashlib-compatible object for the multihash func.
760
+
761
+ Args:
762
+ func: Hash function code or Func enum
763
+ length: Optional length for SHAKE hashes. Required for SHAKE. Returns None if None for SHAKE.
764
+
765
+ Returns:
766
+ Hash object or None if not available
767
+
768
+ Note:
769
+ SHAKE functions (shake_128, shake_256) require a length parameter
770
+ to specify the output digest size. If length is None for SHAKE
771
+ functions, this method returns None.
772
+ """
773
+ new = cls._func_hash[func].new
774
+ if new is None:
775
+ # Handle SHAKE functions with variable length
776
+ if func == Func.shake_128:
777
+ if length is None:
778
+ return None
779
+ return ShakeHash(hashlib.shake_128, length)
780
+ elif func == Func.shake_256:
781
+ if length is None:
782
+ return None
783
+ return ShakeHash(hashlib.shake_256, length)
784
+ return None
785
+ return new()
786
+
787
+
788
+ # Initialize the function hash registry.
789
+ FuncReg.reset()