filedgr-pkg-utils 0.8.4__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.
Files changed (56) hide show
  1. filedgr_pkg_utils/__init__.py +1 -0
  2. filedgr_pkg_utils/caching/__init__.py +1 -0
  3. filedgr_pkg_utils/caching/memoize.py +54 -0
  4. filedgr_pkg_utils/canonicalization/__init__.py +0 -0
  5. filedgr_pkg_utils/canonicalization/canonical_json_mixin.py +38 -0
  6. filedgr_pkg_utils/compression/__init__.py +7 -0
  7. filedgr_pkg_utils/compression/algorithms/__init__.py +0 -0
  8. filedgr_pkg_utils/compression/algorithms/compression_algorithm_brotli.py +31 -0
  9. filedgr_pkg_utils/compression/algorithms/compression_algorithm_zip.py +45 -0
  10. filedgr_pkg_utils/compression/algorithms/compression_algorithm_zstd.py +35 -0
  11. filedgr_pkg_utils/compression/algorithms/compression_algortihm_gzip.py +34 -0
  12. filedgr_pkg_utils/compression/compression_algorithm.py +24 -0
  13. filedgr_pkg_utils/compression/compression_utils.py +37 -0
  14. filedgr_pkg_utils/converters/__init__.py +0 -0
  15. filedgr_pkg_utils/converters/abstract_converter.py +21 -0
  16. filedgr_pkg_utils/cryptography/__init__.py +0 -0
  17. filedgr_pkg_utils/cryptography/hashing/__init__.py +0 -0
  18. filedgr_pkg_utils/cryptography/hashing/conversion_utils.py +4 -0
  19. filedgr_pkg_utils/cryptography/hashing/hash_algorithm.py +101 -0
  20. filedgr_pkg_utils/cryptography/hashing/hash_utils.py +18 -0
  21. filedgr_pkg_utils/cryptography/signing/__init__.py +6 -0
  22. filedgr_pkg_utils/cryptography/signing/conversion_utils.py +27 -0
  23. filedgr_pkg_utils/cryptography/signing/hmac_signature_algorithm.py +15 -0
  24. filedgr_pkg_utils/cryptography/signing/secp256k1_evm_signature_algorithm.py +20 -0
  25. filedgr_pkg_utils/cryptography/signing/secp256k1_signature_algorithm.py +46 -0
  26. filedgr_pkg_utils/cryptography/signing/signature_algorithm.py +10 -0
  27. filedgr_pkg_utils/cryptography/signing/signature_utils.py +31 -0
  28. filedgr_pkg_utils/evm/__init__.py +8 -0
  29. filedgr_pkg_utils/evm/hex_utils.py +81 -0
  30. filedgr_pkg_utils/filesystem/__init__.py +1 -0
  31. filedgr_pkg_utils/filesystem/atomic.py +124 -0
  32. filedgr_pkg_utils/filesystem/tar_utils.py +50 -0
  33. filedgr_pkg_utils/fldgr_logging/__init__.py +1 -0
  34. filedgr_pkg_utils/fldgr_logging/sanitizer_logger_adapter.py +22 -0
  35. filedgr_pkg_utils/fldgr_logging/structured_logger.py +78 -0
  36. filedgr_pkg_utils/hooks/__init__.py +0 -0
  37. filedgr_pkg_utils/hooks/decorators.py +246 -0
  38. filedgr_pkg_utils/images/__init__.py +0 -0
  39. filedgr_pkg_utils/images/hashing/__init__.py +6 -0
  40. filedgr_pkg_utils/images/hashing/algorithms/__init__.py +0 -0
  41. filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_ahash.py +33 -0
  42. filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_dhash.py +33 -0
  43. filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_phash.py +33 -0
  44. filedgr_pkg_utils/images/hashing/image_hash_algorithm.py +14 -0
  45. filedgr_pkg_utils/images/hashing/image_hash_utils.py +31 -0
  46. filedgr_pkg_utils/mixins/__init__.py +0 -0
  47. filedgr_pkg_utils/mixins/without_keys_mixin.py +7 -0
  48. filedgr_pkg_utils/resilience/__init__.py +5 -0
  49. filedgr_pkg_utils/resilience/decorators.py +192 -0
  50. filedgr_pkg_utils/security/__init__.py +0 -0
  51. filedgr_pkg_utils/security/sanitizer.py +60 -0
  52. filedgr_pkg_utils/security/sanitizer_decorators.py +30 -0
  53. filedgr_pkg_utils-0.8.4.dist-info/METADATA +171 -0
  54. filedgr_pkg_utils-0.8.4.dist-info/RECORD +56 -0
  55. filedgr_pkg_utils-0.8.4.dist-info/WHEEL +5 -0
  56. filedgr_pkg_utils-0.8.4.dist-info/top_level.txt +1 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.8.4"
