messages.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. from typing import (
  2. Any,
  3. Dict,
  4. NamedTuple,
  5. Optional,
  6. Union,
  7. )
  8. from eth_typing import (
  9. Address,
  10. Hash32,
  11. )
  12. from eth_utils.curried import (
  13. ValidationError,
  14. keccak,
  15. text_if_str,
  16. to_bytes,
  17. to_canonical_address,
  18. )
  19. from hexbytes import (
  20. HexBytes,
  21. )
  22. from eth_account._utils.encode_typed_data.encoding_and_hashing import (
  23. get_primary_type,
  24. hash_domain,
  25. hash_eip712_message,
  26. )
  27. from eth_account._utils.validation import (
  28. is_valid_address,
  29. )
  30. text_to_bytes = text_if_str(to_bytes)
  31. # watch for updates to signature format
  32. class SignableMessage(NamedTuple):
  33. """
  34. A message compatible with EIP-191_ that is ready to be signed.
  35. The properties are components of an EIP-191_ signable message. Other message formats
  36. can be encoded into this format for easy signing. This data structure doesn't need
  37. to know about the original message format. For example, you can think of
  38. EIP-712 as compiling down to an EIP-191 message.
  39. In typical usage, you should never need to create these by hand. Instead, use
  40. one of the available encode_* methods in this module, like:
  41. - :meth:`encode_intended_validator`
  42. - :meth:`encode_defunct`
  43. - :meth:`encode_typed_data`
  44. .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191
  45. """
  46. version: bytes # must be length 1
  47. header: bytes # aka "version specific data"
  48. body: bytes # aka "data to sign"
  49. def _hash_eip191_message(signable_message: SignableMessage) -> Hash32:
  50. version = signable_message.version
  51. if len(version) != 1:
  52. raise ValidationError(
  53. f"The supplied message version is {version!r}. "
  54. "The EIP-191 signable message standard only supports one-byte versions."
  55. )
  56. joined = b"\x19" + version + signable_message.header + signable_message.body
  57. return Hash32(keccak(joined))
  58. # watch for updates to signature format
  59. def encode_intended_validator(
  60. validator_address: Union[Address, str],
  61. primitive: Optional[bytes] = None,
  62. *,
  63. hexstr: Optional[str] = None,
  64. text: Optional[str] = None,
  65. ) -> SignableMessage:
  66. """
  67. Encode a message using the "intended validator" approach (ie~ version 0)
  68. defined in EIP-191_.
  69. Supply the message as exactly one of these three arguments:
  70. bytes as a primitive, a hex string, or a unicode string.
  71. .. WARNING:: Note that this code has not gone through an external audit.
  72. :param validator_address: which on-chain contract is capable of validating this
  73. message, provided as a checksummed address or in native bytes.
  74. :param primitive: the binary message to be signed
  75. :type primitive: bytes or int
  76. :param str hexstr: the message encoded as hex
  77. :param str text: the message as a series of unicode characters (a normal Py3 str)
  78. :returns: The EIP-191 encoded message, ready for signing
  79. .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191
  80. """
  81. if not is_valid_address(validator_address):
  82. raise ValidationError(
  83. f"Cannot encode message with 'Validator Address': {validator_address!r}. "
  84. "It must be a checksum address, or an address converted to bytes."
  85. )
  86. # The validator_address is a str or Address (which is a subtype of bytes). Both of
  87. # these are AnyStr, which includes str and bytes.
  88. # Not sure why mypy complains here...
  89. canonical_address = to_canonical_address(validator_address)
  90. message_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
  91. return SignableMessage(
  92. HexBytes(b"\x00"), # version 0, as defined in EIP-191
  93. canonical_address,
  94. message_bytes,
  95. )
  96. def encode_defunct(
  97. primitive: Optional[bytes] = None,
  98. *,
  99. hexstr: Optional[str] = None,
  100. text: Optional[str] = None,
  101. ) -> SignableMessage:
  102. r"""
  103. Encode a message for signing, using an old, unrecommended approach.
  104. Only use this method if you must have compatibility with
  105. :meth:`w3.eth.sign() <web3.eth.Eth.sign>`.
  106. EIP-191 defines this as "version ``E``".
  107. .. NOTE: This standard includes the number of bytes in the message as a part of
  108. the header. Awkwardly, the number of bytes in the message is encoded in
  109. decimal ascii. So if the message is 'abcde', then the length is encoded
  110. as the ascii character '5'. This is one of the reasons that this message
  111. format is not preferred. There is ambiguity when the message '00' is
  112. encoded, for example.
  113. Supply exactly one of the three arguments: bytes, a hex string, or a unicode string.
  114. :param primitive: the binary message to be signed
  115. :type primitive: bytes or int
  116. :param str hexstr: the message encoded as hex
  117. :param str text: the message as a series of unicode characters (a normal Py3 str)
  118. :returns: The EIP-191 encoded message, ready for signing
  119. .. doctest:: python
  120. >>> from eth_account.messages import encode_defunct
  121. >>> from eth_utils.curried import to_hex, to_bytes
  122. >>> message_text = "I♥SF"
  123. >>> encode_defunct(text=message_text)
  124. SignableMessage(version=b'E',
  125. header=b'thereum Signed Message:\n6',
  126. body=b'I\xe2\x99\xa5SF')
  127. These four also produce the same hash:
  128. >>> encode_defunct(to_bytes(text=message_text))
  129. SignableMessage(version=b'E',
  130. header=b'thereum Signed Message:\n6',
  131. body=b'I\xe2\x99\xa5SF')
  132. >>> encode_defunct(bytes(message_text, encoding='utf-8'))
  133. SignableMessage(version=b'E',
  134. header=b'thereum Signed Message:\n6',
  135. body=b'I\xe2\x99\xa5SF')
  136. >>> to_hex(text=message_text)
  137. '0x49e299a55346'
  138. >>> encode_defunct(hexstr='0x49e299a55346')
  139. SignableMessage(version=b'E',
  140. header=b'thereum Signed Message:\n6',
  141. body=b'I\xe2\x99\xa5SF')
  142. >>> encode_defunct(0x49e299a55346)
  143. SignableMessage(version=b'E',
  144. header=b'thereum Signed Message:\n6',
  145. body=b'I\xe2\x99\xa5SF')
  146. """
  147. message_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
  148. msg_length = str(len(message_bytes)).encode("utf-8")
  149. # Encoding version E defined by EIP-191
  150. return SignableMessage(
  151. b"E",
  152. b"thereum Signed Message:\n" + msg_length,
  153. message_bytes,
  154. )
  155. def defunct_hash_message(
  156. primitive: Optional[bytes] = None,
  157. *,
  158. hexstr: Optional[str] = None,
  159. text: Optional[str] = None,
  160. ) -> HexBytes:
  161. """
  162. Convert the provided message into a message hash, to be signed.
  163. .. CAUTION:: Intended for use with
  164. :meth:`eth_account.account.Account.unsafe_sign_hash`.
  165. This is for backwards compatibility only. All new implementations
  166. should use :meth:`encode_defunct` instead.
  167. :param primitive: the binary message to be signed
  168. :type primitive: bytes or int
  169. :param str hexstr: the message encoded as hex
  170. :param str text: the message as a series of unicode characters (a normal Py3 str)
  171. :returns: The hash of the message, after adding the prefix
  172. """
  173. signable = encode_defunct(primitive, hexstr=hexstr, text=text)
  174. hashed = _hash_eip191_message(signable)
  175. return HexBytes(hashed)
  176. def encode_typed_data(
  177. domain_data: Optional[Dict[str, Any]] = None,
  178. message_types: Optional[Dict[str, Any]] = None,
  179. message_data: Optional[Dict[str, Any]] = None,
  180. full_message: Optional[Dict[str, Any]] = None,
  181. ) -> SignableMessage:
  182. r"""
  183. Encode an EIP-712_ message in a manner compatible with other implementations
  184. in use, such as the Metamask and Ethers ``signTypedData`` functions.
  185. See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information.
  186. You may supply the information to be encoded in one of two ways:
  187. As exactly three arguments:
  188. - ``domain_data``, a dict of the EIP-712 domain data
  189. - ``message_types``, a dict of custom types (do not include a ``EIP712Domain``
  190. key)
  191. - ``message_data``, a dict of the data to be signed
  192. Or as a single argument:
  193. - ``full_message``, a dict containing the following keys:
  194. - ``types``, a dict of custom types (may include a ``EIP712Domain`` key)
  195. - ``primaryType``, (optional) a string of the primary type of the message
  196. - ``domain``, a dict of the EIP-712 domain data
  197. - ``message``, a dict of the data to be signed
  198. .. WARNING:: Note that this code has not gone through an external audit, and
  199. the test cases are incomplete.
  200. Type Coercion:
  201. - For fixed-size bytes types, smaller values will be padded to fit in larger
  202. types, but values larger than the type will raise ``ValueOutOfBounds``.
  203. e.g., an 8-byte value will be padded to fit a ``bytes16`` type, but 16-byte
  204. value provided for a ``bytes8`` type will raise an error.
  205. - Fixed-size and dynamic ``bytes`` types will accept ``int``s. Any negative
  206. values will be converted to ``0`` before being converted to ``bytes``
  207. - ``int`` and ``uint`` types will also accept strings. If prefixed with ``"0x"``
  208. , the string will be interpreted as hex. Otherwise, it will be interpreted as
  209. decimal.
  210. - Any value for a ``bool`` type that Python considers "falsy" will be
  211. interpreted as ``False``. The strings ``"False"``, ``"false"``, and ``"0"``
  212. will be also interpreted as ``False``. All other values will be interpreted as
  213. ``True``.
  214. Noteable differences from ``signTypedData``:
  215. - Custom types that are not alphanumeric will encode differently.
  216. - Custom types that are used but not defined in ``types`` will not encode.
  217. :param domain_data: EIP712 domain data
  218. :param message_types: custom types used by the `value` data
  219. :param message_data: data to be signed
  220. :param full_message: a dict containing all data and types
  221. :returns: a ``SignableMessage``, an encoded message ready to be signed
  222. .. doctest:: python
  223. >>> # examples of basic usage
  224. >>> from eth_account import Account
  225. >>> from eth_account.messages import encode_typed_data
  226. >>> # 3-argument usage
  227. >>> # all domain properties are optional
  228. >>> domain_data = {
  229. ... "name": "Ether Mail",
  230. ... "version": "1",
  231. ... "chainId": 1,
  232. ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC",
  233. ... "salt": b"decafbeef",
  234. ... }
  235. >>> # custom types
  236. >>> message_types = {
  237. ... "Person": [
  238. ... {"name": "name", "type": "string"},
  239. ... {"name": "wallet", "type": "address"},
  240. ... ],
  241. ... "Mail": [
  242. ... {"name": "from", "type": "Person"},
  243. ... {"name": "to", "type": "Person"},
  244. ... {"name": "contents", "type": "string"},
  245. ... ],
  246. ... }
  247. >>> # the data to be signed
  248. >>> message_data = {
  249. ... "from": {
  250. ... "name": "Cow",
  251. ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826",
  252. ... },
  253. ... "to": {
  254. ... "name": "Bob",
  255. ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB",
  256. ... },
  257. ... "contents": "Hello, Bob!",
  258. ... }
  259. >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  260. >>> signable_message = encode_typed_data(domain_data, message_types, message_data)
  261. >>> signed_message = Account.sign_message(signable_message, key)
  262. >>> signed_message.message_hash
  263. HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530')
  264. >>> # the message can be signed in one step using Account.sign_typed_data
  265. >>> signed_typed_data = Account.sign_typed_data(key, domain_data, message_types, message_data)
  266. >>> signed_typed_data == signed_message
  267. True
  268. >>> # 1-argument usage
  269. >>> # all domain properties are optional
  270. >>> full_message = {
  271. ... "types": {
  272. ... "EIP712Domain": [
  273. ... {"name": "name", "type": "string"},
  274. ... {"name": "version", "type": "string"},
  275. ... {"name": "chainId", "type": "uint256"},
  276. ... {"name": "verifyingContract", "type": "address"},
  277. ... {"name": "salt", "type": "bytes32"},
  278. ... ],
  279. ... "Person": [
  280. ... {"name": "name", "type": "string"},
  281. ... {"name": "wallet", "type": "address"},
  282. ... ],
  283. ... "Mail": [
  284. ... {"name": "from", "type": "Person"},
  285. ... {"name": "to", "type": "Person"},
  286. ... {"name": "contents", "type": "string"},
  287. ... ],
  288. ... },
  289. ... "primaryType": "Mail",
  290. ... "domain": {
  291. ... "name": "Ether Mail",
  292. ... "version": "1",
  293. ... "chainId": 1,
  294. ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC",
  295. ... "salt": b"decafbeef"
  296. ... },
  297. ... "message": {
  298. ... "from": {
  299. ... "name": "Cow",
  300. ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
  301. ... },
  302. ... "to": {
  303. ... "name": "Bob",
  304. ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
  305. ... },
  306. ... "contents": "Hello, Bob!",
  307. ... },
  308. ... }
  309. >>> signable_message_2 = encode_typed_data(full_message=full_message)
  310. >>> signed_message_2 = Account.sign_message(signable_message_2, key)
  311. >>> signed_message_2.message_hash
  312. HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530')
  313. >>> signed_message_2 == signed_message
  314. True
  315. >>> # the full_message can be signed in one step using Account.sign_typed_data
  316. >>> signed_typed_data_2 = Account.sign_typed_data(key, domain_data, message_types, message_data)
  317. >>> signed_typed_data_2 == signed_message_2
  318. True
  319. .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712
  320. """ # noqa: E501
  321. if full_message is not None:
  322. if (
  323. domain_data is not None
  324. or message_types is not None
  325. or message_data is not None
  326. ):
  327. raise ValueError(
  328. "You may supply either `full_message` as a single argument or "
  329. "`domain_data`, `message_types`, and `message_data` as three arguments,"
  330. " but not both."
  331. )
  332. full_message_types = full_message["types"].copy()
  333. full_message_domain = full_message["domain"].copy()
  334. # If EIP712Domain types were provided, check that they match the domain data
  335. if "EIP712Domain" in full_message_types:
  336. domain_data_keys = list(full_message_domain.keys())
  337. domain_types_keys = [
  338. field["name"] for field in full_message_types["EIP712Domain"]
  339. ]
  340. if set(domain_data_keys) != (set(domain_types_keys)):
  341. raise ValidationError(
  342. "The fields provided in `domain` do not match the fields provided"
  343. " in `types.EIP712Domain`. The fields provided in `domain` were"
  344. f" `{domain_data_keys}`, but the fields provided in "
  345. f"`types.EIP712Domain` were `{domain_types_keys}`."
  346. )
  347. full_message_types.pop("EIP712Domain", None)
  348. # If primaryType was provided, check that it matches the derived primaryType
  349. if "primaryType" in full_message:
  350. derived_primary_type = get_primary_type(full_message_types)
  351. provided_primary_type = full_message["primaryType"]
  352. if derived_primary_type != provided_primary_type:
  353. raise ValidationError(
  354. "The provided `primaryType` does not match the derived "
  355. "`primaryType`. The provided `primaryType` was "
  356. f"`{provided_primary_type}`, but the derived `primaryType` was "
  357. f"`{derived_primary_type}`."
  358. )
  359. parsed_domain_data = full_message_domain
  360. parsed_message_types = full_message_types
  361. parsed_message_data = full_message["message"]
  362. else:
  363. parsed_domain_data = domain_data
  364. parsed_message_types = message_types
  365. parsed_message_data = message_data
  366. return SignableMessage(
  367. HexBytes(b"\x01"),
  368. hash_domain(parsed_domain_data),
  369. hash_eip712_message(parsed_message_types, parsed_message_data),
  370. )