_utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import binascii
  2. from typing import (
  3. Union,
  4. )
  5. def to_bytes(val: Union[bool, bytearray, bytes, int, str, memoryview]) -> bytes:
  6. """
  7. Equivalent to: `eth_utils.hexstr_if_str(eth_utils.to_bytes, val)` .
  8. Convert a hex string, integer, or bool, to a bytes representation.
  9. Alternatively, pass through bytes or bytearray as a bytes value.
  10. """
  11. if isinstance(val, bytes):
  12. return val
  13. elif isinstance(val, str):
  14. return hexstr_to_bytes(val)
  15. elif isinstance(val, bytearray):
  16. return bytes(val)
  17. elif isinstance(val, bool):
  18. return b"\x01" if val else b"\x00"
  19. elif isinstance(val, int):
  20. # Note that this int check must come after the bool check, because
  21. # isinstance(True, int) is True
  22. if val < 0:
  23. raise ValueError(f"Cannot convert negative integer {val} to bytes")
  24. else:
  25. return to_bytes(hex(val))
  26. elif isinstance(val, memoryview):
  27. return bytes(val)
  28. else:
  29. raise TypeError(f"Cannot convert {val!r} of type {type(val)} to bytes")
  30. def hexstr_to_bytes(hexstr: str) -> bytes:
  31. if hexstr.startswith(("0x", "0X")):
  32. non_prefixed_hex = hexstr[2:]
  33. else:
  34. non_prefixed_hex = hexstr
  35. # if the hex string is odd-length, then left-pad it to an even length
  36. if len(hexstr) % 2:
  37. padded_hex = "0" + non_prefixed_hex
  38. else:
  39. padded_hex = non_prefixed_hex
  40. try:
  41. ascii_hex = padded_hex.encode("ascii")
  42. except UnicodeDecodeError:
  43. raise ValueError(
  44. f"hex string {padded_hex} may only contain [0-9a-fA-F] characters"
  45. )
  46. else:
  47. return binascii.unhexlify(ascii_hex)