main.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from typing import (
  2. Union,
  3. )
  4. from .abc import (
  5. BackendAPI,
  6. PreImageAPI,
  7. )
  8. class Keccak256:
  9. def __init__(self, backend: BackendAPI) -> None:
  10. self._backend = backend
  11. self.hasher = self._hasher_first_run
  12. self.preimage = self._preimage_first_run
  13. def _hasher_first_run(self, in_data: Union[bytearray, bytes]) -> bytes:
  14. """
  15. Validate, on first-run, that the hasher backend is valid.
  16. After first run, replace this with the new hasher method.
  17. This is a bit of a hacky way to minimize overhead on hash calls after
  18. this first one.
  19. """
  20. # Execute directly before saving method,
  21. # to let any side-effects settle (see AutoBackend)
  22. result = self._backend.keccak256(in_data)
  23. new_hasher = self._backend.keccak256
  24. assert (
  25. new_hasher(b"")
  26. == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501
  27. )
  28. self.hasher = new_hasher
  29. return result
  30. def _preimage_first_run(self, in_data: Union[bytearray, bytes]) -> PreImageAPI:
  31. # Execute directly before saving method,
  32. # to let any side-effects settle (see AutoBackend)
  33. result = self._backend.preimage(in_data)
  34. self.preimage = self._backend.preimage
  35. return result
  36. def __call__(self, preimage: Union[bytearray, bytes]) -> bytes:
  37. if not isinstance(preimage, (bytearray, bytes)):
  38. raise TypeError(
  39. "Can only compute the hash of `bytes` or `bytearray` values, "
  40. f"not {repr(preimage)}"
  41. )
  42. return self.hasher(preimage)
  43. def new(self, preimage: Union[bytearray, bytes]) -> PreImageAPI:
  44. if not isinstance(preimage, (bytearray, bytes)):
  45. raise TypeError(
  46. "Can only compute the hash of `bytes` or `bytearray` values, "
  47. f"not {repr(preimage)}"
  48. )
  49. return self.preimage(preimage)