@@ -0,0 +1 @@
1
+ from .memoize import ttl_cache
@@ -0,0 +1,54 @@
1
+ import time
2
+ import inspect
3
+ from functools import wraps
4
+ from typing import Callable, Any, Dict, Tuple
5
+
6
+
7
+ def ttl_cache(maxsize: int = 128, ttl_seconds: int = 3600):
8
+ """
9
+ LRU-style in-memory cache with Time-To-Live (TTL).
10
+ Supports both sync and async functions.
11
+ """
12
+ def decorator(func: Callable) -> Callable:
13
+ cache: Dict[Tuple, Tuple[float, Any]] = {}
14
+
15
+ def get_cache_key(args, kwargs):
16
+ return (args, tuple(sorted(kwargs.items())))
17
+
18
+ def check_cache(key):
19
+ current_time = time.time()
20
+ if key in cache:
21
+ expiration_time, result = cache[key]
22
+ if current_time < expiration_time:
23
+ return True, result
24
+ return False, None
25
+
26
+ def save_cache(key, result):
27
+ if len(cache) >= maxsize:
28
+ oldest_key = next(iter(cache))
29
+ del cache[oldest_key]
30
+ cache[key] = (time.time() + ttl_seconds, result)
31
+
32
+ if inspect.iscoroutinefunction(func):
33
+ @wraps(func)
34
+ async def async_wrapper(*args, **kwargs):
35
+ key = get_cache_key(args, kwargs)
36
+ hit, result = check_cache(key)
37
+ if hit:
38
+ return result
39
+ result = await func(*args, **kwargs)
40
+ save_cache(key, result)
41
+ return result
42
+ return async_wrapper
43
+ else:
44
+ @wraps(func)
45
+ def sync_wrapper(*args, **kwargs):
46
+ key = get_cache_key(args, kwargs)
47
+ hit, result = check_cache(key)
48
+ if hit:
49
+ return result
50
+ result = func(*args, **kwargs)
51
+ save_cache(key, result)
52
+ return result
53
+ return sync_wrapper
54
+ return decorator
File without changes
@@ -0,0 +1,38 @@
1
+ import orjson
2
+ from pydantic import BaseModel
3
+ from datetime import datetime, timezone
4
+ from typing import Any
5
+
6
+
7
+ class CanonicalJsonMixin(BaseModel):
8
+ """
9
+ Deterministic, whitespace-free, sorted-key JSON serialization.
10
+ Suitable for hashing, signing, and blockchain payloads.
11
+ """
12
+
13
+ @staticmethod
14
+ def _default(obj: Any):
15
+ if isinstance(obj, datetime):
16
+ # Enforce UTC + milliseconds + Z
17
+ return (
18
+ obj.astimezone(timezone.utc)
19
+ .isoformat(timespec="milliseconds")
20
+ .replace("+00:00", "Z")
21
+ )
22
+ raise TypeError
23
+
24
+ def canonical_json_bytes(self) -> bytes:
25
+ """
26
+ Canonical JSON as bytes (best for hashing & signing).
27
+ """
28
+ return orjson.dumps(
29
+ self.model_dump(mode="json"),
30
+ option=orjson.OPT_SORT_KEYS,
31
+ default=self._default,
32
+ )
33
+
34
+ def canonical_json(self) -> str:
35
+ """
36
+ Canonical JSON as UTF-8 string.
37
+ """
38
+ return self.canonical_json_bytes().decode("utf-8")
@@ -0,0 +1,7 @@
1
+ from .algorithms.compression_algorithm_zip import ZipAlgorithm
2
+ from .algorithms.compression_algortihm_gzip import GzipAlgorithm
3
+ from .algorithms.compression_algorithm_zstd import ZstdAlgorithm
4
+ from .algorithms.compression_algorithm_brotli import BrotliAlgorithm
5
+
6
+ from .compression_algorithm import CompressionAlgorithm
7
+ from .compression_utils import CompressionUtils
File without changes
@@ -0,0 +1,31 @@
1
+ import brotli
2
+
3
+
4
+ class BrotliAlgorithm:
5
+ name = "brotli"
6
+
7
+ def __init__(self, quality: int = 11):
8
+ """
9
+ :param quality: 0 (fastest/lowest) to 11 (slowest/highest). Default is 11.
10
+ """
11
+ self.quality = quality
12
+
13
+ def compress(self, data: bytes) -> bytes:
14
+ return brotli.compress(data, quality=self.quality)
15
+
16
+ def decompress(self, data: bytes) -> bytes:
17
+ return brotli.decompress(data)
18
+
19
+ def compress_file(self, src: str, dest: str) -> None:
20
+ with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
21
+ f_out.write(brotli.compress(f_in.read(), quality=self.quality))
22
+
23
+ def decompress_file(self, src: str, dest: str) -> None:
24
+ with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
25
+ f_out.write(brotli.decompress(f_in.read()))
26
+
27
+ def compress_folder(self, src: str, dest: str) -> None:
28
+ raise NotImplementedError("Brotli does not natively support folder compression. Use a tarball instead.")
29
+
30
+ def decompress_folder(self, src: str, dest: str) -> None:
31
+ raise NotImplementedError("Brotli does not natively support folder decompression. Use a tarball instead.")
@@ -0,0 +1,45 @@
1
+ import os
2
+ import shutil
3
+ import zipfile
4
+ import zlib
5
+
6
+
7
+ class ZipAlgorithm:
8
+ name = "zip"
9
+
10
+ def __init__(self, compresslevel: int = 6):
11
+ """
12
+ :param compresslevel: 0 (no compression), 1 (fastest) to 9 (slowest/highest).
13
+ Default is 6 zlib default.
14
+ """
15
+ self.compresslevel = compresslevel
16
+
17
+ def compress(self, data: bytes) -> bytes:
18
+ return zlib.compress(data, level=self.compresslevel)
19
+
20
+ def decompress(self, data: bytes) -> bytes:
21
+ return zlib.decompress(data)
22
+
23
+ def compress_file(self, src: str, dest: str) -> None:
24
+ with zipfile.ZipFile(dest, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=self.compresslevel) as zf:
25
+ zf.write(src, arcname=os.path.basename(src))
26
+
27
+ def decompress_file(self, src: str, dest: str) -> None:
28
+ with zipfile.ZipFile(src, 'r') as zf:
29
+ names = zf.namelist()
30
+ if not names:
31
+ return
32
+ with zf.open(names[0]) as f_in, open(dest, 'wb') as f_out:
33
+ shutil.copyfileobj(f_in, f_out)
34
+
35
+ def compress_folder(self, src: str, dest: str) -> None:
36
+ with zipfile.ZipFile(dest, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=self.compresslevel) as zf:
37
+ for root, _, files in os.walk(src):
38
+ for file in files:
39
+ file_path = os.path.join(root, file)
40
+ arcname = os.path.relpath(file_path, start=src)
41
+ zf.write(file_path, arcname=arcname)
42
+
43
+ def decompress_folder(self, src: str, dest: str) -> None:
44
+ with zipfile.ZipFile(src, 'r') as zf:
45
+ zf.extractall(path=dest)
@@ -0,0 +1,35 @@
1
+ import zstandard as zstd
2
+
3
+
4
+ class ZstdAlgorithm:
5
+ name = "zstd"
6
+
7
+ def __init__(self, level: int = 3):
8
+ """
9
+ :param level: 1 (fastest) to 22 (slowest/highest). Default is usually 3.
10
+ """
11
+ self.level = level
12
+
13
+ def compress(self, data: bytes) -> bytes:
14
+ compressor = zstd.ZstdCompressor(level=self.level)
15
+ return compressor.compress(data)
16
+
17
+ def decompress(self, data: bytes) -> bytes:
18
+ decompressor = zstd.ZstdDecompressor()
19
+ return decompressor.decompress(data)
20
+
21
+ def compress_file(self, src: str, dest: str) -> None:
22
+ cctx = zstd.ZstdCompressor(level=self.level)
23
+ with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
24
+ cctx.copy_stream(f_in, f_out)
25
+
26
+ def decompress_file(self, src: str, dest: str) -> None:
27
+ dctx = zstd.ZstdDecompressor()
28
+ with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
29
+ dctx.copy_stream(f_in, f_out)
30
+
31
+ def compress_folder(self, src: str, dest: str) -> None:
32
+ raise NotImplementedError("Zstd does not natively support folder compression. Use a tarball instead.")
33
+
34
+ def decompress_folder(self, src: str, dest: str) -> None:
35
+ raise NotImplementedError("Zstd does not natively support folder decompression. Use a tarball instead.")
@@ -0,0 +1,34 @@
1
+ import gzip
2
+ import shutil
3
+
4
+
5
+ class GzipAlgorithm:
6
+ name = "gzip"
7
+
8
+ def __init__(self, compresslevel: int = 9):
9
+ """
10
+ :param compresslevel: 1 (fastest/lowest) to 9 (slowest/highest). Default is 9.
11
+ """
12
+ self.compresslevel = compresslevel
13
+
14
+ def compress(self, data: bytes) -> bytes:
15
+ return gzip.compress(data, compresslevel=self.compresslevel)
16
+
17
+ def decompress(self, data: bytes) -> bytes:
18
+ return gzip.decompress(data)
19
+
20
+ def compress_file(self, src: str, dest: str) -> None:
21
+ with open(src, 'rb') as f_in:
22
+ with gzip.open(dest, 'wb', compresslevel=self.compresslevel) as f_out:
23
+ shutil.copyfileobj(f_in, f_out)
24
+
25
+ def decompress_file(self, src: str, dest: str) -> None:
26
+ with gzip.open(src, 'rb') as f_in:
27
+ with open(dest, 'wb') as f_out:
28
+ shutil.copyfileobj(f_in, f_out)
29
+
30
+ def compress_folder(self, src: str, dest: str) -> None:
31
+ raise NotImplementedError("Gzip does not natively support folder compression. Use a tarball instead.")
32
+
33
+ def decompress_folder(self, src: str, dest: str) -> None:
34
+ raise NotImplementedError("Gzip does not natively support folder decompression. Use a tarball instead.")
@@ -0,0 +1,24 @@
1
+ from typing import Protocol
2
+
3
+
4
+ class CompressionAlgorithm(Protocol):
5
+ """Pure compression contract: handles bytes, files, and directories."""
6
+ name: str
7
+
8
+ def compress(self, data: bytes) -> bytes:
9
+ ...
10
+
11
+ def decompress(self, data: bytes) -> bytes:
12
+ ...
13
+
14
+ def compress_file(self, src: str, dest: str) -> None:
15
+ ...
16
+
17
+ def decompress_file(self, src: str, dest: str) -> None:
18
+ ...
19
+
20
+ def compress_folder(self, src: str, dest: str) -> None:
21
+ ...
22
+
23
+ def decompress_folder(self, src: str, dest: str) -> None:
24
+ ...
@@ -0,0 +1,37 @@
1
+ import os
2
+ from filedgr_pkg_utils.compression.compression_algorithm import CompressionAlgorithm
3
+
4
+
5
+ class CompressionUtils:
6
+ def __init__(self, algorithm: CompressionAlgorithm):
7
+ self.algorithm = algorithm
8
+
9
+ def compress(self, data: bytes) -> bytes:
10
+ if not isinstance(data, bytes):
11
+ raise TypeError("Data to compress must be bytes.")
12
+ return self.algorithm.compress(data)
13
+
14
+ def decompress(self, data: bytes) -> bytes:
15
+ if not isinstance(data, bytes):
16
+ raise TypeError("Data to decompress must be bytes.")
17
+ return self.algorithm.decompress(data)
18
+
19
+ def compress_file(self, src_path: str, dest_path: str) -> None:
20
+ if not os.path.isfile(src_path):
21
+ raise FileNotFoundError(f"Source file not found: {src_path}")
22
+ self.algorithm.compress_file(src_path, dest_path)
23
+
24
+ def decompress_file(self, src_path: str, dest_path: str) -> None:
25
+ if not os.path.isfile(src_path):
26
+ raise FileNotFoundError(f"Source file not found: {src_path}")
27
+ self.algorithm.decompress_file(src_path, dest_path)
28
+
29
+ def compress_folder(self, src_path: str, dest_path: str) -> None:
30
+ if not os.path.isdir(src_path):
31
+ raise NotADirectoryError(f"Source directory not found: {src_path}")
32
+ self.algorithm.compress_folder(src_path, dest_path)
33
+
34
+ def decompress_folder(self, src_path: str, dest_path: str) -> None:
35
+ if not os.path.isfile(src_path):
36
+ raise FileNotFoundError(f"Compressed source file not found: {src_path}")
37
+ self.algorithm.decompress_folder(src_path, dest_path)
File without changes
@@ -0,0 +1,21 @@
1
+ import abc
2
+ from abc import ABC
3
+ from typing import TypeVar, Generic, Type
4
+
5
+ DTO = TypeVar('DTO')
6
+ MODEL = TypeVar('MODEL')
7
+
8
+
9
+ class AbstractConverter(ABC, Generic[MODEL, DTO]):
10
+
11
+ @abc.abstractmethod
12
+ def convert_request_to_model(self, request) -> MODEL:
13
+ pass
14
+
15
+ @abc.abstractmethod
16
+ def convert_model_to_dto(self, model: MODEL, return_type: Type) -> DTO:
17
+ pass
18
+
19
+ @abc.abstractmethod
20
+ def convert_dto_to_model(self, dto: DTO) -> MODEL:
21
+ pass
File without changes
File without changes
@@ -0,0 +1,4 @@
1
+ def convert_hex_str_to_bytes32(input: str) -> bytes:
2
+ from web3 import Web3
3
+ bytes32_value = Web3.to_bytes(text=input)
4
+ return bytes32_value
@@ -0,0 +1,101 @@
1
+ from typing import Protocol, BinaryIO
2
+ import hashlib
3
+
4
+ from eth_hash.auto import keccak
5
+
6
+
7
+ class HashAlgorithm(Protocol):
8
+ """Pure hashing contract: bytes in, digest bytes out."""
9
+ name: str
10
+
11
+ def hash_bytes(self, data: bytes) -> bytes:
12
+ ...
13
+
14
+ def hash_file(self, path: str, chunk_size: int = 1024 * 1024) -> bytes:
15
+ ...
16
+
17
+ def hash_stream(self, stream: BinaryIO, chunk_size: int = 1024 * 1024) -> bytes:
18
+ ...
19
+
20
+
21
+ class Sha256Algorithm:
22
+ name = "sha256"
23
+
24
+ def hash_bytes(self, data: bytes) -> bytes:
25
+ return hashlib.sha256(data).digest()
26
+
27
+ def hash_file(self, path: str, chunk_size: int = 1024 * 1024) -> bytes:
28
+ h = hashlib.sha256()
29
+ with open(path, "rb") as f:
30
+ for chunk in iter(lambda: f.read(chunk_size), b""):
31
+ h.update(chunk)
32
+ return h.digest()
33
+
34
+ def hash_stream(self, stream: BinaryIO, chunk_size: int = 1024 * 1024) -> bytes:
35
+ h = hashlib.sha256()
36
+ while chunk := stream.read(chunk_size):
37
+ h.update(chunk)
38
+ return h.digest()
39
+
40
+
41
+ class Sha512Algorithm:
42
+ name = "sha512"
43
+
44
+ def hash_bytes(self, data: bytes) -> bytes:
45
+ return hashlib.sha512(data).digest()
46
+
47
+ def hash_file(self, path: str, chunk_size: int = 1024 * 1024) -> bytes:
48
+ h = hashlib.sha512()
49
+ with open(path, "rb") as f:
50
+ for chunk in iter(lambda: f.read(chunk_size), b""):
51
+ h.update(chunk)
52
+ return h.digest()
53
+
54
+ def hash_stream(self, stream: BinaryIO, chunk_size: int = 1024 * 1024) -> bytes:
55
+ h = hashlib.sha512()
56
+ while chunk := stream.read(chunk_size):
57
+ h.update(chunk)
58
+ return h.digest()
59
+
60
+
61
+ class Blake2bAlgorithm:
62
+ name = "blake2b"
63
+
64
+ def __init__(self, digest_size: int = 32):
65
+ # 32 bytes == 256-bit, 64 bytes == 512-bit
66
+ self.digest_size = digest_size
67
+
68
+ def hash_bytes(self, data: bytes) -> bytes:
69
+ return hashlib.blake2b(data, digest_size=self.digest_size).digest()
70
+
71
+ def hash_file(self, path: str, chunk_size: int = 1024 * 1024) -> bytes:
72
+ h = hashlib.blake2b(digest_size=self.digest_size)
73
+ with open(path, "rb") as f:
74
+ for chunk in iter(lambda: f.read(chunk_size), b""):
75
+ h.update(chunk)
76
+ return h.digest()
77
+
78
+ def hash_stream(self, stream: BinaryIO, chunk_size: int = 1024 * 1024) -> bytes:
79
+ h = hashlib.blake2b(digest_size=self.digest_size)
80
+ while chunk := stream.read(chunk_size):
81
+ h.update(chunk)
82
+ return h.digest()
83
+
84
+
85
+ class Keccak256Algorithm:
86
+ """
87
+ Keccak-256 (Ethereum standard) via eth-hash.
88
+ """
89
+ name = "keccak256"
90
+
91
+ def hash_bytes(self, data: bytes) -> bytes:
92
+ return keccak(data)
93
+
94
+ def hash_file(self, path: str, chunk_size: int = 1024 * 1024) -> bytes:
95
+ raise NotImplementedError("keccak of the web3 libraries does not expose a streaming API")
96
+
97
+ def hash_stream(self, stream: BinaryIO, chunk_size: int = 1024 * 1024) -> bytes:
98
+ h = hashlib.sha256()
99
+ while chunk := stream.read(chunk_size):
100
+ h.update(chunk)
101
+ return h.digest()
@@ -0,0 +1,18 @@
1
+ from typing import Union, BinaryIO
2
+
3
+ from filedgr_pkg_utils.cryptography.hashing.hash_algorithm import HashAlgorithm
4
+
5
+
6
+ class HashUtils:
7
+ def __init__(self, algorithm: HashAlgorithm):
8
+ self.algorithm = algorithm
9
+
10
+ def hash_message(self, message: Union[str, bytes], *, encoding: str = "utf-8") -> str:
11
+ data = message.encode(encoding) if isinstance(message, str) else message
12
+ return f"0x{self.algorithm.hash_bytes(data).hex()}"
13
+
14
+ def hash_file(self, path: str, *, chunk_size: int = 1024 * 1024) -> str:
15
+ return f"0x{self.algorithm.hash_file(path, chunk_size=chunk_size).hex()}"
16
+
17
+ def hash_stream(self, stream: BinaryIO, *, chunk_size: int = 1024 * 1024) -> str:
18
+ return f"0x{self.algorithm.hash_stream(stream, chunk_size=chunk_size).hex()}"
@@ -0,0 +1,6 @@
1
+ from .hmac_signature_algorithm import HmacAlgorithm
2
+ from .secp256k1_signature_algorithm import Secp256k1Algorithm
3
+ from .secp256k1_evm_signature_algorithm import Secp256k1EvmAlgorithm
4
+ from .signature_algorithm import SignatureAlgorithm
5
+ from .signature_utils import SignatureUtils
6
+ from .conversion_utils import sig_hex_to_vrs
@@ -0,0 +1,27 @@
1
+ from typing import Tuple
2
+
3
+
4
+ def sig_hex_to_vrs(signature_hex: str) -> Tuple[int, bytes, bytes]:
5
+ if signature_hex.startswith(("0x", "0X")):
6
+ signature_hex = signature_hex[2:]
7
+
8
+ sig = bytes.fromhex(signature_hex)
9
+
10
+ if len(sig) != 65:
11
+ raise ValueError(f"Expected 65-byte signature (r||s||v). Got {len(sig)} bytes.")
12
+
13
+ r = int.from_bytes(sig[0:32], "big")
14
+ s = int.from_bytes(sig[32:64], "big")
15
+ v = sig[64]
16
+
17
+ # Normalize v into what your Solidity expects.
18
+ # Many contracts accept 27/28; many clients produce 0/1.
19
+ if v in (0, 1):
20
+ v += 27
21
+ if v not in (27, 28):
22
+ raise ValueError(f"Invalid v value: {v}")
23
+
24
+ # Return as Solidity-ready types:
25
+ r_bytes32 = r.to_bytes(32, "big")
26
+ s_bytes32 = s.to_bytes(32, "big")
27
+ return v, r_bytes32, s_bytes32
@@ -0,0 +1,15 @@
1
+ import hashlib
2
+ import hmac
3
+
4
+
5
+ class HmacAlgorithm:
6
+
7
+ def __init__(self, secret: bytes):
8
+ self.__secret = secret
9
+
10
+ def sign(self, digest: bytes) -> bytes:
11
+ return hmac.new(self.__secret, digest, hashlib.sha256).digest()
12
+
13
+ def verify(self, digest: bytes, signature: bytes) -> bool:
14
+ expected_signature = self.sign(digest)
15
+ return hmac.compare_digest(expected_signature, signature)
@@ -0,0 +1,20 @@
1
+ from eth_account import Account
2
+
3
+
4
+ class Secp256k1EvmAlgorithm:
5
+
6
+ def __init__(self,
7
+ sign_key_hex: str = None,
8
+ verify_key_hex: str = None):
9
+ if sign_key_hex:
10
+ self.__priv = sign_key_hex if sign_key_hex.startswith("0x") else "0x" + sign_key_hex
11
+
12
+ def sign(self, digest: bytes) -> bytes:
13
+ # digest = bytes.fromhex(digest[2:] if digest.startswith("0x") else digest)
14
+ if len(digest) != 32:
15
+ raise ValueError("digest must be 32 bytes")
16
+ signed = Account.unsafe_sign_hash(digest, private_key=self.__priv)
17
+ return signed.signature
18
+
19
+ def verify(self, digest: bytes, signature: bytes) -> bool:
20
+ raise NotImplementedError()
@@ -0,0 +1,46 @@
1
+ # Third party imports
2
+ from cryptography.exceptions import InvalidSignature
3
+ from cryptography.hazmat.primitives import hashes
4
+ from cryptography.hazmat.primitives.asymmetric import ec
5
+ from cryptography.hazmat.primitives.asymmetric.utils import (
6
+ decode_dss_signature,
7
+ encode_dss_signature,
8
+ )
9
+
10
+ _CURVE = ec.SECP256K1()
11
+ _HASH = hashes.SHA256()
12
+ _ORDER_BYTES = 32
13
+
14
+
15
+ class Secp256k1Algorithm:
16
+ """secp256k1 signer/verifier backed by OpenSSL (``cryptography``).
17
+
18
+ Keys are exchanged as raw hex: the private key is the 32-byte scalar and
19
+ the public key is the uncompressed point ``x || y`` (64 bytes, no prefix).
20
+ Signatures are the raw ``r || s`` pair (64 bytes).
21
+ """
22
+
23
+ def __init__(self,
24
+ sign_key_hex: str = None,
25
+ verify_key_hex: str = None):
26
+ if sign_key_hex:
27
+ secret = int.from_bytes(bytes.fromhex(sign_key_hex), "big")
28
+ self.__priv = ec.derive_private_key(secret, _CURVE)
29
+ if verify_key_hex:
30
+ point = b"\x04" + bytes.fromhex(verify_key_hex)
31
+ self.__pub = ec.EllipticCurvePublicKey.from_encoded_point(_CURVE, point)
32
+
33
+ def sign(self, digest: bytes) -> bytes:
34
+ der_signature = self.__priv.sign(digest, ec.ECDSA(_HASH))
35
+ r, s = decode_dss_signature(der_signature)
36
+ return r.to_bytes(_ORDER_BYTES, "big") + s.to_bytes(_ORDER_BYTES, "big")
37
+
38
+ def verify(self, digest: bytes, signature: bytes) -> bool:
39
+ r = int.from_bytes(signature[:_ORDER_BYTES], "big")
40
+ s = int.from_bytes(signature[_ORDER_BYTES:], "big")
41
+ der_signature = encode_dss_signature(r, s)
42
+ try:
43
+ self.__pub.verify(der_signature, digest, ec.ECDSA(_HASH))
44
+ return True
45
+ except InvalidSignature:
46
+ return False
@@ -0,0 +1,10 @@
1
+ from typing import Protocol
2
+
3
+
4
+ class SignatureAlgorithm(Protocol):
5
+
6
+ def sign(self, digest: bytes) -> bytes:
7
+ ...
8
+
9
+ def verify(self, digest: bytes, signature: bytes) -> bool:
10
+ ...
@@ -0,0 +1,31 @@
1
+ from filedgr_pkg_utils.cryptography.signing.signature_algorithm import SignatureAlgorithm
2
+
3
+
4
+ class SignatureUtils:
5
+
6
+ def __init__(self, algo: SignatureAlgorithm):
7
+ self.algo = algo
8
+
9
+ def sign(self, digest: str) -> str:
10
+ """
11
+ :param digest: The hash as a hex string
12
+ :return: The signature as a hex string
13
+ """
14
+ if digest.startswith("0x"):
15
+ digest = digest[2:]
16
+ digest = bytes.fromhex(digest)
17
+ return f"0x{self.algo.sign(digest).hex()}"
18
+
19
+ def verify(self, digest: str, signature: str) -> bool:
20
+ """
21
+ :param digest: The hash as a hex string
22
+ :param signature: The signature as a hex string
23
+ :return: True/False
24
+ """
25
+ if signature.startswith("0x"):
26
+ signature = signature[2:]
27
+ signature = bytes.fromhex(signature)
28
+ if digest.startswith("0x"):
29
+ digest = digest[2:]
30
+ digest = bytes.fromhex(digest)
31
+ return self.algo.verify(digest, signature)
@@ -0,0 +1,8 @@
1
+ """EVM-related utilities (hex normalization, log shapes, etc.)."""
2
+ from filedgr_pkg_utils.evm.hex_utils import (
3
+ normalize_hex,
4
+ normalize_log,
5
+ normalize_topic,
6
+ )
7
+
8
+ __all__ = ["normalize_hex", "normalize_log", "normalize_topic"]