_utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import hashlib
  2. import hmac
  3. from typing import (
  4. Union,
  5. )
  6. import unicodedata
  7. from eth_keys import (
  8. keys,
  9. )
  10. from eth_utils import (
  11. ValidationError,
  12. )
  13. from hexbytes import (
  14. HexBytes,
  15. )
  16. PBKDF2_ROUNDS = 2048
  17. SECP256K1_N = int(
  18. "FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFE_BAAEDCE6_AF48A03B_BFD25E8C_D0364141", 16
  19. )
  20. def unicode_decompose_string(txt: Union[str, bytes]) -> str:
  21. if isinstance(txt, bytes):
  22. utxt = txt.decode("utf8")
  23. elif isinstance(txt, str):
  24. utxt = txt
  25. else:
  26. raise ValidationError("String value expected")
  27. return unicodedata.normalize("NFKD", utxt)
  28. def unicode_compose_string(txt: Union[str, bytes]) -> str:
  29. if isinstance(txt, bytes):
  30. utxt = txt.decode("utf8")
  31. elif isinstance(txt, str):
  32. utxt = txt
  33. else:
  34. raise ValidationError("String value expected")
  35. return unicodedata.normalize("NFKC", utxt)
  36. def sha256(data: bytes) -> bytes:
  37. return hashlib.sha256(data).digest()
  38. def hmac_sha512(chain_code: bytes, data: bytes) -> bytes:
  39. """
  40. As specified by RFC4231 - https://tools.ietf.org/html/rfc4231 .
  41. """
  42. return hmac.new(chain_code, data, hashlib.sha512).digest()
  43. def pbkdf2_hmac_sha512(passcode: str, salt: str) -> bytes:
  44. return hashlib.pbkdf2_hmac(
  45. "sha512",
  46. passcode.encode("utf-8"),
  47. salt.encode("utf-8"),
  48. PBKDF2_ROUNDS,
  49. )
  50. def ec_point(pkey: bytes) -> bytes:
  51. """
  52. Compute `point(p)`, where `point` is ecdsa point multiplication.
  53. Note: Result is ecdsa public key serialized to compressed form
  54. """
  55. return keys.PrivateKey(HexBytes(pkey)).public_key.to_compressed_bytes()